Fixed an issue with other nodes than text being parsed incorrectly in the table of contents

This commit is contained in:
Piotr Janosz
2019-08-29 19:59:45 +02:00
parent 16ae47f2ad
commit 93bda7972c

View File

@@ -1,5 +1,3 @@
const { toJSX } = require('@mdx-js/mdx/mdx-hast-to-jsx');
const MIN_HEADING_LEVEL = 1;
const MAX_HEADING_LEVEL = 3;
@@ -63,15 +61,28 @@ function isSlugifiedSection(node) {
return node.tagName === 'section' && node.properties && node.properties.id && node.properties.depth;
}
// Because of autolinking headings earlier (at remark stage), the headings (nodes)
// contain an anchor tag next to the title, we only want to render the title.
// Unless there is no title, then we render whatever nodes we get after the anchor
function toFragment(nodes) {
// Because of autolinking headings earlier (at remark stage), the headings (nodes)
// contain an anchor tag next to the title, we only want to render the text.
// Unless there is no text, then we render whatever nodes we get in a Fragment
const textNode = nodes.find(node => node.type === 'text');
if (textNode) {
return JSON.stringify(textNode.value);
const nodesCopy = [...nodes]; // We copy not to mutate the original nodes array
nodesCopy.shift(); // Remove the heading anchor created by remark_autolink_headings
if (nodesCopy.length === 1 && nodesCopy[0].type === 'text') {
return JSON.stringify(nodesCopy[0].value);
} else {
const textNodes = [];
for (node of nodesCopy) {
if (node.type === 'text') {
textNodes.push(node.value);
} else {
// For nodes other than text (e.g. anchors) find child node that containes the text
childTextNode = node.children.find(child => child.type === 'text');
textNodes.push(childTextNode.value);
}
}
return `<React.Fragment>${textNodes.join('')}</React.Fragment>`;
}
return '<React.Fragment>' + nodes.map(toJSX).join('') + '</React.Fragment>';
}
function tableOfContentsListSerializer(nodes, indent = 0) {