vizmatic 0.8.0 → 0.8.3

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 (97) hide show
  1. package/PROMPT.md +10 -9
  2. package/README.md +167 -61
  3. package/ROADMAP.md +5 -4
  4. package/SCIENCE.md +1 -2
  5. package/assets/THIRD_PARTY_LICENSES.md +3 -3
  6. package/assets/fonts/SourceSerif4-24pt-SemiBold.ttf +0 -0
  7. package/assets/licenses/raster-codecs-MIT.txt +2 -2
  8. package/dist/{chunk-ZB3HK7RM.js → chunk-4MXGLMBG.js} +274 -24
  9. package/dist/chunk-GGFDBJ25.js +88 -0
  10. package/dist/{chunk-USDVNKO7.js → chunk-I745F4QK.js} +2323 -357
  11. package/dist/{chunk-DZHX76RS.js → chunk-JZPMGVBP.js} +32 -3
  12. package/dist/cli.js +443 -104
  13. package/dist/index.cjs +1055 -98
  14. package/dist/index.d.cts +216 -4
  15. package/dist/index.d.ts +216 -4
  16. package/dist/index.js +734 -63
  17. package/dist/scene-browser-chunks/chunk-RQNLYYJN.js +70 -0
  18. package/dist/scene-browser-chunks/{scene-browser-layout-M3XSXMV4.js → scene-browser-layout-RC3ECYRK.js} +1 -1
  19. package/dist/scene-browser.js +16 -16
  20. package/dist/scene-cli.js +1 -1
  21. package/dist/scene-runtime.cjs +24 -3
  22. package/dist/scene-runtime.js +1 -1
  23. package/dist/{server-2FYHZ4UO.js → server-Q4COUZHV.js} +3 -3
  24. package/dist/stage-browser/browser.d.ts +8240 -315
  25. package/dist/stage-browser/stage.js +22 -5
  26. package/dist/stage-export.cjs +3640 -298
  27. package/dist/stage-export.d.cts +56 -3
  28. package/dist/stage-export.d.ts +56 -3
  29. package/dist/stage-export.js +677 -149
  30. package/dist/stage.cjs +33026 -7554
  31. package/dist/stage.d.cts +7809 -286
  32. package/dist/stage.d.ts +7809 -286
  33. package/dist/stage.js +26066 -2599
  34. package/dist/{svg-import-C-RG1t7s.d.cts → svg-import-B5BGbC1t.d.cts} +455 -53
  35. package/dist/{svg-import-C-RG1t7s.d.ts → svg-import-B5BGbC1t.d.ts} +455 -53
  36. package/dist/{video-BSwNJZkn.d.ts → video-CiN1MDCS.d.cts} +27 -2
  37. package/dist/{video-BSwNJZkn.d.cts → video-CiN1MDCS.d.ts} +27 -2
  38. package/examples/README.md +1 -1
  39. package/examples/_teaching/layer-stack-connector.ts +36 -0
  40. package/examples/_teaching/layer-stack-recurrence.ts +29 -0
  41. package/examples/_teaching/layer-stack-tiny-gpt.ts +37 -0
  42. package/examples/_teaching/layer-stack-transformer.ts +44 -0
  43. package/examples/catalog-convolution-kernel.tsx +6 -7
  44. package/examples/{aurora-incident.tsx → checkout-incident.tsx} +1 -1
  45. package/examples/films/beam-search.ts +52 -0
  46. package/examples/films/cache-miss.ts +4 -3
  47. package/examples/films/catalog.json +30 -0
  48. package/examples/films/forecast.ts +354 -0
  49. package/examples/films/passage/chunking.ts +40 -0
  50. package/examples/films/passage/evidence.ts +44 -0
  51. package/examples/films/passage/prompt.ts +34 -0
  52. package/examples/films/paxos.ts +596 -0
  53. package/examples/films/taylor-series.ts +1 -1
  54. package/examples/narrated-cues/README.md +32 -0
  55. package/examples/narrated-cues/data/numbers.json +1 -0
  56. package/examples/narrated-cues/film.json +9 -0
  57. package/examples/narrated-cues/film.ts +78 -0
  58. package/examples/narrated-cues/package.json +1 -0
  59. package/examples/narrated-cues/script.json +57 -0
  60. package/examples/narrated-cues/timing.json +1 -0
  61. package/examples/narrated-cues/tsconfig.json +1 -0
  62. package/examples/proofs/decoding-bars.ts +67 -0
  63. package/examples/proofs/pipeline.ts +27 -0
  64. package/examples/proofs/table/evaluation.ts +41 -0
  65. package/examples/proofs/table/ledger.ts +47 -0
  66. package/examples/proofs/table/routing.ts +46 -0
  67. package/package.json +9 -4
  68. package/templates/narrated/README.md +61 -0
  69. package/templates/narrated/data/numbers.json +5 -0
  70. package/templates/narrated/film.json +12 -0
  71. package/templates/narrated/film.ts +14 -0
  72. package/templates/narrated/gitignore +8 -0
  73. package/templates/narrated/package.json +1 -0
  74. package/templates/narrated/scenes/answer.ts +25 -0
  75. package/templates/narrated/scenes/kit.ts +39 -0
  76. package/templates/narrated/scenes/question.ts +31 -0
  77. package/templates/narrated/script.json +26 -0
  78. package/templates/narrated/sources.md +22 -0
  79. package/templates/narrated/timing.json +1 -0
  80. package/templates/narrated/tsconfig.json +1 -0
  81. package/tools/narration/README.md +123 -0
  82. package/tools/narration/beats.py +43 -0
  83. package/tools/narration/checks.py +587 -0
  84. package/tools/narration/draft.py +73 -0
  85. package/tools/narration/film.py +341 -0
  86. package/tools/narration/lag.py +58 -0
  87. package/tools/narration/mix.py +265 -0
  88. package/tools/narration/probe.py +99 -0
  89. package/tools/narration/record.py +33 -0
  90. package/tools/narration/resound.py +170 -0
  91. package/tools/narration/soundbed.py +404 -0
  92. package/tools/narration/sync.py +93 -0
  93. package/tools/narration/transcribe.py +84 -0
  94. package/tools/narration/verify.py +59 -0
  95. package/tools/narration/voice.py +113 -0
  96. package/dist/chunk-6N6P2GJG.js +0 -88
  97. package/dist/scene-browser-chunks/chunk-5MVLYGXM.js +0 -70
@@ -140,6 +140,9 @@ var tokens = midnight.colors;
140
140
  function setColorTokens(next) {
141
141
  tokens = next;
142
142
  }
143
+ function getColorTokens() {
144
+ return tokens;
145
+ }
143
146
  function parseColor(input) {
144
147
  const token = tokens[input];
145
148
  const value = token ?? input;
@@ -168,6 +171,26 @@ function toPaint(input) {
168
171
  function isGradient(paint) {
169
172
  return !Array.isArray(paint);
170
173
  }
174
+ function luminance(color) {
175
+ const channel = (value) => {
176
+ const x = value / 255;
177
+ return x <= 0.03928 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
178
+ };
179
+ return 0.2126 * channel(color[0]) + 0.7152 * channel(color[1]) + 0.0722 * channel(color[2]);
180
+ }
181
+ function contrast(first, second) {
182
+ const x = luminance(first), y = luminance(second);
183
+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);
184
+ }
185
+ function over(color, alpha, background) {
186
+ const a = color[3] * alpha;
187
+ return [
188
+ color[0] * a + background[0] * (1 - a),
189
+ color[1] * a + background[1] * (1 - a),
190
+ color[2] * a + background[2] * (1 - a),
191
+ 1
192
+ ];
193
+ }
171
194
  function css(color, alpha = 1) {
172
195
  const a = color[3] * alpha;
173
196
  const r = Math.round(color[0]), g = Math.round(color[1]), b = Math.round(color[2]);
@@ -243,6 +266,18 @@ function mixPaint(a, b, t) {
243
266
  const solidB = gb ? sampleStops(b.stops, 0.5) : b;
244
267
  return mixColor(solidA, solidB, t);
245
268
  }
269
+ function toward(backdrop, color, dim) {
270
+ return [
271
+ backdrop[0] + (color[0] - backdrop[0]) * dim,
272
+ backdrop[1] + (color[1] - backdrop[1]) * dim,
273
+ backdrop[2] + (color[2] - backdrop[2]) * dim,
274
+ color[3]
275
+ ];
276
+ }
277
+ function dimPaint(paint, dim, backdrop) {
278
+ if (!isGradient(paint)) return toward(backdrop, paint, dim);
279
+ return { ...paint, stops: paint.stops.map(([at, color]) => [at, toward(backdrop, color, dim)]) };
280
+ }
246
281
  function sampleStops(stops, at) {
247
282
  if (stops.length === 0) return TRANSPARENT;
248
283
  if (at <= stops[0][0]) return stops[0][1];
@@ -282,6 +317,18 @@ function ramp(count, ...colors) {
282
317
  }
283
318
 
284
319
  // src/stage/geometry.ts
320
+ function projectToLine(point, origin, towards) {
321
+ const dx = towards[0] - origin[0], dy = towards[1] - origin[1];
322
+ const length = Math.hypot(dx, dy);
323
+ if (length === 0) throw new RangeError("A projection line needs two distinct points");
324
+ const ux = dx / length, uy = dy / length;
325
+ const signedDistance = (point[0] - origin[0]) * ux + (point[1] - origin[1]) * uy;
326
+ const foot = [origin[0] + signedDistance * ux, origin[1] + signedDistance * uy];
327
+ if (!Number.isFinite(length) || !Number.isFinite(foot[0]) || !Number.isFinite(foot[1])) {
328
+ throw new RangeError("Projection coordinates must give a finite line and foot");
329
+ }
330
+ return { foot, signedDistance };
331
+ }
285
332
  var IDENTITY = [1, 0, 0, 1, 0, 0];
286
333
  var EMPTY_BOUNDS = { x: 0, y: 0, width: 0, height: 0 };
287
334
  var KAPPA = 0.5522847498307936;
@@ -312,14 +359,14 @@ function invert(m) {
312
359
  function apply(m, x, y) {
313
360
  return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
314
361
  }
315
- function compose(x, y, rotation, sx, sy, px, py) {
362
+ function compose(x, y, rotation, sx, sy, px2, py) {
316
363
  const cos = rotation === 0 ? 1 : Math.cos(rotation);
317
364
  const sin = rotation === 0 ? 0 : Math.sin(rotation);
318
365
  const a = cos * sx;
319
366
  const b = sin * sx;
320
367
  const c = -sin * sy;
321
368
  const d = cos * sy;
322
- return [a, b, c, d, x - a * px - c * py, y - b * px - d * py];
369
+ return [a, b, c, d, x - a * px2 - c * py, y - b * px2 - d * py];
323
370
  }
324
371
  function matScale(m) {
325
372
  return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
@@ -546,8 +593,8 @@ function locate(m, distance) {
546
593
  let k = 0;
547
594
  while (k < LUT_STEPS - 1 && m.lut[base + k] < local) k++;
548
595
  const start = k === 0 ? 0 : m.lut[base + k - 1];
549
- const end = m.lut[base + k];
550
- const fraction = end > start ? (local - start) / (end - start) : 0;
596
+ const end2 = m.lut[base + k];
597
+ const fraction = end2 > start ? (local - start) / (end2 - start) : 0;
551
598
  return [lo, (k + fraction) / LUT_STEPS];
552
599
  }
553
600
  function trimRing(r, from, to2) {
@@ -565,16 +612,16 @@ function trimRing(r, from, to2) {
565
612
  for (let i = i0; i <= i1; i++) {
566
613
  let seg = Array.from(r.p.subarray(i * 6, i * 6 + 8));
567
614
  const start = i === i0 ? t0 : 0;
568
- const end = i === i1 ? t1 : 1;
615
+ const end2 = i === i1 ? t1 : 1;
569
616
  if (start > 0) {
570
617
  const rest = [];
571
618
  splitInto(seg, 0, start, [], rest);
572
619
  seg = rest;
573
620
  }
574
- if (end < 1) {
621
+ if (end2 < 1) {
575
622
  const left = [];
576
623
  const rest = [];
577
- const scaled = start > 0 ? (end - start) / (1 - start) : end;
624
+ const scaled = start > 0 ? (end2 - start) / (1 - start) : end2;
578
625
  splitInto(seg, 0, scaled, left, rest);
579
626
  seg = [seg[0], seg[1], ...left];
580
627
  }
@@ -599,10 +646,10 @@ function trimPath(path, from, to2, each = false) {
599
646
  for (const r of path) {
600
647
  const length = ringLength(r);
601
648
  const start = (from * total - travelled) / (length || 1);
602
- const end = (to2 * total - travelled) / (length || 1);
649
+ const end2 = (to2 * total - travelled) / (length || 1);
603
650
  travelled += length;
604
- if (end <= 0 || start >= 1) continue;
605
- const piece = trimRing(r, Math.max(0, start), Math.min(1, end));
651
+ if (end2 <= 0 || start >= 1) continue;
652
+ const piece = trimRing(r, Math.max(0, start), Math.min(1, end2));
606
653
  if (piece) out.push(piece);
607
654
  }
608
655
  return out;
@@ -651,9 +698,9 @@ function extendCubicAxis(range, p0, p1, p2, p3) {
651
698
  if (Math.abs(a) < 1e-9) {
652
699
  if (Math.abs(b) > 1e-9) roots.push(-c / b);
653
700
  } else {
654
- const disc = b * b - 4 * a * c;
655
- if (disc >= 0) {
656
- const s = Math.sqrt(disc);
701
+ const disc2 = b * b - 4 * a * c;
702
+ if (disc2 >= 0) {
703
+ const s = Math.sqrt(disc2);
657
704
  roots.push((-b + s) / (2 * a), (-b - s) / (2 * a));
658
705
  }
659
706
  }
@@ -743,8 +790,8 @@ function parseSvgPath(d) {
743
790
  if (out.length >= 8) rings.push(ring(out, closed));
744
791
  out = [];
745
792
  };
746
- const begin = (px, py) => {
747
- if (out.length === 0) out.push(px, py);
793
+ const begin2 = (px2, py) => {
794
+ if (out.length === 0) out.push(px2, py);
748
795
  };
749
796
  let cmd = "";
750
797
  while (i < tokens2.length) {
@@ -772,7 +819,7 @@ function parseSvgPath(d) {
772
819
  }
773
820
  case "L": {
774
821
  const nx = (rel ? x : 0) + num(), ny = (rel ? y : 0) + num();
775
- begin(x, y);
822
+ begin2(x, y);
776
823
  lineInto(out, x, y, nx, ny);
777
824
  x = nx;
778
825
  y = ny;
@@ -780,14 +827,14 @@ function parseSvgPath(d) {
780
827
  }
781
828
  case "H": {
782
829
  const nx = (rel ? x : 0) + num();
783
- begin(x, y);
830
+ begin2(x, y);
784
831
  lineInto(out, x, y, nx, y);
785
832
  x = nx;
786
833
  break;
787
834
  }
788
835
  case "V": {
789
836
  const ny = (rel ? y : 0) + num();
790
- begin(x, y);
837
+ begin2(x, y);
791
838
  lineInto(out, x, y, x, ny);
792
839
  y = ny;
793
840
  break;
@@ -795,7 +842,7 @@ function parseSvgPath(d) {
795
842
  case "C": {
796
843
  const ox = rel ? x : 0, oy = rel ? y : 0;
797
844
  const c1x = ox + num(), c1y = oy + num(), c2x = ox + num(), c2y = oy + num(), nx = ox + num(), ny = oy + num();
798
- begin(x, y);
845
+ begin2(x, y);
799
846
  out.push(c1x, c1y, c2x, c2y, nx, ny);
800
847
  lastCx = c2x;
801
848
  lastCy = c2y;
@@ -808,7 +855,7 @@ function parseSvgPath(d) {
808
855
  const smooth2 = "CScs".includes(lastCmd);
809
856
  const c1x = smooth2 ? 2 * x - lastCx : x, c1y = smooth2 ? 2 * y - lastCy : y;
810
857
  const c2x = ox + num(), c2y = oy + num(), nx = ox + num(), ny = oy + num();
811
- begin(x, y);
858
+ begin2(x, y);
812
859
  out.push(c1x, c1y, c2x, c2y, nx, ny);
813
860
  lastCx = c2x;
814
861
  lastCy = c2y;
@@ -819,7 +866,7 @@ function parseSvgPath(d) {
819
866
  case "Q": {
820
867
  const ox = rel ? x : 0, oy = rel ? y : 0;
821
868
  const qx = ox + num(), qy = oy + num(), nx = ox + num(), ny = oy + num();
822
- begin(x, y);
869
+ begin2(x, y);
823
870
  out.push(x + (qx - x) * 2 / 3, y + (qy - y) * 2 / 3, nx + (qx - nx) * 2 / 3, ny + (qy - ny) * 2 / 3, nx, ny);
824
871
  lastCx = qx;
825
872
  lastCy = qy;
@@ -832,7 +879,7 @@ function parseSvgPath(d) {
832
879
  const smooth2 = "QTqt".includes(lastCmd);
833
880
  const qx = smooth2 ? 2 * x - lastCx : x, qy = smooth2 ? 2 * y - lastCy : y;
834
881
  const nx = ox + num(), ny = oy + num();
835
- begin(x, y);
882
+ begin2(x, y);
836
883
  out.push(x + (qx - x) * 2 / 3, y + (qy - y) * 2 / 3, nx + (qx - nx) * 2 / 3, ny + (qy - ny) * 2 / 3, nx, ny);
837
884
  lastCx = qx;
838
885
  lastCy = qy;
@@ -843,7 +890,7 @@ function parseSvgPath(d) {
843
890
  case "A": {
844
891
  const rx = num(), ry = num(), angle = num(), large = flags(), sweep = flags();
845
892
  const nx = (rel ? x : 0) + num(), ny = (rel ? y : 0) + num();
846
- begin(x, y);
893
+ begin2(x, y);
847
894
  arcInto(out, x, y, rx, ry, angle, large === 1, sweep === 1, nx, ny);
848
895
  x = nx;
849
896
  y = ny;
@@ -935,14 +982,29 @@ function pathToD(path) {
935
982
  }
936
983
 
937
984
  // src/stage/track.ts
985
+ var LIBRARY_FONT = "sans";
938
986
  var clock = {
939
987
  now: 0,
940
988
  mode: "free",
941
989
  /** Increments once per rendered frame and invalidates per-frame overlays. */
942
990
  frame: 0,
943
991
  /** While set, writes to mounted nodes collect here instead of creating keys. */
944
- capture: null
992
+ capture: null,
993
+ /**
994
+ * The font that the film names for its texts, or null: outside a film, and in a film that names none.
995
+ * A text measures its glyphs when it is made, so the font must be known then. The font of a film lives on
996
+ * its stage. The stage puts it here when the callback of the film starts, at each call that the callback
997
+ * makes on the stage, and while one of its frames is drawn.
998
+ */
999
+ font: null,
1000
+ /**
1001
+ * The stage of the film whose callback runs now, or null outside a film. The stage puts itself here where
1002
+ * it puts its font. The layout reads the frame from it, and adds a check for the end of the build: a node
1003
+ * that it put off the frame stops the build.
1004
+ */
1005
+ canvas: null
945
1006
  };
1007
+ var moves = (key) => key.at !== null && key.t1 > key.t0;
946
1008
  var Track = class {
947
1009
  constructor(initial) {
948
1010
  this.initial = initial;
@@ -977,11 +1039,23 @@ var Track = class {
977
1039
  step(t, value) {
978
1040
  this.add({ t0: t, t1: t, ease: null, to: value, at: null });
979
1041
  }
1042
+ /**
1043
+ * A step that does not take the place of a motion. It sets the value at a time, and a motion that starts
1044
+ * at that time stays in effect, whatever the order in which the two were written. A change of the pivot
1045
+ * of a node writes the place of the node this way: it keeps the node where it is, and it is not a move.
1046
+ * So the order of two animations of one play does not decide if a node moves.
1047
+ */
1048
+ stepUnder(t, value) {
1049
+ const keys = this.keys;
1050
+ let index = keys.length;
1051
+ while (index > 0 && (keys[index - 1].t0 > t || keys[index - 1].t0 === t && moves(keys[index - 1]))) index--;
1052
+ keys.splice(index, 0, { t0: t, t1: t, ease: null, to: value, at: null });
1053
+ }
980
1054
  /** Last time this track changes. */
981
1055
  get end() {
982
- let end = 0;
983
- for (const key of this.keys) if (key.t1 > end) end = key.t1;
984
- return end;
1056
+ let end2 = 0;
1057
+ for (const key of this.keys) if (key.t1 > end2) end2 = key.t1;
1058
+ return end2;
985
1059
  }
986
1060
  };
987
1061
 
@@ -1151,6 +1225,7 @@ function matchSequence(a, b) {
1151
1225
  }
1152
1226
 
1153
1227
  // src/stage/node.ts
1228
+ var rebindCloneParts = /* @__PURE__ */ Symbol("rebindCloneParts");
1154
1229
  var DEFAULT_PROPS = {
1155
1230
  x: 0,
1156
1231
  y: 0,
@@ -1160,6 +1235,7 @@ var DEFAULT_PROPS = {
1160
1235
  px: 0,
1161
1236
  py: 0,
1162
1237
  opacity: 1,
1238
+ dim: 1,
1163
1239
  visible: true,
1164
1240
  z: 0,
1165
1241
  path: null,
@@ -1190,6 +1266,7 @@ var NUMERIC = /* @__PURE__ */ new Set([
1190
1266
  "px",
1191
1267
  "py",
1192
1268
  "opacity",
1269
+ "dim",
1193
1270
  "z",
1194
1271
  "fillOpacity",
1195
1272
  "strokeOpacity",
@@ -1222,6 +1299,18 @@ function mixer(prop, from, to2) {
1222
1299
  return null;
1223
1300
  }
1224
1301
  var nextId = 1;
1302
+ var isBlock = (value) => typeof value === "object" && value !== null && !(value instanceof Node) && !Array.isArray(value) && Array.isArray(value.items) && typeof value.kind === "string";
1303
+ var notNode = (value) => value === null ? "null" : Array.isArray(value) ? "a list" : typeof value === "object" ? "an object that is not a node" : typeof value === "string" ? JSON.stringify(value) : String(value);
1304
+ function boundsOfTarget(what, target) {
1305
+ if (target instanceof Node) return target.bounds();
1306
+ if (isBlock(target)) {
1307
+ const boxes = target.nodes.map((node) => node.bounds());
1308
+ const x = Math.min(...boxes.map((b) => b.x)), y = Math.min(...boxes.map((b) => b.y));
1309
+ return { x, y, width: Math.max(...boxes.map((b) => b.x + b.width)) - x, height: Math.max(...boxes.map((b) => b.y + b.height)) - y };
1310
+ }
1311
+ if (Array.isArray(target) && target.length === 2 && Number.isFinite(target[0]) && Number.isFinite(target[1])) return { x: target[0], y: target[1], width: 0, height: 0 };
1312
+ throw new Error(`${what}: the target is ${Array.isArray(target) && target.length === 2 ? `the point [${target[0]}, ${target[1]}], which is not a place` : notNode(target)}. Give a node, a block of the layout, or a point [x, y] of the stage`);
1313
+ }
1225
1314
  var Node = class _Node {
1226
1315
  id = nextId++;
1227
1316
  parent = null;
@@ -1230,6 +1319,12 @@ var Node = class _Node {
1230
1319
  data = {};
1231
1320
  /** Label shown in timelines and diagnostics. */
1232
1321
  label = "";
1322
+ /**
1323
+ * The box that the layout measures for this node, in the coordinates of the node: left, top, right and
1324
+ * bottom. Null for a node that measures as its bounds. A text sets its line box, and a pictogram sets the
1325
+ * square of its grid, so that items of one size line up whatever they draw. `boxOf` reads it.
1326
+ */
1327
+ layoutBox = null;
1233
1328
  base = Object.create(DEFAULT_PROPS);
1234
1329
  tracks = null;
1235
1330
  overlay = null;
@@ -1240,6 +1335,11 @@ var Node = class _Node {
1240
1335
  draw = null;
1241
1336
  /** Emits draw operations directly, for objects with thousands of marks such as 3D meshes. */
1242
1337
  rawOps = null;
1338
+ /**
1339
+ * The node whose `draw` built this node for the frame that is on screen. A node that `draw` returns has no
1340
+ * parent, so this is the way from a mark of a dynamic drawing up to the object that made it.
1341
+ */
1342
+ drawer = null;
1243
1343
  constructor(path) {
1244
1344
  if (path) this.base.path = path;
1245
1345
  }
@@ -1297,7 +1397,8 @@ var Node = class _Node {
1297
1397
  }
1298
1398
  // ── Tree ──────────────────────────────────────────────────────────────
1299
1399
  add(...nodes) {
1300
- for (const child of nodes) {
1400
+ for (const child of nodes.flatMap((item) => isBlock(item) ? item.nodes : [item])) {
1401
+ if (!(child instanceof _Node)) throw new Error(`add: a child is ${notNode(child)}. Give nodes, or blocks of the layout`);
1301
1402
  if (child.parent === this) continue;
1302
1403
  child.parent?.drop(child);
1303
1404
  child.parent = this;
@@ -1326,12 +1427,40 @@ var Node = class _Node {
1326
1427
  leaves() {
1327
1428
  return this.all().filter((node) => node.get("path") !== null || node.draw !== null || node.get("image") !== null);
1328
1429
  }
1329
- /** A static copy of the current state, off stage. */
1430
+ /**
1431
+ * A static copy of the current state, off stage. An object that keeps its parts in fields, such as the
1432
+ * glyphs of a text or the frame of a card, gets fields that point at the copies of those parts.
1433
+ */
1330
1434
  clone() {
1435
+ const copies = /* @__PURE__ */ new Map();
1436
+ const copy = this.copyTree(copies);
1437
+ delete copy.data["ownLabel"];
1438
+ for (const [from, to2] of copies) {
1439
+ for (const [key, value] of Object.entries(from)) {
1440
+ if (key === "parent" || key === "children") continue;
1441
+ const target = to2;
1442
+ if (value instanceof _Node) {
1443
+ const part = copies.get(value);
1444
+ if (part) target[key] = part;
1445
+ } else if (Array.isArray(value) && value.some((item) => item instanceof _Node) && value.every((item) => item === null || item instanceof _Node)) {
1446
+ target[key] = value.map((item) => item ? copies.get(item) ?? item : null);
1447
+ }
1448
+ }
1449
+ }
1450
+ let connections;
1451
+ for (const [from, to2] of copies) {
1452
+ const connect = from[rebindCloneParts]?.(to2, copies);
1453
+ if (connect) (connections ??= []).push(connect);
1454
+ }
1455
+ for (const connect of connections ?? []) connect();
1456
+ return copy;
1457
+ }
1458
+ copyTree(copies) {
1331
1459
  const copy = Object.create(Object.getPrototypeOf(this));
1332
1460
  Object.assign(copy, this);
1333
1461
  copy.id = nextId++;
1334
1462
  copy.parent = null;
1463
+ copy.drawer = null;
1335
1464
  copy.mounted = false;
1336
1465
  copy.tracks = null;
1337
1466
  copy.overlay = null;
@@ -1343,10 +1472,11 @@ var Node = class _Node {
1343
1472
  copy.base[key] = this.get(key);
1344
1473
  }
1345
1474
  copy.children = this.children.map((child) => {
1346
- const next = child.clone();
1475
+ const next = child.copyTree(copies);
1347
1476
  next.parent = copy;
1348
1477
  return next;
1349
1478
  });
1479
+ copies.set(this, copy);
1350
1480
  return copy;
1351
1481
  }
1352
1482
  // ── Transforms ────────────────────────────────────────────────────────
@@ -1410,8 +1540,8 @@ var Node = class _Node {
1410
1540
  }
1411
1541
  /** Set the local position of the origin. */
1412
1542
  at(x, y) {
1413
- const [px, py] = typeof x === "number" ? [x, y ?? 0] : x;
1414
- this.set("x", px);
1543
+ const [px2, py] = typeof x === "number" ? [x, y ?? 0] : x;
1544
+ this.set("x", px2);
1415
1545
  this.set("y", py);
1416
1546
  return this;
1417
1547
  }
@@ -1423,7 +1553,8 @@ var Node = class _Node {
1423
1553
  }
1424
1554
  /** Move so the center of the bounds lands on a stage point or on another node's center. */
1425
1555
  moveTo(target) {
1426
- const destination = target instanceof _Node ? target.center : target;
1556
+ const to2 = boundsOfTarget("moveTo", target);
1557
+ const destination = target instanceof _Node ? target.center : [to2.x + to2.width / 2, to2.y + to2.height / 2];
1427
1558
  const [cx, cy] = this.center;
1428
1559
  const inverse = this.parent ? invert(this.parent.worldMatrix()) : IDENTITY;
1429
1560
  const [lx0, ly0] = apply(inverse, cx, cy);
@@ -1438,10 +1569,19 @@ var Node = class _Node {
1438
1569
  const [nx, ny] = apply(invert(parent), point[0], point[1]);
1439
1570
  this.set("px", lx);
1440
1571
  this.set("py", ly);
1441
- this.set("x", nx);
1442
- this.set("y", ny);
1572
+ this.pivotPlace("x", nx);
1573
+ this.pivotPlace("y", ny);
1443
1574
  return this;
1444
1575
  }
1576
+ /**
1577
+ * Write the place that goes with a new pivot. It keeps the node where it is, so it is not a move: on the
1578
+ * timeline, a motion that starts at this time stays in effect. Without this, `grow` after `along` in one
1579
+ * play would stop the node.
1580
+ */
1581
+ pivotPlace(prop, value) {
1582
+ if (clock.capture || !this.mounted || clock.mode === "render") this.set(prop, value);
1583
+ else this.track(prop).stepUnder(clock.now, value);
1584
+ }
1445
1585
  /** Scale around the center, or around a given stage point. */
1446
1586
  scale(factor, about) {
1447
1587
  const [fx, fy] = typeof factor === "number" ? [factor, factor] : factor;
@@ -1468,7 +1608,7 @@ var Node = class _Node {
1468
1608
  /** Place beside another node or stage point, with a gap measured between bounds. */
1469
1609
  nextTo(target, side = "right", gap = 28) {
1470
1610
  const [dx, dy] = direction(side);
1471
- const b = target instanceof _Node ? target.bounds() : { x: target[0], y: target[1], width: 0, height: 0 };
1611
+ const b = boundsOfTarget("nextTo", target);
1472
1612
  const own = this.bounds();
1473
1613
  const cx = b.x + b.width / 2, cy = b.y + b.height / 2;
1474
1614
  const anchorX = cx + dx * (b.width / 2 + gap + own.width / 2);
@@ -1478,13 +1618,17 @@ var Node = class _Node {
1478
1618
  /** Line up one edge with another node's same edge. */
1479
1619
  alignTo(target, edge) {
1480
1620
  const own = this.bounds();
1481
- const b = target instanceof _Node ? target.bounds() : { x: target[0], y: target[1], width: 0, height: 0 };
1621
+ const b = boundsOfTarget("alignTo", target);
1482
1622
  if (edge === "left") return this.shift(b.x - own.x, 0);
1483
1623
  if (edge === "right") return this.shift(b.x + b.width - own.x - own.width, 0);
1484
1624
  if (edge === "top") return this.shift(0, b.y - own.y);
1485
1625
  return this.shift(0, b.y + b.height - own.y - own.height);
1486
1626
  }
1487
- /** Lay out children in a row or column, keeping the group's center. */
1627
+ /**
1628
+ * Lay out children in a row or column, keeping the group's center. It stays for the films that use it.
1629
+ * In a new film, use `row` and `column` of the layout: they line up left edges and base lines, they nest,
1630
+ * and they leave each node its own, so one node fades in without the others.
1631
+ */
1488
1632
  arrange(side = "right", gap = 24) {
1489
1633
  const [dx, dy] = direction(side);
1490
1634
  const center = this.center;
@@ -1492,9 +1636,9 @@ var Node = class _Node {
1492
1636
  for (const child of this.children) {
1493
1637
  if (previous) {
1494
1638
  const b = previous.bounds(), own = child.bounds();
1495
- const px = b.x + b.width / 2 + dx * (b.width / 2 + gap + own.width / 2);
1639
+ const px2 = b.x + b.width / 2 + dx * (b.width / 2 + gap + own.width / 2);
1496
1640
  const py = b.y + b.height / 2 + dy * (b.height / 2 + gap + own.height / 2);
1497
- child.moveTo([dx === 0 ? b.x + b.width / 2 : px, dy === 0 ? b.y + b.height / 2 : py]);
1641
+ child.moveTo([dx === 0 ? b.x + b.width / 2 : px2, dy === 0 ? b.y + b.height / 2 : py]);
1498
1642
  }
1499
1643
  previous = child;
1500
1644
  }
@@ -1555,6 +1699,13 @@ var Node = class _Node {
1555
1699
  this.label = label;
1556
1700
  return this;
1557
1701
  }
1702
+ /**
1703
+ * The labels that belong to one part of this object, such as the name and the readout of a bar. A light
1704
+ * on the part keeps them bright. An object that has such labels says so here.
1705
+ */
1706
+ labelsOf(_part) {
1707
+ return [];
1708
+ }
1558
1709
  };
1559
1710
  function boundsOfRect(m, width, height) {
1560
1711
  const corners = [apply(m, 0, 0), apply(m, width, 0), apply(m, width, height), apply(m, 0, height)];
@@ -1578,6 +1729,19 @@ function mountTree(node, time) {
1578
1729
  if (wasVisible) track.step(time, true);
1579
1730
  }
1580
1731
  }
1732
+ function ownLabels(owner, options = {}) {
1733
+ if (!(owner instanceof Node)) throw new Error(`ownLabels: the owner is ${isBlock(owner) ? "a block of the layout" : notNode(owner)}. Give the node of the object`);
1734
+ if (options.name) objectName(owner, options.name);
1735
+ if (options.plot || !owner.data["ownLayout"]) owner.data["ownLayout"] = options.plot ? "plot" : true;
1736
+ const labels = options.labels ?? owner.all().filter((node) => node.draw !== null || node.children.some((child) => child.data["key"] !== void 0));
1737
+ for (const label of labels) if (label) label.data["ownLabel"] = true;
1738
+ return owner;
1739
+ }
1740
+ function objectName(node, name) {
1741
+ if (!(node instanceof Node)) throw new Error(`objectName: the first argument is ${isBlock(node) ? "a block of the layout" : notNode(node)}. Give the node of the object`);
1742
+ node.data["object"] = name;
1743
+ return node;
1744
+ }
1581
1745
  function group(...children) {
1582
1746
  return new Node().add(...children);
1583
1747
  }
@@ -1662,16 +1826,16 @@ function inspectPng(bytes, strict = true) {
1662
1826
  const width = view.getUint32(16), height = view.getUint32(20);
1663
1827
  if (!width || !height || width * height > MAX_PIXELS) fail(`Image PNG must contain at most ${MAX_PIXELS} pixels with positive dimensions.`);
1664
1828
  const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[bytes[25]];
1665
- const depth = bytes[24], interlace = bytes[28];
1666
- if (strict && (depth !== 8 || interlace !== 0)) {
1829
+ const depth2 = bytes[24], interlace = bytes[28];
1830
+ if (strict && (depth2 !== 8 || interlace !== 0)) {
1667
1831
  fail("Image assets support noninterlaced 8-bit PNGs, including RGB, RGBA, grayscale and palette images.");
1668
1832
  }
1669
1833
  const depths = bytes[25] === 0 ? [1, 2, 4, 8, 16] : bytes[25] === 3 ? [1, 2, 4, 8] : [8, 16];
1670
- if (!channels || !depths.includes(depth) || bytes[26] !== 0 || bytes[27] !== 0 || interlace > 1) fail("Image PNG has unsupported header fields.");
1834
+ if (!channels || !depths.includes(depth2) || bytes[26] !== 0 || bytes[27] !== 0 || interlace > 1) fail("Image PNG has unsupported header fields.");
1671
1835
  const passes = interlace ? [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]] : [[0, 0, 1, 1]];
1672
1836
  const expected = passes.reduce((sum, [x, y, dx, dy]) => {
1673
1837
  const w = Math.max(0, Math.ceil((width - x) / dx)), h = Math.max(0, Math.ceil((height - y) / dy));
1674
- return sum + (w && h ? h * (1 + Math.ceil(w * channels * depth / 8)) : 0);
1838
+ return sum + (w && h ? h * (1 + Math.ceil(w * channels * depth2 / 8)) : 0);
1675
1839
  }, 0);
1676
1840
  let expanded = 0, data = false, dataEnded = false, ended = false;
1677
1841
  const inflater = new Unzlib((chunk) => {
@@ -1679,33 +1843,33 @@ function inspectPng(bytes, strict = true) {
1679
1843
  if (expanded > expected) fail("Image PNG expands beyond its declared dimensions.");
1680
1844
  });
1681
1845
  for (let at = 8; at + 12 <= bytes.length; ) {
1682
- const length = view.getUint32(at), type = name(at), end = at + length + 12;
1683
- if (end > bytes.length) fail("Image PNG chunk exceeds the encoded bytes.");
1846
+ const length = view.getUint32(at), type = name(at), end2 = at + length + 12;
1847
+ if (end2 > bytes.length) fail("Image PNG chunk exceeds the encoded bytes.");
1684
1848
  if (type === "IHDR" && at !== 8) fail("Image PNG has more than one IHDR chunk.");
1685
1849
  if (strict && ["iCCP", "acTL", "fcTL", "fdAT"].includes(type)) fail("Image assets do not support compressed color profiles or animated PNGs.");
1686
1850
  if (type === "iCCP") {
1687
1851
  let start = at + 8;
1688
- while (start < end - 4 && bytes[start] !== 0) start++;
1689
- if (start + 2 >= end - 4 || bytes[start + 1] !== 0) fail("Image PNG color profile is invalid.");
1852
+ while (start < end2 - 4 && bytes[start] !== 0) start++;
1853
+ if (start + 2 >= end2 - 4 || bytes[start + 1] !== 0) fail("Image PNG color profile is invalid.");
1690
1854
  let profileSize = 0;
1691
1855
  const profile = new Unzlib((chunk) => {
1692
1856
  profileSize += chunk.length;
1693
1857
  if (profileSize > MAX_BYTES) fail("Image PNG color profile exceeds the decoded byte limit.");
1694
1858
  });
1695
- for (let part = start + 2; part < end - 4; part += 1024) profile.push(bytes.subarray(part, Math.min(part + 1024, end - 4)), false);
1859
+ for (let part = start + 2; part < end2 - 4; part += 1024) profile.push(bytes.subarray(part, Math.min(part + 1024, end2 - 4)), false);
1696
1860
  profile.push(new Uint8Array(0), true);
1697
1861
  }
1698
1862
  if (type === "IDAT") {
1699
1863
  if (dataEnded) fail("Image PNG data chunks must be consecutive.");
1700
1864
  data = true;
1701
- for (let part = at + 8; part < end - 4; part += 1024) inflater.push(bytes.subarray(part, Math.min(part + 1024, end - 4)), false);
1865
+ for (let part = at + 8; part < end2 - 4; part += 1024) inflater.push(bytes.subarray(part, Math.min(part + 1024, end2 - 4)), false);
1702
1866
  } else if (data) dataEnded = true;
1703
1867
  if (type === "IEND") {
1704
- if (length || end !== bytes.length) fail("Image PNG has an invalid end chunk.");
1868
+ if (length || end2 !== bytes.length) fail("Image PNG has an invalid end chunk.");
1705
1869
  ended = true;
1706
1870
  break;
1707
1871
  }
1708
- at = end;
1872
+ at = end2;
1709
1873
  }
1710
1874
  if (!data || !ended) fail("Image PNG is missing its data or end chunk.");
1711
1875
  inflater.push(new Uint8Array(0), true);
@@ -1785,22 +1949,22 @@ function jpegOrientation(bytes) {
1785
1949
  while (bytes[at] === 255) at++;
1786
1950
  const marker = bytes[at++];
1787
1951
  if (marker === 218 || marker === 217 || at + 2 > bytes.length) break;
1788
- const length = view.getUint16(at), start = at + 2, end = at + length;
1789
- if (length < 2 || end > bytes.length) break;
1790
- if (marker === 225 && end - start >= 14 && String.fromCharCode(...bytes.subarray(start, start + 6)) === "Exif\0\0") {
1952
+ const length = view.getUint16(at), start = at + 2, end2 = at + length;
1953
+ if (length < 2 || end2 > bytes.length) break;
1954
+ if (marker === 225 && end2 - start >= 14 && String.fromCharCode(...bytes.subarray(start, start + 6)) === "Exif\0\0") {
1791
1955
  const tiff = start + 6, order = view.getUint16(tiff), little = order === 18761;
1792
1956
  if (![18761, 19789].includes(order) || view.getUint16(tiff + 2, little) !== 42) return 1;
1793
1957
  const ifd = tiff + view.getUint32(tiff + 4, little);
1794
- if (ifd < tiff + 8 || ifd + 2 > end) return 1;
1958
+ if (ifd < tiff + 8 || ifd + 2 > end2) return 1;
1795
1959
  const count = view.getUint16(ifd, little);
1796
- for (let entry = ifd + 2; entry + 12 <= end && entry < ifd + 2 + count * 12; entry += 12) {
1960
+ for (let entry = ifd + 2; entry + 12 <= end2 && entry < ifd + 2 + count * 12; entry += 12) {
1797
1961
  if (view.getUint16(entry, little) === 274 && view.getUint16(entry + 2, little) === 3 && view.getUint32(entry + 4, little) === 1) {
1798
1962
  const orientation = view.getUint16(entry + 8, little);
1799
1963
  return orientation >= 1 && orientation <= 8 ? orientation : 1;
1800
1964
  }
1801
1965
  }
1802
1966
  }
1803
- at = end;
1967
+ at = end2;
1804
1968
  }
1805
1969
  return 1;
1806
1970
  }
@@ -1955,10 +2119,10 @@ function legacyImageHeader(bytes) {
1955
2119
  return { width, height, mediaType, visible };
1956
2120
  }
1957
2121
  function pngVisibility(png) {
1958
- const { width, height, channels, depth, data, palette, transparency } = png;
2122
+ const { width, height, channels, depth: depth2, data, palette, transparency } = png;
1959
2123
  if (channels !== 2 && channels !== 4 && !palette && !transparency) return true;
1960
2124
  const mask = new Uint8Array(Math.ceil(width * height / 8));
1961
- const sample = (x, y, channel = 0) => depth >= 8 ? data[(y * width + x) * channels + channel] : data[y * Math.ceil(width * depth / 8) + (x * depth >> 3)] >> 8 - depth - x * depth % 8 & (1 << depth) - 1;
2125
+ const sample = (x, y, channel = 0) => depth2 >= 8 ? data[(y * width + x) * channels + channel] : data[y * Math.ceil(width * depth2 / 8) + (x * depth2 >> 3)] >> 8 - depth2 - x * depth2 % 8 & (1 << depth2) - 1;
1962
2126
  let count = 0;
1963
2127
  for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
1964
2128
  let visible;
@@ -1999,8 +2163,8 @@ function imageHasVisiblePixels(asset, crop) {
1999
2163
  return false;
2000
2164
  }
2001
2165
  function validateGifData(data, minimum, pixels) {
2002
- const clear = 1 << minimum, end = clear + 1, lengths = new Uint16Array(4096);
2003
- let bits = minimum + 1, next = end + 1, previous = 0, offset = 0, written = 0;
2166
+ const clear = 1 << minimum, end2 = clear + 1, lengths = new Uint16Array(4096);
2167
+ let bits = minimum + 1, next = end2 + 1, previous = 0, offset = 0, written = 0;
2004
2168
  for (; ; ) {
2005
2169
  if (offset + bits > data.length * 8) fail("Image GIF compressed data is truncated.");
2006
2170
  let code = 0;
@@ -2008,11 +2172,11 @@ function validateGifData(data, minimum, pixels) {
2008
2172
  offset += bits;
2009
2173
  if (code === clear) {
2010
2174
  bits = minimum + 1;
2011
- next = end + 1;
2175
+ next = end2 + 1;
2012
2176
  previous = 0;
2013
2177
  continue;
2014
2178
  }
2015
- if (code === end) {
2179
+ if (code === end2) {
2016
2180
  if (written !== pixels) fail("Image GIF decoded length does not match its frame dimensions.");
2017
2181
  return;
2018
2182
  }
@@ -2067,6 +2231,144 @@ function imageFromAsset(asset, options = {}) {
2067
2231
  return node;
2068
2232
  }
2069
2233
 
2234
+ // src/stage/light.ts
2235
+ var SAME_TIME = 1e-6;
2236
+ var sameTime = (a, b) => Math.abs(a - b) < SAME_TIME;
2237
+ var seconds = (time) => `${Math.round(time * 1e3) / 1e3} s`;
2238
+ function inside(node, outer) {
2239
+ for (let up = node.parent; up; up = up.parent) if (up === outer) return true;
2240
+ return false;
2241
+ }
2242
+ function drawnDim(node) {
2243
+ let least = 1;
2244
+ for (let up = node; up; up = up.parent) least = Math.min(least, up.get("dim"));
2245
+ return least;
2246
+ }
2247
+ function drawnDimAt(node, time) {
2248
+ const saved = clock.now;
2249
+ clock.now = time;
2250
+ try {
2251
+ return drawnDim(node);
2252
+ } finally {
2253
+ clock.now = saved;
2254
+ }
2255
+ }
2256
+ function visibleAt(node, time) {
2257
+ const saved = clock.now;
2258
+ clock.now = time;
2259
+ try {
2260
+ for (let up = node; up; up = up.parent) if (!up.get("visible")) return false;
2261
+ return true;
2262
+ } finally {
2263
+ clock.now = saved;
2264
+ }
2265
+ }
2266
+ function entersAt(stage, node, time) {
2267
+ if (!visibleAt(node, time + SAME_TIME)) return false;
2268
+ if (!visibleAt(node, time - SAME_TIME)) return true;
2269
+ for (let up = node; up; up = up.parent) {
2270
+ const arrival = stage.arrivals.get(up);
2271
+ if (arrival !== void 0 && sameTime(arrival, time)) return true;
2272
+ }
2273
+ return false;
2274
+ }
2275
+ function showsAt(stage, node, start) {
2276
+ if (!visibleAt(node, start + SAME_TIME) || entersAt(stage, node, start)) return false;
2277
+ for (let up = node; up; up = up.parent) if (up.get("opacity") <= 0) return false;
2278
+ return true;
2279
+ }
2280
+ function depth(light) {
2281
+ let count = 0;
2282
+ for (let up = light.within; up; up = up.parent) count++;
2283
+ return count;
2284
+ }
2285
+ function addLight(stage, light) {
2286
+ if (stage.lights.some((other) => other.within === light.within && sameTime(other.start, light.start))) {
2287
+ const where = light.within ? "in the same node" : "on the stage";
2288
+ throw new Error(`spotlight: two lights start at ${seconds(light.start)} ${where}, and only one can decide what is dim. Give one light all the targets, or start one of them later`);
2289
+ }
2290
+ stage.lights.push(light);
2291
+ }
2292
+ function verify(light, targets, stage, dimmed) {
2293
+ const at = seconds(light.start);
2294
+ targets.forEach((target, index) => {
2295
+ const onStage = inside(target, stage.root);
2296
+ const shows = () => {
2297
+ if (visibleAt(target, light.start)) return true;
2298
+ for (let up = target; up; up = up.parent) {
2299
+ if (entersAt(stage, up, light.start)) return true;
2300
+ if (stage.morphs.some((morph2) => sameTime(morph2.start, light.start) && morph2.from.includes(up))) return true;
2301
+ }
2302
+ return false;
2303
+ };
2304
+ if (onStage && shows()) return;
2305
+ const which = targets.length > 1 ? `target ${index + 1} of ${targets.length}` : "the target";
2306
+ const state = onStage ? "does not show at that time: it is hidden, or it comes to the stage later" : "is not on the stage";
2307
+ throw new Error(`spotlight: ${which} of the light at ${at} ${state}. So the light would show nothing. Show the node before the light, or bring it at the time that the light starts. For a morph that starts then, light the node that the morph starts from`);
2308
+ });
2309
+ for (let up = light.within; up; up = up.parent) {
2310
+ if (dimmed.has(up)) throw new Error(`spotlight: the node for within is dim at ${at}, because another light is on something else then. So the light in it would show nothing. Make that node a target of the other light, or turn the other light off first`);
2311
+ }
2312
+ }
2313
+ function verifyMorphs(stage, lights) {
2314
+ const dimAt = (nodes, time) => nodes.some((node) => drawnDimAt(node, time) < 1);
2315
+ for (const morph2 of stage.morphs) {
2316
+ const time = dimAt(morph2.from, morph2.start) ? morph2.start : dimAt([...morph2.to, ...morph2.ghosts], morph2.end) ? morph2.end : null;
2317
+ if (time === null) continue;
2318
+ const light = [...lights].reverse().find((other) => other.targets !== null && other.start <= time);
2319
+ throw new Error(`spotlight: the light at ${seconds(light?.start ?? time)} dims a node while it morphs, from ${seconds(morph2.start)} to ${seconds(morph2.end)}. A dim morph would jump in brightness. Make the node that the morph starts from a target or a keep of that light, or turn the light off before the morph`);
2320
+ }
2321
+ }
2322
+ function restOf(light, targets, scope, stage) {
2323
+ const labels = targets.flatMap((target) => {
2324
+ const found = [];
2325
+ for (let up = target.parent; up; up = up.parent) found.push(...up.labelsOf(target));
2326
+ return found;
2327
+ });
2328
+ const bright = /* @__PURE__ */ new Set([...targets, ...labels, ...light.keep, ...scope.all().filter((node) => node.get("fixed"))]);
2329
+ const holders = /* @__PURE__ */ new Set();
2330
+ for (const node of bright) for (let up = node.parent; up; up = up.parent) holders.add(up);
2331
+ const rest = /* @__PURE__ */ new Set();
2332
+ const collect = (parent) => {
2333
+ for (const child of parent.children) {
2334
+ if (bright.has(child) || stage.marks.has(child)) continue;
2335
+ if (holders.has(child)) collect(child);
2336
+ else if (showsAt(stage, child, light.start)) rest.add(child);
2337
+ }
2338
+ };
2339
+ collect(scope);
2340
+ return rest;
2341
+ }
2342
+ function settleLights(stage) {
2343
+ if (stage.lights.length === 0) return;
2344
+ const lights = [...stage.lights].sort((a, b) => sameTime(a.start, b.start) ? depth(a) - depth(b) : a.start - b.start);
2345
+ const dimmed = /* @__PURE__ */ new Set();
2346
+ const saved = clock.now;
2347
+ try {
2348
+ for (const light of lights) {
2349
+ clock.now = light.start;
2350
+ const scope = light.within ?? stage.root;
2351
+ if (light.targets) verify(light, light.targets, stage, dimmed);
2352
+ const rest = light.targets ? restOf(light, light.targets, scope, stage) : /* @__PURE__ */ new Set();
2353
+ const inRest = (node) => {
2354
+ for (let up = node; up && up !== scope; up = up.parent) if (rest.has(up)) return true;
2355
+ return false;
2356
+ };
2357
+ const before = light.within ? [...dimmed].filter((node) => inside(node, scope)) : [...dimmed];
2358
+ for (const node of /* @__PURE__ */ new Set([...before, ...rest])) {
2359
+ const to2 = inRest(node) ? light.dim : 1;
2360
+ const from = drawnDim(node);
2361
+ node.track("dim").add({ t0: light.start, t1: light.end, ease: light.ease, to: to2, at: (alpha) => from + (to2 - from) * alpha });
2362
+ if (to2 === 1) dimmed.delete(node);
2363
+ else dimmed.add(node);
2364
+ }
2365
+ }
2366
+ verifyMorphs(stage, lights);
2367
+ } finally {
2368
+ clock.now = saved;
2369
+ }
2370
+ }
2371
+
2070
2372
  // src/stage/display.ts
2071
2373
  var clockNow = () => clock.now;
2072
2374
  var ALONG_PIECE_LENGTH = 14;
@@ -2092,11 +2394,11 @@ function toWorld(node, path, m) {
2092
2394
  worldCache.set(node, { path, matrix: m, world });
2093
2395
  return world;
2094
2396
  }
2095
- function emit(node, path, m, alpha, ops) {
2397
+ function emit(node, path, m, alpha, blend, ops) {
2096
2398
  const fill = node.get("fill");
2097
- const stroke = node.get("stroke");
2399
+ const stroke2 = node.get("stroke");
2098
2400
  const fillAlpha = fill ? alpha * node.get("fillOpacity") : 0;
2099
- const strokeAlpha = stroke ? alpha * node.get("strokeOpacity") : 0;
2401
+ const strokeAlpha = stroke2 ? alpha * node.get("strokeOpacity") : 0;
2100
2402
  const glow = node.get("glow");
2101
2403
  if (fillAlpha <= 2e-3 && strokeAlpha <= 2e-3 && glow <= 0) return;
2102
2404
  const world = toWorld(node, path, m);
@@ -2112,7 +2414,7 @@ function emit(node, path, m, alpha, ops) {
2112
2414
  strokePath,
2113
2415
  fill: fillAlpha > 2e-3 ? worldPaint(fill, m) : null,
2114
2416
  fillAlpha,
2115
- stroke: strokeAlpha > 2e-3 ? worldPaint(stroke, m) : null,
2417
+ stroke: strokeAlpha > 2e-3 ? worldPaint(stroke2, m) : null,
2116
2418
  strokeAlpha,
2117
2419
  strokeWidth: node.get("strokeWidth") * scale,
2118
2420
  cap: node.get("cap"),
@@ -2121,7 +2423,7 @@ function emit(node, path, m, alpha, ops) {
2121
2423
  dashOffset: node.get("dashOffset") * scale,
2122
2424
  glow: glow * scale,
2123
2425
  glowColor: node.get("glowColor"),
2124
- blend: node.get("blend"),
2426
+ blend,
2125
2427
  node
2126
2428
  };
2127
2429
  if (op.stroke && isGradient(op.stroke) && op.stroke.type === "along") splitAlong(op, op.stroke, ops);
@@ -2134,37 +2436,62 @@ function splitAlong(op, paint, ops) {
2134
2436
  const full = pathLength(op.path);
2135
2437
  if (length === 0) return;
2136
2438
  const fraction = full > 0 ? Math.min(1, length / full) : 1;
2137
- const pieces = Math.min(MAX_ALONG_PIECES, Math.max(2, Math.ceil(length / ALONG_PIECE_LENGTH)));
2138
- const overlap = 0.6 / pieces;
2139
- for (let i = 0; i < pieces; i++) {
2140
- const from = i / pieces, to2 = Math.min(1, (i + 1) / pieces + overlap);
2439
+ const pieces2 = Math.min(MAX_ALONG_PIECES, Math.max(2, Math.ceil(length / ALONG_PIECE_LENGTH)));
2440
+ const overlap = 0.6 / pieces2;
2441
+ for (let i = 0; i < pieces2; i++) {
2442
+ const from = i / pieces2, to2 = Math.min(1, (i + 1) / pieces2 + overlap);
2141
2443
  const piece = trimPath(op.strokePath, from, to2);
2142
2444
  if (piece.length === 0) continue;
2143
2445
  ops.push({
2144
2446
  ...glowless,
2145
2447
  strokePath: piece,
2146
2448
  path: piece,
2147
- stroke: sampleStops(paint.stops, (i + 0.5) / pieces * fraction),
2148
- cap: i === 0 || i === pieces - 1 ? op.cap : "butt"
2449
+ stroke: sampleStops(paint.stops, (i + 0.5) / pieces2 * fraction),
2450
+ cap: i === 0 || i === pieces2 - 1 ? op.cap : "butt"
2149
2451
  });
2150
2452
  }
2151
2453
  }
2152
- function walk(node, parent, screen, alpha, ops) {
2454
+ function dimOps(ops, first, dim, backdrop) {
2455
+ for (let i = first; i < ops.length; i++) {
2456
+ const op = ops[i];
2457
+ ops[i] = op.kind === "image" ? { ...op, dim, backdrop } : {
2458
+ ...op,
2459
+ fill: op.fill && dimPaint(op.fill, dim, backdrop),
2460
+ stroke: op.stroke && dimPaint(op.stroke, dim, backdrop),
2461
+ // A glow with no color of its own takes the dim color of the stroke or the fill.
2462
+ glowColor: op.glowColor && dimPaint(op.glowColor, dim, backdrop)
2463
+ };
2464
+ }
2465
+ }
2466
+ function markDim(node, marks) {
2467
+ const target = marks.get(node);
2468
+ return target ? Math.min(drawnDim(target), markDim(target, marks)) : 1;
2469
+ }
2470
+ function walk(node, parent, alpha, dim, inheritedBlend, pass) {
2153
2471
  if (!node.get("visible")) return;
2154
2472
  const opacity = node.get("opacity") * alpha;
2155
2473
  if (opacity <= 2e-3) return;
2474
+ const { screen, ops, marks } = pass;
2475
+ const least = Math.min(node.get("dim"), dim, marks ? markDim(node, marks) : 1);
2476
+ const ownBlend = node.get("blend");
2477
+ const blend = ownBlend !== "normal" ? ownBlend : inheritedBlend;
2156
2478
  const base = node.get("fixed") ? screen : parent;
2157
2479
  const m = mul(base, node.localMatrix());
2480
+ const first = ops.length;
2158
2481
  const path = node.get("path");
2159
- if (path && path.length > 0) emit(node, path, m, opacity, ops);
2482
+ if (path && path.length > 0) emit(node, path, m, opacity, blend, ops);
2160
2483
  const image = node.get("image");
2161
- if (image) ops.push({ kind: "image", image, matrix: m, alpha: opacity, node });
2484
+ if (image) ops.push({ kind: "image", image, matrix: m, alpha: opacity, blend, node });
2162
2485
  if (node.rawOps) node.rawOps(m, opacity, ops);
2486
+ if (least < 1) dimOps(ops, first, least, pass.backdrop);
2163
2487
  if (node.draw) {
2164
2488
  const built = node.draw(clockNow());
2165
2489
  if (built) {
2166
2490
  const list2 = Array.isArray(built) ? built : [built];
2167
- for (const child of list2) walk(child, m, screen, opacity, ops);
2491
+ for (const child of list2) {
2492
+ child.drawer = node;
2493
+ walk(child, m, opacity, least, blend, pass);
2494
+ }
2168
2495
  }
2169
2496
  }
2170
2497
  const children = node.children;
@@ -2177,13 +2504,14 @@ function walk(node, parent, screen, alpha, ops) {
2177
2504
  }
2178
2505
  }
2179
2506
  const ordered = sorted ? children.map((child, index) => ({ child, index, z: child.get("z") })).sort((a, b) => a.z - b.z || a.index - b.index).map((entry) => entry.child) : children;
2180
- for (const child of ordered) walk(child, m, screen, opacity, ops);
2507
+ for (const child of ordered) walk(child, m, opacity, least, blend, pass);
2181
2508
  }
2182
- function buildOps(root, camera, width, height) {
2509
+ function buildOps(root, camera, width, height, backdrop = [0, 0, 0, 1], marks = null) {
2510
+ if (typeof root?.localMatrix !== "function") throw new Error("buildOps: the root is not a node. Give one node, such as the root of a stage, or a group of the nodes: group(block)");
2183
2511
  const screen = [1, 0, 0, 1, width / 2, height / 2];
2184
2512
  const view = mul(screen, compose(0, 0, -camera.rotation, camera.zoom, camera.zoom, camera.x, camera.y));
2185
2513
  const ops = [];
2186
- walk(root, view, screen, 1, ops);
2514
+ walk(root, view, 1, 1, "normal", { screen, backdrop, marks, ops });
2187
2515
  return ops;
2188
2516
  }
2189
2517
  var GLOW_PASSES = 7;
@@ -2213,6 +2541,9 @@ function pathData(path) {
2213
2541
  function fmt2(value) {
2214
2542
  return String(Math.round(value * 1e3) / 1e3);
2215
2543
  }
2544
+ function exact(value) {
2545
+ return String(Math.round(value * 1e6) / 1e6);
2546
+ }
2216
2547
  function gradientDef(id, paint) {
2217
2548
  const stops = paint.stops.map(([at, color]) => `<stop offset="${fmt2(at)}" stop-color="${css([color[0], color[1], color[2], 1])}"${color[3] < 1 ? ` stop-opacity="${fmt2(color[3])}"` : ""}/>`).join("");
2218
2549
  if (paint.type === "linear") {
@@ -2236,7 +2567,7 @@ function frameToSvg(frame, options = {}) {
2236
2567
  const w = frame.width, h = frame.height;
2237
2568
  const defs = [];
2238
2569
  const body = [];
2239
- let gradientCount = 0;
2570
+ let gradientCount = 0, dimCount = 0;
2240
2571
  const paintAttr = (paint, attr, alpha) => {
2241
2572
  if (isGradient(paint)) {
2242
2573
  const id = `g${gradientCount++}`;
@@ -2255,7 +2586,15 @@ function frameToSvg(frame, options = {}) {
2255
2586
  if (crop && !image.asset) throw new ImageAssetError("Cropped image SVG needs a prepared image asset.");
2256
2587
  const picture = `<image href="${escapeAttr(image.src)}" width="${crop ? image.asset.width : image.width}" height="${crop ? image.asset.height : image.height}" preserveAspectRatio="none"/>`;
2257
2588
  const content = crop ? `<svg width="${fmt2(image.width)}" height="${fmt2(image.height)}" viewBox="${[crop.x, crop.y, crop.width, crop.height].map(fmt2).join(" ")}" preserveAspectRatio="none" overflow="hidden">${picture}</svg>` : picture;
2258
- body.push(`<g transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha < 1 ? ` opacity="${fmt2(op.alpha)}"` : ""}>${content}</g>`);
2589
+ let filter = "";
2590
+ if (op.dim !== void 0 && op.dim < 1 && op.backdrop) {
2591
+ const id = `d${dimCount++}`, keep = exact(op.dim);
2592
+ const [r, g, b] = [0, 1, 2].map((i) => exact((1 - op.dim) * op.backdrop[i] / 255));
2593
+ defs.push(`<filter id="${id}" x="0" y="0" width="1" height="1" color-interpolation-filters="sRGB"><feColorMatrix type="matrix" values="${keep} 0 0 0 ${r} 0 ${keep} 0 0 ${g} 0 0 ${keep} 0 ${b} 0 0 0 1 0"/></filter>`);
2594
+ filter = ` filter="url(#${id})"`;
2595
+ }
2596
+ const imageStyle = op.blend && op.blend !== "normal" ? ` style="mix-blend-mode:${op.blend}"` : "";
2597
+ body.push(`<g transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha < 1 ? ` opacity="${fmt2(op.alpha)}"` : ""}${filter}${imageStyle}>${content}</g>`);
2259
2598
  continue;
2260
2599
  }
2261
2600
  const style = op.blend !== "normal" ? ` style="mix-blend-mode:${op.blend}"` : "";
@@ -2310,6 +2649,24 @@ var BLEND = {
2310
2649
  multiply: "multiply",
2311
2650
  overlay: "overlay"
2312
2651
  };
2652
+ var dimCopies = /* @__PURE__ */ new WeakMap();
2653
+ function dimCopy(source, image, dim, backdrop) {
2654
+ const crop = image.crop;
2655
+ const width = Math.max(1, Math.ceil(crop?.width ?? image.asset?.width ?? image.width)), height = Math.max(1, Math.ceil(crop?.height ?? image.asset?.height ?? image.height));
2656
+ const key = [dim, backdrop[0], backdrop[1], backdrop[2], crop?.x, crop?.y, width, height].join(" ");
2657
+ const kept = dimCopies.get(source);
2658
+ if (kept?.key === key) return kept.copy;
2659
+ const copy = typeof OffscreenCanvas === "undefined" ? Object.assign(document.createElement("canvas"), { width, height }) : new OffscreenCanvas(width, height);
2660
+ const pen = copy.getContext("2d");
2661
+ if (crop) pen.drawImage(source, crop.x, crop.y, crop.width, crop.height, 0, 0, width, height);
2662
+ else pen.drawImage(source, 0, 0, width, height);
2663
+ pen.globalCompositeOperation = "source-atop";
2664
+ pen.globalAlpha = 1 - dim;
2665
+ pen.fillStyle = css([backdrop[0], backdrop[1], backdrop[2], 1]);
2666
+ pen.fillRect(0, 0, width, height);
2667
+ dimCopies.set(source, { key, copy });
2668
+ return copy;
2669
+ }
2313
2670
  function paintFrame(ctx, frame, scale = 1, images) {
2314
2671
  ctx.setTransform(1, 0, 0, 1, 0, 0);
2315
2672
  ctx.globalAlpha = 1;
@@ -2328,9 +2685,10 @@ function paintFrame(ctx, frame, scale = 1, images) {
2328
2685
  ctx.save();
2329
2686
  ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
2330
2687
  ctx.globalAlpha = op.alpha;
2331
- ctx.globalCompositeOperation = "source-over";
2688
+ ctx.globalCompositeOperation = BLEND[op.blend ?? "normal"];
2332
2689
  const crop = op.image.crop;
2333
- if (crop) ctx.drawImage(source, crop.x, crop.y, crop.width, crop.height, 0, 0, op.image.width, op.image.height);
2690
+ if (op.dim !== void 0 && op.dim < 1 && op.backdrop) ctx.drawImage(dimCopy(source, op.image, op.dim, op.backdrop), 0, 0, op.image.width, op.image.height);
2691
+ else if (crop) ctx.drawImage(source, crop.x, crop.y, crop.width, crop.height, 0, 0, op.image.width, op.image.height);
2334
2692
  else ctx.drawImage(source, 0, 0, op.image.width, op.image.height);
2335
2693
  ctx.restore();
2336
2694
  continue;
@@ -2500,9 +2858,1352 @@ function cubicBezier(x1, y1, x2, y2) {
2500
2858
  };
2501
2859
  }
2502
2860
 
2861
+ // src/stage/assets.ts
2862
+ var assetBase = null;
2863
+ function setAssetBase(url) {
2864
+ assetBase = url;
2865
+ }
2866
+ function isNodeRuntime() {
2867
+ return typeof process !== "undefined" && process.release?.name === "node";
2868
+ }
2869
+ function filePathToUrl(filePath) {
2870
+ const normalized = filePath.replace(/\\/g, "/");
2871
+ const encoded = encodeURI(normalized).replace(/#/g, "%23").replace(/\?/g, "%3F");
2872
+ return encoded.startsWith("/") ? `file://${encoded}` : `file:///${encoded}`;
2873
+ }
2874
+ function moduleUrl() {
2875
+ const url = import.meta.url;
2876
+ if (url) return url;
2877
+ return typeof __filename !== "undefined" ? filePathToUrl(__filename) : "file:///";
2878
+ }
2879
+ async function nodeRead(relative) {
2880
+ const fsName = "node:fs/promises", pathName = "node:path", urlName = "node:url";
2881
+ const [fs, path, url] = await Promise.all([import(fsName), import(pathName), import(urlName)]);
2882
+ const currentFile = import.meta.url ? url.fileURLToPath(import.meta.url) : typeof __filename !== "undefined" ? url.fileURLToPath(url.pathToFileURL(__filename).href) : url.fileURLToPath(moduleUrl());
2883
+ let directory = path.dirname(currentFile);
2884
+ for (let depth2 = 0; depth2 < 6; depth2++) {
2885
+ const candidate = path.join(directory, "assets", relative);
2886
+ try {
2887
+ const bytes = await fs.readFile(candidate);
2888
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
2889
+ } catch (error) {
2890
+ if (error.code !== "ENOENT") throw error;
2891
+ }
2892
+ directory = path.dirname(directory);
2893
+ }
2894
+ throw new Error(`Bundled asset not found: assets/${relative}`);
2895
+ }
2896
+ async function loadBinaryAsset(relative) {
2897
+ if (isNodeRuntime() && (assetBase === null || assetBase.startsWith("file:"))) return nodeRead(relative);
2898
+ const base = assetBase ?? new URL("./assets/", moduleUrl()).href;
2899
+ const response = await fetch(new URL(relative, base));
2900
+ const type = response.headers.get("content-type") ?? "";
2901
+ if (!response.ok || type.includes("text/html")) {
2902
+ throw new Error(`Could not load ${relative} from ${response.url} (HTTP ${response.status}, ${type || "no content type"}). Call setAssetBase() with the folder that holds fonts/.`);
2903
+ }
2904
+ return response.arrayBuffer();
2905
+ }
2906
+
2907
+ // src/stage/font-types.ts
2908
+ function curveFree(contours) {
2909
+ return { contours: contours.filter((contour) => contour.length >= 8) };
2910
+ }
2911
+
2912
+ // src/stage/enclose.ts
2913
+ var CURVE_PIECES = 6;
2914
+ function pieces(r, o, visit) {
2915
+ const p = r.p;
2916
+ const x0 = p[o], y0 = p[o + 1], x3 = p[o + 6], y3 = p[o + 7];
2917
+ if (r.straight) return visit(x0, y0, x3, y3);
2918
+ const x1 = p[o + 2], y1 = p[o + 3], x2 = p[o + 4], y2 = p[o + 5];
2919
+ let lastX = x0, lastY = y0;
2920
+ for (let k = 1; k <= CURVE_PIECES; k++) {
2921
+ const t = k / CURVE_PIECES, u = 1 - t;
2922
+ const a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t;
2923
+ const x = a * x0 + b * x1 + c * x2 + d * x3;
2924
+ const y = a * y0 + b * y1 + c * y2 + d * y3;
2925
+ if (visit(lastX, lastY, x, y)) return true;
2926
+ lastX = x;
2927
+ lastY = y;
2928
+ }
2929
+ return false;
2930
+ }
2931
+ function encloses(path, px2, py) {
2932
+ let inside2 = false;
2933
+ const edge = (x0, y0, x1, y1) => {
2934
+ if (y0 > py !== y1 > py && px2 < x0 + (x1 - x0) * (py - y0) / (y1 - y0)) inside2 = !inside2;
2935
+ return false;
2936
+ };
2937
+ for (const r of path) {
2938
+ const p = r.p;
2939
+ if (p.length < 8) continue;
2940
+ for (let o = 0; o + 7 < p.length; o += 6) pieces(r, o, edge);
2941
+ edge(p[p.length - 2], p[p.length - 1], p[0], p[1]);
2942
+ }
2943
+ return inside2;
2944
+ }
2945
+
2946
+ // src/stage/text.ts
2947
+ var TextNode = class extends Node {
2948
+ chars = [];
2949
+ source = "";
2950
+ /** The font of the text: the font that it names, or the font of the film. `text()` records it when it makes the node. */
2951
+ font = LIBRARY_FONT;
2952
+ /** The size of the text, in the pixels of the node. `text()` records it. */
2953
+ size = 0;
2954
+ /** The y of the base line of the first line, in the coordinates of the node. A row of the layout puts texts of two sizes on one base line with it. */
2955
+ baseline = 0;
2956
+ /**
2957
+ * The top and the bottom of the letters of the font at the size of the text, in the coordinates of the
2958
+ * node: the highest letter over the first base line, and the lowest one under the last. It is the same for
2959
+ * every text of one font and one size, whatever its letters. The layout measures the room over and under
2960
+ * a text from it, so a named gap is even from row to row.
2961
+ */
2962
+ letters = [0, 0];
2963
+ /** Glyph nodes whose characters match, such as every "x". */
2964
+ find(fragment) {
2965
+ const out = [];
2966
+ const keys = this.chars.map((glyph) => glyph.data["key"]).join("");
2967
+ const needle = fragment.replace(/\s/g, "");
2968
+ for (let at = keys.indexOf(needle); at >= 0; at = keys.indexOf(needle, at + 1)) {
2969
+ out.push(...this.chars.slice(at, at + needle.length));
2970
+ }
2971
+ return out;
2972
+ }
2973
+ };
2974
+ function centered(path) {
2975
+ const b = pathBounds(path);
2976
+ if (!b) return { path, x: 0, y: 0 };
2977
+ const x = b.x + b.width / 2, y = b.y + b.height / 2;
2978
+ return { path: transformPath(path, [1, 0, 0, 1, -x, -y]), x, y };
2979
+ }
2980
+ function filmFont() {
2981
+ return clock.font;
2982
+ }
2983
+ var LINE_BOX = 1.2;
2984
+ var letterLines = /* @__PURE__ */ new WeakMap();
2985
+ function linesOf(font) {
2986
+ let lines = letterLines.get(font);
2987
+ if (!lines) {
2988
+ let over2 = 0, under = 0;
2989
+ for (let code = 33; code < 127; code++) {
2990
+ const glyph = font.glyphFor(code);
2991
+ if (glyph === 0) continue;
2992
+ for (const contour of font.outline(glyph)?.contours ?? []) {
2993
+ for (let i = 1; i < contour.length; i += 2) {
2994
+ over2 = Math.max(over2, contour[i]);
2995
+ under = Math.max(under, -contour[i]);
2996
+ }
2997
+ }
2998
+ }
2999
+ letterLines.set(font, lines = [over2 / font.unitsPerEm, under / font.unitsPerEm]);
3000
+ }
3001
+ return lines;
3002
+ }
3003
+ function text(content, options = {}) {
3004
+ const size = options.size ?? 40;
3005
+ const family = options.font ?? clock.font ?? LIBRARY_FONT;
3006
+ const weight = options.weight ?? 400;
3007
+ const italic = options.italic ?? false;
3008
+ const font = fontFor(family, weight, italic);
3009
+ const scale = size / font.unitsPerEm;
3010
+ const tracking = (options.tracking ?? 0) * size;
3011
+ const leading = (options.leading ?? 1.3) * size;
3012
+ const paint = toPaint(options.color ?? "ink");
3013
+ const source = options.uppercase ? content.toUpperCase() : content;
3014
+ const measureWord = (word) => {
3015
+ const glyphs = [];
3016
+ let x = 0, previous = 0, previousFont = null;
3017
+ for (const char of word) {
3018
+ const code = char.codePointAt(0);
3019
+ let owner = font, glyph = font.glyphFor(code);
3020
+ if (glyph === 0) {
3021
+ const found = fallbackGlyph(family, code, weight, italic);
3022
+ if (found) {
3023
+ owner = found.font;
3024
+ glyph = found.glyph;
3025
+ }
3026
+ }
3027
+ const ownerScale = size / owner.unitsPerEm;
3028
+ if (previous && previousFont === owner) x += owner.kern(previous, glyph) * ownerScale;
3029
+ glyphs.push({ font: owner, glyph, x, char });
3030
+ x += owner.advance(glyph) * ownerScale + tracking;
3031
+ previous = glyph;
3032
+ previousFont = owner;
3033
+ }
3034
+ return { glyphs, width: x };
3035
+ };
3036
+ const lines = [];
3037
+ const space = font.advance(font.glyphFor(32)) * scale + tracking;
3038
+ for (const paragraph of source.split("\n")) {
3039
+ let line = [];
3040
+ let width = 0;
3041
+ for (const word of paragraph.split(" ")) {
3042
+ const measured = measureWord(word);
3043
+ const gap = line.length > 0 ? space : 0;
3044
+ if (options.maxWidth !== void 0 && line.length > 0 && width + gap + measured.width > options.maxWidth) {
3045
+ lines.push({ glyphs: line, width });
3046
+ line = [];
3047
+ width = 0;
3048
+ }
3049
+ const offset = width + (line.length > 0 ? space : 0);
3050
+ for (const glyph of measured.glyphs) line.push({ ...glyph, x: glyph.x + offset });
3051
+ width = offset + measured.width;
3052
+ }
3053
+ lines.push({ glyphs: line, width });
3054
+ }
3055
+ const blockWidth = Math.max(0, ...lines.map((line) => line.width));
3056
+ const align = options.align ?? "left";
3057
+ const node = new TextNode();
3058
+ node.source = content;
3059
+ node.font = family;
3060
+ lines.forEach((line, row2) => {
3061
+ const start = align === "left" ? 0 : align === "center" ? (blockWidth - line.width) / 2 : blockWidth - line.width;
3062
+ for (const placed of line.glyphs) {
3063
+ const path = glyphPath(placed.font, placed.glyph, size);
3064
+ if (path.length === 0) continue;
3065
+ const shape = centered(path);
3066
+ const leaf = new Node(shape.path).at(start + placed.x + shape.x, row2 * leading + shape.y);
3067
+ leaf.base.fill = paint;
3068
+ leaf.base.trimEach = true;
3069
+ leaf.data["key"] = placed.char;
3070
+ leaf.data["base"] = -shape.y;
3071
+ if (placed.glyph === 0) leaf.data["missingGlyph"] = true;
3072
+ node.chars.push(leaf);
3073
+ node.children.push(leaf);
3074
+ leaf.parent = node;
3075
+ }
3076
+ });
3077
+ const ascent = font.ascent * scale;
3078
+ const height = (lines.length - 1) * leading;
3079
+ const anchor = options.anchor ?? "center";
3080
+ node.base.px = anchor === "left" ? 0 : anchor === "right" ? blockWidth : blockWidth / 2;
3081
+ node.base.py = height / 2 - ascent * 0.36;
3082
+ node.data["size"] = size;
3083
+ node.size = size;
3084
+ const half = (height + size * LINE_BOX) / 2;
3085
+ node.layoutBox = [0, node.base.py - half, blockWidth, node.base.py + half];
3086
+ const [over2, under] = linesOf(font);
3087
+ node.letters = [-over2 * size, height + under * size];
3088
+ return node;
3089
+ }
3090
+
3091
+ // src/stage/layout.ts
3092
+ var GAP = { none: 0, tight: 12, normal: 24, wide: 48, loose: 72 };
3093
+ var GAP_NAMES = "none, tight, normal, wide or loose";
3094
+ var round = (value) => Math.round(value * 10) / 10;
3095
+ var FIT = 0.5;
3096
+ function kindOf(value) {
3097
+ if (value === void 0) return "undefined";
3098
+ if (value === null) return "null";
3099
+ if (value instanceof Node) return "a node";
3100
+ if (value instanceof Block) return "a block";
3101
+ if (value instanceof Box) return "a region";
3102
+ if (typeof value === "string") return `the string ${JSON.stringify(value.length > 48 ? `${value.slice(0, 48)}...` : value)}`;
3103
+ if (typeof value === "number" || typeof value === "boolean") return `the value ${value}`;
3104
+ if (typeof value === "function") return "a function";
3105
+ if (Array.isArray(value)) return "a list";
3106
+ return "an object that is not a node";
3107
+ }
3108
+ var isPoint = (thing) => Array.isArray(thing) && thing.length === 2 && typeof thing[0] === "number" && typeof thing[1] === "number";
3109
+ var oneOf = (words) => words.length < 2 ? words.join("") : `${words.slice(0, -1).join(", ")} or ${words[words.length - 1]}`;
3110
+ function px(gap, what) {
3111
+ if (typeof gap === "number") {
3112
+ if (!Number.isFinite(gap)) throw new Error(`${what}: a gap is ${GAP_NAMES}, or a number of pixels, and it is ${gap}`);
3113
+ return gap;
3114
+ }
3115
+ if (typeof gap !== "string" || !Object.hasOwn(GAP, gap)) throw new Error(`${what}: no gap ${typeof gap === "string" ? JSON.stringify(gap) : kindOf(gap)}. A gap is ${GAP_NAMES}, or a number of pixels`);
3116
+ return GAP[gap];
3117
+ }
3118
+ function optionsOf(what, options, names, example) {
3119
+ if (options === void 0) return {};
3120
+ if (typeof options !== "object" || options === null || Array.isArray(options) || options instanceof Node || options instanceof Block || options instanceof Box) {
3121
+ const list2 = options instanceof Node || options instanceof Block ? `. The items are one list: ${what}([a, b])` : "";
3122
+ throw new Error(`${what}: the options are an object such as ${example}, and the second argument is ${kindOf(options)}${list2}`);
3123
+ }
3124
+ const unknown = Object.keys(options).find((name) => !names.includes(name));
3125
+ if (unknown !== void 0) throw new Error(`${what} has no option "${unknown}". Its options are: ${names.join(", ")}`);
3126
+ return options;
3127
+ }
3128
+ var Box = class _Box {
3129
+ constructor(left, top, right, bottom) {
3130
+ this.left = left;
3131
+ this.top = top;
3132
+ this.right = right;
3133
+ this.bottom = bottom;
3134
+ if (!(Number.isFinite(left) && Number.isFinite(top) && Number.isFinite(right) && Number.isFinite(bottom))) {
3135
+ throw new Error(`Box: the edges are left ${left}, top ${top}, right ${right} and bottom ${bottom}. Each edge is a finite number of stage pixels. A value that is not a number comes from a division by 0, or from a value that is missing`);
3136
+ }
3137
+ if (right < left || bottom < top) {
3138
+ throw new Error(`Box: the edges are left ${left}, top ${top}, right ${right} and bottom ${bottom}. A box has its right edge at or after its left edge, and its bottom edge at or under its top edge`);
3139
+ }
3140
+ this.cx = (left + right) / 2;
3141
+ this.cy = (top + bottom) / 2;
3142
+ this.width = right - left;
3143
+ this.height = bottom - top;
3144
+ }
3145
+ left;
3146
+ top;
3147
+ right;
3148
+ bottom;
3149
+ /** The middle. */
3150
+ cx;
3151
+ cy;
3152
+ width;
3153
+ height;
3154
+ /** The middle, the middle of an edge, or a corner, as `[x, y]`: `box.point('top right')`. For the end of a line or an arrow. */
3155
+ point(where = "center") {
3156
+ const [h, v] = sides(where, "point");
3157
+ return [h < 0 ? this.left : h > 0 ? this.right : this.cx, v < 0 ? this.top : v > 0 ? this.bottom : this.cy];
3158
+ }
3159
+ /**
3160
+ * Cut into columns, from left to right. Give a count for equal columns, or the share of each one:
3161
+ * `area.columns(2)`, `area.columns([2, 1])`. The gap between two columns is wide by default.
3162
+ */
3163
+ columns(shares, gap = "wide") {
3164
+ return cut(shares, this.left, this.right, px(gap, "columns"), "columns", "wider").map(([from, to2]) => new _Box(from, this.top, to2, this.bottom));
3165
+ }
3166
+ /** Cut into rows, from top to bottom: `area.rows(3)`, `area.rows([3, 1])`. The gap between two rows is wide by default. */
3167
+ rows(shares, gap = "wide") {
3168
+ return cut(shares, this.top, this.bottom, px(gap, "rows"), "rows", "higher").map(([from, to2]) => new _Box(this.left, from, this.right, to2));
3169
+ }
3170
+ /** The region with a margin inside each edge: `panel.inset('normal')`. A second gap is for the top and the bottom. */
3171
+ inset(x, y = x) {
3172
+ return this.margin("inset", px(x, "inset"), px(y, "inset"));
3173
+ }
3174
+ /** The region with a margin outside each edge: `boxOf(queue).grow('tight')`. A second gap is for the top and the bottom. */
3175
+ grow(x, y = x) {
3176
+ return this.margin("grow", -px(x, "grow"), -px(y, "grow"));
3177
+ }
3178
+ margin(what, dx, dy) {
3179
+ if (2 * dx >= this.width && dx > 0 || 2 * dy >= this.height && dy > 0) {
3180
+ throw new Error(`${what}: a margin of ${Math.abs(dx)} by ${Math.abs(dy)} leaves nothing of a region that is ${round(this.width)} wide and ${round(this.height)} high. Use a smaller gap, or a larger region`);
3181
+ }
3182
+ return new _Box(this.left + dx, this.top + dy, this.right - dx, this.bottom - dy);
3183
+ }
3184
+ /**
3185
+ * The part of this region on one side of a thing: `area.beside(lanes, 'under')` is the room under the
3186
+ * lanes. The gap is between the thing and the new region, and it is normal by default. The new region
3187
+ * stays inside this one: a thing that is outside it cuts nothing off.
3188
+ */
3189
+ beside(other, side, gap = "normal") {
3190
+ checkSide(side, "beside");
3191
+ const b = measure2(other, "beside", "the thing"), g = px(gap, "beside");
3192
+ const left = side === "right" ? Math.max(this.left, b.right + g) : this.left, right = side === "left" ? Math.min(this.right, b.left - g) : this.right;
3193
+ const top = side === "under" ? Math.max(this.top, b.bottom + g) : this.top, bottom = side === "above" ? Math.min(this.bottom, b.top - g) : this.bottom;
3194
+ if (right - left <= 0 || bottom - top <= 0) {
3195
+ const where = side === "under" || side === "above" ? side : `at the ${side} of`;
3196
+ const missing = -Math.min(right - left, bottom - top);
3197
+ const smaller = g > missing ? `Use a gap under ${round(g - missing)}, make` : "Make";
3198
+ throw new Error(`beside: the region has no room ${where} ${describe(other)}: with a gap of ${g}, ${round(missing)} pixels are missing. ${smaller} the thing smaller, or move it away from that edge`);
3199
+ }
3200
+ return new _Box(left, top, right, bottom);
3201
+ }
3202
+ };
3203
+ function cut(shares, from, to2, gap, what, larger) {
3204
+ const list2 = typeof shares === "number" ? Array.from({ length: Number.isInteger(shares) && shares > 0 ? shares : 0 }, () => 1) : Array.isArray(shares) ? [...shares] : [];
3205
+ if (list2.length === 0 || !list2.every((share) => Number.isFinite(share) && share > 0)) {
3206
+ throw new Error(`${what}: give a count such as 2, or the share of each part such as [2, 1], and it is ${typeof shares === "number" || Array.isArray(shares) ? JSON.stringify(shares) : kindOf(shares)}`);
3207
+ }
3208
+ const room = to2 - from - gap * (list2.length - 1);
3209
+ if (room <= 0) throw new Error(`${what}: ${list2.length} ${what} with a gap of ${gap} need more than ${round(gap * (list2.length - 1))} pixels, and the region has ${round(to2 - from)}. Use fewer ${what}, a smaller gap, or a ${larger} region`);
3210
+ const total = list2.reduce((sum, share) => sum + share, 0);
3211
+ const out = [];
3212
+ let at = from;
3213
+ for (const share of list2) {
3214
+ const size = room * share / total;
3215
+ out.push([at, at + size]);
3216
+ at += size + gap;
3217
+ }
3218
+ return out;
3219
+ }
3220
+ function sides(where, what) {
3221
+ const words = typeof where === "string" ? where.split(" ") : [];
3222
+ const known = ["center", "left", "right", "top", "bottom"];
3223
+ const twice = words.includes("left") && words.includes("right") || words.includes("top") && words.includes("bottom") || words[0] === words[1];
3224
+ if (words.length === 0 || words.length > 2 || words.some((word) => !known.includes(word)) || twice) {
3225
+ throw new Error(`${what}: no place ${typeof where === "string" ? JSON.stringify(where) : kindOf(where)}. A place is center, an edge such as top, or a corner such as top left`);
3226
+ }
3227
+ return [words.includes("left") ? -1 : words.includes("right") ? 1 : 0, words.includes("top") ? -1 : words.includes("bottom") ? 1 : 0];
3228
+ }
3229
+ function checkSide(side, what) {
3230
+ if (!["left", "right", "above", "under"].includes(side)) throw new Error(`${what}: the side is left, right, above or under, and it is ${typeof side === "string" ? JSON.stringify(side) : kindOf(side)}`);
3231
+ }
3232
+ var MADE = /* @__PURE__ */ new WeakMap();
3233
+ var Block = class {
3234
+ constructor(items, kind = "row") {
3235
+ this.items = items;
3236
+ this.kind = kind;
3237
+ if (!Array.isArray(items)) throw new Error(`Block: the items are a list, and the first argument is ${kindOf(items)}`);
3238
+ items.forEach((item, index) => checkItem("Block", item, `item ${index}`));
3239
+ }
3240
+ items;
3241
+ kind;
3242
+ /** Every node of the block, in order. */
3243
+ get nodes() {
3244
+ return nodesOf(this.items);
3245
+ }
3246
+ /** The measure of the block now. */
3247
+ get box() {
3248
+ return boxOf(this.items);
3249
+ }
3250
+ };
3251
+ function checkItem(what, item, name) {
3252
+ if (item instanceof Node || item instanceof Block) return;
3253
+ if (Array.isArray(item) && !isPoint(item)) {
3254
+ item.forEach((part, index) => {
3255
+ if (part) checkItem(what, part, `${name}[${index}]`);
3256
+ });
3257
+ return;
3258
+ }
3259
+ const hint = typeof item === "string" ? ". Make a node from the words, with `label` of the kit or with `text`" : item instanceof Box || isPoint(item) ? ". A region and a point have no place to change: put a node there with `place` or `beside`" : "";
3260
+ throw new Error(`${what}: ${name} is ${isPoint(item) ? `the point [${item[0]}, ${item[1]}]` : kindOf(item)}. An item is a node, a block that a container returned, or a list of them${hint}`);
3261
+ }
3262
+ function nodesOf(item) {
3263
+ if (item instanceof Node) return [item];
3264
+ if (item instanceof Block) return item.nodes;
3265
+ return item.flatMap((part) => part ? nodesOf(part) : []);
3266
+ }
3267
+ function nodesFor(what, target, name = "the target") {
3268
+ if (target instanceof Node) return [target];
3269
+ if (target instanceof Block) return target.nodes;
3270
+ if (Array.isArray(target) && !isPoint(target)) return target.flatMap((item, index) => nodesFor(what, item, `${name}[${index}]`));
3271
+ throw new Error(`${what}: ${name} is ${isPoint(target) ? `the point [${target[0]}, ${target[1]}]` : kindOf(target)}. Give a node, a block of the layout, or a list of them`);
3272
+ }
3273
+ function oneNode(what, value, name = "the node") {
3274
+ if (value instanceof Node) return value;
3275
+ if (value instanceof Block) throw new Error(`${what}: ${name} is a block of the layout, and here ${what} takes one node. Give one node of the block, such as block.nodes[0], or the block as one group: group(block)`);
3276
+ throw new Error(`${what}: ${name} is ${isPoint(value) ? `the point [${value[0]}, ${value[1]}]` : kindOf(value)}. Give a node`);
3277
+ }
3278
+ function nodeOrPoint(what, value, name) {
3279
+ if (value instanceof Node || isPoint(value) && Number.isFinite(value[0]) && Number.isFinite(value[1])) return value;
3280
+ if (value instanceof Block) throw new Error(`${what}: ${name} is a block of the layout, and here ${what} takes one node or a point. Give one node of the block, such as block.nodes[0], or a point of its box, such as boxOf(block).point('right')`);
3281
+ throw new Error(`${what}: ${name} is ${isPoint(value) ? `the point [${value[0]}, ${value[1]}]` : kindOf(value)}. Give a node, or a point [x, y] of the stage`);
3282
+ }
3283
+ function oneObject(what, value, name, kind, words) {
3284
+ if (value instanceof kind) return value;
3285
+ throw new Error(`${what}: ${name} is ${value instanceof Block ? "a block of the layout" : value instanceof Node ? "a node of another kind" : kindOf(value)}. Give ${words}`);
3286
+ }
3287
+ function distinct(what, item, holder) {
3288
+ const nodes = nodesOf(item), seen = /* @__PURE__ */ new Set();
3289
+ for (const node of nodes) {
3290
+ if (seen.has(node)) throw new Error(`${what}: ${describe(node)} is in ${holder} two times. A node has one place. Give it one time, or give a copy of it: node.clone()`);
3291
+ seen.add(node);
3292
+ }
3293
+ for (const node of nodes) {
3294
+ for (let up = node.parent; up; up = up.parent) {
3295
+ if (seen.has(up)) throw new Error(`${what}: ${describe(node)} is a part of ${describe(up)}, and ${holder} has both. A group moves its parts, so the part would move two times. Give the group, or the part`);
3296
+ }
3297
+ }
3298
+ }
3299
+ function boxOf(thing) {
3300
+ return measure2(thing, "boxOf", "the thing");
3301
+ }
3302
+ function measure2(thing, what, name) {
3303
+ if (thing instanceof Box) return thing;
3304
+ if (thing instanceof Block) return thing.box;
3305
+ if (thing instanceof Node) return nodeBox(thing, what);
3306
+ if (!Array.isArray(thing)) throw new Error(`${what}: ${name} is ${kindOf(thing)}, which has no measure. Give a node, a block, a region, a point [x, y], or a list of them`);
3307
+ if (isPoint(thing)) {
3308
+ if (!(Number.isFinite(thing[0]) && Number.isFinite(thing[1]))) throw new Error(`${what}: ${name} is the point [${thing[0]}, ${thing[1]}], which is not a place. Each number of a point is finite. A value that is not a number comes from a division by 0, or from a value that is missing`);
3309
+ return new Box(thing[0], thing[1], thing[0], thing[1]);
3310
+ }
3311
+ const boxes = thing.filter(Boolean).map((part, index) => measure2(part, what, `${name}[${index}]`));
3312
+ if (boxes.length === 0) throw new Error(`${what}: ${name} is an empty list, which has no measure. Give it at least one node`);
3313
+ return new Box(Math.min(...boxes.map((b) => b.left)), Math.min(...boxes.map((b) => b.top)), Math.max(...boxes.map((b) => b.right)), Math.max(...boxes.map((b) => b.bottom)));
3314
+ }
3315
+ function nodeBox(node, what) {
3316
+ let edges2;
3317
+ const own = node.layoutBox;
3318
+ if (own) {
3319
+ const m = node.worldMatrix();
3320
+ const corners = [apply(m, own[0], own[1]), apply(m, own[2], own[1]), apply(m, own[2], own[3]), apply(m, own[0], own[3])];
3321
+ const xs = corners.map((c) => c[0]), ys = corners.map((c) => c[1]);
3322
+ edges2 = [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
3323
+ } else {
3324
+ const b = everyBounds(node, node.parent ? node.parent.worldMatrix() : IDENTITY) ?? { x: 0, y: 0, width: 0, height: 0 };
3325
+ edges2 = [b.x, b.y, b.x + b.width, b.y + b.height];
3326
+ }
3327
+ if (!edges2.every((edge) => Number.isFinite(edge))) {
3328
+ throw new Error(`${what}: ${describe(node, false)} has a place or a size that is not a number, so it has no measure. Look at the values of its .at(), .shift() and .scale(): one comes from a division by 0, or from a value that is missing`);
3329
+ }
3330
+ return new Box(...edges2);
3331
+ }
3332
+ function everyBounds(node, parent, lines = false) {
3333
+ const m = mul(parent, node.localMatrix());
3334
+ let result = null;
3335
+ const path = node.get("path");
3336
+ if (path) {
3337
+ result = pathBounds(transformPath(path, m));
3338
+ const out = lines && node.get("stroke") ? node.get("strokeWidth") / 2 * Math.hypot(m[0], m[1]) : 0;
3339
+ if (result && out > 0) result = { x: result.x - out, y: result.y - out, width: result.width + 2 * out, height: result.height + 2 * out };
3340
+ }
3341
+ const image = node.get("image");
3342
+ if (image) {
3343
+ const corners = [apply(m, 0, 0), apply(m, image.width, 0), apply(m, image.width, image.height), apply(m, 0, image.height)];
3344
+ const xs = corners.map((c) => c[0]), ys = corners.map((c) => c[1]);
3345
+ result = unionBounds(result, { x: Math.min(...xs), y: Math.min(...ys), width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys) });
3346
+ }
3347
+ if (node.draw) {
3348
+ const b = node.bounds();
3349
+ if (b.width > 0 || b.height > 0) result = unionBounds(result, b);
3350
+ }
3351
+ for (const child of node.children) result = unionBounds(result, everyBounds(child, m, lines));
3352
+ return result;
3353
+ }
3354
+ var objectOf = (node) => node.data["object"];
3355
+ function describe(thing, measured = true) {
3356
+ if (thing instanceof Box) return "the region";
3357
+ if (isPoint(thing)) return `the point [${thing[0]}, ${thing[1]}]`;
3358
+ const nodes = (thing instanceof Node || thing instanceof Block ? [thing] : thing.filter((part) => Boolean(part) && !(part instanceof Box))).flatMap((part) => nodesOf(part));
3359
+ const one = nodes.length === 1 ? nodes[0] : null;
3360
+ const kind = thing instanceof Block ? `the ${thing.kind}` : !one ? `the list of ${nodes.length} nodes` : one instanceof TextNode ? "the text" : objectOf(one) ? `the ${objectOf(one)}` : "the item";
3361
+ for (const node of nodes) {
3362
+ for (const part of node.all()) {
3363
+ const source = part.source;
3364
+ if (typeof source !== "string" || !source.trim()) continue;
3365
+ const words = JSON.stringify(source.length > 48 ? `${source.slice(0, 48)}...` : source);
3366
+ return kind === "the text" ? `the text ${words}` : `${kind} with the text ${words}`;
3367
+ }
3368
+ }
3369
+ const name = nodes.map((node) => node.label).find(Boolean);
3370
+ if (name) return `${kind} "${name}"`;
3371
+ if (!measured || nodes.length === 0) return kind;
3372
+ const b = measure2(nodes, "describe", "the thing");
3373
+ return `${kind} at (${Math.round(b.cx)}, ${Math.round(b.cy)}), ${round(b.width)} wide and ${round(b.height)} high`;
3374
+ }
3375
+ function move(item, dx, dy) {
3376
+ if (dx === 0 && dy === 0) return;
3377
+ if (item instanceof Block) return move(item.items, dx, dy);
3378
+ if (!(item instanceof Node)) {
3379
+ for (const part of item) if (part) move(part, dx, dy);
3380
+ return;
3381
+ }
3382
+ const inverse = item.parent ? invert(item.parent.worldMatrix()) : IDENTITY;
3383
+ const [x0, y0] = apply(inverse, 0, 0), [x1, y1] = apply(inverse, dx, dy);
3384
+ item.shift(x1 - x0, y1 - y0);
3385
+ }
3386
+ function between(a, b) {
3387
+ const one = measure2(a, "between", "the first thing"), other = measure2(b, "between", "the second thing");
3388
+ const left = Math.min(one.left, other.left), right = Math.max(one.right, other.right), top = Math.min(one.top, other.top), bottom = Math.max(one.bottom, other.bottom);
3389
+ if (one.bottom <= other.top) return new Box(left, one.bottom, right, other.top);
3390
+ if (other.bottom <= one.top) return new Box(left, other.bottom, right, one.top);
3391
+ if (one.right <= other.left) return new Box(one.right, top, other.left, bottom);
3392
+ if (other.right <= one.left) return new Box(other.right, top, one.left, bottom);
3393
+ throw new Error(`between: ${describe(a)} and ${describe(b)} overlap, so there is no room between them. Lay them out first, with a gap, and then ask for the room`);
3394
+ }
3395
+ function fitted(region, build) {
3396
+ const target = typeof region === "number" ? region : measure2(region, "fitted", "the region").width;
3397
+ if (!(Number.isFinite(target) && target > 0)) throw new Error(`fitted: the region is ${target} wide. Give a region, or a width that is more than 0`);
3398
+ if (typeof build !== "function") throw new Error(`fitted: the second argument is a function that builds the object from a width, such as (width) => lanes(names, events, { width }), and it is ${kindOf(build)}`);
3399
+ const made = (width2) => {
3400
+ const object2 = build(width2);
3401
+ if (!(object2 instanceof Node)) throw new Error(`fitted: the function returned ${kindOf(object2)}. It returns the object that it builds, which is a node`);
3402
+ return object2;
3403
+ };
3404
+ let width = target, object = made(width);
3405
+ for (let pass = 0; pass < 3; pass++) {
3406
+ const over2 = boxOf(object).width - target;
3407
+ if (Math.abs(over2) < FIT) return object;
3408
+ width -= over2;
3409
+ if (width <= 0) {
3410
+ if (Math.abs(boxOf(made(target / 2)).width - boxOf(object).width) < FIT) {
3411
+ throw new Error(`fitted: the object is ${round(boxOf(object).width)} wide for each width that the function gets, and the region is ${round(target)} wide. Give the width to the object, as in (width) => lanes(names, events, { width }), or place an object that has one size with \`place\``);
3412
+ }
3413
+ throw new Error(`fitted: the parts beside the plot are ${round(target - width)} wide, and the region is ${round(target)} wide, so no width is left for the plot. Give a region that is wider than ${round(target - width)}, or make the parts beside the plot narrower, such as shorter names`);
3414
+ }
3415
+ object = made(width);
3416
+ }
3417
+ return object;
3418
+ }
3419
+ var TEXT_ROOM = 0.3;
3420
+ var TEXT_SPARE = 0.5;
3421
+ function textsOf(thing) {
3422
+ if (thing instanceof Box || isPoint(thing)) return [];
3423
+ return (thing instanceof Node || thing instanceof Block ? [thing] : thing.filter((part) => Boolean(part) && !(part instanceof Box))).flatMap((part) => nodesOf(part)).filter((node) => node instanceof TextNode);
3424
+ }
3425
+ function roomBox(node) {
3426
+ const line = boxOf(node), ink = everyBounds(node, node.parent ? node.parent.worldMatrix() : IDENTITY);
3427
+ const m = node.worldMatrix();
3428
+ const upright = Math.abs(m[1]) < 1e-9 && Math.abs(m[2]) < 1e-9 && m[3] > 0;
3429
+ const top = upright ? apply(m, 0, node.letters[0])[1] : line.top, bottom = upright ? apply(m, 0, node.letters[1])[1] : line.bottom;
3430
+ if (!ink) return new Box(line.left, Math.min(top, bottom), line.right, Math.max(top, bottom));
3431
+ return new Box(Math.min(line.left, ink.x), Math.min(top, ink.y), Math.max(line.right, ink.x + ink.width), Math.max(bottom, ink.y + ink.height));
3432
+ }
3433
+ function drawnBox(node) {
3434
+ const b = everyBounds(node, node.parent ? node.parent.worldMatrix() : IDENTITY, true);
3435
+ return b ? new Box(b.x, b.y, b.x + b.width, b.y + b.height) : boxOf(node);
3436
+ }
3437
+ function marksOf(thing) {
3438
+ if (thing instanceof Box || isPoint(thing)) return [measure2(thing, "gap", "the thing")];
3439
+ return (thing instanceof Node || thing instanceof Block ? [thing] : thing.filter(Boolean)).flatMap((part) => part instanceof Box ? [part] : nodesOf(part).filter((node) => !(node instanceof TextNode)).map((node) => drawnBox(node)));
3440
+ }
3441
+ function gapBetween(gap, what, first, second, axis) {
3442
+ const base = px(gap, what);
3443
+ if (typeof gap === "number" || gap === "none") return base;
3444
+ const far = (b) => axis === "x" ? b.right : b.bottom, near = (b) => axis === "x" ? b.left : b.top;
3445
+ const one = measure2(first, what, "the thing"), other = measure2(second, what, "the thing");
3446
+ const room = (node) => {
3447
+ const m = node.worldMatrix();
3448
+ return TEXT_ROOM * node.size * Math.hypot(m[0], m[1]) + TEXT_SPARE;
3449
+ };
3450
+ const markInFirst = Math.min(Infinity, ...marksOf(first).map((b) => far(one) - far(b))), markInSecond = Math.min(Infinity, ...marksOf(second).map((b) => near(b) - near(other)));
3451
+ let least = base;
3452
+ for (const node of textsOf(first)) least = Math.max(least, room(node) - (far(one) - far(roomBox(node))) - markInSecond);
3453
+ for (const node of textsOf(second)) least = Math.max(least, room(node) - (near(roomBox(node)) - near(other)) - markInFirst);
3454
+ return least;
3455
+ }
3456
+ function itemsOf(what, items) {
3457
+ if (!Array.isArray(items)) throw new Error(`${what}: the items are one list, such as ${what}([a, b]), and the first argument is ${kindOf(items)}`);
3458
+ items.forEach((item, index) => {
3459
+ if (item) checkItem(what, item, `item ${index}`);
3460
+ });
3461
+ return items.filter(Boolean);
3462
+ }
3463
+ function baseOf(item) {
3464
+ if (item instanceof TextNode) {
3465
+ const m = item.worldMatrix();
3466
+ return Math.abs(m[1]) > 1e-9 ? null : apply(m, 0, item.baseline)[1];
3467
+ }
3468
+ if (item instanceof Block && item.kind === "row") {
3469
+ for (const part of item.items) {
3470
+ const base = baseOf(part);
3471
+ if (base !== null) return base;
3472
+ }
3473
+ }
3474
+ return null;
3475
+ }
3476
+ function lineUp(items, boxes, align) {
3477
+ const heights = boxes.map((b) => b.height), height = Math.max(...heights);
3478
+ if (align === "top") return { tops: heights.map(() => 0), height };
3479
+ if (align === "bottom") return { tops: heights.map((h) => height - h), height };
3480
+ const middles = heights.map((h) => (height - h) / 2);
3481
+ if (align === "center") return { tops: middles, height };
3482
+ const bases = items.map((item) => baseOf(item));
3483
+ const texts = bases.flatMap((base, index) => base === null ? [] : [index]);
3484
+ if (texts.length < 2) return { tops: middles, height };
3485
+ const up = Math.max(...texts.map((i) => bases[i] - boxes[i].top)), down = Math.max(...texts.map((i) => boxes[i].bottom - bases[i]));
3486
+ const all = Math.max(height, up + down), line = (all - (up + down)) / 2 + up;
3487
+ return { tops: heights.map((h, i) => bases[i] === null ? (all - h) / 2 : line - (bases[i] - boxes[i].top)), height: all };
3488
+ }
3489
+ function row(items, options = {}) {
3490
+ const list2 = itemsOf("row", items);
3491
+ const { gap = "normal", align = "baseline" } = optionsOf("row", options, ["gap", "align"], "{ gap: 'tight' }");
3492
+ if (list2.length === 0) throw new Error("row: give it at least one item");
3493
+ if (!["baseline", "top", "center", "bottom"].includes(align)) throw new Error(`row: align is baseline, top, center or bottom, and it is ${JSON.stringify(align)}`);
3494
+ px(gap, "row");
3495
+ distinct("row", list2, "the row");
3496
+ const boxes = list2.map((item, index) => measure2(item, "row", `item ${index}`));
3497
+ const gaps = list2.slice(1).map((item, index) => gapBetween(gap, "row", list2[index], item, "x"));
3498
+ const { tops, height } = lineUp(list2, boxes, align);
3499
+ let at = -(boxes.reduce((sum, b) => sum + b.width, 0) + gaps.reduce((sum, g) => sum + g, 0)) / 2;
3500
+ list2.forEach((item, index) => {
3501
+ const b = boxes[index];
3502
+ move(item, at - b.left, -height / 2 + tops[index] - b.top);
3503
+ at += b.width + (gaps[index] ?? 0);
3504
+ });
3505
+ const made = new Block(list2, "row");
3506
+ MADE.set(made, { gapsX: gaps.reduce((sum, g) => sum + g, 0), gapsY: 0 });
3507
+ return made;
3508
+ }
3509
+ function column(items, options = {}) {
3510
+ const list2 = itemsOf("column", items);
3511
+ const { gap = "normal", align = "left" } = optionsOf("column", options, ["gap", "align"], "{ gap: 'tight' }");
3512
+ if (list2.length === 0) throw new Error("column: give it at least one item");
3513
+ if (!["left", "center", "right"].includes(align)) throw new Error(`column: align is left, center or right, and it is ${JSON.stringify(align)}`);
3514
+ px(gap, "column");
3515
+ distinct("column", list2, "the column");
3516
+ const boxes = list2.map((item, index) => measure2(item, "column", `item ${index}`));
3517
+ const gaps = list2.slice(1).map((item, index) => gapBetween(gap, "column", list2[index], item, "y"));
3518
+ const width = Math.max(...boxes.map((b) => b.width));
3519
+ let at = -(boxes.reduce((sum, b) => sum + b.height, 0) + gaps.reduce((sum, g) => sum + g, 0)) / 2;
3520
+ list2.forEach((item, index) => {
3521
+ const b = boxes[index];
3522
+ const start = align === "left" ? -width / 2 : align === "right" ? width / 2 - b.width : -b.width / 2;
3523
+ move(item, start - b.left, at - b.top);
3524
+ at += b.height + (gaps[index] ?? 0);
3525
+ });
3526
+ const made = new Block(list2, "column");
3527
+ MADE.set(made, { gapsX: 0, gapsY: gaps.reduce((sum, g) => sum + g, 0) });
3528
+ return made;
3529
+ }
3530
+ function gridSize(cells, columns, gx, gy, even) {
3531
+ const rows = Math.ceil(cells.length / columns);
3532
+ const widths = Array.from({ length: columns }, (_, c) => Math.max(0, ...cells.filter((cell, i) => cell && i % columns === c).map((cell) => cell.width)));
3533
+ const own = Array.from({ length: rows }, (_, r) => Math.max(0, ...cells.slice(r * columns, (r + 1) * columns).map((cell) => cell ? cell.height : 0)));
3534
+ const heights = even ? own.map(() => Math.max(...own)) : own;
3535
+ return { widths, heights, width: widths.reduce((sum, w) => sum + w, 0) + gx * (columns - 1), height: heights.reduce((sum, h) => sum + h, 0) + gy * (rows - 1) };
3536
+ }
3537
+ function grid(items, options) {
3538
+ if (!Array.isArray(items)) throw new Error(`grid: the items are one list, such as grid([a, b, c, d], { columns: 2 }), and the first argument is ${kindOf(items)}`);
3539
+ const given = optionsOf("grid", options ?? {}, ["columns", "gap", "align", "even"], "{ columns: 2 }");
3540
+ const columns = given.columns;
3541
+ if (!(Number.isInteger(columns) && columns > 0)) throw new Error(`grid: columns is the count of columns, a whole number of 1 or more, and it is ${typeof columns === "number" || columns === void 0 ? String(columns) : kindOf(columns)}`);
3542
+ items.forEach((item, index) => {
3543
+ if (item) checkItem("grid", item, `item ${index}`);
3544
+ });
3545
+ if (items.length === 0 || !items.some(Boolean)) throw new Error("grid: give it at least one item");
3546
+ const one = given.gap ?? "normal";
3547
+ const [nameX, nameY] = Array.isArray(given.gap) ? given.gap : [one, one];
3548
+ px(nameX, "grid");
3549
+ px(nameY, "grid");
3550
+ const aligns = Array.isArray(given.align) ? given.align : Array.from({ length: columns }, () => given.align ?? "left");
3551
+ if (aligns.length !== columns) throw new Error(`grid: align is a list of ${aligns.length}, and the grid has ${columns} columns. Give one value for all columns, or a list with one value for each column`);
3552
+ for (const align of aligns) {
3553
+ if (!["left", "center", "right"].includes(align)) throw new Error(`grid: align is left, center or right, and it is ${JSON.stringify(align)}`);
3554
+ }
3555
+ const cells = items.map((item) => item ? item : null);
3556
+ distinct("grid", cells.filter((cell) => cell !== null), "the grid");
3557
+ const boxes = cells.map((cell, index) => cell ? measure2(cell, "grid", `item ${index}`) : null);
3558
+ const rows = Math.ceil(cells.length / columns);
3559
+ const across = cells.map((cell, i) => cell && cells[i + 1] && (i + 1) % columns !== 0 ? gapBetween(nameX, "grid", cell, cells[i + 1], "x") : px(nameX, "grid"));
3560
+ const down = cells.map((cell, i) => cell && cells[i + columns] ? gapBetween(nameY, "grid", cell, cells[i + columns], "y") : px(nameY, "grid"));
3561
+ const gx = Math.max(...across), gy = Math.max(...down);
3562
+ const lines = Array.from({ length: rows }, (_, r) => {
3563
+ const at2 = cells.map((_2, i) => i).slice(r * columns, (r + 1) * columns).filter((i) => cells[i]);
3564
+ return at2.length === 0 ? { at: at2, tops: [], height: 0 } : { at: at2, ...lineUp(at2.map((i) => cells[i]), at2.map((i) => boxes[i]), "baseline") };
3565
+ });
3566
+ const { widths } = gridSize(boxes, columns, gx, gy, false);
3567
+ const highest = Math.max(...lines.map((line) => line.height));
3568
+ const heights = lines.map((line) => given.even ? highest : line.height);
3569
+ const lefts = [], tops = [];
3570
+ let at = -(widths.reduce((sum, w) => sum + w, 0) + gx * (columns - 1)) / 2;
3571
+ for (const width of widths) {
3572
+ lefts.push(at);
3573
+ at += width + gx;
3574
+ }
3575
+ at = -(heights.reduce((sum, h) => sum + h, 0) + gy * (rows - 1)) / 2;
3576
+ for (const height of heights) {
3577
+ tops.push(at);
3578
+ at += height + gy;
3579
+ }
3580
+ lines.forEach((line, r) => line.at.forEach((index, k) => {
3581
+ const c = index % columns, box2 = boxes[index], align = aligns[c];
3582
+ const x = align === "left" ? lefts[c] : align === "right" ? lefts[c] + widths[c] - box2.width : lefts[c] + (widths[c] - box2.width) / 2;
3583
+ move(cells[index], x - box2.left, tops[r] + (heights[r] - line.height) / 2 + line.tops[k] - box2.top);
3584
+ }));
3585
+ const made = new Block(cells.filter((cell) => cell !== null), "grid");
3586
+ MADE.set(made, { gapsX: gx * (columns - 1), gapsY: gy * (rows - 1), grid: { cells, columns, gx, gy, even: given.even === true } });
3587
+ return made;
3588
+ }
3589
+ function waysToFit(item, region, axis, why) {
3590
+ const along3 = (b) => axis === "x" ? b.width : b.height;
3591
+ const word = axis === "x" ? "wide" : "high";
3592
+ const room = along3(region), own = along3(boxOf(item)), over2 = own - room;
3593
+ if (item instanceof Block) {
3594
+ const ways = [];
3595
+ const made = MADE.get(item), sizes = item.items.map((part) => along3(boxOf(part)));
3596
+ const largest = Math.max(...sizes), which = item.items[sizes.indexOf(largest)];
3597
+ const gaps = made ? axis === "x" ? made.gapsX : made.gapsY : 0;
3598
+ if (gaps > 0 && gaps >= over2) ways.push(`a smaller gap (the gaps take ${round(gaps)} of the ${round(own)})`);
3599
+ if (made?.grid) {
3600
+ const g = made.grid, boxes = g.cells.map((cell) => cell ? boxOf(cell) : null);
3601
+ const counts = axis === "x" ? Array.from({ length: g.columns - 1 }, (_, i) => g.columns - 1 - i) : Array.from({ length: Math.max(0, g.cells.length - g.columns) }, (_, i) => g.columns + 1 + i);
3602
+ const found = counts.find((columns) => {
3603
+ const size = gridSize(boxes, columns, g.gx, g.gy, g.even);
3604
+ return size.width <= region.width + FIT && size.height <= region.height + FIT;
3605
+ });
3606
+ if (found !== void 0) ways.push(`${axis === "x" ? "fewer" : "more"} columns (\`columns: ${found}\` fits)`);
3607
+ } else if (item.kind === "row" === (axis === "x") && item.items.length > 1) {
3608
+ ways.push(`fewer items in the ${item.kind}`);
3609
+ }
3610
+ if (largest > room + FIT) {
3611
+ why.push(`${describe(which).replace(/^t/, "T")} alone is ${round(largest)} ${word}`);
3612
+ return waysToFit(which, region, axis, why);
3613
+ }
3614
+ return ways;
3615
+ }
3616
+ if (item instanceof TextNode) {
3617
+ const ways = [];
3618
+ const m = item.worldMatrix(), scale = Math.hypot(m[0], m[1]) || 1;
3619
+ const lineBox = item.layoutBox ? (item.layoutBox[3] - item.layoutBox[1]) * scale : own, oneLine = LINE_BOX2 * item.size * scale;
3620
+ const lines = lineBox - oneLine > 1 ? "more" : "one";
3621
+ if (axis === "y") {
3622
+ why.push(`A text measures ${LINE_BOX2} of its size for each line: one line of size ${round(item.size)} is ${round(oneLine)} high`);
3623
+ if (lines === "more" && oneLine <= room + FIT) ways.push("fewer lines (fewer words, or a larger `maxWidth`)");
3624
+ } else {
3625
+ const words = item.source.trim().split(/\s+/);
3626
+ const longest = Math.max(...words.map((part) => part.length)) / Math.max(1, item.source.trim().length) * own;
3627
+ const wrapped = Math.ceil(own / room) * LEADING * item.size * scale + oneLine;
3628
+ if (lines === "one" && words.length > 1 && longest <= room && wrapped <= region.height + FIT) ways.push(`lines that wrap at ${Math.floor(room)} or less (\`maxWidth\` of \`text\`, or the width of \`para\`)`);
3629
+ if (words.length > 1) ways.push("fewer words");
3630
+ }
3631
+ ways.push(`a text size of ${Math.floor(item.size * room / own)} or less (it is ${round(item.size)})`);
3632
+ return ways;
3633
+ }
3634
+ return [`a ${axis === "x" ? "width" : "height"} of ${round(room)} or less`];
3635
+ }
3636
+ var LINE_BOX2 = 1.2;
3637
+ var LEADING = 1.3;
3638
+ function advice(item, region, wide, high) {
3639
+ const own = boxOf(item), why = [];
3640
+ const say = (axis) => {
3641
+ const larger = axis === "x" ? `a region that is ${round(own.width)} wide or more` : `a region that is ${round(own.height)} high or more`;
3642
+ const ways = [.../* @__PURE__ */ new Set([...waysToFit(item, region, axis, why), larger])];
3643
+ return `${ways.slice(0, -1).join(", ")}${ways.length > 1 ? ", or " : ""}${ways[ways.length - 1]}`;
3644
+ };
3645
+ const works = wide && high ? `What works for the width: ${say("x")}. What works for the height: ${say("y")}` : `What works: ${say(wide ? "x" : "y")}`;
3646
+ return [...new Set(why), works].join(". ");
3647
+ }
3648
+ var PLACED = /* @__PURE__ */ new WeakMap();
3649
+ function offFrame(box2, width, height) {
3650
+ const all = [["left", -width / 2 - box2.left], ["right", box2.right - width / 2], ["top", -height / 2 - box2.top], ["bottom", box2.bottom - height / 2]];
3651
+ return all.filter(([, by]) => by > FIT);
3652
+ }
3653
+ function shownFrom(node) {
3654
+ let time = 0;
3655
+ for (let up = node; up; up = up.parent) {
3656
+ const visible = up.tracks?.get("visible");
3657
+ if (!visible) continue;
3658
+ const first = visible.initial === true ? 0 : visible.keys.find((key) => key.to === true)?.t0 ?? Infinity;
3659
+ time = Math.max(time, first);
3660
+ }
3661
+ return time;
3662
+ }
3663
+ function inFrame(what, item, box2, from, advice2) {
3664
+ const canvas = clock.canvas;
3665
+ if (!canvas || clock.mode !== "compile") return;
3666
+ const w = canvas.width / 2, h = canvas.height / 2;
3667
+ const away = from.right < -w || from.left > w || from.bottom < -h || from.top > h;
3668
+ const message = (thing, off, when) => `${what}: ${describe(thing)} ${when} ${off.map(([edge, by]) => `${round(by)} off the frame at the ${edge}`).join(" and ")}. The frame is ${canvas.width} by ${canvas.height}, with its middle at [0, 0]. ${advice2(off.map(([edge]) => edge))}`;
3669
+ if (clock.capture) {
3670
+ const off = away ? [] : offFrame(box2, canvas.width, canvas.height);
3671
+ if (off.length > 0) throw new Error(message(item, off, "would be"));
3672
+ return;
3673
+ }
3674
+ let placed = PLACED.get(canvas);
3675
+ if (!placed) {
3676
+ const made = /* @__PURE__ */ new Map();
3677
+ PLACED.set(canvas, placed = made);
3678
+ canvas.checks.push(() => {
3679
+ const now = clock.now;
3680
+ try {
3681
+ for (const [node, record] of made) {
3682
+ if (!node.mounted) continue;
3683
+ const time = Math.max(record.time, shownFrom(node));
3684
+ if (!Number.isFinite(time)) continue;
3685
+ clock.now = time;
3686
+ const off = offFrame(boxOf(node), canvas.width, canvas.height);
3687
+ if (off.length > 0) throw new Error(`${record.what}: ${describe(node)} is ${off.map(([edge, by]) => `${round(by)} off the frame at the ${edge}`).join(" and ")}. The frame is ${canvas.width} by ${canvas.height}, with its middle at [0, 0]. ${record.advice(off.map(([edge]) => edge))}`);
3688
+ }
3689
+ } finally {
3690
+ clock.now = now;
3691
+ }
3692
+ });
3693
+ }
3694
+ for (const node of nodesOf(item)) {
3695
+ if (away) placed.delete(node);
3696
+ else placed.set(node, { what, time: clock.now, advice: advice2 });
3697
+ }
3698
+ }
3699
+ function place(item, region, where = "center") {
3700
+ checkItem("place", item, "the item");
3701
+ if (region === void 0 || region === null) throw new Error(`place: the region is ${region}. A region is a \`Box\` such as the \`area\` of the kit, or a thing whose measure is the region: a node, a block or a list`);
3702
+ if (isPoint(region)) throw new Error(`place: the region is the point [${region[0]}, ${region[1]}], and a point has no room for an item. To put an item at a point, use beside(item, [x, y], side), or give a region`);
3703
+ const target = measure2(region, "place", "the region");
3704
+ const [h, v] = sides(where, "place");
3705
+ if (nodesOf(item).length === 0) throw new Error("place: the item is an empty list. Give it at least one node");
3706
+ distinct("place", item, "the list");
3707
+ const own = measure2(item, "place", "the item");
3708
+ const wide = own.width - target.width > FIT, high = own.height - target.height > FIT;
3709
+ if (wide || high) {
3710
+ const parts = [wide ? `${round(own.width - target.width)} too wide (${round(own.width)} in ${round(target.width)})` : "", high ? `${round(own.height - target.height)} too high (${round(own.height)} in ${round(target.height)})` : ""].filter(Boolean);
3711
+ throw new Error(`place: ${describe(item)} is ${parts.join(" and ")} for its region. ${advice(item, target, wide, high)}`);
3712
+ }
3713
+ const x = h < 0 ? target.left - own.left : h > 0 ? target.right - own.right : target.cx - own.cx;
3714
+ const y = v < 0 ? target.top - own.top : v > 0 ? target.bottom - own.bottom : target.cy - own.cy;
3715
+ inFrame("place", item, new Box(own.left + x, own.top + y, own.right + x, own.bottom + y), target, () => "The region reaches over the frame there: use a region that is inside the frame");
3716
+ move(item, x, y);
3717
+ return item;
3718
+ }
3719
+ function ownerOf(node) {
3720
+ for (let up = node.parent; up; up = up.parent) if (up.data["ownLayout"] === true && objectOf(up)) return up;
3721
+ return null;
3722
+ }
3723
+ function beside(item, other, side, gap = "normal", align = "center") {
3724
+ checkItem("beside", item, "the item");
3725
+ checkSide(side, "beside");
3726
+ const horizontal = side === "left" || side === "right";
3727
+ const allowed = horizontal ? ["center", "top", "bottom"] : ["center", "left", "right"];
3728
+ if (typeof align === "string" && !allowed.includes(align)) {
3729
+ throw new Error(`beside: for the side ${side}, align is ${oneOf(allowed)}, or a part of the other thing that the item lines up with, and it is ${JSON.stringify(align)}`);
3730
+ }
3731
+ const part = typeof align === "string" ? null : measure2(align, "beside", "the part that the item lines up with");
3732
+ if (other === void 0 || other === null) throw new Error(`beside: the other thing is ${other}. Give a node, a block, a region, or a point [x, y]`);
3733
+ if (nodesOf(item).length === 0) throw new Error("beside: the item is an empty list. Give it at least one node");
3734
+ distinct("beside", item, "the list");
3735
+ const b = measure2(other, "beside", "the other thing"), own = measure2(item, "beside", "the item"), axis = horizontal ? "x" : "y";
3736
+ const g = side === "left" || side === "above" ? gapBetween(gap, "beside", item, other, axis) : gapBetween(gap, "beside", other, item, axis);
3737
+ const across = (from, to2, a, z, middle) => middle !== null ? middle - (from + to2) / 2 : align === "center" ? (a + z) / 2 - (from + to2) / 2 : align === "top" || align === "left" ? a - from : z - to2;
3738
+ const dx = horizontal ? side === "right" ? b.right + g - own.left : b.left - g - own.right : across(own.left, own.right, b.left, b.right, part ? part.cx : null);
3739
+ const dy = horizontal ? across(own.top, own.bottom, b.top, b.bottom, part ? part.cy : null) : side === "under" ? b.bottom + g - own.top : b.top - g - own.bottom;
3740
+ const owner = other instanceof Node ? ownerOf(other) : null;
3741
+ if (owner && !nodesOf(item).some((node) => owner.all().includes(node))) {
3742
+ const whole = boxOf(owner);
3743
+ const on = Math.min(own.right + dx, whole.right) - Math.max(own.left + dx, whole.left) > 1 && Math.min(own.bottom + dy, whole.bottom) - Math.max(own.top + dy, whole.top) > 1;
3744
+ if (on) {
3745
+ throw new Error(`beside: ${describe(item)} would lie on the ${objectOf(owner)} that the other thing is a part of. To put it beside the whole ${objectOf(owner)}, at the ${horizontal ? "height" : "x"} of the part, give the object and then the part: beside(item, object, '${side}', gap, part). To put it on the object on purpose, give boxOf(part)`);
3746
+ }
3747
+ }
3748
+ inFrame("beside", item, new Box(own.left + dx, own.top + dy, own.right + dx, own.bottom + dy), b, (edges2) => {
3749
+ const along3 = edges2.some((edge) => horizontal ? edge === "left" || edge === "right" : edge === "top" || edge === "bottom");
3750
+ if (along3) return "Put it at another side of the other thing, use a smaller gap, or move the other thing away from that edge of the frame";
3751
+ return `Line up an edge in place of the middle, with ${horizontal ? "'top' or 'bottom'" : "'left' or 'right'"} as the last argument, make the item smaller, or move the other thing away from that edge of the frame`;
3752
+ });
3753
+ move(item, dx, dy);
3754
+ return item;
3755
+ }
3756
+
3757
+ // src/stage/objects/pictograms.ts
3758
+ var GRID = 24;
3759
+ var stroke = (d, accent = false) => ({ path: parseSvgPath(d), paint: "line", accent });
3760
+ var dashed = (d, accent = false) => ({ path: parseSvgPath(d), paint: "line", accent, dash: [1.5, 2.6] });
3761
+ var solid2 = (d, accent = false) => ({ path: parseSvgPath(d), paint: "solid", accent });
3762
+ var soft = (d, accent = false) => ({ path: parseSvgPath(d), paint: "soft", accent });
3763
+ var ring2 = (x, y, r, accent = false) => ({ path: circlePath(x, y, r), paint: "line", accent });
3764
+ var disc = (x, y, r, accent = false) => ({ path: circlePath(x, y, r), paint: "solid", accent });
3765
+ var box = (x, y, w, h, r = 0, accent = false) => ({ path: rectPath(x, y, w, h, r), paint: "line", accent });
3766
+ var slab = (x, y, w, h, r = 0, accent = false) => ({ path: rectPath(x, y, w, h, r), paint: "solid", accent });
3767
+ var curve = (x, y, rx, ry, from, to2, accent = false) => ({ path: arcPath(x, y, rx, ry, from, to2), paint: "line", accent });
3768
+ function arrowTo(from, to2, gap, accent = false) {
3769
+ const dx = to2[0] - from[0], dy = to2[1] - from[1];
3770
+ const length = Math.hypot(dx, dy) || 1;
3771
+ const ux = dx / length, uy = dy / length;
3772
+ const tip = [to2[0] - ux * gap, to2[1] - uy * gap];
3773
+ const size = 2.2, half = 1.2;
3774
+ const base = [tip[0] - ux * size, tip[1] - uy * size];
3775
+ return [
3776
+ { path: polyPath([[from[0] + ux * gap, from[1] + uy * gap], base]), paint: "line", accent },
3777
+ { path: polyPath([tip, [base[0] - uy * half, base[1] + ux * half], [base[0] + uy * half, base[1] - ux * half]], true), paint: "solid", accent }
3778
+ ];
3779
+ }
3780
+ function arcArrow(x, y, r, from, to2, accent = false) {
3781
+ const size = 2.6, half = 1.5;
3782
+ const end2 = to2 - size / r;
3783
+ const tip = [x + Math.cos(to2) * r, y + Math.sin(to2) * r];
3784
+ const base = [x + Math.cos(end2) * r, y + Math.sin(end2) * r];
3785
+ const ox = Math.cos(end2), oy = Math.sin(end2);
3786
+ return [
3787
+ { path: arcPath(x, y, r, r, from, end2), paint: "line", accent },
3788
+ { path: polyPath([tip, [base[0] + ox * half, base[1] + oy * half], [base[0] - ox * half, base[1] - oy * half]], true), paint: "solid", accent }
3789
+ ];
3790
+ }
3791
+ function edges(points, pairs, paint = "line") {
3792
+ return pairs.map(([a, b]) => ({ path: polyPath([points[a], points[b]]), paint }));
3793
+ }
3794
+ function gear() {
3795
+ const teeth = 8, outer = 9.2, root = 6.9, points = [];
3796
+ for (let i = 0; i < teeth; i++) {
3797
+ const a = i / teeth * Math.PI * 2 - Math.PI / 2, w = Math.PI / teeth;
3798
+ for (const [angle, radius] of [[a - w * 0.5, outer], [a + w * 0.5, outer], [a + w * 0.78, root], [a + w * 1.22, root]]) {
3799
+ points.push([12 + Math.cos(angle) * radius, 12 + Math.sin(angle) * radius]);
3800
+ }
3801
+ }
3802
+ return [{ path: polyPath(points, true), paint: "line" }, ring2(12, 12, 3, true)];
3803
+ }
3804
+ function legs(half, at) {
3805
+ const near = 12 - half, far = 12 + half;
3806
+ return at.flatMap((place2) => [stroke(`M${place2} 2.8V${near}`), stroke(`M${place2} ${far}V21.2`), stroke(`M2.8 ${place2}H${near}`), stroke(`M${far} ${place2}H21.2`)]);
3807
+ }
3808
+ function ringBuffer() {
3809
+ const inner = 4.6, outer = 8.6, slot = Math.PI / 4, top = -Math.PI / 2, filled = 3;
3810
+ const at = (radius, angle, side = 0) => {
3811
+ const x = 12 + Math.cos(angle) * radius - Math.sin(angle) * side, y = 12 + Math.sin(angle) * radius + Math.cos(angle) * side;
3812
+ return `${+x.toFixed(3)} ${+y.toFixed(3)}`;
3813
+ };
3814
+ const end2 = top + filled * slot, turn = top + Math.PI * 2;
3815
+ return [
3816
+ // The two rims are each in two parts, so the filled slots are all in the accent at each weight. The parts meet under a divider.
3817
+ curve(12, 12, outer, outer, end2, turn),
3818
+ curve(12, 12, inner, inner, end2, turn),
3819
+ solid2(`M${at(outer, top)}A${outer} ${outer} 0 0 1 ${at(outer, end2)}L${at(inner, end2)}A${inner} ${inner} 0 0 0 ${at(inner, top)}Z`, true),
3820
+ curve(12, 12, outer, outer, top, end2, true),
3821
+ curve(12, 12, inner, inner, top, end2, true),
3822
+ ...Array.from({ length: 8 }, (_, i) => stroke(`M${at(inner, top + i * slot)}L${at(outer, top + i * slot)}`)),
3823
+ solid2(`M${at(10.2, end2)}L${at(13.2, end2, 1.8)}L${at(13.2, end2, -1.8)}Z`)
3824
+ ];
3825
+ }
3826
+ function shard() {
3827
+ const x = 11.8, y = 13.4, radius = 7.2, piece = Math.PI / 3, top = -Math.PI / 2;
3828
+ const at = (ox, oy, r, angle) => `${+(ox + Math.cos(angle) * r).toFixed(2)} ${+(oy + Math.sin(angle) * r).toFixed(2)}`;
3829
+ const px2 = +(x + Math.cos(top + piece / 2) * 3.8).toFixed(2), py = +(y + Math.sin(top + piece / 2) * 3.8).toFixed(2);
3830
+ return [
3831
+ stroke(`M${x} ${y}L${at(x, y, radius, top + piece)}A${radius} ${radius} 0 1 1 ${at(x, y, radius, top)}Z`),
3832
+ ...[2, 3, 4, 5].map((i) => stroke(`M${x} ${y}L${at(x, y, radius, top + i * piece)}`)),
3833
+ solid2(`M${px2} ${py}L${at(px2, py, 7.4, top)}A7.4 7.4 0 0 1 ${at(px2, py, 7.4, top + piece)}Z`, true)
3834
+ ];
3835
+ }
3836
+ var GRAPH = [[4.5, 6.5], [15.5, 4.5], [10.5, 12.5], [19.5, 13.5], [6.5, 19.5], [16, 20]];
3837
+ var TREE = [[12, 4.5], [6.5, 12], [17.5, 12], [3.5, 19.5], [9.5, 19.5], [17.5, 19.5]];
3838
+ var NET_IN = [[4.5, 7.5], [4.5, 16.5]];
3839
+ var NET_MID = [[12, 4.5], [12, 12], [12, 19.5]];
3840
+ var NET_OUT = [[19.5, 7.5], [19.5, 16.5]];
3841
+ var DAG = [[4, 12], [12, 4.5], [12, 19.5], [20, 12]];
3842
+ var ART = {
3843
+ // Telemetry
3844
+ series: () => [stroke("M2.5 15 5.5 10.5 8 13.5 11 6.5 14 12 16.5 9 19 13.5 21.5 7", true)],
3845
+ chart: () => [stroke("M3 3V21H21"), stroke("M6.5 16 10 11.5 13.5 14 19.5 6.5", true)],
3846
+ forecast: () => [
3847
+ soft("M11 11.5 21.5 3.5V15.5Z", true),
3848
+ stroke("M2.5 16.5 5 12.5 7.5 15.5 11 11.5"),
3849
+ stroke("M11 11.5 21.5 9.5", true),
3850
+ disc(11, 11.5, 1.5, true)
3851
+ ],
3852
+ threshold: () => [dashed("M2.5 8H21.5", true), stroke("M2.5 17 6.5 15 10 16.5 14 11.5 17.5 8.5 21.5 4")],
3853
+ anomaly: () => [stroke("M2.5 16 6 14.5 9 16 12 6 15 15.5 18 14 21.5 15.5"), disc(12, 6, 2.1, true)],
3854
+ logs: () => [
3855
+ disc(3.6, 5.5, 1.15, true),
3856
+ stroke("M7.5 5.5H16"),
3857
+ disc(3.6, 10, 1.15),
3858
+ stroke("M7.5 10H21"),
3859
+ disc(3.6, 14.5, 1.15),
3860
+ stroke("M7.5 14.5H13.5"),
3861
+ disc(3.6, 19, 1.15),
3862
+ stroke("M7.5 19H18.5")
3863
+ ],
3864
+ traces: () => [slab(2.5, 3.6, 19, 3.2, 1.6), slab(5, 8.4, 11, 3.2, 1.6, true), slab(8.5, 13.2, 7.5, 3.2, 1.6, true), slab(12.5, 18, 9, 3.2, 1.6)],
3865
+ bars: () => [stroke("M2.5 21H21.5"), slab(4, 13, 3.6, 8, 0.9), slab(10.2, 8.5, 3.6, 12.5, 0.9), slab(16.4, 4, 3.6, 17, 0.9, true)],
3866
+ table: () => [box(3, 4, 18, 16, 2.2), stroke("M3 14.7H21"), stroke("M10 4V20"), stroke("M3 9.4H21", true)],
3867
+ matrix: () => [0, 1, 2].flatMap((row2) => [0, 1, 2].map((column2) => {
3868
+ const lit = row2 === 0 && column2 === 1 || row2 === 1 && column2 === 2 || row2 === 2 && column2 === 0;
3869
+ return (lit ? slab : box)(3.2 + column2 * 6.6, 3.2 + row2 * 6.6, 4.4, 4.4, 1.1, lit);
3870
+ })),
3871
+ event: () => [solid2("M12 4 20 12 12 20 4 12Z", true)],
3872
+ alert: () => [stroke("M6 16.5V11A6 6 0 0 1 18 11V16.5L19.8 19H4.2Z"), stroke("M12 2.8V5"), stroke("M10 21.6H14", true)],
3873
+ // Structure
3874
+ graph: () => [
3875
+ ...edges(GRAPH, [[0, 1], [0, 2], [1, 2], [1, 3], [2, 3], [2, 4], [3, 5], [4, 5]]),
3876
+ ...GRAPH.map(([x, y], i) => disc(x, y, 2.1, i === 2))
3877
+ ],
3878
+ dag: () => [
3879
+ ...arrowTo(DAG[0], DAG[1], 2.7),
3880
+ ...arrowTo(DAG[0], DAG[2], 2.7),
3881
+ ...arrowTo(DAG[1], DAG[3], 2.7),
3882
+ ...arrowTo(DAG[2], DAG[3], 2.7),
3883
+ ...DAG.map(([x, y], i) => disc(x, y, 2.1, i === 3))
3884
+ ],
3885
+ tree: () => [
3886
+ ...edges(TREE, [[0, 1], [0, 2], [1, 3], [1, 4], [2, 5]]),
3887
+ ...TREE.map(([x, y], i) => disc(x, y, 2.1, i === 0))
3888
+ ],
3889
+ layers: () => [stroke("M12 3 21 7.5 12 12 3 7.5Z", true), stroke("M3 12 12 16.5 21 12"), stroke("M3 16.5 12 21 21 16.5")],
3890
+ pipeline: () => [box(1.6, 9, 4.2, 6, 1.3), box(9.9, 9, 4.2, 6, 1.3), box(18.2, 9, 4.2, 6, 1.3, true), solid2("M6.9 10.4 8.9 12 6.9 13.6Z"), solid2("M15.2 10.4 17.2 12 15.2 13.6Z")],
3891
+ branch: () => [stroke("M7 7.4V16.6"), stroke("M17 10.4C17 15 7 12.5 7 16.6"), ring2(7, 5, 2.4), ring2(7, 19, 2.4), ring2(17, 8, 2.4, true)],
3892
+ // Systems
3893
+ service: () => [
3894
+ box(3, 3.5, 18, 7, 2),
3895
+ box(3, 13.5, 18, 7, 2),
3896
+ disc(7, 7, 1.15, true),
3897
+ disc(7, 17, 1.15, true),
3898
+ stroke("M11 7H17"),
3899
+ stroke("M11 17H17")
3900
+ ],
3901
+ database: () => [
3902
+ stroke("M4 6V18"),
3903
+ stroke("M20 6V18"),
3904
+ curve(12, 12, 8, 3, 0, Math.PI),
3905
+ curve(12, 18, 8, 3, 0, Math.PI),
3906
+ { path: arcPath(12, 6, 8, 3, 0, Math.PI * 2), paint: "line", accent: true }
3907
+ ],
3908
+ queue: () => [stroke("M2.5 7H21.5"), stroke("M2.5 17H21.5"), slab(4.5, 9.2, 3.6, 5.6, 1), slab(10.2, 9.2, 3.6, 5.6, 1), slab(15.9, 9.2, 3.6, 5.6, 1, true)],
3909
+ cloud: () => [stroke("M7 18.5H17.3A4.3 4.3 0 0 0 17.9 10A6.2 6.2 0 0 0 6.2 9.4A4.6 4.6 0 0 0 7 18.5Z", true)],
3910
+ chip: () => [box(6, 6, 12, 12, 2), box(9.5, 9.5, 5, 5, 1, true), ...legs(6, [9, 12, 15])],
3911
+ // Machines
3912
+ vm: () => [
3913
+ { path: rectPath(3, 3, 18, 18, 3.2), paint: "line", dash: [1.6, 2.4] },
3914
+ box(7, 7.3, 10, 4, 1.2),
3915
+ box(7, 12.7, 10, 4, 1.2),
3916
+ disc(9.3, 9.3, 0.85, true),
3917
+ disc(9.3, 14.7, 0.85, true)
3918
+ ],
3919
+ process: () => [box(3, 4.5, 18, 15, 2.2), stroke("M3 9.2H21"), disc(6.2, 6.9, 0.9, true), disc(9, 6.9, 0.9, true), stroke("M7 13H13"), stroke("M7 16H16")],
3920
+ kernel: () => [stroke("M12 3 19.8 7.5V16.5L12 21 4.2 16.5V7.5Z"), disc(12, 12, 3, true)],
3921
+ memory: () => [
3922
+ box(2.5, 6.5, 19, 9.5, 1.6),
3923
+ ...[5.4, 9.5, 13.6, 17.7].map((x) => slab(x - 1.2, 9, 2.4, 4.4, 0.6, true)),
3924
+ ...[5, 8.5, 12, 15.5, 19].map((x) => stroke(`M${x} 16V18.8`))
3925
+ ],
3926
+ disk: () => [box(3, 3.5, 18, 17, 2.4), ring2(12, 10, 4.2), disc(12, 10, 1.1, true), stroke("M6.5 17H11.5"), disc(17, 17, 1, true)],
3927
+ nic: () => [box(3, 5, 18, 14, 2.2), stroke("M7.5 15V10.5H10V8.5H14V10.5H16.5V15Z", true)],
3928
+ network: () => [ring2(12, 12, 9), { path: arcPath(12, 12, 4, 9, 0, Math.PI * 2), paint: "line" }, stroke("M3 12H21", true)],
3929
+ snapshot: () => [stroke("M5.5 7H8L9.6 4.5H14.4L16 7H18.5A2.5 2.5 0 0 1 21 9.5V17A2.5 2.5 0 0 1 18.5 19.5H5.5A2.5 2.5 0 0 1 3 17V9.5A2.5 2.5 0 0 1 5.5 7Z"), ring2(12, 13, 3.6, true)],
3930
+ clone: () => [box(8.5, 3, 12.5, 12.5, 2.4), box(3, 8.5, 12.5, 12.5, 2.4, true)],
3931
+ jail: () => [box(4, 3.5, 16, 17, 2.2), stroke("M8 3.5V20.5", true), stroke("M12 3.5V20.5", true), stroke("M16 3.5V20.5", true)],
3932
+ wall: () => [
3933
+ box(3, 5, 18, 14, 1.4),
3934
+ stroke("M3 9.7H21"),
3935
+ stroke("M3 14.3H21"),
3936
+ ...["M9 5V9.7", "M15 5V9.7", "M6 9.7V14.3", "M12 9.7V14.3", "M18 9.7V14.3", "M9 14.3V19", "M15 14.3V19"].map((d) => stroke(d, true))
3937
+ ],
3938
+ key: () => [ring2(7.5, 12, 3.8), stroke("M11.3 12H21"), stroke("M17 12V15", true), stroke("M20.2 12V14.2", true)],
3939
+ stopwatch: () => [ring2(12, 13.5, 7.6), stroke("M10 2.8H14"), stroke("M12 2.8V5.9"), stroke("M12 13.5V9.4", true), stroke("M12 13.5 14.6 15.2", true)],
3940
+ bolt: () => [solid2("M13.2 2.5 5.5 13.6H11L9.9 21.5 18.5 10H12.6Z", true)],
3941
+ // The gate comes last, so the line that leaves it starts under its edge.
3942
+ proxy: () => [...arrowTo([3.3, 12], [7.7, 12], 0), ...arrowTo([16.3, 12], [21.5, 12], 0), box(8.5, 4.5, 7, 15, 1.8, true)],
3943
+ // The seal sits on the corner of the sheet, so the border stops short of it. The ring comes last, so the ribbon ends under it.
3944
+ certificate: () => [
3945
+ stroke("M11.5 15.5H4.5A2 2 0 0 1 2.5 13.5V5.5A2 2 0 0 1 4.5 3.5H19.5A2 2 0 0 1 21.5 5.5V8.4"),
3946
+ stroke("M6 7.5H14"),
3947
+ stroke("M6 11.5H11.5"),
3948
+ solid2("M14.8 16.4V21.4L17 19.6 19.2 21.4V16.4Z", true),
3949
+ ring2(17, 14, 3, true)
3950
+ ],
3951
+ // The box of `server` with its lights off, and a moon where the vents are.
3952
+ sleep: () => [box(2.5, 7, 19, 10, 2), disc(6, 12, 1.15), disc(9.4, 12, 1.15), solid2("M15.29 8.71A3.3 3.3 0 1 0 18.83 12.69A2.7 2.7 0 0 1 15.29 8.71Z", true)],
3953
+ shard,
3954
+ // Hardware
3955
+ core: () => [box(6, 6, 12, 12, 2), slab(8.3, 8.4, 3, 7.2, 1), slab(12.7, 8.4, 3, 7.2, 1, true), ...legs(6, [9, 12, 15])],
3956
+ timer: () => [box(5, 5, 14, 14, 2.2), ring2(12, 12, 4.2, true), stroke("M12 10.1V12L13.6 12.9", true), ...legs(7, [8.5, 12, 15.5])],
3957
+ firmware: () => [
3958
+ stroke("M5.1 7.5H18.9A1.6 1.6 0 0 1 20.5 9.1V14.9A1.6 1.6 0 0 1 18.9 16.5H5.1A1.6 1.6 0 0 1 3.5 14.9V13.8A1.8 1.8 0 0 0 3.5 10.2V9.1A1.6 1.6 0 0 1 5.1 7.5Z"),
3959
+ slab(7.8, 10.4, 10.2, 3.2, 0.8, true),
3960
+ ...[6, 9, 12, 15, 18].flatMap((x) => [stroke(`M${x} 4.3V7.5`), stroke(`M${x} 16.5V19.7`)])
3961
+ ],
3962
+ irqchip: () => [
3963
+ stroke("M2.5 8H4.4"),
3964
+ stroke("M2.5 12H4.4"),
3965
+ stroke("M2.5 16H4.4"),
3966
+ ...arrowTo([10.4, 12], [14.4, 12], 0),
3967
+ box(5.2, 4.5, 4.4, 15, 1.6, true),
3968
+ box(15.2, 9, 6, 6, 1.4),
3969
+ stroke("M16.7 9V7.2"),
3970
+ stroke("M19.7 9V7.2"),
3971
+ stroke("M16.7 15V16.8"),
3972
+ stroke("M19.7 15V16.8")
3973
+ ],
3974
+ // The bar comes last, so the taps end under it.
3975
+ bus: () => [
3976
+ stroke("M6.5 10.5V7.6"),
3977
+ box(4, 2.8, 5, 4.8, 1.2),
3978
+ stroke("M17.5 10.5V7.6"),
3979
+ box(15, 2.8, 5, 4.8, 1.2),
3980
+ stroke("M12 13.5V16.4"),
3981
+ box(9.5, 16.4, 5, 4.8, 1.2),
3982
+ slab(2.5, 10.5, 19, 3, 1.5, true)
3983
+ ],
3984
+ drive: () => [
3985
+ stroke("M19.8 8.2H5.4V15.8H19.8A1.2 1.2 0 0 0 21 14.6V13.8A1.8 1.8 0 0 1 21 10.2V9.4A1.2 1.2 0 0 0 19.8 8.2Z"),
3986
+ slab(7.8, 10.6, 5.2, 2.8, 0.6, true),
3987
+ slab(14.2, 10.6, 2.8, 2.8, 0.6, true),
3988
+ slab(2.4, 7.4, 3.8, 2.7, 0.5),
3989
+ slab(2.4, 11.3, 3.8, 5.3, 0.5)
3990
+ ],
3991
+ // The shutter comes first, so the outline stays whole where the shutter meets it.
3992
+ floppy: () => [
3993
+ stroke("M7.5 3.4V9.2H15.5V3.4", true),
3994
+ stroke("M12.9 5.6V6.6", true),
3995
+ stroke("M4.6 3H17L21 7V19.4A1.6 1.6 0 0 1 19.4 21H4.6A1.6 1.6 0 0 1 3 19.4V4.6A1.6 1.6 0 0 1 4.6 3Z"),
3996
+ stroke("M7 21V14.2H17V21")
3997
+ ],
3998
+ serial: () => [
3999
+ stroke("M5.6 6.5H18.4Q21.9 6.5 21 9.6L19.4 15.2Q18.7 17.5 16.3 17.5H7.7Q5.3 17.5 4.6 15.2L3 9.6Q2.1 6.5 5.6 6.5Z"),
4000
+ ...[6, 9, 12, 15, 18].map((x) => disc(x, 10.2, 1, true)),
4001
+ ...[7.5, 10.5, 13.5, 16.5].map((x) => disc(x, 13.9, 1, true))
4002
+ ],
4003
+ keyboard: () => [
4004
+ box(2.5, 5.5, 19, 13, 2.2),
4005
+ ...[7.7, 11].flatMap((y) => [4.4, 7.7, 11, 14.3, 17.6].map((x) => slab(x, y, 2, 2, 0.5, true))),
4006
+ slab(4.4, 14.3, 2, 2, 0.5, true),
4007
+ slab(7.7, 14.3, 8.6, 2, 0.5, true),
4008
+ slab(17.6, 14.3, 2, 2, 0.5, true)
4009
+ ],
4010
+ server: () => [box(2.5, 7, 19, 10, 2), disc(6, 12, 1.15, true), disc(9.4, 12, 1.15, true), ...[12.6, 15.5, 18.4].map((x) => stroke(`M${x} 10.2V13.8`))],
4011
+ // The deck comes last, so the sides of the screen end under it.
4012
+ laptop: () => [stroke("M5 17.8V7A1.8 1.8 0 0 1 6.8 5.2H17.2A1.8 1.8 0 0 1 19 7V17.8"), slab(2, 17, 20, 2.6, 1.3, true)],
4013
+ // Kernel
4014
+ thread: () => [
4015
+ stroke("M12 2.8C13.3 3.2 15 3.8 15 4.9C15 6.7 9 6.7 9 8.5C9 10.3 15 10.3 15 12.1C15 14.1 12 14.1 12 16.1V19", true),
4016
+ solid2("M12 21.6 10.5 19H13.5Z", true)
4017
+ ],
4018
+ interrupt: () => [
4019
+ stroke("M2.5 17.5H8.2"),
4020
+ ...arrowTo([14.8, 17.5], [21.5, 17.5], 0),
4021
+ stroke("M16.2 3.6 10.4 9.6H15.2", true),
4022
+ ...arrowTo([15.2, 9.6], [10.2, 20.4], 0, true)
4023
+ ],
4024
+ syscall: () => [stroke("M2.5 10H21.5"), stroke("M7.5 3.4V15.5A4.5 4.5 0 0 0 16.5 15.5", true), ...arrowTo([16.5, 15.5], [16.5, 2.6], 0, true)],
4025
+ ring: ringBuffer,
4026
+ page: () => [
4027
+ stroke("M3.5 3.5H16L20.5 8V20.5H3.5Z"),
4028
+ stroke("M16 3.5V8H20.5"),
4029
+ ...[6.2, 10.4].map((x) => slab(x, 7.2, 3.2, 2.4, 0.6, true)),
4030
+ ...[11.2, 15.2].flatMap((y) => [6.2, 10.4, 14.6].map((x) => slab(x, y, 3.2, 2.4, 0.6, true)))
4031
+ ],
4032
+ // The arrow and the fill come first, so the lines of the column stay whole over them.
4033
+ pagetable: () => [
4034
+ ...arrowTo([13, 9.75], [21.3, 9.75], 0, true),
4035
+ slab(4, 7.5, 9, 4.5, 0, true),
4036
+ box(4, 3, 9, 18, 1.8),
4037
+ stroke("M4 7.5H13"),
4038
+ stroke("M4 12H13"),
4039
+ stroke("M4 16.5H13")
4040
+ ],
4041
+ pin: () => [
4042
+ box(3.5, 13.2, 17, 7.8, 2),
4043
+ solid2("M8.6 2.2H15.4A1 1 0 0 1 15.4 4.2H14.4V6.6L16.9 9.4A1 1 0 0 1 16.2 11H7.8A1 1 0 0 1 7.1 9.4L9.6 6.6V4.2H8.6A1 1 0 0 1 8.6 2.2Z", true),
4044
+ stroke("M12 11V16.8", true)
4045
+ ],
4046
+ // Workflows
4047
+ // The arrow comes first, so it starts under the edge of the box. It ends on the edge.
4048
+ worker: () => [...arcArrow(15.5, 8.5, 5, Math.PI, Math.PI * 2.5 - 0.16, true), box(3, 8.5, 12.5, 12, 2.2)],
4049
+ workflow: () => [
4050
+ stroke("M8 4.6H17"),
4051
+ stroke("M11.5 9.6H21.5"),
4052
+ stroke("M11.5 14.4H18.5"),
4053
+ stroke("M8 19.4H13"),
4054
+ solid2("M2.5 7H7.4V12.4L4.95 10.6 2.5 12.4Z", true)
4055
+ ],
4056
+ activity: () => [box(3, 5, 13, 14, 2.2), ...arrowTo([7.5, 12], [21.5, 12], 0, true)],
4057
+ // signal, query, and update share one box. An arrow to the box is a write. An arrow back is an answer, and it is dashed for a read.
4058
+ // The box comes last, so an arrow back starts under its edge.
4059
+ signal: () => [...arrowTo([2.5, 12], [12.7, 12], 0, true), box(13.5, 4.5, 8, 15, 2)],
4060
+ query: () => [...arrowTo([2.5, 8.6], [12.7, 8.6], 0), dashed("M11.6 15.4H5.4", true), solid2("M2.5 15.4 4.7 14.2V16.6Z", true), box(13.5, 4.5, 8, 15, 2)],
4061
+ update: () => [...arrowTo([2.5, 8.6], [12.7, 8.6], 0, true), ...arrowTo([12.7, 15.4], [2.5, 15.4], 0), box(13.5, 4.5, 8, 15, 2)],
4062
+ // Code review
4063
+ issue: () => [box(2.5, 4, 19, 16, 2.2), ring2(8, 10.2, 2.6, true), disc(8, 10.2, 0.9, true), stroke("M13.6 10.2H18.6"), stroke("M5.6 16.2H18.6")],
4064
+ pullRequest: () => [
4065
+ ring2(6.5, 5.5, 2.4),
4066
+ stroke("M6.5 7.9V16.1"),
4067
+ ring2(6.5, 18.5, 2.4),
4068
+ ring2(17.5, 18.5, 2.4, true),
4069
+ stroke("M17.5 16.1V8.7A3.2 3.2 0 0 0 14.3 5.5H13.2", true),
4070
+ solid2("M10.8 5.5 13.2 4V7Z", true)
4071
+ ],
4072
+ repository: () => [
4073
+ stroke("M3 7A1.8 1.8 0 0 1 4.8 5.2H9.2L11.4 7.8H19.2A1.8 1.8 0 0 1 21 9.6V17.7A1.8 1.8 0 0 1 19.2 19.5H4.8A1.8 1.8 0 0 1 3 17.7Z"),
4074
+ stroke("M9 11.3V16.1", true),
4075
+ stroke("M14.8 11.9C14.8 14.4 9 13.6 9 16.1", true),
4076
+ disc(9, 11.3, 1.5, true),
4077
+ disc(9, 16.1, 1.5, true),
4078
+ disc(14.8, 11.9, 1.5, true)
4079
+ ],
4080
+ // The checks come last: each one is larger than its box.
4081
+ checklist: () => [
4082
+ ...[5.5, 12, 18.5].flatMap((y, i) => [box(3.4, y - 1.8, 3.6, 3.6, 0.9), stroke(`M11 ${y}H${i === 1 ? 18 : 20.5}`)]),
4083
+ stroke("M3.9 5.4 5.3 6.8 8.4 3.3", true),
4084
+ stroke("M3.9 11.9 5.3 13.3 8.4 9.8", true)
4085
+ ],
4086
+ approval: () => [ring2(8.4, 8.2, 3.3), curve(8.4, 20.5, 5.9, 6.4, Math.PI, Math.PI * 2), stroke("M14.8 8.4 17 10.6 21.2 5.8", true)],
4087
+ // Models
4088
+ model: () => [
4089
+ ...NET_IN.flatMap((a) => NET_MID.map((b) => ({ path: polyPath([a, b]), paint: "thin" }))),
4090
+ ...NET_MID.flatMap((a) => NET_OUT.map((b) => ({ path: polyPath([a, b]), paint: "thin" }))),
4091
+ ...NET_IN.map(([x, y]) => disc(x, y, 2)),
4092
+ ...NET_MID.map(([x, y]) => disc(x, y, 2, true)),
4093
+ ...NET_OUT.map(([x, y]) => disc(x, y, 2))
4094
+ ],
4095
+ tokens: () => [box(2.5, 8.8, 4.6, 6.4, 1.4), slab(8.6, 8.8, 7.4, 6.4, 1.4, true), box(17.5, 8.8, 4, 6.4, 1.4)],
4096
+ vector: () => [box(2.5, 8.5, 19, 7, 3.5), ...[6.6, 10.2, 13.8, 17.4].map((x) => disc(x, 12, 1.35, true))],
4097
+ agent: () => [
4098
+ box(5, 8, 14, 11.5, 2.6),
4099
+ disc(9.5, 13, 1.2, true),
4100
+ disc(14.5, 13, 1.2, true),
4101
+ stroke("M12 8V5"),
4102
+ disc(12, 3.8, 1.2),
4103
+ stroke("M2.8 12.5V15.5"),
4104
+ stroke("M21.2 12.5V15.5")
4105
+ ],
4106
+ spark: () => [solid2("M12 2.5C12.9 8.4 15.6 11.1 21.5 12C15.6 12.9 12.9 15.6 12 21.5C11.1 15.6 8.4 12.9 2.5 12C8.4 11.1 11.1 8.4 12 2.5Z", true)],
4107
+ // Work
4108
+ dashboard: () => [box(3, 4, 18, 13, 2.2), stroke("M12 17V21"), stroke("M8.5 21H15.5"), stroke("M6.5 12.5 9.5 9.5 12 11.5 15 8 17.5 10", true)],
4109
+ terminal: () => [box(2.5, 4.5, 19, 15, 2.2), stroke("M6.5 9.5 10 12.5 6.5 15.5", true), stroke("M12.5 15.5H17")],
4110
+ container: () => [stroke("M20 7.5V16.5L12 21 4 16.5V7.5"), stroke("M12 12V21"), stroke("M12 3 20 7.5 12 12 4 7.5Z", true)],
4111
+ experiment: () => [stroke("M9 3H15"), stroke("M10 3V9L4.6 18.8A1.5 1.5 0 0 0 5.9 21H18.1A1.5 1.5 0 0 0 19.4 18.8L14 9V3"), stroke("M7.6 15H16.4", true)],
4112
+ target: () => [ring2(12, 12, 9.2), ring2(12, 12, 5.2), disc(12, 12, 1.8, true)],
4113
+ loop: () => [...arcArrow(12, 12, 8, Math.PI * 1.08, Math.PI * 1.86), ...arcArrow(12, 12, 8, Math.PI * 0.08, Math.PI * 0.86, true)],
4114
+ eye: () => [stroke("M2.5 12C5 7.6 8.3 5.5 12 5.5S19 7.6 21.5 12C19 16.4 15.7 18.5 12 18.5S5 16.4 2.5 12Z"), ring2(12, 12, 3, true)],
4115
+ message: () => [stroke("M4.5 4.5H19.5A2 2 0 0 1 21.5 6.5V14.5A2 2 0 0 1 19.5 16.5H10.5L6 20.5V16.5H4.5A2 2 0 0 1 2.5 14.5V6.5A2 2 0 0 1 4.5 4.5Z"), stroke("M7 9H17", true), stroke("M7 12.5H13.5", true)],
4116
+ shield: () => [stroke("M12 3 20 6V11.5C20 16.4 16.6 19.8 12 21.5C7.4 19.8 4 16.4 4 11.5V6Z"), stroke("M8.4 12 11 14.6 15.8 9.6", true)],
4117
+ browser: () => [box(2.5, 3.5, 19, 17, 2.2), stroke("M2.5 9.6H21.5"), disc(5.9, 6.6, 0.95), slab(8.4, 5.4, 10.6, 2.4, 1.2, true)],
4118
+ desktop: () => [box(3, 4, 18, 13, 2.2), stroke("M12 17V21"), stroke("M8.5 21H15.5"), solid2("M9 6.2V14.2L11 12.4 12.4 15.2 13.9 14.5 12.5 11.7H15.2Z", true)],
4119
+ recording: () => [
4120
+ stroke("M3 8V5.5A2.5 2.5 0 0 1 5.5 3H8"),
4121
+ stroke("M16 3H18.5A2.5 2.5 0 0 1 21 5.5V8"),
4122
+ stroke("M21 16V18.5A2.5 2.5 0 0 1 18.5 21H16"),
4123
+ stroke("M8 21H5.5A2.5 2.5 0 0 1 3 18.5V16"),
4124
+ disc(12, 12, 3.6, true)
4125
+ ],
4126
+ // World
4127
+ // The stripe comes first, so the outline stays whole over its ends.
4128
+ creditCard: () => [slab(2.5, 8.6, 19, 3, 0, true), box(2.5, 5.5, 19, 13, 2.2), slab(5.6, 13.6, 3.8, 2.6, 0.6), stroke("M13.4 14.9H18")],
4129
+ warehouse: () => [
4130
+ stroke("M3 19.7V9.4L12 3.6 21 9.4V19.7"),
4131
+ stroke("M6.5 19.7V12H17.5V19.7"),
4132
+ slab(8.6, 17.9, 2.6, 2.6, 0.5, true),
4133
+ slab(12.8, 17.9, 2.6, 2.6, 0.5, true),
4134
+ slab(10.7, 14.3, 2.6, 2.6, 0.5, true)
4135
+ ],
4136
+ // The load comes after the cab, so its line stays whole where the cab meets it. The wheels come last and hide the lines behind them.
4137
+ truck: () => [stroke("M13.5 9H17.6L21.5 12.6V16.5H13.5"), stroke("M2.5 5.5H13.5V16.5H2.5Z", true), disc(6.6, 17.7, 2.3), disc(17.4, 17.7, 2.3)],
4138
+ microphone: () => [box(8.8, 2.8, 6.4, 11, 3.2, true), stroke("M5.5 10.5V11.3A6.5 6.5 0 0 0 18.5 11.3V10.5"), stroke("M12 17.8V21.2"), stroke("M8.5 21.2H15.5")],
4139
+ // The badge sits on the corner of the speech mark, so the outline stops short of it.
4140
+ forum: () => [
4141
+ stroke("M11.8 6.5H4.5A2 2 0 0 0 2.5 8.5V15.5A2 2 0 0 0 4.5 17.5H6V21L10.5 17.5H16.5A2 2 0 0 0 18.5 15.5V12"),
4142
+ solid2("M17.6 2.8 18.66 5.34 21.4 5.56 19.31 7.36 19.95 10.04 17.6 8.6 15.25 10.04 15.89 7.36 13.8 5.56 16.54 5.34Z", true)
4143
+ ],
4144
+ // The lock comes last and hides the lower half of the document.
4145
+ paywall: () => [
4146
+ stroke("M5.5 15V2.8H14.7L18.5 6.6V15"),
4147
+ stroke("M14.7 2.8V6.6H18.5"),
4148
+ stroke("M9.3 14.6V12.4A2.7 2.7 0 0 1 14.7 12.4V14.6", true),
4149
+ slab(4.4, 14.6, 15.2, 6.9, 1.8, true)
4150
+ ],
4151
+ // General
4152
+ document: () => [stroke("M6 3H14.5L19 7.5V21H6Z"), stroke("M14.5 3V7.5H19"), stroke("M9 12.5H16", true), stroke("M9 16.5H16", true)],
4153
+ code: () => [stroke("M8.5 7 3.5 12 8.5 17"), stroke("M15.5 7 20.5 12 15.5 17"), stroke("M13.6 5 10.4 19", true)],
4154
+ gear,
4155
+ clock: () => [ring2(12, 12, 9), stroke("M12 6.8V12L15.6 14.2", true)],
4156
+ user: () => [curve(12, 20.5, 7.6, 7.2, Math.PI, Math.PI * 2), ring2(12, 8, 3.7, true)],
4157
+ search: () => [ring2(10.5, 10.5, 6.6), stroke("M15.3 15.3 21 21", true)],
4158
+ filter: () => [disc(7, 3.7, 1.15), disc(12, 3.7, 1.15), disc(17, 3.7, 1.15), stroke("M3.5 7.6H20.5L14 14V17.4H10V14Z"), disc(12, 20.8, 1.15, true)],
4159
+ lock: () => [box(5, 10.5, 14, 10, 2.2), stroke("M8 10.5V7.5A4 4 0 0 1 16 7.5V10.5"), disc(12, 15.5, 1.3, true)],
4160
+ deploy: () => [stroke("M4 15V19.8H20V15"), stroke("M12 15.5V4", true), stroke("M7.5 8.5 12 4 16.5 8.5", true)],
4161
+ check: () => [stroke("M4.5 12.5 9.5 17.5 19.5 6.5", true)],
4162
+ cross: () => [stroke("M6 6 18 18", true), stroke("M18 6 6 18", true)],
4163
+ warning: () => [stroke("M12 3.5 21.5 20H2.5Z"), stroke("M12 9.5V14", true), disc(12, 17, 1, true)],
4164
+ question: () => [ring2(12, 12, 9.2), stroke("M9.3 9.6A2.8 2.8 0 1 1 13.5 12C12.5 12.6 12 13.2 12 14.4", true), disc(12, 17.3, 1, true)]
4165
+ };
4166
+ var PICTOGRAMS = Object.keys(ART);
4167
+ var Pictogram = class extends Node {
4168
+ constructor(name, options = {}) {
4169
+ super();
4170
+ this.name = name;
4171
+ objectName(this, "pictogram");
4172
+ if (!Object.hasOwn(ART, name)) throw new Error(`pictogram: unknown name ${JSON.stringify(name)}. Names: ${PICTOGRAMS.join(", ")}`);
4173
+ const size = options.size ?? 96, unit = size / GRID;
4174
+ const place2 = [unit, 0, 0, unit, -size / 2, -size / 2];
4175
+ this.size = size;
4176
+ this.layoutBox = [-size / 2, -size / 2, size / 2, size / 2];
4177
+ const draw2 = ART[name];
4178
+ const color = options.color ?? "ink", accent = options.accent ?? color;
4179
+ const weight = (options.weight ?? 1.6) * unit;
4180
+ for (const mark of draw2()) {
4181
+ const node = new Node(transformPath(mark.path, place2));
4182
+ const tone = mark.accent ? accent : color;
4183
+ if (mark.paint === "solid") node.fill(tone);
4184
+ else if (mark.paint === "soft") node.fill(tone, 0.24);
4185
+ else node.stroke(tone, mark.paint === "thin" ? weight * 0.5 : weight);
4186
+ if (mark.dash) node.dash(mark.dash.map((length) => length * unit));
4187
+ this.add(node);
4188
+ }
4189
+ this.named(`pictogram:${name}`);
4190
+ }
4191
+ name;
4192
+ /** The side of the square that holds the picture, in pixels. */
4193
+ size;
4194
+ };
4195
+ function pictogram(name, options = {}) {
4196
+ return new Pictogram(name, options);
4197
+ }
4198
+
2503
4199
  // src/stage/anim.ts
2504
- function list(target) {
2505
- return Array.isArray(target) ? [...target] : [target];
4200
+ function list(target, what = "an animation") {
4201
+ return nodesFor(what, target);
4202
+ }
4203
+ function middleOf(nodes) {
4204
+ const boxes = nodes.map((node) => node.bounds());
4205
+ const left = Math.min(...boxes.map((b) => b.x)), right = Math.max(...boxes.map((b) => b.x + b.width)), top = Math.min(...boxes.map((b) => b.y)), bottom = Math.max(...boxes.map((b) => b.y + b.height));
4206
+ return [(left + right) / 2, (top + bottom) / 2];
2506
4207
  }
2507
4208
  function run(anim, t0, t1, parent) {
2508
4209
  clock.now = t0;
@@ -2552,14 +4253,14 @@ function lagged(anims, options = {}) {
2552
4253
  }
2553
4254
  };
2554
4255
  }
2555
- function delay(anim, seconds) {
4256
+ function delay(anim, seconds2) {
2556
4257
  return {
2557
4258
  label: anim.label,
2558
- duration: anim.duration + seconds,
4259
+ duration: anim.duration + seconds2,
2559
4260
  ease: anim.ease,
2560
4261
  schedule(ctx) {
2561
- const k = anim.duration + seconds > 0 ? (ctx.t1 - ctx.t0) / (anim.duration + seconds) : 1;
2562
- run(anim, ctx.t0 + seconds * k, ctx.t1, ctx);
4262
+ const k = anim.duration + seconds2 > 0 ? (ctx.t1 - ctx.t0) / (anim.duration + seconds2) : 1;
4263
+ run(anim, ctx.t0 + seconds2 * k, ctx.t1, ctx);
2563
4264
  }
2564
4265
  };
2565
4266
  }
@@ -2601,7 +4302,7 @@ function valueAt(node, prop, t) {
2601
4302
  clock.now = previous;
2602
4303
  return value;
2603
4304
  }
2604
- function solid2(paint) {
4305
+ function solid3(paint) {
2605
4306
  return isGradient(paint) ? sampleStops(paint.stops, 0.5) : paint;
2606
4307
  }
2607
4308
  function drawable(target) {
@@ -2609,12 +4310,12 @@ function drawable(target) {
2609
4310
  }
2610
4311
  function drawLeaf(leaf, t0, t1, ease, outline) {
2611
4312
  const d = t1 - t0;
2612
- const fill = leaf.get("fill"), stroke = leaf.get("stroke");
4313
+ const fill = leaf.get("fill"), stroke2 = leaf.get("stroke");
2613
4314
  const fillTarget = leaf.get("fillOpacity");
2614
4315
  const strokeTarget = leaf.get("strokeOpacity");
2615
- if (fill && !stroke) {
4316
+ if (fill && !stroke2) {
2616
4317
  const width = valueAt(leaf, "strokeWidth", t0);
2617
- stepAt(leaf, "stroke", solid2(fill), t0);
4318
+ stepAt(leaf, "stroke", solid3(fill), t0);
2618
4319
  stepAt(leaf, "strokeWidth", outline, t0);
2619
4320
  stepAt(leaf, "strokeOpacity", 1, t0);
2620
4321
  stepAt(leaf, "trimTo", 0, t0);
@@ -2698,20 +4399,20 @@ function fadeIn(target, options = {}) {
2698
4399
  const lag = options.lag ?? 0;
2699
4400
  const each = (ctx.t1 - ctx.t0) / (1 + Math.max(0, items.length - 1) * lag);
2700
4401
  items.forEach((node, i) => {
2701
- const start = ctx.t0 + i * lag * each, end = start + each;
4402
+ const start = ctx.t0 + i * lag * each, end2 = start + each;
2702
4403
  clock.now = start;
2703
4404
  holdUntil(node, ctx.t0, start);
2704
4405
  const opacity = node.get("opacity");
2705
4406
  stepAt(node, "opacity", 0, start);
2706
- node.tween("opacity", opacity, start, end, ctx.ease);
4407
+ node.tween("opacity", opacity, start, end2, ctx.ease);
2707
4408
  if (options.shift) {
2708
4409
  const x = node.get("x"), y = node.get("y");
2709
4410
  stepAt(node, "x", x + options.shift[0], start);
2710
4411
  stepAt(node, "y", y + options.shift[1], start);
2711
- node.tween("x", x, start, end, ctx.ease);
2712
- node.tween("y", y, start, end, ctx.ease);
4412
+ node.tween("x", x, start, end2, ctx.ease);
4413
+ node.tween("y", y, start, end2, ctx.ease);
2713
4414
  }
2714
- if (options.scale !== void 0) scaleFrom(node, options.scale, start, end, ctx.ease);
4415
+ if (options.scale !== void 0) scaleFrom(node, options.scale, start, end2, ctx.ease);
2715
4416
  });
2716
4417
  clock.now = ctx.t0;
2717
4418
  }
@@ -2780,12 +4481,14 @@ function vanish(target) {
2780
4481
  } };
2781
4482
  }
2782
4483
  function to(node, change, options = {}) {
4484
+ const nodes = nodesFor("to", node, "the first argument");
4485
+ if (typeof change !== "function") throw new Error("to: the second argument is the change, a function such as (node) => node.shift(100, 0)");
2783
4486
  return {
2784
4487
  label: "to",
2785
4488
  duration: options.duration ?? 1,
2786
4489
  ease: options.ease,
2787
4490
  schedule(ctx) {
2788
- ensureVisible(node, ctx.t0, ctx.stage);
4491
+ for (const each of nodes) ensureVisible(each, ctx.t0, ctx.stage);
2789
4492
  const touched = /* @__PURE__ */ new Set();
2790
4493
  clock.capture = touched;
2791
4494
  try {
@@ -2806,46 +4509,75 @@ function applyChanges(node, values, ctx, restore) {
2806
4509
  const { t0, t1, ease } = ctx;
2807
4510
  const props = values;
2808
4511
  const restoreValues = /* @__PURE__ */ new Map();
2809
- const px = props.get("px"), py = props.get("py");
2810
- if (px !== void 0 || py !== void 0) {
2811
- const nextPx = px ?? node.get("px"), nextPy = py ?? node.get("py");
4512
+ const px2 = props.get("px"), py = props.get("py");
4513
+ let start = null;
4514
+ if (px2 !== void 0 || py !== void 0) {
4515
+ const nextPx = px2 ?? node.get("px"), nextPy = py ?? node.get("py");
2812
4516
  const m = compose(node.get("x"), node.get("y"), node.get("rotation"), node.get("sx"), node.get("sy"), node.get("px"), node.get("py"));
2813
4517
  const [startX, startY] = apply(m, nextPx, nextPy);
2814
4518
  stepAt(node, "px", nextPx, t0);
2815
4519
  stepAt(node, "py", nextPy, t0);
2816
- stepAt(node, "x", startX, t0);
2817
- stepAt(node, "y", startY, t0);
4520
+ node.track("x").stepUnder(t0, startX);
4521
+ node.track("y").stepUnder(t0, startY);
4522
+ start = { x: startX, y: startY };
2818
4523
  props.delete("px");
2819
4524
  props.delete("py");
2820
4525
  }
2821
4526
  clock.now = t0;
2822
4527
  for (const [prop, value] of props) {
2823
- const from = node.get(prop);
2824
- if (from === value) continue;
4528
+ const place2 = start && (prop === "x" || prop === "y") ? start[prop] : null;
4529
+ const from = place2 ?? node.get(prop);
4530
+ if (from === value || place2 !== null && Math.abs(place2 - value) < 1e-9) continue;
2825
4531
  if (restore) restoreValues.set(prop, from);
2826
4532
  node.tween(prop, value, t0, t1, ease);
2827
4533
  }
2828
4534
  for (const [prop, value] of restoreValues) stepAt(node, prop, value, t1);
2829
4535
  }
4536
+ function toEach(what, target, change, options) {
4537
+ const nodes = nodesFor(what, target, "the first argument");
4538
+ return { ...to(target, () => {
4539
+ for (const node of nodes) change(node, nodes);
4540
+ }, options), label: what === "scaleBy" ? "scale" : what };
4541
+ }
2830
4542
  function moveTo(node, target, options = {}) {
2831
- return { ...to(node, (n) => n.moveTo(target), options), label: "moveTo" };
4543
+ const nodes = nodesFor("moveTo", node, "the first argument");
4544
+ if (!(target instanceof Block)) nodeOrPoint("moveTo", target, "the place");
4545
+ if (node instanceof Node && !(target instanceof Block)) return { ...to(node, (n) => n.moveTo(target), options), label: "moveTo" };
4546
+ return {
4547
+ ...to(node, () => {
4548
+ const [x, y] = target instanceof Block ? middleOf(target.nodes) : target instanceof Node ? target.center : target;
4549
+ const [cx, cy] = middleOf(nodes);
4550
+ for (const each of nodes) each.moveTo([each.center[0] + x - cx, each.center[1] + y - cy]);
4551
+ }, options),
4552
+ label: "moveTo"
4553
+ };
2832
4554
  }
2833
4555
  function shift(node, dx, dy, options = {}) {
2834
- return { ...to(node, (n) => n.shift(dx, dy), options), label: "shift" };
4556
+ return toEach("shift", node, (n) => n.shift(dx, dy), options);
2835
4557
  }
2836
4558
  function scaleBy(node, factor, options = {}) {
2837
- return { ...to(node, (n) => n.scale(factor, options.about), options), label: "scale" };
4559
+ let about;
4560
+ return toEach("scaleBy", node, (n, all) => {
4561
+ if (n === all[0]) about = options.about ?? (all.length > 1 ? middleOf(all) : void 0);
4562
+ n.scale(factor, about);
4563
+ }, options);
2838
4564
  }
2839
4565
  function rotate(node, radians, options = {}) {
2840
- return { ...to(node, (n) => n.rotate(radians, options.about), options), label: "rotate" };
4566
+ let about;
4567
+ return toEach("rotate", node, (n, all) => {
4568
+ if (n === all[0]) about = options.about ?? (all.length > 1 ? middleOf(all) : void 0);
4569
+ n.rotate(radians, about);
4570
+ }, options);
2841
4571
  }
2842
4572
  function recolor(node, color, options = {}) {
2843
- return { ...to(node, (n) => n.color(color), options), label: "recolor" };
4573
+ return toEach("recolor", node, (n) => n.color(color), options);
2844
4574
  }
2845
4575
  function fade(node, opacity, options = {}) {
2846
- return { ...to(node, (n) => n.opacity(opacity), { duration: 0.6, ...options }), label: "fade" };
4576
+ return toEach("fade", node, (n) => n.opacity(opacity), { duration: 0.6, ...options });
2847
4577
  }
2848
4578
  function along2(node, track, options = {}) {
4579
+ oneNode("along", node, "the first argument");
4580
+ if (track instanceof Block) oneNode("along", track, "the track");
2849
4581
  return {
2850
4582
  label: "along",
2851
4583
  duration: options.duration ?? 2,
@@ -2890,7 +4622,7 @@ function warp(target, f, options = {}) {
2890
4622
  const world = leaf.worldMatrix();
2891
4623
  const inverse = invertSafe(world);
2892
4624
  const start = path.map((r) => subdivideEach(r, options.subdivisions ?? 6));
2893
- const end = warpPath(start, (x, y) => {
4625
+ const end2 = warpPath(start, (x, y) => {
2894
4626
  const [wx, wy] = apply(world, x, y);
2895
4627
  const [mx, my] = f(wx, wy);
2896
4628
  return apply(inverse, mx, my);
@@ -2899,9 +4631,9 @@ function warp(target, f, options = {}) {
2899
4631
  t0: ctx.t0,
2900
4632
  t1: ctx.t1,
2901
4633
  ease: ctx.ease,
2902
- to: end,
4634
+ to: end2,
2903
4635
  at: (alpha) => start.map((r, i) => {
2904
- const a = r.p, b = end[i].p;
4636
+ const a = r.p, b = end2[i].p;
2905
4637
  const out = new Float64Array(a.length);
2906
4638
  for (let k = 0; k < a.length; k++) out[k] = a[k] + (b[k] - a[k]) * alpha;
2907
4639
  return { p: out, closed: r.closed };
@@ -2956,6 +4688,7 @@ function bake(leaf) {
2956
4688
  }
2957
4689
  function ghost(stage, from, to2, ctx) {
2958
4690
  const node = new Node();
4691
+ node.data["decoration"] = true;
2959
4692
  node.base.visible = false;
2960
4693
  node.base.path = from.path;
2961
4694
  node.base.cap = from.cap;
@@ -3011,11 +4744,11 @@ function morph(from, to2, options = {}) {
3011
4744
  const pairs = pairCounts(fromLeaves, toLeaves);
3012
4745
  const lag = options.lag ?? 0;
3013
4746
  const each = (ctx.t1 - ctx.t0) / (1 + Math.max(0, pairs.length - 1) * lag);
3014
- pairs.forEach(([x, y], i) => {
4747
+ const ghosts = pairs.map(([x, y], i) => {
3015
4748
  const start = ctx.t0 + i * lag * each;
3016
- ghost(ctx.stage, x, y, { t0: start, t1: start + each, ease: ctx.ease, appear: ctx.t0, hide: ctx.t1 });
4749
+ return ghost(ctx.stage, x, y, { t0: start, t1: start + each, ease: ctx.ease, appear: ctx.t0, hide: ctx.t1 });
3017
4750
  });
3018
- finishMorph(a, b, ctx);
4751
+ finishMorph(a, b, ghosts, ctx);
3019
4752
  }
3020
4753
  };
3021
4754
  }
@@ -3026,12 +4759,15 @@ function prepareTargets(targets, ctx) {
3026
4759
  hideAt(node, ctx.t0);
3027
4760
  }
3028
4761
  }
3029
- function finishMorph(a, b, ctx) {
4762
+ function finishMorph(a, b, ghosts, ctx) {
3030
4763
  for (const node of a) hideAt(node, ctx.t0);
3031
4764
  for (const node of b) node.track("visible").step(ctx.t1, true);
4765
+ ctx.stage.morphs.push({ start: ctx.t0, end: ctx.t1, from: a, to: b, ghosts });
3032
4766
  clock.now = ctx.t0;
3033
4767
  }
3034
4768
  function morphMatching(from, to2, options = {}) {
4769
+ oneNode("morphMatching", from, "the first argument");
4770
+ oneNode("morphMatching", to2, "the second argument");
3035
4771
  return {
3036
4772
  label: "morphMatching",
3037
4773
  duration: options.duration ?? 1.4,
@@ -3043,41 +4779,203 @@ function morphMatching(from, to2, options = {}) {
3043
4779
  const fromBaked = fromLeaves.map(bake), toBaked = toLeaves.map(bake);
3044
4780
  const pairs = matchSequence(fromLeaves.map(keyOf), toLeaves.map(keyOf));
3045
4781
  const usedFrom = new Set(pairs.map(([i]) => i)), usedTo = new Set(pairs.map(([, j]) => j));
3046
- for (const [i, j] of pairs) ghost(ctx.stage, fromBaked[i], toBaked[j], ctx);
4782
+ const ghosts = pairs.map(([i, j]) => ghost(ctx.stage, fromBaked[i], toBaked[j], ctx));
3047
4783
  const span = ctx.t1 - ctx.t0;
3048
4784
  const offset = options.fadeShift ?? [0, 0];
3049
4785
  const shifted = (bakedPath, dx, dy) => transformPath(bakedPath, [1, 0, 0, 1, dx, dy]);
3050
4786
  fromBaked.forEach((baked, i) => {
3051
4787
  if (usedFrom.has(i)) return;
3052
- ghost(ctx.stage, baked, {
4788
+ ghosts.push(ghost(ctx.stage, baked, {
3053
4789
  ...baked,
3054
4790
  path: shifted(baked.path, offset[0], offset[1]),
3055
4791
  fillOpacity: 0,
3056
4792
  strokeOpacity: 0
3057
- }, { t0: ctx.t0, t1: ctx.t0 + span * 0.55, ease: ctx.ease });
4793
+ }, { t0: ctx.t0, t1: ctx.t0 + span * 0.55, ease: ctx.ease }));
3058
4794
  });
3059
4795
  toBaked.forEach((baked, j) => {
3060
4796
  if (usedTo.has(j)) return;
3061
- ghost(ctx.stage, {
4797
+ ghosts.push(ghost(ctx.stage, {
3062
4798
  ...baked,
3063
4799
  path: shifted(baked.path, -offset[0], -offset[1]),
3064
4800
  fillOpacity: 0,
3065
4801
  strokeOpacity: 0
3066
- }, baked, { t0: ctx.t0 + span * 0.35, t1: ctx.t1, ease: ctx.ease });
4802
+ }, baked, { t0: ctx.t0 + span * 0.35, t1: ctx.t1, ease: ctx.ease }));
3067
4803
  });
3068
- finishMorph([from], [to2], ctx);
4804
+ finishMorph([from], [to2], ghosts, ctx);
3069
4805
  }
3070
4806
  };
3071
4807
  }
3072
4808
  function indicate(target, options = {}) {
3073
- const nodes = list(target);
3074
- const anims = nodes.map((node) => retime(to(node, (n) => {
3075
- n.scale(options.scale ?? 1.14);
3076
- n.color(options.color ?? "yellow");
3077
- }, { restore: true }), { ease: options.ease ?? thereAndBack }));
3078
- return { ...par(...anims), label: "indicate", duration: options.duration ?? 0.9 };
4809
+ const nodes = list(target, "indicate");
4810
+ const color = options.color ?? "yellow";
4811
+ return {
4812
+ label: "indicate",
4813
+ duration: options.duration ?? 0.9,
4814
+ schedule(ctx) {
4815
+ let tint = (node) => {
4816
+ node.color(color);
4817
+ };
4818
+ if (!options.fill) {
4819
+ for (const node of nodes) ensureVisible(node, ctx.t0, ctx.stage);
4820
+ clock.now = ctx.t0;
4821
+ const plan = tintPlan(nodes, color, ctx.stage);
4822
+ tint = (node) => applyTint(node, plan);
4823
+ }
4824
+ const anims = nodes.map((node) => retime(to(node, (n) => {
4825
+ n.scale(options.scale ?? 1.14);
4826
+ tint(n);
4827
+ }, { restore: true }), { ease: options.ease ?? thereAndBack }));
4828
+ par(...anims).schedule(ctx);
4829
+ }
4830
+ };
4831
+ }
4832
+ var READABLE = 3;
4833
+ var SMALLER = 0.9;
4834
+ var isText = (node) => typeof node.source === "string" && (Array.isArray(node.chars) || Array.isArray(node.glyphs));
4835
+ function drawOrder(root) {
4836
+ const order = /* @__PURE__ */ new Map();
4837
+ const walk2 = (node) => {
4838
+ order.set(node, order.size);
4839
+ const children = node.children;
4840
+ if (children.length === 0) return;
4841
+ const sorted = children.some((child) => child.get("z") !== 0) ? children.map((child, index) => ({ child, index, z: child.get("z") })).sort((a, b) => a.z - b.z || a.index - b.index).map((entry) => entry.child) : children;
4842
+ for (const child of sorted) walk2(child);
4843
+ };
4844
+ walk2(root);
4845
+ return order;
4846
+ }
4847
+ function shownOpacity(node) {
4848
+ let opacity = 1;
4849
+ for (let up = node; up; up = up.parent) {
4850
+ if (!up.get("visible")) return 0;
4851
+ opacity *= up.get("opacity");
4852
+ }
4853
+ return opacity;
4854
+ }
4855
+ function tintPlan(targets, color, stage) {
4856
+ const paint = toPaint(color);
4857
+ const plan = { color, paint, parts: /* @__PURE__ */ new Map(), keepFill: /* @__PURE__ */ new Set(), keepPart: /* @__PURE__ */ new Set() };
4858
+ const order = drawOrder(stage.root);
4859
+ const backdrop = stage.backdrop;
4860
+ const seen = (value, alpha) => over(isGradient(value) ? sampleStops(value.stops, 0.5) : value, alpha, backdrop);
4861
+ const marks = (node, opacity) => {
4862
+ const stroke2 = node.get("stroke"), fill = node.get("fill");
4863
+ return [...stroke2 ? [seen(stroke2, node.get("strokeOpacity") * opacity)] : [], ...fill ? [seen(fill, node.get("fillOpacity") * opacity)] : []];
4864
+ };
4865
+ const add = (node, kind) => {
4866
+ const opacity = shownOpacity(node);
4867
+ const part = { node, kind, order: opacity > 2e-3 ? order.get(node) ?? Infinity : -1, bounds: { x: 0, y: 0, width: 0, height: 0 }, colors: [], fill: null, tints: true };
4868
+ plan.parts.set(node, part);
4869
+ if (part.order < 0) return;
4870
+ if (kind === "shape") {
4871
+ const path = node.get("path"), fill = node.get("fill");
4872
+ part.bounds = (path && pathBounds(transformPath(path, node.worldMatrix()))) ?? node.bounds();
4873
+ part.colors = [marks(node, opacity)];
4874
+ if (path && fill && node.data["key"] === void 0) part.fill = { color: seen(fill, node.get("fillOpacity") * opacity), alpha: node.get("fillOpacity") * opacity };
4875
+ return;
4876
+ }
4877
+ part.bounds = node.bounds();
4878
+ const built = node.draw ? node.draw(clock.now) : null;
4879
+ const drawn = node.draw ? built ? Array.isArray(built) ? built : [built] : [] : [node];
4880
+ part.tints = !node.draw;
4881
+ const leaves = drawn.flatMap((each) => each.all()).filter((each) => each.get("visible") && (each.get("stroke") || each.get("fill")));
4882
+ part.colors = (kind === "object" ? leaves.slice(0, 1) : leaves).map((each) => marks(each, opacity)).filter((list2) => list2.length > 0);
4883
+ };
4884
+ const visited = /* @__PURE__ */ new Set();
4885
+ const visit = (node) => {
4886
+ if (visited.has(node)) return;
4887
+ visited.add(node);
4888
+ if (node.color !== Node.prototype.color) return add(node, "object");
4889
+ if (isText(node) || node instanceof Pictogram || node.draw || node.rawOps) return add(node, "whole");
4890
+ if (node.get("stroke") || node.get("fill")) add(node, "shape");
4891
+ for (const child of node.children) visit(child);
4892
+ };
4893
+ for (const target of targets) visit(target);
4894
+ const shown = [...plan.parts.values()].filter((part) => part.order >= 0 && (part.bounds.width > 0 || part.bounds.height > 0)).sort((a, b) => a.order - b.order);
4895
+ const fills = shown.filter((part) => part.fill);
4896
+ const cell = Math.max(8, fills.reduce((sum, part) => sum + Math.max(part.bounds.width, part.bounds.height), 0) / Math.max(1, fills.length));
4897
+ const cells = /* @__PURE__ */ new Map(), wide = [];
4898
+ const key = (ix, iy) => ix * 1048576 + iy;
4899
+ const paths = /* @__PURE__ */ new Map();
4900
+ const holds = (fill, x, y) => {
4901
+ const b = fill.bounds;
4902
+ if (x < b.x || y < b.y || x > b.x + b.width || y > b.y + b.height) return false;
4903
+ let path = paths.get(fill);
4904
+ if (!path) paths.set(fill, path = transformPath(fill.node.get("path"), fill.node.worldMatrix()));
4905
+ return encloses(path, x, y);
4906
+ };
4907
+ const contents = /* @__PURE__ */ new Map();
4908
+ for (const part of shown) {
4909
+ const x = part.bounds.x + part.bounds.width / 2, y = part.bounds.y + part.bounds.height / 2, area = part.bounds.width * part.bounds.height;
4910
+ let backing = null;
4911
+ for (const fill of [...cells.get(key(Math.floor(x / cell), Math.floor(y / cell))) ?? [], ...wide]) {
4912
+ if ((!backing || fill.order > backing.order) && area < fill.bounds.width * fill.bounds.height * SMALLER && holds(fill, x, y)) backing = fill;
4913
+ }
4914
+ if (backing) {
4915
+ const on = contents.get(backing);
4916
+ if (on) on.push(part);
4917
+ else contents.set(backing, [part]);
4918
+ }
4919
+ if (!part.fill) continue;
4920
+ const b = part.bounds;
4921
+ const x0 = Math.floor(b.x / cell), x1 = Math.floor((b.x + b.width) / cell), y0 = Math.floor(b.y / cell), y1 = Math.floor((b.y + b.height) / cell);
4922
+ if ((x1 - x0 + 1) * (y1 - y0 + 1) > 1024) {
4923
+ wide.push(part);
4924
+ continue;
4925
+ }
4926
+ for (let ix = x0; ix <= x1; ix++) for (let iy = y0; iy <= y1; iy++) {
4927
+ const list2 = cells.get(key(ix, iy));
4928
+ if (list2) list2.push(part);
4929
+ else cells.set(key(ix, iy), [part]);
4930
+ }
4931
+ }
4932
+ const contrastOf = (part, against) => Math.min(Infinity, ...part.colors.map((list2) => Math.max(...list2.map((each) => contrast(each, against)))));
4933
+ const tintColor = seen(paint, 1);
4934
+ for (const [backing, on] of contents) {
4935
+ const fill = backing.fill;
4936
+ const tinted = seen(paint, fill.alpha);
4937
+ const onContent = Math.min(...on.map((part) => part.tints ? contrast(tintColor, fill.color) : contrastOf(part, fill.color)));
4938
+ const onBacking = Math.min(...on.map((part) => contrastOf(part, tinted)));
4939
+ const asItIs = Math.min(...on.map((part) => contrastOf(part, fill.color)));
4940
+ const best = Math.max(onContent, onBacking);
4941
+ if (best < READABLE && asItIs > best) {
4942
+ plan.keepFill.add(backing.node);
4943
+ for (const part of on) plan.keepPart.add(part.node);
4944
+ } else if (onBacking > onContent && !(onContent >= READABLE && fill.alpha < 1)) {
4945
+ for (const part of on) plan.keepPart.add(part.node);
4946
+ } else {
4947
+ plan.keepFill.add(backing.node);
4948
+ }
4949
+ }
4950
+ return plan;
4951
+ }
4952
+ function applyTint(target, plan) {
4953
+ const paint = plan.paint;
4954
+ const like = (old) => !isGradient(paint) && !isGradient(old) && old[3] < 1 ? [paint[0], paint[1], paint[2], old[3]] : paint;
4955
+ const tintNode = (node, withFill) => {
4956
+ const stroke2 = node.get("stroke"), fill = node.get("fill");
4957
+ if (stroke2) node.set("stroke", like(stroke2));
4958
+ if (fill && withFill) node.set("fill", like(fill));
4959
+ if (node.get("glowColor") && !isGradient(paint)) node.set("glowColor", paint);
4960
+ };
4961
+ const visit = (node) => {
4962
+ const part = plan.parts.get(node);
4963
+ if (part) {
4964
+ if (!plan.keepPart.has(node)) {
4965
+ if (part.kind === "object") node.color(plan.color);
4966
+ else if (part.kind === "shape") tintNode(node, !plan.keepFill.has(node));
4967
+ else for (const each of node.all()) tintNode(each, true);
4968
+ }
4969
+ if (part.kind !== "shape") return;
4970
+ } else if (node.get("glowColor") && !isGradient(paint)) {
4971
+ node.set("glowColor", paint);
4972
+ }
4973
+ for (const child of node.children) visit(child);
4974
+ };
4975
+ visit(target);
3079
4976
  }
3080
4977
  function shake(node, options = {}) {
4978
+ oneNode("shake", node, "the first argument");
3081
4979
  return {
3082
4980
  label: "shake",
3083
4981
  duration: options.duration ?? 0.8,
@@ -3094,6 +4992,7 @@ function shake(node, options = {}) {
3094
4992
  };
3095
4993
  }
3096
4994
  function circumscribe(target, options = {}) {
4995
+ oneNode("circumscribe", target, "the first argument");
3097
4996
  return {
3098
4997
  label: "circumscribe",
3099
4998
  duration: options.duration ?? 1.3,
@@ -3102,7 +5001,9 @@ function circumscribe(target, options = {}) {
3102
5001
  const b = target.bounds();
3103
5002
  const pad = options.pad ?? 14;
3104
5003
  const outline = new Node(rectPath(b.x - pad, b.y - pad, b.width + pad * 2, b.height + pad * 2, options.radius ?? 12)).stroke(options.color ?? "yellow", options.width ?? 3).glow(8);
5004
+ outline.data["decoration"] = true;
3105
5005
  ctx.stage.add(outline);
5006
+ ctx.stage.marks.set(outline, target);
3106
5007
  const t0 = ctx.t0, t1 = ctx.t1, mid = t0 + (t1 - t0) * 0.55;
3107
5008
  stepAt(outline, "trimTo", 0, t0);
3108
5009
  outline.tween("trimTo", 1, t0, mid, smooth);
@@ -3111,7 +5012,12 @@ function circumscribe(target, options = {}) {
3111
5012
  }
3112
5013
  };
3113
5014
  }
5015
+ function markOf(ctx, mark, target) {
5016
+ if (target instanceof Node) ctx.stage.marks.set(mark, target);
5017
+ else ctx.stage.arrivals.set(mark, ctx.t0);
5018
+ }
3114
5019
  function flash(point, options = {}) {
5020
+ nodeOrPoint("flash", point, "the first argument");
3115
5021
  return {
3116
5022
  label: "flash",
3117
5023
  duration: options.duration ?? 0.7,
@@ -3125,6 +5031,7 @@ function flash(point, options = {}) {
3125
5031
  const cos = Math.cos(angle), sin = Math.sin(angle);
3126
5032
  const ray = new Node(linePath([center[0] + cos * radius * 0.35, center[1] + sin * radius * 0.35], [center[0] + cos * radius, center[1] + sin * radius])).stroke(options.color ?? "yellow", 2.5).glow(5);
3127
5033
  ctx.stage.add(ray);
5034
+ markOf(ctx, ray, point);
3128
5035
  stepAt(ray, "trimTo", 0, ctx.t0);
3129
5036
  ray.tween("trimTo", 1, ctx.t0, ctx.t0 + (ctx.t1 - ctx.t0) * 0.6, ctx.ease);
3130
5037
  ray.tween("trimFrom", 1, ctx.t0 + (ctx.t1 - ctx.t0) * 0.25, ctx.t1, ctx.ease);
@@ -3134,24 +5041,27 @@ function flash(point, options = {}) {
3134
5041
  };
3135
5042
  }
3136
5043
  function ripple(point, options = {}) {
5044
+ nodeOrPoint("ripple", point, "the first argument");
3137
5045
  return {
3138
5046
  label: "ripple",
3139
5047
  duration: options.duration ?? 1,
3140
5048
  ease: options.ease ?? smooth,
3141
5049
  schedule(ctx) {
3142
5050
  const center = point instanceof Node ? point.center : point;
3143
- const ring2 = new Node(circlePath(0, 0, options.radius ?? 90)).stroke(options.color ?? "blue", options.width ?? 3).at(center);
3144
- ctx.stage.add(ring2);
3145
- stepAt(ring2, "sx", 0.05, ctx.t0);
3146
- stepAt(ring2, "sy", 0.05, ctx.t0);
3147
- ring2.tween("sx", 1, ctx.t0, ctx.t1, ctx.ease);
3148
- ring2.tween("sy", 1, ctx.t0, ctx.t1, ctx.ease);
3149
- ring2.tween("strokeOpacity", 0, ctx.t0 + (ctx.t1 - ctx.t0) * 0.2, ctx.t1, ctx.ease);
3150
- hideAt(ring2, ctx.t1);
5051
+ const ring3 = new Node(circlePath(0, 0, options.radius ?? 90)).stroke(options.color ?? "blue", options.width ?? 3).at(center);
5052
+ ctx.stage.add(ring3);
5053
+ markOf(ctx, ring3, point);
5054
+ stepAt(ring3, "sx", 0.05, ctx.t0);
5055
+ stepAt(ring3, "sy", 0.05, ctx.t0);
5056
+ ring3.tween("sx", 1, ctx.t0, ctx.t1, ctx.ease);
5057
+ ring3.tween("sy", 1, ctx.t0, ctx.t1, ctx.ease);
5058
+ ring3.tween("strokeOpacity", 0, ctx.t0 + (ctx.t1 - ctx.t0) * 0.2, ctx.t1, ctx.ease);
5059
+ hideAt(ring3, ctx.t1);
3151
5060
  }
3152
5061
  };
3153
5062
  }
3154
5063
  function pulse(line, options = {}) {
5064
+ oneNode("pulse", line, "the first argument");
3155
5065
  return {
3156
5066
  label: "pulse",
3157
5067
  duration: options.duration ?? 1.1,
@@ -3161,6 +5071,7 @@ function pulse(line, options = {}) {
3161
5071
  if (!path) return;
3162
5072
  const lit = new Node(transformPath(path, line.worldMatrix())).stroke(options.color ?? "yellow", options.width ?? line.get("strokeWidth") + 1.5).glow(options.glow ?? 10);
3163
5073
  ctx.stage.add(lit);
5074
+ ctx.stage.marks.set(lit, line);
3164
5075
  const length = options.length ?? 0.18;
3165
5076
  stepAt(lit, "trimFrom", 0, ctx.t0);
3166
5077
  stepAt(lit, "trimTo", 0, ctx.t0);
@@ -3198,6 +5109,14 @@ var Value = class {
3198
5109
  };
3199
5110
 
3200
5111
  // src/stage/stage.ts
5112
+ function backdropOf(background, look) {
5113
+ const colors = look.colors;
5114
+ try {
5115
+ return parseColor(colors[background] ?? background);
5116
+ } catch {
5117
+ return parseColor(colors["bg"]);
5118
+ }
5119
+ }
3201
5120
  var ASPECTS = {
3202
5121
  "16:9": [1920, 1080],
3203
5122
  "9:16": [1080, 1920],
@@ -3205,6 +5124,7 @@ var ASPECTS = {
3205
5124
  "4:3": [1440, 1080],
3206
5125
  "21:9": [2520, 1080]
3207
5126
  };
5127
+ var FONTS = Object.keys({ sans: true, serif: true, "text-serif": true, mono: true, noto: true });
3208
5128
  var Stage = class {
3209
5129
  root = new Node();
3210
5130
  /** Move, zoom, and rotate the view with to(s.camera, ...). `sx` is the zoom. */
@@ -3213,10 +5133,33 @@ var Stage = class {
3213
5133
  height;
3214
5134
  fps;
3215
5135
  look;
5136
+ /** The font that the film names for its texts, or null when it names none. A text with no font is then sans. */
5137
+ font;
3216
5138
  chapters = [];
3217
5139
  clips = [];
3218
5140
  captions = [];
3219
5141
  updaters = [];
5142
+ /** The lights that `spotlight` added. `settleLights` turns them into the `dim` of each node, in time order. */
5143
+ lights = [];
5144
+ /**
5145
+ * Three records for the lights, of facts that the timeline does not hold. Only a film with a light reads
5146
+ * them, so they change nothing in a film with none.
5147
+ * `arrivals` is the time at which a verb brought a node to the stage: a node that arrives at the very
5148
+ * time of a light enters with it, and at time 0 the timeline cannot tell it from a node of `s.add`.
5149
+ * `marks` is the node that a mark of a verb belongs to, such as the line of `circumscribe` and its
5150
+ * target: the mark is as bright as that node.
5151
+ * `morphs` is each morph with its nodes: a light must not dim a node while it changes its shape.
5152
+ */
5153
+ arrivals = /* @__PURE__ */ new WeakMap();
5154
+ marks = /* @__PURE__ */ new Map();
5155
+ morphs = [];
5156
+ /** The color that a dim node goes toward: the background of the film, or of its look when the film has none. */
5157
+ backdrop;
5158
+ /**
5159
+ * Checks that run when the timeline is complete, in order. The clock of a narrated scene adds one: it
5160
+ * asks then what was on the stage at each of its cues. A check that fails throws, and the film does not build.
5161
+ */
5162
+ checks = [];
3220
5163
  time = 0;
3221
5164
  ending = 0;
3222
5165
  constructor(options) {
@@ -3225,6 +5168,11 @@ var Stage = class {
3225
5168
  this.height = options.height ?? h;
3226
5169
  this.fps = options.fps ?? 60;
3227
5170
  this.look = resolveLook(options.look);
5171
+ if (options.font !== void 0 && !FONTS.includes(options.font)) {
5172
+ throw new Error(`film: font is ${FONTS.map((name) => `'${name}'`).join(", ").replace(/, ([^,]*)$/, " or $1")}, not ${JSON.stringify(options.font)}`);
5173
+ }
5174
+ this.font = options.font ?? null;
5175
+ this.backdrop = backdropOf(options.background ?? this.look.background, this.look);
3228
5176
  this.root.mounted = true;
3229
5177
  this.camera.mounted = true;
3230
5178
  }
@@ -3241,10 +5189,26 @@ var Stage = class {
3241
5189
  get bottom() {
3242
5190
  return this.height / 2;
3243
5191
  }
3244
- /** Put nodes on stage now. Returns the first, so setup reads as one line. */
5192
+ /**
5193
+ * Take the clock for this film. Each call that the callback makes on its stage starts here. When the
5194
+ * callbacks of two films await, they take turns, and the other film has put its own font on the clock
5195
+ * since the last call. A stage whose callback does not run leaves the clock alone.
5196
+ */
5197
+ claim() {
5198
+ if (building(this)) {
5199
+ setColorTokens(this.look.colors);
5200
+ clock.font = this.font;
5201
+ clock.canvas = this;
5202
+ }
5203
+ }
5204
+ /**
5205
+ * Put nodes on stage now. A block of the layout, and a list that the layout placed, put their nodes there:
5206
+ * `s.add(place(row([a, b]), region))`. Returns the first, so setup reads as one line.
5207
+ */
3245
5208
  add(first, ...rest) {
5209
+ this.claim();
3246
5210
  clock.now = this.time;
3247
- for (const node of [first, ...rest]) {
5211
+ for (const node of [first, ...rest].flatMap((item, index) => nodesFor("s.add", item, `argument ${index}`))) {
3248
5212
  if (!node.mounted) {
3249
5213
  node.parent?.drop(node);
3250
5214
  node.parent = this.root;
@@ -3258,17 +5222,26 @@ var Stage = class {
3258
5222
  }
3259
5223
  /** Put a node on stage so it first shows at `time`, which may differ from the cursor. */
3260
5224
  mountAt(node, time) {
5225
+ this.claim();
5226
+ oneNode("s.mountAt", node);
3261
5227
  if (node.mounted) return;
3262
5228
  node.parent?.drop(node);
3263
5229
  node.parent = this.root;
3264
5230
  this.root.children.push(node);
3265
5231
  mountTree(node, time);
5232
+ this.arrivals.set(node, time);
3266
5233
  }
3267
5234
  remove(...nodes) {
3268
- for (const node of nodes) node.track("visible").step(this.time, false);
5235
+ this.claim();
5236
+ for (const node of nodes.flatMap((item, index) => nodesFor("s.remove", item, `argument ${index}`))) node.track("visible").step(this.time, false);
3269
5237
  }
3270
5238
  /** Run animations together and advance the timeline past them. */
3271
5239
  play(...items) {
5240
+ this.claim();
5241
+ items.forEach((item, index) => {
5242
+ if (item instanceof Node || item instanceof Block) throw new Error(`s.play: argument ${index} is ${item instanceof Node ? "a node" : "a block of the layout"}, and play takes animations. Give an animation of it, such as fadeIn(${item instanceof Node ? "node" : "block"}), or put it on the stage with s.add`);
5243
+ if (typeof item !== "object" || item === null) throw new Error(`s.play: argument ${index} is ${String(item)}. Give animations, such as fadeIn(node), and then the options of the play`);
5244
+ });
3272
5245
  const anims = items.filter((item) => "schedule" in item);
3273
5246
  const options = items.find((item) => !("schedule" in item)) ?? {};
3274
5247
  if (anims.length === 0) return this;
@@ -3278,8 +5251,8 @@ var Stage = class {
3278
5251
  const t1 = t0 + duration;
3279
5252
  for (const anim of anims) {
3280
5253
  clock.now = t0;
3281
- const end = options.duration !== void 0 ? t1 : t0 + anim.duration;
3282
- anim.schedule({ t0, t1: end, ease: options.ease ?? anim.ease ?? smooth, stage: this });
5254
+ const end2 = options.duration !== void 0 ? t1 : t0 + anim.duration;
5255
+ anim.schedule({ t0, t1: end2, ease: options.ease ?? anim.ease ?? smooth, stage: this });
3283
5256
  }
3284
5257
  this.clips.push({ t0, t1, labels: options.label ? [options.label] : anims.map((anim) => anim.label) });
3285
5258
  this.time = t1;
@@ -3288,14 +5261,16 @@ var Stage = class {
3288
5261
  return this;
3289
5262
  }
3290
5263
  /** Hold on the current picture. */
3291
- wait(seconds = 1) {
3292
- this.time += seconds;
5264
+ wait(seconds2 = 1) {
5265
+ this.claim();
5266
+ this.time += seconds2;
3293
5267
  this.ending = Math.max(this.ending, this.time);
3294
5268
  clock.now = this.time;
3295
5269
  return this;
3296
5270
  }
3297
5271
  /** Author something at another time, then return to where you were. */
3298
5272
  at(time, build) {
5273
+ this.claim();
3299
5274
  const saved = this.time;
3300
5275
  this.time = time;
3301
5276
  clock.now = time;
@@ -3307,21 +5282,26 @@ var Stage = class {
3307
5282
  }
3308
5283
  /** Mark a chapter for the player, presentation steps, and the timeline. */
3309
5284
  chapter(title) {
5285
+ this.claim();
3310
5286
  this.chapters.push({ title, time: this.time });
3311
5287
  return this;
3312
5288
  }
3313
5289
  /** Show a caption for a span of time. Captions also export as a VTT sidecar. */
3314
5290
  caption(text2, duration = 3) {
5291
+ this.claim();
3315
5292
  this.captions.push({ t0: this.time, t1: this.time + duration, text: text2 });
3316
5293
  this.ending = Math.max(this.ending, this.time + duration);
3317
5294
  return this;
3318
5295
  }
3319
5296
  /** A number that animates, for driving dynamic drawings. */
3320
5297
  value(initial = 0) {
5298
+ this.claim();
3321
5299
  return new Value(initial);
3322
5300
  }
3323
5301
  /** Re-run a function each frame while the node shows. It can set any property on the node. */
3324
5302
  update(node, fn, window2 = {}) {
5303
+ this.claim();
5304
+ oneNode("s.update", node);
3325
5305
  this.updaters.push({
3326
5306
  node,
3327
5307
  fn,
@@ -3356,6 +5336,14 @@ var Suspend = class {
3356
5336
  promise;
3357
5337
  /** Lets a second copy of the engine recognize this without instanceof. */
3358
5338
  isVizmaticSuspend = true;
5339
+ /**
5340
+ * What a tool prints when this leaves the compiler: a text at the top of a film file throws it when the
5341
+ * file loads, and a second copy of the engine throws one that this copy does not know.
5342
+ */
5343
+ message = 'vizmatic needs a font, the math engine or another asset that is not loaded yet. A film loads them while its callback runs, and then runs the callback again. Make each text, equation and graph inside the callback of film(), not at the top of a file. If they are inside the callback, the film file and a file that it imports use two copies of vizmatic: give the folder of the film a package.json with "type": "module".';
5344
+ toString() {
5345
+ return this.message;
5346
+ }
3359
5347
  };
3360
5348
  function isSuspend(error) {
3361
5349
  return typeof error === "object" && error !== null && error.isVizmaticSuspend === true;
@@ -3413,6 +5401,9 @@ var CompiledFilm = class {
3413
5401
  pending2 = resolveLegacyImage(image.src, this.allowImageNetwork).then((asset2) => {
3414
5402
  this.imageAssets.set(image.src, asset2);
3415
5403
  return asset2;
5404
+ }).catch((error) => {
5405
+ this.imageLoads.delete(image.src);
5406
+ throw error;
3416
5407
  });
3417
5408
  this.imageLoads.set(image.src, pending2);
3418
5409
  }
@@ -3432,10 +5423,12 @@ var CompiledFilm = class {
3432
5423
  frame(time) {
3433
5424
  const t = Math.max(0, Math.min(this.duration, time));
3434
5425
  const stage = this.stage;
3435
- const previous = { mode: clock.mode, now: clock.now };
5426
+ const previous = { mode: clock.mode, now: clock.now, font: clock.font, canvas: clock.canvas, colors: getColorTokens() };
3436
5427
  setColorTokens(stage.look.colors);
3437
5428
  clock.mode = "render";
3438
5429
  clock.now = t;
5430
+ clock.font = stage.font;
5431
+ clock.canvas = stage;
3439
5432
  clock.frame++;
3440
5433
  try {
3441
5434
  for (const updater of stage.updaters) {
@@ -3447,7 +5440,7 @@ var CompiledFilm = class {
3447
5440
  y: camera.get("y"),
3448
5441
  zoom: camera.get("sx"),
3449
5442
  rotation: camera.get("rotation")
3450
- }, stage.width, stage.height);
5443
+ }, stage.width, stage.height, stage.backdrop, stage.lights.length > 0 ? stage.marks : null);
3451
5444
  const preparedOps = ops.map((op) => {
3452
5445
  if (op.kind !== "image") return op;
3453
5446
  const asset = op.image.asset ?? this.imageAssets.get(op.image.src);
@@ -3458,8 +5451,11 @@ var CompiledFilm = class {
3458
5451
  });
3459
5452
  return { width: stage.width, height: stage.height, background: this.background, bloom: this.bloom, dark: stage.look.dark, ops: preparedOps };
3460
5453
  } finally {
5454
+ setColorTokens(previous.colors);
3461
5455
  clock.mode = previous.mode;
3462
5456
  clock.now = previous.now;
5457
+ clock.font = previous.font;
5458
+ clock.canvas = previous.canvas;
3463
5459
  }
3464
5460
  }
3465
5461
  /** Standalone SVG for a time. */
@@ -3467,30 +5463,73 @@ var CompiledFilm = class {
3467
5463
  return frameToSvg(this.frame(time), options);
3468
5464
  }
3469
5465
  };
5466
+ var builds = [];
5467
+ function building(stage) {
5468
+ return builds.some((build) => build.stage === stage);
5469
+ }
5470
+ function begin(stage) {
5471
+ const build = {
5472
+ stage,
5473
+ found: { mode: clock.mode, now: clock.now, font: clock.font, canvas: clock.canvas, colors: getColorTokens() }
5474
+ };
5475
+ builds.push(build);
5476
+ setColorTokens(stage.look.colors);
5477
+ clock.mode = "compile";
5478
+ clock.now = 0;
5479
+ clock.font = stage.font;
5480
+ clock.canvas = stage;
5481
+ return build;
5482
+ }
5483
+ function end(build) {
5484
+ const index = builds.indexOf(build);
5485
+ if (index < 0) return;
5486
+ builds.splice(index, 1);
5487
+ const later = builds[index];
5488
+ if (!later) {
5489
+ setColorTokens(build.found.colors);
5490
+ clock.mode = build.found.mode;
5491
+ clock.now = build.found.now;
5492
+ clock.font = build.found.font;
5493
+ clock.canvas = build.found.canvas;
5494
+ return;
5495
+ }
5496
+ later.found = build.found;
5497
+ const current = builds[builds.length - 1].stage;
5498
+ setColorTokens(current.look.colors);
5499
+ clock.font = current.font;
5500
+ clock.canvas = current;
5501
+ }
5502
+ var TWO_ENGINES = 'Two copies of vizmatic/stage built this film, so a part of it is on another timeline. The usual cause is a film of several files in a folder with no "type": "module" in its package.json: one file then loads the package as CommonJS and another as an ES module. Add "type": "module" to the package.json beside the film.';
3470
5503
  async function compileFilm(definition, overrides = {}) {
3471
- const options = { ...definition.options, ...overrides.look ? { look: overrides.look } : {}, ...overrides.fps ? { fps: overrides.fps } : {} };
5504
+ const options = {
5505
+ ...definition.options,
5506
+ ...overrides.look ? { look: overrides.look } : {},
5507
+ ...overrides.fps ? { fps: overrides.fps } : {},
5508
+ // The stage needs the background too: a light dims a node toward it.
5509
+ ...overrides.background !== void 0 ? { background: overrides.background } : {}
5510
+ };
3472
5511
  for (let attempt = 0; attempt < 64; attempt++) {
3473
5512
  const stage = new Stage(options);
3474
- setColorTokens(stage.look.colors);
3475
- const saved = { mode: clock.mode, now: clock.now };
3476
- clock.mode = "compile";
3477
- clock.now = 0;
5513
+ const build = begin(stage);
3478
5514
  try {
3479
- await definition.build(stage);
3480
- clock.mode = saved.mode;
3481
- clock.now = saved.now;
5515
+ const pending2 = definition.build(stage);
5516
+ if (pending2 !== null && typeof pending2 === "object" && typeof pending2.then === "function") await pending2;
5517
+ setColorTokens(stage.look.colors);
5518
+ for (const check of stage.checks) check();
5519
+ settleLights(stage);
3482
5520
  const compiled = new CompiledFilm(stage, options, overrides);
5521
+ end(build);
3483
5522
  await compiled.preloadImages();
3484
5523
  await probe(compiled);
3485
5524
  return compiled;
3486
5525
  } catch (error) {
3487
- clock.mode = saved.mode;
3488
- clock.now = saved.now;
5526
+ end(build);
3489
5527
  clock.capture = null;
3490
5528
  if (error instanceof Suspend) {
3491
5529
  await error.promise;
3492
5530
  continue;
3493
5531
  }
5532
+ if (isSuspend(error)) throw new Error(TWO_ENGINES);
3494
5533
  throw error;
3495
5534
  }
3496
5535
  }
@@ -3511,49 +5550,6 @@ async function probe(film2) {
3511
5550
  }
3512
5551
  }
3513
5552
 
3514
- // src/stage/assets.ts
3515
- var assetBase = null;
3516
- function setAssetBase(url) {
3517
- assetBase = url;
3518
- }
3519
- var isNode = typeof process !== "undefined" && !!process.versions?.node && typeof globalThis.document === "undefined";
3520
- function moduleUrl() {
3521
- const url = import.meta.url;
3522
- if (url) return url;
3523
- return `file://${typeof __filename !== "undefined" ? __filename : ""}`;
3524
- }
3525
- async function nodeRead(relative) {
3526
- const fsName = "node:fs/promises", pathName = "node:path", urlName = "node:url";
3527
- const [fs, path, url] = await Promise.all([import(fsName), import(pathName), import(urlName)]);
3528
- let directory = path.dirname(url.fileURLToPath(moduleUrl()));
3529
- for (let depth = 0; depth < 6; depth++) {
3530
- const candidate = path.join(directory, "assets", relative);
3531
- try {
3532
- const bytes = await fs.readFile(candidate);
3533
- return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
3534
- } catch (error) {
3535
- if (error.code !== "ENOENT") throw error;
3536
- }
3537
- directory = path.dirname(directory);
3538
- }
3539
- throw new Error(`Bundled asset not found: assets/${relative}`);
3540
- }
3541
- async function loadBinaryAsset(relative) {
3542
- if (isNode) return nodeRead(relative);
3543
- const base = assetBase ?? new URL("./assets/", moduleUrl()).href;
3544
- const response = await fetch(new URL(relative, base));
3545
- const type = response.headers.get("content-type") ?? "";
3546
- if (!response.ok || type.includes("text/html")) {
3547
- throw new Error(`Could not load ${relative} from ${response.url} (HTTP ${response.status}, ${type || "no content type"}). Call setAssetBase() with the folder that holds fonts/.`);
3548
- }
3549
- return response.arrayBuffer();
3550
- }
3551
-
3552
- // src/stage/font-types.ts
3553
- function curveFree(contours) {
3554
- return { contours: contours.filter((contour) => contour.length >= 8) };
3555
- }
3556
-
3557
5553
  // src/stage/font.ts
3558
5554
  var Reader = class {
3559
5555
  constructor(bytes, offset = 0) {
@@ -3642,16 +5638,16 @@ function parseFont(bytes) {
3642
5638
  return r.u16();
3643
5639
  };
3644
5640
  const outlines = /* @__PURE__ */ new Map();
3645
- const contours = (glyph, depth) => {
3646
- if (glyph >= glyphCount || depth > 6) return [];
5641
+ const contours = (glyph, depth2) => {
5642
+ if (glyph >= glyphCount || depth2 > 6) return [];
3647
5643
  r.seek(loca.offset + (longLoca ? glyph * 4 : glyph * 2));
3648
5644
  const start = longLoca ? r.u32() : r.u16() * 2;
3649
- const end = longLoca ? r.u32() : r.u16() * 2;
3650
- if (start === end) return [];
5645
+ const end2 = longLoca ? r.u32() : r.u16() * 2;
5646
+ if (start === end2) return [];
3651
5647
  r.seek(glyf.offset + start);
3652
5648
  const count = r.i16();
3653
5649
  r.seek(r.position + 8);
3654
- if (count < 0) return composite(glyph, depth);
5650
+ if (count < 0) return composite(glyph, depth2);
3655
5651
  const ends = [];
3656
5652
  for (let i = 0; i < count; i++) ends.push(r.u16());
3657
5653
  const instructionLength = r.u16();
@@ -3698,7 +5694,7 @@ function parseFont(bytes) {
3698
5694
  }
3699
5695
  return out;
3700
5696
  };
3701
- function composite(_glyph, depth) {
5697
+ function composite(_glyph, depth2) {
3702
5698
  const parts = [];
3703
5699
  let more = true;
3704
5700
  while (more) {
@@ -3736,7 +5732,7 @@ function parseFont(bytes) {
3736
5732
  }
3737
5733
  const out = [];
3738
5734
  for (const part of parts) {
3739
- for (const contour of contours(part.glyph, depth + 1)) {
5735
+ for (const contour of contours(part.glyph, depth2 + 1)) {
3740
5736
  const moved = new Array(contour.length);
3741
5737
  const [a, b, c, d, e, f] = part.m;
3742
5738
  for (let i = 0; i < contour.length; i += 2) {
@@ -3846,9 +5842,9 @@ function parseCmap(r, offset) {
3846
5842
  let lo = 0, hi = table.length - 1;
3847
5843
  while (lo <= hi) {
3848
5844
  const mid = lo + hi >> 1;
3849
- const [start, end, glyph] = table[mid];
5845
+ const [start, end2, glyph] = table[mid];
3850
5846
  if (code < start) hi = mid - 1;
3851
- else if (code > end) lo = mid + 1;
5847
+ else if (code > end2) lo = mid + 1;
3852
5848
  else return glyph + code - start;
3853
5849
  }
3854
5850
  return 0;
@@ -3864,11 +5860,11 @@ function parseCmap(r, offset) {
3864
5860
  const rangesAt = deltasAt + segX2;
3865
5861
  const map = /* @__PURE__ */ new Map();
3866
5862
  for (let i = 0; i < segs; i++) {
3867
- const end = r.seek(endsAt + i * 2).u16();
5863
+ const end2 = r.seek(endsAt + i * 2).u16();
3868
5864
  const start = r.seek(startsAt + i * 2).u16();
3869
5865
  const delta = r.seek(deltasAt + i * 2).i16();
3870
5866
  const range = r.seek(rangesAt + i * 2).u16();
3871
- for (let c = start; c <= end && c !== 65535; c++) {
5867
+ for (let c = start; c <= end2 && c !== 65535; c++) {
3872
5868
  let glyph;
3873
5869
  if (range === 0) glyph = c + delta & 65535;
3874
5870
  else {
@@ -3953,9 +5949,9 @@ function readCoverage(r, offset) {
3953
5949
  } else if (format === 2) {
3954
5950
  const count = r.u16();
3955
5951
  for (let i = 0; i < count; i++) {
3956
- const start = r.u16(), end = r.u16();
5952
+ const start = r.u16(), end2 = r.u16();
3957
5953
  r.u16();
3958
- for (let glyph = start; glyph <= end; glyph++) out.add(glyph);
5954
+ for (let glyph = start; glyph <= end2; glyph++) out.add(glyph);
3959
5955
  }
3960
5956
  }
3961
5957
  return out;
@@ -3971,8 +5967,8 @@ function readClasses(r, offset) {
3971
5967
  } else if (format === 2) {
3972
5968
  const count = r.u16();
3973
5969
  for (let i = 0; i < count; i++) {
3974
- const start = r.u16(), end = r.u16(), value = r.u16();
3975
- for (let glyph = start; glyph <= end; glyph++) classes.set(glyph, value);
5970
+ const start = r.u16(), end2 = r.u16(), value = r.u16();
5971
+ for (let glyph = start; glyph <= end2; glyph++) classes.set(glyph, value);
3976
5972
  }
3977
5973
  }
3978
5974
  return (glyph) => classes.get(glyph) ?? 0;
@@ -4012,9 +6008,9 @@ function readPairs(r, sub) {
4012
6008
  } else if (coverageFormat === 2) {
4013
6009
  const count = r.u16();
4014
6010
  for (let i = 0; i < count; i++) {
4015
- const start = r.u16(), end = r.u16();
6011
+ const start = r.u16(), end2 = r.u16();
4016
6012
  r.u16();
4017
- for (let glyph = start; glyph <= end; glyph++) glyphs.push(glyph);
6013
+ for (let glyph = start; glyph <= end2; glyph++) glyphs.push(glyph);
4018
6014
  }
4019
6015
  }
4020
6016
  const sets = /* @__PURE__ */ new Map();
@@ -4054,7 +6050,7 @@ function readPairs(r, sub) {
4054
6050
  var FILES = {
4055
6051
  sans: { "400": "Inter-Regular.ttf", "600": "Inter-SemiBold.ttf", "700": "Inter-Bold.ttf" },
4056
6052
  serif: { "400": "InstrumentSerif-Regular.ttf", "italic": "InstrumentSerif-Italic.ttf" },
4057
- "text-serif": { "400": "SourceSerif4-24pt-Regular.ttf", "italic": "SourceSerif4-24pt-Italic.ttf" },
6053
+ "text-serif": { "400": "SourceSerif4-24pt-Regular.ttf", "600": "SourceSerif4-24pt-SemiBold.ttf", "italic": "SourceSerif4-24pt-Italic.ttf" },
4058
6054
  mono: { "400": "JetBrainsMono-Regular.ttf" },
4059
6055
  noto: { "400": "NotoSans-Regular.ttf" },
4060
6056
  math: { "400": "NotoSansMath-Regular.ttf" }
@@ -4078,6 +6074,9 @@ function fontFor(family, weight = 400, italic = false) {
4078
6074
  waiting = loadBinaryAsset(`fonts/${file}`).then((bytes) => {
4079
6075
  fonts.set(file, parseFont(bytes));
4080
6076
  pending.delete(file);
6077
+ }, (error) => {
6078
+ pending.delete(file);
6079
+ throw error;
4081
6080
  });
4082
6081
  pending.set(file, waiting);
4083
6082
  }
@@ -4113,111 +6112,18 @@ function glyphPath(font, glyph, size) {
4113
6112
  return path;
4114
6113
  }
4115
6114
 
4116
- // src/stage/text.ts
4117
- var TextNode = class extends Node {
4118
- chars = [];
4119
- source = "";
4120
- /** Glyph nodes whose characters match, such as every "x". */
4121
- find(fragment) {
4122
- const out = [];
4123
- const keys = this.chars.map((glyph) => glyph.data["key"]).join("");
4124
- const needle = fragment.replace(/\s/g, "");
4125
- for (let at = keys.indexOf(needle); at >= 0; at = keys.indexOf(needle, at + 1)) {
4126
- out.push(...this.chars.slice(at, at + needle.length));
4127
- }
4128
- return out;
4129
- }
4130
- };
4131
- function centered(path) {
4132
- const b = pathBounds(path);
4133
- if (!b) return { path, x: 0, y: 0 };
4134
- const x = b.x + b.width / 2, y = b.y + b.height / 2;
4135
- return { path: transformPath(path, [1, 0, 0, 1, -x, -y]), x, y };
4136
- }
4137
- function text(content, options = {}) {
4138
- const size = options.size ?? 40;
4139
- const family = options.font ?? "sans";
4140
- const weight = options.weight ?? 400;
4141
- const italic = options.italic ?? false;
4142
- const font = fontFor(family, weight, italic);
4143
- const scale = size / font.unitsPerEm;
4144
- const tracking = (options.tracking ?? 0) * size;
4145
- const leading = (options.leading ?? 1.3) * size;
4146
- const paint = toPaint(options.color ?? "ink");
4147
- const source = options.uppercase ? content.toUpperCase() : content;
4148
- const measureWord = (word) => {
4149
- const glyphs = [];
4150
- let x = 0, previous = 0, previousFont = null;
4151
- for (const char of word) {
4152
- const code = char.codePointAt(0);
4153
- let owner = font, glyph = font.glyphFor(code);
4154
- if (glyph === 0) {
4155
- const found = fallbackGlyph(family, code, weight, italic);
4156
- if (found) {
4157
- owner = found.font;
4158
- glyph = found.glyph;
4159
- }
4160
- }
4161
- const ownerScale = size / owner.unitsPerEm;
4162
- if (previous && previousFont === owner) x += owner.kern(previous, glyph) * ownerScale;
4163
- glyphs.push({ font: owner, glyph, x, char });
4164
- x += owner.advance(glyph) * ownerScale + tracking;
4165
- previous = glyph;
4166
- previousFont = owner;
4167
- }
4168
- return { glyphs, width: x };
4169
- };
4170
- const lines = [];
4171
- const space = font.advance(font.glyphFor(32)) * scale + tracking;
4172
- for (const paragraph of source.split("\n")) {
4173
- let line = [];
4174
- let width = 0;
4175
- for (const word of paragraph.split(" ")) {
4176
- const measured = measureWord(word);
4177
- const gap = line.length > 0 ? space : 0;
4178
- if (options.maxWidth !== void 0 && line.length > 0 && width + gap + measured.width > options.maxWidth) {
4179
- lines.push({ glyphs: line, width });
4180
- line = [];
4181
- width = 0;
4182
- }
4183
- const offset = width + (line.length > 0 ? space : 0);
4184
- for (const glyph of measured.glyphs) line.push({ ...glyph, x: glyph.x + offset });
4185
- width = offset + measured.width;
4186
- }
4187
- lines.push({ glyphs: line, width });
6115
+ // src/stage/svg-import.ts
6116
+ function safeCodePoint(code) {
6117
+ if (!Number.isInteger(code) || code < 1 || code > 1114111 || code >= 55296 && code <= 57343) {
6118
+ return "\uFFFD";
4188
6119
  }
4189
- const blockWidth = Math.max(0, ...lines.map((line) => line.width));
4190
- const align = options.align ?? "left";
4191
- const node = new TextNode();
4192
- node.source = content;
4193
- lines.forEach((line, row) => {
4194
- const start = align === "left" ? 0 : align === "center" ? (blockWidth - line.width) / 2 : blockWidth - line.width;
4195
- for (const placed of line.glyphs) {
4196
- const path = glyphPath(placed.font, placed.glyph, size);
4197
- if (path.length === 0) continue;
4198
- const shape = centered(path);
4199
- const leaf = new Node(shape.path).at(start + placed.x + shape.x, row * leading + shape.y);
4200
- leaf.base.fill = paint;
4201
- leaf.base.trimEach = true;
4202
- leaf.data["key"] = placed.char;
4203
- if (placed.glyph === 0) leaf.data["missingGlyph"] = true;
4204
- node.chars.push(leaf);
4205
- node.children.push(leaf);
4206
- leaf.parent = node;
4207
- }
4208
- });
4209
- const ascent = font.ascent * scale;
4210
- const height = (lines.length - 1) * leading;
4211
- node.base.px = blockWidth / 2;
4212
- node.base.py = height / 2 - ascent * 0.36;
4213
- node.data["size"] = size;
4214
- return node;
6120
+ return String.fromCodePoint(code);
4215
6121
  }
4216
-
4217
- // src/stage/svg-import.ts
4218
6122
  function decode(value) {
4219
- return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code))).replace(/&#x([\da-fA-F]+);/g, (_, code) => String.fromCodePoint(parseInt(code, 16))).replace(/&amp;/g, "&");
6123
+ return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#(\d+);/g, (_, code) => safeCodePoint(Number(code))).replace(/&#x([\da-fA-F]+);/g, (_, code) => safeCodePoint(parseInt(code, 16))).replace(/&amp;/g, "&");
4220
6124
  }
6125
+ var MAX_SVG_DEPTH = 64;
6126
+ var MAX_SVG_NODES = 1e4;
4221
6127
  function parseXml(source) {
4222
6128
  const root = { name: "#root", attrs: {}, children: [], text: "" };
4223
6129
  const stack = [root];
@@ -4263,6 +6169,7 @@ function parseTransform(value) {
4263
6169
  }
4264
6170
  return m;
4265
6171
  }
6172
+ var MONOSPACE = /monospace|mono\b|\bcode\b|courier|consolas|menlo|monaco|inconsolata/i;
4266
6173
  var NOT_DRAWN = /* @__PURE__ */ new Set(["defs", "clipPath", "mask", "pattern", "filter", "symbol", "marker", "linearGradient", "radialGradient", "title", "desc", "metadata", "style", "script"]);
4267
6174
  var SvgNode = class extends Node {
4268
6175
  byId = /* @__PURE__ */ new Map();
@@ -4320,8 +6227,8 @@ function splitIntoGlyphs(path) {
4320
6227
  for (let j = k - 1; j >= 0; j--) {
4321
6228
  const outer = items[order[j]];
4322
6229
  if (outer.owner !== -1) continue;
4323
- const inside = inner.b.x >= outer.b.x - 0.01 && inner.b.y >= outer.b.y - 0.01 && inner.b.x + inner.b.width <= outer.b.x + outer.b.width + 0.01 && inner.b.y + inner.b.height <= outer.b.y + outer.b.height + 0.01;
4324
- if (inside) {
6230
+ const inside2 = inner.b.x >= outer.b.x - 0.01 && inner.b.y >= outer.b.y - 0.01 && inner.b.x + inner.b.width <= outer.b.x + outer.b.width + 0.01 && inner.b.y + inner.b.height <= outer.b.y + outer.b.height + 0.01;
6231
+ if (inside2) {
4325
6232
  inner.owner = order[j];
4326
6233
  break;
4327
6234
  }
@@ -4351,11 +6258,11 @@ function fromSvg(source, options = {}) {
4351
6258
  element.children.forEach(index);
4352
6259
  };
4353
6260
  index(svg);
4354
- const box = (svg.attrs["viewBox"] ?? "").trim().split(/[\s,]+/).map(Number);
6261
+ const box2 = (svg.attrs["viewBox"] ?? "").trim().split(/[\s,]+/).map(Number);
4355
6262
  const declaredW = parseFloat(svg.attrs["width"] ?? ""), declaredH = parseFloat(svg.attrs["height"] ?? "");
4356
- const viewW = box.length === 4 && box[2] ? box[2] : declaredW || 300;
4357
- const viewH = box.length === 4 && box[3] ? box[3] : declaredH || 150;
4358
- const viewX = box.length === 4 ? box[0] : 0, viewY = box.length === 4 ? box[1] : 0;
6263
+ const viewW = box2.length === 4 && box2[2] ? box2[2] : declaredW || 300;
6264
+ const viewH = box2.length === 4 && box2[3] ? box2[3] : declaredH || 150;
6265
+ const viewX = box2.length === 4 ? box2[0] : 0, viewY = box2.length === 4 ? box2[1] : 0;
4359
6266
  const naturalW = Number.isFinite(declaredW) && declaredW > 0 ? declaredW : viewW;
4360
6267
  const naturalH = Number.isFinite(declaredH) && declaredH > 0 ? declaredH : viewH;
4361
6268
  let scale = 1;
@@ -4376,26 +6283,38 @@ function fromSvg(source, options = {}) {
4376
6283
  const splitting = options.splitGlyphs ?? true;
4377
6284
  const keepBackground = options.background ?? false;
4378
6285
  let firstShape = true;
4379
- const gradientOf = (id, m, path) => {
6286
+ let expandedNodes = 0;
6287
+ const gradientOf = (id, m, path, seen = /* @__PURE__ */ new Set()) => {
6288
+ if (seen.has(id) || seen.size >= MAX_SVG_DEPTH) return null;
4380
6289
  const element = defs.get(id);
4381
6290
  if (!element) return null;
6291
+ const nextSeen = new Set(seen);
6292
+ nextSeen.add(id);
4382
6293
  if (element.name === "pattern") {
4383
6294
  const inner = element.children.find((child) => child.name === "linearGradient");
4384
- if (inner) return linear2(inner, m, path, true);
6295
+ if (inner) return linear2(inner, m, path, true, nextSeen);
4385
6296
  const fill = element.children.find((child) => child.attrs["fill"]?.startsWith("url(#"));
4386
6297
  const nested = fill?.attrs["fill"]?.match(/url\(#([^)]+)\)/)?.[1];
4387
- return nested ? gradientOf(nested, m, path) : null;
6298
+ return nested ? gradientOf(nested, m, path, nextSeen) : null;
4388
6299
  }
4389
- if (element.name === "linearGradient") return linear2(element, m, path, element.attrs["gradientUnits"] !== "userSpaceOnUse");
6300
+ if (element.name === "linearGradient") return linear2(element, m, path, element.attrs["gradientUnits"] !== "userSpaceOnUse", nextSeen);
4390
6301
  if (element.name === "radialGradient") {
4391
- const stops = stopsOf(element);
6302
+ const stops = stopsOf(element, nextSeen);
4392
6303
  return stops.length ? stops[stops.length - 1][1] : null;
4393
6304
  }
4394
6305
  return null;
4395
6306
  };
4396
- const stopsOf = (element) => {
4397
- const inherited = element.attrs["href"] ?? element.attrs["xlink:href"];
4398
- const source2 = element.children.some((child) => child.name === "stop") || !inherited ? element : defs.get(inherited.replace(/^#/, "")) ?? element;
6307
+ const stopsOf = (element, seen = /* @__PURE__ */ new Set()) => {
6308
+ let source2 = element;
6309
+ const visited = new Set(seen);
6310
+ for (let hop = 0; hop < MAX_SVG_DEPTH && !source2.children.some((child) => child.name === "stop"); hop++) {
6311
+ const inherited = (source2.attrs["href"] ?? source2.attrs["xlink:href"] ?? "").replace(/^#/, "");
6312
+ if (!inherited || visited.has(inherited)) break;
6313
+ visited.add(inherited);
6314
+ const next = defs.get(inherited);
6315
+ if (!next) break;
6316
+ source2 = next;
6317
+ }
4399
6318
  return source2.children.filter((child) => child.name === "stop").map((stop) => {
4400
6319
  const style2 = parseStyle(stop.attrs["style"]);
4401
6320
  const offsetRaw = stop.attrs["offset"] ?? "0";
@@ -4405,8 +6324,8 @@ function fromSvg(source, options = {}) {
4405
6324
  return [offset, [color[0], color[1], color[2], color[3] * alpha]];
4406
6325
  });
4407
6326
  };
4408
- const linear2 = (element, m, path, objectBox) => {
4409
- const stops = stopsOf(element);
6327
+ const linear2 = (element, m, path, objectBox, seen = /* @__PURE__ */ new Set()) => {
6328
+ const stops = stopsOf(element, seen);
4410
6329
  if (stops.length === 0) return null;
4411
6330
  const coordinate = (value, fallback) => {
4412
6331
  if (value === void 0) return fallback;
@@ -4468,8 +6387,8 @@ function fromSvg(source, options = {}) {
4468
6387
  if (color) style2.color = color;
4469
6388
  const fill = pick("fill");
4470
6389
  if (fill) style2.fill = fill === "currentColor" ? style2.color : fill;
4471
- const stroke = pick("stroke");
4472
- if (stroke) style2.stroke = stroke === "currentColor" ? style2.color : stroke;
6390
+ const stroke2 = pick("stroke");
6391
+ if (stroke2) style2.stroke = stroke2 === "currentColor" ? style2.color : stroke2;
4473
6392
  const width = pick("stroke-width");
4474
6393
  if (width !== void 0) style2.strokeWidth = parseFloat(width) || 0;
4475
6394
  const fo = pick("fill-opacity");
@@ -4486,6 +6405,8 @@ function fromSvg(source, options = {}) {
4486
6405
  if (dashOffset !== void 0) style2.dashOffset = parseFloat(dashOffset) || 0;
4487
6406
  const size = pick("font-size");
4488
6407
  if (size !== void 0) style2.fontSize = parseFloat(size) || style2.fontSize;
6408
+ const family = pick("font-family") ?? pick("font");
6409
+ if (family) style2.family = family;
4489
6410
  const anchor = pick("text-anchor");
4490
6411
  if (anchor) style2.anchor = anchor;
4491
6412
  return { style: style2, opacity: parseFloat(pick("opacity") ?? "1") };
@@ -4496,13 +6417,13 @@ function fromSvg(source, options = {}) {
4496
6417
  const url = (value) => value?.match(/^url\(#([^)]+)\)/)?.[1];
4497
6418
  const fillId = url(style2.fill), strokeId = url(style2.stroke);
4498
6419
  const fill = fillId ? gradientOf(fillId, m, world) : safeColor(style2.fill);
4499
- const stroke = strokeId ? gradientOf(strokeId, m, world) : safeColor(style2.stroke);
6420
+ const stroke2 = strokeId ? gradientOf(strokeId, m, world) : safeColor(style2.stroke);
4500
6421
  const visibleFill = fill && style2.fillOpacity > 0 && !(Array.isArray(fill) && fill[3] === 0);
4501
- const visibleStroke = stroke && style2.strokeOpacity > 0 && style2.strokeWidth > 0 && !(Array.isArray(stroke) && stroke[3] === 0);
6422
+ const visibleStroke = stroke2 && style2.strokeOpacity > 0 && style2.strokeWidth > 0 && !(Array.isArray(stroke2) && stroke2[3] === 0);
4502
6423
  if (!visibleFill && !visibleStroke) return [];
4503
6424
  const clippedStroke = element.attrs["clip-path"] ? 0.5 : 1;
4504
- const pieces = splitting && visibleFill && !visibleStroke && world.length > 1 ? splitIntoGlyphs(world) : [world];
4505
- return pieces.map((piece) => {
6425
+ const pieces2 = splitting && visibleFill && !visibleStroke && world.length > 1 ? splitIntoGlyphs(world) : [world];
6426
+ return pieces2.map((piece) => {
4506
6427
  const b = pathBounds(piece) ?? { x: 0, y: 0, width: 0, height: 0 };
4507
6428
  const cx = b.x + b.width / 2, cy = b.y + b.height / 2;
4508
6429
  const leaf = new Node(transformPath(piece, [1, 0, 0, 1, -cx, -cy])).at(cx, cy);
@@ -4511,7 +6432,7 @@ function fromSvg(source, options = {}) {
4511
6432
  leaf.base.fillOpacity = style2.fillOpacity;
4512
6433
  }
4513
6434
  if (visibleStroke) {
4514
- leaf.base.stroke = shiftPaint(stroke, -cx, -cy);
6435
+ leaf.base.stroke = shiftPaint(stroke2, -cx, -cy);
4515
6436
  leaf.base.strokeWidth = style2.strokeWidth * scaleOf * clippedStroke;
4516
6437
  leaf.base.strokeOpacity = style2.strokeOpacity;
4517
6438
  leaf.base.cap = style2.cap;
@@ -4523,7 +6444,9 @@ function fromSvg(source, options = {}) {
4523
6444
  return leaf;
4524
6445
  });
4525
6446
  };
4526
- const walk2 = (element, parent, inherited, parentMatrix) => {
6447
+ const walk2 = (element, parent, inherited, parentMatrix, depth2 = 0, useStack = /* @__PURE__ */ new Set()) => {
6448
+ if (depth2 > MAX_SVG_DEPTH) throw new Error(`fromSvg exceeds the maximum nesting depth (${MAX_SVG_DEPTH}).`);
6449
+ if (++expandedNodes > MAX_SVG_NODES) throw new Error(`fromSvg exceeds the ${MAX_SVG_NODES}-node budget.`);
4527
6450
  if (NOT_DRAWN.has(element.name)) return;
4528
6451
  if (element.attrs["filter"]) return;
4529
6452
  const { style: style2, opacity } = styleOf(element, inherited);
@@ -4536,19 +6459,23 @@ function fromSvg(source, options = {}) {
4536
6459
  if (opacity < 1) group3.base.opacity = opacity;
4537
6460
  register(group3);
4538
6461
  parent.add(group3);
4539
- for (const child of element.children) walk2(child, group3, style2, m);
6462
+ for (const child of element.children) walk2(child, group3, style2, m, depth2 + 1, useStack);
4540
6463
  return;
4541
6464
  }
4542
6465
  if (element.name === "use") {
4543
6466
  const href = (element.attrs["href"] ?? element.attrs["xlink:href"] ?? "").replace(/^#/, "");
6467
+ if (!href) return;
6468
+ if (useStack.has(href)) throw new Error(`fromSvg encountered a circular <use> reference to #${href}.`);
4544
6469
  const referenced = defs.get(href);
4545
6470
  if (!referenced) return;
6471
+ const nextUseStack = new Set(useStack);
6472
+ nextUseStack.add(href);
4546
6473
  const placed = mul(m, [1, 0, 0, 1, parseFloat(element.attrs["x"] ?? "0") || 0, parseFloat(element.attrs["y"] ?? "0") || 0]);
4547
6474
  const group3 = new Node();
4548
6475
  if (opacity < 1) group3.base.opacity = opacity;
4549
6476
  parent.add(group3);
4550
- if (referenced.name === "symbol") for (const child of referenced.children) walk2(child, group3, style2, placed);
4551
- else walk2(referenced, group3, style2, placed);
6477
+ if (referenced.name === "symbol") for (const child of referenced.children) walk2(child, group3, style2, placed, depth2 + 1, nextUseStack);
6478
+ else walk2(referenced, group3, style2, placed, depth2 + 1, nextUseStack);
4552
6479
  return;
4553
6480
  }
4554
6481
  if (element.name === "image") {
@@ -4572,7 +6499,8 @@ function fromSvg(source, options = {}) {
4572
6499
  if (!body) return;
4573
6500
  const color = safeColor(style2.fill) ?? [0, 0, 0, 1];
4574
6501
  const size = style2.fontSize * matScale(m);
4575
- const label = text(body, { size, color });
6502
+ const named = options.font ?? filmFont();
6503
+ const label = text(body, { size, color, font: named === null ? void 0 : MONOSPACE.test(style2.family) ? "mono" : named });
4576
6504
  const [x, y] = apply(m, parseFloat(element.attrs["x"] ?? "0") || 0, parseFloat(element.attrs["y"] ?? "0") || 0);
4577
6505
  const half = label.get("px");
4578
6506
  label.at(style2.anchor === "middle" ? x : style2.anchor === "end" ? x - half : x + half, y - size * 0.34);
@@ -4612,6 +6540,7 @@ function fromSvg(source, options = {}) {
4612
6540
  dashOffset: 0,
4613
6541
  color: "#000000",
4614
6542
  fontSize: 16,
6543
+ family: "",
4615
6544
  anchor: "start"
4616
6545
  };
4617
6546
  const { style } = styleOf(svg, initial);
@@ -4639,13 +6568,17 @@ export {
4639
6568
  parseColor,
4640
6569
  toPaint,
4641
6570
  isGradient,
6571
+ luminance,
6572
+ over,
4642
6573
  css,
4643
6574
  mixColor,
6575
+ mixPaint,
4644
6576
  sampleStops,
4645
6577
  linearGradient,
4646
6578
  radialGradient,
4647
6579
  along,
4648
6580
  ramp,
6581
+ projectToLine,
4649
6582
  IDENTITY,
4650
6583
  EMPTY_BOUNDS,
4651
6584
  mul,
@@ -4681,15 +6614,24 @@ export {
4681
6614
  parseSvgPath,
4682
6615
  pathToD,
4683
6616
  clock,
6617
+ Track,
6618
+ pathMixer,
4684
6619
  matchSequence,
6620
+ rebindCloneParts,
4685
6621
  Node,
4686
6622
  direction,
6623
+ mountTree,
6624
+ ownLabels,
6625
+ objectName,
4687
6626
  group,
4688
6627
  dynamic,
4689
6628
  ImageAssetError,
4690
6629
  resolveImageAsset,
4691
6630
  imageHasVisiblePixels,
6631
+ isImageAsset,
4692
6632
  imageFromAsset,
6633
+ inside,
6634
+ addLight,
4693
6635
  buildOps,
4694
6636
  frameToSvg,
4695
6637
  paintFrame,
@@ -4722,6 +6664,36 @@ export {
4722
6664
  runningStart,
4723
6665
  during,
4724
6666
  cubicBezier,
6667
+ CURVE_PIECES,
6668
+ pieces,
6669
+ encloses,
6670
+ setAssetBase,
6671
+ parseFont,
6672
+ fontFor,
6673
+ fallbackGlyph,
6674
+ glyphPath,
6675
+ TextNode,
6676
+ filmFont,
6677
+ text,
6678
+ GAP,
6679
+ Box,
6680
+ Block,
6681
+ nodesFor,
6682
+ oneNode,
6683
+ nodeOrPoint,
6684
+ oneObject,
6685
+ boxOf,
6686
+ describe,
6687
+ between,
6688
+ fitted,
6689
+ row,
6690
+ column,
6691
+ grid,
6692
+ place,
6693
+ beside,
6694
+ PICTOGRAMS,
6695
+ Pictogram,
6696
+ pictogram,
4725
6697
  par,
4726
6698
  seq,
4727
6699
  lagged,
@@ -4762,12 +6734,6 @@ export {
4762
6734
  isSuspend,
4763
6735
  CompiledFilm,
4764
6736
  compileFilm,
4765
- setAssetBase,
4766
- parseFont,
4767
- fontFor,
4768
- glyphPath,
4769
- TextNode,
4770
- text,
4771
6737
  SvgNode,
4772
6738
  fromSvg
4773
6739
  };