Closed tbranyen closed 1 year ago
With this fix we'll be able to hook into the parser again and do fun things like make mermaid tags (something I want for the website to display diagrams):
import { use, innerHTML } from 'diffhtml';
use({
createTreeHook({ nodeName, childNodes }) {
if (nodeName === 'mermaid') {
childNodes[0].nodeValue = mermaid(childNodes[0].nodeValue);
}
}
});
innerHTML(document.body, `
<mermaid>
Some mermaid text
</mermaid>
`);
Getting close to having mermaid support, was trickier than anticipated given that it uses the DOM to generate SVG instead of doing it virtually :-/
// Mermaid parsing
use({
createTreeHook({ nodeName, childNodes }) {
if (nodeName === 'mermaid') {
if (childNodes[0].nodeType === Internals.NODE_TYPE.TEXT) {
// FIXME no jsdom support
Object.prototype.getBBox = () => ({
width: 0,
height: 0,
});
// FIXME no jsdom support
Object.prototype.sanitize = (x) => x;
mermaid.render('id1', childNodes[0].nodeValue, svg => {
// Replace with the newly rendered SVG
childNodes[0] = html(svg);
});
}
}
},
});
Wow I got it working and I'm pretty shocked this works:
// Create a jsdom and svgdom merged environment for Mermaid to work.
// Create a jsdom and svgdom merged environment for Mermaid to work.
const SVG = require('svgdom');
const { JSDOM } = require('jsdom');
const { window } = new JSDOM('');
// Patch the Element constructor which is inherited by SVGElement to contain
// the getBBox method to avoid runtime errors with mermaid.
window.Element.prototype.getBBox = SVG.SVGGraphicsElement.prototype.getBBox;
// Unfortunately this patching has to occur in order for the sanitize method
// to return the input and not break under mermaid. Would be great to have
// a fix that didn't involve this.
Object.prototype.sanitize = x => x;
assign(globalThis, {
document: window.document,
window,
});
// Mermaid parsing
use({
createTreeHook({ nodeName, childNodes }) {
if (nodeName === 'mermaid') {
if (childNodes[0].nodeType === Internals.NODE_TYPE.TEXT) {
mermaid.render('mermaid', childNodes[0].nodeValue.trim(), svg => {
// Replace with the newly rendered SVG
childNodes[0] = html(svg);
});
}
}
},
});
In the new parser createTree was called with only a tag name and not the attributes or childNodes. This PR fixes the new parser to wait until the element is closed before calling createTree. This work uncovered some inconsistencies and improved the parser by closing out the pointer and resetting to the parent in a function.