@motionscript/math 0.1.0-alpha.5 → 0.1.0-alpha.7

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 (233) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +39 -33
  3. package/dist/annotate/angle-mark.d.ts +77 -27
  4. package/dist/annotate/angle-mark.d.ts.map +1 -1
  5. package/dist/annotate/angle-mark.js +80 -115
  6. package/dist/annotate/angle-mark.js.map +1 -1
  7. package/dist/annotate/curly-brace.d.ts +94 -25
  8. package/dist/annotate/curly-brace.d.ts.map +1 -1
  9. package/dist/annotate/curly-brace.js +85 -100
  10. package/dist/annotate/curly-brace.js.map +1 -1
  11. package/dist/annotate/emphasis-mark.d.ts +69 -9
  12. package/dist/annotate/emphasis-mark.d.ts.map +1 -1
  13. package/dist/annotate/emphasis-mark.js +33 -34
  14. package/dist/annotate/emphasis-mark.js.map +1 -1
  15. package/dist/browser/chunks/chunk-ABYBW64J.js +2 -0
  16. package/dist/browser/chunks/chunk-ABYBW64J.js.map +7 -0
  17. package/dist/browser/chunks/chunk-K77KLQX4.js +2 -0
  18. package/dist/browser/chunks/chunk-K77KLQX4.js.map +7 -0
  19. package/dist/browser/index.js +1 -1
  20. package/dist/browser/index.js.map +3 -3
  21. package/dist/browser/kit.js +1 -1
  22. package/dist/browser/manifest.json +1 -1
  23. package/dist/browser/tex.js +1 -1
  24. package/dist/browser/tex.js.map +2 -2
  25. package/dist/engine.d.ts +26 -19
  26. package/dist/engine.d.ts.map +1 -1
  27. package/dist/engine.js +17 -14
  28. package/dist/engine.js.map +1 -1
  29. package/dist/kit/component.d.ts +51 -0
  30. package/dist/kit/component.d.ts.map +1 -0
  31. package/dist/kit/component.js +30 -0
  32. package/dist/kit/component.js.map +1 -0
  33. package/dist/kit/curve.d.ts +22 -11
  34. package/dist/kit/curve.d.ts.map +1 -1
  35. package/dist/kit/curve.js +25 -18
  36. package/dist/kit/curve.js.map +1 -1
  37. package/dist/kit/field-mark.d.ts +56 -35
  38. package/dist/kit/field-mark.d.ts.map +1 -1
  39. package/dist/kit/field-mark.js +100 -120
  40. package/dist/kit/field-mark.js.map +1 -1
  41. package/dist/kit/follow.d.ts +67 -29
  42. package/dist/kit/follow.d.ts.map +1 -1
  43. package/dist/kit/follow.js +114 -110
  44. package/dist/kit/follow.js.map +1 -1
  45. package/dist/kit/furniture.d.ts +3 -1
  46. package/dist/kit/furniture.d.ts.map +1 -1
  47. package/dist/kit/furniture.js +5 -0
  48. package/dist/kit/furniture.js.map +1 -1
  49. package/dist/kit/graph.d.ts +46 -0
  50. package/dist/kit/graph.d.ts.map +1 -0
  51. package/dist/kit/graph.js +90 -0
  52. package/dist/kit/graph.js.map +1 -0
  53. package/dist/kit/mark.d.ts +64 -39
  54. package/dist/kit/mark.d.ts.map +1 -1
  55. package/dist/kit/mark.js +80 -96
  56. package/dist/kit/mark.js.map +1 -1
  57. package/dist/kit/place.d.ts +10 -8
  58. package/dist/kit/place.d.ts.map +1 -1
  59. package/dist/kit/place.js +28 -30
  60. package/dist/kit/place.js.map +1 -1
  61. package/dist/kit/system.d.ts +27 -29
  62. package/dist/kit/system.d.ts.map +1 -1
  63. package/dist/kit/system.js +62 -58
  64. package/dist/kit/system.js.map +1 -1
  65. package/dist/kit/withdrawn.d.ts +3 -3
  66. package/dist/kit/withdrawn.js +3 -3
  67. package/dist/kit/withdrawn.js.map +1 -1
  68. package/dist/marks/curve-area.d.ts +37 -18
  69. package/dist/marks/curve-area.d.ts.map +1 -1
  70. package/dist/marks/curve-area.js +50 -73
  71. package/dist/marks/curve-area.js.map +1 -1
  72. package/dist/marks/drop-lines.d.ts +45 -10
  73. package/dist/marks/drop-lines.d.ts.map +1 -1
  74. package/dist/marks/drop-lines.js +37 -52
  75. package/dist/marks/drop-lines.js.map +1 -1
  76. package/dist/marks/plot-point.d.ts +56 -20
  77. package/dist/marks/plot-point.d.ts.map +1 -1
  78. package/dist/marks/plot-point.js +65 -91
  79. package/dist/marks/plot-point.js.map +1 -1
  80. package/dist/marks/riemann-sum.d.ts +47 -26
  81. package/dist/marks/riemann-sum.d.ts.map +1 -1
  82. package/dist/marks/riemann-sum.js +57 -85
  83. package/dist/marks/riemann-sum.js.map +1 -1
  84. package/dist/marks/tangent-line.d.ts +58 -14
  85. package/dist/marks/tangent-line.d.ts.map +1 -1
  86. package/dist/marks/tangent-line.js +73 -87
  87. package/dist/marks/tangent-line.js.map +1 -1
  88. package/dist/marks/vector-arrow.d.ts +48 -20
  89. package/dist/marks/vector-arrow.d.ts.map +1 -1
  90. package/dist/marks/vector-arrow.js +58 -78
  91. package/dist/marks/vector-arrow.js.map +1 -1
  92. package/dist/nodes.d.ts +13 -5
  93. package/dist/nodes.d.ts.map +1 -1
  94. package/dist/nodes.js +0 -6
  95. package/dist/nodes.js.map +1 -1
  96. package/dist/plots/function-plot.d.ts +135 -43
  97. package/dist/plots/function-plot.d.ts.map +1 -1
  98. package/dist/plots/function-plot.js +146 -177
  99. package/dist/plots/function-plot.js.map +1 -1
  100. package/dist/plots/points-plot.d.ts +55 -19
  101. package/dist/plots/points-plot.d.ts.map +1 -1
  102. package/dist/plots/points-plot.js +31 -58
  103. package/dist/plots/points-plot.js.map +1 -1
  104. package/dist/plots/stream-lines.d.ts +60 -19
  105. package/dist/plots/stream-lines.d.ts.map +1 -1
  106. package/dist/plots/stream-lines.js +60 -79
  107. package/dist/plots/stream-lines.js.map +1 -1
  108. package/dist/plots/traced-path.d.ts +54 -15
  109. package/dist/plots/traced-path.d.ts.map +1 -1
  110. package/dist/plots/traced-path.js +33 -48
  111. package/dist/plots/traced-path.js.map +1 -1
  112. package/dist/plots/vector-field.d.ts +48 -11
  113. package/dist/plots/vector-field.d.ts.map +1 -1
  114. package/dist/plots/vector-field.js +50 -64
  115. package/dist/plots/vector-field.js.map +1 -1
  116. package/dist/structures/network-graph.d.ts +140 -49
  117. package/dist/structures/network-graph.d.ts.map +1 -1
  118. package/dist/structures/network-graph.js +168 -217
  119. package/dist/structures/network-graph.js.map +1 -1
  120. package/dist/structures/sample-space.d.ts +90 -38
  121. package/dist/structures/sample-space.d.ts.map +1 -1
  122. package/dist/structures/sample-space.js +132 -170
  123. package/dist/structures/sample-space.js.map +1 -1
  124. package/dist/systems/axes2d.d.ts +159 -37
  125. package/dist/systems/axes2d.d.ts.map +1 -1
  126. package/dist/systems/axes2d.js +147 -183
  127. package/dist/systems/axes2d.js.map +1 -1
  128. package/dist/systems/number-line.d.ts +80 -28
  129. package/dist/systems/number-line.d.ts.map +1 -1
  130. package/dist/systems/number-line.js +82 -118
  131. package/dist/systems/number-line.js.map +1 -1
  132. package/dist/systems/number-plane.d.ts +140 -31
  133. package/dist/systems/number-plane.d.ts.map +1 -1
  134. package/dist/systems/number-plane.js +142 -149
  135. package/dist/systems/number-plane.js.map +1 -1
  136. package/dist/systems/polar-plane.d.ts +76 -26
  137. package/dist/systems/polar-plane.d.ts.map +1 -1
  138. package/dist/systems/polar-plane.js +107 -133
  139. package/dist/systems/polar-plane.js.map +1 -1
  140. package/dist/tex/index.d.ts.map +1 -1
  141. package/dist/tex/index.js +1 -0
  142. package/dist/tex/index.js.map +1 -1
  143. package/dist/tex/matrix.d.ts +88 -18
  144. package/dist/tex/matrix.d.ts.map +1 -1
  145. package/dist/tex/matrix.js +33 -50
  146. package/dist/tex/matrix.js.map +1 -1
  147. package/dist/tex/node.d.ts +84 -201
  148. package/dist/tex/node.d.ts.map +1 -1
  149. package/dist/tex/node.js +23 -593
  150. package/dist/tex/node.js.map +1 -1
  151. package/dist/tex/typeset.d.ts +133 -0
  152. package/dist/tex/typeset.d.ts.map +1 -0
  153. package/dist/tex/typeset.js +403 -0
  154. package/dist/tex/typeset.js.map +1 -0
  155. package/dist/three/axes3d.d.ts +214 -54
  156. package/dist/three/axes3d.d.ts.map +1 -1
  157. package/dist/three/axes3d.js +163 -204
  158. package/dist/three/axes3d.js.map +1 -1
  159. package/dist/three/curve-plot3d.d.ts +108 -42
  160. package/dist/three/curve-plot3d.d.ts.map +1 -1
  161. package/dist/three/curve-plot3d.js +97 -132
  162. package/dist/three/curve-plot3d.js.map +1 -1
  163. package/dist/three/entries.d.ts +17 -0
  164. package/dist/three/entries.d.ts.map +1 -0
  165. package/dist/three/entries.js +15 -0
  166. package/dist/three/entries.js.map +1 -0
  167. package/dist/three/plot-point3d.d.ts +85 -12
  168. package/dist/three/plot-point3d.d.ts.map +1 -1
  169. package/dist/three/plot-point3d.js +27 -53
  170. package/dist/three/plot-point3d.js.map +1 -1
  171. package/dist/three/space.d.ts +17 -2
  172. package/dist/three/space.d.ts.map +1 -1
  173. package/dist/three/space.js +19 -8
  174. package/dist/three/space.js.map +1 -1
  175. package/dist/three/surface-plot3d.d.ts +176 -49
  176. package/dist/three/surface-plot3d.d.ts.map +1 -1
  177. package/dist/three/surface-plot3d.js +227 -261
  178. package/dist/three/surface-plot3d.js.map +1 -1
  179. package/dist/three/vector-arrow3d.d.ts +87 -16
  180. package/dist/three/vector-arrow3d.d.ts.map +1 -1
  181. package/dist/three/vector-arrow3d.js +48 -67
  182. package/dist/three/vector-arrow3d.js.map +1 -1
  183. package/package.json +4 -4
  184. package/src/annotate/angle-mark.ts +95 -105
  185. package/src/annotate/curly-brace.ts +107 -85
  186. package/src/annotate/emphasis-mark.ts +55 -26
  187. package/src/engine.ts +35 -21
  188. package/src/kit/component.ts +57 -0
  189. package/src/kit/curve.ts +38 -20
  190. package/src/kit/field-mark.ts +124 -108
  191. package/src/kit/follow.ts +146 -120
  192. package/src/kit/furniture.ts +6 -1
  193. package/src/kit/graph.ts +116 -0
  194. package/src/kit/mark.ts +135 -114
  195. package/src/kit/place.ts +32 -56
  196. package/src/kit/system.ts +77 -71
  197. package/src/kit/withdrawn.ts +3 -3
  198. package/src/marks/curve-area.ts +65 -65
  199. package/src/marks/drop-lines.ts +50 -42
  200. package/src/marks/plot-point.ts +77 -82
  201. package/src/marks/riemann-sum.ts +73 -72
  202. package/src/marks/tangent-line.ts +87 -71
  203. package/src/marks/vector-arrow.ts +73 -73
  204. package/src/nodes.ts +41 -5
  205. package/src/plots/function-plot.ts +155 -171
  206. package/src/plots/points-plot.ts +46 -50
  207. package/src/plots/stream-lines.ts +75 -66
  208. package/src/plots/traced-path.ts +51 -33
  209. package/src/plots/vector-field.ts +68 -49
  210. package/src/structures/network-graph.ts +168 -185
  211. package/src/structures/sample-space.ts +149 -148
  212. package/src/systems/axes2d.ts +165 -156
  213. package/src/systems/number-line.ts +91 -92
  214. package/src/systems/number-plane.ts +149 -120
  215. package/src/systems/polar-plane.ts +117 -116
  216. package/src/tex/index.ts +2 -1
  217. package/src/tex/matrix.ts +62 -40
  218. package/src/tex/node.ts +54 -621
  219. package/src/tex/typeset.ts +461 -0
  220. package/src/three/axes3d.ts +187 -160
  221. package/src/three/curve-plot3d.ts +107 -110
  222. package/src/three/entries.ts +42 -0
  223. package/src/three/plot-point3d.ts +42 -45
  224. package/src/three/space.ts +34 -9
  225. package/src/three/surface-plot3d.ts +312 -323
  226. package/src/three/vector-arrow3d.ts +65 -54
  227. package/dist/browser/chunks/chunk-3GJB6AVO.js +0 -2
  228. package/dist/browser/chunks/chunk-3GJB6AVO.js.map +0 -7
  229. package/dist/browser/chunks/chunk-D5WHCVBC.js +0 -2
  230. package/dist/browser/chunks/chunk-D5WHCVBC.js.map +0 -7
  231. package/dist/browser/chunks/chunk-WL4KEX7Y.js +0 -2
  232. package/dist/browser/chunks/chunk-WL4KEX7Y.js.map +0 -7
  233. package/src/kit/placement.ts +0 -8
package/dist/tex/node.js CHANGED
@@ -1,595 +1,25 @@
1
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- };
7
- import { Graphics2D, command, node, lerpNumber, pathOps, ShapeNode, toPathString, property, insetsProperty, driveCommand, fillOps, withdraw, } from "@motionscript/sdk";
8
- // From each module, never the `../engine` barrel: it re-exports this file, so a
9
- // load that enters through the barrel runs this class's decorators before
10
- // `OUTLINE_TRIM` exists and the kit fails to import.
11
- import { blankLatex, buildLatexPath, findLatexParts, LatexNotLoaded, loadMathJax, MATHJAX_LOADER, } from "./geometry.js";
12
- import { defaultLatexMorph } from "./tween.js";
13
- import { lerpPartFills, partPaint, readPartFills, withPartFill, } from "../kit/part-fills.js";
14
- import { OUTLINE_TRIM } from "../kit/withdrawn.js";
15
- /** How much of one glyph's writing overlaps the next one's. */
16
- const WRITE_OVERLAP = 0.6;
17
- /** The outline a glyph is written with, as a share of the type size. */
18
- const WRITE_STROKE = 1 / 32;
19
- let Latex = class Latex extends ShapeNode {
20
- /**
21
- * How this node morphs between two formulas. Construction-time-only (see
22
- * {@link LatexStrategies}) — resolved once here rather than left as
23
- * `?? defaultLatexMorph` at every call site.
24
- */
25
- morph;
26
- _intrinsicWidth = 0;
27
- _intrinsicHeight = 0;
28
- /**
29
- * Shared center frame for all current tokens, [minX, minY, maxX, maxY] in
30
- * token space. Passed to every per-token path so glyphs keep their relative
31
- * layout instead of each centering on its own bbox.
32
- */
33
- _bounds = [0, 0, 0, 0];
34
- /** Current tokens to render. Each has its own opacity for tween transitions. */
35
- _tokens = [];
36
- /** The parts of the formula `_tokens` was built from; empty while a morph holds the tokens. */
37
- _parts = [];
38
- /** While a morph holds the tokens: each end's colours by token, and how far between them it is. */
39
- _morphFills = null;
40
- /** Suppresses retokenization while a custom to() is driving frames. */
41
- _animating = false;
42
- /** The `fontSize|latex` the live tokens were built from. See {@link _ensureTokens}. */
43
- _tokenizedFrom = null;
44
- constructor(props) {
45
- super(props);
46
- this.morph = props?.morph ?? defaultLatexMorph;
47
- this.applyProp("width", props?.width ?? "hug");
48
- this.applyProp("height", props?.height ?? "hug");
49
- this._ensureTokens();
50
- }
51
- /**
52
- * Rebuild the token list when the formula or size has moved since it last
53
- * was built.
54
- *
55
- * Pulled from every reader rather than pushed from a prop write, because
56
- * `latex` can be a binding — and a binding has no write to hang a
57
- * subscription on. The key is what the current tokens were built from;
58
- * `_animating` hands ownership to the morph command for its open interval.
59
- */
60
- _ensureTokens() {
61
- if (this._animating) {
62
- if (this.morphProgress > 0 && this.morphProgress < 1)
63
- return;
64
- // The playhead left the morph without it committing either end (a seek
65
- // back to before it evaluates no command), so what is held is a stale
66
- // morph frame. Hand the tokens back to the props.
67
- this._animating = false;
68
- this._morphFills = null;
69
- this._tokenizedFrom = null;
70
- }
71
- const key = `${this.fontSize}|${this._source()}`;
72
- if (key === this._tokenizedFrom)
73
- return;
74
- // Recorded once the tokens are built, so a formula that cannot be
75
- // typeset fails on every read instead of the first and then reads as
76
- // blank. Before MathJax is here the node is blank, and is asked again.
77
- try {
78
- this._updateTokens();
79
- }
80
- catch (error) {
81
- if (!(error instanceof LatexNotLoaded))
82
- throw error;
83
- this._clearTokens();
84
- return;
85
- }
86
- this._tokenizedFrom = key;
87
- }
88
- /** MathJax, before this node is laid out: a scene with no formula in it never loads it. */
89
- declareAssets(assets) {
90
- super.declareAssets(assets);
91
- assets.loader(MATHJAX_LOADER, loadMathJax, { gate: "layout" });
92
- }
93
- /** @internal The formula typeset once `next` is laid over the node's own props: `latex` here, a subclass's own props there. */
94
- _source(next = {}) {
95
- return next.latex ?? this.latex;
96
- }
97
- /** @internal The props that state the formula, as `next` leaves them: what a morph commits at its end. */
98
- _sourceProps(next = {}) {
99
- return { latex: this._source(next) };
100
- }
101
- /** @internal Whether `next` re-sets the glyphs, and so is a morph rather than an ordinary tween. */
102
- _resets(next) {
103
- return next.latex !== undefined || next.fontSize !== undefined;
104
- }
105
- _updateTokens() {
106
- const source = this._source();
107
- if (source) {
108
- const result = buildLatexPath(source, this.fontSize);
109
- this._intrinsicWidth = result.width;
110
- this._intrinsicHeight = result.height;
111
- this._bounds = result.bounds;
112
- this._parts = result.parts;
113
- this._tokens = result.tokens.map(t => ({
114
- token: t.token,
115
- path: t.path,
116
- term: t.term,
117
- opacity: 1,
118
- x: 0,
119
- y: 0,
120
- }));
121
- }
122
- else {
123
- this._clearTokens();
124
- }
125
- }
126
- _clearTokens() {
127
- this._tokens = [];
128
- this._parts = [];
129
- this._intrinsicWidth = 0;
130
- this._intrinsicHeight = 0;
131
- this._bounds = [0, 0, 0, 0];
132
- }
133
- measure(constraints) {
134
- this._ensureTokens();
135
- const pad = this.padding;
136
- const wm = this.width;
137
- const hm = this.height;
138
- const resolvedW = typeof wm === "number"
139
- ? wm
140
- : wm === "hug"
141
- ? this._intrinsicWidth + pad.left + pad.right
142
- : constraints.maxWidth ?? 0;
143
- const resolvedH = typeof hm === "number"
144
- ? hm
145
- : hm === "hug"
146
- ? this._intrinsicHeight + pad.top + pad.bottom
147
- : constraints.maxHeight ?? 0;
148
- return { width: resolvedW, height: resolvedH };
149
- }
150
- /**
151
- * A LaTeX morph — one {@link Command}, like every other `to()`.
152
- *
153
- * Sequence two of them with `sequence(...)` rather than chaining: the chain
154
- * builder this used to return existed only so `latexRef().to(a, 1).to(b, 1)`
155
- * would read as two steps, and it could not compose with anything that was
156
- * not another Latex morph.
157
- */
158
- to(args) {
159
- const data = args.data ?? {};
160
- // Only a new formula or size re-sets the glyphs; anything else is an ordinary tween.
161
- if (!this._resets(data))
162
- return super.to(args);
163
- return this._buildMorph(data, args.duration, args.easing);
164
- }
165
- /**
166
- * Morph this formula into another — a document-facing name for {@link to},
167
- * which already routes through {@link _buildMorph}.
168
- */
169
- morphTo(args) {
170
- return this.to({ data: { latex: args.data?.latex }, duration: args.duration, easing: args.easing });
171
- }
172
- /** Write the formula on, or off: its glyphs one after another, each outlined and then filled. */
173
- writeTo(args) {
174
- const written = args.data?.written;
175
- return super.to({ data: written === undefined ? {} : { written }, duration: args.duration, easing: args.easing });
176
- }
177
- /** Paint one part of the formula, leaving the rest as it is. */
178
- partFillTo(args) {
179
- const { part, fill, occurrence = 0 } = args.data ?? {};
180
- if (!part || fill == null)
181
- return super.to({ data: {}, duration: args.duration, easing: args.easing });
182
- const partFills = withPartFill(this.partFills, { part, fill, occurrence });
183
- return super.to({ data: { partFills }, duration: args.duration, easing: args.easing });
184
- }
185
- /**
186
- * The box around one part of the formula, centred on the node's own centre
187
- * and y-up, or `null` when the formula does not write `part`. `occurrence`
188
- * counts from 1.
189
- */
190
- partBounds(part, occurrence = 1) {
191
- this._ensureTokens();
192
- const span = findLatexParts(this._parts, part)[Math.max(1, Math.round(occurrence)) - 1];
193
- if (!span)
194
- return null;
195
- const box = pathOps.bounds(this._tokens.slice(span[0], span[1]).flatMap((token) => token.path));
196
- if (!box)
197
- return null;
198
- const [minX, minY, maxX, maxY] = this._bounds;
199
- const cx = (minX + maxX) / 2;
200
- const cy = (minY + maxY) / 2;
201
- return {
202
- x: (box.minX + box.maxX) / 2 - cx,
203
- y: cy - (box.minY + box.maxY) / 2,
204
- width: box.maxX - box.minX,
205
- height: box.maxY - box.minY,
206
- };
207
- }
208
- /**
209
- * Build a single LaTeX morph as a {@link Command}: every ordinary
210
- * `ShapeProps` field (via the inherited `_prepareStep`), plus the
211
- * intrinsic size, shared center frame and per-glyph token list — state a
212
- * plain `set()` can't reach — driven together by one eased `t`, matching
213
- * the concurrent `parallel` the generator version ran.
214
- *
215
- * The "from" snapshot (`fromTokens`, `fromLatex`, …) is captured
216
- * **lazily, on the command's first evaluation**, not when this is called.
217
- * That is what lets two morphs be sequenced: `commandSequence` settles each
218
- * prior step before evaluating the next, so a second morph's "from" reads
219
- * the first one's end state rather than whatever the node held before either
220
- * of them ran.
221
- *
222
- * `_animating` suppresses {@link _ensureTokens} for the open interval, and
223
- * both ends commit: `t === 1`
224
- * lands on the target formula, `t === 0` restores the source one — the same
225
- * "membership for the open interval, commit at either end" shape
226
- * `packages/components/code`'s `runTransition` uses, so seeking into either
227
- * side of the morph (not just running it forward) shows the right thing.
228
- *
229
- * `@internal` — the entry point for authors is {@link to}.
230
- */
231
- _buildMorph(to, duration, easing) {
232
- // Not in a tree: no box, no timeline. The command keeps its length and
233
- // writes nothing, as every command built through `Node` does.
234
- if (!this.mounted)
235
- return driveCommand(duration, () => { });
236
- let setupDone = false;
237
- let fromAnimTokens = [];
238
- let fromLatex = "";
239
- let fromProps = {};
240
- let fromFontSize = 0;
241
- let fromWidth = 0;
242
- let fromHeight = 0;
243
- let fromBounds = [0, 0, 0, 0];
244
- let fromParts = [];
245
- let fromFills = [];
246
- let toFills = [];
247
- let toFontSize = 0;
248
- let toLatex = "";
249
- let toResult;
250
- let propStep;
251
- let latexFrame;
252
- const setup = () => {
253
- setupDone = true;
254
- this._ensureTokens();
255
- const fromTokens = this._tokens.map(t => ({ token: t.token, path: t.path, term: t.term }));
256
- fromAnimTokens = this._tokens.map(t => ({ ...t }));
257
- fromLatex = this._source();
258
- fromProps = this._sourceProps();
259
- fromFontSize = this.fontSize;
260
- fromWidth = this._intrinsicWidth;
261
- fromHeight = this._intrinsicHeight;
262
- fromBounds = this._bounds;
263
- fromParts = this._parts;
264
- toFontSize = to.fontSize !== undefined ? to.fontSize : this.fontSize;
265
- toLatex = this._source(to);
266
- try {
267
- toResult = buildLatexPath(toLatex, toFontSize);
268
- }
269
- catch (error) {
270
- if (!(error instanceof LatexNotLoaded))
271
- throw error;
272
- toResult = blankLatex();
273
- }
274
- propStep = this._prepareStep(to, duration);
275
- latexFrame = this.morph(fromTokens, toResult.tokens);
276
- const partFills = this.partFills;
277
- fromFills = fillsByToken(partFills, fromParts, fromTokens.length);
278
- toFills = fillsByToken(partFills, toResult.parts, toResult.tokens.length);
279
- };
280
- return driveCommand(duration, (t) => {
281
- if (!setupDone)
282
- setup();
283
- const toBounds = toResult.bounds;
284
- this._animating = true;
285
- this.morphProgress = t;
286
- propStep.seek(t * duration);
287
- this.set({ fontSize: lerpNumber(fromFontSize, toFontSize, t) });
288
- // Track the measured size so a hugging box grows/shrinks smoothly
289
- // across the morph rather than jumping when the end commits.
290
- this._intrinsicWidth = lerpNumber(fromWidth, toResult.width, t);
291
- this._intrinsicHeight = lerpNumber(fromHeight, toResult.height, t);
292
- // Interpolate the shared center frame in lockstep so glyphs stay
293
- // centered within the resizing box.
294
- this._bounds = [
295
- lerpNumber(fromBounds[0], toBounds[0], t),
296
- lerpNumber(fromBounds[1], toBounds[1], t),
297
- lerpNumber(fromBounds[2], toBounds[2], t),
298
- lerpNumber(fromBounds[3], toBounds[3], t),
299
- ];
300
- this._tokens = latexFrame(t);
301
- this._parts = [];
302
- this._morphFills = { from: fromFills, to: toFills, t };
303
- if (t >= 1) {
304
- this.set({ ...this._sourceProps(to), fontSize: toFontSize });
305
- this._parts = toResult.parts;
306
- this._tokens = toResult.tokens.map(tok => ({ token: tok.token, path: tok.path, term: tok.term, opacity: 1, x: 0, y: 0 }));
307
- this._intrinsicWidth = toResult.width;
308
- this._intrinsicHeight = toResult.height;
309
- this._bounds = toResult.bounds;
310
- this._animating = false;
311
- this._morphFills = null;
312
- this.morphProgress = 0;
313
- this._tokenizedFrom = `${toFontSize}|${toLatex}`;
314
- }
315
- else if (t <= 0) {
316
- this.set({ ...fromProps, fontSize: fromFontSize });
317
- this._parts = fromParts;
318
- this._tokens = fromAnimTokens;
319
- this._intrinsicWidth = fromWidth;
320
- this._intrinsicHeight = fromHeight;
321
- this._bounds = fromBounds;
322
- this._animating = false;
323
- this._morphFills = null;
324
- this.morphProgress = 0;
325
- this._tokenizedFrom = `${fromFontSize}|${fromLatex}`;
326
- }
327
- }, easing);
328
- }
329
- /**
330
- * The shadow op comes **first**, as it does on every other painted node.
331
- *
332
- * The renderer does not draw a shadow when it sees one: `.shadow()` stores
333
- * it pending and the *next* fill or stroke op casts it (`_shadow` →
334
- * `storePendingShadows`, `_fill`/`_stroke` → `takePendingShadows`). Appended
335
- * last, it was stored by every token and then thrown away by the reset at
336
- * the end of the draw — a shadow set on a LaTeX node simply never appeared,
337
- * with no error to say why. Same failure {@link PaintedNode.renderStroke}
338
- * documents for a fill-less stroked shape, and the same one-op fix.
339
- *
340
- * Order also carries the fill-less case for free: an empty fill returns
341
- * before it takes the pending shadow, so the stroke below casts it from the
342
- * glyph outlines instead — which is what `castsShadowFromStroke` arranges on
343
- * a plain shape.
344
- */
345
- renderSelf(ctx) {
346
- const fills = this.fill;
347
- const shadows = this.shadow;
348
- const partOf = this._tokenFills();
349
- const writing = this._writing();
350
- this.eachToken(ctx, (graphics, opacity, index, token) => {
351
- const fill = partPaint(fills, partOf(index, token));
352
- const pen = writing?.(index);
353
- if (!pen) {
354
- return graphics
355
- .shadow(scaleShadowOpacity(shadows, opacity))
356
- .fill(scaleFillopacity(fill, opacity))
357
- .stroke(this.stroke);
358
- }
359
- if (pen.filled <= 0)
360
- return null;
361
- return graphics
362
- .shadow(scaleShadowOpacity(shadows, opacity * pen.filled))
363
- .fill(scaleFillopacity(fill, opacity * pen.filled))
364
- .stroke(this.stroke);
365
- });
366
- if (!writing)
367
- return;
368
- // The pen's line: each glyph's outline, in its own colour, ahead of its fill.
369
- const own = this.stroke;
370
- this.eachToken(ctx, (graphics, opacity, index, token) => {
371
- const pen = writing(index);
372
- if (!pen || pen.filled >= 1 || pen.outlined <= 0)
373
- return null;
374
- const fill = scaleFillopacity(partPaint(fills, partOf(index, token)), opacity * (1 - pen.filled));
375
- return graphics.stroke(own.length > 0 ? own : penStroke(this.fontSize * WRITE_STROKE, fill));
376
- }, (index) => writing(index)?.outlined ?? 1);
377
- }
378
- /** Each token's part fill: by its place in the formula at rest, by both ends' mid-morph. */
379
- _tokenFills() {
380
- const morph = this._morphFills;
381
- if (morph) {
382
- return (_index, token) => {
383
- const a = token.from === undefined ? undefined : morph.from[token.from];
384
- const b = token.to === undefined ? undefined : morph.to[token.to];
385
- if (a && b)
386
- return { ...b, fill: fillOps.lerp(a.fill, b.fill, morph.t), mix: lerpNumber(a.mix, b.mix, morph.t) };
387
- if (a)
388
- return token.to === undefined ? a : { ...a, mix: a.mix * (1 - morph.t) };
389
- if (b)
390
- return token.from === undefined ? b : { ...b, mix: b.mix * morph.t };
391
- return undefined;
392
- };
393
- }
394
- const partFills = this.partFills;
395
- if (partFills.length === 0)
396
- return () => undefined;
397
- const byToken = fillsByToken(partFills, this._parts, this._tokens.length);
398
- return (index) => byToken[index];
399
- }
400
- /**
401
- * How far each glyph is written at the node's `written`: its outline first,
402
- * then its fill, each glyph starting before the one ahead of it is done.
403
- * `null` once the whole formula is.
404
- */
405
- _writing() {
406
- const written = this.written;
407
- if (written >= 1)
408
- return null;
409
- const count = this._tokens.length;
410
- const lead = 1 - WRITE_OVERLAP;
411
- const span = 1 / (1 + Math.max(0, count - 1) * lead);
412
- return (index) => {
413
- const p = Math.min(1, Math.max(0, (written - index * span * lead) / span));
414
- return { outlined: Math.min(1, p * 2), filled: Math.max(0, p * 2 - 1) };
415
- };
416
- }
417
- /**
418
- * The overlay, painted *through* the glyphs.
419
- *
420
- * `ShapeNode`'s inherited overlay pass fills whatever {@link
421
- * ShapeNode.shapeGraphics} describes, and this node describes nothing there:
422
- * a formula has no single fillable silhouette — its silhouette *is* the list
423
- * of token paths, which is why `renderSelf` is overridden rather than a
424
- * `shapeGraphics` supplied. So the generic pass drew nothing and an overlay
425
- * set on a LaTeX node simply never appeared, with no error to say why.
426
- *
427
- * Painted the same way the fill is: one `Graphics2D` per token, all sharing the
428
- * centre frame, each scaled by its token's animated opacity — so a morph
429
- * carries the overlay along with the glyph it is laid over instead of leaving
430
- * a wash hanging over glyphs that have faded out.
431
- *
432
- * The stroke is *not* re-drawn here. `renderSelf` already strokes each token
433
- * (there is no silhouette for the deferred {@link ShapeNode.renderStroke} to
434
- * outline), so it is painted under the overlay rather than over it — the one
435
- * place this node's draw order differs from a plain shape's, and the price of
436
- * a stroke that follows glyphs rather than a box.
437
- */
438
- renderOverlay(ctx) {
439
- const overlay = this.overlay;
440
- if (overlay.length === 0)
441
- return;
442
- const writing = this._writing();
443
- this.eachToken(ctx, (graphics, opacity, index) => {
444
- const filled = writing?.(index).filled ?? 1;
445
- return filled <= 0 ? null : graphics.fill(scaleFillopacity(overlay, opacity * filled));
446
- });
447
- }
448
- /**
449
- * Draws every visible token's path once, handing each one to `paint` to have
450
- * its paint ops appended.
451
- *
452
- * A fresh `Graphics2D` per token per pass, because `.fill()`/`.stroke()` push
453
- * onto one op list and return `this` — a silhouette shared between the fill
454
- * pass and the overlay pass would accumulate both.
455
- */
456
- eachToken(ctx, paint, drawn = () => 1) {
457
- // The one funnel every paint pass goes through, so the tokens a frame
458
- // draws cannot be older than the formula it holds.
459
- this._ensureTokens();
460
- this._tokens.forEach((token, index) => {
461
- if (token.opacity <= 0)
462
- return;
463
- // Translate the path by token's interpolated position offset
464
- const pathStr = token.x !== 0 || token.y !== 0
465
- ? toPathString(offsetPath(token.path, token.x, token.y))
466
- : toPathString(token.path);
467
- const painted = paint(new Graphics2D()
468
- .path({
469
- data: pathStr,
470
- start: this.start,
471
- end: this.end * drawn(index),
472
- // All tokens share one center frame so they keep their relative
473
- // layout — without this each glyph centers on its own bbox and
474
- // they all stack on the origin.
475
- centerBounds: this._bounds,
476
- }), token.opacity, index, token);
477
- if (painted)
478
- ctx.draw(painted);
479
- });
480
- }
481
- };
482
- __decorate([
483
- property({ default: "" })
484
- ], Latex.prototype, "latex", void 0);
485
- __decorate([
486
- property({ default: 16 })
487
- ], Latex.prototype, "fontSize", void 0);
488
- __decorate([
489
- insetsProperty()
490
- ], Latex.prototype, "padding", void 0);
491
- __decorate([
492
- property({ default: [], mapper: readPartFills, tween: lerpPartFills, kind: "vector" })
493
- ], Latex.prototype, "partFills", void 0);
494
- __decorate([
495
- property({ default: 1, min: 0, max: 1, step: 0.01 })
496
- ], Latex.prototype, "written", void 0);
497
- __decorate([
498
- property({ default: 0, animatable: false })
499
- ], Latex.prototype, "morphProgress", void 0);
500
- __decorate([
501
- command({ args: [{ key: "latex", kind: "text", multiline: true }] })
502
- ], Latex.prototype, "morphTo", null);
503
- __decorate([
504
- command({ args: ["written"] })
505
- ], Latex.prototype, "writeTo", null);
506
- __decorate([
507
- command({
508
- args: [
509
- { key: "part", kind: "text", default: "" },
510
- { key: "fill", kind: "fills", default: "#facc15" },
511
- { key: "occurrence", kind: "number", min: 0, step: 1, default: 0 },
512
- ],
513
- })
514
- ], Latex.prototype, "partFillTo", null);
515
- Latex = __decorate([
516
- node({
517
- key: "latex",
518
- parentKey: "shape",
519
- forkable: true,
520
- layout: {
521
- children: "freeform",
522
- defaultWidthMode: "hug",
523
- defaultHeightMode: "hug",
524
- acceptsChildren: true,
525
- },
526
- seed: {
527
- fill: [
528
- {
529
- type: "solid",
530
- color: [
531
- 0.412,
532
- 0.565,
533
- 0.867,
534
- 1,
535
- ],
536
- opacity: 1,
537
- enabled: true,
538
- },
539
- ],
540
- },
1
+ import { component2d, Types, } from "@motionscript/sdk";
2
+ import { drawFormula, formula, formulaFrame, layoutFormula, lerpMorph, loadFormula, measureFormula, TYPESET, TYPESET_COMMANDS, } from "./typeset.js";
3
+ const state = {
4
+ ...TYPESET,
5
+ /** The formula. Mid-tween it holds both ends, and the glyphs morph from the one into the other. */
6
+ latex: Types.custom("", {
7
+ kind: "text", multiline: true, lerp: lerpMorph,
541
8
  }),
542
- withdraw(...OUTLINE_TRIM)
543
- ], Latex);
544
- export { Latex };
545
- function penStroke(weight, fill) {
546
- return [{ weight, fill, dashOffset: 0, align: 0, cap: "round", capScale: 4, join: "round", miterLimit: 4 }];
547
- }
548
- function fillsByToken(partFills, parts, count) {
549
- const out = new Array(count);
550
- for (const entry of partFills) {
551
- if (entry.part.trim() === "")
552
- continue;
553
- const spans = findLatexParts(parts, entry.part);
554
- for (const [from, to] of entry.occurrence > 0 ? spans.slice(entry.occurrence - 1, entry.occurrence) : spans) {
555
- for (let i = from; i < to && i < count; i++)
556
- out[i] = entry;
557
- }
558
- }
559
- return out;
560
- }
561
- function scaleFillopacity(fills, opacity) {
562
- if (opacity >= 1)
563
- return fills;
564
- return fills.map(f => ({ ...f, opacity: (f.opacity ?? 1) * opacity }));
565
- }
566
- /**
567
- * A morphing token fades, and its shadow has to fade with it — the paints are
568
- * scaled the same way the fill's are, so a half-faded glyph casts a half-strength
569
- * shadow rather than sitting over a shadow at full weight.
570
- */
571
- function scaleShadowOpacity(shadows, opacity) {
572
- if (opacity >= 1)
573
- return shadows;
574
- return shadows.map(s => ({ ...s, fill: scaleFillopacity(s.fill, opacity) }));
575
- }
576
- function offsetPath(path, dx, dy) {
577
- return path.map(cmd => {
578
- const c = cmd;
579
- const shifted = { ...c };
580
- if ("x" in c)
581
- shifted.x = c.x + dx;
582
- if ("y" in c)
583
- shifted.y = c.y + dy;
584
- if ("x1" in c) {
585
- shifted.x1 = c.x1 + dx;
586
- shifted.y1 = c.y1 + dy;
587
- }
588
- if ("x2" in c) {
589
- shifted.x2 = c.x2 + dx;
590
- shifted.y2 = c.y2 + dy;
591
- }
592
- return shifted;
593
- });
594
- }
9
+ };
10
+ /** A LaTeX formula drawn as glyph paths, morphing token by token between formulas. */
11
+ export const Latex = formula(component2d({
12
+ key: "latex",
13
+ state,
14
+ defaults: { width: "hug", height: "hug" },
15
+ load: (loader) => loadFormula(loader),
16
+ commands: {
17
+ ...TYPESET_COMMANDS,
18
+ /** Morph this formula into another, its glyphs travelling to their places in it. */
19
+ morphTo: { args: ["latex"] },
20
+ },
21
+ measure: (_measurer, s) => measureFormula(formulaFrame(s.latex, s.fontSize, s.partFills), s),
22
+ layout: (box, s, children) => layoutFormula(box, s, children),
23
+ render: (ctx, s) => drawFormula(ctx, s, formulaFrame(s.latex, s.fontSize, s.partFills)),
24
+ }), (s) => s.latex);
595
25
  //# sourceMappingURL=node.js.map