UNPKG

@lobehub/ui

Version:

Lobe UI is an open-source UI component library for building AIGC web apps

73 lines (72 loc) 2.22 kB
import { SKIP, visitParents } from "unist-util-visit-parents"; import { fromHtmlIsomorphic } from "hast-util-from-html-isomorphic"; import { toText } from "hast-util-to-text"; import katex from "katex"; //#region src/Markdown/plugins/rehypeKatex.ts const emptyClasses = []; const rehypeKatex = (options) => (tree, file) => { const settings = options || {}; visitParents(tree, "element", (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.at(-1); let scope = element; if (element.tagName === "code" && languageMath && parent && parent.type === "element" && parent.tagName === "pre") { scope = parent; parent = parents.at(-2); displayMode = true; } if (!parent) return; const value = toText(scope, { whitespace: "pre" }); let result; try { result = katex.renderToString(value, { ...settings, displayMode, throwOnError: true }); } catch (error) { const cause = error; file.message("Could not render math with KaTeX", { ancestors: [...parents, element], cause, place: element.position, ruleId: cause.name.toLowerCase(), source: "rehype-katex" }); try { result = katex.renderToString(value, { ...settings, displayMode, strict: "ignore", throwOnError: false }); } catch { result = [{ children: [{ type: "text", value }], properties: { className: ["katex-error"], style: "color:" + (settings.errorColor || "#cc0000"), title: String(error) }, tagName: "span", type: "element" }]; } } if (typeof result === "string") result = fromHtmlIsomorphic(result, { fragment: true }).children; const index = parent.children.indexOf(scope); parent.children.splice(index, 1, ...result); return SKIP; }); }; //#endregion export { rehypeKatex }; //# sourceMappingURL=rehypeKatex.mjs.map