All files / src parse-math.ts

18.75% Statements 3/16
0% Branches 0/13
0% Functions 0/1
18.75% Lines 3/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 571x   1x                                         1x                                                                  
import * as path from "path";
import { MathRenderingOption } from "./markdown-engine-config";
import { configs, escapeString, extensionDirectoryPath } from "./utility";
 
// tslint:disable-next-line interface-over-type-literal
export type ParseMathArgs = {
  content: string;
  openTag: string;
  closeTag: string;
  displayMode?: boolean;
  renderingOption: MathRenderingOption;
};
 
let katex;
 
/**
 *
 * @param content the math expression
 * @param openTag the open tag, eg: '\('
 * @param closeTag the close tag, eg: '\)'
 * @param displayMode whether to be rendered in display mode
 * @param renderingOption the math engine to use: KaTeX | MathJax | None
 */
export default ({
  content,
  openTag,
  closeTag,
  displayMode = false,
  renderingOption,
}: ParseMathArgs) => {
  if (!content) {
    return "";
  }
  if (renderingOption === "KaTeX") {
    try {
      if (!katex) {
        katex = require(path.resolve(
          extensionDirectoryPath,
          "./dependencies/katex/katex.min.js",
        ));
      }
      return katex.renderToString(
        content,
        Object.assign({}, configs.katexConfig || {}, { displayMode }),
      );
    } catch (error) {
      return `<span style=\"color: #ee7f49; font-weight: 500;\">${error.toString()}</span>`;
    }
  } else if (renderingOption === "MathJax") {
    const text = (openTag + content + closeTag).replace(/\n/g, " ");
    const tag = displayMode ? "div" : "span";
    return `<${tag} class="mathjax-exps">${escapeString(text)}</${tag}>`;
  } else {
    return "";
  }
};