overleaf/services/web/app/src/Features/Helpers/SafeHTMLSubstitution.js
Alf Eaton 1be43911b4 Merge pull request #3942 from overleaf/prettier-trailing-comma
Set Prettier's "trailingComma" setting to "es5"

GitOrigin-RevId: 9f14150511929a855b27467ad17be6ab262fe5d5
2021-04-28 02:10:01 +00:00

46 lines
1.4 KiB
JavaScript

const pug = require('pug-runtime')
const SPLIT_REGEX = /<(\d+)>(.*?)<\/\1>/g
function render(locale, components) {
const output = []
function addPlainText(text) {
if (!text) return
output.push(pug.escape(text))
}
// 'PRE<0>INNER</0>POST' -> ['PRE', '0', 'INNER', 'POST']
// '<0>INNER</0>' -> ['', '0', 'INNER', '']
// '<0></0>' -> ['', '0', '', '']
// '<0>INNER</0><0>INNER2</0>' -> ['', '0', 'INNER', '', '0', 'INNER2', '']
// '<0><1>INNER</1></0>' -> ['', '0', '<1>INNER</1>', '']
// 'PLAIN TEXT' -> ['PLAIN TEXT']
// NOTE: a test suite is verifying these cases: SafeHTMLSubstituteTests
const chunks = locale.split(SPLIT_REGEX)
// extract the 'PRE' chunk
addPlainText(chunks.shift())
while (chunks.length) {
// each batch consists of three chunks: ['0', 'INNER', 'POST']
const [idx, innerChunk, intermediateChunk] = chunks.splice(0, 3)
const component = components[idx]
const componentName =
typeof component === 'string' ? component : component.name
// pug is doing any necessary escaping on attribute values
const attributes = (component.attrs && pug.attrs(component.attrs)) || ''
output.push(
`<${componentName + attributes}>`,
...render(innerChunk, components),
`</${componentName}>`
)
addPlainText(intermediateChunk)
}
return output.join('')
}
module.exports = {
SPLIT_REGEX,
render,
}