Skip to content

Commit

Permalink
fix(svg): prevent svg transform from clobbering previous nodes (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
paul-sachs committed Feb 16, 2023
1 parent fbbe2eb commit 834e282
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
25 changes: 25 additions & 0 deletions lib/src/mdxast-mermaid.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,29 @@ function MDXContent(props = {}) {
export default MDXContent;
`)
})

test('multiple mermaid instances in svg don\'t clobber previous node', async () => {
const result = await compileMdx(
`## Framework AARRR
Some content
\`\`\`mermaid
graph TD;
A-->B;
\`\`\`
And some more:
\`\`\`mermaid
graph TD;
A-->B;
\`\`\``,
{ output: 'svg' }
);
expect(result.value).toContain('And some more');
})
})


13 changes: 9 additions & 4 deletions lib/src/mdxast-mermaid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,18 @@ export default function plugin(config?: Config) {
if (config?.output === 'svg') {
return async function transformer(ast: any): Promise<Parent> {
// Find all the mermaid diagram code blocks. i.e. ```mermaid
const instances = findInstances(ast)
let instances = findInstances(ast);

// Replace each Mermaid code block with the Mermaid component
for (let i = 0; i < instances.length; i++) {
const [node, index, parent] = instances[i]
// Here we iterate over the instances and replace them with the SVG
// and run findInstances again to get the next set instances. We do this
// because the replacement process can change the AST and cause
// the indexes to be incorrect.
while (instances.length > 0) {
const [node, index, parent] = instances[0];
const result = await outputSVG(node as any, index, parent, config);
Array.prototype.splice.apply(parent.children, [index, 1, ...result])
Array.prototype.splice.apply(parent.children, [index, 1, ...result]);
instances = findInstances(ast);
}
return ast
}
Expand Down

0 comments on commit 834e282

Please sign in to comment.