@motionscript/math 0.1.0-alpha.8 → 0.1.0

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.
Files changed (158) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/LICENSE +201 -201
  3. package/NOTICE +49 -49
  4. package/README.md +390 -391
  5. package/dist/annotate/angle-mark.js.map +1 -1
  6. package/dist/annotate/curly-brace.js.map +1 -1
  7. package/dist/annotate/emphasis-mark.js.map +1 -1
  8. package/dist/browser/chunks/{chunk-FETQZEN2.js → chunk-IRZCG6PM.js} +2 -2
  9. package/dist/browser/chunks/chunk-IRZCG6PM.js.map +7 -0
  10. package/dist/browser/chunks/{chunk-K77KLQX4.js → chunk-WMVW6ZIV.js} +2 -2
  11. package/dist/browser/chunks/chunk-WMVW6ZIV.js.map +7 -0
  12. package/dist/browser/chunks/{mathjax-DNP3YRES.js → mathjax-WV55AC2P.js} +1 -1
  13. package/dist/browser/chunks/{mathjax-DNP3YRES.js.map → mathjax-WV55AC2P.js.map} +1 -1
  14. package/dist/browser/index.js +1 -1
  15. package/dist/browser/index.js.map +1 -1
  16. package/dist/browser/kit.js +1 -1
  17. package/dist/browser/manifest.json +1 -1
  18. package/dist/browser/tex.js +1 -1
  19. package/dist/browser/tex.js.map +1 -1
  20. package/dist/engine.d.ts +1 -1
  21. package/dist/engine.js +1 -1
  22. package/dist/engine.js.map +1 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/kit/brace.js.map +1 -1
  25. package/dist/kit/cache.js.map +1 -1
  26. package/dist/kit/component.d.ts.map +1 -1
  27. package/dist/kit/component.js.map +1 -1
  28. package/dist/kit/contour.js.map +1 -1
  29. package/dist/kit/coords.js.map +1 -1
  30. package/dist/kit/curve.js.map +1 -1
  31. package/dist/kit/equation.js.map +1 -1
  32. package/dist/kit/equation3d.js.map +1 -1
  33. package/dist/kit/expression.js.map +1 -1
  34. package/dist/kit/field-mark.d.ts.map +1 -1
  35. package/dist/kit/field-mark.js.map +1 -1
  36. package/dist/kit/field.js.map +1 -1
  37. package/dist/kit/follow.d.ts.map +1 -1
  38. package/dist/kit/follow.js.map +1 -1
  39. package/dist/kit/furniture.js.map +1 -1
  40. package/dist/kit/geometry.js.map +1 -1
  41. package/dist/kit/graph.js.map +1 -1
  42. package/dist/kit/mark.js.map +1 -1
  43. package/dist/kit/part-fills.js.map +1 -1
  44. package/dist/kit/place.js.map +1 -1
  45. package/dist/kit/sampler.js.map +1 -1
  46. package/dist/kit/scale.js.map +1 -1
  47. package/dist/kit/source.js.map +1 -1
  48. package/dist/kit/system.js.map +1 -1
  49. package/dist/kit/ticks.js.map +1 -1
  50. package/dist/kit/withdrawn.js.map +1 -1
  51. package/dist/marks/curve-area.js.map +1 -1
  52. package/dist/marks/drop-lines.js.map +1 -1
  53. package/dist/marks/plot-point.js.map +1 -1
  54. package/dist/marks/riemann-sum.js.map +1 -1
  55. package/dist/marks/tangent-line.js.map +1 -1
  56. package/dist/marks/vector-arrow.js.map +1 -1
  57. package/dist/nodes.js.map +1 -1
  58. package/dist/plots/function-plot.d.ts.map +1 -1
  59. package/dist/plots/function-plot.js.map +1 -1
  60. package/dist/plots/points-plot.js.map +1 -1
  61. package/dist/plots/stream-lines.js.map +1 -1
  62. package/dist/plots/traced-path.js.map +1 -1
  63. package/dist/plots/vector-field.js.map +1 -1
  64. package/dist/structures/graph-layout.js.map +1 -1
  65. package/dist/structures/network-graph.js.map +1 -1
  66. package/dist/structures/sample-space.js.map +1 -1
  67. package/dist/systems/axes2d.d.ts.map +1 -1
  68. package/dist/systems/axes2d.js.map +1 -1
  69. package/dist/systems/number-line.js.map +1 -1
  70. package/dist/systems/number-plane.js.map +1 -1
  71. package/dist/systems/polar-plane.js.map +1 -1
  72. package/dist/tex/geometry.js.map +1 -1
  73. package/dist/tex/index.js.map +1 -1
  74. package/dist/tex/mathjax.js.map +1 -1
  75. package/dist/tex/matrix.js.map +1 -1
  76. package/dist/tex/node.js.map +1 -1
  77. package/dist/tex/tween.js.map +1 -1
  78. package/dist/tex/typeset.d.ts.map +1 -1
  79. package/dist/tex/typeset.js.map +1 -1
  80. package/dist/three/axes3d.js.map +1 -1
  81. package/dist/three/curve-plot3d.js.map +1 -1
  82. package/dist/three/entries.js.map +1 -1
  83. package/dist/three/label3d.js.map +1 -1
  84. package/dist/three/plot-point3d.js.map +1 -1
  85. package/dist/three/space.js.map +1 -1
  86. package/dist/three/surface-plot3d.js.map +1 -1
  87. package/dist/three/vector-arrow3d.js.map +1 -1
  88. package/package.json +4 -4
  89. package/registry.json +251 -251
  90. package/src/annotate/angle-mark.ts +137 -137
  91. package/src/annotate/curly-brace.ts +148 -148
  92. package/src/annotate/emphasis-mark.ts +118 -118
  93. package/src/engine.ts +86 -86
  94. package/src/index.ts +29 -29
  95. package/src/kit/brace.ts +37 -37
  96. package/src/kit/cache.ts +61 -61
  97. package/src/kit/component.ts +57 -57
  98. package/src/kit/contour.ts +94 -94
  99. package/src/kit/coords.ts +278 -278
  100. package/src/kit/curve.ts +47 -47
  101. package/src/kit/equation.ts +181 -181
  102. package/src/kit/equation3d.ts +137 -137
  103. package/src/kit/expression.ts +159 -159
  104. package/src/kit/field-mark.ts +171 -171
  105. package/src/kit/field.ts +50 -50
  106. package/src/kit/follow.ts +229 -229
  107. package/src/kit/furniture.ts +113 -113
  108. package/src/kit/geometry.ts +49 -49
  109. package/src/kit/graph.ts +116 -116
  110. package/src/kit/mark.ts +152 -152
  111. package/src/kit/part-fills.ts +61 -61
  112. package/src/kit/place.ts +77 -77
  113. package/src/kit/sampler.ts +281 -281
  114. package/src/kit/scale.ts +39 -39
  115. package/src/kit/source.ts +57 -57
  116. package/src/kit/system.ts +105 -105
  117. package/src/kit/ticks.ts +85 -85
  118. package/src/kit/withdrawn.ts +8 -8
  119. package/src/marks/curve-area.ts +89 -89
  120. package/src/marks/drop-lines.ts +71 -71
  121. package/src/marks/plot-point.ts +102 -102
  122. package/src/marks/riemann-sum.ts +99 -99
  123. package/src/marks/tangent-line.ts +119 -119
  124. package/src/marks/vector-arrow.ts +98 -98
  125. package/src/nodes.ts +99 -99
  126. package/src/plots/function-plot.ts +220 -220
  127. package/src/plots/points-plot.ts +103 -103
  128. package/src/plots/stream-lines.ts +160 -160
  129. package/src/plots/traced-path.ts +70 -70
  130. package/src/plots/vector-field.ts +107 -107
  131. package/src/structures/graph-layout.ts +145 -145
  132. package/src/structures/network-graph.ts +291 -291
  133. package/src/structures/sample-space.ts +210 -210
  134. package/src/systems/axes2d.ts +226 -226
  135. package/src/systems/number-line.ts +130 -130
  136. package/src/systems/number-plane.ts +232 -232
  137. package/src/systems/polar-plane.ts +177 -177
  138. package/src/tex/geometry.ts +703 -703
  139. package/src/tex/index.ts +15 -15
  140. package/src/tex/mathjax.ts +82 -82
  141. package/src/tex/matrix.ts +97 -97
  142. package/src/tex/node.ts +74 -74
  143. package/src/tex/tween.ts +308 -308
  144. package/src/tex/typeset.ts +461 -461
  145. package/src/three/axes3d.ts +267 -267
  146. package/src/three/curve-plot3d.ts +146 -146
  147. package/src/three/entries.ts +42 -42
  148. package/src/three/label3d.ts +52 -52
  149. package/src/three/plot-point3d.ts +63 -63
  150. package/src/three/space.ts +92 -92
  151. package/src/three/surface-plot3d.ts +318 -318
  152. package/src/three/vector-arrow3d.ts +88 -88
  153. package/dist/browser/chunks/chunk-FETQZEN2.js.map +0 -7
  154. package/dist/browser/chunks/chunk-K77KLQX4.js.map +0 -7
  155. package/dist/kit/placement.d.ts +0 -8
  156. package/dist/kit/placement.d.ts.map +0 -1
  157. package/dist/kit/placement.js +0 -8
  158. package/dist/kit/placement.js.map +0 -1
@@ -1,703 +1,703 @@
1
-
2
- import { PathCommand } from '@motionscript/sdk';
3
-
4
- import { createBoundedCache } from '../kit/cache';
5
-
6
- // --- MathJax, on demand ---
7
-
8
- type MathJaxRuntime = typeof import('./mathjax');
9
-
10
- let runtime: MathJaxRuntime | null = null;
11
- let loading: Promise<void> | null = null;
12
- // MathJax's DOM, a real one or its own DOM-free tree: read only through its accessors, so its element type is opaque here.
13
- let adaptor: any = null;
14
-
15
- /**
16
- * The asset key a node that typesets declares its loader under: the host waits
17
- * for it before laying the node out, and a scene with no formula never loads it.
18
- */
19
- export const MATHJAX_LOADER = 'math:mathjax';
20
-
21
- /** Load MathJax, once. A host that typesets outside a scene (a tool, a test) awaits this first. */
22
- export function loadMathJax(): Promise<void> {
23
- loading ??= import('./mathjax').then((module) => {
24
- runtime = module;
25
- adaptor = module.adaptor;
26
- });
27
- return loading;
28
- }
29
-
30
- /** Whether MathJax has loaded, so a formula can be typeset now. */
31
- export function mathJaxLoaded(): boolean {
32
- return runtime !== null;
33
- }
34
-
35
- /** What a formula is before MathJax has loaded: nothing to draw, and nothing cached. */
36
- export function blankLatex(): LatexPathResult {
37
- return { tokens: [], parts: [], commands: [], width: 0, height: 0, bounds: [0, 0, 0, 0] };
38
- }
39
-
40
- /** MathJax is not loaded yet: what typesetting throws before {@link loadMathJax} has resolved. */
41
- export class LatexNotLoaded extends Error {
42
- constructor() {
43
- super('MathJax is not loaded: declare the math:mathjax loader, or await loadMathJax(), before typesetting.');
44
- this.name = 'LatexNotLoaded';
45
- }
46
- }
47
-
48
- // --- Public API ---
49
-
50
- /**
51
- * A formula MathJax could not typeset.
52
- *
53
- * MathJax does not throw on malformed TeX. It typesets an error box in place of
54
- * the formula and tags it `data-mjx-error`, so the failure arrives as a drawing:
55
- * nothing at all from the browser adaptor and a filled bar from the DOM-free
56
- * one, which left a host able to tell a bad formula from a blank one only by the
57
- * token count. {@link buildLatexPath} raises this instead, the same way under
58
- * both adaptors. `\require` is an error too, since only the packages named above
59
- * are loaded.
60
- */
61
- export class LatexError extends Error {
62
- /** The formula that failed, as it was given. */
63
- readonly latex: string;
64
- /** MathJax's own description of what is wrong with it. */
65
- readonly reason: string;
66
-
67
- constructor(latex: string, reason: string) {
68
- super(`Cannot typeset "${latex}": ${reason}`);
69
- this.name = 'LatexError';
70
- this.latex = latex;
71
- this.reason = reason;
72
- }
73
- }
74
-
75
- /** A single rendered glyph or shape with its character key and path commands. */
76
- export interface LatexToken {
77
- /** Character this token represents, or a synthetic key for non-glyph shapes. */
78
- token: string;
79
- path: PathCommand[];
80
- /** The source of the top-level term the token belongs to, `a^2` in `a^2 + b^2`; empty for none. */
81
- term?: string;
82
- }
83
-
84
- /**
85
- * A piece of a formula as its source wrote it: `x^2`, `\frac{d}{dx}`, a lone
86
- * `+`. Every group the typesetter makes is one, so parts nest.
87
- */
88
- export interface LatexPart {
89
- /** The part's own source. */
90
- latex: string;
91
- /** The tokens it draws, as a span of the formula's token list: `from` up to, not including, `to`. */
92
- from: number;
93
- to: number;
94
- /** The index of the part it sits in, or -1 at the top. */
95
- parent: number;
96
- }
97
-
98
- export interface LatexPathResult {
99
- /** All tokens in render order. */
100
- tokens: LatexToken[];
101
- /** Every part of the formula, outermost first, in source order. */
102
- parts: LatexPart[];
103
- /** Flat array of all path commands (for legacy single-path rendering). */
104
- commands: PathCommand[];
105
- width: number;
106
- height: number;
107
- /**
108
- * Bounding box over every token, in token coordinate space:
109
- * [minX, minY, maxX, maxY]. All tokens share this frame, so passing it as
110
- * each path's center frame keeps their relative layout (instead of each
111
- * glyph centering on its own bbox).
112
- */
113
- bounds: [number, number, number, number];
114
- }
115
-
116
- /**
117
- * A formula's glyph geometry, before a type size is applied to it.
118
- *
119
- * The dividing line this whole module's caching turns on. Getting here is the
120
- * expensive part — MathJax lays the formula out, then the SVG it produces is
121
- * parsed, its glyph dictionary resolved and every `<use>` walked through its
122
- * transform stack — and **none of it depends on `fontSize`**: `mjDoc.convert`
123
- * is called at a fixed em/ex, and the size arrives at the very end as one
124
- * uniform scale (see {@link scaleLatexGeometry}).
125
- *
126
- * So this is what gets remembered per formula, and the size is applied to it
127
- * afresh. A formula animating from 24pt to 120pt is one trip through MathJax
128
- * and one DOM parse, not one per frame.
129
- */
130
- interface LatexGeometry {
131
- tokens: RawToken[];
132
- parts: LatexPart[];
133
- /** Box over every command, in the SVG's own coordinates. */
134
- box: { minX: number; minY: number; maxX: number; maxY: number };
135
- /** The formula's height in `ex`, as MathJax reported it. */
136
- heightEx: number;
137
- }
138
-
139
- /**
140
- * Formulas already worked out, and formulas already sized.
141
- *
142
- * `buildLatexPath` is a pure function of `(text, fontSize)` and used to have no
143
- * memory, which made every caller pay full price for a question it had already
144
- * asked. The callers are not occasional about it either: constructing a `Latex`
145
- * resolves its formula, and so does every `to({ latex })` the moment it starts,
146
- * so a scene re-resolves every formula in it whenever it is rebuilt *and*
147
- * whenever the playhead moves backwards, since a backward seek replays the
148
- * scene's generator from its first frame. An editor that rebuilds on a keystroke
149
- * and seeks on a click asks for the same handful of formulas hundreds of times.
150
- *
151
- * Two memos, each keyed by what its stage actually depends on, and deliberately
152
- * different sizes:
153
- *
154
- * - {@link geometryCache} is everything up to the type size, keyed by the text
155
- * alone. This is the expensive one, and it is generously sized because
156
- * nothing a scene does can churn it: a deck holds as many distinct formulas
157
- * as it holds, and it holds them for as long as it is open.
158
- * - {@link pathCache} is the finished result, keyed by text *and* size. Small
159
- * on purpose: an animated `fontSize` inserts a distinct key every frame, and
160
- * the right thing for a stream like that is to churn a little memo rather
161
- * than a big one. What a miss costs here is arithmetic over glyphs already
162
- * worked out — no MathJax, no parse.
163
- */
164
- const geometryCache = createBoundedCache<LatexGeometry>(128);
165
- const pathCache = createBoundedCache<LatexPathResult>(64);
166
-
167
- export function buildLatexPath(text: string, fontSize: number): LatexPathResult {
168
- // NUL rather than a punctuation separator, so no formula can spell a key
169
- // belonging to another size.
170
- const key = `${fontSize}\0${text}`;
171
-
172
- const hit = pathCache.get(key);
173
- if (hit) return lend(hit);
174
-
175
- let geometry = geometryCache.get(text);
176
- if (!geometry) {
177
- geometry = buildLatexGeometry(text);
178
- geometryCache.set(text, geometry);
179
- }
180
-
181
- const result = scaleLatexGeometry(geometry, fontSize);
182
- pathCache.set(key, result);
183
- return lend(result);
184
- }
185
-
186
- /** Typeset `text` and reduce the SVG MathJax returns to glyph geometry. */
187
- function buildLatexGeometry(text: string): LatexGeometry {
188
- if (!runtime) throw new LatexNotLoaded();
189
- const svgEl = adaptor.firstChild(runtime.convert(text));
190
- const failure = mathJaxError(svgEl);
191
- if (failure !== null) throw new LatexError(text, failure);
192
-
193
- const heightAttr = adaptor.getAttribute(svgEl, 'height') ?? '';
194
-
195
- return parseLatexSvg(svgEl, parseFloat(heightAttr) || 0);
196
- }
197
-
198
- /**
199
- * MathJax's description of the error box in a typeset formula, or `null` when
200
- * there is none. Read through the adaptor, so a real DOM and the DOM-free tree
201
- * give the same answer.
202
- */
203
- function mathJaxError(svgEl: unknown): string | null {
204
- for (const el of adaptor.tags(svgEl, 'g') as unknown[]) {
205
- const reason = adaptor.getAttribute(el, 'data-mjx-error');
206
- if (reason !== null && reason !== undefined) return String(reason) || 'unknown error';
207
- }
208
- return null;
209
- }
210
-
211
- /**
212
- * A cached result, handed out safely.
213
- *
214
- * `tokens`, `commands` and the path arrays inside them are shared: they are read
215
- * by everything downstream and written by none of it — `Latex` maps tokens into
216
- * its own wrappers, and the morph builds new paths rather than editing the ones
217
- * it is given — so copying them would be copying the whole formula for nothing.
218
- *
219
- * `bounds` is copied, because it is the one field a caller *stores*: `Latex`
220
- * assigns `result.bounds` straight to `this._bounds` and hands it to the
221
- * renderer as a shared centring frame. That was one node holding its own array
222
- * before there was a memo, and would be two nodes drawing the same formula
223
- * holding one array between them after — four numbers is not a price worth
224
- * paying to find out whether anything downstream ever writes to it.
225
- */
226
- function lend(result: LatexPathResult): LatexPathResult {
227
- const [minX, minY, maxX, maxY] = result.bounds;
228
- return { ...result, bounds: [minX, minY, maxX, maxY] };
229
- }
230
-
231
- // --- High-Speed Matrix Math ---
232
-
233
- type Matrix = [number, number, number, number, number, number]; // [a, b, c, d, tx, ty]
234
- const identityMatrix: Matrix = [1, 0, 0, 1, 0, 0];
235
-
236
- function multiplyMatrix(m1: Matrix, m2: Matrix): Matrix {
237
- return [
238
- m1[0] * m2[0] + m1[2] * m2[1],
239
- m1[1] * m2[0] + m1[3] * m2[1],
240
- m1[0] * m2[2] + m1[2] * m2[3],
241
- m1[1] * m2[2] + m1[3] * m2[3],
242
- m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
243
- m1[1] * m2[4] + m1[3] * m2[5] + m1[5],
244
- ];
245
- }
246
-
247
- function parseTransform(str: string | null): Matrix {
248
- if (!str) return identityMatrix;
249
- let m: Matrix = [...identityMatrix];
250
- const re = /([a-z]+)\(([^)]+)\)/g;
251
- let match;
252
- while ((match = re.exec(str)) !== null) {
253
- const type = match[1];
254
- const args = match[2].split(/[ ,]+/).map(parseFloat);
255
- if (type === 'translate') {
256
- m = multiplyMatrix(m, [1, 0, 0, 1, args[0] || 0, args[1] || 0]);
257
- } else if (type === 'scale') {
258
- const sx = args[0] || 1;
259
- const sy = args[1] !== undefined ? args[1] : sx;
260
- m = multiplyMatrix(m, [sx, 0, 0, sy, 0, 0]);
261
- } else if (type === 'matrix') {
262
- m = multiplyMatrix(m, [args[0], args[1], args[2], args[3], args[4], args[5]]);
263
- }
264
- }
265
- return m;
266
- }
267
-
268
- function applyMatrix(x: number, y: number, m: Matrix): [number, number] {
269
- return [
270
- x * m[0] + y * m[2] + m[4],
271
- x * m[1] + y * m[3] + m[5],
272
- ];
273
- }
274
-
275
- // --- Glyph ID → character decoding ---
276
-
277
- /**
278
- * MathJax SVG glyph IDs look like "MJX-1-TEX-N-78" or "MJX-1-TEX-I-1D465".
279
- * The last segment is the Unicode codepoint in hex.
280
- */
281
- function glyphIdToChar(id: string): string {
282
- const parts = id.split('-');
283
- const hex = parts[parts.length - 1];
284
- const cp = parseInt(hex, 16);
285
- if (!isNaN(cp)) {
286
- try { return String.fromCodePoint(cp); } catch { /* fall through */ }
287
- }
288
- return id;
289
- }
290
-
291
- // --- Core Fast Traversal Engine ---
292
-
293
- type RawToken = { token: string; cmds: Array<{ cmd: string; args: number[] }>; term?: string };
294
-
295
- /** The tag name of a node's parent, or "" at the root. */
296
- function parentKind(node: unknown): string {
297
- const parent = adaptor.parent(node);
298
- return parent ? String(adaptor.kind(parent)).toLowerCase() : "";
299
- }
300
-
301
- /**
302
- * The size-independent half: MathJax's own SVG tree in, glyph geometry out.
303
- *
304
- * Walked through the **adaptor** rather than a `DOMParser`. MathJax already
305
- * builds this tree, and the adaptor is its own abstraction over "a real DOM" and
306
- * "the DOM-free `LiteElement` tree" — the two this module already picks between
307
- * at load. Serialising it to a string and parsing it back needed a `DOMParser`,
308
- * which Node does not have, so every LaTeX node threw `DOMParser is not defined`
309
- * and could not render headlessly at all: no export, and nothing the visual
310
- * suite could check.
311
- *
312
- * Reading the tree directly is also one representation instead of three (tree →
313
- * string → tree), so a browser and a headless host cannot disagree about how the
314
- * markup re-parsed.
315
- */
316
- function parseLatexSvg(svgEl: unknown, heightEx: number): LatexGeometry {
317
- // Pre-parse the glyph dictionary. `tags` reaches every <path> in the tree,
318
- // including the ones inside <defs> that the `use` elements reference.
319
- const glyphMap = new Map<string, Array<{ cmd: string; args: number[] }>>();
320
- for (const el of adaptor.tags(svgEl, 'path') as unknown[]) {
321
- const id = adaptor.getAttribute(el, 'id');
322
- const d = adaptor.getAttribute(el, 'd');
323
- if (id && d) {
324
- glyphMap.set(`#${id}`, expandToAbsolute(tokenisePath(d)));
325
- }
326
- }
327
-
328
- // Collect raw tokens — each <use> is one token, rects/paths are grouped as synthetic tokens
329
- const rawTokens: RawToken[] = [];
330
- const parts: LatexPart[] = [];
331
- let synthIdx = 0;
332
-
333
- function pushCmds(token: string, cmds: Array<{ cmd: string; args: number[] }>) {
334
- rawTokens.push({ token, cmds });
335
- }
336
-
337
- function traverse(node: unknown, currentMatrix: Matrix, within: number) {
338
- let nodeMatrix = currentMatrix;
339
-
340
- const transformStr = adaptor.getAttribute(node, "transform");
341
- if (transformStr) {
342
- nodeMatrix = multiplyMatrix(nodeMatrix, parseTransform(transformStr));
343
- }
344
-
345
- const nodeName = String(adaptor.kind(node)).toLowerCase();
346
-
347
- // MathJax tags each group with the source it typeset; the root's is the whole formula.
348
- let part = within;
349
- const source = nodeName === "g" ? adaptor.getAttribute(node, "data-latex") : null;
350
- if (source && adaptor.getAttribute(node, "data-mml-node") !== "math") {
351
- part = parts.length;
352
- parts.push({ latex: String(source), from: rawTokens.length, to: rawTokens.length, parent: within });
353
- }
354
-
355
- if (nodeName === "use") {
356
- const href = adaptor.getAttribute(node, "href") || adaptor.getAttribute(node, "xlink:href");
357
- const x = parseFloat(adaptor.getAttribute(node, "x") || "0");
358
- const y = parseFloat(adaptor.getAttribute(node, "y") || "0");
359
-
360
- if (href && glyphMap.has(href)) {
361
- const glyphCommands = glyphMap.get(href)!;
362
- const cmds: Array<{ cmd: string; args: number[] }> = [];
363
- for (const gc of glyphCommands) {
364
- const shiftedArgs = [...gc.args];
365
- for (let j = 0; j < shiftedArgs.length; j += 2) {
366
- const [nx, ny] = applyMatrix(shiftedArgs[j] + x, shiftedArgs[j + 1] + y, nodeMatrix);
367
- shiftedArgs[j] = nx;
368
- shiftedArgs[j + 1] = ny;
369
- }
370
- cmds.push({ cmd: gc.cmd, args: shiftedArgs });
371
- }
372
- // Derive character from glyph ID
373
- const rawId = href.startsWith('#') ? href.slice(1) : href;
374
- pushCmds(glyphIdToChar(rawId), cmds);
375
- }
376
- } else if (nodeName === "rect") {
377
- const x = parseFloat(adaptor.getAttribute(node, "x") || "0");
378
- const y = parseFloat(adaptor.getAttribute(node, "y") || "0");
379
- const w = parseFloat(adaptor.getAttribute(node, "width") || "0");
380
- const h = parseFloat(adaptor.getAttribute(node, "height") || "0");
381
-
382
- if (w > 0 && h > 0) {
383
- const pts = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
384
- const tp = pts.map(p => applyMatrix(p[0], p[1], nodeMatrix));
385
- pushCmds(`__rect_${synthIdx++}`, [
386
- { cmd: 'M', args: [tp[0][0], tp[0][1]] },
387
- { cmd: 'L', args: [tp[1][0], tp[1][1]] },
388
- { cmd: 'L', args: [tp[2][0], tp[2][1]] },
389
- { cmd: 'L', args: [tp[3][0], tp[3][1]] },
390
- { cmd: 'Z', args: [] },
391
- ]);
392
- }
393
- } else if (nodeName === "path" && parentKind(node) !== "defs") {
394
- const d = adaptor.getAttribute(node, "d");
395
- if (d) {
396
- const abs = expandToAbsolute(tokenisePath(d));
397
- const cmds: Array<{ cmd: string; args: number[] }> = [];
398
- for (const gc of abs) {
399
- const shiftedArgs = [...gc.args];
400
- for (let j = 0; j < shiftedArgs.length; j += 2) {
401
- const [nx, ny] = applyMatrix(shiftedArgs[j], shiftedArgs[j + 1], nodeMatrix);
402
- shiftedArgs[j] = nx;
403
- shiftedArgs[j + 1] = ny;
404
- }
405
- cmds.push({ cmd: gc.cmd, args: shiftedArgs });
406
- }
407
- pushCmds(`__path_${synthIdx++}`, cmds);
408
- }
409
- }
410
-
411
- for (const child of adaptor.childNodes(node) as unknown[]) {
412
- // A text node's kind is "#text"; only elements carry geometry, and
413
- // <defs> holds the dictionary rather than anything drawn.
414
- const kind = String(adaptor.kind(child)).toLowerCase();
415
- if (kind.startsWith("#") || kind === "defs") continue;
416
- traverse(child, nodeMatrix, part);
417
- }
418
- if (part !== within) parts[part].to = rawTokens.length;
419
- }
420
-
421
- traverse(svgEl, identityMatrix, -1);
422
-
423
- for (const part of parts) {
424
- if (part.parent !== -1) continue;
425
- for (let i = part.from; i < part.to; i++) rawTokens[i].term = part.latex;
426
- }
427
-
428
- // Bounding box across all raw commands, in the SVG's own coordinates.
429
- const box = svgBBox(rawTokens.flatMap(t => t.cmds));
430
- return { tokens: rawTokens, parts, box, heightEx };
431
- }
432
-
433
- /**
434
- * The size-dependent half: glyph geometry in, a laid-out formula out.
435
- *
436
- * Everything here is one uniform scale about the geometry's own centre, which
437
- * is exactly why {@link LatexGeometry} is worth remembering on its own.
438
- */
439
- function scaleLatexGeometry(geometry: LatexGeometry, fontSize: number): LatexPathResult {
440
- const { tokens: rawTokens, parts, box, heightEx } = geometry;
441
- if (rawTokens.length === 0) return { tokens: [], parts: [], commands: [], width: 0, height: 0, bounds: [0, 0, 0, 0] };
442
-
443
- const { minX, minY, maxX, maxY } = box;
444
- const svgW = maxX - minX;
445
- const svgH = maxY - minY;
446
-
447
- let scale: number;
448
- if (heightEx > 0 && svgH > 0) {
449
- const exInCoords = svgH / heightEx;
450
- scale = fontSize / (2 * exInCoords);
451
- } else {
452
- scale = svgH > 0 ? fontSize / svgH : 1;
453
- }
454
-
455
- const ocx = (minX + maxX) / 2;
456
- const ocy = (minY + maxY) / 2;
457
-
458
- const tx = (svgX: number) => (svgX - ocx) * scale;
459
- const ty = (svgY: number) => (svgY - ocy) * scale;
460
-
461
- function rawCmdsToPathCommands(cmds: Array<{ cmd: string; args: number[] }>): PathCommand[] {
462
- const out: PathCommand[] = [];
463
- for (const { cmd, args: a } of cmds) {
464
- switch (cmd) {
465
- case 'M': out.push({ type: 'M', x: tx(a[0]), y: ty(a[1]) }); break;
466
- case 'L': out.push({ type: 'L', x: tx(a[0]), y: ty(a[1]) }); break;
467
- case 'Q': out.push({ type: 'Q', x1: tx(a[0]), y1: ty(a[1]), x: tx(a[2]), y: ty(a[3]) }); break;
468
- case 'C': out.push({ type: 'C', x1: tx(a[0]), y1: ty(a[1]), x2: tx(a[2]), y2: ty(a[3]), x: tx(a[4]), y: ty(a[5]) }); break;
469
- case 'Z': out.push({ type: 'Z' }); break;
470
- }
471
- }
472
- return out;
473
- }
474
-
475
- const tokens: LatexToken[] = rawTokens.map(rt => ({
476
- token: rt.token,
477
- path: rawCmdsToPathCommands(rt.cmds),
478
- ...(rt.term !== undefined && { term: rt.term }),
479
- }));
480
-
481
- const commands = tokens.flatMap(t => t.path);
482
-
483
- // Shared center frame for all tokens, in token coordinate space. tx/ty map
484
- // the SVG bbox corners; this is the frame every token's path is laid out in.
485
- const bounds: [number, number, number, number] = [
486
- tx(minX), ty(minY), tx(maxX), ty(maxY),
487
- ];
488
-
489
- return { tokens, parts, commands, width: svgW * scale, height: svgH * scale, bounds };
490
- }
491
-
492
- // --- Parts ---
493
-
494
- // Spacing and grouping braces are how a source is written, not what it says:
495
- // `x^{2}` and `x^2` name one part.
496
- function partKey(latex: string): string {
497
- return latex.replace(/[\s{}]/g, "");
498
- }
499
-
500
- /**
501
- * The sources of a formula's parts, each once, in the order written: what a
502
- * host offers to pick a part from. Empty for a formula that will not typeset.
503
- */
504
- export function latexPartNames(source: string): string[] {
505
- if (source.trim() === "") return [];
506
- let parts: LatexPart[];
507
- try {
508
- parts = buildLatexPath(source, 16).parts;
509
- } catch {
510
- return [];
511
- }
512
- const seen = new Set<string>();
513
- const names: string[] = [];
514
- for (const part of parts) {
515
- const key = partKey(part.latex);
516
- if (part.to <= part.from || key === "" || seen.has(key)) continue;
517
- seen.add(key);
518
- names.push(part.latex);
519
- }
520
- return names;
521
- }
522
-
523
- /**
524
- * The token spans `selector` names in a formula, in source order: every part
525
- * whose source it is, and every run of neighbouring parts that spell it
526
- * together (`b^2 = c^2` in `a^2 + b^2 = c^2`). Empty when it names nothing.
527
- */
528
- export function findLatexParts(parts: readonly LatexPart[], selector: string): Array<[from: number, to: number]> {
529
- const wanted = partKey(selector);
530
- if (wanted === "") return [];
531
- const found = new Map<string, [number, number]>();
532
- const keep = (from: number, to: number) => {
533
- if (to > from) found.set(`${from}:${to}`, [from, to]);
534
- };
535
- const children = new Map<number, number[]>();
536
- parts.forEach((part, i) => {
537
- if (partKey(part.latex) === wanted) keep(part.from, part.to);
538
- const siblings = children.get(part.parent);
539
- if (siblings) siblings.push(i);
540
- else children.set(part.parent, [i]);
541
- });
542
- for (const siblings of children.values()) {
543
- for (let a = 0; a < siblings.length; a++) {
544
- let spelled = "";
545
- for (let b = a; b < siblings.length && spelled.length < wanted.length; b++) {
546
- spelled += partKey(parts[siblings[b]].latex);
547
- if (b > a && spelled === wanted) keep(parts[siblings[a]].from, parts[siblings[b]].to);
548
- }
549
- }
550
- }
551
- return [...found.values()].sort((x, y) => x[0] - y[0] || x[1] - y[1]);
552
- }
553
-
554
- // --- SVG Path Utilities ---
555
-
556
- type RawCmd = { cmd: string; args: number[] };
557
-
558
- function tokenisePath(d: string): RawCmd[] {
559
- const re = /([MmLlHhVvCcSsQqTtAaZz])|([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)/g;
560
- const out: RawCmd[] = [];
561
- let cur: RawCmd | null = null;
562
- let m: RegExpExecArray | null;
563
- while ((m = re.exec(d)) !== null) {
564
- if (m[1]) { cur = { cmd: m[1], args: [] }; out.push(cur); }
565
- else if (cur) cur.args.push(parseFloat(m[2]));
566
- }
567
- return out;
568
- }
569
-
570
- function argCount(cmd: string): number {
571
- switch (cmd.toUpperCase()) {
572
- case 'M': return 2; case 'L': return 2; case 'H': return 1; case 'V': return 1;
573
- case 'C': return 6; case 'S': return 4; case 'Q': return 4; case 'T': return 2;
574
- case 'A': return 7; case 'Z': return 0; default: return 0;
575
- }
576
- }
577
-
578
- interface Pt { x: number; y: number }
579
-
580
- function expandToAbsolute(raw: RawCmd[]): Array<{ cmd: string; args: number[] }> {
581
- const out: Array<{ cmd: string; args: number[] }> = [];
582
- let cx = 0, cy = 0;
583
- let mx = 0, my = 0;
584
- let prevCmd = '';
585
- let prevCtrl: Pt = { x: 0, y: 0 };
586
-
587
- for (const { cmd, args } of raw) {
588
- const up = cmd.toUpperCase();
589
- const rel = cmd === cmd.toLowerCase() && up !== 'Z';
590
- const n = argCount(up);
591
- const reps = n === 0 ? 1 : Math.max(1, Math.ceil(args.length / n));
592
-
593
- for (let r = 0; r < reps; r++) {
594
- const a = args.slice(r * n, r * n + n);
595
- const absX = (i: number) => rel ? a[i] + cx : a[i];
596
- const absY = (i: number) => rel ? a[i] + cy : a[i];
597
-
598
- switch (up) {
599
- case 'M': {
600
- const x = absX(0), y = absY(1);
601
- const emitCmd = r === 0 ? 'M' : 'L';
602
- out.push({ cmd: emitCmd, args: [x, y] });
603
- cx = x; cy = y;
604
- if (r === 0) { mx = x; my = y; }
605
- prevCmd = emitCmd;
606
- prevCtrl = { x: cx, y: cy };
607
- break;
608
- }
609
- case 'Z':
610
- out.push({ cmd: 'Z', args: [] });
611
- cx = mx; cy = my;
612
- prevCmd = 'Z';
613
- break;
614
- case 'L': {
615
- const x = absX(0), y = absY(1);
616
- out.push({ cmd: 'L', args: [x, y] });
617
- cx = x; cy = y;
618
- prevCmd = 'L';
619
- prevCtrl = { x: cx, y: cy };
620
- break;
621
- }
622
- case 'H': {
623
- const x = rel ? a[0] + cx : a[0];
624
- out.push({ cmd: 'L', args: [x, cy] });
625
- cx = x;
626
- prevCmd = 'L';
627
- prevCtrl = { x: cx, y: cy };
628
- break;
629
- }
630
- case 'V': {
631
- const y = rel ? a[0] + cy : a[0];
632
- out.push({ cmd: 'L', args: [cx, y] });
633
- cy = y;
634
- prevCmd = 'L';
635
- prevCtrl = { x: cx, y: cy };
636
- break;
637
- }
638
- case 'C': {
639
- const x1 = absX(0), y1 = absY(1);
640
- const x2 = absX(2), y2 = absY(3);
641
- const x = absX(4), y = absY(5);
642
- out.push({ cmd: 'C', args: [x1, y1, x2, y2, x, y] });
643
- prevCtrl = { x: x2, y: y2 };
644
- cx = x; cy = y;
645
- prevCmd = 'C';
646
- break;
647
- }
648
- case 'S': {
649
- const x1 = prevCmd === 'C' || prevCmd === 'S' ? 2 * cx - prevCtrl.x : cx;
650
- const y1 = prevCmd === 'C' || prevCmd === 'S' ? 2 * cy - prevCtrl.y : cy;
651
- const x2 = absX(0), y2 = absY(1);
652
- const x = absX(2), y = absY(3);
653
- out.push({ cmd: 'C', args: [x1, y1, x2, y2, x, y] });
654
- prevCtrl = { x: x2, y: y2 };
655
- cx = x; cy = y;
656
- prevCmd = 'S';
657
- break;
658
- }
659
- case 'Q': {
660
- const x1 = absX(0), y1 = absY(1);
661
- const x = absX(2), y = absY(3);
662
- out.push({ cmd: 'Q', args: [x1, y1, x, y] });
663
- prevCtrl = { x: x1, y: y1 };
664
- cx = x; cy = y;
665
- prevCmd = 'Q';
666
- break;
667
- }
668
- case 'T': {
669
- const x1 = prevCmd === 'Q' || prevCmd === 'T' ? 2 * cx - prevCtrl.x : cx;
670
- const y1 = prevCmd === 'Q' || prevCmd === 'T' ? 2 * cy - prevCtrl.y : cy;
671
- const x = absX(0), y = absY(1);
672
- out.push({ cmd: 'Q', args: [x1, y1, x, y] });
673
- prevCtrl = { x: x1, y: y1 };
674
- cx = x; cy = y;
675
- prevCmd = 'T';
676
- break;
677
- }
678
- }
679
- }
680
- }
681
-
682
- if (out.length > 0 && out[out.length - 1].cmd !== 'Z') {
683
- out.push({ cmd: 'Z', args: [] });
684
- }
685
-
686
- return out;
687
- }
688
-
689
- function svgBBox(abs: Array<{ cmd: string; args: number[] }>): { minX: number; minY: number; maxX: number; maxY: number } {
690
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
691
- const touch = (x: number, y: number) => {
692
- if (x < minX) minX = x; if (x > maxX) maxX = x;
693
- if (y < minY) minY = y; if (y > maxY) maxY = y;
694
- };
695
- for (const { cmd, args } of abs) {
696
- switch (cmd) {
697
- case 'M': case 'L': touch(args[0], args[1]); break;
698
- case 'C': touch(args[0], args[1]); touch(args[2], args[3]); touch(args[4], args[5]); break;
699
- case 'Q': touch(args[0], args[1]); touch(args[2], args[3]); break;
700
- }
701
- }
702
- return { minX, minY, maxX, maxY };
703
- }
1
+
2
+ import { PathCommand } from '@motionscript/sdk';
3
+
4
+ import { createBoundedCache } from '../kit/cache';
5
+
6
+ // --- MathJax, on demand ---
7
+
8
+ type MathJaxRuntime = typeof import('./mathjax');
9
+
10
+ let runtime: MathJaxRuntime | null = null;
11
+ let loading: Promise<void> | null = null;
12
+ // MathJax's DOM, a real one or its own DOM-free tree: read only through its accessors, so its element type is opaque here.
13
+ let adaptor: any = null;
14
+
15
+ /**
16
+ * The asset key a node that typesets declares its loader under: the host waits
17
+ * for it before laying the node out, and a scene with no formula never loads it.
18
+ */
19
+ export const MATHJAX_LOADER = 'math:mathjax';
20
+
21
+ /** Load MathJax, once. A host that typesets outside a scene (a tool, a test) awaits this first. */
22
+ export function loadMathJax(): Promise<void> {
23
+ loading ??= import('./mathjax').then((module) => {
24
+ runtime = module;
25
+ adaptor = module.adaptor;
26
+ });
27
+ return loading;
28
+ }
29
+
30
+ /** Whether MathJax has loaded, so a formula can be typeset now. */
31
+ export function mathJaxLoaded(): boolean {
32
+ return runtime !== null;
33
+ }
34
+
35
+ /** What a formula is before MathJax has loaded: nothing to draw, and nothing cached. */
36
+ export function blankLatex(): LatexPathResult {
37
+ return { tokens: [], parts: [], commands: [], width: 0, height: 0, bounds: [0, 0, 0, 0] };
38
+ }
39
+
40
+ /** MathJax is not loaded yet: what typesetting throws before {@link loadMathJax} has resolved. */
41
+ export class LatexNotLoaded extends Error {
42
+ constructor() {
43
+ super('MathJax is not loaded: declare the math:mathjax loader, or await loadMathJax(), before typesetting.');
44
+ this.name = 'LatexNotLoaded';
45
+ }
46
+ }
47
+
48
+ // --- Public API ---
49
+
50
+ /**
51
+ * A formula MathJax could not typeset.
52
+ *
53
+ * MathJax does not throw on malformed TeX. It typesets an error box in place of
54
+ * the formula and tags it `data-mjx-error`, so the failure arrives as a drawing:
55
+ * nothing at all from the browser adaptor and a filled bar from the DOM-free
56
+ * one, which left a host able to tell a bad formula from a blank one only by the
57
+ * token count. {@link buildLatexPath} raises this instead, the same way under
58
+ * both adaptors. `\require` is an error too, since only the packages named above
59
+ * are loaded.
60
+ */
61
+ export class LatexError extends Error {
62
+ /** The formula that failed, as it was given. */
63
+ readonly latex: string;
64
+ /** MathJax's own description of what is wrong with it. */
65
+ readonly reason: string;
66
+
67
+ constructor(latex: string, reason: string) {
68
+ super(`Cannot typeset "${latex}": ${reason}`);
69
+ this.name = 'LatexError';
70
+ this.latex = latex;
71
+ this.reason = reason;
72
+ }
73
+ }
74
+
75
+ /** A single rendered glyph or shape with its character key and path commands. */
76
+ export interface LatexToken {
77
+ /** Character this token represents, or a synthetic key for non-glyph shapes. */
78
+ token: string;
79
+ path: PathCommand[];
80
+ /** The source of the top-level term the token belongs to, `a^2` in `a^2 + b^2`; empty for none. */
81
+ term?: string;
82
+ }
83
+
84
+ /**
85
+ * A piece of a formula as its source wrote it: `x^2`, `\frac{d}{dx}`, a lone
86
+ * `+`. Every group the typesetter makes is one, so parts nest.
87
+ */
88
+ export interface LatexPart {
89
+ /** The part's own source. */
90
+ latex: string;
91
+ /** The tokens it draws, as a span of the formula's token list: `from` up to, not including, `to`. */
92
+ from: number;
93
+ to: number;
94
+ /** The index of the part it sits in, or -1 at the top. */
95
+ parent: number;
96
+ }
97
+
98
+ export interface LatexPathResult {
99
+ /** All tokens in render order. */
100
+ tokens: LatexToken[];
101
+ /** Every part of the formula, outermost first, in source order. */
102
+ parts: LatexPart[];
103
+ /** Flat array of all path commands (for legacy single-path rendering). */
104
+ commands: PathCommand[];
105
+ width: number;
106
+ height: number;
107
+ /**
108
+ * Bounding box over every token, in token coordinate space:
109
+ * [minX, minY, maxX, maxY]. All tokens share this frame, so passing it as
110
+ * each path's center frame keeps their relative layout (instead of each
111
+ * glyph centering on its own bbox).
112
+ */
113
+ bounds: [number, number, number, number];
114
+ }
115
+
116
+ /**
117
+ * A formula's glyph geometry, before a type size is applied to it.
118
+ *
119
+ * The dividing line this whole module's caching turns on. Getting here is the
120
+ * expensive part — MathJax lays the formula out, then the SVG it produces is
121
+ * parsed, its glyph dictionary resolved and every `<use>` walked through its
122
+ * transform stack — and **none of it depends on `fontSize`**: `mjDoc.convert`
123
+ * is called at a fixed em/ex, and the size arrives at the very end as one
124
+ * uniform scale (see {@link scaleLatexGeometry}).
125
+ *
126
+ * So this is what gets remembered per formula, and the size is applied to it
127
+ * afresh. A formula animating from 24pt to 120pt is one trip through MathJax
128
+ * and one DOM parse, not one per frame.
129
+ */
130
+ interface LatexGeometry {
131
+ tokens: RawToken[];
132
+ parts: LatexPart[];
133
+ /** Box over every command, in the SVG's own coordinates. */
134
+ box: { minX: number; minY: number; maxX: number; maxY: number };
135
+ /** The formula's height in `ex`, as MathJax reported it. */
136
+ heightEx: number;
137
+ }
138
+
139
+ /**
140
+ * Formulas already worked out, and formulas already sized.
141
+ *
142
+ * `buildLatexPath` is a pure function of `(text, fontSize)` and used to have no
143
+ * memory, which made every caller pay full price for a question it had already
144
+ * asked. The callers are not occasional about it either: constructing a `Latex`
145
+ * resolves its formula, and so does every `to({ latex })` the moment it starts,
146
+ * so a scene re-resolves every formula in it whenever it is rebuilt *and*
147
+ * whenever the playhead moves backwards, since a backward seek replays the
148
+ * scene's generator from its first frame. An editor that rebuilds on a keystroke
149
+ * and seeks on a click asks for the same handful of formulas hundreds of times.
150
+ *
151
+ * Two memos, each keyed by what its stage actually depends on, and deliberately
152
+ * different sizes:
153
+ *
154
+ * - {@link geometryCache} is everything up to the type size, keyed by the text
155
+ * alone. This is the expensive one, and it is generously sized because
156
+ * nothing a scene does can churn it: a deck holds as many distinct formulas
157
+ * as it holds, and it holds them for as long as it is open.
158
+ * - {@link pathCache} is the finished result, keyed by text *and* size. Small
159
+ * on purpose: an animated `fontSize` inserts a distinct key every frame, and
160
+ * the right thing for a stream like that is to churn a little memo rather
161
+ * than a big one. What a miss costs here is arithmetic over glyphs already
162
+ * worked out — no MathJax, no parse.
163
+ */
164
+ const geometryCache = createBoundedCache<LatexGeometry>(128);
165
+ const pathCache = createBoundedCache<LatexPathResult>(64);
166
+
167
+ export function buildLatexPath(text: string, fontSize: number): LatexPathResult {
168
+ // NUL rather than a punctuation separator, so no formula can spell a key
169
+ // belonging to another size.
170
+ const key = `${fontSize}\0${text}`;
171
+
172
+ const hit = pathCache.get(key);
173
+ if (hit) return lend(hit);
174
+
175
+ let geometry = geometryCache.get(text);
176
+ if (!geometry) {
177
+ geometry = buildLatexGeometry(text);
178
+ geometryCache.set(text, geometry);
179
+ }
180
+
181
+ const result = scaleLatexGeometry(geometry, fontSize);
182
+ pathCache.set(key, result);
183
+ return lend(result);
184
+ }
185
+
186
+ /** Typeset `text` and reduce the SVG MathJax returns to glyph geometry. */
187
+ function buildLatexGeometry(text: string): LatexGeometry {
188
+ if (!runtime) throw new LatexNotLoaded();
189
+ const svgEl = adaptor.firstChild(runtime.convert(text));
190
+ const failure = mathJaxError(svgEl);
191
+ if (failure !== null) throw new LatexError(text, failure);
192
+
193
+ const heightAttr = adaptor.getAttribute(svgEl, 'height') ?? '';
194
+
195
+ return parseLatexSvg(svgEl, parseFloat(heightAttr) || 0);
196
+ }
197
+
198
+ /**
199
+ * MathJax's description of the error box in a typeset formula, or `null` when
200
+ * there is none. Read through the adaptor, so a real DOM and the DOM-free tree
201
+ * give the same answer.
202
+ */
203
+ function mathJaxError(svgEl: unknown): string | null {
204
+ for (const el of adaptor.tags(svgEl, 'g') as unknown[]) {
205
+ const reason = adaptor.getAttribute(el, 'data-mjx-error');
206
+ if (reason !== null && reason !== undefined) return String(reason) || 'unknown error';
207
+ }
208
+ return null;
209
+ }
210
+
211
+ /**
212
+ * A cached result, handed out safely.
213
+ *
214
+ * `tokens`, `commands` and the path arrays inside them are shared: they are read
215
+ * by everything downstream and written by none of it — `Latex` maps tokens into
216
+ * its own wrappers, and the morph builds new paths rather than editing the ones
217
+ * it is given — so copying them would be copying the whole formula for nothing.
218
+ *
219
+ * `bounds` is copied, because it is the one field a caller *stores*: `Latex`
220
+ * assigns `result.bounds` straight to `this._bounds` and hands it to the
221
+ * renderer as a shared centring frame. That was one node holding its own array
222
+ * before there was a memo, and would be two nodes drawing the same formula
223
+ * holding one array between them after — four numbers is not a price worth
224
+ * paying to find out whether anything downstream ever writes to it.
225
+ */
226
+ function lend(result: LatexPathResult): LatexPathResult {
227
+ const [minX, minY, maxX, maxY] = result.bounds;
228
+ return { ...result, bounds: [minX, minY, maxX, maxY] };
229
+ }
230
+
231
+ // --- High-Speed Matrix Math ---
232
+
233
+ type Matrix = [number, number, number, number, number, number]; // [a, b, c, d, tx, ty]
234
+ const identityMatrix: Matrix = [1, 0, 0, 1, 0, 0];
235
+
236
+ function multiplyMatrix(m1: Matrix, m2: Matrix): Matrix {
237
+ return [
238
+ m1[0] * m2[0] + m1[2] * m2[1],
239
+ m1[1] * m2[0] + m1[3] * m2[1],
240
+ m1[0] * m2[2] + m1[2] * m2[3],
241
+ m1[1] * m2[2] + m1[3] * m2[3],
242
+ m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
243
+ m1[1] * m2[4] + m1[3] * m2[5] + m1[5],
244
+ ];
245
+ }
246
+
247
+ function parseTransform(str: string | null): Matrix {
248
+ if (!str) return identityMatrix;
249
+ let m: Matrix = [...identityMatrix];
250
+ const re = /([a-z]+)\(([^)]+)\)/g;
251
+ let match;
252
+ while ((match = re.exec(str)) !== null) {
253
+ const type = match[1];
254
+ const args = match[2].split(/[ ,]+/).map(parseFloat);
255
+ if (type === 'translate') {
256
+ m = multiplyMatrix(m, [1, 0, 0, 1, args[0] || 0, args[1] || 0]);
257
+ } else if (type === 'scale') {
258
+ const sx = args[0] || 1;
259
+ const sy = args[1] !== undefined ? args[1] : sx;
260
+ m = multiplyMatrix(m, [sx, 0, 0, sy, 0, 0]);
261
+ } else if (type === 'matrix') {
262
+ m = multiplyMatrix(m, [args[0], args[1], args[2], args[3], args[4], args[5]]);
263
+ }
264
+ }
265
+ return m;
266
+ }
267
+
268
+ function applyMatrix(x: number, y: number, m: Matrix): [number, number] {
269
+ return [
270
+ x * m[0] + y * m[2] + m[4],
271
+ x * m[1] + y * m[3] + m[5],
272
+ ];
273
+ }
274
+
275
+ // --- Glyph ID → character decoding ---
276
+
277
+ /**
278
+ * MathJax SVG glyph IDs look like "MJX-1-TEX-N-78" or "MJX-1-TEX-I-1D465".
279
+ * The last segment is the Unicode codepoint in hex.
280
+ */
281
+ function glyphIdToChar(id: string): string {
282
+ const parts = id.split('-');
283
+ const hex = parts[parts.length - 1];
284
+ const cp = parseInt(hex, 16);
285
+ if (!isNaN(cp)) {
286
+ try { return String.fromCodePoint(cp); } catch { /* fall through */ }
287
+ }
288
+ return id;
289
+ }
290
+
291
+ // --- Core Fast Traversal Engine ---
292
+
293
+ type RawToken = { token: string; cmds: Array<{ cmd: string; args: number[] }>; term?: string };
294
+
295
+ /** The tag name of a node's parent, or "" at the root. */
296
+ function parentKind(node: unknown): string {
297
+ const parent = adaptor.parent(node);
298
+ return parent ? String(adaptor.kind(parent)).toLowerCase() : "";
299
+ }
300
+
301
+ /**
302
+ * The size-independent half: MathJax's own SVG tree in, glyph geometry out.
303
+ *
304
+ * Walked through the **adaptor** rather than a `DOMParser`. MathJax already
305
+ * builds this tree, and the adaptor is its own abstraction over "a real DOM" and
306
+ * "the DOM-free `LiteElement` tree" — the two this module already picks between
307
+ * at load. Serialising it to a string and parsing it back needed a `DOMParser`,
308
+ * which Node does not have, so every LaTeX node threw `DOMParser is not defined`
309
+ * and could not render headlessly at all: no export, and nothing the visual
310
+ * suite could check.
311
+ *
312
+ * Reading the tree directly is also one representation instead of three (tree →
313
+ * string → tree), so a browser and a headless host cannot disagree about how the
314
+ * markup re-parsed.
315
+ */
316
+ function parseLatexSvg(svgEl: unknown, heightEx: number): LatexGeometry {
317
+ // Pre-parse the glyph dictionary. `tags` reaches every <path> in the tree,
318
+ // including the ones inside <defs> that the `use` elements reference.
319
+ const glyphMap = new Map<string, Array<{ cmd: string; args: number[] }>>();
320
+ for (const el of adaptor.tags(svgEl, 'path') as unknown[]) {
321
+ const id = adaptor.getAttribute(el, 'id');
322
+ const d = adaptor.getAttribute(el, 'd');
323
+ if (id && d) {
324
+ glyphMap.set(`#${id}`, expandToAbsolute(tokenisePath(d)));
325
+ }
326
+ }
327
+
328
+ // Collect raw tokens — each <use> is one token, rects/paths are grouped as synthetic tokens
329
+ const rawTokens: RawToken[] = [];
330
+ const parts: LatexPart[] = [];
331
+ let synthIdx = 0;
332
+
333
+ function pushCmds(token: string, cmds: Array<{ cmd: string; args: number[] }>) {
334
+ rawTokens.push({ token, cmds });
335
+ }
336
+
337
+ function traverse(node: unknown, currentMatrix: Matrix, within: number) {
338
+ let nodeMatrix = currentMatrix;
339
+
340
+ const transformStr = adaptor.getAttribute(node, "transform");
341
+ if (transformStr) {
342
+ nodeMatrix = multiplyMatrix(nodeMatrix, parseTransform(transformStr));
343
+ }
344
+
345
+ const nodeName = String(adaptor.kind(node)).toLowerCase();
346
+
347
+ // MathJax tags each group with the source it typeset; the root's is the whole formula.
348
+ let part = within;
349
+ const source = nodeName === "g" ? adaptor.getAttribute(node, "data-latex") : null;
350
+ if (source && adaptor.getAttribute(node, "data-mml-node") !== "math") {
351
+ part = parts.length;
352
+ parts.push({ latex: String(source), from: rawTokens.length, to: rawTokens.length, parent: within });
353
+ }
354
+
355
+ if (nodeName === "use") {
356
+ const href = adaptor.getAttribute(node, "href") || adaptor.getAttribute(node, "xlink:href");
357
+ const x = parseFloat(adaptor.getAttribute(node, "x") || "0");
358
+ const y = parseFloat(adaptor.getAttribute(node, "y") || "0");
359
+
360
+ if (href && glyphMap.has(href)) {
361
+ const glyphCommands = glyphMap.get(href)!;
362
+ const cmds: Array<{ cmd: string; args: number[] }> = [];
363
+ for (const gc of glyphCommands) {
364
+ const shiftedArgs = [...gc.args];
365
+ for (let j = 0; j < shiftedArgs.length; j += 2) {
366
+ const [nx, ny] = applyMatrix(shiftedArgs[j] + x, shiftedArgs[j + 1] + y, nodeMatrix);
367
+ shiftedArgs[j] = nx;
368
+ shiftedArgs[j + 1] = ny;
369
+ }
370
+ cmds.push({ cmd: gc.cmd, args: shiftedArgs });
371
+ }
372
+ // Derive character from glyph ID
373
+ const rawId = href.startsWith('#') ? href.slice(1) : href;
374
+ pushCmds(glyphIdToChar(rawId), cmds);
375
+ }
376
+ } else if (nodeName === "rect") {
377
+ const x = parseFloat(adaptor.getAttribute(node, "x") || "0");
378
+ const y = parseFloat(adaptor.getAttribute(node, "y") || "0");
379
+ const w = parseFloat(adaptor.getAttribute(node, "width") || "0");
380
+ const h = parseFloat(adaptor.getAttribute(node, "height") || "0");
381
+
382
+ if (w > 0 && h > 0) {
383
+ const pts = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
384
+ const tp = pts.map(p => applyMatrix(p[0], p[1], nodeMatrix));
385
+ pushCmds(`__rect_${synthIdx++}`, [
386
+ { cmd: 'M', args: [tp[0][0], tp[0][1]] },
387
+ { cmd: 'L', args: [tp[1][0], tp[1][1]] },
388
+ { cmd: 'L', args: [tp[2][0], tp[2][1]] },
389
+ { cmd: 'L', args: [tp[3][0], tp[3][1]] },
390
+ { cmd: 'Z', args: [] },
391
+ ]);
392
+ }
393
+ } else if (nodeName === "path" && parentKind(node) !== "defs") {
394
+ const d = adaptor.getAttribute(node, "d");
395
+ if (d) {
396
+ const abs = expandToAbsolute(tokenisePath(d));
397
+ const cmds: Array<{ cmd: string; args: number[] }> = [];
398
+ for (const gc of abs) {
399
+ const shiftedArgs = [...gc.args];
400
+ for (let j = 0; j < shiftedArgs.length; j += 2) {
401
+ const [nx, ny] = applyMatrix(shiftedArgs[j], shiftedArgs[j + 1], nodeMatrix);
402
+ shiftedArgs[j] = nx;
403
+ shiftedArgs[j + 1] = ny;
404
+ }
405
+ cmds.push({ cmd: gc.cmd, args: shiftedArgs });
406
+ }
407
+ pushCmds(`__path_${synthIdx++}`, cmds);
408
+ }
409
+ }
410
+
411
+ for (const child of adaptor.childNodes(node) as unknown[]) {
412
+ // A text node's kind is "#text"; only elements carry geometry, and
413
+ // <defs> holds the dictionary rather than anything drawn.
414
+ const kind = String(adaptor.kind(child)).toLowerCase();
415
+ if (kind.startsWith("#") || kind === "defs") continue;
416
+ traverse(child, nodeMatrix, part);
417
+ }
418
+ if (part !== within) parts[part].to = rawTokens.length;
419
+ }
420
+
421
+ traverse(svgEl, identityMatrix, -1);
422
+
423
+ for (const part of parts) {
424
+ if (part.parent !== -1) continue;
425
+ for (let i = part.from; i < part.to; i++) rawTokens[i].term = part.latex;
426
+ }
427
+
428
+ // Bounding box across all raw commands, in the SVG's own coordinates.
429
+ const box = svgBBox(rawTokens.flatMap(t => t.cmds));
430
+ return { tokens: rawTokens, parts, box, heightEx };
431
+ }
432
+
433
+ /**
434
+ * The size-dependent half: glyph geometry in, a laid-out formula out.
435
+ *
436
+ * Everything here is one uniform scale about the geometry's own centre, which
437
+ * is exactly why {@link LatexGeometry} is worth remembering on its own.
438
+ */
439
+ function scaleLatexGeometry(geometry: LatexGeometry, fontSize: number): LatexPathResult {
440
+ const { tokens: rawTokens, parts, box, heightEx } = geometry;
441
+ if (rawTokens.length === 0) return { tokens: [], parts: [], commands: [], width: 0, height: 0, bounds: [0, 0, 0, 0] };
442
+
443
+ const { minX, minY, maxX, maxY } = box;
444
+ const svgW = maxX - minX;
445
+ const svgH = maxY - minY;
446
+
447
+ let scale: number;
448
+ if (heightEx > 0 && svgH > 0) {
449
+ const exInCoords = svgH / heightEx;
450
+ scale = fontSize / (2 * exInCoords);
451
+ } else {
452
+ scale = svgH > 0 ? fontSize / svgH : 1;
453
+ }
454
+
455
+ const ocx = (minX + maxX) / 2;
456
+ const ocy = (minY + maxY) / 2;
457
+
458
+ const tx = (svgX: number) => (svgX - ocx) * scale;
459
+ const ty = (svgY: number) => (svgY - ocy) * scale;
460
+
461
+ function rawCmdsToPathCommands(cmds: Array<{ cmd: string; args: number[] }>): PathCommand[] {
462
+ const out: PathCommand[] = [];
463
+ for (const { cmd, args: a } of cmds) {
464
+ switch (cmd) {
465
+ case 'M': out.push({ type: 'M', x: tx(a[0]), y: ty(a[1]) }); break;
466
+ case 'L': out.push({ type: 'L', x: tx(a[0]), y: ty(a[1]) }); break;
467
+ case 'Q': out.push({ type: 'Q', x1: tx(a[0]), y1: ty(a[1]), x: tx(a[2]), y: ty(a[3]) }); break;
468
+ case 'C': out.push({ type: 'C', x1: tx(a[0]), y1: ty(a[1]), x2: tx(a[2]), y2: ty(a[3]), x: tx(a[4]), y: ty(a[5]) }); break;
469
+ case 'Z': out.push({ type: 'Z' }); break;
470
+ }
471
+ }
472
+ return out;
473
+ }
474
+
475
+ const tokens: LatexToken[] = rawTokens.map(rt => ({
476
+ token: rt.token,
477
+ path: rawCmdsToPathCommands(rt.cmds),
478
+ ...(rt.term !== undefined && { term: rt.term }),
479
+ }));
480
+
481
+ const commands = tokens.flatMap(t => t.path);
482
+
483
+ // Shared center frame for all tokens, in token coordinate space. tx/ty map
484
+ // the SVG bbox corners; this is the frame every token's path is laid out in.
485
+ const bounds: [number, number, number, number] = [
486
+ tx(minX), ty(minY), tx(maxX), ty(maxY),
487
+ ];
488
+
489
+ return { tokens, parts, commands, width: svgW * scale, height: svgH * scale, bounds };
490
+ }
491
+
492
+ // --- Parts ---
493
+
494
+ // Spacing and grouping braces are how a source is written, not what it says:
495
+ // `x^{2}` and `x^2` name one part.
496
+ function partKey(latex: string): string {
497
+ return latex.replace(/[\s{}]/g, "");
498
+ }
499
+
500
+ /**
501
+ * The sources of a formula's parts, each once, in the order written: what a
502
+ * host offers to pick a part from. Empty for a formula that will not typeset.
503
+ */
504
+ export function latexPartNames(source: string): string[] {
505
+ if (source.trim() === "") return [];
506
+ let parts: LatexPart[];
507
+ try {
508
+ parts = buildLatexPath(source, 16).parts;
509
+ } catch {
510
+ return [];
511
+ }
512
+ const seen = new Set<string>();
513
+ const names: string[] = [];
514
+ for (const part of parts) {
515
+ const key = partKey(part.latex);
516
+ if (part.to <= part.from || key === "" || seen.has(key)) continue;
517
+ seen.add(key);
518
+ names.push(part.latex);
519
+ }
520
+ return names;
521
+ }
522
+
523
+ /**
524
+ * The token spans `selector` names in a formula, in source order: every part
525
+ * whose source it is, and every run of neighbouring parts that spell it
526
+ * together (`b^2 = c^2` in `a^2 + b^2 = c^2`). Empty when it names nothing.
527
+ */
528
+ export function findLatexParts(parts: readonly LatexPart[], selector: string): Array<[from: number, to: number]> {
529
+ const wanted = partKey(selector);
530
+ if (wanted === "") return [];
531
+ const found = new Map<string, [number, number]>();
532
+ const keep = (from: number, to: number) => {
533
+ if (to > from) found.set(`${from}:${to}`, [from, to]);
534
+ };
535
+ const children = new Map<number, number[]>();
536
+ parts.forEach((part, i) => {
537
+ if (partKey(part.latex) === wanted) keep(part.from, part.to);
538
+ const siblings = children.get(part.parent);
539
+ if (siblings) siblings.push(i);
540
+ else children.set(part.parent, [i]);
541
+ });
542
+ for (const siblings of children.values()) {
543
+ for (let a = 0; a < siblings.length; a++) {
544
+ let spelled = "";
545
+ for (let b = a; b < siblings.length && spelled.length < wanted.length; b++) {
546
+ spelled += partKey(parts[siblings[b]].latex);
547
+ if (b > a && spelled === wanted) keep(parts[siblings[a]].from, parts[siblings[b]].to);
548
+ }
549
+ }
550
+ }
551
+ return [...found.values()].sort((x, y) => x[0] - y[0] || x[1] - y[1]);
552
+ }
553
+
554
+ // --- SVG Path Utilities ---
555
+
556
+ type RawCmd = { cmd: string; args: number[] };
557
+
558
+ function tokenisePath(d: string): RawCmd[] {
559
+ const re = /([MmLlHhVvCcSsQqTtAaZz])|([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)/g;
560
+ const out: RawCmd[] = [];
561
+ let cur: RawCmd | null = null;
562
+ let m: RegExpExecArray | null;
563
+ while ((m = re.exec(d)) !== null) {
564
+ if (m[1]) { cur = { cmd: m[1], args: [] }; out.push(cur); }
565
+ else if (cur) cur.args.push(parseFloat(m[2]));
566
+ }
567
+ return out;
568
+ }
569
+
570
+ function argCount(cmd: string): number {
571
+ switch (cmd.toUpperCase()) {
572
+ case 'M': return 2; case 'L': return 2; case 'H': return 1; case 'V': return 1;
573
+ case 'C': return 6; case 'S': return 4; case 'Q': return 4; case 'T': return 2;
574
+ case 'A': return 7; case 'Z': return 0; default: return 0;
575
+ }
576
+ }
577
+
578
+ interface Pt { x: number; y: number }
579
+
580
+ function expandToAbsolute(raw: RawCmd[]): Array<{ cmd: string; args: number[] }> {
581
+ const out: Array<{ cmd: string; args: number[] }> = [];
582
+ let cx = 0, cy = 0;
583
+ let mx = 0, my = 0;
584
+ let prevCmd = '';
585
+ let prevCtrl: Pt = { x: 0, y: 0 };
586
+
587
+ for (const { cmd, args } of raw) {
588
+ const up = cmd.toUpperCase();
589
+ const rel = cmd === cmd.toLowerCase() && up !== 'Z';
590
+ const n = argCount(up);
591
+ const reps = n === 0 ? 1 : Math.max(1, Math.ceil(args.length / n));
592
+
593
+ for (let r = 0; r < reps; r++) {
594
+ const a = args.slice(r * n, r * n + n);
595
+ const absX = (i: number) => rel ? a[i] + cx : a[i];
596
+ const absY = (i: number) => rel ? a[i] + cy : a[i];
597
+
598
+ switch (up) {
599
+ case 'M': {
600
+ const x = absX(0), y = absY(1);
601
+ const emitCmd = r === 0 ? 'M' : 'L';
602
+ out.push({ cmd: emitCmd, args: [x, y] });
603
+ cx = x; cy = y;
604
+ if (r === 0) { mx = x; my = y; }
605
+ prevCmd = emitCmd;
606
+ prevCtrl = { x: cx, y: cy };
607
+ break;
608
+ }
609
+ case 'Z':
610
+ out.push({ cmd: 'Z', args: [] });
611
+ cx = mx; cy = my;
612
+ prevCmd = 'Z';
613
+ break;
614
+ case 'L': {
615
+ const x = absX(0), y = absY(1);
616
+ out.push({ cmd: 'L', args: [x, y] });
617
+ cx = x; cy = y;
618
+ prevCmd = 'L';
619
+ prevCtrl = { x: cx, y: cy };
620
+ break;
621
+ }
622
+ case 'H': {
623
+ const x = rel ? a[0] + cx : a[0];
624
+ out.push({ cmd: 'L', args: [x, cy] });
625
+ cx = x;
626
+ prevCmd = 'L';
627
+ prevCtrl = { x: cx, y: cy };
628
+ break;
629
+ }
630
+ case 'V': {
631
+ const y = rel ? a[0] + cy : a[0];
632
+ out.push({ cmd: 'L', args: [cx, y] });
633
+ cy = y;
634
+ prevCmd = 'L';
635
+ prevCtrl = { x: cx, y: cy };
636
+ break;
637
+ }
638
+ case 'C': {
639
+ const x1 = absX(0), y1 = absY(1);
640
+ const x2 = absX(2), y2 = absY(3);
641
+ const x = absX(4), y = absY(5);
642
+ out.push({ cmd: 'C', args: [x1, y1, x2, y2, x, y] });
643
+ prevCtrl = { x: x2, y: y2 };
644
+ cx = x; cy = y;
645
+ prevCmd = 'C';
646
+ break;
647
+ }
648
+ case 'S': {
649
+ const x1 = prevCmd === 'C' || prevCmd === 'S' ? 2 * cx - prevCtrl.x : cx;
650
+ const y1 = prevCmd === 'C' || prevCmd === 'S' ? 2 * cy - prevCtrl.y : cy;
651
+ const x2 = absX(0), y2 = absY(1);
652
+ const x = absX(2), y = absY(3);
653
+ out.push({ cmd: 'C', args: [x1, y1, x2, y2, x, y] });
654
+ prevCtrl = { x: x2, y: y2 };
655
+ cx = x; cy = y;
656
+ prevCmd = 'S';
657
+ break;
658
+ }
659
+ case 'Q': {
660
+ const x1 = absX(0), y1 = absY(1);
661
+ const x = absX(2), y = absY(3);
662
+ out.push({ cmd: 'Q', args: [x1, y1, x, y] });
663
+ prevCtrl = { x: x1, y: y1 };
664
+ cx = x; cy = y;
665
+ prevCmd = 'Q';
666
+ break;
667
+ }
668
+ case 'T': {
669
+ const x1 = prevCmd === 'Q' || prevCmd === 'T' ? 2 * cx - prevCtrl.x : cx;
670
+ const y1 = prevCmd === 'Q' || prevCmd === 'T' ? 2 * cy - prevCtrl.y : cy;
671
+ const x = absX(0), y = absY(1);
672
+ out.push({ cmd: 'Q', args: [x1, y1, x, y] });
673
+ prevCtrl = { x: x1, y: y1 };
674
+ cx = x; cy = y;
675
+ prevCmd = 'T';
676
+ break;
677
+ }
678
+ }
679
+ }
680
+ }
681
+
682
+ if (out.length > 0 && out[out.length - 1].cmd !== 'Z') {
683
+ out.push({ cmd: 'Z', args: [] });
684
+ }
685
+
686
+ return out;
687
+ }
688
+
689
+ function svgBBox(abs: Array<{ cmd: string; args: number[] }>): { minX: number; minY: number; maxX: number; maxY: number } {
690
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
691
+ const touch = (x: number, y: number) => {
692
+ if (x < minX) minX = x; if (x > maxX) maxX = x;
693
+ if (y < minY) minY = y; if (y > maxY) maxY = y;
694
+ };
695
+ for (const { cmd, args } of abs) {
696
+ switch (cmd) {
697
+ case 'M': case 'L': touch(args[0], args[1]); break;
698
+ case 'C': touch(args[0], args[1]); touch(args[2], args[3]); touch(args[4], args[5]); break;
699
+ case 'Q': touch(args[0], args[1]); touch(args[2], args[3]); break;
700
+ }
701
+ }
702
+ return { minX, minY, maxX, maxY };
703
+ }