"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const browser = require("../hast-util-from-html-isomorphic/lib-browser.cjs");
const katex = require("../katex/dist-katex.cjs");
const index = require("../unist-util-visit-parents/lib-index.cjs");
const index$1 = require("../hast-util-to-text/lib-index.cjs");
const emptyOptions = {};
const emptyClasses = [];
function rehypeKatex(options) {
  const settings = options || emptyOptions;
  return function(tree, file) {
    index.visitParents(tree, "element", function(element, parents) {
      const classes = Array.isArray(element.properties.className) ? element.properties.className : emptyClasses;
      const languageMath = classes.includes("language-math");
      const mathDisplay = classes.includes("math-display");
      const mathInline = classes.includes("math-inline");
      let displayMode = mathDisplay;
      if (!languageMath && !mathDisplay && !mathInline) {
        return;
      }
      let parent = parents[parents.length - 1];
      let scope = element;
      if (element.tagName === "code" && languageMath && parent && parent.type === "element" && parent.tagName === "pre") {
        scope = parent;
        parent = parents[parents.length - 2];
        displayMode = true;
      }
      if (!parent) return;
      const value = index$1.toText(scope, { whitespace: "pre" });
      let result;
      try {
        result = katex.default.renderToString(value, {
          ...settings,
          displayMode,
          throwOnError: true
        });
      } catch (error) {
        const cause = (
          /** @type {Error} */
          error
        );
        const ruleId = cause.name.toLowerCase();
        file.message("Could not render math with KaTeX", {
          ancestors: [...parents, element],
          cause,
          place: element.position,
          ruleId,
          source: "rehype-katex"
        });
        try {
          result = katex.default.renderToString(value, {
            ...settings,
            displayMode,
            strict: "ignore",
            throwOnError: false
          });
        } catch {
          result = [
            {
              type: "element",
              tagName: "span",
              properties: {
                className: ["katex-error"],
                style: "color:" + (settings.errorColor || "#cc0000"),
                title: String(error)
              },
              children: [{ type: "text", value }]
            }
          ];
        }
      }
      if (typeof result === "string") {
        const root = browser.fromHtmlIsomorphic(result);
        result = /** @type {Array<ElementContent>} */
        root.children;
      }
      const index$2 = parent.children.indexOf(scope);
      parent.children.splice(index$2, 1, ...result);
      return index.SKIP;
    });
  };
}
exports.default = rehypeKatex;
//# sourceMappingURL=lib-index.cjs.map
