@motionscript/math 0.0.0-stage → 0.1.0-alpha.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/CHANGELOG.md +110 -0
- package/LICENSE +201 -0
- package/NOTICE +48 -0
- package/README.md +385 -3
- package/dist/annotate/angle-mark.d.ts +46 -0
- package/dist/annotate/angle-mark.d.ts.map +1 -0
- package/dist/annotate/angle-mark.js +132 -0
- package/dist/annotate/angle-mark.js.map +1 -0
- package/dist/annotate/curly-brace.d.ts +46 -0
- package/dist/annotate/curly-brace.d.ts.map +1 -0
- package/dist/annotate/curly-brace.js +114 -0
- package/dist/annotate/curly-brace.js.map +1 -0
- package/dist/annotate/emphasis-mark.d.ts +20 -0
- package/dist/annotate/emphasis-mark.d.ts.map +1 -0
- package/dist/annotate/emphasis-mark.js +81 -0
- package/dist/annotate/emphasis-mark.js.map +1 -0
- package/dist/browser/THIRD_PARTY_LICENSES.txt +420 -0
- package/dist/browser/chunks/chunk-3GJB6AVO.js +2 -0
- package/dist/browser/chunks/chunk-3GJB6AVO.js.map +7 -0
- package/dist/browser/chunks/chunk-D5WHCVBC.js +2 -0
- package/dist/browser/chunks/chunk-D5WHCVBC.js.map +7 -0
- package/dist/browser/chunks/chunk-WL4KEX7Y.js +2 -0
- package/dist/browser/chunks/chunk-WL4KEX7Y.js.map +7 -0
- package/dist/browser/chunks/mathjax-DNP3YRES.js +61 -0
- package/dist/browser/chunks/mathjax-DNP3YRES.js.map +7 -0
- package/dist/browser/index.js +2 -0
- package/dist/browser/index.js.map +7 -0
- package/dist/browser/kit.js +2 -0
- package/dist/browser/kit.js.map +7 -0
- package/dist/browser/manifest.json +30 -0
- package/dist/browser/tex.js +2 -0
- package/dist/browser/tex.js.map +7 -0
- package/dist/engine.d.ts +64 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +42 -0
- package/dist/engine.js.map +1 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +30 -0
- package/dist/index.js.map +1 -0
- package/dist/kit/brace.d.ts +8 -0
- package/dist/kit/brace.d.ts.map +1 -0
- package/dist/kit/brace.js +36 -0
- package/dist/kit/brace.js.map +1 -0
- package/dist/kit/cache.d.ts +30 -0
- package/dist/kit/cache.d.ts.map +1 -0
- package/dist/kit/cache.js +53 -0
- package/dist/kit/cache.js.map +1 -0
- package/dist/kit/contour.d.ts +8 -0
- package/dist/kit/contour.d.ts.map +1 -0
- package/dist/kit/contour.js +93 -0
- package/dist/kit/contour.js.map +1 -0
- package/dist/kit/coords.d.ts +69 -0
- package/dist/kit/coords.d.ts.map +1 -0
- package/dist/kit/coords.js +224 -0
- package/dist/kit/coords.js.map +1 -0
- package/dist/kit/curve.d.ts +17 -0
- package/dist/kit/curve.d.ts.map +1 -0
- package/dist/kit/curve.js +22 -0
- package/dist/kit/curve.js.map +1 -0
- package/dist/kit/equation.d.ts +61 -0
- package/dist/kit/equation.d.ts.map +1 -0
- package/dist/kit/equation.js +168 -0
- package/dist/kit/equation.js.map +1 -0
- package/dist/kit/equation3d.d.ts +50 -0
- package/dist/kit/equation3d.d.ts.map +1 -0
- package/dist/kit/equation3d.js +103 -0
- package/dist/kit/equation3d.js.map +1 -0
- package/dist/kit/expression.d.ts +35 -0
- package/dist/kit/expression.d.ts.map +1 -0
- package/dist/kit/expression.js +124 -0
- package/dist/kit/expression.js.map +1 -0
- package/dist/kit/field-mark.d.ts +58 -0
- package/dist/kit/field-mark.d.ts.map +1 -0
- package/dist/kit/field-mark.js +129 -0
- package/dist/kit/field-mark.js.map +1 -0
- package/dist/kit/field.d.ts +14 -0
- package/dist/kit/field.d.ts.map +1 -0
- package/dist/kit/field.js +46 -0
- package/dist/kit/field.js.map +1 -0
- package/dist/kit/follow.d.ts +71 -0
- package/dist/kit/follow.d.ts.map +1 -0
- package/dist/kit/follow.js +159 -0
- package/dist/kit/follow.js.map +1 -0
- package/dist/kit/furniture.d.ts +30 -0
- package/dist/kit/furniture.d.ts.map +1 -0
- package/dist/kit/furniture.js +87 -0
- package/dist/kit/furniture.js.map +1 -0
- package/dist/kit/geometry.d.ts +13 -0
- package/dist/kit/geometry.d.ts.map +1 -0
- package/dist/kit/geometry.js +54 -0
- package/dist/kit/geometry.js.map +1 -0
- package/dist/kit/mark.d.ts +47 -0
- package/dist/kit/mark.d.ts.map +1 -0
- package/dist/kit/mark.js +103 -0
- package/dist/kit/mark.js.map +1 -0
- package/dist/kit/part-fills.d.ts +23 -0
- package/dist/kit/part-fills.d.ts.map +1 -0
- package/dist/kit/part-fills.js +46 -0
- package/dist/kit/part-fills.js.map +1 -0
- package/dist/kit/place.d.ts +18 -0
- package/dist/kit/place.d.ts.map +1 -0
- package/dist/kit/place.js +68 -0
- package/dist/kit/place.js.map +1 -0
- package/dist/kit/placement.d.ts +8 -0
- package/dist/kit/placement.d.ts.map +1 -0
- package/dist/kit/placement.js +8 -0
- package/dist/kit/placement.js.map +1 -0
- package/dist/kit/sampler.d.ts +17 -0
- package/dist/kit/sampler.d.ts.map +1 -0
- package/dist/kit/sampler.js +250 -0
- package/dist/kit/sampler.js.map +1 -0
- package/dist/kit/scale.d.ts +12 -0
- package/dist/kit/scale.d.ts.map +1 -0
- package/dist/kit/scale.js +37 -0
- package/dist/kit/scale.js.map +1 -0
- package/dist/kit/source.d.ts +22 -0
- package/dist/kit/source.d.ts.map +1 -0
- package/dist/kit/source.js +45 -0
- package/dist/kit/source.js.map +1 -0
- package/dist/kit/system.d.ts +33 -0
- package/dist/kit/system.d.ts.map +1 -0
- package/dist/kit/system.js +67 -0
- package/dist/kit/system.js.map +1 -0
- package/dist/kit/ticks.d.ts +19 -0
- package/dist/kit/ticks.d.ts.map +1 -0
- package/dist/kit/ticks.js +78 -0
- package/dist/kit/ticks.js.map +1 -0
- package/dist/kit/withdrawn.d.ts +9 -0
- package/dist/kit/withdrawn.d.ts.map +1 -0
- package/dist/kit/withdrawn.js +9 -0
- package/dist/kit/withdrawn.js.map +1 -0
- package/dist/marks/curve-area.d.ts +32 -0
- package/dist/marks/curve-area.d.ts.map +1 -0
- package/dist/marks/curve-area.js +82 -0
- package/dist/marks/curve-area.js.map +1 -0
- package/dist/marks/drop-lines.d.ts +22 -0
- package/dist/marks/drop-lines.d.ts.map +1 -0
- package/dist/marks/drop-lines.js +58 -0
- package/dist/marks/drop-lines.js.map +1 -0
- package/dist/marks/plot-point.d.ts +35 -0
- package/dist/marks/plot-point.d.ts.map +1 -0
- package/dist/marks/plot-point.js +97 -0
- package/dist/marks/plot-point.js.map +1 -0
- package/dist/marks/riemann-sum.d.ts +37 -0
- package/dist/marks/riemann-sum.d.ts.map +1 -0
- package/dist/marks/riemann-sum.js +91 -0
- package/dist/marks/riemann-sum.js.map +1 -0
- package/dist/marks/tangent-line.d.ts +27 -0
- package/dist/marks/tangent-line.d.ts.map +1 -0
- package/dist/marks/tangent-line.js +103 -0
- package/dist/marks/tangent-line.js.map +1 -0
- package/dist/marks/vector-arrow.d.ts +32 -0
- package/dist/marks/vector-arrow.d.ts.map +1 -0
- package/dist/marks/vector-arrow.js +87 -0
- package/dist/marks/vector-arrow.js.map +1 -0
- package/dist/nodes.d.ts +35 -0
- package/dist/nodes.d.ts.map +1 -0
- package/dist/nodes.js +63 -0
- package/dist/nodes.js.map +1 -0
- package/dist/plots/function-plot.d.ts +67 -0
- package/dist/plots/function-plot.d.ts.map +1 -0
- package/dist/plots/function-plot.js +215 -0
- package/dist/plots/function-plot.js.map +1 -0
- package/dist/plots/points-plot.d.ts +28 -0
- package/dist/plots/points-plot.d.ts.map +1 -0
- package/dist/plots/points-plot.js +99 -0
- package/dist/plots/points-plot.js.map +1 -0
- package/dist/plots/stream-lines.d.ts +35 -0
- package/dist/plots/stream-lines.d.ts.map +1 -0
- package/dist/plots/stream-lines.js +141 -0
- package/dist/plots/stream-lines.js.map +1 -0
- package/dist/plots/traced-path.d.ts +31 -0
- package/dist/plots/traced-path.d.ts.map +1 -0
- package/dist/plots/traced-path.js +56 -0
- package/dist/plots/traced-path.js.map +1 -0
- package/dist/plots/vector-field.d.ts +23 -0
- package/dist/plots/vector-field.d.ts.map +1 -0
- package/dist/plots/vector-field.js +91 -0
- package/dist/plots/vector-field.js.map +1 -0
- package/dist/structures/graph-layout.d.ts +11 -0
- package/dist/structures/graph-layout.d.ts.map +1 -0
- package/dist/structures/graph-layout.js +135 -0
- package/dist/structures/graph-layout.js.map +1 -0
- package/dist/structures/network-graph.d.ts +83 -0
- package/dist/structures/network-graph.d.ts.map +1 -0
- package/dist/structures/network-graph.js +289 -0
- package/dist/structures/network-graph.js.map +1 -0
- package/dist/structures/sample-space.d.ts +62 -0
- package/dist/structures/sample-space.d.ts.map +1 -0
- package/dist/structures/sample-space.js +199 -0
- package/dist/structures/sample-space.js.map +1 -0
- package/dist/systems/axes2d.d.ts +75 -0
- package/dist/systems/axes2d.d.ts.map +1 -0
- package/dist/systems/axes2d.js +193 -0
- package/dist/systems/axes2d.js.map +1 -0
- package/dist/systems/number-line.d.ts +49 -0
- package/dist/systems/number-line.d.ts.map +1 -0
- package/dist/systems/number-line.js +127 -0
- package/dist/systems/number-line.js.map +1 -0
- package/dist/systems/number-plane.d.ts +59 -0
- package/dist/systems/number-plane.d.ts.map +1 -0
- package/dist/systems/number-plane.js +193 -0
- package/dist/systems/number-plane.js.map +1 -0
- package/dist/systems/polar-plane.d.ts +48 -0
- package/dist/systems/polar-plane.d.ts.map +1 -0
- package/dist/systems/polar-plane.js +165 -0
- package/dist/systems/polar-plane.js.map +1 -0
- package/dist/tex/geometry.d.ts +85 -0
- package/dist/tex/geometry.d.ts.map +1 -0
- package/dist/tex/geometry.js +632 -0
- package/dist/tex/geometry.js.map +1 -0
- package/dist/tex/index.d.ts +11 -0
- package/dist/tex/index.d.ts.map +1 -0
- package/dist/tex/index.js +9 -0
- package/dist/tex/index.js.map +1 -0
- package/dist/tex/mathjax.d.ts +33 -0
- package/dist/tex/mathjax.d.ts.map +1 -0
- package/dist/tex/mathjax.js +74 -0
- package/dist/tex/mathjax.js.map +1 -0
- package/dist/tex/matrix.d.ts +31 -0
- package/dist/tex/matrix.d.ts.map +1 -0
- package/dist/tex/matrix.js +73 -0
- package/dist/tex/matrix.js.map +1 -0
- package/dist/tex/node.d.ts +215 -0
- package/dist/tex/node.d.ts.map +1 -0
- package/dist/tex/node.js +595 -0
- package/dist/tex/node.js.map +1 -0
- package/dist/tex/tween.d.ts +50 -0
- package/dist/tex/tween.d.ts.map +1 -0
- package/dist/tex/tween.js +253 -0
- package/dist/tex/tween.js.map +1 -0
- package/dist/three/axes3d.d.ts +87 -0
- package/dist/three/axes3d.d.ts.map +1 -0
- package/dist/three/axes3d.js +228 -0
- package/dist/three/axes3d.js.map +1 -0
- package/dist/three/curve-plot3d.d.ts +60 -0
- package/dist/three/curve-plot3d.d.ts.map +1 -0
- package/dist/three/curve-plot3d.js +143 -0
- package/dist/three/curve-plot3d.js.map +1 -0
- package/dist/three/label3d.d.ts +11 -0
- package/dist/three/label3d.d.ts.map +1 -0
- package/dist/three/label3d.js +40 -0
- package/dist/three/label3d.js.map +1 -0
- package/dist/three/plot-point3d.d.ts +26 -0
- package/dist/three/plot-point3d.d.ts.map +1 -0
- package/dist/three/plot-point3d.js +60 -0
- package/dist/three/plot-point3d.js.map +1 -0
- package/dist/three/space.d.ts +28 -0
- package/dist/three/space.d.ts.map +1 -0
- package/dist/three/space.js +47 -0
- package/dist/three/space.js.map +1 -0
- package/dist/three/surface-plot3d.d.ts +80 -0
- package/dist/three/surface-plot3d.d.ts.map +1 -0
- package/dist/three/surface-plot3d.js +290 -0
- package/dist/three/surface-plot3d.js.map +1 -0
- package/dist/three/vector-arrow3d.d.ts +25 -0
- package/dist/three/vector-arrow3d.d.ts.map +1 -0
- package/dist/three/vector-arrow3d.js +72 -0
- package/dist/three/vector-arrow3d.js.map +1 -0
- package/package.json +79 -3
- package/registry.json +251 -0
- package/src/annotate/angle-mark.ts +147 -0
- package/src/annotate/curly-brace.ts +126 -0
- package/src/annotate/emphasis-mark.ts +89 -0
- package/src/engine.ts +72 -0
- package/src/index.ts +29 -0
- package/src/kit/brace.ts +37 -0
- package/src/kit/cache.ts +61 -0
- package/src/kit/contour.ts +94 -0
- package/src/kit/coords.ts +278 -0
- package/src/kit/curve.ts +29 -0
- package/src/kit/equation.ts +181 -0
- package/src/kit/equation3d.ts +137 -0
- package/src/kit/expression.ts +159 -0
- package/src/kit/field-mark.ts +155 -0
- package/src/kit/field.ts +50 -0
- package/src/kit/follow.ts +203 -0
- package/src/kit/furniture.ts +108 -0
- package/src/kit/geometry.ts +49 -0
- package/src/kit/mark.ts +131 -0
- package/src/kit/part-fills.ts +61 -0
- package/src/kit/place.ts +101 -0
- package/src/kit/placement.ts +8 -0
- package/src/kit/sampler.ts +281 -0
- package/src/kit/scale.ts +39 -0
- package/src/kit/source.ts +57 -0
- package/src/kit/system.ts +99 -0
- package/src/kit/ticks.ts +85 -0
- package/src/kit/withdrawn.ts +8 -0
- package/src/marks/curve-area.ts +89 -0
- package/src/marks/drop-lines.ts +63 -0
- package/src/marks/plot-point.ts +107 -0
- package/src/marks/riemann-sum.ts +98 -0
- package/src/marks/tangent-line.ts +103 -0
- package/src/marks/vector-arrow.ts +98 -0
- package/src/nodes.ts +63 -0
- package/src/plots/function-plot.ts +236 -0
- package/src/plots/points-plot.ts +107 -0
- package/src/plots/stream-lines.ts +151 -0
- package/src/plots/traced-path.ts +52 -0
- package/src/plots/vector-field.ts +88 -0
- package/src/structures/graph-layout.ts +145 -0
- package/src/structures/network-graph.ts +308 -0
- package/src/structures/sample-space.ts +209 -0
- package/src/systems/axes2d.ts +217 -0
- package/src/systems/number-line.ts +131 -0
- package/src/systems/number-plane.ts +203 -0
- package/src/systems/polar-plane.ts +176 -0
- package/src/tex/geometry.ts +703 -0
- package/src/tex/index.ts +14 -0
- package/src/tex/mathjax.ts +82 -0
- package/src/tex/matrix.ts +75 -0
- package/src/tex/node.ts +641 -0
- package/src/tex/tween.ts +308 -0
- package/src/three/axes3d.ts +240 -0
- package/src/three/curve-plot3d.ts +147 -0
- package/src/three/label3d.ts +50 -0
- package/src/three/plot-point3d.ts +66 -0
- package/src/three/space.ts +67 -0
- package/src/three/surface-plot3d.ts +323 -0
- package/src/three/vector-arrow3d.ts +77 -0
|
@@ -0,0 +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
|
+
}
|