@algorisys/tinyfly 0.115.0 → 0.117.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 (71) hide show
  1. package/README.md +11 -6
  2. package/docs/api-reference.md +2 -1
  3. package/docs/editor-guide.md +1 -1
  4. package/docs/examples.md +1 -1
  5. package/docs/getting-started.md +1 -1
  6. package/docs/gsap-compat.md +1 -1
  7. package/docs/llm-guide.md +18 -0
  8. package/docs/maps.md +2 -2
  9. package/docs/math.md +313 -0
  10. package/docs/teaching.md +1 -1
  11. package/lib/addons/characters.js +2614 -2548
  12. package/lib/addons/math.js +3384 -0
  13. package/lib/browser/tinyfly-math.iife.js +53 -0
  14. package/lib/browser/tinyfly.iife.js +12 -12
  15. package/lib/browser/tinyfly.js +993 -905
  16. package/lib/browser/tinyfly.umd.js +12 -12
  17. package/lib/embed/tinyfly-embed.iife.js +1 -1
  18. package/lib/embed/tinyfly-embed.js +8 -0
  19. package/lib/engine/tinyfly-engine.js +112 -98
  20. package/lib/engine/tinyfly-engine.umd.cjs +2 -2
  21. package/lib/player/tinyfly-player.es.js +8 -0
  22. package/lib/player/tinyfly-player.iife.js +1 -1
  23. package/lib/player/tinyfly-player.umd.js +1 -1
  24. package/lib/types/characters/capabilities.d.ts +8 -0
  25. package/lib/types/engine/authoring/random.d.ts +7 -0
  26. package/lib/types/math/browser-entry.d.ts +3 -0
  27. package/lib/types/math/embed/auto-mount-math.d.ts +7 -0
  28. package/lib/types/math/embed/explorable.d.ts +46 -0
  29. package/lib/types/math/embed/mount-math.d.ts +31 -0
  30. package/lib/types/math/expr/differentiate.d.ts +7 -0
  31. package/lib/types/math/expr/evaluate.d.ts +21 -0
  32. package/lib/types/math/expr/parse-expression.d.ts +50 -0
  33. package/lib/types/math/figure/derived.d.ts +17 -0
  34. package/lib/types/math/figure/display-list.d.ts +87 -0
  35. package/lib/types/math/figure/figure-spec.d.ts +349 -0
  36. package/lib/types/math/figure/item-context.d.ts +39 -0
  37. package/lib/types/math/figure/items/calculus.d.ts +7 -0
  38. package/lib/types/math/figure/items/curves.d.ts +7 -0
  39. package/lib/types/math/figure/items/grid.d.ts +5 -0
  40. package/lib/types/math/figure/items/probability.d.ts +13 -0
  41. package/lib/types/math/figure/items/regions.d.ts +5 -0
  42. package/lib/types/math/figure/items/text.d.ts +5 -0
  43. package/lib/types/math/figure/items/vectors.d.ts +9 -0
  44. package/lib/types/math/figure/layout-figure.d.ts +13 -0
  45. package/lib/types/math/figure/plane.d.ts +20 -0
  46. package/lib/types/math/figure/validate-spec.d.ts +2 -0
  47. package/lib/types/math/index.d.ts +49 -0
  48. package/lib/types/math/linear/mat2.d.ts +41 -0
  49. package/lib/types/math/linear/vec2.d.ts +18 -0
  50. package/lib/types/math/presets/calculus.d.ts +59 -0
  51. package/lib/types/math/presets/linear-algebra.d.ts +42 -0
  52. package/lib/types/math/presets/probability.d.ts +62 -0
  53. package/lib/types/math/prob/bayes.d.ts +16 -0
  54. package/lib/types/math/prob/distributions.d.ts +58 -0
  55. package/lib/types/math/prob/galton.d.ts +18 -0
  56. package/lib/types/math/prob/histogram.d.ts +20 -0
  57. package/lib/types/math/prob/scatter.d.ts +24 -0
  58. package/lib/types/math/render/arrow.d.ts +10 -0
  59. package/lib/types/math/render/display-list-to-svg.d.ts +10 -0
  60. package/lib/types/math/render/draw-display-list.d.ts +6 -0
  61. package/lib/types/math/steps/math-steps.d.ts +34 -0
  62. package/lib/types/math/targets/math-target.d.ts +43 -0
  63. package/lib/types/math/tex/equation-morph.d.ts +21 -0
  64. package/lib/types/math/tex/glyph-metrics.d.ts +24 -0
  65. package/lib/types/math/tex/tex-layout.d.ts +59 -0
  66. package/lib/types/math/tex/tex-parser.d.ts +88 -0
  67. package/lib/types/player/player.d.ts +6 -0
  68. package/llms-full.txt +400 -10
  69. package/llms.txt +32 -31
  70. package/package.json +6 -2
  71. package/skills/tinyfly/SKILL.md +12 -0
@@ -0,0 +1,3384 @@
1
+ import { randomNormal as De, createRandom as ce, hashSeed as ue, closestName as dn, unknownName as J, deserializeTimeline as ke, playheadCrossings as hn } from "@algorisys/tinyfly";
2
+ import { D as $e } from "./dom-adapter-Cphr2HZn.js";
3
+ const pn = (t, e) => [t[0] + e[0], t[1] + e[1]], de = (t, e) => [t[0] - e[0], t[1] - e[1]], Jt = (t, e) => [t[0] * e, t[1] * e], fn = (t, e) => t[0] * e[0] + t[1] * e[1], mn = (t, e) => t[0] * e[1] - t[1] * e[0], Re = (t) => Math.hypot(t[0], t[1]);
4
+ function _e(t) {
5
+ const e = Re(t);
6
+ return e === 0 ? [0, 0] : [t[0] / e, t[1] / e];
7
+ }
8
+ const yn = (t, e, n) => [t[0] + (e[0] - t[0]) * n, t[1] + (e[1] - t[1]) * n];
9
+ function it(t) {
10
+ return Array.isArray(t) && t.length === 2 && t.every(Number.isFinite);
11
+ }
12
+ const Xi = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
13
+ __proto__: null,
14
+ add: pn,
15
+ cross: mn,
16
+ dot: fn,
17
+ isVec2: it,
18
+ length: Re,
19
+ lerp: yn,
20
+ normalize: _e,
21
+ scale: Jt,
22
+ sub: de
23
+ }, Symbol.toStringTag, { value: "Module" })), xt = [1, 0, 0, 1], U = ([t, e, n, i], [s, r]) => [t * s + e * r, n * s + i * r];
24
+ function gn(t, e) {
25
+ const [n, i, s, r] = t, [o, l, c, d] = e;
26
+ return [n * o + i * c, n * l + i * d, s * o + r * c, s * l + r * d];
27
+ }
28
+ const St = ([t, e, n, i]) => t * i - e * n;
29
+ function bn(t) {
30
+ const e = St(t);
31
+ if (Math.abs(e) < 1e-12) return;
32
+ const [n, i, s, r] = t;
33
+ return [r / e, -i / e, -s / e, n / e];
34
+ }
35
+ const vn = (t, e, n) => t.map((i, s) => i + (e[s] - i) * n), wn = (t) => [Math.cos(t), -Math.sin(t), Math.sin(t), Math.cos(t)];
36
+ function Ve(t) {
37
+ const [e, n, i, s] = t, r = e + s, o = St(t), l = r * r - 4 * o, c = 1e-9;
38
+ if (l < -c) return [];
39
+ const d = Math.sqrt(Math.max(0, l)), u = d < c ? [r / 2] : [(r + d) / 2, (r - d) / 2], p = [];
40
+ for (const h of u) {
41
+ const f = [[e - h, n], [i, s - h]].reduce((w, M) => Math.hypot(...M) > Math.hypot(...w) ? M : w);
42
+ if (Math.hypot(...f) < c) {
43
+ p.push({ value: h, vector: [1, 0] }, { value: h, vector: [0, 1] });
44
+ continue;
45
+ }
46
+ const y = [-f[1], f[0]], a = Math.hypot(...y), g = y[0] < -c || Math.abs(y[0]) <= c && y[1] < 0 ? -1 : 1;
47
+ p.push({ value: h, vector: [g * y[0] / a + 0, g * y[1] / a + 0] });
48
+ }
49
+ return p;
50
+ }
51
+ function pt(t) {
52
+ return Array.isArray(t) && t.length === 4 && t.every(Number.isFinite);
53
+ }
54
+ const Yi = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
55
+ __proto__: null,
56
+ IDENTITY: xt,
57
+ apply: U,
58
+ determinant: St,
59
+ eigen: Ve,
60
+ inverse: bn,
61
+ isMat2: pt,
62
+ lerp: vn,
63
+ multiply: gn,
64
+ rotation: wn
65
+ }, Symbol.toStringTag, { value: "Module" })), Qt = {
66
+ sin: { arity: 1, apply: Math.sin },
67
+ cos: { arity: 1, apply: Math.cos },
68
+ tan: { arity: 1, apply: Math.tan },
69
+ asin: { arity: 1, apply: Math.asin },
70
+ acos: { arity: 1, apply: Math.acos },
71
+ atan: { arity: 1, apply: Math.atan },
72
+ atan2: { arity: 2, apply: Math.atan2 },
73
+ sinh: { arity: 1, apply: Math.sinh },
74
+ cosh: { arity: 1, apply: Math.cosh },
75
+ tanh: { arity: 1, apply: Math.tanh },
76
+ exp: { arity: 1, apply: Math.exp },
77
+ ln: { arity: 1, apply: Math.log },
78
+ log: { arity: 1, apply: Math.log10 },
79
+ log2: { arity: 1, apply: Math.log2 },
80
+ sqrt: { arity: 1, apply: Math.sqrt },
81
+ abs: { arity: 1, apply: Math.abs },
82
+ floor: { arity: 1, apply: Math.floor },
83
+ ceil: { arity: 1, apply: Math.ceil },
84
+ round: { arity: 1, apply: Math.round },
85
+ sign: { arity: 1, apply: Math.sign },
86
+ min: { arity: 2, apply: Math.min },
87
+ max: { arity: 2, apply: Math.max },
88
+ // The logistic function, common in ML lessons
89
+ sigmoid: { arity: 1, apply: (t) => 1 / (1 + Math.exp(-t)) },
90
+ relu: { arity: 1, apply: (t) => Math.max(0, t) }
91
+ }, Ct = { pi: Math.PI, e: Math.E, tau: Math.PI * 2 };
92
+ class ht extends Error {
93
+ source;
94
+ /** 0-based index into the source */
95
+ position;
96
+ constructor(e, n, i) {
97
+ super(`${e} at ${i + 1} in "${n}"`), this.name = "ExpressionError", this.source = n, this.position = i;
98
+ }
99
+ }
100
+ function kn(t) {
101
+ const e = [];
102
+ let n = 0;
103
+ for (; n < t.length; ) {
104
+ const i = t[n];
105
+ if (/\s/.test(i)) {
106
+ n++;
107
+ continue;
108
+ }
109
+ const s = /^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(t.slice(n));
110
+ if (s) {
111
+ e.push({ kind: "number", value: Number(s[0]), at: n }), n += s[0].length;
112
+ continue;
113
+ }
114
+ const r = /^[A-Za-z_][A-Za-z_0-9]*/.exec(t.slice(n));
115
+ if (r) {
116
+ e.push({ kind: "name", value: r[0], at: n }), n += r[0].length;
117
+ continue;
118
+ }
119
+ if ("+-*/^(),".includes(i)) {
120
+ e.push({ kind: "op", value: i, at: n }), n++;
121
+ continue;
122
+ }
123
+ throw new ht(`Unexpected "${i}"`, t, n);
124
+ }
125
+ return e.push({ kind: "end", at: t.length }), e;
126
+ }
127
+ function lt(t) {
128
+ if (typeof t != "string") throw new TypeError("parseExpression: expected a string");
129
+ const e = kn(t);
130
+ let n = 0;
131
+ const i = () => e[n], s = (h) => {
132
+ const m = i();
133
+ return m.kind === "op" && m.value === h;
134
+ }, r = (h) => {
135
+ if (!s(h)) throw new ht(`Expected "${h}"`, t, i().at);
136
+ n++;
137
+ }, o = () => {
138
+ let h = l();
139
+ for (; s("+") || s("-"); )
140
+ h = { type: "binary", operator: e[n++].value, left: h, right: l() };
141
+ return h;
142
+ }, l = () => {
143
+ let h = c();
144
+ for (; ; )
145
+ if (s("*") || s("/"))
146
+ h = { type: "binary", operator: e[n++].value, left: h, right: c() };
147
+ else if (i().kind === "name" || i().kind === "number" || s("("))
148
+ h = { type: "binary", operator: "*", left: h, right: d() };
149
+ else
150
+ return h;
151
+ }, c = () => s("-") || s("+") ? { type: "unary", operator: e[n++].value, operand: c() } : d(), d = () => {
152
+ const h = u();
153
+ return s("^") ? (n++, { type: "binary", operator: "^", left: h, right: c() }) : h;
154
+ }, u = () => {
155
+ const h = i();
156
+ if (h.kind === "number")
157
+ return n++, { type: "number", value: h.value };
158
+ if (h.kind === "name") {
159
+ if (n++, !s("(")) return { type: "name", name: h.value };
160
+ const m = Object.prototype.hasOwnProperty.call(Qt, h.value) ? Qt[h.value] : void 0;
161
+ if (!m) throw new ht(`Unknown function "${h.value}"`, t, h.at);
162
+ n++;
163
+ const f = [];
164
+ if (!s(")"))
165
+ for (f.push(o()); s(","); )
166
+ n++, f.push(o());
167
+ if (r(")"), f.length !== m.arity)
168
+ throw new ht(`"${h.value}" takes ${m.arity} argument${m.arity === 1 ? "" : "s"}, got ${f.length}`, t, h.at);
169
+ return { type: "call", name: h.value, args: f };
170
+ }
171
+ if (s("(")) {
172
+ n++;
173
+ const m = o();
174
+ return r(")"), m;
175
+ }
176
+ throw new ht(h.kind === "end" ? "Unexpected end" : `Unexpected "${h.value}"`, t, h.at);
177
+ }, p = o();
178
+ if (i().kind !== "end") throw new ht(`Unexpected "${i().value}"`, t, i().at);
179
+ return p;
180
+ }
181
+ function Me(t) {
182
+ const e = /* @__PURE__ */ new Set(), n = (i) => {
183
+ i.type === "name" && !(i.name in Ct) ? e.add(i.name) : i.type === "unary" ? n(i.operand) : i.type === "binary" ? (n(i.left), n(i.right)) : i.type === "call" && i.args.forEach(n);
184
+ };
185
+ return n(t), [...e].sort();
186
+ }
187
+ const O = (t) => ({ type: "number", value: t }), kt = O(0), I = O(1), C = (t) => t.type === "number", _ = (t, e) => t.type === "number" && t.value === e;
188
+ function nt(t, e) {
189
+ return C(t) && C(e) ? O(t.value + e.value) : _(t, 0) ? e : _(e, 0) ? t : { type: "binary", operator: "+", left: t, right: e };
190
+ }
191
+ function X(t, e) {
192
+ return C(t) && C(e) ? O(t.value - e.value) : _(e, 0) ? t : _(t, 0) ? Lt(e) : { type: "binary", operator: "-", left: t, right: e };
193
+ }
194
+ function P(t, e) {
195
+ return C(t) && C(e) ? O(t.value * e.value) : _(t, 0) || _(e, 0) ? kt : _(t, 1) ? e : _(e, 1) ? t : C(e) ? P(e, t) : C(t) && e.type === "binary" && e.operator === "*" && C(e.left) ? P(O(t.value * e.left.value), e.right) : { type: "binary", operator: "*", left: t, right: e };
196
+ }
197
+ function j(t, e) {
198
+ return _(t, 0) ? kt : _(e, 1) ? t : C(t) && C(e) && e.value !== 0 ? O(t.value / e.value) : { type: "binary", operator: "/", left: t, right: e };
199
+ }
200
+ function Q(t, e) {
201
+ return _(e, 0) ? I : _(e, 1) ? t : C(t) && C(e) ? O(t.value ** e.value) : { type: "binary", operator: "^", left: t, right: e };
202
+ }
203
+ function Lt(t) {
204
+ return C(t) ? O(-t.value) : t.type === "unary" && t.operator === "-" ? t.operand : { type: "unary", operator: "-", operand: t };
205
+ }
206
+ const D = (t, ...e) => ({ type: "call", name: t, args: e });
207
+ function at(t, e) {
208
+ switch (t.type) {
209
+ case "number":
210
+ return !0;
211
+ case "name":
212
+ return t.name !== e;
213
+ case "unary":
214
+ return at(t.operand, e);
215
+ case "binary":
216
+ return at(t.left, e) && at(t.right, e);
217
+ case "call":
218
+ return t.args.every((n) => at(n, e));
219
+ }
220
+ }
221
+ function tt(t, e = "x") {
222
+ if (at(t, e)) return kt;
223
+ switch (t.type) {
224
+ case "number":
225
+ return kt;
226
+ case "name":
227
+ return t.name === e ? I : kt;
228
+ case "unary":
229
+ return t.operator === "-" ? Lt(tt(t.operand, e)) : tt(t.operand, e);
230
+ case "binary": {
231
+ const { left: n, right: i } = t, s = () => tt(n, e), r = () => tt(i, e);
232
+ switch (t.operator) {
233
+ case "+":
234
+ return nt(s(), r());
235
+ case "-":
236
+ return X(s(), r());
237
+ case "*":
238
+ return nt(P(s(), i), P(n, r()));
239
+ case "/":
240
+ return j(X(P(s(), i), P(n, r())), Q(i, O(2)));
241
+ case "^":
242
+ if (at(i, e)) {
243
+ const o = C(i) ? O(i.value - 1) : X(i, I);
244
+ return P(P(i, Q(n, o)), s());
245
+ }
246
+ return at(n, e) ? P(P(t, D("ln", n)), r()) : P(t, nt(P(r(), D("ln", n)), j(P(i, s()), n)));
247
+ }
248
+ break;
249
+ }
250
+ case "call": {
251
+ const [n, i] = t.args, s = () => tt(n, e), r = (o) => P(o, s());
252
+ switch (t.name) {
253
+ case "sin":
254
+ return r(D("cos", n));
255
+ case "cos":
256
+ return r(Lt(D("sin", n)));
257
+ case "tan":
258
+ return r(j(I, Q(D("cos", n), O(2))));
259
+ case "asin":
260
+ return r(j(I, D("sqrt", X(I, Q(n, O(2))))));
261
+ case "acos":
262
+ return r(Lt(j(I, D("sqrt", X(I, Q(n, O(2)))))));
263
+ case "atan":
264
+ return r(j(I, nt(I, Q(n, O(2)))));
265
+ case "sinh":
266
+ return r(D("cosh", n));
267
+ case "cosh":
268
+ return r(D("sinh", n));
269
+ case "tanh":
270
+ return r(X(I, Q(D("tanh", n), O(2))));
271
+ case "exp":
272
+ return r(t);
273
+ case "ln":
274
+ return r(j(I, n));
275
+ case "log":
276
+ return r(j(I, P(n, O(Math.LN10))));
277
+ case "log2":
278
+ return r(j(I, P(n, O(Math.LN2))));
279
+ case "sqrt":
280
+ return r(j(I, P(O(2), t)));
281
+ case "abs":
282
+ return r(D("sign", n));
283
+ case "sigmoid":
284
+ return r(P(t, X(I, t)));
285
+ case "relu":
286
+ return r(j(nt(D("sign", n), I), O(2)));
287
+ case "atan2": {
288
+ const o = tt(i, e);
289
+ return j(X(P(i, s()), P(n, o)), nt(Q(n, O(2)), Q(i, O(2))));
290
+ }
291
+ case "min":
292
+ case "max": {
293
+ const o = t.name === "max" ? 1 : -1, l = tt(i, e), c = j(nt(I, P(O(o), D("sign", X(n, i)))), O(2));
294
+ return nt(P(c, s()), P(X(I, c), l));
295
+ }
296
+ }
297
+ throw new Error(`differentiate: "${t.name}" has no derivative rule`);
298
+ }
299
+ }
300
+ throw new Error("differentiate: malformed expression");
301
+ }
302
+ function $n(t, e, n = "x") {
303
+ let i = t;
304
+ for (let s = 0; s < e; s++) i = tt(i, n);
305
+ return i;
306
+ }
307
+ function Pt(t) {
308
+ switch (t.type) {
309
+ case "number":
310
+ return t.value < 0 ? `(${t.value})` : String(t.value);
311
+ case "name":
312
+ return t.name;
313
+ case "unary":
314
+ return `(${t.operator}${Pt(t.operand)})`;
315
+ case "binary":
316
+ return `(${Pt(t.left)} ${t.operator} ${Pt(t.right)})`;
317
+ case "call":
318
+ return `${t.name}(${t.args.map(Pt).join(", ")})`;
319
+ }
320
+ }
321
+ function rt(t, e = {}) {
322
+ switch (t.type) {
323
+ case "number":
324
+ return t.value;
325
+ case "name": {
326
+ if (Object.prototype.hasOwnProperty.call(e, t.name)) return e[t.name];
327
+ if (Object.prototype.hasOwnProperty.call(Ct, t.name)) return Ct[t.name];
328
+ throw new Error(`evaluate: unknown name "${t.name}"`);
329
+ }
330
+ case "unary": {
331
+ const n = rt(t.operand, e);
332
+ return t.operator === "-" ? -n : n;
333
+ }
334
+ case "binary": {
335
+ const n = rt(t.left, e), i = rt(t.right, e);
336
+ switch (t.operator) {
337
+ case "+":
338
+ return n + i;
339
+ case "-":
340
+ return n - i;
341
+ case "*":
342
+ return n * i;
343
+ case "/":
344
+ return n / i;
345
+ case "^":
346
+ return n ** i;
347
+ }
348
+ break;
349
+ }
350
+ case "call":
351
+ return Qt[t.name].apply(...t.args.map((n) => rt(n, e)));
352
+ }
353
+ throw new Error("evaluate: malformed expression");
354
+ }
355
+ const Ft = /* @__PURE__ */ new Map();
356
+ function R(t, e = "x") {
357
+ let n = Ft.get(t);
358
+ n || (n = lt(t), Ft.size < 256 && Ft.set(t, n));
359
+ const i = n;
360
+ return (s, r = {}) => rt(i, { ...r, [e]: s });
361
+ }
362
+ const Wt = /* @__PURE__ */ new Map();
363
+ function he(t, e, n = "x") {
364
+ if (!Number.isInteger(e) || e < 0) throw new Error(`compileDerivative: order must be a whole number ≥ 0, got ${e}`);
365
+ const i = `${n}|${e}|${t}`;
366
+ let s = Wt.get(i);
367
+ if (!s) {
368
+ let o = Ft.get(t);
369
+ o || (o = lt(t)), s = $n(o, e, n), Wt.size < 512 && Wt.set(i, s);
370
+ }
371
+ const r = s;
372
+ return (o, l = {}) => rt(r, { ...l, [n]: o });
373
+ }
374
+ function Be(t) {
375
+ const e = {};
376
+ for (const [n, i] of Object.entries(t))
377
+ if (typeof i == "number")
378
+ e[n] = i;
379
+ else if (pt(i)) {
380
+ const [s, r, o, l] = i;
381
+ Object.assign(e, { [`${n}.a`]: s, [`${n}.b`]: r, [`${n}.c`]: o, [`${n}.d`]: l, [`${n}.det`]: St(i) });
382
+ } else it(i) && Object.assign(e, { [`${n}.x`]: i[0], [`${n}.y`]: i[1], [`${n}.length`]: Math.hypot(i[0], i[1]) });
383
+ return e;
384
+ }
385
+ function E(t, e, n) {
386
+ return e ? Object.prototype.hasOwnProperty.call(t.colors, e) ? t.colors[e] : e : n;
387
+ }
388
+ function $t(t, e) {
389
+ if (typeof e != "string") return e;
390
+ const n = t[e];
391
+ if (!it(n)) throw new Error(`math figure: value "${e}" is not an [x, y] vector`);
392
+ return n;
393
+ }
394
+ function ct(t, e) {
395
+ if (e === void 0) return xt;
396
+ const n = t[e];
397
+ if (!pt(n)) throw new Error(`math figure: value "${e}" is not a [a, b, c, d] matrix`);
398
+ return n;
399
+ }
400
+ function S(t, e) {
401
+ if (typeof e == "number") return e;
402
+ const n = t[e];
403
+ if (typeof n != "number") throw new Error(`math figure: value "${e}" is not a number`);
404
+ return n;
405
+ }
406
+ function ft(t, e) {
407
+ const n = (s) => s === void 0 ? void 0 : S(t, s), i = (s) => s === void 0 ? void 0 : Math.round(S(t, s));
408
+ switch (e.kind) {
409
+ case "normal":
410
+ return { kind: "normal", mean: n(e.mean), sd: n(e.sd) };
411
+ case "uniform":
412
+ return { kind: "uniform", min: n(e.min), max: n(e.max) };
413
+ case "exponential":
414
+ return { kind: "exponential", rate: n(e.rate) };
415
+ case "binomial":
416
+ return { kind: "binomial", n: i(e.n), p: n(e.p) };
417
+ case "poisson":
418
+ return { kind: "poisson", rate: n(e.rate) };
419
+ case "dice":
420
+ return { kind: "dice", count: i(e.count), sides: i(e.sides) };
421
+ case "mean":
422
+ return { kind: "mean", of: ft(t, e.of), count: i(e.count) };
423
+ }
424
+ }
425
+ const zt = ["normal", "uniform", "exponential", "binomial", "poisson", "dice", "mean"];
426
+ function Mn(t) {
427
+ switch (t.kind) {
428
+ case "binomial":
429
+ return [0, t.n];
430
+ case "dice":
431
+ return [t.count ?? 2, (t.count ?? 2) * (t.sides ?? 6)];
432
+ case "poisson":
433
+ return [0, 1 / 0];
434
+ default:
435
+ return [-1 / 0, 1 / 0];
436
+ }
437
+ }
438
+ function _t(t) {
439
+ return t.kind === "binomial" || t.kind === "poisson" || t.kind === "dice";
440
+ }
441
+ const qt = /* @__PURE__ */ (() => {
442
+ const t = [0];
443
+ return (e) => {
444
+ for (let n = t.length; n <= e; n++) t[n] = t[n - 1] + Math.log(n);
445
+ return t[e];
446
+ };
447
+ })(), Ut = (t, e) => Math.exp(qt(t) - qt(e) - qt(t - e));
448
+ function st(t, e) {
449
+ switch (t.kind) {
450
+ case "normal": {
451
+ const { mean: n = 0, sd: i = 1 } = t;
452
+ return Math.exp(-(((e - n) / i) ** 2) / 2) / (i * Math.sqrt(2 * Math.PI));
453
+ }
454
+ case "uniform": {
455
+ const { min: n = 0, max: i = 1 } = t;
456
+ return e >= n && e <= i ? 1 / (i - n) : 0;
457
+ }
458
+ case "exponential": {
459
+ const { rate: n = 1 } = t;
460
+ return e < 0 ? 0 : n * Math.exp(-n * e);
461
+ }
462
+ case "binomial":
463
+ return !Number.isInteger(e) || e < 0 || e > t.n ? 0 : Ut(t.n, e) * t.p ** e * (1 - t.p) ** (t.n - e);
464
+ case "poisson":
465
+ return !Number.isInteger(e) || e < 0 ? 0 : Math.exp(e * Math.log(t.rate) - t.rate - qt(e));
466
+ case "dice": {
467
+ const { count: n = 2, sides: i = 6 } = t;
468
+ if (!Number.isInteger(e) || e < n || e > n * i) return 0;
469
+ let s = 0;
470
+ for (let r = 0; r <= Math.floor((e - n) / i); r++)
471
+ s += (r % 2 ? -1 : 1) * Ut(n, r) * Ut(e - i * r - 1, n - 1);
472
+ return s / i ** n;
473
+ }
474
+ case "mean":
475
+ return t.count === 1 ? st(t.of, e) : st({ kind: "normal", mean: At(t.of), sd: Et(t.of) / Math.sqrt(t.count) }, e);
476
+ }
477
+ }
478
+ function At(t) {
479
+ switch (t.kind) {
480
+ case "normal":
481
+ return t.mean ?? 0;
482
+ case "uniform":
483
+ return ((t.min ?? 0) + (t.max ?? 1)) / 2;
484
+ case "exponential":
485
+ return 1 / (t.rate ?? 1);
486
+ case "binomial":
487
+ return t.n * t.p;
488
+ case "poisson":
489
+ return t.rate;
490
+ case "dice":
491
+ return (t.count ?? 2) * ((t.sides ?? 6) + 1) / 2;
492
+ case "mean":
493
+ return At(t.of);
494
+ }
495
+ }
496
+ function Et(t) {
497
+ switch (t.kind) {
498
+ case "normal":
499
+ return t.sd ?? 1;
500
+ case "uniform":
501
+ return ((t.max ?? 1) - (t.min ?? 0)) / Math.sqrt(12);
502
+ case "exponential":
503
+ return 1 / (t.rate ?? 1);
504
+ case "binomial":
505
+ return Math.sqrt(t.n * t.p * (1 - t.p));
506
+ case "poisson":
507
+ return Math.sqrt(t.rate);
508
+ case "dice":
509
+ return Math.sqrt((t.count ?? 2) * ((t.sides ?? 6) ** 2 - 1) / 12);
510
+ case "mean":
511
+ return Et(t.of) / Math.sqrt(t.count);
512
+ }
513
+ }
514
+ function We(t, e) {
515
+ switch (t.kind) {
516
+ case "normal":
517
+ return De(e, t.mean ?? 0, t.sd ?? 1);
518
+ case "uniform":
519
+ return (t.min ?? 0) + e.next() * ((t.max ?? 1) - (t.min ?? 0));
520
+ case "exponential":
521
+ return -Math.log(1 - e.next()) / (t.rate ?? 1);
522
+ case "binomial": {
523
+ let n = 0;
524
+ for (let i = 0; i < t.n; i++) e.next() < t.p && n++;
525
+ return n;
526
+ }
527
+ case "poisson": {
528
+ const n = Math.exp(-t.rate);
529
+ let i = 0, s = e.next();
530
+ for (; s > n; )
531
+ i++, s *= e.next();
532
+ return i;
533
+ }
534
+ case "dice": {
535
+ let n = 0;
536
+ for (let i = 0; i < (t.count ?? 2); i++) n += 1 + Math.floor(e.next() * (t.sides ?? 6));
537
+ return n;
538
+ }
539
+ case "mean": {
540
+ let n = 0;
541
+ for (let i = 0; i < t.count; i++) n += We(t.of, e);
542
+ return n / t.count;
543
+ }
544
+ }
545
+ }
546
+ const Nt = /* @__PURE__ */ new Map();
547
+ function Ue(t, e, n) {
548
+ const i = `${JSON.stringify(t)}|${e}`;
549
+ let s = Nt.get(i);
550
+ if (s || (s = [], Nt.size > 64 && Nt.clear(), Nt.set(i, s)), s.length < n) {
551
+ const r = ce(typeof e == "number" ? e : ue(e)), o = [];
552
+ for (let l = 0; l < n; l++) o.push(We(t, r));
553
+ s.splice(0, s.length, ...o);
554
+ }
555
+ return s.slice(0, n);
556
+ }
557
+ function He(t) {
558
+ if (!t || typeof t != "object" || !zt.includes(t.kind)) return `kind must be one of ${zt.join(", ")}`;
559
+ const e = (n, i) => n !== void 0 && !(n > 0) ? `${i} must be positive` : void 0;
560
+ switch (t.kind) {
561
+ case "normal":
562
+ return e(t.sd, "sd");
563
+ case "uniform":
564
+ return (t.max ?? 1) > (t.min ?? 0) ? void 0 : "max must be greater than min";
565
+ case "exponential":
566
+ return e(t.rate, "rate");
567
+ case "binomial":
568
+ return Number.isInteger(t.n) && t.n >= 0 && t.n <= 1e3 && t.p >= 0 && t.p <= 1 ? void 0 : "n must be a whole number 0..1000 and p in 0..1";
569
+ case "poisson":
570
+ return t.rate > 0 && t.rate <= 200 ? void 0 : "rate must be in (0, 200]";
571
+ case "dice":
572
+ return Number.isInteger(t.count ?? 2) && (t.count ?? 2) >= 1 && (t.count ?? 2) <= 50 && Number.isInteger(t.sides ?? 6) && (t.sides ?? 6) >= 2 ? void 0 : "count must be 1..50 and sides a whole number ≥ 2";
573
+ case "mean":
574
+ return Number.isInteger(t.count) && t.count >= 1 && t.count <= 200 ? He(t.of) : "count must be a whole number 1..200";
575
+ }
576
+ }
577
+ function xe(t) {
578
+ const e = At(t), n = Et(t);
579
+ if (_t(t)) {
580
+ const [i, s] = Mn(t), r = Math.max(i, Math.floor(e - 4 * n)), o = Math.min(s, Math.ceil(e + 4 * n));
581
+ return [r - 0.5, o + 0.5, o - r + 1];
582
+ }
583
+ return [e - 4 * n, e + 4 * n, 30];
584
+ }
585
+ function xn(t, [e, n, i], s) {
586
+ const r = (n - e) / i, o = new Array(i).fill(0);
587
+ for (const c of t) {
588
+ const d = Math.floor((c - e) / r);
589
+ d >= 0 && d < i ? o[d]++ : c === n && o[i - 1]++;
590
+ }
591
+ const l = t.length || 1;
592
+ return o.map((c, d) => ({
593
+ left: e + d * r,
594
+ right: e + (d + 1) * r,
595
+ count: c,
596
+ height: s === "density" ? c / (l * r) : c
597
+ }));
598
+ }
599
+ function Sn(t) {
600
+ if (t.length === 0) return { mean: 0, sd: 0 };
601
+ const e = t.reduce((i, s) => i + s, 0) / t.length, n = t.reduce((i, s) => i + (s - e) ** 2, 0) / t.length;
602
+ return { mean: e, sd: Math.sqrt(n) };
603
+ }
604
+ function Xe(t, e, n) {
605
+ const i = ce(typeof e == "number" ? e : ue(e));
606
+ return Array.from({ length: Math.max(0, Math.floor(n)) }, () => {
607
+ const s = i.next();
608
+ if (t.kind === "uniform") {
609
+ const o = i.next();
610
+ return [t.x[0] + s * (t.x[1] - t.x[0]), t.y[0] + o * (t.y[1] - t.y[0])];
611
+ }
612
+ const r = t.x[0] + s * (t.x[1] - t.x[0]);
613
+ return [r, t.slope * r + t.intercept + t.noise * De(i)];
614
+ });
615
+ }
616
+ function Ye(t) {
617
+ const e = t.length;
618
+ if (e < 2) return;
619
+ const n = t.reduce((c, d) => c + d[0], 0) / e, i = t.reduce((c, d) => c + d[1], 0) / e;
620
+ let s = 0, r = 0, o = 0;
621
+ for (const [c, d] of t)
622
+ s += (c - n) * (d - i), r += (c - n) ** 2, o += (d - i) ** 2;
623
+ if (r === 0) return;
624
+ const l = s / r;
625
+ return { slope: l, intercept: i - l * n, r: o === 0 ? 0 : s / Math.sqrt(r * o) };
626
+ }
627
+ function An(t, e, n) {
628
+ const i = Math.min(1, Math.max(0, t)), s = i * Math.min(1, Math.max(0, e)), r = (1 - i) * Math.min(1, Math.max(0, n)), o = s + r;
629
+ return { truePositive: s, falsePositive: r, positive: o, posterior: o > 0 ? s / o : 0 };
630
+ }
631
+ function Se(t, e, n) {
632
+ const i = ce(ue(`${t}:${e}`));
633
+ return Array.from({ length: n }, () => i.next() < 0.5);
634
+ }
635
+ const Ht = (t) => t.filter(Boolean).length;
636
+ function En(t, e) {
637
+ const n = t.length, i = Math.min(1, Math.max(0, e)) * n, s = Math.min(n - 1, Math.floor(i)), r = i - s, l = t.slice(0, s).filter(Boolean).length - s / 2, c = l + (t[s] ? 0.5 : -0.5), d = 0.18 * Math.sin(Math.PI * r);
638
+ return { x: l + (c - l) * r, depth: s + r - d };
639
+ }
640
+ const Tn = '"Latin Modern Math", "STIX Two Math", "Cambria Math", "Times New Roman", "Liberation Serif", "Noto Serif", Times, serif', Ze = 0.25, Mt = 0.05, Ae = {
641
+ a: 0.5,
642
+ b: 0.56,
643
+ c: 0.44,
644
+ d: 0.56,
645
+ e: 0.44,
646
+ f: 0.31,
647
+ g: 0.5,
648
+ h: 0.56,
649
+ i: 0.28,
650
+ j: 0.31,
651
+ k: 0.53,
652
+ l: 0.28,
653
+ m: 0.83,
654
+ n: 0.56,
655
+ o: 0.5,
656
+ p: 0.56,
657
+ q: 0.53,
658
+ r: 0.39,
659
+ s: 0.39,
660
+ t: 0.39,
661
+ u: 0.56,
662
+ v: 0.53,
663
+ w: 0.72,
664
+ x: 0.53,
665
+ y: 0.53,
666
+ z: 0.44,
667
+ A: 0.75,
668
+ B: 0.71,
669
+ C: 0.72,
670
+ D: 0.76,
671
+ E: 0.68,
672
+ F: 0.65,
673
+ G: 0.78,
674
+ H: 0.75,
675
+ I: 0.36,
676
+ J: 0.51,
677
+ K: 0.78,
678
+ L: 0.63,
679
+ M: 0.92,
680
+ N: 0.75,
681
+ O: 0.78,
682
+ P: 0.68,
683
+ Q: 0.78,
684
+ R: 0.74,
685
+ S: 0.56,
686
+ T: 0.72,
687
+ U: 0.75,
688
+ V: 0.75,
689
+ W: 1.03,
690
+ X: 0.75,
691
+ Y: 0.75,
692
+ Z: 0.61
693
+ };
694
+ function te(t) {
695
+ return t.length !== 1 ? t.length * 0.5 : /[0-9]/.test(t) ? 0.5 : Object.prototype.hasOwnProperty.call(Ae, t) ? Ae[t] + 0.04 : "()[]".includes(t) ? 0.39 : "{}".includes(t) ? 0.5 : "|".includes(t) || ",.;:!".includes(t) ? 0.28 : "+−=<>±×÷≤≥≠≈∼≡∝→←↔⇒⇔∈∉⊂⊃⊆⊇∪∩∧∨".includes(t) ? 0.78 : "·∘".includes(t) ? 0.28 : "∑∏".includes(t) ? 1.05 : "∫".includes(t) ? 0.56 : "∞".includes(t) || "…⋯".includes(t) ? 1 : /[Α-Ω]/.test(t) ? 0.72 : /[α-ω]/.test(t) ? 0.56 : 0.6;
696
+ }
697
+ function Ge(t) {
698
+ return "gjpqy(),;[]{}|∫".includes(t) || "βγζημξρφχψ".includes(t) ? { height: 0.72, depth: 0.22 } : "∑∏".includes(t) ? { height: 0.75, depth: 0.25 } : /[a-z]/.test(t) && !"bdfhklt".includes(t) ? { height: 0.45, depth: 0 } : { height: 0.7, depth: 0 };
699
+ }
700
+ const ee = {
701
+ alpha: "α",
702
+ beta: "β",
703
+ gamma: "γ",
704
+ delta: "δ",
705
+ epsilon: "ε",
706
+ varepsilon: "ε",
707
+ zeta: "ζ",
708
+ eta: "η",
709
+ theta: "θ",
710
+ iota: "ι",
711
+ kappa: "κ",
712
+ lambda: "λ",
713
+ mu: "μ",
714
+ nu: "ν",
715
+ xi: "ξ",
716
+ pi: "π",
717
+ rho: "ρ",
718
+ sigma: "σ",
719
+ tau: "τ",
720
+ upsilon: "υ",
721
+ phi: "φ",
722
+ varphi: "φ",
723
+ chi: "χ",
724
+ psi: "ψ",
725
+ omega: "ω",
726
+ Gamma: "Γ",
727
+ Delta: "Δ",
728
+ Theta: "Θ",
729
+ Lambda: "Λ",
730
+ Xi: "Ξ",
731
+ Pi: "Π",
732
+ Sigma: "Σ",
733
+ Phi: "Φ",
734
+ Psi: "Ψ",
735
+ Omega: "Ω"
736
+ }, ne = {
737
+ cdot: ["·", "bin"],
738
+ times: ["×", "bin"],
739
+ div: ["÷", "bin"],
740
+ pm: ["±", "bin"],
741
+ mp: ["∓", "bin"],
742
+ circ: ["∘", "bin"],
743
+ cup: ["∪", "bin"],
744
+ cap: ["∩", "bin"],
745
+ land: ["∧", "bin"],
746
+ lor: ["∨", "bin"],
747
+ setminus: ["∖", "bin"],
748
+ le: ["≤", "rel"],
749
+ leq: ["≤", "rel"],
750
+ ge: ["≥", "rel"],
751
+ geq: ["≥", "rel"],
752
+ ne: ["≠", "rel"],
753
+ neq: ["≠", "rel"],
754
+ approx: ["≈", "rel"],
755
+ sim: ["∼", "rel"],
756
+ equiv: ["≡", "rel"],
757
+ propto: ["∝", "rel"],
758
+ to: ["→", "rel"],
759
+ rightarrow: ["→", "rel"],
760
+ leftarrow: ["←", "rel"],
761
+ mapsto: ["↦", "rel"],
762
+ Rightarrow: ["⇒", "rel"],
763
+ implies: ["⇒", "rel"],
764
+ iff: ["⇔", "rel"],
765
+ Leftrightarrow: ["⇔", "rel"],
766
+ in: ["∈", "rel"],
767
+ notin: ["∉", "rel"],
768
+ subset: ["⊂", "rel"],
769
+ subseteq: ["⊆", "rel"],
770
+ supset: ["⊃", "rel"],
771
+ mid: ["|", "rel"],
772
+ perp: ["⊥", "rel"],
773
+ infty: ["∞", "ord"],
774
+ partial: ["∂", "ord"],
775
+ nabla: ["∇", "ord"],
776
+ forall: ["∀", "ord"],
777
+ exists: ["∃", "ord"],
778
+ emptyset: ["∅", "ord"],
779
+ neg: ["¬", "ord"],
780
+ ldots: ["…", "ord"],
781
+ cdots: ["⋯", "ord"],
782
+ prime: ["′", "ord"],
783
+ hbar: ["ℏ", "ord"],
784
+ ell: ["ℓ", "ord"],
785
+ degree: ["°", "ord"],
786
+ lVert: ["‖", "open"],
787
+ rVert: ["‖", "close"],
788
+ langle: ["⟨", "open"],
789
+ rangle: ["⟩", "close"],
790
+ lbrace: ["{", "open"],
791
+ rbrace: ["}", "close"]
792
+ }, ie = { sum: ["∑", !0], prod: ["∏", !0], int: ["∫", !1], oint: ["∮", !1] }, re = {
793
+ sin: !1,
794
+ cos: !1,
795
+ tan: !1,
796
+ log: !1,
797
+ ln: !1,
798
+ exp: !1,
799
+ det: !1,
800
+ tr: !1,
801
+ rank: !1,
802
+ lim: !0,
803
+ max: !0,
804
+ min: !0,
805
+ argmax: !0,
806
+ argmin: !0,
807
+ arg: !1,
808
+ sup: !0,
809
+ inf: !0,
810
+ Pr: !1,
811
+ E: !1,
812
+ Var: !1
813
+ }, se = { ",": 3 / 18, ":": 4 / 18, ";": 5 / 18, "!": -3 / 18, quad: 1, qquad: 2 }, Ee = /* @__PURE__ */ new Set(["pmatrix", "bmatrix", "vmatrix", "matrix"]);
814
+ class On extends Error {
815
+ source;
816
+ /** 0-based index into the source */
817
+ position;
818
+ constructor(e, n, i) {
819
+ super(`${e} at ${i + 1} in "${n}"`), this.name = "TexError", this.source = n, this.position = i;
820
+ }
821
+ }
822
+ const Pn = [
823
+ ...Object.keys(ee),
824
+ ...Object.keys(ne),
825
+ ...Object.keys(ie),
826
+ ...Object.keys(re),
827
+ ...Object.keys(se).filter((t) => t.length > 1),
828
+ "frac",
829
+ "sqrt",
830
+ "vec",
831
+ "hat",
832
+ "bar",
833
+ "text",
834
+ "color",
835
+ "id",
836
+ "val",
837
+ "begin",
838
+ "end",
839
+ "left",
840
+ "right"
841
+ ].sort();
842
+ function Nn(t) {
843
+ if (typeof t != "string") throw new TypeError("parseTex: expected a string");
844
+ let e = 0;
845
+ const n = () => {
846
+ for (; e < t.length && /\s/.test(t[e]); ) e++;
847
+ }, i = (u, p = e) => {
848
+ throw new On(u, t, p);
849
+ }, s = () => {
850
+ const u = e;
851
+ if (/[A-Za-z]/.test(t[e] ?? ""))
852
+ for (; /[A-Za-z]/.test(t[e] ?? ""); ) e++;
853
+ else e < t.length ? e++ : i("A backslash with no command");
854
+ return t.slice(u, e);
855
+ }, r = (u) => {
856
+ n(), t[e] !== "{" && i(`Expected "{" for ${u}`);
857
+ const p = t.indexOf("}", e);
858
+ p < 0 && i(`Missing "}" for ${u}`);
859
+ const h = t.slice(e + 1, p);
860
+ return e = p + 1, h;
861
+ }, o = (u) => {
862
+ if (n(), e >= t.length && i(`Missing ${u}`), t[e] === "{") {
863
+ e++;
864
+ const h = l("}");
865
+ return e++, { type: "group", body: h };
866
+ }
867
+ const p = c();
868
+ return p || i(`Missing ${u}`), p;
869
+ }, l = (u) => {
870
+ const p = [];
871
+ for (; ; ) {
872
+ if (n(), e >= t.length)
873
+ return u === "}" && i('Missing "}"'), u === "cell" && i("Missing \\end"), p;
874
+ if (u === "}" && t[e] === "}" || (t[e] === "}" && i('Unexpected "}"'), u === "cell" && (t[e] === "&" || t.startsWith("\\\\", e) || t.startsWith("\\end", e)))) return p;
875
+ if (t[e] === "^" || t[e] === "_") {
876
+ const m = e, f = t[e] === "^";
877
+ e++;
878
+ const y = o(f ? "superscript" : "subscript");
879
+ let a = p.pop() ?? { type: "group", body: [] };
880
+ a.type !== "scripts" && (a = { type: "scripts", base: a }), a.type === "scripts" && ((f && a.sup || !f && a.sub) && i(`Double ${f ? "superscript" : "subscript"}`, m), f ? a.sup = y : a.sub = y), p.push(a);
881
+ continue;
882
+ }
883
+ if (t[e] === "'") {
884
+ e++;
885
+ const m = { type: "symbol", text: "′", cls: "ord", italic: !1 }, f = p.pop() ?? { type: "group", body: [] };
886
+ p.push(f.type === "scripts" && !f.sup ? { ...f, sup: m } : { type: "scripts", base: f, sup: m });
887
+ continue;
888
+ }
889
+ const h = c();
890
+ h && p.push(h);
891
+ }
892
+ }, c = () => {
893
+ const u = t[e];
894
+ if (u === "{") {
895
+ e++;
896
+ const p = l("}");
897
+ return e++, { type: "group", body: p };
898
+ }
899
+ if (u === "&" && i('"&" outside a matrix'), u === "\\") {
900
+ const p = e;
901
+ e++;
902
+ const h = s();
903
+ if (h === "\\" && i('"\\\\" outside a matrix', p), h in se) return { type: "space", width: se[h] };
904
+ if (h === "{" || h === "}") return { type: "symbol", text: h, cls: h === "{" ? "open" : "close", italic: !1 };
905
+ if (h === "|") return { type: "symbol", text: "‖", cls: "ord", italic: !1 };
906
+ if (Object.prototype.hasOwnProperty.call(ee, h))
907
+ return { type: "symbol", text: ee[h], cls: "ord", italic: h[0] === h[0].toLowerCase() };
908
+ if (Object.prototype.hasOwnProperty.call(ne, h)) {
909
+ const [f, y] = ne[h];
910
+ return { type: "symbol", text: f, cls: y, italic: !1 };
911
+ }
912
+ if (Object.prototype.hasOwnProperty.call(ie, h)) {
913
+ const [f, y] = ie[h];
914
+ return { type: "bigop", text: f, limits: y };
915
+ }
916
+ if (Object.prototype.hasOwnProperty.call(re, h)) return { type: "opname", text: h, limits: re[h] };
917
+ switch (h) {
918
+ case "frac":
919
+ return { type: "frac", num: o("numerator"), den: o("denominator") };
920
+ case "sqrt":
921
+ return { type: "sqrt", body: o("the square root's body") };
922
+ case "vec":
923
+ case "hat":
924
+ case "bar":
925
+ return { type: "accent", accent: h, body: o(`\\${h}'s body`) };
926
+ case "text":
927
+ return { type: "text", text: r("\\text") };
928
+ case "color": {
929
+ const f = r("\\color").trim();
930
+ return /^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)$/.test(f) || i(`"${f}" is not a colour name or #hex`, p), { type: "color", color: f, body: o("\\color's body") };
931
+ }
932
+ case "id": {
933
+ const f = r("\\id").trim();
934
+ return /^[\w.-]+$/.test(f) || i(`"${f}" is not a term id (letters, digits, _ . -)`, p), { type: "id", id: f, body: o("\\id's body") };
935
+ }
936
+ case "val": {
937
+ const f = r("\\val").trim(), y = /^([A-Za-z_][\w.]*)(?::(\d))?$/.exec(f);
938
+ return y || i(`"${f}" is not a value name (name or name:digits)`, p), { type: "value", name: y[1], digits: y[2] === void 0 ? 2 : Number(y[2]) };
939
+ }
940
+ case "left":
941
+ case "right": {
942
+ n();
943
+ const f = t[e] === "\\" ? (e++, s()) : t[e++];
944
+ if (f === ".") return { type: "space", width: 0 };
945
+ const a = { "(": "(", ")": ")", "[": "[", "]": "]", "|": "|", "{": "{", "}": "}", langle: "⟨", rangle: "⟩", "|.": "‖" }[f];
946
+ return a || i(`"${f}" is not a delimiter`, p), { type: "symbol", text: a, cls: h === "left" ? "open" : "close", italic: !1 };
947
+ }
948
+ case "begin": {
949
+ const f = r("\\begin").trim();
950
+ Ee.has(f) || i(`Unknown environment "${f}" (use ${[...Ee].join(", ")})`, p);
951
+ const y = [[]];
952
+ for (; ; ) {
953
+ const a = l("cell");
954
+ if (y[y.length - 1].push({ type: "group", body: a }), t[e] === "&")
955
+ e++;
956
+ else if (t.startsWith("\\\\", e))
957
+ e += 2, y.push([]);
958
+ else {
959
+ e += 4;
960
+ const g = r("\\end").trim();
961
+ g !== f && i(`\\begin{${f}} ended by \\end{${g}}`);
962
+ break;
963
+ }
964
+ }
965
+ return y.length > 1 && y[y.length - 1].every((a) => a.type === "group" && a.body.length === 0) && y.pop(), { type: "matrix", delimiters: f, rows: y };
966
+ }
967
+ case "end":
968
+ return i("\\end without \\begin", p);
969
+ }
970
+ const m = dn(h, Pn);
971
+ return i(`Unknown command "\\${h}"${m ? ` (did you mean "\\${m}"?)` : ""}`, p);
972
+ }
973
+ return e++, /[A-Za-z]/.test(u) ? { type: "symbol", text: u, cls: "ord", italic: !0 } : /[0-9.]/.test(u) ? { type: "symbol", text: u, cls: "ord", italic: !1 } : u === "+" ? { type: "symbol", text: "+", cls: "bin", italic: !1 } : u === "-" ? { type: "symbol", text: "−", cls: "bin", italic: !1 } : u === "*" ? { type: "symbol", text: "∗", cls: "bin", italic: !1 } : "=<>".includes(u) ? { type: "symbol", text: u, cls: "rel", italic: !1 } : "([".includes(u) ? { type: "symbol", text: u, cls: "open", italic: !1 } : ")]".includes(u) ? { type: "symbol", text: u, cls: "close", italic: !1 } : ",;".includes(u) ? { type: "symbol", text: u, cls: "punct", italic: !1 } : "|/!:".includes(u) ? { type: "symbol", text: u, cls: u === ":" ? "rel" : "ord", italic: !1 } : i(`Unexpected "${u}"`, e - 1);
974
+ };
975
+ return { type: "group", body: l("") };
976
+ }
977
+ const Z = [1, 1, 0.7, 0.5], In = (t) => t <= 1 ? 2 : 3, Ln = (t) => Math.min(3, t + 1), pe = () => ({ width: 0, height: 0, depth: 0, pieces: [] });
978
+ function Y(t, e, n) {
979
+ return t.pieces.map((i) => i.kind === "stroke" ? { ...i, points: i.points.map(([s, r]) => [s + e, r + n]) } : { ...i, x: i.x + e, y: i.y + n });
980
+ }
981
+ function mt(t, e) {
982
+ if (t.id) return t.id;
983
+ const n = (t.counts.get(e) ?? 0) + 1;
984
+ return t.counts.set(e, n), `${e}#${n}`;
985
+ }
986
+ function Te(t, e, n, i = 1, s = t) {
987
+ const r = Z[n.level] * i, o = te(t) * r, { height: l, depth: c } = Ge(t);
988
+ return {
989
+ width: o,
990
+ height: l * r,
991
+ depth: c * r,
992
+ pieces: [{ kind: "glyph", text: t, x: 0, y: 0, width: o, size: r, italic: e, ...n.color ? { color: n.color } : {}, id: mt(n, s) }]
993
+ };
994
+ }
995
+ function Xt(t, e, n) {
996
+ const i = pe(), s = mt(e, n), r = Z[e.level];
997
+ for (const o of t) {
998
+ const l = (o === " " ? 0.28 : /[A-Za-z]/.test(o) ? te(o) - 0.04 : te(o)) * r;
999
+ if (o !== " ") {
1000
+ const { height: c, depth: d } = Ge(o);
1001
+ i.pieces.push({ kind: "glyph", text: o, x: i.width, y: 0, width: l, size: r, italic: !1, ...e.color ? { color: e.color } : {}, id: s }), i.height = Math.max(i.height, c * r), i.depth = Math.max(i.depth, d * r);
1002
+ }
1003
+ i.width += l;
1004
+ }
1005
+ return i;
1006
+ }
1007
+ function oe(t) {
1008
+ switch (t.type) {
1009
+ case "symbol":
1010
+ return t.cls;
1011
+ case "bigop":
1012
+ case "opname":
1013
+ return "op";
1014
+ case "scripts":
1015
+ return oe(t.base);
1016
+ case "id":
1017
+ case "color":
1018
+ return oe(t.body);
1019
+ default:
1020
+ return "ord";
1021
+ }
1022
+ }
1023
+ function Fn(t, e) {
1024
+ return t === "bin" || e === "bin" ? 4 : t === "rel" || e === "rel" ? t === "open" || e === "close" || e === "punct" ? 0 : 5 : t === "punct" || t === "op" && (e === "ord" || e === "op") || e === "op" && t === "ord" ? 3 : 0;
1025
+ }
1026
+ function qn(t, e) {
1027
+ const n = pe();
1028
+ let i;
1029
+ return t.forEach((s) => {
1030
+ if (s.type === "space") {
1031
+ n.width += s.width * Z[e.level];
1032
+ return;
1033
+ }
1034
+ let r = oe(s);
1035
+ r === "bin" && (i === void 0 || i === "bin" || i === "rel" || i === "open" || i === "punct" || i === "op") && (r = "ord"), i !== void 0 && e.level <= 1 && (n.width += Fn(i, r) / 18 * Z[e.level]);
1036
+ const o = V(s, e);
1037
+ n.pieces.push(...Y(o, n.width, 0)), n.width += o.width, n.height = Math.max(n.height, o.height), n.depth = Math.max(n.depth, o.depth), i = r;
1038
+ }), n;
1039
+ }
1040
+ function Cn(t, e) {
1041
+ if (!Number.isFinite(t)) return t > 0 ? "∞" : t < 0 ? "−∞" : "?";
1042
+ const n = t.toFixed(e), i = n.includes(".") ? n.replace(/\.?0+$/, "") : n;
1043
+ return (i === "-0" ? "0" : i).replace("-", "−");
1044
+ }
1045
+ function V(t, e) {
1046
+ const n = Z[e.level];
1047
+ switch (t.type) {
1048
+ case "symbol":
1049
+ return Te(t.text, t.italic, e);
1050
+ case "group":
1051
+ return qn(t.body, e);
1052
+ case "space":
1053
+ return { ...pe(), width: t.width * n };
1054
+ case "text":
1055
+ return Xt(t.text, e, `text:${t.text}`);
1056
+ case "opname":
1057
+ return Xt(t.text, e, t.text);
1058
+ case "value": {
1059
+ const i = e.values[t.name];
1060
+ if (i === void 0) throw new Error(`\\val{${t.name}}: no value named "${t.name}"`);
1061
+ return Xt(Cn(i, t.digits), { ...e, id: e.id ?? `val:${t.name}` }, `val:${t.name}`);
1062
+ }
1063
+ case "bigop":
1064
+ return Te(t.text, !1, e, e.level === 0 ? 1.4 : 1.1);
1065
+ case "color":
1066
+ return V(t.body, { ...e, color: t.color });
1067
+ case "id":
1068
+ return V(t.body, { ...e, id: t.id });
1069
+ case "scripts":
1070
+ return zn(t, e);
1071
+ case "frac":
1072
+ return jn(t, e);
1073
+ case "sqrt":
1074
+ return Dn(t, e);
1075
+ case "accent":
1076
+ return Rn(t, e);
1077
+ case "matrix":
1078
+ return _n(t, e);
1079
+ }
1080
+ }
1081
+ function zn(t, e) {
1082
+ const n = V(t.base, e), i = { ...e, level: In(e.level) }, s = t.sup ? V(t.sup, i) : void 0, r = t.sub ? V(t.sub, i) : void 0, o = Z[e.level], l = e.level === 0 && (t.base.type === "bigop" && t.base.limits || t.base.type === "opname" && t.base.limits), c = { ...n, pieces: [...n.pieces] };
1083
+ if (l) {
1084
+ const m = Math.max(n.width, s?.width ?? 0, r?.width ?? 0), f = Y(n, (m - n.width) / 2, 0);
1085
+ let y = n.height, a = n.depth;
1086
+ const g = 0.12 * o;
1087
+ if (s) {
1088
+ const w = -(n.height + g + s.depth);
1089
+ f.push(...Y(s, (m - s.width) / 2, w)), y = -w + s.height;
1090
+ }
1091
+ if (r) {
1092
+ const w = n.depth + g + r.height;
1093
+ f.push(...Y(r, (m - r.width) / 2, w)), a = w + r.depth;
1094
+ }
1095
+ return { width: m, height: y, depth: a, pieces: f };
1096
+ }
1097
+ let d = s ? Math.max(0.42 * o, n.height - 0.3 * o, s.depth + 0.25 * o) : 0, u = r ? Math.max(0.2 * o, n.depth + 0.12 * o, r.height - 0.4 * o) : 0;
1098
+ if (s && r) {
1099
+ const m = d - s.depth - (r.height - u);
1100
+ m < 0.2 * o && (u += 0.2 * o - m);
1101
+ }
1102
+ const p = n.width + 0.03 * o;
1103
+ let h = n.width;
1104
+ return s ? (c.pieces.push(...Y(s, p, -d)), c.height = Math.max(c.height, d + s.height), h = Math.max(h, p + s.width)) : d = 0, r && (c.pieces.push(...Y(r, p, u)), c.depth = Math.max(c.depth, u + r.depth), h = Math.max(h, p + r.width)), c.width = h + 0.04 * o, c;
1105
+ }
1106
+ function jn(t, e) {
1107
+ const n = { ...e, level: Ln(e.level) }, i = V(t.num, n), s = V(t.den, n), r = Z[e.level], o = Mt * r, l = Ze * r, c = (e.level === 0 ? 0.16 : 0.1) * r, d = 0.1 * r, u = Math.max(i.width, s.width) + d * 2, p = -(l + o / 2 + c + i.depth), h = -l + o / 2 + c + s.height;
1108
+ return {
1109
+ width: u,
1110
+ height: -p + i.height,
1111
+ depth: h + s.depth,
1112
+ pieces: [
1113
+ ...Y(i, (u - i.width) / 2, p),
1114
+ { kind: "rule", x: 0, y: -l - o / 2, width: u, height: o, ...e.color ? { color: e.color } : {}, id: mt(e, "frac") },
1115
+ ...Y(s, (u - s.width) / 2, h)
1116
+ ]
1117
+ };
1118
+ }
1119
+ function Dn(t, e) {
1120
+ const n = V(t.body, e), i = Z[e.level], s = Math.max(n.height, 0.7 * i) + 0.14 * i, r = Math.max(n.depth, 0.05 * i) + 0.05 * i, o = 0.56 * i, l = o + n.width + 0.08 * i, c = [
1121
+ [0.02 * i, -0.36 * i],
1122
+ [0.13 * i, -0.44 * i],
1123
+ [0.3 * i, r],
1124
+ [o - 0.04 * i, -s],
1125
+ [l, -s]
1126
+ ];
1127
+ return {
1128
+ width: l,
1129
+ height: s + Mt * i,
1130
+ depth: r,
1131
+ pieces: [{ kind: "stroke", points: c, width: Mt * i, ...e.color ? { color: e.color } : {}, id: mt(e, "sqrt") }, ...Y(n, o, 0)]
1132
+ };
1133
+ }
1134
+ function Rn(t, e) {
1135
+ const n = V(t.body, e), i = Z[e.level], s = -(n.height + 0.12 * i), r = 0.04 * i, o = Math.max(n.width - 0.02 * i, r + 0.3 * i), l = e.color ? { color: e.color } : {}, c = mt(e, t.accent);
1136
+ let d;
1137
+ if (t.accent === "vec") {
1138
+ const u = 0.12 * i;
1139
+ d = [[[r, s], [o, s]], [[o - u, s - u * 0.7], [o, s], [o - u, s + u * 0.7]]];
1140
+ } else if (t.accent === "hat") {
1141
+ const u = (r + o) / 2;
1142
+ d = [[[u - 0.16 * i, s + 0.02 * i], [u, s - 0.12 * i], [u + 0.16 * i, s + 0.02 * i]]];
1143
+ } else
1144
+ d = [[[r, s], [o, s]]];
1145
+ return {
1146
+ width: Math.max(n.width, o + 0.02 * i),
1147
+ height: -s + 0.14 * i,
1148
+ depth: n.depth,
1149
+ pieces: [...n.pieces, ...d.map((u) => ({ kind: "stroke", points: u, width: Mt * i * 0.9, ...l, id: c }))]
1150
+ };
1151
+ }
1152
+ function _n(t, e) {
1153
+ const n = { ...e, level: Math.max(e.level, 1) }, i = Z[n.level], s = t.rows.map((k) => k.map(($) => V($, n))), r = Math.max(...s.map((k) => k.length)), o = Array.from({ length: r }, (k, $) => Math.max(0, ...s.map((x) => x[$]?.width ?? 0))), l = s.map((k) => Math.max(0.7 * i, ...k.map(($) => $.height))), c = s.map((k) => Math.max(0.2 * i, ...k.map(($) => $.depth))), d = 0.9 * i, u = 0.25 * i, p = t.delimiters === "matrix" ? 0 : 0.55 * i, h = o.reduce((k, $) => k + $, 0) + d * (r - 1), m = l.reduce((k, $, x) => k + $ + c[x], 0) + u * (s.length - 1), f = -Ze * i - m / 2, y = [];
1154
+ let a = f;
1155
+ s.forEach((k, $) => {
1156
+ a += l[$];
1157
+ let x = p;
1158
+ k.forEach((T, N) => {
1159
+ y.push(...Y(T, x + (o[N] - T.width) / 2, a)), x += o[N] + d;
1160
+ }), a += c[$] + u;
1161
+ });
1162
+ const g = h + p * 2, w = f + m, M = e.color ? { color: e.color } : {}, v = (k, $) => ({ kind: "stroke", points: k, width: Mt * i * 1.1, ...M, id: mt(e, $) }), b = 0.08 * i;
1163
+ if (t.delimiters === "pmatrix") {
1164
+ const k = ($) => {
1165
+ const x = $ === 1 ? p * 0.75 : g - p * 0.75, T = $ * p * 0.5;
1166
+ return Array.from({ length: 17 }, (N, q) => {
1167
+ const F = q / 16;
1168
+ return [x - T * Math.sin(Math.PI * F), f - b + (m + b * 2) * F];
1169
+ });
1170
+ };
1171
+ y.push(v(k(1), "("), v(k(-1), ")"));
1172
+ } else if (t.delimiters === "bmatrix") {
1173
+ const k = p * 0.35, $ = p * 0.2, x = g - p * 0.2;
1174
+ y.push(
1175
+ v([[$ + k, f - b], [$, f - b], [$, w + b], [$ + k, w + b]], "["),
1176
+ v([[x - k, f - b], [x, f - b], [x, w + b], [x - k, w + b]], "]")
1177
+ );
1178
+ } else t.delimiters === "vmatrix" && y.push(v([[p * 0.4, f - b], [p * 0.4, w + b]], "|"), v([[g - p * 0.4, f - b], [g - p * 0.4, w + b]], "|"));
1179
+ return { width: g, height: -f + b, depth: w + b, pieces: y };
1180
+ }
1181
+ function ut(t, e = {}) {
1182
+ const n = typeof t == "string" ? Nn(t) : t, i = { level: e.style === "inline" ? 1 : 0, values: e.values ?? {}, counts: /* @__PURE__ */ new Map() }, s = V(n, i);
1183
+ return { width: s.width, height: s.height, depth: s.depth, pieces: s.pieces };
1184
+ }
1185
+ const Oe = 'system-ui, -apple-system, "Segoe UI", sans-serif', Pe = (t, e) => Math.hypot(e[0] - t[0], e[1] - t[1]);
1186
+ function G(t, e) {
1187
+ if (e >= 1) return t;
1188
+ if (e <= 0) return [];
1189
+ const n = t.map((r) => r.slice(1).reduce((o, l, c) => o + Pe(r[c], l), 0));
1190
+ let i = n.reduce((r, o) => r + o, 0) * e;
1191
+ const s = [];
1192
+ for (const [r, o] of t.entries()) {
1193
+ if (i <= 0) break;
1194
+ if (n[r] <= i) {
1195
+ s.push(o), i -= n[r];
1196
+ continue;
1197
+ }
1198
+ const l = [o[0]];
1199
+ for (let c = 1; c < o.length; c++) {
1200
+ const d = Pe(o[c - 1], o[c]);
1201
+ if (d >= i) {
1202
+ const u = d === 0 ? 0 : i / d;
1203
+ l.push([o[c - 1][0] + (o[c][0] - o[c - 1][0]) * u, o[c - 1][1] + (o[c][1] - o[c - 1][1]) * u]);
1204
+ break;
1205
+ }
1206
+ l.push(o[c]), i -= d;
1207
+ }
1208
+ s.push(l), i = 0;
1209
+ }
1210
+ return s;
1211
+ }
1212
+ function fe(t, e) {
1213
+ const n = e.align ?? "center", i = n === "left" ? 0 : n === "right" ? -t.width : -t.width / 2, s = e.baseline === "baseline" ? 0 : (t.height - t.depth) / 2;
1214
+ return [e.x + i * e.size, e.y + s * e.size];
1215
+ }
1216
+ function Ke(t, e, n) {
1217
+ const [i, s] = e, r = n.size, o = n.opacity ?? 1;
1218
+ return t.map((l) => {
1219
+ const c = l.color ?? n.color, d = o * (l.opacity ?? 1), u = `${n.idPrefix}${l.id}`;
1220
+ if (l.kind === "glyph")
1221
+ return {
1222
+ type: "text",
1223
+ id: u,
1224
+ text: l.text,
1225
+ x: i + (l.x + l.width / 2) * r,
1226
+ y: s + l.y * r,
1227
+ size: l.size * r,
1228
+ font: Tn,
1229
+ italic: l.italic,
1230
+ color: c,
1231
+ align: "center",
1232
+ opacity: d
1233
+ };
1234
+ if (l.kind === "rule") {
1235
+ const p = i + l.x * r, h = s + l.y * r, m = l.width * r, f = Math.max(1, l.height * r);
1236
+ return { type: "line", id: u, points: [[p, h], [p + m, h], [p + m, h + f], [p, h + f]], closed: !0, fill: c, opacity: d };
1237
+ }
1238
+ return { type: "line", id: u, points: l.points.map(([p, h]) => [i + p * r, s + h * r]), stroke: c, width: Math.max(1, l.width * r), opacity: d };
1239
+ });
1240
+ }
1241
+ function yt(t, e) {
1242
+ return Ke(t.pieces, fe(t, e), e);
1243
+ }
1244
+ const jt = 480;
1245
+ function Je(t, e) {
1246
+ const n = [];
1247
+ let i = [];
1248
+ return t.forEach((s, r) => {
1249
+ const o = t[r - 1];
1250
+ (!s || o && Math.abs(s[1] - o[1]) > e * 1.5) && (i.length >= 2 && n.push(i), i = []), s && i.push(s);
1251
+ }), i.length >= 2 && n.push(i), n;
1252
+ }
1253
+ function Qe(t, e) {
1254
+ const n = Math.max(e.plane.width, e.plane.height) * 20;
1255
+ if (!(!Number.isFinite(t[0]) || !Number.isFinite(t[1])))
1256
+ return [Math.max(-n, Math.min(n, t[0])), Math.max(-n, Math.min(n, t[1]))];
1257
+ }
1258
+ function tn(t, e, n, i, s, r) {
1259
+ return G(e, s.draw).map((o, l) => ({ type: "line", id: `${t}.${l}`, points: o, stroke: n, width: i, opacity: s.opacity, ...r ? { dash: r } : {} }));
1260
+ }
1261
+ function Vt(t, e, n, i, s, r, o, l) {
1262
+ const c = Array.from({ length: jt + 1 }, (d, u) => {
1263
+ const p = n + (i - n) * u / jt;
1264
+ return Qe(o.plane.toScreen([p, e(p)]), o);
1265
+ });
1266
+ return tn(t, Je(c, o.plane.height), s, r, o, l);
1267
+ }
1268
+ function Vn(t, e) {
1269
+ const n = t.derivative ? he(t.expr, t.derivative) : R(t.expr, "x"), [i, s] = t.domain ?? e.plane.x, r = E(e.theme, t.color, e.theme.colors.blue), o = t.dashed ? [10 * e.plane.scale, 8 * e.plane.scale] : void 0;
1270
+ return Vt(t.id, (l) => n(l, e.scope), i, s, r, (t.width ?? 3.5) * e.plane.scale, e, o);
1271
+ }
1272
+ function Bn(t, e) {
1273
+ const n = R(t.x, "t"), i = R(t.y, "t"), s = ct(e.values, t.transform), [r, o] = t.t ?? [0, Math.PI * 2], l = Array.from({ length: jt + 1 }, (d, u) => {
1274
+ const p = r + (o - r) * u / jt;
1275
+ return Qe(e.plane.toScreen(U(s, [n(p, e.scope), i(p, e.scope)])), e);
1276
+ }), c = E(e.theme, t.color, e.theme.colors.blue);
1277
+ return tn(t.id, Je(l, e.plane.height), c, (t.width ?? 3.5) * e.plane.scale, e);
1278
+ }
1279
+ const me = (t, e, n, i, s) => [[e, n], [i, n], [i, s], [e, s]].map(t.plane.toScreen), Dt = (t) => Math.min(2e4, Math.max(0, Math.floor(t)));
1280
+ function Wn(t, e) {
1281
+ const n = ft(e.values, t.distribution), i = Ue(n, t.seed ?? t.id, Dt(S(e.values, t.count))), s = xn(i, t.bins ?? xe(n), t.scale ?? "density"), r = E(e.theme, t.color, e.theme.colors.blue), o = e.opacity * e.draw, l = s.flatMap(
1282
+ (c, d) => c.height > 0 ? [{ type: "line", id: `${t.id}.${d}`, points: me(e, c.left, 0, c.right, c.height), closed: !0, fill: r, stroke: e.theme.background, width: 1 * e.plane.scale, opacity: o * (t.fillOpacity ?? 0.75) }] : []
1283
+ );
1284
+ if (t.curve && (t.scale ?? "density") === "density") {
1285
+ const [c, d] = t.bins ?? xe(n), u = E(e.theme, "yellow", e.theme.colors.yellow);
1286
+ l.push(...Vt(`${t.id}.curve`, (p) => st(_t(n) ? { kind: "normal", mean: At(n), sd: Et(n) } : n, p), c, d, u, 3 * e.plane.scale, { ...e, draw: 1 }));
1287
+ }
1288
+ return l;
1289
+ }
1290
+ function Un(t, e) {
1291
+ const n = ft(e.values, t.distribution), i = E(e.theme, t.color, e.theme.colors.blue), [s, r] = t.domain ?? e.plane.x, o = t.shade ? [S(e.values, t.shade[0]), S(e.values, t.shade[1])].sort((d, u) => d - u) : void 0, l = E(e.theme, "yellow", e.theme.colors.yellow);
1292
+ if (_t(n)) {
1293
+ const d = [], u = Math.max(0, Math.ceil(s)), p = Math.floor(r), h = u + Math.ceil((p - u + 1) * e.draw);
1294
+ for (let m = u; m < h && m <= p; m++) {
1295
+ const f = st(n, m);
1296
+ if (f <= 0) continue;
1297
+ const y = o && m >= o[0] && m <= o[1];
1298
+ d.push({ type: "line", id: `${t.id}.${m}`, points: me(e, m - 0.4, 0, m + 0.4, f), closed: !0, fill: y ? l : i, opacity: e.opacity * (t.fillOpacity ?? 0.8) });
1299
+ }
1300
+ return d;
1301
+ }
1302
+ const c = [];
1303
+ if (o && e.draw >= 1) {
1304
+ const [d, u] = [Math.max(o[0], s), Math.min(o[1], r)];
1305
+ if (u > d) {
1306
+ const h = Array.from({ length: 121 }, (f, y) => {
1307
+ const a = d + (u - d) * y / 120;
1308
+ return [a, st(n, a)];
1309
+ }), m = [[d, 0], ...h, [u, 0]].map(e.plane.toScreen);
1310
+ c.push({ type: "line", id: `${t.id}.shade`, points: m, closed: !0, fill: l, opacity: e.opacity * (t.fillOpacity ?? 0.4) });
1311
+ }
1312
+ }
1313
+ return c.push(...Vt(t.id, (d) => st(n, d), s, r, i, (t.width ?? 3.5) * e.plane.scale, e)), c;
1314
+ }
1315
+ function Hn(t, e) {
1316
+ const n = t.rows ?? 10, i = t.spacing ?? 0.5, s = t.top ?? e.plane.y[1] - i, r = i * 0.9, o = (b, k) => [b * i, s - k * r], l = E(e.theme, "grey", e.theme.colors.grey), c = E(e.theme, t.color, e.theme.colors.yellow), d = i * 0.19 * e.plane.unitX, u = [];
1317
+ for (let b = 0; b < n; b++)
1318
+ for (let k = 0; k <= b; k++) {
1319
+ const [$, x] = e.plane.toScreen(o(k - b / 2, b));
1320
+ u.push({ type: "circle", id: `${t.id}.peg.${b}.${k}`, x: $, y: x, r: d * 0.45, fill: l, opacity: e.opacity * e.draw });
1321
+ }
1322
+ const p = n + 0.3, h = Math.max(n + 2, (s - e.plane.y[0]) / r - 0.2);
1323
+ for (let b = 0; b <= n + 1; b++) {
1324
+ const k = b - (n + 1) / 2, $ = G([[o(k, p), o(k, h)].map(e.plane.toScreen)], e.draw);
1325
+ for (const x of $) u.push({ type: "line", id: `${t.id}.bin.${b}`, points: x, stroke: l, width: 1.2 * e.plane.scale, opacity: e.opacity * 0.6 });
1326
+ }
1327
+ const m = G([[o(-(n + 1) / 2, h), o((n + 1) / 2, h)].map(e.plane.toScreen)], e.draw);
1328
+ for (const b of m) u.push({ type: "line", id: `${t.id}.floor`, points: b, stroke: l, width: 1.2 * e.plane.scale, opacity: e.opacity * 0.6 });
1329
+ const f = Math.max(0, S(e.values, t.balls)), y = Math.floor(f), a = t.seed ?? t.id, g = new Array(n + 1).fill(0), w = 2 * d / e.plane.unitY / r, M = (b, k) => ({ x: b - n / 2 + (k % 2 ? 0.22 : -0.22), depth: h - w * (Math.floor(k / 2) + 0.5) });
1330
+ for (let b = 0; b < y; b++) {
1331
+ const k = Ht(Se(a, b, n)), $ = M(k, g[k]), [x, T] = e.plane.toScreen(o($.x, $.depth));
1332
+ g[k]++, u.push({ type: "circle", id: `${t.id}.ball.${b}`, x, y: T, r: d, fill: c, opacity: e.opacity });
1333
+ }
1334
+ const v = f - y;
1335
+ if (v > 0) {
1336
+ const b = Se(a, y, n), k = Math.min(1, v / 0.8);
1337
+ let { x: $, depth: x } = En(b, k);
1338
+ if (x -= 1, v > 0.8) {
1339
+ const q = ((v - 0.8) / 0.2) ** 2, F = Ht(b), vt = M(F, g[F]), K = { x: Ht(b) - n / 2, depth: n - 1 };
1340
+ x = K.depth + (vt.depth - K.depth) * q, $ = K.x + (vt.x - K.x) * q;
1341
+ }
1342
+ const [T, N] = e.plane.toScreen(o($, x));
1343
+ u.push({ type: "circle", id: `${t.id}.falling`, x: T, y: N, r: d, fill: c, opacity: e.opacity });
1344
+ }
1345
+ return u;
1346
+ }
1347
+ function Xn(t, e) {
1348
+ const n = en(t, e), i = Xe(n, t.seed ?? t.id, Dt(S(e.values, t.count))), s = E(e.theme, t.color, e.theme.colors.blue), r = E(e.theme, t.insideColor, e.theme.colors.yellow), o = t.inside ? lt(t.inside) : void 0, l = (t.radius ?? 3) * e.plane.scale, c = i.map(([d, u], p) => {
1349
+ const [h, m] = e.plane.toScreen([d, u]), f = o ? rt(o, { ...e.scope, x: d, y: u }) <= 0 : !1;
1350
+ return { type: "circle", id: `${t.id}.${p}`, x: h, y: m, r: l, fill: f ? r : s, opacity: e.opacity * e.draw * 0.85 };
1351
+ });
1352
+ if (t.fit) {
1353
+ const d = Ye(i);
1354
+ if (d) {
1355
+ const [u, p] = e.plane.x;
1356
+ c.push({ type: "line", id: `${t.id}.fit`, points: [[u, d.slope * u + d.intercept], [p, d.slope * p + d.intercept]].map(e.plane.toScreen), stroke: E(e.theme, "red", e.theme.colors.red), width: 3 * e.plane.scale, opacity: e.opacity });
1357
+ }
1358
+ }
1359
+ return c;
1360
+ }
1361
+ function en(t, e) {
1362
+ const n = t.points;
1363
+ return n.kind === "uniform" ? n : { kind: "linear", slope: S(e.values, n.slope), intercept: S(e.values, n.intercept), noise: S(e.values, n.noise), x: n.x };
1364
+ }
1365
+ function Yn(t, e) {
1366
+ const n = S(e.values, t.prior), i = S(e.values, t.truePositive), s = S(e.values, t.falsePositive), r = e.plane.x[1] - e.plane.x[0], o = e.plane.y[1] - e.plane.y[0], [l, c] = t.size ?? [r * 0.8, o * 0.7], [d, u] = t.at ?? [e.plane.x[0] + r * 0.1, e.plane.y[0] + o * 0.08], p = d + l * Math.min(1, Math.max(0, n)), h = E(e.theme, t.color, e.theme.colors.yellow), m = E(e.theme, "red", e.theme.colors.red), f = E(e.theme, "grey", e.theme.colors.grey), y = e.opacity * e.draw, a = (b, k, $, x, T, N, q) => ({
1367
+ type: "line",
1368
+ id: `${t.id}.${b}`,
1369
+ points: me(e, k, $, x, T),
1370
+ closed: !0,
1371
+ fill: N,
1372
+ stroke: e.theme.background,
1373
+ width: 2 * e.plane.scale,
1374
+ opacity: y * q
1375
+ }), g = u + c, w = g - c * Math.min(1, Math.max(0, i)), M = g - c * Math.min(1, Math.max(0, s)), v = [
1376
+ a("tp", d, w, p, g, h, 0.85),
1377
+ a("fn", d, u, p, w, f, 0.35),
1378
+ a("fp", p, M, d + l, g, m, 0.8),
1379
+ a("tn", p, u, d + l, M, f, 0.2)
1380
+ ];
1381
+ if (t.labels !== !1 && e.draw >= 1) {
1382
+ const b = 20 * e.plane.scale, k = ($, x, T, N) => {
1383
+ const [q, F] = e.plane.toScreen(T);
1384
+ v.push(...yt(ut(x, { values: e.scope, style: "inline" }), { x: q, y: F, size: b, color: N, opacity: e.opacity, idPrefix: `${t.id}.label.${$}.` }));
1385
+ };
1386
+ k("prior", `\\text{has it: } \\val{${t.id}.prior:3}`, [d + l / 2, u - o * 0.04], e.theme.ink), k("tp", `\\text{has it, tests positive: } \\val{${t.id}.truePositive:3}`, [d + l / 2, u - o * 0.09], h), k("fp", `\\text{does not, tests positive: } \\val{${t.id}.falsePositive:3}`, [d + l / 2, u - o * 0.14], m), k("posterior", `P(\\text{has it} \\mid +) = \\val{${t.id}.posterior:3}`, [d + l / 2, u + c + o * 0.05], h);
1387
+ }
1388
+ return v;
1389
+ }
1390
+ function Yt(t, e, n, i = 512) {
1391
+ if (e === n) return 0;
1392
+ const s = (n - e) / i;
1393
+ let r = t(e) + t(n);
1394
+ for (let o = 1; o < i; o++) r += t(e + o * s) * (o % 2 ? 4 : 2);
1395
+ return r * s / 3;
1396
+ }
1397
+ function nn(t, e, n, i, s) {
1398
+ const r = (n - e) / i;
1399
+ return Array.from({ length: i }, (o, l) => {
1400
+ const c = e + l * r, d = c + r;
1401
+ if (s === "trapezoid") return [c, d, t(c), t(d)];
1402
+ const u = t(s === "left" ? c : s === "right" ? d : (c + d) / 2);
1403
+ return [c, d, u, u];
1404
+ });
1405
+ }
1406
+ const rn = (t) => Math.min(400, Math.max(1, Math.round(t)));
1407
+ function sn(t, e, n) {
1408
+ const i = {}, s = { ...n };
1409
+ for (const r of t)
1410
+ switch (r.kind) {
1411
+ case "tangent": {
1412
+ const o = R(r.expr), l = S(e, r.at), c = r.h === void 0 ? 0 : S(e, r.h), d = Math.abs(c) > 1e-9 ? (o(l + c, s) - o(l, s)) / c : he(r.expr, 1)(l, s);
1413
+ Object.assign(i, { [`${r.id}.slope`]: d, [`${r.id}.x`]: l, [`${r.id}.y`]: o(l, s) });
1414
+ break;
1415
+ }
1416
+ case "riemann": {
1417
+ const o = R(r.expr), l = S(e, r.from), c = S(e, r.to), d = rn(S(e, r.n)), p = nn((h) => o(h, s), l, c, d, r.rule ?? "left").reduce((h, [m, f, y, a]) => h + (y + a) / 2 * (f - m), 0);
1418
+ Object.assign(i, { [`${r.id}.sum`]: p, [`${r.id}.exact`]: Yt((h) => o(h, s), l, c), [`${r.id}.n`]: d });
1419
+ break;
1420
+ }
1421
+ case "area": {
1422
+ const o = R(r.expr), l = r.lower ? R(r.lower) : () => 0;
1423
+ i[`${r.id}.value`] = Yt((c) => o(c, s) - l(c, s), S(e, r.from), S(e, r.to));
1424
+ break;
1425
+ }
1426
+ case "point":
1427
+ if (r.on !== void 0 && r.x !== void 0) {
1428
+ const o = S(e, r.x);
1429
+ Object.assign(i, { [`${r.id}.x`]: o, [`${r.id}.y`]: R(r.on)(o, s) });
1430
+ }
1431
+ break;
1432
+ case "histogram": {
1433
+ const o = Ue(ft(e, r.distribution), r.seed ?? r.id, Dt(S(e, r.count))), { mean: l, sd: c } = Sn(o);
1434
+ Object.assign(i, { [`${r.id}.count`]: o.length, [`${r.id}.mean`]: l, [`${r.id}.sd`]: c });
1435
+ break;
1436
+ }
1437
+ case "distribution": {
1438
+ const o = ft(e, r.distribution);
1439
+ let l = 0;
1440
+ if (r.shade) {
1441
+ const [c, d] = [S(e, r.shade[0]), S(e, r.shade[1])].sort((u, p) => u - p);
1442
+ if (_t(o))
1443
+ for (let u = Math.max(0, Math.ceil(c)); u <= Math.floor(d) && u <= 5e3; u++) l += st(o, u);
1444
+ else
1445
+ l = Yt((u) => st(o, u), c, d, 2048);
1446
+ }
1447
+ Object.assign(i, { [`${r.id}.p`]: l, [`${r.id}.mean`]: At(o), [`${r.id}.sd`]: Et(o) });
1448
+ break;
1449
+ }
1450
+ case "galton":
1451
+ i[`${r.id}.landed`] = Math.max(0, Math.floor(S(e, r.balls)));
1452
+ break;
1453
+ case "scatter": {
1454
+ const o = Xe(en(r, { values: e }), r.seed ?? r.id, Dt(S(e, r.count))), l = r.inside ? lt(r.inside) : void 0, c = l ? o.filter(([u, p]) => rt(l, { ...s, x: u, y: p }) <= 0).length : 0, d = Ye(o);
1455
+ Object.assign(i, {
1456
+ [`${r.id}.count`]: o.length,
1457
+ [`${r.id}.inside`]: c,
1458
+ [`${r.id}.ratio`]: o.length ? c / o.length : 0,
1459
+ [`${r.id}.slope`]: d?.slope ?? 0,
1460
+ [`${r.id}.intercept`]: d?.intercept ?? 0,
1461
+ [`${r.id}.r`]: d?.r ?? 0
1462
+ });
1463
+ break;
1464
+ }
1465
+ case "bayes": {
1466
+ const o = S(e, r.prior), l = An(o, S(e, r.truePositive), S(e, r.falsePositive));
1467
+ Object.assign(i, { [`${r.id}.prior`]: o, [`${r.id}.posterior`]: l.posterior, [`${r.id}.positive`]: l.positive, [`${r.id}.truePositive`]: l.truePositive, [`${r.id}.falsePositive`]: l.falsePositive });
1468
+ break;
1469
+ }
1470
+ case "taylor":
1471
+ i[`${r.id}.order`] = Math.min(20, Math.max(0, S(e, r.order))), i[`${r.id}.degree`] = Math.floor(i[`${r.id}.order`]);
1472
+ break;
1473
+ }
1474
+ return i;
1475
+ }
1476
+ const B = (t, e, n) => t + (e - t) * n;
1477
+ function Ne(t, e, n) {
1478
+ return t.kind === "stroke" ? { ...t, points: t.points.map(([i, s]) => [i + e, s + n]) } : { ...t, x: t.x + e, y: t.y + n };
1479
+ }
1480
+ function Zn(t, e, n) {
1481
+ if (t.kind === "glyph" && e.kind === "glyph" && t.text === e.text)
1482
+ return { ...e, x: B(t.x, e.x, n), y: B(t.y, e.y, n), width: B(t.width, e.width, n), size: B(t.size, e.size, n) };
1483
+ if (t.kind === "rule" && e.kind === "rule")
1484
+ return { ...e, x: B(t.x, e.x, n), y: B(t.y, e.y, n), width: B(t.width, e.width, n), height: B(t.height, e.height, n) };
1485
+ if (t.kind === "stroke" && e.kind === "stroke" && t.points.length === e.points.length)
1486
+ return { ...e, width: B(t.width, e.width, n), points: t.points.map(([i, s], r) => [B(i, e.points[r][0], n), B(s, e.points[r][1], n)]) };
1487
+ }
1488
+ const Gn = (t) => t * t * (3 - 2 * t);
1489
+ function Kn(t, e, n) {
1490
+ const i = Math.min(1, Math.max(0, n)), s = t.layout.pieces.map((m) => Ne(m, t.x, t.y)), r = e.layout.pieces.map((m) => Ne(m, e.x, e.y));
1491
+ if (i === 0) return s.map((m) => ({ ...m, opacity: 1 }));
1492
+ if (i === 1) return r.map((m) => ({ ...m, opacity: 1 }));
1493
+ const o = (m) => {
1494
+ const f = /* @__PURE__ */ new Map();
1495
+ for (const y of m) f.set(y.id, [...f.get(y.id) ?? [], y]);
1496
+ return f;
1497
+ }, l = o(s), c = o(r), d = [], u = Gn(i), p = Math.max(0, 1 - i * 2), h = Math.max(0, i * 2 - 1);
1498
+ for (const m of /* @__PURE__ */ new Set([...l.keys(), ...c.keys()])) {
1499
+ const f = l.get(m) ?? [], y = c.get(m) ?? [], a = Math.max(f.length, y.length);
1500
+ for (let g = 0; g < a; g++) {
1501
+ const w = f[g], M = y[g], v = w && M ? Zn(w, M, u) : void 0;
1502
+ if (v) {
1503
+ d.push({ ...v, opacity: 1 });
1504
+ continue;
1505
+ }
1506
+ w && d.push({ ...w, opacity: p }), M && d.push({ ...M, opacity: h });
1507
+ }
1508
+ }
1509
+ return d.filter((m) => m.opacity > 0);
1510
+ }
1511
+ const Ie = [
1512
+ "grid",
1513
+ "axes",
1514
+ "vector",
1515
+ "basis",
1516
+ "point",
1517
+ "function",
1518
+ "parametric",
1519
+ "polygon",
1520
+ "line",
1521
+ "label",
1522
+ "equation",
1523
+ "tangent",
1524
+ "riemann",
1525
+ "area",
1526
+ "taylor",
1527
+ "histogram",
1528
+ "distribution",
1529
+ "galton",
1530
+ "scatter",
1531
+ "bayes"
1532
+ ], ae = {
1533
+ dark: {
1534
+ background: "#0f1117",
1535
+ ink: "#f2f2f2",
1536
+ grid: "#29abca",
1537
+ ghost: "rgba(255,255,255,0.18)",
1538
+ axes: "#f2f2f2",
1539
+ colors: { blue: "#58c4dd", green: "#83c167", red: "#fc6255", yellow: "#ffd75e", purple: "#b189f0", orange: "#ff9b4d", teal: "#5cd0b3", pink: "#f58ad1", ink: "#f2f2f2", grey: "#8a8f99" }
1540
+ },
1541
+ light: {
1542
+ background: "#fbfaf7",
1543
+ ink: "#1f2430",
1544
+ grid: "#7fb3d5",
1545
+ ghost: "rgba(31,36,48,0.14)",
1546
+ axes: "#1f2430",
1547
+ colors: { blue: "#2f6fd0", green: "#2f9a4a", red: "#d64545", yellow: "#c99a00", purple: "#7b4fc9", orange: "#e0761f", teal: "#178f7c", pink: "#c94f9c", ink: "#1f2430", grey: "#7a808c" }
1548
+ },
1549
+ chalk: {
1550
+ background: "#23332b",
1551
+ ink: "#eef0e6",
1552
+ grid: "rgba(238,240,230,0.35)",
1553
+ ghost: "rgba(238,240,230,0.14)",
1554
+ axes: "#eef0e6",
1555
+ colors: { blue: "#9fd3f0", green: "#b9e39a", red: "#f59a8f", yellow: "#f6e58d", purple: "#d0b5f2", orange: "#f7c08a", teal: "#a3e4d4", pink: "#f4b6dc", ink: "#eef0e6", grey: "#a9b0a6" }
1556
+ }
1557
+ }, Jn = /* @__PURE__ */ new Set([
1558
+ "x",
1559
+ "y",
1560
+ "z",
1561
+ "t",
1562
+ "opacity",
1563
+ "rotate",
1564
+ "rotateX",
1565
+ "rotateY",
1566
+ "scale",
1567
+ "scaleX",
1568
+ "scaleY",
1569
+ "skewX",
1570
+ "skewY",
1571
+ "originX",
1572
+ "originY",
1573
+ "perspective",
1574
+ "width",
1575
+ "height",
1576
+ "fill",
1577
+ "stroke",
1578
+ "fillStyle",
1579
+ "strokeStyle",
1580
+ "lineWidth",
1581
+ "strokeWidth",
1582
+ "filter",
1583
+ "blur",
1584
+ "visible",
1585
+ "clipTop",
1586
+ "clipRight",
1587
+ "clipBottom",
1588
+ "clipLeft",
1589
+ "quaternion"
1590
+ ]);
1591
+ function Tt(t) {
1592
+ const e = (a) => {
1593
+ throw new Error(`math figure: ${a}`);
1594
+ };
1595
+ (!t || typeof t != "object") && e("expected a figure object"), (!(t.width > 0) || !(t.height > 0)) && e("width and height must be positive numbers (px)");
1596
+ for (const a of ["x", "y"]) {
1597
+ const g = t[a];
1598
+ g !== void 0 && !(Array.isArray(g) && g.length === 2 && g.every(Number.isFinite) && g[0] < g[1]) && e(`${a} must be [min, max] with min < max`);
1599
+ }
1600
+ t.theme !== void 0 && !(t.theme in ae) && e(J("theme", t.theme, Object.keys(ae))), Array.isArray(t.items) || e("items must be an array");
1601
+ const n = t.values ?? {};
1602
+ for (const [a, g] of Object.entries(n))
1603
+ /^[A-Za-z_]\w*$/.test(a) || e(`value name "${a}" must be letters, digits and _ (starting with a letter)`), Jn.has(a) && e(`"${a}" cannot name a value: it is ${a === "x" || a === "t" ? "the variable of functions and curves" : "a property of the figure itself (its place, size or look)"}`), typeof g == "number" && Number.isFinite(g) || it(g) || pt(g) || e(`value "${a}" must be a number, an [x, y] vector or an [a, b, c, d] matrix`);
1604
+ const i = Be(n), s = Object.keys(n).filter((a) => typeof n[a] == "number"), r = (a, g, w) => {
1605
+ w !== void 0 && (typeof w == "string" ? (w in n || e(`${a.id}.${g}: ${J("value", w, Object.keys(n))}`), it(n[w]) || e(`${a.id}.${g}: value "${w}" is not an [x, y] vector`)) : it(w) || e(`${a.id}.${g} must be [x, y] or the name of a vector value`));
1606
+ }, o = (a, g, w) => {
1607
+ w !== void 0 && (w in n || e(`${a.id}.${g}: ${J("value", w, Object.keys(n))}`), pt(n[w]) || e(`${a.id}.${g}: value "${w}" is not an [a, b, c, d] matrix`));
1608
+ }, l = (a, g, w, M) => {
1609
+ let v = [];
1610
+ try {
1611
+ v = Me(lt(w));
1612
+ } catch (b) {
1613
+ e(`${a.id}.${g}: ${b.message}`);
1614
+ }
1615
+ for (const b of v)
1616
+ b !== M && !(b in Ct) && !s.includes(b) && e(`${a.id}.${g}: "${b}" is neither ${M} nor a number value (${J("value", b, [M, ...s])})`);
1617
+ }, c = [], d = (a, g, w) => {
1618
+ c.push([a, g, w]);
1619
+ }, u = (a, g, w) => {
1620
+ w !== void 0 && (typeof w == "string" ? (w in n || e(`${a.id}.${g}: ${J("value", w, s)}`), typeof n[w] != "number" && e(`${a.id}.${g}: value "${w}" is not a number`)) : Number.isFinite(w) || e(`${a.id}.${g} must be a number or the name of a number value`));
1621
+ }, p = (a, g, w) => {
1622
+ (!w || typeof w != "object" || !zt.includes(w.kind)) && e(`${a.id}.${g}: ${J("distribution", w?.kind, zt)}`);
1623
+ for (const [v, b] of Object.entries(w))
1624
+ v !== "kind" && (v === "of" ? p(a, `${g}.of`, b) : u(a, `${g}.${v}`, b));
1625
+ const M = He(ft(n, w));
1626
+ M && e(`${a.id}.${g}: ${M}`);
1627
+ }, h = (a, g, w) => {
1628
+ let M = [];
1629
+ try {
1630
+ M = Me(lt(w));
1631
+ } catch (v) {
1632
+ e(`${a.id}.${g}: ${v.message}`);
1633
+ }
1634
+ for (const v of M)
1635
+ v !== "x" && v !== "y" && !s.includes(v) && e(`${a.id}.${g}: "${v}" is neither x, y nor a number value`);
1636
+ }, m = (a, g, w, M) => {
1637
+ try {
1638
+ let v = lt(w);
1639
+ for (let b = 0; b < M; b++) v = tt(v);
1640
+ } catch (v) {
1641
+ e(`${a.id}.${g}: ${v.message} (calculus needs functions with derivatives)`);
1642
+ }
1643
+ }, f = /* @__PURE__ */ new Set();
1644
+ for (const a of t.items)
1645
+ switch ((!a || typeof a != "object") && e("every item must be an object"), Ie.includes(a.kind) || e(J("item kind", a.kind, Ie)), (typeof a.id != "string" || !/^[A-Za-z_][\w-]*$/.test(a.id)) && e(`a ${a.kind} needs an id (letters, digits, _ and -)`), f.has(a.id) && e(`two items have the id "${a.id}"`), a.id in n && e(`"${a.id}" is both an item id and a value name`), f.add(a.id), a.kind) {
1646
+ case "grid":
1647
+ a.step !== void 0 && !(a.step > 0) && e(`${a.id}.step must be positive`), o(a, "transform", a.transform);
1648
+ break;
1649
+ case "vector":
1650
+ r(a, "to", a.to), r(a, "from", a.from), o(a, "transform", a.transform), a.label && d(a, "label", a.label);
1651
+ break;
1652
+ case "basis":
1653
+ o(a, "transform", a.transform);
1654
+ break;
1655
+ case "point":
1656
+ a.at === void 0 == (a.on === void 0) && e(`${a.id} needs at, or on with x (a point on a curve)`), a.on !== void 0 && (a.x === void 0 && e(`${a.id}: a point on a curve needs x`), l(a, "on", a.on, "x"), u(a, "x", a.x)), r(a, "at", a.at), o(a, "transform", a.transform), a.label && d(a, "label", a.label);
1657
+ break;
1658
+ case "function":
1659
+ l(a, "expr", a.expr, "x"), a.derivative !== void 0 && ((!Number.isInteger(a.derivative) || a.derivative < 0 || a.derivative > 8) && e(`${a.id}.derivative must be a whole number from 0 to 8`), m(a, "expr", a.expr, a.derivative));
1660
+ break;
1661
+ case "tangent":
1662
+ l(a, "expr", a.expr, "x"), m(a, "expr", a.expr, 1), u(a, "at", a.at), u(a, "h", a.h), a.label && d(a, "label", a.label);
1663
+ break;
1664
+ case "riemann":
1665
+ l(a, "expr", a.expr, "x"), u(a, "from", a.from), u(a, "to", a.to), u(a, "n", a.n), a.rule !== void 0 && !["left", "right", "midpoint", "trapezoid"].includes(a.rule) && e(`${a.id}.rule: ${J("rule", a.rule, ["left", "right", "midpoint", "trapezoid"])}`);
1666
+ break;
1667
+ case "area":
1668
+ l(a, "expr", a.expr, "x"), a.lower !== void 0 && l(a, "lower", a.lower, "x"), u(a, "from", a.from), u(a, "to", a.to);
1669
+ break;
1670
+ case "histogram":
1671
+ p(a, "distribution", a.distribution), u(a, "count", a.count), a.bins !== void 0 && !(Array.isArray(a.bins) && a.bins.length === 3 && a.bins[1] > a.bins[0] && Number.isInteger(a.bins[2]) && a.bins[2] >= 1 && a.bins[2] <= 500) && e(`${a.id}.bins must be [from, to, count] with from < to and a whole count 1..500`);
1672
+ break;
1673
+ case "distribution":
1674
+ p(a, "distribution", a.distribution), a.shade && a.shade.forEach((g, w) => u(a, `shade[${w}]`, g));
1675
+ break;
1676
+ case "galton":
1677
+ a.rows !== void 0 && !(Number.isInteger(a.rows) && a.rows >= 1 && a.rows <= 30) && e(`${a.id}.rows must be a whole number 1..30`), u(a, "balls", a.balls);
1678
+ break;
1679
+ case "scatter":
1680
+ (!a.points || !["uniform", "linear"].includes(a.points.kind)) && e(`${a.id}.points: ${J("points kind", a.points?.kind, ["uniform", "linear"])}`), a.points.kind === "linear" && (u(a, "points.slope", a.points.slope), u(a, "points.intercept", a.points.intercept), u(a, "points.noise", a.points.noise)), u(a, "count", a.count), a.inside && h(a, "inside", a.inside);
1681
+ break;
1682
+ case "bayes":
1683
+ u(a, "prior", a.prior), u(a, "truePositive", a.truePositive), u(a, "falsePositive", a.falsePositive);
1684
+ break;
1685
+ case "taylor":
1686
+ l(a, "expr", a.expr, "x"), m(a, "expr", a.expr, 3), u(a, "at", a.at), u(a, "order", a.order);
1687
+ break;
1688
+ case "parametric":
1689
+ l(a, "x", a.x, "t"), l(a, "y", a.y, "t"), o(a, "transform", a.transform);
1690
+ break;
1691
+ case "polygon":
1692
+ a.points !== void 0 && !(Array.isArray(a.points) && a.points.length >= 3 && a.points.every(it)) && e(`${a.id}.points must be three or more [x, y] points`), o(a, "transform", a.transform), a.label && d(a, "label", a.label);
1693
+ break;
1694
+ case "line":
1695
+ a.along === void 0 == (a.eigen === void 0) && e(`${a.id} needs exactly one of along or eigen`), r(a, "along", a.along), o(a, "eigen", a.eigen);
1696
+ break;
1697
+ case "label":
1698
+ r(a, "at", a.at), d(a, "tex", a.tex);
1699
+ break;
1700
+ case "equation":
1701
+ r(a, "at", a.at), (!Array.isArray(a.steps) || a.steps.length === 0) && e(`${a.id}.steps needs at least one TeX step`), a.steps.forEach((g, w) => d(a, `steps[${w}]`, g));
1702
+ break;
1703
+ }
1704
+ const y = { ...i, ...sn(t.items, n, i) };
1705
+ for (const [a, g, w] of c)
1706
+ try {
1707
+ ut(w, { values: y });
1708
+ } catch (M) {
1709
+ e(`${a.id}.${g}: ${M.message}`);
1710
+ }
1711
+ return t;
1712
+ }
1713
+ function on(t) {
1714
+ const { width: e, height: n } = t, i = t.x ?? [-5, 5], s = e / (i[1] - i[0]), r = t.y ?? [-(n / s) / 2, n / s / 2], o = n / (r[1] - r[0]);
1715
+ return {
1716
+ width: e,
1717
+ height: n,
1718
+ x: i,
1719
+ y: r,
1720
+ unitX: s,
1721
+ unitY: o,
1722
+ scale: Math.min(e, n) / 600,
1723
+ toScreen: ([l, c]) => [(l - i[0]) * s, (r[1] - c) * o],
1724
+ toWorld: ([l, c]) => [i[0] + l / s, r[1] - c / o]
1725
+ };
1726
+ }
1727
+ function Qn(t, e) {
1728
+ const n = Math.max(Math.abs(t.x[0]), Math.abs(t.x[1]), Math.abs(t.y[0]), Math.abs(t.y[1])), [i, s, r, o] = e, l = Math.hypot(i, s, r, o), c = l === 0 ? 0 : Math.abs(St(e)) / l;
1729
+ return Math.min(n * 12, n / Math.max(c, 0.08)) + 1;
1730
+ }
1731
+ function Le(t, e, n) {
1732
+ const i = Qn(t, e), s = Math.min(120, Math.ceil(i / n)), r = [];
1733
+ for (let o = -s; o <= s; o++) {
1734
+ const l = o * n;
1735
+ r.push({ line: [U(e, [l, -i]), U(e, [l, i])].map(t.toScreen), axis: o === 0 }), r.push({ line: [U(e, [-i, l]), U(e, [i, l])].map(t.toScreen), axis: o === 0 });
1736
+ }
1737
+ return r;
1738
+ }
1739
+ function ti(t, e) {
1740
+ const { plane: n, theme: i } = e, s = t.step ?? 1, r = [], o = 1.4 * n.scale;
1741
+ if (t.ghost)
1742
+ for (const [c, { line: d }] of Le(n, [1, 0, 0, 1], s).entries())
1743
+ r.push({ type: "line", id: `${t.id}.ghost.${c}`, points: d, stroke: i.ghost, width: o, opacity: e.opacity });
1744
+ const l = E(i, t.color, i.grid);
1745
+ for (const [c, { line: d, axis: u }] of Le(n, ct(e.values, t.transform), s).entries()) {
1746
+ const [p] = G([d], e.draw);
1747
+ p && r.push({ type: "line", id: `${t.id}.${c}`, points: p, stroke: u ? i.ink : l, width: u ? o * 1.6 : o, opacity: e.opacity });
1748
+ }
1749
+ return r;
1750
+ }
1751
+ function ei(t, e) {
1752
+ const { plane: n, theme: i } = e, s = E(i, t.color, i.axes), r = 2 * n.scale, o = e.opacity, l = G([[n.toScreen([n.x[0], 0]), n.toScreen([n.x[1], 0])]], e.draw), c = G([[n.toScreen([0, n.y[0]]), n.toScreen([0, n.y[1]])]], e.draw), d = [...l, ...c].map((y, a) => ({ type: "line", id: `${t.id}.${a ? "y" : "x"}`, points: y, stroke: s, width: r, opacity: o })), u = t.ticks ?? 1;
1753
+ if (u <= 0 || e.draw < 1) return d;
1754
+ const p = 5 * n.scale, h = 13 * n.scale, m = (y, a) => {
1755
+ const g = [];
1756
+ for (let w = Math.ceil(y / u) * u; w <= a + 1e-9; w += u) Math.abs(w) > 1e-9 && g.push(Number(w.toFixed(6)));
1757
+ return g;
1758
+ }, f = (y) => String(y).replace("-", "−");
1759
+ for (const y of m(n.x[0], n.x[1])) {
1760
+ const [a, g] = n.toScreen([y, 0]);
1761
+ d.push({ type: "line", id: `${t.id}.tick.x${y}`, points: [[a, g - p], [a, g + p]], stroke: s, width: r * 0.8, opacity: o }), t.labels !== !1 && d.push({ type: "text", id: `${t.id}.label.x${y}`, text: f(y), x: a, y: g + p + h * 1.1, size: h, font: Oe, color: s, align: "center", opacity: o * 0.8 });
1762
+ }
1763
+ for (const y of m(n.y[0], n.y[1])) {
1764
+ const [a, g] = n.toScreen([0, y]);
1765
+ d.push({ type: "line", id: `${t.id}.tick.y${y}`, points: [[a - p, g], [a + p, g]], stroke: s, width: r * 0.8, opacity: o }), t.labels !== !1 && d.push({ type: "text", id: `${t.id}.label.y${y}`, text: f(y), x: a - p - h * 0.4, y: g + h * 0.35, size: h, font: Oe, color: s, align: "right", opacity: o * 0.8 });
1766
+ }
1767
+ return d;
1768
+ }
1769
+ function Rt(t, e, n, i, s, r) {
1770
+ const o = 26 * r.plane.scale, [l, c] = _e(n), d = ut(t, { values: r.scope, style: "inline" }), u = o * (0.55 + Math.abs(l) * d.width * 0.5);
1771
+ return yt(d, { x: e[0] + l * u, y: e[1] + c * u, size: o, color: i, opacity: r.opacity, idPrefix: `${s}.label.` });
1772
+ }
1773
+ function an(t, e, n, i, s, r) {
1774
+ const o = r.plane.toScreen(e), l = r.plane.toScreen(n), [c] = G([[o, l]], r.draw);
1775
+ if (!c) return [];
1776
+ const d = Math.hypot(l[0] - o[0], l[1] - o[1]), u = Math.min(s * 3.6, d * 0.45);
1777
+ return [{ type: "arrow", id: t, points: c, stroke: i, width: s, head: u, opacity: r.opacity }];
1778
+ }
1779
+ function ni(t, e) {
1780
+ const n = ct(e.values, t.transform), i = U(n, t.from === void 0 ? [0, 0] : $t(e.values, t.from)), s = U(n, $t(e.values, t.to)), r = E(e.theme, t.color, e.theme.colors.yellow), o = an(t.id, i, s, r, (t.width ?? 4) * e.plane.scale, e);
1781
+ if (t.label && e.draw >= 1) {
1782
+ const l = e.plane.toScreen(s), c = e.plane.toScreen(i), d = de(l, c);
1783
+ if (t.labelAt === "middle") {
1784
+ const u = [(l[0] + c[0]) / 2, (l[1] + c[1]) / 2];
1785
+ o.push(...Rt(t.label, u, [d[1], -d[0]], r, t.id, e));
1786
+ } else
1787
+ o.push(...Rt(t.label, l, d, r, t.id, e));
1788
+ }
1789
+ return o;
1790
+ }
1791
+ function ii(t, e) {
1792
+ const n = ct(e.values, t.transform), i = 4.5 * e.plane.scale, s = e.plane.toScreen([0, 0]), r = [], o = [
1793
+ ["i", [1, 0], e.theme.colors.green, "\\hat{i}"],
1794
+ ["j", [0, 1], e.theme.colors.red, "\\hat{j}"]
1795
+ ];
1796
+ for (const [l, c, d, u] of o) {
1797
+ const p = U(n, c);
1798
+ if (r.push(...an(`${t.id}.${l}`, [0, 0], p, d, i, e)), t.labels !== !1 && e.draw >= 1) {
1799
+ const h = e.plane.toScreen(p);
1800
+ r.push(...Rt(u, h, de(h, s), d, `${t.id}.${l}`, e));
1801
+ }
1802
+ }
1803
+ return r;
1804
+ }
1805
+ function ri(t, e) {
1806
+ const n = t.on !== void 0 ? [e.scope[`${t.id}.x`], e.scope[`${t.id}.y`]] : $t(e.values, t.at);
1807
+ if (!Number.isFinite(n[0]) || !Number.isFinite(n[1])) return [];
1808
+ const i = U(ct(e.values, t.transform), n), [s, r] = e.plane.toScreen(i), o = E(e.theme, t.color, e.theme.colors.yellow), l = (t.radius ?? 6) * e.plane.scale * Math.min(1, e.draw * 2), c = t.hollow ? { type: "circle", id: t.id, x: s, y: r, r: l, fill: e.theme.background, stroke: o, width: 2.5 * e.plane.scale, opacity: e.opacity } : { type: "circle", id: t.id, x: s, y: r, r: l, fill: o, opacity: e.opacity }, d = l > 0 ? [c] : [];
1809
+ return t.label && e.draw >= 1 && d.push(...Rt(t.label, [s, r], [0.7, -0.7], o, t.id, e)), d;
1810
+ }
1811
+ const si = [[0, 0], [1, 0], [1, 1], [0, 1]];
1812
+ function oi(t, e) {
1813
+ const n = ct(e.values, t.transform), i = (t.points ?? si).map((l) => U(n, l)), s = i.map(e.plane.toScreen), r = E(e.theme, t.color, e.theme.colors.yellow), o = [
1814
+ { type: "line", id: `${t.id}.fill`, points: s, closed: !0, fill: r, opacity: e.opacity * (t.fillOpacity ?? 0.3) * e.draw },
1815
+ ...G([[...s, s[0]]], e.draw).map((l) => ({ type: "line", id: `${t.id}.outline`, points: l, stroke: r, width: 2.5 * e.plane.scale, opacity: e.opacity }))
1816
+ ];
1817
+ if (t.label && e.draw >= 1) {
1818
+ const l = i.reduce((u, p) => [u[0] + p[0] / i.length, u[1] + p[1] / i.length], [0, 0]), [c, d] = e.plane.toScreen(l);
1819
+ o.push(...yt(ut(t.label, { values: e.scope, style: "inline" }), { x: c, y: d, size: 24 * e.plane.scale, color: e.theme.ink, opacity: e.opacity, idPrefix: `${t.id}.label.` }));
1820
+ }
1821
+ return o;
1822
+ }
1823
+ function ai(t, e) {
1824
+ const n = t.eigen ? Ve(ct(e.values, t.eigen)).map((o) => o.vector) : t.along !== void 0 ? [$t(e.values, t.along)] : [], i = Math.max(Math.abs(e.plane.x[0]), Math.abs(e.plane.x[1]), Math.abs(e.plane.y[0]), Math.abs(e.plane.y[1])) * 1.5, s = E(e.theme, t.color, e.theme.colors.yellow), r = (t.width ?? 2.5) * e.plane.scale;
1825
+ return n.flatMap((o, l) => {
1826
+ const c = Math.hypot(o[0], o[1]);
1827
+ if (c === 0) return [];
1828
+ const d = Jt(o, i / c), u = [Jt(d, -1), d].map(e.plane.toScreen);
1829
+ return G([u], e.draw).map((p) => ({
1830
+ type: "line",
1831
+ id: `${t.id}.${l}`,
1832
+ points: p,
1833
+ stroke: s,
1834
+ width: r,
1835
+ opacity: e.opacity,
1836
+ ...t.dashed ? { dash: [10 * e.plane.scale, 8 * e.plane.scale] } : {}
1837
+ }));
1838
+ });
1839
+ }
1840
+ function le(t, e, n, i) {
1841
+ const s = n.size * 0.35;
1842
+ let r = 1 / 0, o = 1 / 0, l = -1 / 0, c = -1 / 0;
1843
+ for (const d of e) {
1844
+ const [u, p] = fe(d, n);
1845
+ r = Math.min(r, u - s), l = Math.max(l, u + d.width * n.size + s), o = Math.min(o, p - d.height * n.size - s), c = Math.max(c, p + d.depth * n.size + s);
1846
+ }
1847
+ return [{
1848
+ type: "line",
1849
+ id: `${t}.backdrop`,
1850
+ points: [[r, o], [l, o], [l, c], [r, c]],
1851
+ closed: !0,
1852
+ fill: i.theme.background,
1853
+ opacity: (n.opacity ?? 1) * 0.85
1854
+ }];
1855
+ }
1856
+ function ln(t, e, n) {
1857
+ const i = $t(n.values, t);
1858
+ return e ? i : n.plane.toScreen(i);
1859
+ }
1860
+ function li(t, e) {
1861
+ const [n, i] = ln(t.at, t.screen, e), s = (t.size ?? 28) * e.plane.scale, r = E(e.theme, t.color, e.theme.ink), o = { x: n, y: i, size: s, color: r, align: t.align, opacity: e.opacity * e.draw, idPrefix: `${t.id}.` }, l = ut(t.tex, { values: e.scope });
1862
+ return [...t.backdrop ?? t.screen ?? !1 ? le(t.id, [l], o, e) : [], ...yt(l, o)];
1863
+ }
1864
+ function ci(t, e) {
1865
+ const [n, i] = ln(t.at, t.screen, e), s = (t.size ?? 36) * e.plane.scale, r = E(e.theme, t.color, e.theme.ink), o = t.steps.length - 1, l = Math.min(o, Math.max(0, e.prop("step") ?? t.step ?? 0)), c = Math.floor(l), d = l - c, u = { x: n, y: i, size: s, color: r, align: t.align, opacity: e.opacity * e.draw, idPrefix: `${t.id}.` }, p = (a) => ut(t.steps[a], { values: e.scope }), h = t.backdrop ?? t.screen ?? !1;
1866
+ if (d === 0 || c >= o) {
1867
+ const a = p(c);
1868
+ return [...h ? le(t.id, [a], u, e) : [], ...yt(a, u)];
1869
+ }
1870
+ const m = (a) => {
1871
+ const [g, w] = fe(a, u);
1872
+ return { layout: a, x: g / s, y: w / s };
1873
+ }, f = p(c), y = p(c + 1);
1874
+ return [
1875
+ ...h ? le(t.id, [f, y], u, e) : [],
1876
+ ...Ke(Kn(m(f), m(y), d), [0, 0], u)
1877
+ ];
1878
+ }
1879
+ function ui(t, e) {
1880
+ const n = R(t.expr), i = S(e.values, t.at), s = t.h === void 0 ? 0 : S(e.values, t.h), r = n(i, e.scope), o = e.scope[`${t.id}.slope`];
1881
+ if (!Number.isFinite(r) || !Number.isFinite(o)) return [];
1882
+ const l = t.length !== void 0 ? t.length / 2 : Math.max(Math.abs(e.plane.x[0] - i), Math.abs(e.plane.x[1] - i)), c = [[i - l, r - o * l], [i + l, r + o * l]], d = E(e.theme, t.color, e.theme.colors.yellow), u = e.plane.toScreen([i, r]), p = c.map(e.plane.toScreen), h = [p[0], p[1]].flatMap(
1883
+ (m, f) => G([[u, m]], e.draw).map((y) => ({ type: "line", id: `${t.id}.${f}`, points: y, stroke: d, width: (t.width ?? 3) * e.plane.scale, opacity: e.opacity }))
1884
+ );
1885
+ if (t.points !== !1) {
1886
+ const m = 6 * e.plane.scale;
1887
+ if (h.push({ type: "circle", id: `${t.id}.point`, x: u[0], y: u[1], r: m, fill: d, opacity: e.opacity }), Math.abs(s) > 1e-9) {
1888
+ const [f, y] = e.plane.toScreen([i + s, n(i + s, e.scope)]);
1889
+ Number.isFinite(y) && h.push({ type: "circle", id: `${t.id}.secant`, x: f, y, r: m, fill: d, opacity: e.opacity });
1890
+ }
1891
+ }
1892
+ if (t.label && e.draw >= 1) {
1893
+ const m = 24 * e.plane.scale, f = ut(t.label, { values: e.scope, style: "inline" });
1894
+ h.push(...yt(f, { x: u[0], y: u[1] - m * 1.6, size: m, color: d, opacity: e.opacity, idPrefix: `${t.id}.label.` }));
1895
+ }
1896
+ return h;
1897
+ }
1898
+ function di(t, e) {
1899
+ const n = R(t.expr), i = S(e.values, t.from), s = S(e.values, t.to), r = rn(S(e.values, t.n)), o = nn((u) => n(u, e.scope), i, s, r, t.rule ?? "left"), l = E(e.theme, t.color, e.theme.colors.blue), c = Math.ceil(o.length * e.draw), d = Math.max(0.5, Math.min(1.5, 60 / r)) * e.plane.scale;
1900
+ return o.slice(0, c).flatMap(([u, p, h, m], f) => {
1901
+ if (!Number.isFinite(h) || !Number.isFinite(m)) return [];
1902
+ const y = [[u, 0], [p, 0], [p, m], [u, h]].map(e.plane.toScreen), g = (h + m) / 2 < 0 ? E(e.theme, "red", e.theme.colors.red) : l;
1903
+ return [{ type: "line", id: `${t.id}.${f}`, points: y, closed: !0, fill: g, stroke: g, width: d, opacity: e.opacity * (t.fillOpacity ?? 0.35) }];
1904
+ });
1905
+ }
1906
+ function hi(t, e) {
1907
+ const n = R(t.expr), i = t.lower ? R(t.lower) : () => 0, s = S(e.values, t.from), r = s + (S(e.values, t.to) - s) * e.draw;
1908
+ if (s === r) return [];
1909
+ const o = 240, l = E(e.theme, t.color, e.theme.colors.blue), c = E(e.theme, t.negativeColor, e.theme.colors.red), d = e.opacity * (t.fillOpacity ?? 0.4), u = [];
1910
+ let p = [], h = [], m;
1911
+ const f = () => {
1912
+ p.length >= 2 && u.push({ type: "line", id: `${t.id}.${u.length}`, points: [...p, ...h.reverse()].map(e.plane.toScreen), closed: !0, fill: m ? l : c, opacity: d }), p = [], h = [];
1913
+ };
1914
+ let y;
1915
+ for (let a = 0; a <= o; a++) {
1916
+ const g = s + (r - s) * a / o, w = n(g, e.scope), M = i(g, e.scope);
1917
+ if (!Number.isFinite(w) || !Number.isFinite(M)) {
1918
+ f(), y = void 0;
1919
+ continue;
1920
+ }
1921
+ const v = w - M >= 0;
1922
+ if (y && m !== void 0 && v !== m) {
1923
+ const b = y.fy - y.gy, k = w - M, $ = b / (b - k), x = y.x + (g - y.x) * $, T = y.gy + (M - y.gy) * $;
1924
+ p.push([x, T]), h.push([x, T]), f(), p.push([x, T]), h.push([x, T]);
1925
+ }
1926
+ m = v, p.push([g, w]), h.push([g, M]), y = { x: g, fy: w, gy: M };
1927
+ }
1928
+ return f(), u;
1929
+ }
1930
+ const pi = Array.from({ length: 22 }, (t, e) => e).map((t) => t === 0 ? 1 : Array.from({ length: t }, (e, n) => n + 1).reduce((e, n) => e * n, 1));
1931
+ function fi(t, e) {
1932
+ const n = S(e.values, t.at), i = e.scope[`${t.id}.order`], s = Math.floor(i), r = i - s, o = Array.from({ length: Math.min(20, s + 1) + 1 }, (p, h) => he(t.expr, h)(n, e.scope) / pi[h]), l = (p) => {
1933
+ let h = 0, m = 1;
1934
+ for (let f = 0; f <= s; f++)
1935
+ h += o[f] * m, m *= p - n;
1936
+ return r > 0 && s < 20 ? h + r * o[s + 1] * m : h;
1937
+ }, c = E(e.theme, t.color, e.theme.colors.yellow), [d, u] = t.domain ?? e.plane.x;
1938
+ return Vt(t.id, (p) => l(p), d, u, c, (t.width ?? 3.5) * e.plane.scale, e);
1939
+ }
1940
+ function mi(t, e) {
1941
+ switch (t.kind) {
1942
+ case "grid":
1943
+ return ti(t, e);
1944
+ case "axes":
1945
+ return ei(t, e);
1946
+ case "vector":
1947
+ return ni(t, e);
1948
+ case "basis":
1949
+ return ii(t, e);
1950
+ case "point":
1951
+ return ri(t, e);
1952
+ case "function":
1953
+ return Vn(t, e);
1954
+ case "parametric":
1955
+ return Bn(t, e);
1956
+ case "polygon":
1957
+ return oi(t, e);
1958
+ case "line":
1959
+ return ai(t, e);
1960
+ case "label":
1961
+ return li(t, e);
1962
+ case "equation":
1963
+ return ci(t, e);
1964
+ case "tangent":
1965
+ return ui(t, e);
1966
+ case "riemann":
1967
+ return di(t, e);
1968
+ case "area":
1969
+ return hi(t, e);
1970
+ case "taylor":
1971
+ return fi(t, e);
1972
+ case "histogram":
1973
+ return Wn(t, e);
1974
+ case "distribution":
1975
+ return Un(t, e);
1976
+ case "galton":
1977
+ return Hn(t, e);
1978
+ case "scatter":
1979
+ return Xn(t, e);
1980
+ case "bayes":
1981
+ return Yn(t, e);
1982
+ }
1983
+ }
1984
+ const Fe = (t) => Math.min(1, Math.max(0, t));
1985
+ function Bt(t, e = {}) {
1986
+ const n = ae[t.theme ?? "dark"], i = on(t), s = { ...t.values }, r = /* @__PURE__ */ new Map();
1987
+ for (const [u, p] of Object.entries(e))
1988
+ u.indexOf(".") < 0 ? typeof p != "string" && (s[u] = p) : typeof p == "number" && r.set(u, p);
1989
+ const o = Be(s), l = { ...o, ...sn(t.items, s, o) }, c = [];
1990
+ for (const u of t.items) {
1991
+ const p = (f) => r.get(`${u.id}.${f}`), h = Fe(p("draw") ?? u.draw ?? 1), m = Fe(p("opacity") ?? u.opacity ?? 1);
1992
+ h <= 0 || m <= 0 || c.push(...mi(u, { plane: i, theme: n, values: s, scope: l, draw: h, opacity: m, prop: p }));
1993
+ }
1994
+ const d = t.background === "none" ? void 0 : t.background ?? n.background;
1995
+ return { width: t.width, height: t.height, ...d ? { background: d } : {}, shapes: c };
1996
+ }
1997
+ function cn(t, e) {
1998
+ if (t.length < 2) return { shaft: t, head: void 0 };
1999
+ const n = t[t.length - 1], i = t[t.length - 2], s = n[0] - i[0], r = n[1] - i[1], o = Math.hypot(s, r);
2000
+ if (o === 0 || e <= 0) return { shaft: t, head: void 0 };
2001
+ const l = s / o, c = r / o, d = Math.min(e, o), u = [n[0] - l * d, n[1] - c * d], p = d * 0.55;
2002
+ return {
2003
+ shaft: [...t.slice(0, -1), u],
2004
+ head: [n, [u[0] - c * p, u[1] + l * p], [u[0] + c * p, u[1] - l * p]]
2005
+ };
2006
+ }
2007
+ function Zt(t, e, n = !1) {
2008
+ t.beginPath(), e.forEach(([i, s], r) => r === 0 ? t.moveTo(i, s) : t.lineTo(i, s)), n && t.closePath();
2009
+ }
2010
+ function yi(t, e) {
2011
+ switch (t.globalAlpha = e.opacity ?? 1, e.type) {
2012
+ case "line":
2013
+ if (e.points.length < 2) return;
2014
+ Zt(t, e.points, e.closed), e.fill && (t.fillStyle = e.fill, t.fill()), e.stroke && (e.width ?? 1) > 0 && (t.strokeStyle = e.stroke, t.lineWidth = e.width ?? 1, t.setLineDash(e.dash ?? []), t.stroke(), t.setLineDash([]));
2015
+ return;
2016
+ case "arrow": {
2017
+ const { shaft: n, head: i } = cn(e.points, e.head);
2018
+ t.strokeStyle = e.stroke, t.fillStyle = e.stroke, t.lineWidth = e.width, n.length >= 2 && (Zt(t, n), t.stroke()), i && (Zt(t, i, !0), t.fill());
2019
+ return;
2020
+ }
2021
+ case "circle":
2022
+ t.beginPath(), t.arc(e.x, e.y, e.r, 0, Math.PI * 2), e.fill && (t.fillStyle = e.fill, t.fill()), e.stroke && (t.strokeStyle = e.stroke, t.lineWidth = e.width ?? 1, t.stroke());
2023
+ return;
2024
+ case "text":
2025
+ t.font = `${e.italic ? "italic " : ""}${e.size}px ${e.font}`, t.textAlign = e.align, t.textBaseline = "alphabetic", t.fillStyle = e.color, t.fillText(e.text, e.x, e.y);
2026
+ }
2027
+ }
2028
+ function gi(t, e) {
2029
+ t.save(), t.beginPath(), t.rect(0, 0, e.width, e.height), t.clip(), e.background && (t.fillStyle = e.background, t.fillRect(0, 0, e.width, e.height)), t.lineCap = "round", t.lineJoin = "round";
2030
+ for (const n of e.shapes) yi(t, n);
2031
+ t.restore();
2032
+ }
2033
+ const L = (t) => String(Math.round(t * 100) / 100), W = (t) => t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"), Gt = (t, e = !1) => t.map(([n, i], s) => `${s ? "L" : "M"}${L(n)} ${L(i)}`).join("") + (e ? "Z" : ""), It = (t) => t.opacity !== void 0 && t.opacity < 1 ? ` opacity="${L(t.opacity)}"` : "";
2034
+ function bi(t) {
2035
+ switch (t.type) {
2036
+ case "line": {
2037
+ if (t.points.length < 2) return "";
2038
+ const e = t.fill ? ` fill="${W(t.fill)}"` : ' fill="none"', n = t.stroke && (t.width ?? 1) > 0 ? ` stroke="${W(t.stroke)}" stroke-width="${L(t.width ?? 1)}"` : "", i = t.dash?.length ? ` stroke-dasharray="${t.dash.map(L).join(" ")}"` : "";
2039
+ return `<path d="${Gt(t.points, t.closed)}"${e}${n}${i}${It(t)}/>`;
2040
+ }
2041
+ case "arrow": {
2042
+ const { shaft: e, head: n } = cn(t.points, t.head), i = W(t.stroke), s = e.length >= 2 ? `<path d="${Gt(e)}" fill="none" stroke="${i}" stroke-width="${L(t.width)}"/>` : "", r = n ? `<path d="${Gt(n, !0)}" fill="${i}"/>` : "";
2043
+ return `<g${It(t)}>${s}${r}</g>`;
2044
+ }
2045
+ case "circle": {
2046
+ const e = t.fill ? ` fill="${W(t.fill)}"` : ' fill="none"', n = t.stroke ? ` stroke="${W(t.stroke)}" stroke-width="${L(t.width ?? 1)}"` : "";
2047
+ return `<circle cx="${L(t.x)}" cy="${L(t.y)}" r="${L(t.r)}"${e}${n}${It(t)}/>`;
2048
+ }
2049
+ case "text": {
2050
+ const e = t.align === "center" ? "middle" : t.align === "right" ? "end" : "start", n = t.italic ? ' font-style="italic"' : "";
2051
+ return `<text x="${L(t.x)}" y="${L(t.y)}" font-size="${L(t.size)}" font-family="${W(t.font)}"${n} text-anchor="${e}" fill="${W(t.color)}"${It(t)}>${W(t.text)}</text>`;
2052
+ }
2053
+ }
2054
+ }
2055
+ function ye(t) {
2056
+ return `${t.background ? `<rect width="${L(t.width)}" height="${L(t.height)}" fill="${W(t.background)}"/>` : ""}<g stroke-linecap="round" stroke-linejoin="round">${t.shapes.map(bi).join("")}</g>`;
2057
+ }
2058
+ function vi(t, e = {}) {
2059
+ const n = e.title ? `<title>${W(e.title)}</title>` : "", i = e.title ? ` role="img" aria-label="${W(e.title)}"` : "";
2060
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${L(t.width)} ${L(t.height)}" width="${L(t.width)}" height="${L(t.height)}"${i}>${n}${ye(t)}</svg>`;
2061
+ }
2062
+ function wi(t) {
2063
+ const e = {};
2064
+ for (const [n, i] of Object.entries(t.values ?? {})) {
2065
+ const s = typeof i == "number" ? "number" : i.length === 2 ? "[x, y] vector" : "[a, b, c, d] matrix";
2066
+ e[n] = { description: `The value ${n} (a ${s})`, kind: typeof i == "number" ? "number" : "list" };
2067
+ }
2068
+ for (const n of t.items)
2069
+ e[`${n.id}.draw`] = { description: `How much of the ${n.kind} "${n.id}" is drawn`, unit: "0..1", min: 0, max: 1 }, e[`${n.id}.opacity`] = { description: `Opacity of the ${n.kind} "${n.id}"`, unit: "0..1", min: 0, max: 1 }, n.kind === "equation" && (e[`${n.id}.step`] = { description: `Which step of "${n.id}" shows; in between, terms glide`, unit: "step", min: 0, max: n.steps.length - 1 });
2070
+ return e;
2071
+ }
2072
+ function Zi(t, e = {}) {
2073
+ Tt(t);
2074
+ const n = wi(t), i = { ...t.values ?? {} };
2075
+ return {
2076
+ type: "custom",
2077
+ x: e.x ?? 0,
2078
+ y: e.y ?? 0,
2079
+ width: t.width,
2080
+ height: t.height,
2081
+ props: i,
2082
+ acceptsProp: (s) => Object.prototype.hasOwnProperty.call(n, s),
2083
+ draw(s, r) {
2084
+ gi(s, Bt(t, r.props ?? {}));
2085
+ },
2086
+ about: {
2087
+ kind: "math figure",
2088
+ summary: `A ${t.width}×${t.height} maths figure with ${t.items.map((s) => `${s.kind} "${s.id}"`).join(", ")}. Animate its values by name and each item's draw / opacity (an equation's step).`,
2089
+ props: n
2090
+ }
2091
+ };
2092
+ }
2093
+ function Gi(t, e, n, i = {}) {
2094
+ const s = new Set(n.items.map((c) => c.id)), r = (c) => {
2095
+ if (!s.has(c)) throw new Error(`mathSteps: no item "${c}" (items: ${[...s].join(", ")})`);
2096
+ }, o = { ...n.values ?? {} };
2097
+ for (const c of n.items)
2098
+ o[`${c.id}.draw`] = c.draw ?? 1, o[`${c.id}.opacity`] = c.opacity ?? 1, c.kind === "equation" && (o[`${c.id}.step`] = c.step ?? 0);
2099
+ for (const c of i.hidden ?? [])
2100
+ r(c), o[`${c}.draw`] = 0;
2101
+ t.initial(e, o);
2102
+ const l = {
2103
+ toValue(c, d, u) {
2104
+ if (!(c in o)) throw new Error(`mathSteps: no value "${c}" (values: ${Object.keys(n.values ?? {}).join(", ")})`);
2105
+ return t.to(e, { [c]: d }, { duration: 1200, ...u }), l;
2106
+ },
2107
+ applyMatrix(c, d = {}) {
2108
+ const { name: u = "M", ...p } = d;
2109
+ if (c.length !== 4 || !c.every(Number.isFinite)) throw new Error("mathSteps.applyMatrix: expected [a, b, c, d]");
2110
+ return l.toValue(u, c, { duration: 1600, ...p });
2111
+ },
2112
+ drawOn(c, d) {
2113
+ return r(c), t.to(e, { [`${c}.draw`]: 1 }, { duration: 900, ...d }), l;
2114
+ },
2115
+ fadeIn(c, d) {
2116
+ return r(c), t.set(e, { [`${c}.draw`]: 1, [`${c}.opacity`]: 0 }), t.to(e, { [`${c}.opacity`]: 1 }, { duration: 500, ...d }), l;
2117
+ },
2118
+ fadeOut(c, d) {
2119
+ return r(c), t.to(e, { [`${c}.opacity`]: 0 }, { duration: 500, ...d }), l;
2120
+ },
2121
+ showStep(c, d, u) {
2122
+ return r(c), t.to(e, { [`${c}.step`]: d }, { duration: 900, ...u }), l;
2123
+ }
2124
+ };
2125
+ return l;
2126
+ }
2127
+ class qe {
2128
+ media;
2129
+ offset;
2130
+ driftTolerance;
2131
+ constructor(e, n = {}) {
2132
+ this.media = e, this.offset = n.offset ?? 0, this.driftTolerance = Math.max(0, n.driftTolerance ?? 0.15);
2133
+ }
2134
+ /** Map a timeline time (ms) to the media's time (seconds), never negative. */
2135
+ targetTime(e) {
2136
+ return Math.max(0, e / 1e3 + this.offset);
2137
+ }
2138
+ /**
2139
+ * Reconcile the media with the timeline for the current frame.
2140
+ *
2141
+ * @param timelineTimeMs current timeline time in milliseconds
2142
+ * @param isPlaying whether the timeline is playing
2143
+ */
2144
+ update(e, n) {
2145
+ const i = this.targetTime(e);
2146
+ n ? (this.media.paused && this.safePlay(), Math.abs(this.media.currentTime - i) > this.driftTolerance && (this.media.currentTime = i)) : (this.media.paused || this.media.pause(), this.media.currentTime !== i && (this.media.currentTime = i));
2147
+ }
2148
+ /** Hard-align the media to a timeline time (used on explicit seeks). */
2149
+ seek(e) {
2150
+ this.media.currentTime = this.targetTime(e);
2151
+ }
2152
+ /** Mirror the timeline playback rate onto the media. */
2153
+ setRate(e) {
2154
+ this.media.playbackRate = e;
2155
+ }
2156
+ /** Pause the media and release it. */
2157
+ dispose() {
2158
+ this.media.paused || this.media.pause();
2159
+ }
2160
+ safePlay() {
2161
+ const e = this.media.play();
2162
+ e && typeof e.catch == "function" && e.catch(() => {
2163
+ });
2164
+ }
2165
+ }
2166
+ function ki(t, e, n, i, s) {
2167
+ const r = n - s;
2168
+ if (r < 0) {
2169
+ e.paused || e.pause(), e.currentTime = 0;
2170
+ return;
2171
+ }
2172
+ t.update(r, i);
2173
+ }
2174
+ class $i {
2175
+ container;
2176
+ timeline = null;
2177
+ adapter;
2178
+ animationFrameId;
2179
+ lastTime;
2180
+ options;
2181
+ targets = {};
2182
+ isDestroyed = !1;
2183
+ mediaSync;
2184
+ mediaTargets = [];
2185
+ symbolInstances = [];
2186
+ scenarioList = [];
2187
+ scenarioId;
2188
+ authored = /* @__PURE__ */ new Map();
2189
+ markerList = [];
2190
+ listeners = /* @__PURE__ */ new Set();
2191
+ /** Where the playhead was when marker crossings were last worked out */
2192
+ playhead = { time: 0, iteration: 0, direction: "forward" };
2193
+ /** Stop at the next marker crossed (step mode, or `next()`) */
2194
+ stepping = !1;
2195
+ lastMarkerId = null;
2196
+ reducedQuery;
2197
+ onReducedChange = () => this.applyReducedMotion();
2198
+ visibilityObserver;
2199
+ onScreen = !0;
2200
+ /** Playback was paused by leaving the screen, and resumes on return */
2201
+ pausedByVisibility = !1;
2202
+ /** `autoplay` waits for the first time the container is seen */
2203
+ autoplayWhenSeen = !1;
2204
+ onDocumentVisibility = () => this.updateVisibility();
2205
+ constructor(e, n = {}) {
2206
+ if (typeof e == "string") {
2207
+ const i = document.querySelector(e);
2208
+ if (!i)
2209
+ throw new Error(`Container not found: ${e}`);
2210
+ this.container = i;
2211
+ } else
2212
+ this.container = e;
2213
+ this.options = n, this.adapter = new $e();
2214
+ }
2215
+ /**
2216
+ * Load animation from a URL or JSON object.
2217
+ */
2218
+ async load(e) {
2219
+ this.scenarioList = [], this.scenarioId = void 0, await this.loadSource(e);
2220
+ }
2221
+ async loadSource(e) {
2222
+ let n;
2223
+ if (typeof e == "string") {
2224
+ const i = await fetch(e);
2225
+ if (!i.ok)
2226
+ throw new Error(`Failed to load animation: ${i.statusText}`);
2227
+ n = await i.json();
2228
+ } else
2229
+ n = e;
2230
+ this.useDefinition(n), this.showInitialFrame(), this.watchReducedMotion(), this.watchVisibility(), this.options.autoplay && !this.reducedMotion && (this.options.playWhenVisible && !this.onScreen ? this.autoplayWhenSeen = !0 : this.play());
2231
+ }
2232
+ /**
2233
+ * Make a definition the current timeline: targets, symbols and media bound, no
2234
+ * frame drawn and nothing played. The definition itself is not modified, so a
2235
+ * scenario's timeline can be used again.
2236
+ */
2237
+ useDefinition(e) {
2238
+ const n = { ...e.config };
2239
+ this.options.speed !== void 0 && (n.speed = this.options.speed), this.options.loop !== void 0 && (n.loop = this.options.loop), this.options.alternate !== void 0 && (n.alternate = this.options.alternate), this.timeline = ke({ ...e, config: n }), this.markerList = this.timeline.markers, this.lastMarkerId = null, this.options.onComplete && (this.timeline.onComplete = this.options.onComplete), this.options.onUpdate && (this.timeline.onUpdate = this.options.onUpdate), this.autoRegisterTargets(), this.setupSymbolInstances(), this.scanMedia();
2240
+ }
2241
+ // --- scenarios: the reader chooses which timeline plays --------------------
2242
+ /**
2243
+ * Load several timelines for the same markup, and show one. The reader switches
2244
+ * with `setScenario`; the embed's controls and `data-tinyfly-choose` hotspots
2245
+ * call it.
2246
+ */
2247
+ async loadScenarios(e, n = {}) {
2248
+ if (e.length === 0) throw new Error("tinyfly: loadScenarios needs at least one scenario");
2249
+ const i = /* @__PURE__ */ new Set();
2250
+ for (const r of e) {
2251
+ if (i.has(r.id)) throw new Error(`tinyfly: scenario id "${r.id}" is used more than once`);
2252
+ i.add(r.id);
2253
+ }
2254
+ const s = n.initial === void 0 ? e[0] : e.find((r) => r.id === n.initial);
2255
+ if (!s) throw new Error(`tinyfly: there is no scenario "${n.initial}"`);
2256
+ this.scenarioList = [...e], this.scenarioId = s.id, await this.loadSource(s.timeline);
2257
+ }
2258
+ /** The scenarios to choose from (empty for a single timeline). */
2259
+ get scenarios() {
2260
+ return this.scenarioList.map((e) => ({ id: e.id, label: e.label ?? e.id }));
2261
+ }
2262
+ /** The id of the scenario showing, if scenarios were loaded. */
2263
+ get scenario() {
2264
+ return this.scenarioId;
2265
+ }
2266
+ /**
2267
+ * Switch to another scenario. Whatever the previous one drew is undone first.
2268
+ * The reader stays at the same step when the new scenario has a marker with the
2269
+ * same id, stays at the end if they were at the end, and otherwise starts from
2270
+ * the beginning. Playback continues if it was playing. Under reduced motion the
2271
+ * new scenario's final frame shows. Returns false for an unknown id.
2272
+ */
2273
+ setScenario(e) {
2274
+ const n = this.scenarioList.find((l) => l.id === e);
2275
+ if (!n || !this.timeline) return !1;
2276
+ if (e === this.scenarioId) return !0;
2277
+ const i = this.isPlaying, s = this.currentTime >= this.duration - 0.5, r = this.currentMarker?.id;
2278
+ this.stopAnimationLoop(), this.stepping = !1, this.pausedByVisibility = !1, this.restoreAuthored(), this.scenarioId = e, this.useDefinition(n.timeline), this.lastMarkerId = null;
2279
+ let o = 0;
2280
+ return this.reducedMotion || s ? o = this.duration : r !== void 0 && (o = this.markers.find((l) => l.id === r)?.time ?? 0), this.seek(o), i && !this.reducedMotion ? (this.stepping = this.options.stepMode === !0, this.startPlaying()) : this.notify(), !0;
2281
+ }
2282
+ /** Remember how an element was authored, the first time it becomes a target. */
2283
+ rememberAuthored(e) {
2284
+ if (this.authored.has(e)) return;
2285
+ const n = { style: e.getAttribute("style") };
2286
+ e.children.length === 0 && (n.text = e.textContent ?? "");
2287
+ const i = e.tagName.toLowerCase() === "path" ? e : e.querySelector("path");
2288
+ i && (n.path = { element: i, d: i.getAttribute("d") }), this.authored.set(e, n);
2289
+ }
2290
+ /** Put every target back the way it was authored. */
2291
+ restoreAuthored() {
2292
+ for (const [e, n] of this.authored) {
2293
+ n.style === null ? e.removeAttribute("style") : e.setAttribute("style", n.style), n.text !== void 0 && e.textContent !== n.text && (e.textContent = n.text), n.path && (n.path.d === null ? n.path.element.removeAttribute("d") : n.path.element.setAttribute("d", n.path.d));
2294
+ const i = e.dataset;
2295
+ i && delete i.shineBase;
2296
+ }
2297
+ }
2298
+ // --- teaching: frames, markers, reduced motion, visibility -----------------
2299
+ /**
2300
+ * Be told whenever the time, play state or current marker may have changed —
2301
+ * for controls and captions. Returns a function that stops it.
2302
+ */
2303
+ subscribe(e) {
2304
+ return this.listeners.add(e), () => this.listeners.delete(e);
2305
+ }
2306
+ notify() {
2307
+ for (const e of this.listeners) e();
2308
+ }
2309
+ /** Whether the reader asked for reduced motion (and the player respects it). */
2310
+ get reducedMotion() {
2311
+ return this.reducedQuery?.matches === !0;
2312
+ }
2313
+ /** The timeline's markers, in time order. */
2314
+ get markers() {
2315
+ return this.markerList;
2316
+ }
2317
+ /** The last marker at or before the playhead. */
2318
+ get currentMarker() {
2319
+ const e = this.currentTime;
2320
+ let n;
2321
+ for (const i of this.markers)
2322
+ if (i.time <= e + 0.5) n = i;
2323
+ else break;
2324
+ return n;
2325
+ }
2326
+ /**
2327
+ * Caption for a marker (default: the current one) in a language (default: the
2328
+ * container's closest `lang`, then the document's), falling back to the
2329
+ * marker's own label.
2330
+ */
2331
+ caption(e, n) {
2332
+ const i = e ? this.markers.find((o) => o.id === e) : this.currentMarker;
2333
+ if (!i) return;
2334
+ const s = n ?? this.language(), r = (o) => o?.[s]?.[i.id] ?? o?.[s.split("-")[0]]?.[i.id];
2335
+ return r(this.options.captions) ?? r(this.timeline?.captions) ?? i.label;
2336
+ }
2337
+ /** Move to the next marker: animated, or a jump under reduced motion. At the last marker, to the end. */
2338
+ next() {
2339
+ if (!this.timeline) return;
2340
+ const e = this.currentTime, n = this.markers.find((i) => i.time > e + 0.5);
2341
+ if (this.reducedMotion) {
2342
+ this.seek(n ? n.time : this.duration);
2343
+ return;
2344
+ }
2345
+ e >= this.duration - 0.5 || (this.stepping = n !== void 0, this.startPlaying());
2346
+ }
2347
+ /** Jump back to the previous marker (or the start). */
2348
+ prev() {
2349
+ if (!this.timeline) return;
2350
+ const e = this.currentTime, n = [...this.markers].reverse().find((i) => i.time < e - 0.5);
2351
+ this.pause(), this.seek(n ? n.time : 0);
2352
+ }
2353
+ /** Jump to a marker by id, paused there. */
2354
+ goToMarker(e) {
2355
+ const n = this.markers.find((i) => i.id === e);
2356
+ n && (this.pause(), this.seek(n.time));
2357
+ }
2358
+ language() {
2359
+ return this.container.closest("[lang]")?.getAttribute("lang") || (typeof document < "u" ? document.documentElement.lang : "") || "en";
2360
+ }
2361
+ showInitialFrame() {
2362
+ if (!this.timeline) return;
2363
+ const e = this.options.initialFrame ?? "start";
2364
+ if (e === "none") return;
2365
+ const n = e === "end" ? this.timeline.duration : e === "start" ? 0 : e;
2366
+ this.timeline.seek(Math.max(0, Math.min(this.timeline.duration, n))), this.applyState();
2367
+ }
2368
+ watchReducedMotion() {
2369
+ this.options.respectReducedMotion === !1 || typeof window > "u" || typeof window.matchMedia != "function" || (this.reducedQuery ??= window.matchMedia("(prefers-reduced-motion: reduce)"), this.reducedQuery.addEventListener?.("change", this.onReducedChange), this.reducedQuery.matches && this.applyReducedMotion());
2370
+ }
2371
+ /** Under reduced motion: stop, and show the finished state. */
2372
+ applyReducedMotion() {
2373
+ !this.reducedMotion || !this.timeline || (this.autoplayWhenSeen = !1, this.pause(), this.seek(this.timeline.duration));
2374
+ }
2375
+ watchVisibility() {
2376
+ if (!(!this.options.playWhenVisible || typeof window > "u")) {
2377
+ if (typeof IntersectionObserver == "function") {
2378
+ this.visibilityObserver?.disconnect(), this.visibilityObserver = new IntersectionObserver((n) => {
2379
+ for (const i of n) this.onScreen = i.isIntersecting;
2380
+ this.updateVisibility();
2381
+ }), this.visibilityObserver.observe(this.container);
2382
+ const e = this.container.getBoundingClientRect?.();
2383
+ e && (e.width > 0 || e.height > 0) && (this.onScreen = e.bottom > 0 && e.top < window.innerHeight && e.right > 0 && e.left < window.innerWidth);
2384
+ }
2385
+ document.addEventListener("visibilitychange", this.onDocumentVisibility);
2386
+ }
2387
+ }
2388
+ updateVisibility() {
2389
+ const e = this.onScreen && document.visibilityState !== "hidden";
2390
+ !e && this.isPlaying ? (this.pausedByVisibility = !0, this.pause()) : e && (this.pausedByVisibility || this.autoplayWhenSeen) && !this.reducedMotion && (this.pausedByVisibility = !1, this.autoplayWhenSeen = !1, this.startPlaying());
2391
+ }
2392
+ /** Report the current marker if it changed since the last frame. */
2393
+ announceMarker() {
2394
+ if (!this.options.onMarker) return;
2395
+ const e = this.currentMarker, n = e?.id;
2396
+ n !== this.lastMarkerId && (this.lastMarkerId = n, this.options.onMarker(e));
2397
+ }
2398
+ /**
2399
+ * Find embedded media elements (`[data-tinyfly-media]`) in the container and
2400
+ * bind each to the timeline. Emitted by the editor's export for audio/video
2401
+ * scene elements; the `data-tinyfly-start` attribute sets when each begins.
2402
+ */
2403
+ scanMedia() {
2404
+ this.mediaTargets = [], this.container.querySelectorAll("[data-tinyfly-media]").forEach((n) => {
2405
+ const i = n, s = Number(i.getAttribute("data-tinyfly-start") ?? "0") || 0, r = i.getAttribute("data-volume");
2406
+ r !== null && (i.volume = Math.max(0, Math.min(1, Number(r) || 0))), this.mediaTargets.push({ el: i, startTime: s, sync: new qe(i) });
2407
+ });
2408
+ }
2409
+ /** Sync all discovered media targets to a timeline time. */
2410
+ syncAllMedia(e, n) {
2411
+ for (const i of this.mediaTargets)
2412
+ ki(i.sync, i.el, e, n, i.startTime);
2413
+ }
2414
+ /**
2415
+ * Load animation from inline JSON string.
2416
+ */
2417
+ loadFromString(e) {
2418
+ const n = JSON.parse(e);
2419
+ this.load(n);
2420
+ }
2421
+ /**
2422
+ * Register a target element by name.
2423
+ */
2424
+ registerTarget(e, n) {
2425
+ if (typeof n == "string") {
2426
+ const i = this.container.querySelector(n);
2427
+ i && (this.rememberAuthored(i), this.targets[e] = i, this.adapter.registerTarget(e, i));
2428
+ } else
2429
+ this.rememberAuthored(n), this.targets[e] = n, this.adapter.registerTarget(e, n);
2430
+ }
2431
+ /**
2432
+ * Auto-register targets using data-tinyfly attribute.
2433
+ */
2434
+ autoRegisterTargets() {
2435
+ this.container.querySelectorAll("[data-tinyfly]").forEach((n) => {
2436
+ const i = n.closest("[data-tinyfly-symbol]");
2437
+ if (i && i !== n) return;
2438
+ const s = n.getAttribute("data-tinyfly");
2439
+ s && this.registerTarget(s, n);
2440
+ }), this.timeline && new Set(this.timeline.tracks.map((i) => i.target)).forEach((i) => {
2441
+ if (!this.targets[i]) {
2442
+ const s = this.container.querySelector(`[data-tinyfly="${i}"]`) || this.container.querySelector(`.${i}`) || this.container.querySelector(`#${i}`);
2443
+ s && this.registerTarget(i, s);
2444
+ }
2445
+ });
2446
+ }
2447
+ /**
2448
+ * Bind each embedded symbol instance (`[data-tinyfly-symbol="id"]`) to its
2449
+ * symbol's nested timeline: a private adapter drives the instance's inner
2450
+ * elements, looped over the symbol's duration and synced to the main playhead.
2451
+ */
2452
+ setupSymbolInstances() {
2453
+ this.symbolInstances = [];
2454
+ const e = this.options.symbols;
2455
+ if (!e || e.length === 0) return;
2456
+ const n = new Map(e.map((i) => [i.id, i]));
2457
+ this.container.querySelectorAll("[data-tinyfly-symbol]").forEach((i) => {
2458
+ const s = i.getAttribute("data-tinyfly-symbol");
2459
+ if (!s) return;
2460
+ const r = n.get(s);
2461
+ if (!r || !r.timeline.tracks?.length) return;
2462
+ const o = new $e();
2463
+ i.querySelectorAll("[data-tinyfly]").forEach((l) => {
2464
+ const c = l.getAttribute("data-tinyfly");
2465
+ c && o.registerTarget(c, l);
2466
+ }), this.symbolInstances.push({ adapter: o, timeline: ke(r.timeline) });
2467
+ });
2468
+ }
2469
+ /**
2470
+ * Attach an audio/video element (or any {@link SyncableMedia}) that should
2471
+ * stay in sync with the animation timeline. The timeline remains the clock;
2472
+ * the media follows its play/pause/seek and rate, with drift corrected as it
2473
+ * plays. Pass `{ offset }` to start the media at a timeline offset.
2474
+ */
2475
+ attachMedia(e, n) {
2476
+ this.mediaSync = new qe(e, n), this.timeline && (this.mediaSync.setRate(this.timeline.speed), this.mediaSync.update(this.timeline.currentTime, this.isPlaying));
2477
+ }
2478
+ /** Detach and pause the currently synced media, if any. */
2479
+ detachMedia() {
2480
+ this.mediaSync?.dispose(), this.mediaSync = void 0;
2481
+ }
2482
+ /**
2483
+ * Start or resume playback.
2484
+ */
2485
+ play() {
2486
+ !this.timeline || this.isDestroyed || (this.autoplayWhenSeen = !1, this.stepping = this.options.stepMode === !0, this.startPlaying());
2487
+ }
2488
+ startPlaying() {
2489
+ if (!this.timeline || this.isDestroyed) return;
2490
+ const e = this.timeline.playbackState === "idle";
2491
+ this.timeline.play(), e && this.timeline.currentTime === 0 && this.applyState(), this.playhead = { time: this.timeline.currentTime, iteration: this.timeline.loopIteration, direction: this.timeline.direction }, this.mediaSync?.update(this.timeline.currentTime, !0), this.syncAllMedia(this.timeline.currentTime, !0), this.startAnimationLoop(), this.notify();
2492
+ }
2493
+ /**
2494
+ * Pause playback.
2495
+ */
2496
+ pause() {
2497
+ this.timeline && (this.stepping = !1, this.timeline.pause(), this.notify(), this.mediaSync?.update(this.timeline.currentTime, !1), this.syncAllMedia(this.timeline.currentTime, !1), this.stopAnimationLoop());
2498
+ }
2499
+ /**
2500
+ * Stop playback and reset to beginning.
2501
+ */
2502
+ stop() {
2503
+ this.timeline && (this.timeline.stop(), this.stopAnimationLoop(), this.applyState(), this.mediaSync?.update(this.timeline.currentTime, !1), this.syncAllMedia(this.timeline.currentTime, !1));
2504
+ }
2505
+ /**
2506
+ * Seek to a specific time (in milliseconds).
2507
+ */
2508
+ seek(e) {
2509
+ this.timeline && (this.timeline.seek(e), this.applyState(), this.playhead = { time: this.timeline.currentTime, iteration: this.timeline.loopIteration, direction: this.timeline.direction }, this.mediaSync?.seek(this.timeline.currentTime), this.syncAllMedia(this.timeline.currentTime, this.isPlaying));
2510
+ }
2511
+ /**
2512
+ * Set playback speed.
2513
+ */
2514
+ setSpeed(e) {
2515
+ this.timeline && (this.timeline.speed = e, this.mediaSync?.setRate(e));
2516
+ }
2517
+ /**
2518
+ * Reverse playback direction.
2519
+ */
2520
+ reverse() {
2521
+ this.timeline && this.timeline.reverse();
2522
+ }
2523
+ /**
2524
+ * Get current playback time.
2525
+ */
2526
+ get currentTime() {
2527
+ return this.timeline?.currentTime ?? 0;
2528
+ }
2529
+ /**
2530
+ * The animated values at the playhead, for renderers that draw from values
2531
+ * rather than DOM elements (a canvas, or an SVG rebuilt each frame). Read it
2532
+ * from a `subscribe` listener. Undefined before a timeline loads.
2533
+ */
2534
+ get state() {
2535
+ return this.timeline?.getStateAtTime(this.timeline.currentTime);
2536
+ }
2537
+ /**
2538
+ * Get total duration.
2539
+ */
2540
+ get duration() {
2541
+ return this.timeline?.duration ?? 0;
2542
+ }
2543
+ /**
2544
+ * Check if currently playing.
2545
+ */
2546
+ get isPlaying() {
2547
+ return this.timeline?.playbackState === "playing";
2548
+ }
2549
+ /**
2550
+ * Clean up resources.
2551
+ */
2552
+ destroy() {
2553
+ this.isDestroyed = !0, this.stopAnimationLoop(), this.reducedQuery?.removeEventListener?.("change", this.onReducedChange), this.visibilityObserver?.disconnect(), typeof document < "u" && document.removeEventListener("visibilitychange", this.onDocumentVisibility), this.mediaSync?.dispose(), this.mediaSync = void 0;
2554
+ for (const e of this.mediaTargets)
2555
+ e.el.paused || e.el.pause();
2556
+ this.mediaTargets = [], this.adapter.clearTargets();
2557
+ for (const e of this.symbolInstances) e.adapter.clearTargets();
2558
+ this.symbolInstances = [], this.authored.clear(), this.timeline = null;
2559
+ }
2560
+ startAnimationLoop() {
2561
+ if (this.animationFrameId !== void 0) return;
2562
+ this.lastTime = performance.now();
2563
+ const e = (n) => {
2564
+ if (this.isDestroyed || !this.timeline) return;
2565
+ const i = n - (this.lastTime ?? n);
2566
+ this.lastTime = n;
2567
+ const s = this.playhead;
2568
+ this.timeline.tick(i), this.stopAtMarker(s), this.applyState();
2569
+ const r = this.timeline.playbackState === "playing";
2570
+ this.mediaSync?.update(this.timeline.currentTime, r), this.syncAllMedia(this.timeline.currentTime, r), this.timeline.playbackState === "playing" ? this.animationFrameId = requestAnimationFrame(e) : (this.animationFrameId = void 0, this.notify());
2571
+ };
2572
+ this.animationFrameId = requestAnimationFrame(e);
2573
+ }
2574
+ /**
2575
+ * If this frame crossed a marker it should stop at — the next one while
2576
+ * stepping, or any marker with `pause` — put the playhead exactly there and pause.
2577
+ */
2578
+ stopAtMarker(e) {
2579
+ const n = this.timeline, i = { time: n.currentTime, iteration: n.loopIteration, direction: n.direction };
2580
+ this.playhead = i;
2581
+ const s = this.markers;
2582
+ if (s.length === 0) return;
2583
+ const { crossings: r } = hn(
2584
+ s.map((o) => o.time),
2585
+ e,
2586
+ i,
2587
+ { duration: n.duration, alternate: n.config.alternate === !0, holding: n.repeatDelayRemaining > 0 }
2588
+ );
2589
+ for (const o of r) {
2590
+ if (o.kind !== "event") continue;
2591
+ const l = s[o.index];
2592
+ if (this.stepping || l.pause) {
2593
+ this.stepping = !1, n.pause(), n.seek(l.time), this.playhead = { time: l.time, iteration: n.loopIteration, direction: n.direction };
2594
+ return;
2595
+ }
2596
+ }
2597
+ }
2598
+ stopAnimationLoop() {
2599
+ this.animationFrameId !== void 0 && (cancelAnimationFrame(this.animationFrameId), this.animationFrameId = void 0);
2600
+ }
2601
+ applyState() {
2602
+ if (!this.timeline) return;
2603
+ const e = this.timeline.currentTime;
2604
+ this.adapter.applyState(this.timeline.getStateAtTime(e)), this.announceMarker(), this.notify();
2605
+ for (const n of this.symbolInstances) {
2606
+ const i = n.timeline.duration;
2607
+ n.adapter.applyState(n.timeline.getStateAtTime(i > 0 ? e % i : e));
2608
+ }
2609
+ }
2610
+ }
2611
+ const Mi = {
2612
+ play: "Play",
2613
+ pause: "Pause",
2614
+ prev: "Previous step",
2615
+ next: "Next step",
2616
+ restart: "Restart",
2617
+ scrub: "Position",
2618
+ speed: "Speed",
2619
+ reveal: "Reveal",
2620
+ step: "Step",
2621
+ of: "of",
2622
+ stepFormat: "{index} / {total}",
2623
+ scenario: "Scenario",
2624
+ fullscreen: "Full screen",
2625
+ exitFullscreen: "Exit full screen"
2626
+ }, Ce = "tinyfly-controls-style", xi = `
2627
+ .tf-ctl { --tf-ctl-fg: #1d1d1f; --tf-ctl-bg: #f4f2ee; --tf-ctl-accent: #c2410c; --tf-ctl-radius: 8px;
2628
+ font: 14px/1.4 var(--tf-ctl-font, system-ui, sans-serif); color: var(--tf-ctl-fg); margin-top: 8px; }
2629
+ .tf-ctl-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 6px; border-radius: var(--tf-ctl-radius); background: var(--tf-ctl-bg); }
2630
+ .tf-ctl-btn { min-width: 36px; height: 36px; padding: 0 10px; border: 0; border-radius: calc(var(--tf-ctl-radius) - 2px); background: transparent; color: inherit; font: inherit; cursor: pointer; }
2631
+ .tf-ctl-btn:hover { background: color-mix(in srgb, var(--tf-ctl-fg) 8%, transparent); }
2632
+ .tf-ctl-btn:focus-visible, .tf-ctl-scrub:focus-visible, .tf-ctl-speed:focus-visible { outline: 2px solid var(--tf-ctl-accent); outline-offset: 2px; }
2633
+ .tf-ctl-btn[disabled] { opacity: 0.4; cursor: default; }
2634
+ .tf-ctl-primary { background: var(--tf-ctl-accent); color: #fff; }
2635
+ .tf-ctl-primary:hover { background: var(--tf-ctl-accent); filter: brightness(1.08); }
2636
+ .tf-ctl-scrub { flex: 1 1 120px; min-width: 80px; accent-color: var(--tf-ctl-accent); }
2637
+ .tf-ctl-speed { height: 32px; border: 0; border-radius: 6px; background: transparent; color: inherit; font: inherit; }
2638
+ .tf-ctl-step { font-variant-numeric: tabular-nums; opacity: 0.75; padding: 0 4px; }
2639
+ .tf-ctl-caption { margin: 6px 2px 0; min-height: 1.4em; }
2640
+ .tf-ctl-question { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 6px 2px 0; font-weight: 600; }
2641
+ .tf-ctl-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
2642
+ /* The hidden attribute only hides through the browser's default stylesheet; any rule
2643
+ above that sets display would override it, so enforce it for everything here. */
2644
+ .tf-ctl [hidden] { display: none !important; }
2645
+ .tf-ctl-choices { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 8px 0 0; padding: 0; border: 0; }
2646
+ .tf-ctl-choices legend { float: left; margin-right: 4px; padding: 0; font-weight: 600; }
2647
+ .tf-ctl-choice { position: relative; display: inline-flex; }
2648
+ .tf-ctl-choice input { position: absolute; opacity: 0; width: 1px; height: 1px; }
2649
+ .tf-ctl-choice span { display: inline-block; padding: 6px 12px; border-radius: var(--tf-ctl-radius); background: var(--tf-ctl-bg); cursor: pointer; }
2650
+ .tf-ctl-choice input:checked + span { background: var(--tf-ctl-accent); color: #fff; }
2651
+ .tf-ctl-choice input:focus-visible + span { outline: 2px solid var(--tf-ctl-accent); outline-offset: 2px; }
2652
+ .tf-ctl-choice-slider { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 8px 0 0; }
2653
+ .tf-ctl-choice-slider span { font-weight: 600; }
2654
+ .tf-ctl-choice-slider input { flex: 1 1 140px; accent-color: var(--tf-ctl-accent); }
2655
+ .tf-ctl-choice-slider input:focus-visible { outline: 2px solid var(--tf-ctl-accent); outline-offset: 2px; }
2656
+ .tf-ctl-choice-slider output { font-variant-numeric: tabular-nums; min-width: 4em; }
2657
+ .tf-ctl-fullscreen { margin-left: auto; display: inline-flex; align-items: center; justify-content: center; }
2658
+ .tf-ctl-fullscreen svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; }
2659
+ /* Full screen, by either route. The figure becomes a column: the drawing takes the room
2660
+ that's left after the controls and captions. !important because the host page's own
2661
+ figure rules (a max-width, a min-width that makes a diagram scroll on phones) would
2662
+ otherwise keep the drawing at its in-page size. */
2663
+ .tf-fullscreen { box-sizing: border-box !important; display: flex !important; flex-direction: column; width: 100% !important; max-width: none !important; height: 100vh; height: 100dvh; margin: 0 !important; padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(12px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left)) !important; overflow: auto !important; background: var(--tf-fullscreen-bg, #fff); }
2664
+ .tf-fullscreen > * { flex: none; }
2665
+ .tf-fullscreen > svg, .tf-fullscreen > canvas { flex: 1 1 0; min-height: 0; width: 100% !important; min-width: 0 !important; height: 100% !important; }
2666
+ .tf-fullscreen-overlay { position: fixed !important; inset: 0; z-index: 2147483000; }
2667
+ /* A short landscape screen (a phone on its side): stacking the controls under the drawing
2668
+ leaves the drawing a thin strip, so put them in a column beside it instead. */
2669
+ @media (orientation: landscape) and (max-height: 520px) {
2670
+ .tf-fullscreen { display: grid !important; grid-template-columns: minmax(0, 1fr) minmax(200px, 34%); grid-auto-rows: min-content; column-gap: 12px; align-content: start; }
2671
+ .tf-fullscreen > svg, .tf-fullscreen > canvas { grid-column: 1; grid-row: 1 / span 12; height: calc(100vh - 24px) !important; height: calc(100dvh - 24px) !important; }
2672
+ .tf-fullscreen > :not(svg):not(canvas) { grid-column: 2; }
2673
+ }
2674
+ `;
2675
+ let Si = 0;
2676
+ function Ai(t) {
2677
+ if (t.getElementById(Ce)) return;
2678
+ const e = t.createElement("style");
2679
+ e.id = Ce, e.textContent = xi, t.head.appendChild(e);
2680
+ }
2681
+ function Ei(t, e, n = {}) {
2682
+ const i = e.ownerDocument;
2683
+ Ai(i);
2684
+ const s = { ...Mi, ...n.labels }, r = n.speeds ?? [0.5, 1, 2], o = () => t.markers.length > 0, l = () => t.markers.some((A) => A.label !== void 0 || t.caption(A.id) !== void 0), c = i.createElement("div");
2685
+ c.className = "tf-ctl";
2686
+ const d = i.createElement("div");
2687
+ d.className = "tf-ctl-bar", d.setAttribute("role", "group");
2688
+ const u = (A, z, ot, et = "") => {
2689
+ const H = i.createElement("button");
2690
+ return H.type = "button", H.className = `tf-ctl-btn ${et}`.trim(), H.setAttribute("aria-label", A), H.title = A, H.textContent = z, H.addEventListener("click", ot), H;
2691
+ }, p = u(s.restart, "⟲", () => {
2692
+ t.pause(), t.seek(0);
2693
+ }), h = u(s.prev, "|◀", () => t.prev()), m = u(s.play, "▶", () => t.isPlaying ? t.pause() : y(), "tf-ctl-primary"), f = u(s.next, "▶|", () => t.next()), y = () => {
2694
+ t.currentTime >= t.duration - 0.5 && t.seek(0), t.play();
2695
+ }, a = i.createElement("input");
2696
+ a.type = "range", a.className = "tf-ctl-scrub", a.min = "0", a.max = "1000", a.step = "1", a.setAttribute("aria-label", s.scrub), a.addEventListener("input", () => {
2697
+ t.pause(), t.seek(Number(a.value) / 1e3 * t.duration);
2698
+ });
2699
+ const g = i.createElement("span");
2700
+ g.className = "tf-ctl-step";
2701
+ const w = i.createElement("select");
2702
+ w.className = "tf-ctl-speed", w.setAttribute("aria-label", s.speed);
2703
+ for (const A of r) {
2704
+ const z = i.createElement("option");
2705
+ z.value = String(A), z.textContent = `${A}×`, A === 1 && (z.selected = !0), w.appendChild(z);
2706
+ }
2707
+ w.addEventListener("change", () => t.setSpeed(Number(w.value))), d.append(p, h, m, f, a, g), r.length > 0 && d.append(w), c.append(d);
2708
+ const M = n.fullscreen ? Ni(e, i, s) : void 0;
2709
+ M && d.append(M.button);
2710
+ const v = i.createElement("p");
2711
+ v.className = "tf-ctl-caption", v.setAttribute("aria-live", "polite"), n.captions !== !1 && c.append(v);
2712
+ const b = i.createElement("div");
2713
+ b.className = "tf-ctl-question", b.hidden = !0;
2714
+ const k = i.createElement("span"), $ = u(s.reveal, s.reveal, () => t.play(), "tf-ctl-primary");
2715
+ b.append(k, $), c.append(b);
2716
+ const x = Ti(t, i, s.scenario, n.scenarioControl ?? "buttons");
2717
+ x && c.append(x.element);
2718
+ const T = n.mount;
2719
+ T ? T.appendChild(c) : e.insertAdjacentElement("afterend", c);
2720
+ const N = () => {
2721
+ const A = t.isPlaying;
2722
+ m.textContent = A ? "❚❚" : "▶", m.setAttribute("aria-label", A ? s.pause : s.play), m.title = A ? s.pause : s.play;
2723
+ const z = t.duration;
2724
+ i.activeElement !== a && (a.value = String(z > 0 ? Math.round(t.currentTime / z * 1e3) : 0));
2725
+ const ot = t.markers;
2726
+ if (h.hidden = f.hidden = g.hidden = ot.length === 0, ot.length > 0) {
2727
+ const et = t.currentMarker, H = et ? ot.indexOf(et) + 1 : 0;
2728
+ g.textContent = s.stepFormat.replace("{index}", String(H)).replace("{total}", String(ot.length)), g.setAttribute("aria-label", `${s.step} ${H} ${s.of} ${ot.length}`), h.disabled = t.currentTime <= 0.5, f.disabled = t.currentTime >= z - 0.5;
2729
+ const ve = t.caption() ?? "";
2730
+ v.textContent !== ve && (v.textContent = ve), v.hidden = !l();
2731
+ const we = !A && et?.question !== void 0 && Math.abs(t.currentTime - et.time) < 1;
2732
+ b.hidden = !we, we && k.textContent !== et.question && (k.textContent = et.question);
2733
+ } else
2734
+ b.hidden = !0, v.hidden = !0;
2735
+ x?.update();
2736
+ }, q = t.subscribe(N);
2737
+ N();
2738
+ const F = n.keyboardScope ?? e;
2739
+ !F.hasAttribute("tabindex") && F.tabIndex < 0 && (F.tabIndex = 0);
2740
+ const vt = /* @__PURE__ */ new WeakSet(), K = (A) => {
2741
+ if (vt.has(A) || (vt.add(A), A.defaultPrevented || A.altKey || A.ctrlKey || A.metaKey)) return;
2742
+ const z = A.target;
2743
+ if (!(z.tagName === "INPUT" || z.tagName === "SELECT") && !(A.key === " " && z.tagName === "BUTTON"))
2744
+ switch (A.key) {
2745
+ case " ":
2746
+ A.preventDefault(), t.isPlaying ? t.pause() : y();
2747
+ break;
2748
+ case "ArrowRight":
2749
+ if (!o()) return;
2750
+ A.preventDefault(), t.next();
2751
+ break;
2752
+ case "ArrowLeft":
2753
+ if (!o()) return;
2754
+ A.preventDefault(), t.prev();
2755
+ break;
2756
+ case "Home":
2757
+ A.preventDefault(), t.pause(), t.seek(0);
2758
+ break;
2759
+ case "f":
2760
+ case "F":
2761
+ if (!M) return;
2762
+ A.preventDefault(), M.active ? M.exit() : M.enter();
2763
+ break;
2764
+ }
2765
+ };
2766
+ return F.addEventListener("keydown", K), c.addEventListener("keydown", K), {
2767
+ element: c,
2768
+ fullscreen: M && {
2769
+ get active() {
2770
+ return M.active;
2771
+ },
2772
+ enter: M.enter,
2773
+ exit: M.exit
2774
+ },
2775
+ destroy() {
2776
+ M?.destroy(), q(), F.removeEventListener("keydown", K), c.removeEventListener("keydown", K), c.remove();
2777
+ }
2778
+ };
2779
+ }
2780
+ function Ti(t, e, n, i) {
2781
+ const s = t.scenarios;
2782
+ if (s.length < 2) return;
2783
+ if (i === "slider") {
2784
+ const u = e.createElement("div");
2785
+ u.className = "tf-ctl-choice-slider";
2786
+ const p = e.createElement("span");
2787
+ p.textContent = n, p.setAttribute("aria-hidden", "true");
2788
+ const h = e.createElement("input");
2789
+ h.type = "range", h.min = "0", h.max = String(s.length - 1), h.step = "1", h.setAttribute("aria-label", n);
2790
+ const m = e.createElement("output");
2791
+ return m.setAttribute("aria-hidden", "true"), h.addEventListener("input", () => {
2792
+ const y = s[Number(h.value)];
2793
+ y && t.setScenario(y.id);
2794
+ }), u.append(p, h, m), { element: u, update: () => {
2795
+ const y = Math.max(0, s.findIndex((g) => g.id === t.scenario));
2796
+ e.activeElement !== h && (h.value = String(y));
2797
+ const a = s[y].label;
2798
+ m.textContent !== a && (m.textContent = a), h.setAttribute("aria-valuetext", a);
2799
+ } };
2800
+ }
2801
+ const r = e.createElement("fieldset");
2802
+ r.className = "tf-ctl-choices";
2803
+ const o = e.createElement("legend");
2804
+ o.textContent = n, r.append(o);
2805
+ const l = `tf-ctl-scenario-${++Si}`, c = s.map((u) => {
2806
+ const p = e.createElement("label");
2807
+ p.className = "tf-ctl-choice";
2808
+ const h = e.createElement("input");
2809
+ h.type = "radio", h.name = l, h.value = u.id, h.addEventListener("change", () => {
2810
+ h.checked && t.setScenario(u.id);
2811
+ });
2812
+ const m = e.createElement("span");
2813
+ return m.textContent = u.label, p.append(h, m), r.append(p), h;
2814
+ });
2815
+ return { element: r, update: () => {
2816
+ for (const u of c) {
2817
+ const p = u.value === t.scenario;
2818
+ u.checked !== p && (u.checked = p);
2819
+ }
2820
+ } };
2821
+ }
2822
+ const Oi = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>', Pi = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>';
2823
+ function Ni(t, e, n) {
2824
+ const i = e, s = t, r = e.createElement("button");
2825
+ r.type = "button", r.className = "tf-ctl-btn tf-ctl-fullscreen";
2826
+ let o, l = "";
2827
+ const c = () => {
2828
+ const y = o !== void 0;
2829
+ r.innerHTML = y ? Pi : Oi;
2830
+ const a = y ? n.exitFullscreen : n.fullscreen;
2831
+ r.setAttribute("aria-label", a), r.title = a, r.setAttribute("aria-pressed", String(y)), t.classList.toggle("tf-fullscreen", y), t.classList.toggle("tf-fullscreen-overlay", o === "overlay");
2832
+ }, d = () => i.fullscreenElement ?? i.webkitFullscreenElement ?? null, u = () => {
2833
+ d() === t ? o = "native" : o === "native" && (o = void 0), c();
2834
+ }, p = (y) => {
2835
+ y.key === "Escape" && f();
2836
+ }, h = () => {
2837
+ o = "overlay", l = e.documentElement.style.overflow, e.documentElement.style.overflow = "hidden", e.addEventListener("keydown", p), c();
2838
+ };
2839
+ async function m() {
2840
+ if (o) return;
2841
+ const y = s.requestFullscreen?.bind(s) ?? s.webkitRequestFullscreen?.bind(s), a = i.fullscreenEnabled ?? i.webkitFullscreenEnabled ?? !1;
2842
+ if (y && a)
2843
+ try {
2844
+ if (await y(), d() === t) {
2845
+ o = "native", c();
2846
+ return;
2847
+ }
2848
+ } catch {
2849
+ }
2850
+ h();
2851
+ }
2852
+ async function f() {
2853
+ if (o === "overlay")
2854
+ e.removeEventListener("keydown", p), e.documentElement.style.overflow = l, o = void 0, c();
2855
+ else if (o === "native") {
2856
+ o = void 0, c();
2857
+ const y = i.exitFullscreen?.bind(i) ?? i.webkitExitFullscreen?.bind(i);
2858
+ d() === t && y && await y();
2859
+ }
2860
+ }
2861
+ return r.addEventListener("click", () => {
2862
+ o ? f() : m();
2863
+ }), e.addEventListener("fullscreenchange", u), e.addEventListener("webkitfullscreenchange", u), c(), {
2864
+ button: r,
2865
+ get active() {
2866
+ return o !== void 0;
2867
+ },
2868
+ enter: m,
2869
+ exit: f,
2870
+ destroy() {
2871
+ f(), e.removeEventListener("fullscreenchange", u), e.removeEventListener("webkitfullscreenchange", u), r.remove();
2872
+ }
2873
+ };
2874
+ }
2875
+ const ze = "tinyfly-choices-style", Ii = `
2876
+ [data-tinyfly-choose] { cursor: pointer; }
2877
+ [data-tinyfly-choose]:focus-visible { outline: 2px solid var(--tf-ctl-accent, #c2410c); outline-offset: 2px; }
2878
+ `;
2879
+ function Li(t) {
2880
+ if (t.getElementById(ze)) return;
2881
+ const e = t.createElement("style");
2882
+ e.id = ze, e.textContent = Ii, t.head.appendChild(e);
2883
+ }
2884
+ function Fi(t, e) {
2885
+ const n = Array.from(e.querySelectorAll("[data-tinyfly-choose]"));
2886
+ if (n.length === 0) return () => {
2887
+ };
2888
+ Li(e.ownerDocument);
2889
+ const i = [], s = [];
2890
+ for (const l of n) {
2891
+ const c = l.getAttribute("data-tinyfly-choose") ?? "", d = [], u = (f, y) => {
2892
+ l.hasAttribute(f) || (l.setAttribute(f, y), d.push(f));
2893
+ };
2894
+ u("role", "button"), u("tabindex", "0");
2895
+ const p = t.scenarios.find((f) => f.id === c)?.label;
2896
+ p !== void 0 && u("aria-label", p), l.setAttribute("aria-pressed", "false"), d.push("aria-pressed"), i.push({ element: l, attributes: d });
2897
+ const h = () => t.setScenario(c), m = (f) => {
2898
+ const y = f.key;
2899
+ y !== "Enter" && y !== " " || (f.preventDefault(), h());
2900
+ };
2901
+ l.addEventListener("click", h), l.addEventListener("keydown", m), s.push(() => {
2902
+ l.removeEventListener("click", h), l.removeEventListener("keydown", m);
2903
+ });
2904
+ }
2905
+ const r = () => {
2906
+ for (const { element: l } of i)
2907
+ l.setAttribute("aria-pressed", String(l.getAttribute("data-tinyfly-choose") === t.scenario));
2908
+ }, o = t.subscribe(r);
2909
+ return r(), () => {
2910
+ o();
2911
+ for (const l of s) l();
2912
+ for (const { element: l, attributes: c } of i) for (const d of c) l.removeAttribute(d);
2913
+ };
2914
+ }
2915
+ const je = /* @__PURE__ */ new WeakMap(), qi = /* @__PURE__ */ new WeakMap();
2916
+ let Ci = 0;
2917
+ function wt(t, e, n) {
2918
+ if (t)
2919
+ try {
2920
+ return JSON.parse(t);
2921
+ } catch (i) {
2922
+ console.warn(`tinyfly: invalid ${e} JSON on`, n, i);
2923
+ return;
2924
+ }
2925
+ }
2926
+ async function zi(t, e = {}) {
2927
+ const n = je.get(t);
2928
+ if (n) return n;
2929
+ const i = Array.from(t.querySelectorAll("script[data-tinyfly-timeline]")), s = i[0], r = t.getAttribute("data-src"), o = Di(t.getAttribute("data-markers")), l = i.length > 1 || s?.hasAttribute("data-scenario") ? ji(i, o, t) : void 0;
2930
+ if (l && l.length === 0) return;
2931
+ let c = s && !l ? wt(s.textContent, "timeline", t) : void 0;
2932
+ if (!c && r && o) {
2933
+ const m = await fetch(r);
2934
+ m.ok && (c = await m.json());
2935
+ }
2936
+ if (c && o && (c = un(c, o)), !c && !r && !l) {
2937
+ console.warn('tinyfly: embed has no timeline (a <script type="application/json" data-tinyfly-timeline> or data-src)', t);
2938
+ return;
2939
+ }
2940
+ const d = wt(t.querySelector("script[data-tinyfly-captions]")?.textContent, "captions", t), u = {
2941
+ playWhenVisible: !0,
2942
+ ...e.player,
2943
+ ...d && { captions: d },
2944
+ ...wt(t.getAttribute("data-options"), "data-options", t)
2945
+ };
2946
+ Ri(t);
2947
+ const p = new $i(t, u), h = { element: t, player: p };
2948
+ if (je.set(t, h), t.setAttribute("data-tinyfly-mounted", ""), l) {
2949
+ const m = t.getAttribute("data-scenario") ?? void 0;
2950
+ await p.loadScenarios(l, { initial: l.some((f) => f.id === m) ? m : void 0 }), qi.set(t, Fi(p, t));
2951
+ } else
2952
+ await p.load(c ?? r);
2953
+ if (t.getAttribute("data-controls") !== "false") {
2954
+ const m = wt(t.getAttribute("data-labels"), "data-labels", t), f = t.querySelector("figcaption"), y = t.getAttribute("data-scenario-legend"), a = t.getAttribute("data-scenario-control");
2955
+ h.controls = Ei(p, t, {
2956
+ ...e.controls,
2957
+ ...t.getAttribute("data-fullscreen") === "true" ? { fullscreen: !0 } : {},
2958
+ ...a === "slider" || a === "buttons" ? { scenarioControl: a } : {},
2959
+ labels: { ...e.controls?.labels, ...m, ...y ? { scenario: y } : {} },
2960
+ // Inside the figure, before its figcaption, so the caption stays last.
2961
+ mount: void 0
2962
+ }), f ? t.insertBefore(h.controls.element, f) : t.appendChild(h.controls.element);
2963
+ }
2964
+ return h;
2965
+ }
2966
+ function ji(t, e, n) {
2967
+ const i = [];
2968
+ return t.forEach((s, r) => {
2969
+ const o = wt(s.textContent, "timeline", n);
2970
+ if (!o) return;
2971
+ const l = s.getAttribute("data-scenario") || `scenario-${r + 1}`;
2972
+ if (i.some((d) => d.id === l)) {
2973
+ console.warn(`tinyfly: scenario id "${l}" is used more than once; the later one is skipped`, n);
2974
+ return;
2975
+ }
2976
+ const c = s.getAttribute("data-scenario-label") ?? void 0;
2977
+ i.push({ id: l, label: c, timeline: e ? un(o, e) : o });
2978
+ }), i;
2979
+ }
2980
+ function un(t, e) {
2981
+ return t.config.markers?.length ? t : { ...t, config: { ...t.config, markers: e.map((n, i) => ({ id: `step-${i + 1}`, time: n })) } };
2982
+ }
2983
+ function Di(t) {
2984
+ if (!t) return;
2985
+ const e = t.split(/[\s,]+/).filter(Boolean).map(Number).filter((n) => Number.isFinite(n) && n >= 0).sort((n, i) => n - i);
2986
+ return e.length > 0 ? e : void 0;
2987
+ }
2988
+ function Ri(t) {
2989
+ const e = t.querySelector("svg");
2990
+ if (!e || e.hasAttribute("role") || e.hasAttribute("aria-hidden")) return;
2991
+ const n = t.getAttribute("data-alt"), i = t.querySelector("figcaption");
2992
+ e.setAttribute("role", "img"), n ? e.setAttribute("aria-label", n) : i && (i.id ||= `tinyfly-caption-${++Ci}`, e.setAttribute("aria-labelledby", i.id));
2993
+ }
2994
+ const _i = "http://www.w3.org/2000/svg", Kt = /* @__PURE__ */ new WeakMap();
2995
+ function Vi(t, e) {
2996
+ const n = t?.values.get(e);
2997
+ return n ? Object.fromEntries(n) : {};
2998
+ }
2999
+ async function Bi(t, e = {}) {
3000
+ const n = Kt.get(t);
3001
+ if (n) return n;
3002
+ const i = t.querySelector("script[data-tinyfly-figure]");
3003
+ let s;
3004
+ try {
3005
+ s = Tt(JSON.parse(i?.textContent ?? "null"));
3006
+ } catch (h) {
3007
+ console.warn("tinyfly: math figure is missing or invalid", t, h);
3008
+ return;
3009
+ }
3010
+ const r = t.getAttribute("data-target") ?? "fig";
3011
+ let o = t.querySelector("svg[data-tinyfly-math-svg]");
3012
+ o || (o = t.ownerDocument.createElementNS(_i, "svg"), o.setAttribute("data-tinyfly-math-svg", ""), o.setAttribute("viewBox", `0 0 ${s.width} ${s.height}`), o.setAttribute("style", "display:block;width:100%;height:auto"), t.insertBefore(o, t.querySelector("figcaption")));
3013
+ const l = (h) => {
3014
+ o.innerHTML = ye(Bt(s, h));
3015
+ };
3016
+ if (l({}), !(t.querySelector("script[data-tinyfly-timeline]") || t.hasAttribute("data-src"))) {
3017
+ const h = { element: t, figure: s, redraw: () => l({}) };
3018
+ return Kt.set(t, h), h;
3019
+ }
3020
+ const d = await zi(t, e);
3021
+ if (!d) return;
3022
+ const u = () => l(Vi(d.player.state, r));
3023
+ d.player.subscribe(u), u();
3024
+ const p = { ...d, figure: s, redraw: u };
3025
+ return Kt.set(t, p), p;
3026
+ }
3027
+ async function Ki(t = document, e = {}) {
3028
+ const n = Array.from(t.querySelectorAll("[data-tinyfly-math]"));
3029
+ return (await Promise.all(n.map((s) => Bi(s, e)))).filter((s) => s !== void 0);
3030
+ }
3031
+ const Wi = "http://www.w3.org/2000/svg";
3032
+ function Ji(t, e, n = {}) {
3033
+ Tt(e);
3034
+ const i = { ...e.values ?? {} };
3035
+ for (const v of n.sliders ?? [])
3036
+ if (typeof i[v.value] != "number") throw new Error(`mathExplorable: slider value "${v.value}" is not a number value of the figure`);
3037
+ for (const v of n.drag ?? []) {
3038
+ if ("vector" in v && !it(i[v.vector])) throw new Error(`mathExplorable: "${v.vector}" is not a vector value of the figure`);
3039
+ if ("matrix" in v && !pt(i[v.matrix])) throw new Error(`mathExplorable: "${v.matrix}" is not a matrix value of the figure`);
3040
+ }
3041
+ const s = on(e), r = t.ownerDocument, o = r.createElementNS(Wi, "svg");
3042
+ o.setAttribute("viewBox", `0 0 ${e.width} ${e.height}`), o.setAttribute("style", "display:block;width:100%;height:auto;touch-action:none"), o.setAttribute("role", "img"), t.appendChild(o);
3043
+ const l = n.drag ?? [], c = (v) => {
3044
+ if ("vector" in v) return i[v.vector];
3045
+ const [b, k, $, x] = i[v.matrix];
3046
+ return v.column === 0 ? [b, $] : [k, x];
3047
+ }, d = () => {
3048
+ const v = l.map((b) => {
3049
+ const [k, $] = s.toScreen(c(b));
3050
+ return `<circle cx="${k}" cy="${$}" r="${14 * s.scale}" fill="rgba(255,255,255,0.08)" stroke="rgba(255,255,255,0.55)" stroke-width="${1.5 * s.scale}" style="cursor:grab"/>`;
3051
+ });
3052
+ o.innerHTML = ye(Bt(e, i)) + v.join(""), n.onChange?.({ ...i });
3053
+ }, u = (v, b) => {
3054
+ if (!(v in i)) throw new Error(`mathExplorable: no value "${v}"`);
3055
+ i[v] = b;
3056
+ const k = p.get(v);
3057
+ k && typeof b == "number" && (k.value = String(b), h.get(v).textContent = String(b)), d();
3058
+ }, p = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map();
3059
+ let m;
3060
+ if (n.sliders?.length) {
3061
+ m = r.createElement("div"), m.setAttribute("style", "display:flex;flex-wrap:wrap;gap:8px 18px;align-items:center;padding:8px 0;font:14px system-ui,sans-serif");
3062
+ for (const v of n.sliders) {
3063
+ const b = r.createElement("label");
3064
+ b.setAttribute("style", "display:flex;align-items:center;gap:6px");
3065
+ const k = r.createElement("input");
3066
+ k.type = "range", k.min = String(v.min), k.max = String(v.max), k.step = String(v.step ?? (v.max - v.min) / 100), k.value = String(i[v.value]), k.setAttribute("aria-label", v.label ?? v.value);
3067
+ const $ = r.createElement("output");
3068
+ $.textContent = String(i[v.value]), k.addEventListener("input", () => u(v.value, Number(k.value))), b.append(v.label ?? v.value, k, $), m.appendChild(b), p.set(v.value, k), h.set(v.value, $);
3069
+ }
3070
+ t.appendChild(m);
3071
+ }
3072
+ const f = n.snap ?? 0.1, y = (v) => {
3073
+ const b = o.getBoundingClientRect(), k = (v.clientX - b.left) / (b.width || e.width) * e.width, $ = (v.clientY - b.top) / (b.height || e.height) * e.height, [x, T] = s.toWorld([k, $]), N = (q) => f > 0 ? Math.round(q / f) * f : q;
3074
+ return [Number(N(x).toFixed(6)), Number(N(T).toFixed(6))];
3075
+ };
3076
+ let a;
3077
+ const g = (v) => {
3078
+ const b = o.getBoundingClientRect(), k = e.width / (b.width || e.width), $ = [(v.clientX - b.left) * k, (v.clientY - b.top) * k];
3079
+ let x;
3080
+ for (const T of l) {
3081
+ const [N, q] = s.toScreen(c(T)), F = Math.hypot(N - $[0], q - $[1]);
3082
+ F < 30 * s.scale * Math.max(1, k) && (!x || F < x.distance) && (x = { handle: T, distance: F });
3083
+ }
3084
+ x && (a = x.handle, o.setPointerCapture?.(v.pointerId), v.preventDefault());
3085
+ }, w = (v) => {
3086
+ if (!a) return;
3087
+ const [b, k] = y(v);
3088
+ if ("vector" in a)
3089
+ u(a.vector, [b, k]);
3090
+ else {
3091
+ const [$, x, T, N] = i[a.matrix];
3092
+ u(a.matrix, a.column === 0 ? [b, x, k, N] : [$, b, T, k]);
3093
+ }
3094
+ }, M = () => {
3095
+ a = void 0;
3096
+ };
3097
+ return o.addEventListener("pointerdown", g), o.addEventListener("pointermove", w), o.addEventListener("pointerup", M), o.addEventListener("pointercancel", M), d(), {
3098
+ get values() {
3099
+ return { ...i };
3100
+ },
3101
+ set: u,
3102
+ destroy() {
3103
+ o.removeEventListener("pointerdown", g), o.removeEventListener("pointermove", w), o.removeEventListener("pointerup", M), o.removeEventListener("pointercancel", M), m?.remove();
3104
+ }
3105
+ };
3106
+ }
3107
+ const Ot = (t, e, n) => ({
3108
+ width: t.width ?? 600,
3109
+ height: t.height ?? 600,
3110
+ ...t.theme ? { theme: t.theme } : {},
3111
+ ...t.x ? { x: t.x } : {},
3112
+ values: e,
3113
+ items: n
3114
+ }), ge = "\\begin{bmatrix} \\val{M.a} & \\val{M.b} \\\\ \\val{M.c} & \\val{M.d} \\end{bmatrix}", be = (t) => [(t.width ?? 600) * 0.05, (t.height ?? 600) * 0.1];
3115
+ function Qi(t = {}) {
3116
+ return Ot(t, { M: t.matrix ?? xt }, [
3117
+ { id: "grid", kind: "grid", transform: "M", ghost: !0 },
3118
+ { id: "square", kind: "polygon", transform: "M", color: "yellow", fillOpacity: 0.25 },
3119
+ { id: "basis", kind: "basis", transform: "M" },
3120
+ { id: "matrix", kind: "label", tex: ge, at: be(t), screen: !0, align: "left" }
3121
+ ]);
3122
+ }
3123
+ function tr(t = {}) {
3124
+ return Ot(t, { M: t.matrix ?? xt }, [
3125
+ { id: "grid", kind: "grid", transform: "M", ghost: !0 },
3126
+ { id: "square", kind: "polygon", transform: "M", color: "yellow", fillOpacity: 0.35, label: "\\det = \\val{M.det}" },
3127
+ { id: "basis", kind: "basis", transform: "M" },
3128
+ { id: "matrix", kind: "label", tex: ge, at: be(t), screen: !0, align: "left" }
3129
+ ]);
3130
+ }
3131
+ function er(t) {
3132
+ return Ot(t, { M: xt, A: t.matrix }, [
3133
+ { id: "grid", kind: "grid", transform: "M", ghost: !0 },
3134
+ { id: "eigen", kind: "line", eigen: "A", color: "yellow", width: 3 },
3135
+ { id: "basis", kind: "basis", transform: "M" },
3136
+ { id: "matrix", kind: "label", tex: ge, at: be(t), screen: !0, align: "left" }
3137
+ ]);
3138
+ }
3139
+ function nr(t) {
3140
+ const e = [t.u[0] + t.v[0], t.u[1] + t.v[1]];
3141
+ return Ot(t, { u: t.u, v: t.v, s: e }, [
3142
+ { id: "grid", kind: "grid", ghost: !1, color: "grey", opacity: 0.5 },
3143
+ { id: "axes", kind: "axes" },
3144
+ { id: "arrowU", kind: "vector", to: "u", color: "green", label: "\\vec{u}", labelAt: "middle" },
3145
+ { id: "arrowV", kind: "vector", from: "u", to: "s", color: "red", label: "\\vec{v}", labelAt: "middle" },
3146
+ { id: "sum", kind: "vector", to: "s", color: "yellow", label: "\\vec{u} + \\vec{v}" }
3147
+ ]);
3148
+ }
3149
+ function ir(t) {
3150
+ const e = [
3151
+ { id: "axes", kind: "axes" },
3152
+ { id: "spanU", kind: "line", along: "u", color: "green", dashed: !0 },
3153
+ { id: "arrowU", kind: "vector", to: "u", color: "green", label: "\\vec{u}" }
3154
+ ], n = { u: t.u };
3155
+ return t.v && (n.v = t.v, e.splice(2, 0, { id: "spanV", kind: "line", along: "v", color: "red", dashed: !0 }), e.push({ id: "arrowV", kind: "vector", to: "v", color: "red", label: "\\vec{v}" })), Ot(t, n, e);
3156
+ }
3157
+ const gt = (t, e, n) => ({
3158
+ width: t.width ?? 600,
3159
+ height: t.height ?? 600,
3160
+ ...t.theme ? { theme: t.theme } : {},
3161
+ ...t.x ? { x: t.x } : {},
3162
+ ...t.y ? { y: t.y } : {},
3163
+ values: e,
3164
+ items: [{ id: "axes", kind: "axes" }, { id: "f", kind: "function", expr: t.expr, color: "blue" }, ...n]
3165
+ });
3166
+ function rr(t) {
3167
+ return gt(t, { a: t.at ?? 1 }, [
3168
+ { id: "tangent", kind: "tangent", expr: t.expr, at: "a", color: "yellow", label: "\\text{slope} = \\val{tangent.slope}" }
3169
+ ]);
3170
+ }
3171
+ function sr(t) {
3172
+ return gt(t, { a: t.at ?? 1, h: t.h ?? 2 }, [
3173
+ { id: "secant", kind: "tangent", expr: t.expr, at: "a", h: "h", color: "yellow", label: "\\frac{\\Delta y}{\\Delta x} = \\val{secant.slope}" }
3174
+ ]);
3175
+ }
3176
+ function or(t) {
3177
+ const e = gt(t, { n: t.n ?? 4 }, [
3178
+ { id: "sum", kind: "riemann", expr: t.expr, from: t.from, to: t.to, n: "n", rule: t.rule ?? "left", color: "teal" }
3179
+ ]);
3180
+ return e.items.push(e.items.splice(1, 1)[0]), e.items.push({
3181
+ id: "readout",
3182
+ kind: "label",
3183
+ screen: !0,
3184
+ align: "left",
3185
+ size: 24,
3186
+ at: [(t.width ?? 600) * 0.05, (t.height ?? 600) * 0.08],
3187
+ tex: "n = \\val{sum.n:0} \\quad \\text{sum} = \\val{sum.sum:3} \\quad \\int = \\val{sum.exact:3}"
3188
+ }), e;
3189
+ }
3190
+ function ar(t) {
3191
+ const e = gt(t, { b: t.to }, [
3192
+ { id: "area", kind: "area", expr: t.expr, from: t.from, to: "b", color: "teal" }
3193
+ ]);
3194
+ return e.items.push(e.items.splice(1, 1)[0]), e.items.push({
3195
+ id: "readout",
3196
+ kind: "label",
3197
+ screen: !0,
3198
+ align: "left",
3199
+ size: 26,
3200
+ at: [(t.width ?? 600) * 0.05, (t.height ?? 600) * 0.09],
3201
+ tex: `\\int_{${t.from}}^{\\val{b:2}} f(x)\\,dx = \\val{area.value:3}`
3202
+ }), e;
3203
+ }
3204
+ function lr(t) {
3205
+ const e = gt(t, { order: t.order ?? 1 }, [
3206
+ { id: "taylor", kind: "taylor", expr: t.expr, at: t.at ?? 0, order: "order", color: "yellow" },
3207
+ { id: "centre", kind: "point", on: t.expr, x: t.at ?? 0, color: "yellow" }
3208
+ ]);
3209
+ return e.items.push({
3210
+ id: "readout",
3211
+ kind: "label",
3212
+ screen: !0,
3213
+ align: "left",
3214
+ size: 26,
3215
+ at: [(t.width ?? 600) * 0.05, (t.height ?? 600) * 0.09],
3216
+ tex: "\\text{degree } \\val{taylor.degree:0}"
3217
+ }), e;
3218
+ }
3219
+ function cr(t) {
3220
+ const e = gt(t, { p: t.from ?? t.at - 2 }, [
3221
+ { id: "hole", kind: "point", at: [t.at, t.limit], hollow: !0, color: "blue", radius: 7 },
3222
+ { id: "moving", kind: "point", on: t.expr, x: "p", color: "yellow" }
3223
+ ]);
3224
+ return e.items.push({
3225
+ id: "readout",
3226
+ kind: "label",
3227
+ screen: !0,
3228
+ align: "left",
3229
+ size: 26,
3230
+ at: [(t.width ?? 600) * 0.05, (t.height ?? 600) * 0.09],
3231
+ tex: "f(\\val{moving.x:3}) = \\val{moving.y:4}"
3232
+ }), e;
3233
+ }
3234
+ const dt = (t, e, n, i) => ({
3235
+ width: t.width ?? 600,
3236
+ height: t.height ?? 600,
3237
+ ...t.theme ? { theme: t.theme } : {},
3238
+ x: t.x ?? e.x,
3239
+ y: t.y ?? e.y,
3240
+ values: n,
3241
+ items: i
3242
+ }), bt = (t, e) => ({
3243
+ id: "readout",
3244
+ kind: "label",
3245
+ screen: !0,
3246
+ align: "left",
3247
+ size: 24,
3248
+ at: [(t.width ?? 600) * 0.05, (t.height ?? 600) * 0.08],
3249
+ tex: e
3250
+ });
3251
+ function ur(t = {}) {
3252
+ const [e, n] = t.shade ?? [-1, 1];
3253
+ return dt(t, { x: [-4, 4], y: [-0.08, 0.55] }, { mu: t.mean ?? 0, sigma: t.sd ?? 1, a: e, b: n }, [
3254
+ { id: "axes", kind: "axes", ticks: 1, labels: !0 },
3255
+ { id: "dist", kind: "distribution", distribution: { kind: "normal", mean: "mu", sd: "sigma" }, shade: ["a", "b"] },
3256
+ bt(t, "P(\\val{a:2} \\le X \\le \\val{b:2}) = \\val{dist.p:3}")
3257
+ ]);
3258
+ }
3259
+ function dr(t = {}) {
3260
+ const e = t.n ?? 10;
3261
+ return dt(t, { x: [-1, e + 1], y: [-0.04, 0.4] }, { n: e, p: t.p ?? 0.5 }, [
3262
+ { id: "axes", kind: "axes", ticks: Math.max(1, Math.round(e / 10)) },
3263
+ { id: "dist", kind: "distribution", distribution: { kind: "binomial", n: "n", p: "p" } },
3264
+ bt(t, "n = \\val{n:0} \\quad p = \\val{p:2} \\quad \\mu = \\val{dist.mean:2}")
3265
+ ]);
3266
+ }
3267
+ function hr(t = {}) {
3268
+ return dt(t, { x: [-0.2, 3.2], y: [-0.2, 3] }, { k: t.k ?? 1, samples: t.samples ?? 2e3 }, [
3269
+ { id: "axes", kind: "axes", ticks: 1 },
3270
+ { id: "hist", kind: "histogram", distribution: { kind: "mean", of: t.of ?? { kind: "exponential", rate: 1 }, count: "k" }, count: "samples", bins: [0, 3, 45], curve: !0, color: "teal" },
3271
+ bt(t, "k = \\val{k:0} \\text{ draws averaged} \\quad \\bar{x} = \\val{hist.mean:3} \\quad s = \\val{hist.sd:3}")
3272
+ ]);
3273
+ }
3274
+ function pr(t = {}) {
3275
+ const e = t.rows ?? 10;
3276
+ return dt(t, { x: [-(e + 2) * 0.25, (e + 2) * 0.25], y: [-12, 1] }, { balls: t.balls ?? 0 }, [
3277
+ { id: "board", kind: "galton", rows: e, balls: "balls", spacing: 0.5, top: 0 },
3278
+ bt(t, "\\val{board.landed:0} \\text{ balls}")
3279
+ ]);
3280
+ }
3281
+ function fr(t = {}) {
3282
+ return dt(t, { x: [-1.3, 1.3], y: [-1.3, 1.3] }, { count: t.count ?? 0 }, [
3283
+ { id: "square", kind: "polygon", points: [[-1, -1], [1, -1], [1, 1], [-1, 1]], color: "grey", fillOpacity: 0 },
3284
+ { id: "circle", kind: "parametric", x: "cos(t)", y: "sin(t)", color: "yellow", width: 2.5 },
3285
+ { id: "pts", kind: "scatter", points: { kind: "uniform", x: [-1, 1], y: [-1, 1] }, count: "count", inside: "x^2 + y^2 - 1", color: "blue", radius: 2.2 },
3286
+ bt(t, "\\frac{\\text{inside}}{\\text{all}} = \\frac{\\val{pts.inside:0}}{\\val{pts.count:0}} = \\val{pts.ratio:4} \\approx \\frac{\\pi}{4}")
3287
+ ]);
3288
+ }
3289
+ function mr(t = {}) {
3290
+ return dt(t, { x: [-1, 11], y: [-2, 10] }, { slope: t.slope ?? 0.6, intercept: t.intercept ?? 1, noise: t.noise ?? 1, count: t.count ?? 60 }, [
3291
+ { id: "axes", kind: "axes", ticks: 2 },
3292
+ { id: "pts", kind: "scatter", points: { kind: "linear", slope: "slope", intercept: "intercept", noise: "noise", x: [0, 10] }, count: "count", fit: !0, radius: 3.5 },
3293
+ bt(t, "y = \\val{pts.slope:2}\\,x + \\val{pts.intercept:2} \\quad r = \\val{pts.r:2}")
3294
+ ]);
3295
+ }
3296
+ function yr(t = {}) {
3297
+ return dt(t, { x: [0, 1], y: [0, 1] }, { prior: t.prior ?? 0.1, sensitivity: t.sensitivity ?? 0.9, falsePositive: t.falsePositive ?? 0.1 }, [
3298
+ { id: "test", kind: "bayes", prior: "prior", truePositive: "sensitivity", falsePositive: "falsePositive", at: [0.08, 0.2], size: [0.84, 0.66] }
3299
+ ]);
3300
+ }
3301
+ function gr(t) {
3302
+ return Tt(t);
3303
+ }
3304
+ function br(t, e = {}, n = {}) {
3305
+ return vi(Bt(Tt(t), e), n);
3306
+ }
3307
+ export {
3308
+ Ct as CONSTANTS,
3309
+ zt as DISTRIBUTION_KINDS,
3310
+ ht as ExpressionError,
3311
+ Qt as FUNCTIONS,
3312
+ Ie as ITEM_KINDS,
3313
+ Tn as MATH_FONT,
3314
+ ae as MATH_THEMES,
3315
+ ge as MATRIX_TEX,
3316
+ ne as SYMBOLS,
3317
+ Pn as TEX_COMMANDS,
3318
+ On as TexError,
3319
+ ar as areaFigure,
3320
+ En as ballAt,
3321
+ Se as ballPath,
3322
+ An as bayesAreas,
3323
+ yr as bayesFigure,
3324
+ Ht as binOf,
3325
+ xn as binSamples,
3326
+ dr as binomialFigure,
3327
+ hr as cltFigure,
3328
+ R as compile,
3329
+ he as compileDerivative,
3330
+ xe as defaultBins,
3331
+ st as density,
3332
+ tr as determinantFigure,
3333
+ tt as differentiate,
3334
+ vi as displayListToSvg,
3335
+ ye as displayListToSvgContent,
3336
+ He as distributionProblem,
3337
+ gi as drawDisplayList,
3338
+ er as eigenFigure,
3339
+ rt as evaluate,
3340
+ Me as expressionNames,
3341
+ Pt as expressionToString,
3342
+ pr as galtonFigure,
3343
+ Yt as integrate,
3344
+ _t as isDiscrete,
3345
+ Bt as layoutFigure,
3346
+ ut as layoutTex,
3347
+ Ye as leastSquares,
3348
+ cr as limitFigure,
3349
+ Qi as linearMapFigure,
3350
+ Yi as mat2,
3351
+ Ji as mathExplorable,
3352
+ gr as mathFigure,
3353
+ wi as mathFigureProps,
3354
+ br as mathFigureToSvg,
3355
+ Gi as mathSteps,
3356
+ Zi as mathTarget,
3357
+ At as meanOf,
3358
+ fr as monteCarloPiFigure,
3359
+ Kn as morphEquation,
3360
+ Ki as mountAllMath,
3361
+ Bi as mountMath,
3362
+ ur as normalFigure,
3363
+ $n as nthDerivative,
3364
+ lt as parseExpression,
3365
+ Nn as parseTex,
3366
+ on as planeOf,
3367
+ mr as regressionFigure,
3368
+ or as riemannFigure,
3369
+ We as sample,
3370
+ Ue as samples,
3371
+ Xe as scatterPoints,
3372
+ Et as sdOf,
3373
+ sr as secantFigure,
3374
+ ir as spanFigure,
3375
+ Sn as summary,
3376
+ Mn as supportOf,
3377
+ rr as tangentFigure,
3378
+ lr as taylorFigure,
3379
+ yt as texToShapes,
3380
+ G as trimPolylines,
3381
+ Tt as validateMathFigure,
3382
+ Xi as vec2,
3383
+ nr as vectorSumFigure
3384
+ };