diff options
Diffstat (limited to 'tools/doc/html.js')
-rw-r--r-- | tools/doc/html.js | 49 |
1 files changed, 40 insertions, 9 deletions
diff --git a/tools/doc/html.js b/tools/doc/html.js index b519fd9c5a8..67157ba6b5f 100644 --- a/tools/doc/html.js +++ b/tools/doc/html.js @@ -187,6 +187,8 @@ function linkJsTypeDocs(text) { return parts.join('`'); } +const isJSFlavorSnippet = (node) => node.lang === 'cjs' || node.lang === 'mjs'; + // Preprocess headers, stability blockquotes, and YAML blocks. function preprocessElements({ filename }) { return (tree) => { @@ -194,7 +196,7 @@ function preprocessElements({ filename }) { let headingIndex = -1; let heading = null; - visit(tree, null, (node, index) => { + visit(tree, null, (node, index, parent) => { if (node.type === 'heading') { headingIndex = index; heading = node; @@ -204,15 +206,44 @@ function preprocessElements({ filename }) { `No language set in ${filename}, ` + `line ${node.position.start.line}`); } - const language = (node.lang || '').split(' ')[0]; - const highlighted = getLanguage(language) ? - highlight(language, node.value).value : - node.value; + const className = isJSFlavorSnippet(node) ? + `language-js ${node.lang}` : + `language-${node.lang}`; + const highlighted = + `<code class='${className}'>` + + (getLanguage(node.lang || '') ? + highlight(node.lang, node.value) : node).value + + '</code>'; node.type = 'html'; - node.value = '<pre>' + - `<code class = 'language-${node.lang}'>` + - highlighted + - '</code></pre>'; + + if (isJSFlavorSnippet(node)) { + const previousNode = parent.children[index - 1] || {}; + const nextNode = parent.children[index + 1] || {}; + + if (!isJSFlavorSnippet(previousNode) && + isJSFlavorSnippet(nextNode) && + nextNode.lang !== node.lang) { + // Saving the highlight code as value to be added in the next node. + node.value = highlighted; + } else if (isJSFlavorSnippet(previousNode)) { + node.value = '<pre>' + + '<input class="js-flavor-selector" type="checkbox"' + + // If CJS comes in second, ESM should display by default. + (node.lang === 'cjs' ? ' checked' : '') + + ' aria-label="Show modern ES modules syntax">' + + previousNode.value + + highlighted + + '</pre>'; + node.lang = null; + previousNode.value = ''; + previousNode.lang = null; + } else { + // Isolated JS snippet, no need to add the checkbox. + node.value = `<pre>${highlighted}</pre>`; + } + } else { + node.value = `<pre>${highlighted}</pre>`; + } } else if (node.type === 'html' && common.isYAMLBlock(node.value)) { node.value = parseYAML(node.value); |