MathJax-docs icon indicating copy to clipboard operation
MathJax-docs copied to clipboard

The getSvgImage function does not work as written under Creating Stand-Alone SVG Images

Open brichwin opened this issue 5 months ago • 0 comments

Description

When I run the Creating Stand-Alone SVG Images example:

 const svgCss = [
   'svg a{fill:blue;stroke:blue}',
   '[data-mml-node="merror"]>g{fill:red;stroke:red}',
   '[data-mml-node="merror"]>rect[data-background]{fill:yellow;stroke:none}',
   '[data-frame],[data-line]{stroke-width:70px;fill:none}',
   '.mjx-dashed{stroke-dasharray:140}',
   '.mjx-dotted{stroke-linecap:round;stroke-dasharray:0,140}',
   'use[data-c]{stroke-width:3px}'
 ].join('');
 const xmlDeclaration = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>';

 async function getSvgImage(math, options = {}) {
   const adaptor = MathJax.startup.adaptor;
   const result = await MathJax.tex2svgPromise(math, options);
   let svg = adaptor.tags(result, 'svg')[0];
   svg = (svg.match(/^<svg.*?><defs>/)
     ? svg.replace(/<defs>/, `<defs><style>${svgCss}</style>`)
     : svg.replace(/^(<svg.*?>)/, `$1<defs><style>${svgCss}</style></defs>`));
  svg = svg.replace(/ (?:role|focusable|aria-hidden)=".*?"/g, '')
           .replace(/"currentColor"/g, '"black"');
  return xmlDeclaration + '\n' + svg;
}

I get:

file:///Users/brichwin/dev/mathjax-node-testing/services/mathjax.mjs:56
   svg = (svg.match(/^<svg.*?><defs>/)
              ^

TypeError: svg.match is not a function
    at getSvgImage (file:///Users/brichwin/dev/mathjax-node-testing/services/mathjax.mjs:56:15)
    at async file:///Users/brichwin/dev/mathjax-node-testing/services/mathjax.mjs:65:13

The line let svg = adaptor.tags(result, 'svg')[0]; appears to return a DOM node which must be converted to a string before calling match.

It appears to work if replacing that line with these:

  const svgNode = adaptor.tags(result, 'svg')[0] || result;
  let svg = adaptor.outerHTML(svgNode);

brichwin avatar Oct 08 '25 21:10 brichwin