From 4862966c1441fecb9e0eb6334671535fc76948bc Mon Sep 17 00:00:00 2001 From: Alex Crawford Date: Tue, 7 May 2024 16:47:16 -0700 Subject: [PATCH] tools: support rewriting links in code blocks Within the API documentation for modules, there is a section of pseudo-code which contains links to another file. This pseudo-code is inside of a pre-formatted element (`
`), but that prevents the
build process from rewriting those links from the Markdown source to
their corresponding HTML output.

This addresses that by adding a new language, "pre", whose output
remains unformatted but allows code fences to be annotated with
metadata - code fences must have a language before the metadata. When
the right metadata ("html") is present, it indicates that the code
block should be processed so that anchor tags are rewritten just like
other references.

The actual change to the documentation will happen in a later commit.
---
 tools/doc/html.mjs        | 3 +++
 tools/doc/markdown.mjs    | 9 +++++++++
 tools/lint-md/lint-md.mjs | 1 +
 3 files changed, 13 insertions(+)

diff --git a/tools/doc/html.mjs b/tools/doc/html.mjs
index ff1c6854b58e22..428a7c761208db 100644
--- a/tools/doc/html.mjs
+++ b/tools/doc/html.mjs
@@ -205,6 +205,7 @@ function linkJsTypeDocs(text) {
 }
 
 const isJSFlavorSnippet = (node) => node.lang === 'cjs' || node.lang === 'mjs';
+const isPreSnippet = (node) => node.lang === 'pre';
 
 // Preprocess headers, stability blockquotes, and YAML blocks.
 export function preprocessElements({ filename }) {
@@ -265,6 +266,8 @@ export function preprocessElements({ filename }) {
             // Isolated JS snippet, no need to add the checkbox.
             node.value = `
${highlighted} ${copyButton}
`; } + } else if (isPreSnippet(node)) { + node.value = `
${node.value}
`; } else { node.value = `
${highlighted} ${copyButton}
`; } diff --git a/tools/doc/markdown.mjs b/tools/doc/markdown.mjs index 21104e592b8a24..f148b0ecc6fea6 100644 --- a/tools/doc/markdown.mjs +++ b/tools/doc/markdown.mjs @@ -1,6 +1,7 @@ import { visit } from 'unist-util-visit'; export const referenceToLocalMdFile = /^(?![+a-z]+:)([^#?]+)\.md(#.+)?$/i; +export const referenceToLocalMdFileInPre = //g; export function replaceLinks({ filename, linksMapper }) { return (tree) => { @@ -14,6 +15,14 @@ export function replaceLinks({ filename, linksMapper }) { ); } }); + visit(tree, 'code', (node) => { + if (node.meta === 'html') { + node.value = node.value.replace( + referenceToLocalMdFileInPre, + (_, path, fragment) => ``, + ); + } + }); visit(tree, 'definition', (node) => { const htmlUrl = fileHtmlUrls && fileHtmlUrls[node.identifier]; diff --git a/tools/lint-md/lint-md.mjs b/tools/lint-md/lint-md.mjs index 2130891fe75d43..5758d70c9b5d45 100644 --- a/tools/lint-md/lint-md.mjs +++ b/tools/lint-md/lint-md.mjs @@ -23409,6 +23409,7 @@ const plugins = [ "markdown", "mjs", "powershell", + "pre", "r", "text", "ts",