1
0
mirror of synced 2025-12-23 03:44:00 -05:00

optimize render of textOnly snippets (#31581)

Co-authored-by: Robert Sese <734194+rsese@users.noreply.github.com>
This commit is contained in:
Peter Bengtsson
2022-10-11 19:52:03 +02:00
committed by GitHub
parent 9c9b380ddd
commit 3d462180da

View File

@@ -1,6 +1,6 @@
import liquid from './liquid.js'
import cheerio from 'cheerio'
import { encode } from 'html-entities'
import { encode, decode } from 'html-entities'
import stripHtmlComments from 'strip-html-comments'
import createProcessor from './create-processor.js'
@@ -52,17 +52,21 @@ async function renderContent(template = '', context = {}, options = {}) {
let html = vFile.toString()
// Remove unwanted newlines (which appear as spaces) from inline tags inside tables
if (html.includes('<table>')) html = removeNewlinesFromInlineTags(html)
if (html.includes('<table>')) {
html = removeNewlinesFromInlineTags(html)
}
if (options.textOnly) {
html = cheerio.load(html).text().trim()
html = fastTextOnly(html)
}
if (options.cheerioObject) {
return cheerio.load(html, { xmlMode: true })
}
if (options.encodeEntities) html = encode(html)
if (options.encodeEntities) {
html = encode(html)
}
return html.trim()
} catch (error) {
@@ -85,6 +89,21 @@ function removeNewlinesFromInlineTags(html) {
return $('body').html()
}
// Given a piece of HTML return it without HTML. E.g.
// `<p>Foo &amp; bar</p>` becomes `Foo & bar`
// and `A <a href="">link</a> and <code>code</code>` becomes `A link and code`.
// Take advantage of the subtle fact that a lot of the times, the html value
// we get here is a single line that starts with `<p>` and ends with `</p>`
// and contains no longer HTML tags.
function fastTextOnly(html) {
if (!html) return ''
if (html.startsWith('<p>') && html.endsWith('</p>')) {
const middle = html.slice(3, -4)
if (!middle.includes('<')) return decode(middle.trim())
}
return cheerio.load(html, { xmlMode: true }).text().trim()
}
renderContent.liquid = liquid
export default renderContent