Pete Bacon Darwin 77309e2ea4 build(aio): map H3 headings into H4 headings for certain templates (#24000)
The sections such as methods and decorator options are already headed
by a H3 heading so we need to map the H3 headings in the API doc source
down to H4 headings.

This commit includes general heading mapping functionality accessible via
the `marked` Nunjucks filter.

PR Close #24000
2018-06-13 16:47:40 -07:00

32 lines
817 B
JavaScript

const visit = require('unist-util-visit');
function headingToLevel(heading) {
const match = /^h(\d+)/.exec(heading);
return match ? match[1] : '0';
}
function parseMappings(mappings) {
const mapping = {};
Object.keys(mappings).forEach(key => mapping[headingToLevel(key)] = headingToLevel(mappings[key]));
return mapping;
}
module.exports = function mapHeadings(mappings) {
const headings = parseMappings(mappings || {});
return () => ast => {
const nodesToFix = [];
Object.keys(headings).forEach(heading => {
visit(ast, 'heading', node => {
if (node.depth === Number(heading)) {
nodesToFix.push(node);
}
});
});
// Update the depth of the matched nodes
nodesToFix.forEach(node => node.depth = headings[node.depth]);
return ast;
};
};