@pie-element/shared-math-rendering-mathjax 0.1.1-next.3 → 0.1.1-next.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/adapter.d.ts CHANGED
@@ -2,8 +2,9 @@ import type { MathjaxOptions } from './types.js';
2
2
  /**
3
3
  * Create a MathJax renderer function.
4
4
  *
5
- * MathJax loads once per page, the first time an element holds math, from `srcUrl` or MathJax
6
- * 4.1.3 on jsDelivr. A MathJax the page already has, or is loading, is used instead.
5
+ * MathJax loads once per page, on the first render, from `srcUrl` or MathJax 4.1.3 on jsDelivr.
6
+ * A MathJax the page already has, or is loading, is used instead. A render waits on the load only
7
+ * when its element holds math.
7
8
  *
8
9
  * @param options - Renderer options
9
10
  * @returns Renderer function that typesets math in an element
package/dist/index.d.ts CHANGED
@@ -17,4 +17,6 @@
17
17
  */
18
18
  export { createMathjaxRenderer, getMathjaxCssUrls } from './adapter.js';
19
19
  export type { MathRenderer, MathRenderingAPI, MathjaxOptions } from './types.js';
20
+ export { MATHJAX_CONFLICT_EVENT, UNSUPPORTED_PAGE_DOCS_URL } from './unsupported-page.js';
21
+ export type { MathjaxConflictCondition, MathjaxConflictDetail } from './unsupported-page.js';
20
22
  export { renderMath, wrapMath, unWrapMath, mmlToLatex } from './render-math.js';
package/dist/index.js CHANGED
@@ -1,121 +1,203 @@
1
+ //#region src/unsupported-page.ts
2
+ var e = "https://github.com/pie-framework/pie-players/blob/develop/docs/item-player/loading-strategies.md#one-mathjax-version-per-page", t = "pie-mathjax-version-conflict", n = Symbol.for("@pie-element/shared-math-rendering-mathjax/unsupported-page");
3
+ function r(r, i) {
4
+ if (typeof window > "u") return;
5
+ let a = globalThis;
6
+ a[n] ??= {
7
+ logged: !1,
8
+ conditions: []
9
+ };
10
+ let o = a[n];
11
+ if (o.conditions.includes(r)) return;
12
+ o.conditions.push(r);
13
+ let s = `[math-rendering] Unsupported page (${r}): ${i}. PIE supports one MathJax major version per page; with MathJax 3 and 4 on one page, math rendering is best effort and may break. See ${e}`;
14
+ o.logged || (o.logged = !0, console.error(s)), window.dispatchEvent(new CustomEvent(t, { detail: {
15
+ condition: r,
16
+ message: s,
17
+ docsUrl: e
18
+ } }));
19
+ }
20
+ function i() {
21
+ let e = window.MathJax?.version;
22
+ return typeof e == "string" && e.startsWith("3.") ? e : void 0;
23
+ }
24
+ //#endregion
1
25
  //#region src/adapter.ts
2
- var e = {
26
+ var a = "https://cdn.jsdelivr.net/npm/mathjax@4.1.3/tex-mml-chtml.js", o = {
3
27
  parallelogram: "\\lower.2em{\\Huge\\unicode{x25B1}}",
4
28
  overarc: "\\overparen",
5
29
  napprox: "\\not\\approx",
6
30
  longdiv: "\\enclose{longdiv}",
7
31
  abs: ["\\left|#1\\right|", 1]
8
- }, t = "[math-rendering] using $ is not advisable, please use $$..$$ or \\(...\\)", n = /\\\(|\\\[|\$\$|\\\$|\\begin\{|\\(?:eq)?ref\{/, r = /\\\(|\\\[|\$|\\begin\{|\\(?:eq)?ref\{/, i = /\\embed\{newLine\}\[\]/g, a = [
32
+ }, s = "[math-rendering] using $ is not advisable, please use $$..$$ or \\(...\\)", c = /\\\(|\\\[|\$\$|\\\$|\\begin\{|\\(?:eq)?ref\{/, l = /\\\(|\\\[|\$|\\begin\{|\\(?:eq)?ref\{/, u = /\\embed\{newLine\}\[\]/g, d = [
9
33
  ["$$", "$$"],
10
34
  ["$", "$"],
11
35
  ["\\[", "\\]"],
12
36
  ["\\(", "\\)"]
13
- ], o = Symbol.for("@pie-element/shared-math-rendering-mathjax/loading");
14
- function s() {
37
+ ], f = Symbol.for("@pie-element/shared-math-rendering-mathjax/loading"), p = "PIE-MJX-CHTML-styles", m = "MJX-CHTML-styles", h = [m, "MJX-SVG-styles"], g = 201;
38
+ function _(e) {
39
+ let t = [...e.matches("mjx-container") ? [e] : [], ...e.querySelectorAll("mjx-container")];
40
+ for (let e of t) for (let t of [e, ...e.querySelectorAll("[data-latex],[data-latex-item]")]) t.removeAttribute("data-latex"), t.removeAttribute("data-latex-item");
41
+ }
42
+ function v() {
15
43
  return window.MathJax;
16
44
  }
17
- function c(e) {
45
+ function y(e) {
18
46
  let t = e.includes("\\displaystyle") ? e.replace("\\displaystyle", "").trim() : e;
19
- for (let [e, n] of a) if (t.startsWith(e) && t.endsWith(n)) return t.substring(e.length, t.length - n.length);
47
+ for (let [e, n] of d) if (t.startsWith(e) && t.endsWith(n)) return t.substring(e.length, t.length - n.length);
20
48
  return t;
21
49
  }
22
- function l(e) {
50
+ function b(e) {
23
51
  for (let t of e.querySelectorAll("[data-latex]")) {
24
52
  if (t.dataset.mathHandled || t.closest("mjx-container")) continue;
25
53
  let e = t.textContent;
26
- e && (t.textContent = `\\(${c(e)}\\)`.replace(i, "\\newline "), t.dataset.mathHandled = "true");
54
+ e && (t.textContent = `\\(${y(e)}\\)`.replace(u, "\\newline "), t.dataset.mathHandled = "true");
27
55
  }
28
56
  }
29
- function u(e, t) {
57
+ function x(e, t) {
30
58
  for (let t of e.querySelectorAll("math")) if (!t.closest("mjx-assistive-mml")) return !0;
31
- return (t ? r : n).test(e.textContent ?? "");
59
+ return (t ? l : c).test(e.textContent ?? "");
32
60
  }
33
- function d(n) {
34
- return new Promise((r, i) => {
35
- let { useSingleDollar: a = !1, accessibility: o = !0, loadFonts: c = !0, srcUrl: l } = n, u = {
61
+ function S(e) {
62
+ return new Promise((t, n) => {
63
+ let { useSingleDollar: r = !1, accessibility: i = !0, loadFonts: c = !0, srcUrl: l } = e, u = {
36
64
  loader: {
37
- load: o ? ["a11y/assistive-mml"] : [],
38
- failed: (e) => i(e)
65
+ load: i ? ["a11y/assistive-mml"] : [],
66
+ failed: (e) => n(e)
39
67
  },
40
68
  startup: {
41
69
  typeset: !1,
42
70
  ready: () => {
43
- let e = s()?.startup;
44
- e?.defaultReady?.(), Promise.resolve(e?.promise).then(() => r(), i);
71
+ let e = v(), r = e?.startup, i = !!e?.version?.startsWith("4.");
72
+ i && C(e), r?.defaultReady?.(), i && w(r?.document), Promise.resolve(r?.promise).then(() => t(), n);
45
73
  }
46
74
  },
47
- tex: { macros: { ...e } },
75
+ tex: { macros: { ...o } },
48
76
  options: {
49
- enableMenu: o,
77
+ enableMenu: i,
50
78
  menuOptions: { settings: {
51
- assistiveMml: o,
79
+ assistiveMml: i,
52
80
  enrich: !1,
53
81
  inTabOrder: !1
54
82
  } }
55
83
  }
56
84
  };
57
- a && u.tex && (console.warn(t), u.tex.inlineMath = [["$", "$"], ["\\(", "\\)"]], u.tex.processEscapes = !0), c || (u.chtml = { fontURL: "" }), window.MathJax = u;
85
+ r && u.tex && (console.warn(s), u.tex.inlineMath = [["$", "$"], ["\\(", "\\)"]], u.tex.processEscapes = !0), c || (u.chtml = { fontURL: "" }), window.MathJax = u;
58
86
  let d = document.createElement("script");
59
- d.src = l || "https://cdn.jsdelivr.net/npm/mathjax@4.1.3/tex-mml-chtml.js", d.async = !0, d.onerror = () => i(/* @__PURE__ */ Error("Failed to load MathJax")), document.head.appendChild(d);
87
+ d.src = l || a, d.async = !0, d.onerror = () => n(/* @__PURE__ */ Error("Failed to load MathJax")), document.head.appendChild(d);
88
+ });
89
+ }
90
+ function C(e) {
91
+ let t = e?._?.output?.chtml_ts?.CHTML;
92
+ t && (t.STYLESHEETID = p);
93
+ }
94
+ function w(e) {
95
+ if (!e) return;
96
+ let t = /* @__PURE__ */ new WeakSet(), n = (e) => {
97
+ let n = e.typesetRoot;
98
+ !n || t.has(n) || (_(n), t.add(n));
99
+ };
100
+ e.addRenderAction?.("pie-strip-latex", g, (e) => {
101
+ for (let t of e.math ?? []) n(t);
102
+ return !1;
103
+ }, (e) => {
104
+ let t = e.typesetRoot;
105
+ return t && _(t), !1;
106
+ });
107
+ let r = e.outputJax?.chtmlStyles;
108
+ r?.id === m && (r.id = p), D();
109
+ }
110
+ function T(e) {
111
+ return e instanceof HTMLStyleElement && h.includes(e.id);
112
+ }
113
+ function E(e) {
114
+ r("foreign-output-stylesheet", `another MathJax added <style id="${e.id}"> to <head>`);
115
+ }
116
+ function D() {
117
+ let e = document.head, t = [...e.children].find(T);
118
+ if (t) {
119
+ E(t);
120
+ return;
121
+ }
122
+ let n = new MutationObserver((e) => {
123
+ for (let t of e) {
124
+ let e = [...t.addedNodes].find(T);
125
+ if (e) {
126
+ E(e), n.disconnect();
127
+ return;
128
+ }
129
+ }
60
130
  });
131
+ n.observe(e, { childList: !0 });
61
132
  }
62
- function f(e) {
133
+ function O(e) {
63
134
  return new Promise((t, n) => {
64
135
  let r = e.startup ?? {};
65
136
  e.startup = r;
66
137
  let i = r.ready;
67
138
  r.ready = () => {
68
- let e = s()?.startup;
139
+ let e = v()?.startup;
69
140
  i ? i.call(r) : e?.defaultReady?.(), Promise.resolve(e?.promise).then(() => t(), n);
70
141
  };
71
142
  });
72
143
  }
73
- function p(e) {
74
- let t = s();
75
- return t ? t.version ? t.startup?.promise ? Promise.resolve(t.startup.promise).then(() => void 0) : Promise.resolve() : f(t) : d(e);
144
+ function k(e) {
145
+ let t = v();
146
+ return t ? t.version ? t.startup?.promise ? Promise.resolve(t.startup.promise).then(() => void 0) : Promise.resolve() : O(t) : S(e);
76
147
  }
77
- function m(e) {
78
- return p(e).then(() => {
79
- typeof s()?.typesetPromise != "function" && console.warn("[mathjax-renderer] MathJax on this page has no typesetPromise; math stays untypeset.");
148
+ function A(e) {
149
+ return k(e).then(() => {
150
+ typeof v()?.typesetPromise != "function" && console.warn("[mathjax-renderer] MathJax on this page has no typesetPromise; math stays untypeset.");
80
151
  });
81
152
  }
82
- function h(e) {
83
- let t = globalThis, n = t[o];
84
- return n || (n = m(e), t[o] = n), n;
153
+ function j(e) {
154
+ let t = globalThis, n = t[f];
155
+ return n || (n = A(e), t[f] = n), n;
85
156
  }
86
- function g(e = {}) {
157
+ function M(e = {}) {
87
158
  let t = e.useSingleDollar ?? !1;
88
159
  return async (n) => {
89
- if (typeof window > "u" || (l(n), !u(n, t))) return;
90
- await h(e);
91
- let r = s();
92
- await r?.startup?.promise, typeof r?.typesetPromise == "function" && await r.typesetPromise([n]);
160
+ if (typeof window > "u") return;
161
+ let a = i();
162
+ a && r("mathjax-3-global", `window.MathJax is MathJax ${a}`), b(n);
163
+ let o = j(e);
164
+ if (!x(n, t)) {
165
+ o.catch(() => {});
166
+ return;
167
+ }
168
+ await o;
169
+ let s = v();
170
+ await s?.startup?.promise, typeof s?.typesetPromise == "function" && (await s.typesetPromise([n]), _(n));
93
171
  };
94
172
  }
95
- function _() {
173
+ function N() {
96
174
  return [];
97
175
  }
98
176
  //#endregion
99
177
  //#region src/render-math.ts
100
- var v = "@pie-lib/math-rendering", y = "@pie-lib/math-rendering@2", b = null;
101
- function x() {
102
- return !!window[y]?.opts?.useSingleDollar;
178
+ var P = "@pie-lib/math-rendering", F = "@pie-lib/math-rendering@2", I = null;
179
+ function L() {
180
+ return !!window[F]?.opts?.useSingleDollar;
103
181
  }
104
- function S() {
105
- return b ||= g({ useSingleDollar: x() }), b;
182
+ function R() {
183
+ return I ||= M({ useSingleDollar: L() }), I;
106
184
  }
107
- function C() {
185
+ function z() {
108
186
  if (typeof window > "u") return null;
109
- let e = window[v];
187
+ let e = window[P];
110
188
  return typeof e?.renderMath == "function" ? e : null;
111
189
  }
112
- var w = async (e) => {
190
+ function B() {
191
+ let e = i();
192
+ e && r("legacy-renderer-delegation", `window['${P}'] renders this element's math with MathJax ${e}`);
193
+ }
194
+ var V = async (e) => {
113
195
  if (typeof window > "u") return;
114
196
  let t = typeof e == "string", n;
115
197
  t ? (n = document.createElement("div"), n.innerHTML = e) : n = e || document.body;
116
- let r = C();
117
- return r ? await r.renderMath?.(n) : await S()(n), t ? n.innerHTML : void 0;
118
- }, T = (e) => C()?.wrapMath?.(e) ?? e, E = (e) => {
198
+ let r = z();
199
+ return r ? (B(), await r.renderMath?.(n)) : await R()(n), t ? n.innerHTML : void 0;
200
+ }, H = (e) => z()?.wrapMath?.(e) ?? e, U = (e) => {
119
201
  let t = e.trim();
120
202
  return t.startsWith("\\[") && t.endsWith("\\]") ? {
121
203
  unwrapped: t.slice(2, -2).trim(),
@@ -142,6 +224,6 @@ var w = async (e) => {
142
224
  close: "$"
143
225
  }
144
226
  } : { unwrapped: t };
145
- }, D = (e) => C()?.mmlToLatex?.(e) ?? e;
227
+ }, W = (e) => z()?.mmlToLatex?.(e) ?? e;
146
228
  //#endregion
147
- export { g as createMathjaxRenderer, _ as getMathjaxCssUrls, D as mmlToLatex, w as renderMath, E as unWrapMath, T as wrapMath };
229
+ export { t as MATHJAX_CONFLICT_EVENT, e as UNSUPPORTED_PAGE_DOCS_URL, M as createMathjaxRenderer, N as getMathjaxCssUrls, W as mmlToLatex, V as renderMath, U as unWrapMath, H as wrapMath };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Reporting for pages that run MathJax 3 beside this adapter's MathJax 4. PIE supports one
3
+ * MathJax major version per page; on a mixed page rendering is best effort, and the developer
4
+ * learns why from the console and from {@link MATHJAX_CONFLICT_EVENT}.
5
+ */
6
+ export declare const UNSUPPORTED_PAGE_DOCS_URL = "https://github.com/pie-framework/pie-players/blob/develop/docs/item-player/loading-strategies.md#one-mathjax-version-per-page";
7
+ /**
8
+ * Dispatched on `window` once per condition per page, with a {@link MathjaxConflictDetail}.
9
+ * Hosts and players forward it to their instrumentation.
10
+ */
11
+ export declare const MATHJAX_CONFLICT_EVENT = "pie-mathjax-version-conflict";
12
+ export type MathjaxConflictCondition =
13
+ /** `window.MathJax` is a MathJax 3 build. */
14
+ 'mathjax-3-global'
15
+ /** Another MathJax output stylesheet was added to `<head>` beside this adapter's. */
16
+ | 'foreign-output-stylesheet'
17
+ /** `window['@pie-lib/math-rendering']` routes ESM element math to MathJax 3. */
18
+ | 'legacy-renderer-delegation';
19
+ export interface MathjaxConflictDetail {
20
+ condition: MathjaxConflictCondition;
21
+ message: string;
22
+ docsUrl: string;
23
+ }
24
+ /**
25
+ * Logs one `console.error` per page, for the first condition seen, and dispatches
26
+ * {@link MATHJAX_CONFLICT_EVENT} once for each condition.
27
+ */
28
+ export declare function reportUnsupportedPage(condition: MathjaxConflictCondition, detail: string): void;
29
+ /** The version of `window.MathJax` when it is a MathJax 3 build. */
30
+ export declare function mathjax3Version(): string | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pie-element/shared-math-rendering-mathjax",
3
- "version": "0.1.1-next.3",
3
+ "version": "0.1.1-next.5",
4
4
  "description": "MathJax adapter for PIE math rendering",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -18,6 +18,7 @@
18
18
  "build": "rm -rf dist tsconfig.tsbuildinfo && vite build && tsc --emitDeclarationOnly",
19
19
  "dev": "vite build --watch",
20
20
  "test": "vitest",
21
+ "test:e2e": "playwright test",
21
22
  "clean": "rm -rf dist"
22
23
  },
23
24
  "dependencies": {},