okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
2.0 KiB34 linesraw
1// serve/web/math-adapter.js - the KaTeX renderer for math.js (PR #2974 by CC-David-CC). KaTeX 0.19.0 is vendored in
2// serve/web/vendor/katex (MIT, see PROVENANCE.json there): no network, no CDN. Nothing is loaded until "Render math" is
3// switched on and an answer holds a formula.
4//
5// What a formula may do: nothing but draw. `trust: false` turns off \href, \url, \includegraphics and \htmlClass-style
6// commands, so a formula cannot make a link, load a picture or add an attribute; the macros are not shared between
7// formulas; \def loops are cut by maxExpand and a huge \rule or \kern by maxSize. KaTeX builds DOM nodes itself (no
8// innerHTML), the result is cloned into the page by math.js, and an error returns the source text instead.
9"use strict";
10(function (root) {
11  const OPTIONS = {output: "htmlAndMathml", trust: false, throwOnError: true, strict: "ignore", maxExpand: 1000, maxSize: 20};
12  const adapter = {
13    OPTIONS,
14    async initialize() {
15      if (root.katex && document.querySelector("link[data-katex-ready]")) return;
16      const css = document.createElement("link"); css.rel = "stylesheet";
17      css.href = "web/vendor/katex/dist/katex.min.css";
18      const loaded = new Promise((resolve, reject) => { css.onload = resolve; css.onerror = reject; });
19      document.head.append(css);
20      await Promise.all([loaded, root.katex ? Promise.resolve() : root.StrataMath.script("web/vendor/katex/dist/katex.min.js")]);
21      css.dataset.katexReady = "1";
22    },
23    async render(source, {display, signal}) {
24      if (signal.aborted) return {ok: false, reason: "unavailable"};
25      const element = document.createElement("span");
26      try {
27        root.katex.render(source, element, {...OPTIONS, displayMode: display, macros: {}});
28        return {ok: true, element: element.firstElementChild};
29      } catch (_) { return {ok: false, reason: "invalid"}; }
30    },
31  };
32  root.StrataMathAdapter = adapter;
33  if (typeof module !== "undefined" && module.exports) module.exports = adapter;
34})(typeof globalThis !== "undefined" ? globalThis : this);