@pie-element/shared-math-rendering-mathjax 0.1.1-next.2 → 0.1.1-next.20261002100925

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
@@ -1,66 +1,19 @@
1
- /**
2
- * MathJax math renderer
3
- *
4
- * Loads MathJax v4 from CDN and provides math rendering functionality.
5
- * Supports LaTeX and MathML with full accessibility features.
6
- */
7
1
  import type { MathjaxOptions } from './types.js';
8
- interface MathJaxTexConfig {
9
- inlineMath?: [string, string][];
10
- displayMath?: [string, string][];
11
- processEscapes?: boolean;
12
- packages?: string[];
13
- macros?: Record<string, string>;
14
- }
15
- interface MathJaxDocument {
16
- assistiveMml?: () => {
17
- updateDocument?: () => unknown;
18
- };
19
- }
20
- interface MathJaxInstance {
21
- version?: string;
22
- tex?: MathJaxTexConfig;
23
- options?: {
24
- enableMenu?: boolean;
25
- enableExplorer?: boolean;
26
- enableAssistiveMml?: boolean;
27
- };
28
- startup: {
29
- ready?: () => void;
30
- defaultReady: () => void;
31
- document?: MathJaxDocument;
32
- };
33
- typesetPromise?: (elements?: Element[]) => Promise<void>;
34
- }
35
- declare global {
36
- interface Window {
37
- MathJax?: MathJaxInstance;
38
- }
39
- }
2
+ /** `latex` without the pair of legacy delimiters around all of it, if it has one. */
3
+ export declare function stripLegacyDelimiters(latex: string): string;
40
4
  /**
41
- * Create a MathJax-based math renderer
5
+ * Create a MathJax renderer function.
42
6
  *
43
- * Loads MathJax v4 from CDN (~2.7MB, cached) and returns a function
44
- * that can render math expressions in DOM elements.
7
+ * MathJax loads once per page, on the first render, from `srcUrl` or MathJax 4.1.3 on jsDelivr.
8
+ * A MathJax the page already has, or is loading, is used instead. A render waits on the load only
9
+ * when its element holds math.
45
10
  *
46
- * @param options - MathJax configuration options
47
- * @returns Math renderer function
48
- *
49
- * @example
50
- * ```typescript
51
- * const renderer = createMathjaxRenderer({
52
- * accessibility: true,
53
- * useSingleDollar: false
54
- * });
55
- *
56
- * renderer(document.body);
57
- * ```
11
+ * @param options - Renderer options
12
+ * @returns Renderer function that typesets math in an element
58
13
  */
59
14
  export declare function createMathjaxRenderer(options?: MathjaxOptions): (element: HTMLElement) => Promise<void>;
60
15
  /**
61
- * Get CSS URLs required by MathJax renderer
62
- *
63
- * @returns Array of CSS URLs needed for MathJax rendering (empty - MathJax handles its own CSS)
16
+ * Get CSS URLs for MathJax
17
+ * MathJax v4 injects its own styles, so no external CSS needed
64
18
  */
65
19
  export declare function getMathjaxCssUrls(): string[];
66
- export {};
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,88 +1,236 @@
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 = Symbol.for("@pie-element/shared-math-rendering-mathjax/loading");
3
- function t(t) {
4
- if (typeof window > "u" || window.MathJax?.typesetPromise) return Promise.resolve();
5
- let n = globalThis, r = n[e];
6
- if (r) return r;
7
- let i = new Promise((e, n) => {
8
- let { useSingleDollar: r = !1, accessibility: i = !0, loadFonts: a = !0, srcUrl: o } = t, s = {
9
- loader: { load: i ? ["a11y/assistive-mml"] : [] },
10
- tex: {
11
- packages: [
12
- "base",
13
- "ams",
14
- "autoload"
15
- ],
16
- macros: {
17
- parallelogram: "\\lower.2em{\\Huge\\unicode{x25B1}}",
18
- overarc: "\\overparen",
19
- napprox: "\\not\\approx",
20
- longdiv: "\\enclose{longdiv}"
26
+ var a = "https://cdn.jsdelivr.net/npm/mathjax@4.1.3/tex-mml-chtml.js", o = {
27
+ parallelogram: "\\lower.2em{\\Huge\\unicode{x25B1}}",
28
+ overarc: "\\overparen",
29
+ napprox: "\\not\\approx",
30
+ longdiv: "\\enclose{longdiv}",
31
+ abs: ["\\left|#1\\right|", 1]
32
+ }, s = "[math-rendering] using $ is not advisable, please use $$..$$ or \\(...\\)", c = /\\\(|\\\[|\$\$|\\\$|\\begin\{|\\(?:eq)?ref\{/, l = /\\\(|\\\[|\$|\\begin\{|\\(?:eq)?ref\{/, u = /\\embed\{newLine\}\[\]/g, d = [
33
+ ["$$", "$$"],
34
+ ["$", "$"],
35
+ ["\\[", "\\]"],
36
+ ["\\(", "\\)"]
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() {
43
+ return window.MathJax;
44
+ }
45
+ function y(e) {
46
+ for (let [t, n] of d) if (e.startsWith(t) && e.endsWith(n)) return e.substring(t.length, e.length - n.length);
47
+ return e;
48
+ }
49
+ function b(e) {
50
+ return y(e.includes("\\displaystyle") ? e.replace("\\displaystyle", "").trim() : e);
51
+ }
52
+ var x = "mathjax_ignore", S = "mathjax_process";
53
+ function C(e, t) {
54
+ let n = e.closest(`.${x}, .${S}`);
55
+ return n !== null && t.contains(n) && !n.classList.contains(S);
56
+ }
57
+ function w(e) {
58
+ for (let t of e.querySelectorAll("[data-latex]")) {
59
+ if (t.dataset.mathHandled || t.closest("mjx-container") || C(t, e)) continue;
60
+ let n = t.textContent;
61
+ n && (t.textContent = `\\(${b(n)}\\)`.replace(u, "\\newline "), t.dataset.mathHandled = "true");
62
+ }
63
+ }
64
+ function T(e, t) {
65
+ for (let t of e.querySelectorAll("math")) if (!t.closest("mjx-assistive-mml")) return !0;
66
+ return (t ? l : c).test(e.textContent ?? "");
67
+ }
68
+ function E(e) {
69
+ return new Promise((t, n) => {
70
+ let { useSingleDollar: r = !1, accessibility: i = !0, loadFonts: c = !0, srcUrl: l } = e, u = {
71
+ loader: {
72
+ load: i ? ["a11y/assistive-mml"] : [],
73
+ failed: (e) => n(e)
74
+ },
75
+ startup: {
76
+ typeset: !1,
77
+ ready: () => {
78
+ let e = v(), r = e?.startup, i = !!e?.version?.startsWith("4.");
79
+ i && D(e), r?.defaultReady?.(), i && O(r?.document), Promise.resolve(r?.promise).then(() => t(), n);
21
80
  }
22
81
  },
82
+ tex: { macros: { ...o } },
23
83
  options: {
24
84
  enableMenu: i,
25
- enableExplorer: i,
26
- enableAssistiveMml: i
27
- },
28
- startup: {
29
- ready: () => {
30
- window.MathJax?.startup.defaultReady && (window.MathJax.startup.defaultReady(), e());
31
- },
32
- defaultReady: () => {}
85
+ menuOptions: { settings: {
86
+ assistiveMml: i,
87
+ enrich: !1,
88
+ inTabOrder: !1
89
+ } }
33
90
  }
34
91
  };
35
- r && s.tex && (s.tex.inlineMath = [["$", "$"], ["\\(", "\\)"]], s.tex.processEscapes = !0), a || (s.chtml = { fontURL: "" }), window.MathJax = s;
36
- let c = document.createElement("script");
37
- c.src = o || "https://cdn.jsdelivr.net/npm/mathjax@4/tex-chtml.js", c.async = !0, c.onload = () => {
38
- setTimeout(e, 100);
39
- }, c.onerror = () => {
40
- n(/* @__PURE__ */ Error("Failed to load MathJax"));
41
- }, document.head.appendChild(c);
92
+ r && u.tex && (console.warn(s), u.tex.inlineMath = [["$", "$"], ["\\(", "\\)"]], u.tex.processEscapes = !0), c || (u.chtml = { fontURL: "" }), window.MathJax = u;
93
+ let d = document.createElement("script");
94
+ d.src = l || a, d.async = !0, d.onerror = () => n(/* @__PURE__ */ Error("Failed to load MathJax")), document.head.appendChild(d);
42
95
  });
43
- return n[e] = i, i;
44
- }
45
- function n() {
46
- let e = window.MathJax?.startup?.document;
47
- if (typeof e?.assistiveMml == "function") try {
48
- e.assistiveMml().updateDocument?.();
49
- } catch (e) {
50
- console.warn("[mathjax-renderer] Failed to attach assistive MathML:", e);
96
+ }
97
+ function D(e) {
98
+ let t = e?._?.output?.chtml_ts?.CHTML;
99
+ t && (t.STYLESHEETID = p);
100
+ }
101
+ function O(e) {
102
+ if (!e) return;
103
+ let t = /* @__PURE__ */ new WeakSet(), n = (e) => {
104
+ let n = e.typesetRoot;
105
+ !n || t.has(n) || (_(n), t.add(n));
106
+ };
107
+ e.addRenderAction?.("pie-strip-latex", g, (e) => {
108
+ for (let t of e.math ?? []) n(t);
109
+ return !1;
110
+ }, (e) => {
111
+ let t = e.typesetRoot;
112
+ return t && _(t), !1;
113
+ });
114
+ let r = e.outputJax?.chtmlStyles;
115
+ r?.id === m && (r.id = p), j();
116
+ }
117
+ function k(e) {
118
+ return e instanceof HTMLStyleElement && h.includes(e.id);
119
+ }
120
+ function A(e) {
121
+ r("foreign-output-stylesheet", `another MathJax added <style id="${e.id}"> to <head>`);
122
+ }
123
+ function j() {
124
+ let e = document.head, t = [...e.children].find(k);
125
+ if (t) {
126
+ A(t);
127
+ return;
51
128
  }
129
+ let n = new MutationObserver((e) => {
130
+ for (let t of e) {
131
+ let e = [...t.addedNodes].find(k);
132
+ if (e) {
133
+ A(e), n.disconnect();
134
+ return;
135
+ }
136
+ }
137
+ });
138
+ n.observe(e, { childList: !0 });
139
+ }
140
+ function M(e) {
141
+ return new Promise((t, n) => {
142
+ let r = e.startup ?? {};
143
+ e.startup = r;
144
+ let i = r.ready;
145
+ r.ready = () => {
146
+ let e = v()?.startup;
147
+ i ? i.call(r) : e?.defaultReady?.(), Promise.resolve(e?.promise).then(() => t(), n);
148
+ };
149
+ });
150
+ }
151
+ function N(e) {
152
+ let t = v();
153
+ return t ? t.version ? t.startup?.promise ? Promise.resolve(t.startup.promise).then(() => void 0) : Promise.resolve() : M(t) : E(e);
52
154
  }
53
- function r(e = {}) {
54
- return async (r) => {
55
- if (await t(e), !window.MathJax?.typesetPromise) {
56
- console.warn("[mathjax-renderer] MathJax not loaded or missing typesetPromise.");
155
+ function P(e) {
156
+ return N(e).then(() => {
157
+ typeof v()?.typesetPromise != "function" && console.warn("[mathjax-renderer] MathJax on this page has no typesetPromise; math stays untypeset.");
158
+ });
159
+ }
160
+ function F(e) {
161
+ let t = globalThis, n = t[f];
162
+ return n || (n = P(e), t[f] = n), n;
163
+ }
164
+ function I(e = {}) {
165
+ let t = e.useSingleDollar ?? !1;
166
+ return async (n) => {
167
+ if (typeof window > "u") return;
168
+ let a = i();
169
+ a && r("mathjax-3-global", `window.MathJax is MathJax ${a}`), w(n);
170
+ let o = F(e);
171
+ if (!T(n, t)) {
172
+ o.catch(() => {});
57
173
  return;
58
174
  }
59
- await window.MathJax.typesetPromise([r]), n();
175
+ await o;
176
+ let s = v();
177
+ await s?.startup?.promise, typeof s?.typesetPromise == "function" && (await s.typesetPromise([n]), _(n));
60
178
  };
61
179
  }
62
- function i() {
180
+ function L() {
63
181
  return [];
64
182
  }
65
183
  //#endregion
66
184
  //#region src/render-math.ts
67
- var a = "@pie-lib/math-rendering", o = null;
68
- function s() {
69
- return o ||= r({
70
- accessibility: !0,
71
- useSingleDollar: !0
72
- }), o;
73
- }
74
- function c() {
185
+ var R = "@pie-lib/math-rendering", z = "@pie-lib/math-rendering@2", B = "pie-print", V = 50, H = 1e4, U = null;
186
+ function W() {
187
+ return !!window[z]?.opts?.useSingleDollar;
188
+ }
189
+ function G() {
190
+ return U ||= I({ useSingleDollar: W() }), U;
191
+ }
192
+ function K() {
75
193
  if (typeof window > "u") return null;
76
- let e = window[a];
77
- return typeof e?.renderMath == "function" ? e : null;
194
+ let e = window[R];
195
+ return typeof e?.renderMath == "function" && e.renderMath !== X ? e : null;
196
+ }
197
+ function q(e) {
198
+ let t = e;
199
+ for (; t;) {
200
+ if (t instanceof Element && t.localName === B) return t;
201
+ t = t instanceof ShadowRoot ? t.host : t.parentNode;
202
+ }
203
+ return null;
204
+ }
205
+ function J() {
206
+ let e = window.renderMath;
207
+ return typeof e == "function" ? e : null;
208
+ }
209
+ async function Y(e) {
210
+ let t = q(e);
211
+ if (!t) return null;
212
+ let n = J();
213
+ if (n || t.mathRenderingModuleUrlImported !== !0) return n;
214
+ let r = Date.now() + H;
215
+ for (; Date.now() < r;) {
216
+ await new Promise((e) => setTimeout(e, V));
217
+ let e = J();
218
+ if (e) return e;
219
+ }
220
+ return null;
78
221
  }
79
- var l = async (e) => {
222
+ var X = async (e) => {
80
223
  if (typeof window > "u") return;
81
224
  let t = typeof e == "string", n;
82
225
  t ? (n = document.createElement("div"), n.innerHTML = e) : n = e || document.body;
83
- let r = c();
84
- return r ? await r.renderMath?.(n) : await s()(n), t ? n.innerHTML : void 0;
85
- }, u = (e) => c()?.wrapMath?.(e) ?? e, d = (e) => {
226
+ let r = K(), i = r || t ? null : await Y(n);
227
+ return r ? await r.renderMath?.(n) : i && i !== X ? await i(n) : await G()(n), t ? n.innerHTML : void 0;
228
+ }, Z = (e, t) => {
229
+ let n = K()?.wrapMath?.(e, t);
230
+ if (n != null) return n;
231
+ let [r, i] = t === "dollar" || t === "double_dollar" ? ["$", "$"] : ["\\(", "\\)"];
232
+ return `${r}${y(e)}${i}`;
233
+ }, Q = (e) => {
86
234
  let t = e.trim();
87
235
  return t.startsWith("\\[") && t.endsWith("\\]") ? {
88
236
  unwrapped: t.slice(2, -2).trim(),
@@ -109,6 +257,6 @@ var l = async (e) => {
109
257
  close: "$"
110
258
  }
111
259
  } : { unwrapped: t };
112
- }, f = (e) => c()?.mmlToLatex?.(e) ?? e;
260
+ }, $ = (e) => K()?.mmlToLatex?.(e) ?? e;
113
261
  //#endregion
114
- export { r as createMathjaxRenderer, i as getMathjaxCssUrls, f as mmlToLatex, l as renderMath, d as unWrapMath, u as wrapMath };
262
+ export { t as MATHJAX_CONFLICT_EVENT, e as UNSUPPORTED_PAGE_DOCS_URL, I as createMathjaxRenderer, L as getMathjaxCssUrls, $ as mmlToLatex, X as renderMath, Q as unWrapMath, Z as wrapMath };
@@ -9,9 +9,14 @@
9
9
  */
10
10
  export declare const renderMath: (el?: Element | string) => Promise<string | undefined>;
11
11
  /**
12
- * Wrap LaTeX - MathJax handles delimiters, so just pass through
12
+ * Wraps LaTeX in inline delimiters, through the page renderer's `wrapMath` when it has one. The
13
+ * fallback wraps as `@pie-lib/math-rendering` does, `$…$` for its `dollar` and `double_dollar`
14
+ * wrap types and `\(…\)` for any other, so a math node saves the same markup whichever renderer
15
+ * the authoring page installed. LaTeX that already has delimiters keeps one pair, where the legacy
16
+ * function adds a second: a math span saved without `data-raw` reaches the editor with its
17
+ * delimiters.
13
18
  */
14
- export declare const wrapMath: (latex: string) => string;
19
+ export declare const wrapMath: (latex: string, wrapType?: string | null) => string;
15
20
  /**
16
21
  * Unwrap LaTeX delimiters - minimal implementation for editable-html-tip-tap
17
22
  */
package/dist/types.d.ts CHANGED
@@ -3,12 +3,13 @@
3
3
  */
4
4
  export interface MathjaxOptions {
5
5
  /**
6
- * Use single dollar signs as delimiters
6
+ * Treat `$...$` as inline math. The renderer behind `renderMath` enables it when the page sets
7
+ * the legacy opt-in, `window['@pie-lib/math-rendering@2'] = { opts: { useSingleDollar: true } }`.
7
8
  * @default false
8
9
  */
9
10
  useSingleDollar?: boolean;
10
11
  /**
11
- * Enable accessibility features (speech, aria-labels)
12
+ * Add hidden MathML for screen readers and the MathJax context menu
12
13
  * @default true
13
14
  */
14
15
  accessibility?: boolean;
@@ -18,7 +19,7 @@ export interface MathjaxOptions {
18
19
  */
19
20
  loadFonts?: boolean;
20
21
  /**
21
- * Override the MathJax script URL.
22
+ * Override the MathJax script URL. Defaults to MathJax 4.1.3 `tex-mml-chtml.js` on jsDelivr.
22
23
  */
23
24
  srcUrl?: string;
24
25
  }
@@ -28,7 +29,7 @@ export interface MathjaxOptions {
28
29
  export type MathRenderer = (element: HTMLElement) => void | Promise<void>;
29
30
  export interface MathRenderingAPI {
30
31
  renderMath: MathRenderer;
31
- wrapMath?: (latex: string) => string;
32
+ wrapMath?: (latex: string, wrapType?: string | null) => string;
32
33
  unWrapMath?: (wrapped: string) => string;
33
34
  mmlToLatex?: (mathml: string) => string;
34
35
  }
@@ -0,0 +1,28 @@
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
+ export interface MathjaxConflictDetail {
18
+ condition: MathjaxConflictCondition;
19
+ message: string;
20
+ docsUrl: string;
21
+ }
22
+ /**
23
+ * Logs one `console.error` per page, for the first condition seen, and dispatches
24
+ * {@link MATHJAX_CONFLICT_EVENT} once for each condition.
25
+ */
26
+ export declare function reportUnsupportedPage(condition: MathjaxConflictCondition, detail: string): void;
27
+ /** The version of `window.MathJax` when it is a MathJax 3 build. */
28
+ 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.2",
3
+ "version": "0.1.1-next.20261002100925",
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": {},