Skip to content

Commit f883942

Browse files
committed
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 (`<pre>`), 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.
1 parent b372fff commit f883942

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

tools/doc/html.mjs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ function linkJsTypeDocs(text) {
205205
}
206206

207207
const isJSFlavorSnippet = (node) => node.lang === 'cjs' || node.lang === 'mjs';
208+
const isPreSnippet = (node) => node.lang === 'pre';
208209

209210
// Preprocess headers, stability blockquotes, and YAML blocks.
210211
export function preprocessElements({ filename }) {
@@ -265,6 +266,8 @@ export function preprocessElements({ filename }) {
265266
// Isolated JS snippet, no need to add the checkbox.
266267
node.value = `<pre>${highlighted} ${copyButton}</pre>`;
267268
}
269+
} else if (isPreSnippet(node)) {
270+
node.value = `<pre>${node.value}</pre>`;
268271
} else {
269272
node.value = `<pre>${highlighted} ${copyButton}</pre>`;
270273
}

tools/doc/markdown.mjs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { visit } from 'unist-util-visit';
22

33
export const referenceToLocalMdFile = /^(?![+a-z]+:)([^#?]+)\.md(#.+)?$/i;
4+
export const referenceToLocalMdFileInPre = /<a href="([^#"]+)\.md(#[^"]+)?">/g;
45

56
export function replaceLinks({ filename, linksMapper }) {
67
return (tree) => {
@@ -14,6 +15,14 @@ export function replaceLinks({ filename, linksMapper }) {
1415
);
1516
}
1617
});
18+
visit(tree, 'code', (node) => {
19+
if (node.meta === 'html') {
20+
node.value = node.value.replace(
21+
referenceToLocalMdFileInPre,
22+
(_, path, fragment) => `<a href="${path}.html${fragment || ''}">`,
23+
);
24+
}
25+
});
1726
visit(tree, 'definition', (node) => {
1827
const htmlUrl = fileHtmlUrls && fileHtmlUrls[node.identifier];
1928

0 commit comments

Comments
 (0)