Skip to content

Commit 24df945

Browse files
committed
doc: add legacy anchors to headers to preserve old links
1 parent 778c162 commit 24df945

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

tools/doc/html.mjs

+24
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,7 @@ const DEPRECATION_HEADING_PATTERN = /^DEP\d+:/;
381381
export function buildToc({ filename, apilinks }) {
382382
return (tree, file) => {
383383
const idCounters = Object.create(null);
384+
const legacyIdCounters = Object.create(null);
384385
let toc = '';
385386
let depth = 0;
386387

@@ -399,6 +400,8 @@ export function buildToc({ filename, apilinks }) {
399400
node.children[0].position.start.offset,
400401
node.position.end.offset).trim();
401402
const id = getId(headingText, idCounters);
403+
// Use previous ID generator to create alias
404+
const legacyId = getLegacyId(`${realFilename}_${headingText}`, legacyIdCounters);
402405

403406
const isDeprecationHeading =
404407
DEPRECATION_HEADING_PATTERN.test(headingText);
@@ -417,6 +420,9 @@ export function buildToc({ filename, apilinks }) {
417420
let anchor =
418421
`<span><a class="mark" href="#${id}" id="${id}">#</a></span>`;
419422

423+
// Add alias anchor to preserve old links
424+
anchor += `<a class="legacy" id="${legacyId}"></a>`;
425+
420426
if (realFilename === 'errors' && headingText.startsWith('ERR_')) {
421427
anchor +=
422428
`<span><a class="mark" href="#${headingText}" id="${headingText}">#</a></span>`;
@@ -446,6 +452,7 @@ export function buildToc({ filename, apilinks }) {
446452
};
447453
}
448454

455+
// ID generator that mirrors Github's heading anchor parser
449456
const punctuation = /[^\w\- ]/g;
450457
function getId(text, idCounters) {
451458
text = text.toLowerCase()
@@ -458,6 +465,23 @@ function getId(text, idCounters) {
458465
return text;
459466
}
460467

468+
// This ID generator is purely to generate aliases
469+
// so we can preserve old doc links
470+
const notAlphaNumerics = /[^a-z0-9]+/g;
471+
const edgeUnderscores = /^_+|_+$/g;
472+
const notAlphaStart = /^[^a-z]/;
473+
function getLegacyId(text, idCounters) {
474+
text = text.toLowerCase()
475+
.replace(notAlphaNumerics, '_')
476+
.replace(edgeUnderscores, '')
477+
.replace(notAlphaStart, '_$&');
478+
if (idCounters[text] !== undefined) {
479+
return `${text}_${++idCounters[text]}`;
480+
}
481+
idCounters[text] = 0;
482+
return text;
483+
}
484+
461485
function altDocs(filename, docCreated, versions) {
462486
const [, docCreatedMajor, docCreatedMinor] = docCreated.map(Number);
463487
const host = 'https://nodejs.org';

0 commit comments

Comments
 (0)