From c398d9054f35fcd8470b9c052d32d24252167440 Mon Sep 17 00:00:00 2001 From: Eugene Kuzmenko Date: Thu, 11 Feb 2016 21:59:05 +0200 Subject: [PATCH] [added] `private Markup.markdownToUnwrappedHTML` - If a simple single line string is passed to the Markdown parser it thinks that it is a paragraph (it sort of technically is) and unnecessarily wraps it into `

`, which most often is not the desired behavior. This function fixes that. --- docs/Markup.html | 8 +++---- docs/Markup.js.html | 26 ++++++++++++++++++++-- docs/quicksearch.html | 2 +- lib/Markup.js | 30 ++++++++++++++++++++++++-- package.json | 4 ++-- src/Markup.js | 26 ++++++++++++++++++++-- test/Markup.spec.js | 50 +++++++++++++++++++++++++++++++++---------- 7 files changed, 122 insertions(+), 24 deletions(-) diff --git a/docs/Markup.html b/docs/Markup.html index 11a2be6..b161310 100644 --- a/docs/Markup.html +++ b/docs/Markup.html @@ -386,7 +386,7 @@
Parameters:
@@ -574,7 +574,7 @@
Parameters:
@@ -762,7 +762,7 @@
Parameters:
@@ -950,7 +950,7 @@
Parameters:
diff --git a/docs/Markup.js.html b/docs/Markup.js.html index b108260..4041f8c 100644 --- a/docs/Markup.js.html +++ b/docs/Markup.js.html @@ -223,6 +223,28 @@

Source: Markup.js

return map(reject(children, ['type', 'comment']), (c, i) => 'text' === c.type ? c.data : Markup.childToJSX(c, i)); } + /** + * If a simple single line string is passed to the Markdown parser it thinks that it's a paragraph (it sort of + * technically is) and unnecessarily wraps it into `<p></p>`, which most often is not the desired behavior. + * + * This function converts Markdown to HTML and then removes the wrapping paragraph if it is the only top level tag + * unwrapping its contents. + * + * @memberof Markup + * @static + * @private + * @method markdownToUnwrappedHTML + * @param {string} markdown - an arbitrary Markdown string + * @return {string} an HTML string + */ + static markdownToUnwrappedHTML(markdown: string): string { + const html = trim(marked(markdown)), + dom = load(html), + {children} = dom.root().toArray()[0]; + + return 1 === children.length && 'tag' === children[0].type && 'p' === children[0].name ? dom('p').html() : html; + } + /** * Recursively flattens `args` and combines string values. * @@ -292,7 +314,7 @@

Source: Markup.js

*/ markdownToHTML(markdown: string = ''): string { markdown = trim(markdown); - return markdown ? trim(this.transform(marked(markdown))) : ''; + return markdown ? trim(this.transform(Markup.markdownToUnwrappedHTML(markdown))) : ''; } /** @@ -308,7 +330,7 @@

Source: Markup.js

*/ markdownToJSX(markdown: string = ''): Array<any> { markdown = trim(markdown); - return markdown ? this.htmlToJSX(marked(markdown)) : []; + return markdown ? this.htmlToJSX(Markup.markdownToUnwrappedHTML(markdown)) : []; } } diff --git a/docs/quicksearch.html b/docs/quicksearch.html index 9cfc1af..757fcf2 100644 --- a/docs/quicksearch.html +++ b/docs/quicksearch.html @@ -7,7 +7,7 @@