vizmatic 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PROMPT.md +9 -3
- package/README.md +479 -3
- package/dist/chunk-FEIPTPBZ.js +1165 -0
- package/dist/chunk-TH3F4SDB.js +79 -0
- package/dist/cli.js +14 -8
- package/dist/index.cjs +2732 -125
- package/dist/index.d.cts +557 -2
- package/dist/index.d.ts +557 -2
- package/dist/index.js +2026 -559
- package/dist/scene-cli.d.ts +1 -0
- package/dist/scene-cli.js +4 -0
- package/dist/scene-runtime.cjs +930 -0
- package/dist/scene-runtime.d.cts +80 -0
- package/dist/scene-runtime.d.ts +80 -0
- package/dist/scene-runtime.js +20 -0
- package/examples/README.md +4 -0
- package/examples/aurora-incident.tsx +108 -0
- package/examples/daybreak-launch.tsx +81 -0
- package/examples/model-garden.tsx +97 -0
- package/examples/pressure-mechanism.scene.json +14 -0
- package/examples/videos/README.md +28 -0
- package/examples/videos/request-lifecycle.tsx +99 -0
- package/examples/videos/signal-to-story.tsx +126 -0
- package/examples/vizmatic-bare.d.ts +7 -0
- package/examples/weekend-field-notes.tsx +81 -0
- package/package.json +18 -7
package/dist/index.cjs
CHANGED
|
@@ -83,6 +83,8 @@ __export(index_exports, {
|
|
|
83
83
|
ProgressRow: () => ProgressRow,
|
|
84
84
|
QuadrantChart: () => QuadrantChart,
|
|
85
85
|
Row: () => Row,
|
|
86
|
+
SCENE_LIMITS: () => SCENE_LIMITS,
|
|
87
|
+
SCENE_RUNTIME_VERSION: () => SCENE_RUNTIME_VERSION,
|
|
86
88
|
ScatterPlot: () => ScatterPlot,
|
|
87
89
|
Scene: () => Scene,
|
|
88
90
|
SequenceDiagram: () => SequenceDiagram,
|
|
@@ -109,10 +111,16 @@ __export(index_exports, {
|
|
|
109
111
|
Watermark: () => Watermark,
|
|
110
112
|
WindowFrame: () => WindowFrame,
|
|
111
113
|
analyzeAnimationCadence: () => analyzeAnimationCadence,
|
|
114
|
+
arcSwap: () => arcSwap,
|
|
115
|
+
cameraSvgTransform: () => cameraSvgTransform,
|
|
112
116
|
canvas: () => canvas,
|
|
113
117
|
checkFrame: () => checkFrame,
|
|
114
118
|
colors: () => colors,
|
|
119
|
+
createCanvasComponents: () => createCanvasComponents,
|
|
120
|
+
createCueTrack: () => createCueTrack,
|
|
115
121
|
createPlotArea: () => createPlotArea,
|
|
122
|
+
createPolylineMorph: () => createPolylineMorph,
|
|
123
|
+
createTeachingCanvas: () => createTeachingCanvas,
|
|
116
124
|
cropPixels: () => cropPixels,
|
|
117
125
|
defineAnimation: () => defineAnimation,
|
|
118
126
|
defineDiagramIcon: () => defineDiagramIcon,
|
|
@@ -121,8 +129,12 @@ __export(index_exports, {
|
|
|
121
129
|
detectBackgroundColor: () => detectBackgroundColor,
|
|
122
130
|
detectContentBounds: () => detectContentBounds,
|
|
123
131
|
detectOverflow: () => detectOverflow,
|
|
132
|
+
dotProduct: () => dotProduct,
|
|
133
|
+
entropy: () => entropy,
|
|
134
|
+
evaluateSceneSource: () => evaluateSceneSource,
|
|
124
135
|
formatMathText: () => formatMathText,
|
|
125
136
|
formatTensorShape: () => formatTensorShape,
|
|
137
|
+
gaussian: () => gaussian,
|
|
126
138
|
getColor: () => getColor,
|
|
127
139
|
getFonts: () => getFonts,
|
|
128
140
|
getGradient: () => getGradient,
|
|
@@ -139,24 +151,48 @@ __export(index_exports, {
|
|
|
139
151
|
hold: () => hold,
|
|
140
152
|
importD2Graph: () => importD2Graph,
|
|
141
153
|
importMermaidGraph: () => importMermaidGraph,
|
|
154
|
+
interpolateCamera: () => interpolateCamera,
|
|
142
155
|
keyframe: () => keyframe,
|
|
156
|
+
layoutAllocation: () => layoutAllocation,
|
|
157
|
+
layoutCellGrid: () => layoutCellGrid,
|
|
158
|
+
layoutTokenRow: () => layoutTokenRow,
|
|
159
|
+
lerpArray: () => lerpArray,
|
|
143
160
|
loadAdditionalAsset: () => loadAdditionalAsset,
|
|
161
|
+
morphPolyline: () => morphPolyline,
|
|
162
|
+
multiplyMatrices: () => multiplyMatrices,
|
|
163
|
+
normalizeVector: () => normalizeVector,
|
|
144
164
|
normalizeWatermark: () => normalizeWatermark,
|
|
145
165
|
parallel: () => parallel,
|
|
166
|
+
pointAlongPath: () => pointAlongPath,
|
|
167
|
+
prepareScene: () => prepareScene,
|
|
168
|
+
projectWorldPoint: () => projectWorldPoint,
|
|
146
169
|
renderAnimatedGif: () => renderAnimatedGif,
|
|
147
170
|
renderAnimatedGifWithOutput: () => renderAnimatedGifWithOutput,
|
|
148
171
|
renderAnimationGif: () => renderAnimationGif,
|
|
149
172
|
renderAnimationGifWithOutput: () => renderAnimationGifWithOutput,
|
|
173
|
+
renderAnimationVideo: () => renderAnimationVideo,
|
|
174
|
+
renderMathSvg: () => renderMathSvg,
|
|
175
|
+
renderRgbaVideo: () => renderRgbaVideo,
|
|
176
|
+
renderSceneFrame: () => renderSceneFrame,
|
|
177
|
+
renderSceneVideo: () => renderSceneVideo,
|
|
150
178
|
renderToBuffer: () => renderToBuffer,
|
|
151
179
|
renderToPng: () => renderToPng,
|
|
152
180
|
renderToPngWithOutput: () => renderToPngWithOutput,
|
|
153
181
|
renderToSvg: () => renderToSvg,
|
|
154
182
|
sampleAnimation: () => sampleAnimation,
|
|
183
|
+
sampleAnimationFrame: () => sampleAnimationFrame,
|
|
155
184
|
sampleAnimationFrames: () => sampleAnimationFrames,
|
|
185
|
+
sampleFunction: () => sampleFunction,
|
|
186
|
+
sampleGaussian: () => sampleGaussian,
|
|
187
|
+
seededRandom: () => seededRandom,
|
|
188
|
+
smoothstep: () => smoothstep,
|
|
189
|
+
stableSoftmax: () => stableSoftmax,
|
|
156
190
|
styles: () => styles,
|
|
157
191
|
toneGradients: () => toneGradients,
|
|
192
|
+
tracePolyline: () => tracePolyline,
|
|
158
193
|
tween: () => tween,
|
|
159
194
|
typography: () => typography,
|
|
195
|
+
videoFrameSchedule: () => videoFrameSchedule,
|
|
160
196
|
withColorAlpha: () => withColorAlpha,
|
|
161
197
|
wrapWithBrand: () => wrapWithBrand,
|
|
162
198
|
wrapWithWatermark: () => wrapWithWatermark
|
|
@@ -523,12 +559,12 @@ function withColorAlpha(color, opacity) {
|
|
|
523
559
|
if (typeof color !== "string" || !Number.isFinite(opacity)) return "transparent";
|
|
524
560
|
const parsed = parseColor(color);
|
|
525
561
|
if (!parsed) return "transparent";
|
|
526
|
-
const
|
|
562
|
+
const alpha2 = Math.min(1, Math.max(0, parsed.alpha * Math.min(1, Math.max(0, opacity))));
|
|
527
563
|
const hex = color.trim();
|
|
528
564
|
if (/^#[\da-f]{6}$/i.test(hex)) {
|
|
529
|
-
return `${hex}${Math.round(
|
|
565
|
+
return `${hex}${Math.round(alpha2 * 255).toString(16).padStart(2, "0")}`;
|
|
530
566
|
}
|
|
531
|
-
return `rgba(${parsed.channels.join(", ")}, ${Number(
|
|
567
|
+
return `rgba(${parsed.channels.join(", ")}, ${Number(alpha2.toFixed(6))})`;
|
|
532
568
|
}
|
|
533
569
|
function colorLuminance(color, backdrop) {
|
|
534
570
|
const parsed = parseColor(color);
|
|
@@ -3693,9 +3729,9 @@ function preferredSide(from, to) {
|
|
|
3693
3729
|
return to.cy >= from.cy ? "bottom" : "top";
|
|
3694
3730
|
}
|
|
3695
3731
|
function routingAnchor(node, side, offset = 0.5) {
|
|
3696
|
-
const
|
|
3697
|
-
if (side === "left" || side === "right") return { x:
|
|
3698
|
-
return { x:
|
|
3732
|
+
const bounds2 = box(node);
|
|
3733
|
+
if (side === "left" || side === "right") return { x: bounds2[side], y: bounds2.top + node.height * offset };
|
|
3734
|
+
return { x: bounds2.left + node.width * offset, y: bounds2[side] };
|
|
3699
3735
|
}
|
|
3700
3736
|
function outward(point, side, distance) {
|
|
3701
3737
|
return {
|
|
@@ -3909,7 +3945,7 @@ function routeOrthogonalGraph(nodes, edges, width, height, clearance = 12, gap =
|
|
|
3909
3945
|
}
|
|
3910
3946
|
const points = simplify([start, ...result.points, end]);
|
|
3911
3947
|
if (points.length < 2) continue;
|
|
3912
|
-
const repeated = (previous.get(key) ?? []).some((route) => route.length === points.length && (route.every((point,
|
|
3948
|
+
const repeated = (previous.get(key) ?? []).some((route) => route.length === points.length && (route.every((point, position2) => point.x === points[position2].x && point.y === points[position2].y) || route.every((point, position2) => point.x === points[points.length - 1 - position2].x && point.y === points[points.length - 1 - position2].y)));
|
|
3913
3949
|
if (repeated) {
|
|
3914
3950
|
failure = "parallel connectors have no separate lane at the requested clearance";
|
|
3915
3951
|
continue;
|
|
@@ -3925,17 +3961,17 @@ function routeOrthogonalGraph(nodes, edges, width, height, clearance = 12, gap =
|
|
|
3925
3961
|
}
|
|
3926
3962
|
function routingLabelPosition(points) {
|
|
3927
3963
|
let longest = 0;
|
|
3928
|
-
let
|
|
3964
|
+
let position2 = points[0];
|
|
3929
3965
|
for (let i = 1; i < points.length; i++) {
|
|
3930
3966
|
const a = points[i - 1];
|
|
3931
3967
|
const b = points[i];
|
|
3932
3968
|
const length = Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
|
|
3933
3969
|
if (length > longest) {
|
|
3934
3970
|
longest = length;
|
|
3935
|
-
|
|
3971
|
+
position2 = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
|
|
3936
3972
|
}
|
|
3937
3973
|
}
|
|
3938
|
-
return
|
|
3974
|
+
return position2;
|
|
3939
3975
|
}
|
|
3940
3976
|
|
|
3941
3977
|
// src/primitives/diagrams.ts
|
|
@@ -4226,13 +4262,13 @@ function connectorLabelCollisions(edges, nodes, groups = []) {
|
|
|
4226
4262
|
if (rectanglesOverlap(labels[index].bounds, labels[otherIndex].bounds, 4)) collisions += 1;
|
|
4227
4263
|
}
|
|
4228
4264
|
for (const node of nodes.values()) {
|
|
4229
|
-
const
|
|
4265
|
+
const bounds2 = {
|
|
4230
4266
|
left: node.cx - node.width / 2,
|
|
4231
4267
|
right: node.cx + node.width / 2,
|
|
4232
4268
|
top: node.cy - node.height / 2,
|
|
4233
4269
|
bottom: node.cy + node.height / 2
|
|
4234
4270
|
};
|
|
4235
|
-
if (rectanglesOverlap(labels[index].bounds,
|
|
4271
|
+
if (rectanglesOverlap(labels[index].bounds, bounds2)) collisions += 1;
|
|
4236
4272
|
}
|
|
4237
4273
|
for (const group of groups) {
|
|
4238
4274
|
const headerBounds = {
|
|
@@ -4493,24 +4529,24 @@ function GraphDiagram({
|
|
|
4493
4529
|
const offsetX = (resolvedWidth - (graphSize.width ?? resolvedWidth)) / 2;
|
|
4494
4530
|
const offsetY = (resolvedHeight - (graphSize.height ?? resolvedHeight)) / 2;
|
|
4495
4531
|
layout = new Map(nodes.map((node) => {
|
|
4496
|
-
const
|
|
4532
|
+
const position2 = graph.node(node.id);
|
|
4497
4533
|
return [node.id, {
|
|
4498
4534
|
...node,
|
|
4499
4535
|
width: node.width ?? nodeWidth,
|
|
4500
4536
|
height: node.height ?? nodeHeight,
|
|
4501
|
-
cx: (
|
|
4502
|
-
cy: (
|
|
4537
|
+
cx: (position2?.x ?? resolvedWidth / 2) + offsetX,
|
|
4538
|
+
cy: (position2?.y ?? resolvedHeight / 2) + offsetY
|
|
4503
4539
|
}];
|
|
4504
4540
|
}));
|
|
4505
4541
|
const groupsById = new Map(groups.map((group) => [group.id, group]));
|
|
4506
4542
|
groupLayout = groups.map((group) => {
|
|
4507
|
-
const
|
|
4543
|
+
const position2 = graph.node(group.id);
|
|
4508
4544
|
return {
|
|
4509
4545
|
...group,
|
|
4510
|
-
width:
|
|
4511
|
-
height:
|
|
4512
|
-
cx: (
|
|
4513
|
-
cy: (
|
|
4546
|
+
width: position2?.width ?? 0,
|
|
4547
|
+
height: position2?.height ?? 0,
|
|
4548
|
+
cx: (position2?.x ?? resolvedWidth / 2) + offsetX,
|
|
4549
|
+
cy: (position2?.y ?? resolvedHeight / 2) + offsetY,
|
|
4514
4550
|
depth: graphGroupDepth(group, groupsById)
|
|
4515
4551
|
};
|
|
4516
4552
|
}).sort((left, right) => left.depth - right.depth);
|
|
@@ -4804,7 +4840,8 @@ function GraphDiagram({
|
|
|
4804
4840
|
flexDirection: "column",
|
|
4805
4841
|
alignItems: icon ? "flex-start" : "center",
|
|
4806
4842
|
gap: node.detail ? 5 : 0,
|
|
4807
|
-
minWidth: 0
|
|
4843
|
+
minWidth: 0,
|
|
4844
|
+
flexShrink: 1
|
|
4808
4845
|
}
|
|
4809
4846
|
},
|
|
4810
4847
|
import_react7.default.createElement("div", {
|
|
@@ -5550,7 +5587,7 @@ function SequenceDiagram({
|
|
|
5550
5587
|
const noteElements = rows.map((row, rowIndex) => {
|
|
5551
5588
|
if (!row.item || !isNote(row.item)) return null;
|
|
5552
5589
|
const note = row.item;
|
|
5553
|
-
const
|
|
5590
|
+
const bounds2 = sequenceNoteBounds(note, participantXs, resolvedWidth, noteWidth, padding);
|
|
5554
5591
|
const tone = note.tone ?? "warm";
|
|
5555
5592
|
const accent = note.muted ? c.textMuted : getToneColor(tone, c);
|
|
5556
5593
|
return import_react8.default.createElement("div", {
|
|
@@ -5558,9 +5595,9 @@ function SequenceDiagram({
|
|
|
5558
5595
|
"data-vizmatic-sequence-note": note.id ?? row.key,
|
|
5559
5596
|
style: {
|
|
5560
5597
|
position: "absolute",
|
|
5561
|
-
left:
|
|
5598
|
+
left: bounds2.left,
|
|
5562
5599
|
top: rowCenter(rowIndex) - 17,
|
|
5563
|
-
width:
|
|
5600
|
+
width: bounds2.width,
|
|
5564
5601
|
minHeight: 34,
|
|
5565
5602
|
boxSizing: "border-box",
|
|
5566
5603
|
display: "flex",
|
|
@@ -7220,25 +7257,44 @@ function CanvasChartFit({ children, width, height }) {
|
|
|
7220
7257
|
}
|
|
7221
7258
|
function prepareChartFits(element) {
|
|
7222
7259
|
const sizes = /* @__PURE__ */ new Map();
|
|
7260
|
+
const hasText = (node) => {
|
|
7261
|
+
if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") return true;
|
|
7262
|
+
if (Array.isArray(node)) return node.some(hasText);
|
|
7263
|
+
return (0, import_react11.isValidElement)(node) && node.type === import_react11.default.Fragment && hasText(node.props.children);
|
|
7264
|
+
};
|
|
7223
7265
|
const visit = (node, scope) => {
|
|
7224
7266
|
if (Array.isArray(node)) return node.map((child) => visit(child, scope));
|
|
7225
7267
|
if (!(0, import_react11.isValidElement)(node)) return node;
|
|
7226
|
-
|
|
7227
|
-
|
|
7268
|
+
const forwarded = node.type;
|
|
7269
|
+
const render = typeof node.type === "function" ? node.type : forwarded?.$$typeof === /* @__PURE__ */ Symbol.for("react.forward_ref") ? forwarded.render : void 0;
|
|
7270
|
+
if (render) {
|
|
7271
|
+
const resolved = visit(render(node.props), scope);
|
|
7228
7272
|
return node.key != null && (0, import_react11.isValidElement)(resolved) ? import_react11.default.cloneElement(resolved, { key: node.key }) : resolved;
|
|
7229
7273
|
}
|
|
7230
7274
|
const size = node.props[FIT_PROP];
|
|
7231
7275
|
const props = { ...node.props };
|
|
7232
7276
|
delete props[FIT_PROP];
|
|
7277
|
+
let childScope = scope;
|
|
7233
7278
|
if (size) {
|
|
7234
7279
|
const id = String(sizes.size);
|
|
7235
7280
|
sizes.set(id, size);
|
|
7236
7281
|
props[VIEWPORT_PROP] = id;
|
|
7237
|
-
|
|
7282
|
+
childScope = id;
|
|
7283
|
+
} else if (scope !== void 0 && typeof node.type === "string") {
|
|
7284
|
+
props[SCOPE_PROP] = scope;
|
|
7238
7285
|
}
|
|
7239
|
-
if (scope !== void 0 && typeof node.type === "string") props[SCOPE_PROP] = scope;
|
|
7240
7286
|
const children = node.props.children;
|
|
7241
|
-
|
|
7287
|
+
const preparedChildren = children === void 0 ? void 0 : visit(children, childScope);
|
|
7288
|
+
if (typeof node.type === "string") {
|
|
7289
|
+
const style = node.props.style;
|
|
7290
|
+
props.style = {
|
|
7291
|
+
minWidth: 0,
|
|
7292
|
+
minHeight: 0,
|
|
7293
|
+
...style?.flex === void 0 ? { flexShrink: hasText(preparedChildren) ? 1 : 0 } : {},
|
|
7294
|
+
...style
|
|
7295
|
+
};
|
|
7296
|
+
}
|
|
7297
|
+
return children === void 0 ? import_react11.default.cloneElement(node, props) : import_react11.default.cloneElement(node, props, preparedChildren);
|
|
7242
7298
|
};
|
|
7243
7299
|
return { element: visit(element), sizes };
|
|
7244
7300
|
}
|
|
@@ -7264,14 +7320,14 @@ async function renderWithCanvasChartFit(render, element, options) {
|
|
|
7264
7320
|
const prepared = prepareChartFits(element);
|
|
7265
7321
|
if (!prepared.sizes.size) return render(prepared.element, options);
|
|
7266
7322
|
const viewports = /* @__PURE__ */ new Map();
|
|
7267
|
-
const
|
|
7323
|
+
const bounds2 = /* @__PURE__ */ new Map();
|
|
7268
7324
|
await render(prepared.element, { ...options, onNodeDetected(node) {
|
|
7269
7325
|
const viewport = node.props[VIEWPORT_PROP];
|
|
7270
7326
|
if (typeof viewport === "string") viewports.set(viewport, node);
|
|
7271
7327
|
const id = node.props[SCOPE_PROP];
|
|
7272
|
-
if (typeof id !== "string" || node.width
|
|
7273
|
-
const prior =
|
|
7274
|
-
|
|
7328
|
+
if (typeof id !== "string" || node.width < 0 || node.height < 0) return;
|
|
7329
|
+
const prior = bounds2.get(id);
|
|
7330
|
+
bounds2.set(id, {
|
|
7275
7331
|
left: Math.min(prior?.left ?? Infinity, node.left),
|
|
7276
7332
|
top: Math.min(prior?.top ?? Infinity, node.top),
|
|
7277
7333
|
right: Math.max(prior?.right ?? -Infinity, node.left + node.width),
|
|
@@ -7281,7 +7337,7 @@ async function renderWithCanvasChartFit(render, element, options) {
|
|
|
7281
7337
|
const geometry = /* @__PURE__ */ new Map();
|
|
7282
7338
|
for (const [id, size] of prepared.sizes) {
|
|
7283
7339
|
const viewport = viewports.get(id);
|
|
7284
|
-
const measured =
|
|
7340
|
+
const measured = bounds2.get(id);
|
|
7285
7341
|
if (!viewport || !measured) throw new Error("Could not measure the chart inside CanvasItem.");
|
|
7286
7342
|
const width = measured.right - measured.left, height = measured.bottom - measured.top;
|
|
7287
7343
|
const scale = Math.min(size.width / width, size.height / height);
|
|
@@ -7388,7 +7444,7 @@ function chartLabel(key, text, x, y, c, options = {}) {
|
|
|
7388
7444
|
const labelHeight = options.height ?? Math.ceil(fontSize * 1.4);
|
|
7389
7445
|
let left = x;
|
|
7390
7446
|
let top = y;
|
|
7391
|
-
let
|
|
7447
|
+
let transform2 = options.transform ?? (align === "center" ? "translate(-50%, -50%)" : align === "right" ? "translate(-100%, -50%)" : "translate(0, -50%)");
|
|
7392
7448
|
if (options.bounds) {
|
|
7393
7449
|
const padding = options.bounds.padding ?? 4;
|
|
7394
7450
|
const idealLeft = align === "center" ? x - width / 2 : align === "right" ? x - width : x;
|
|
@@ -7403,7 +7459,7 @@ function chartLabel(key, text, x, y, c, options = {}) {
|
|
|
7403
7459
|
options.bounds.y + padding,
|
|
7404
7460
|
options.bounds.y + options.bounds.height - labelHeight - padding
|
|
7405
7461
|
);
|
|
7406
|
-
|
|
7462
|
+
transform2 = void 0;
|
|
7407
7463
|
}
|
|
7408
7464
|
return import_react12.default.createElement("div", {
|
|
7409
7465
|
key,
|
|
@@ -7412,7 +7468,7 @@ function chartLabel(key, text, x, y, c, options = {}) {
|
|
|
7412
7468
|
left,
|
|
7413
7469
|
top,
|
|
7414
7470
|
width,
|
|
7415
|
-
...
|
|
7471
|
+
...transform2 !== void 0 ? { transform: transform2 } : {},
|
|
7416
7472
|
display: "flex",
|
|
7417
7473
|
justifyContent: align === "right" ? "flex-end" : align === "left" ? "flex-start" : "center",
|
|
7418
7474
|
...textFitStyle(align),
|
|
@@ -9228,8 +9284,11 @@ function CanvasItem({ children, x, y, width, height }) {
|
|
|
9228
9284
|
if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error("CanvasItem x and y must be finite numbers.");
|
|
9229
9285
|
const sizedChildren = import_react14.default.Children.map(children, (child) => {
|
|
9230
9286
|
if (!import_react14.default.isValidElement(child)) return child;
|
|
9231
|
-
|
|
9232
|
-
|
|
9287
|
+
if (width !== void 0 && height !== void 0 && isCanvasChart(child.type)) {
|
|
9288
|
+
const chart = import_react14.default.cloneElement(child, { width: child.props.width ?? width, height: child.props.height ?? height });
|
|
9289
|
+
return import_react14.default.createElement(CanvasChartFit, { width, height, __vizmaticTextScope: child.props.__vizmaticTextScope }, chart);
|
|
9290
|
+
}
|
|
9291
|
+
return import_react14.default.cloneElement(child, { ...width !== void 0 ? { width } : {}, ...height !== void 0 ? { height } : {} });
|
|
9233
9292
|
});
|
|
9234
9293
|
return import_react14.default.createElement("div", { style: {
|
|
9235
9294
|
display: "flex",
|
|
@@ -9292,8 +9351,8 @@ function normalizeWatermark(watermark) {
|
|
|
9292
9351
|
function Watermark(_props) {
|
|
9293
9352
|
return null;
|
|
9294
9353
|
}
|
|
9295
|
-
function positionStyle(
|
|
9296
|
-
switch (
|
|
9354
|
+
function positionStyle(position2) {
|
|
9355
|
+
switch (position2) {
|
|
9297
9356
|
case "top-left":
|
|
9298
9357
|
return { top: 8, left: 10 };
|
|
9299
9358
|
case "bottom-left":
|
|
@@ -9344,7 +9403,7 @@ function wrapWithWatermark(element, width, height, theme = "dark", watermark = t
|
|
|
9344
9403
|
const isDark = theme === "dark";
|
|
9345
9404
|
const options = normalizeWatermark(watermark);
|
|
9346
9405
|
const color = options?.color ?? (isDark ? WATERMARK_COLOR_DARK : WATERMARK_COLOR_LIGHT);
|
|
9347
|
-
const
|
|
9406
|
+
const position2 = options?.position ?? "top-right";
|
|
9348
9407
|
const opacity = options?.opacity ?? (isDark ? 0.55 : 0.4);
|
|
9349
9408
|
const icon = options ? imageNode(options.image) ?? iconNode(options.icon, color) : void 0;
|
|
9350
9409
|
const text = options?.text ?? DEFAULT_WATERMARK_TEXT;
|
|
@@ -9377,7 +9436,7 @@ function wrapWithWatermark(element, width, height, theme = "dark", watermark = t
|
|
|
9377
9436
|
{
|
|
9378
9437
|
style: {
|
|
9379
9438
|
position: "absolute",
|
|
9380
|
-
...positionStyle(
|
|
9439
|
+
...positionStyle(position2),
|
|
9381
9440
|
display: "flex",
|
|
9382
9441
|
alignItems: "center",
|
|
9383
9442
|
gap: 5,
|
|
@@ -9741,23 +9800,19 @@ function cropLayoutNodes(nodes, region) {
|
|
|
9741
9800
|
}];
|
|
9742
9801
|
});
|
|
9743
9802
|
}
|
|
9744
|
-
function cropSavesEnough(source, target) {
|
|
9745
|
-
if (source <= 0 || target >= source) return false;
|
|
9746
|
-
return (source - target) / source * 100 >= CROP_THRESHOLD_PERCENT;
|
|
9747
|
-
}
|
|
9748
9803
|
var CanvasOverflowError = class extends Error {
|
|
9749
9804
|
width;
|
|
9750
9805
|
height;
|
|
9751
9806
|
overflow;
|
|
9752
9807
|
animation;
|
|
9753
9808
|
constructor(width, height, overflow, animation) {
|
|
9754
|
-
const
|
|
9809
|
+
const position2 = animation ? [
|
|
9755
9810
|
animation.sceneIndex != null ? `scene ${animation.sceneIndex + 1}` : void 0,
|
|
9756
9811
|
animation.frameIndex != null ? `frame ${animation.frameIndex + 1}${animation.frameCount ? `/${animation.frameCount}` : ""}` : void 0,
|
|
9757
9812
|
animation.time != null ? `${Math.round(animation.time)}ms` : void 0,
|
|
9758
9813
|
animation.label ? JSON.stringify(animation.label) : void 0
|
|
9759
9814
|
].filter(Boolean).join(", ") : "";
|
|
9760
|
-
super(`Canvas overflow detected (${width}\xD7${height})${
|
|
9815
|
+
super(`Canvas overflow detected (${width}\xD7${height})${position2 ? ` at ${position2}` : ""}: ${overflow.message}`);
|
|
9761
9816
|
this.name = "CanvasOverflowError";
|
|
9762
9817
|
this.width = width;
|
|
9763
9818
|
this.height = height;
|
|
@@ -9801,7 +9856,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
|
|
|
9801
9856
|
const detectPixels = detectResult.pixels;
|
|
9802
9857
|
const pixelData = new Uint8Array(detectPixels.buffer);
|
|
9803
9858
|
const detectedBg = detectBackgroundColor(pixelData);
|
|
9804
|
-
const
|
|
9859
|
+
const bounds2 = detectContentBounds(
|
|
9805
9860
|
pixelData,
|
|
9806
9861
|
options.width,
|
|
9807
9862
|
detectResult.height,
|
|
@@ -9820,7 +9875,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
|
|
|
9820
9875
|
let finalWidth = options.width;
|
|
9821
9876
|
let finalHeight = options.height;
|
|
9822
9877
|
let finalElement = element;
|
|
9823
|
-
const croppedHeight =
|
|
9878
|
+
const croppedHeight = bounds2.y + bounds2.height;
|
|
9824
9879
|
const heightSaved = options.height - croppedHeight;
|
|
9825
9880
|
const heightSavedPercent = heightSaved / options.height * 100;
|
|
9826
9881
|
if (shouldCropHeight(options.crop) && heightSavedPercent >= CROP_THRESHOLD_PERCENT) {
|
|
@@ -9879,7 +9934,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
|
|
|
9879
9934
|
viewportBg,
|
|
9880
9935
|
AUTOCROP_PADDING
|
|
9881
9936
|
);
|
|
9882
|
-
if (
|
|
9937
|
+
if (viewportBounds.width < finalWidth || viewportBounds.height < viewportCheck.height) {
|
|
9883
9938
|
finalSvg = cropSvgViewport(finalSvg, viewportBounds);
|
|
9884
9939
|
finalRender.layoutNodes = cropLayoutNodes(finalRender.layoutNodes, viewportBounds);
|
|
9885
9940
|
finalWidth = viewportBounds.width;
|
|
@@ -10011,18 +10066,18 @@ function clampProgress(progress) {
|
|
|
10011
10066
|
return Math.max(0, Math.min(1, progress));
|
|
10012
10067
|
}
|
|
10013
10068
|
function easingValue(easing = "linear", progress) {
|
|
10014
|
-
const
|
|
10069
|
+
const amount2 = clampProgress(progress);
|
|
10015
10070
|
let result;
|
|
10016
10071
|
if (typeof easing === "function") {
|
|
10017
|
-
result = easing(
|
|
10072
|
+
result = easing(amount2);
|
|
10018
10073
|
} else if (easing === "ease-in") {
|
|
10019
|
-
result =
|
|
10074
|
+
result = amount2 * amount2 * amount2;
|
|
10020
10075
|
} else if (easing === "ease-out") {
|
|
10021
|
-
result = 1 - (1 -
|
|
10076
|
+
result = 1 - (1 - amount2) ** 3;
|
|
10022
10077
|
} else if (easing === "ease-in-out") {
|
|
10023
|
-
result =
|
|
10078
|
+
result = amount2 < 0.5 ? 4 * amount2 * amount2 * amount2 : 1 - (-2 * amount2 + 2) ** 3 / 2;
|
|
10024
10079
|
} else if (easing === "linear") {
|
|
10025
|
-
result =
|
|
10080
|
+
result = amount2;
|
|
10026
10081
|
} else {
|
|
10027
10082
|
throw new Error(`Unknown animation easing: ${String(easing)}`);
|
|
10028
10083
|
}
|
|
@@ -10094,8 +10149,8 @@ function defineAnimation(definition) {
|
|
|
10094
10149
|
fps
|
|
10095
10150
|
};
|
|
10096
10151
|
}
|
|
10097
|
-
function interpolateValue(from, to, progress,
|
|
10098
|
-
if (
|
|
10152
|
+
function interpolateValue(from, to, progress, interpolate2) {
|
|
10153
|
+
if (interpolate2) return interpolate2(from, to, progress);
|
|
10099
10154
|
if (typeof from === "number" && typeof to === "number" && Number.isFinite(from) && Number.isFinite(to)) {
|
|
10100
10155
|
return from + (to - from) * progress;
|
|
10101
10156
|
}
|
|
@@ -10231,6 +10286,23 @@ function sampleAnimation(animation, time) {
|
|
|
10231
10286
|
if (!Number.isFinite(time)) throw new Error("Animation sample time must be finite");
|
|
10232
10287
|
return evaluateAnimation(animation, time).state;
|
|
10233
10288
|
}
|
|
10289
|
+
function sampleAnimationFrame(animation, requestedTime, timing) {
|
|
10290
|
+
if (!Number.isFinite(requestedTime)) throw new Error("Animation sample time must be finite");
|
|
10291
|
+
const time = Math.max(0, Math.min(animation.duration, requestedTime));
|
|
10292
|
+
const evaluated = evaluateAnimation(animation, time);
|
|
10293
|
+
return {
|
|
10294
|
+
state: evaluated.state,
|
|
10295
|
+
frame: {
|
|
10296
|
+
...timing,
|
|
10297
|
+
time,
|
|
10298
|
+
duration: animation.duration,
|
|
10299
|
+
progress: time / animation.duration,
|
|
10300
|
+
step: evaluated.step,
|
|
10301
|
+
stepProgress: evaluated.stepProgress,
|
|
10302
|
+
label: evaluated.label
|
|
10303
|
+
}
|
|
10304
|
+
};
|
|
10305
|
+
}
|
|
10234
10306
|
function animationCadence(duration, fps) {
|
|
10235
10307
|
const interval = 1e3 / fps;
|
|
10236
10308
|
const times = [0];
|
|
@@ -10269,24 +10341,12 @@ function sampleAnimationFrames(animation, options = {}) {
|
|
|
10269
10341
|
assertFps(fps);
|
|
10270
10342
|
const cadence = animationCadence(animation.duration, fps);
|
|
10271
10343
|
const count = cadence.times.length;
|
|
10272
|
-
return cadence.times.map((time, index) => {
|
|
10273
|
-
|
|
10274
|
-
|
|
10275
|
-
|
|
10276
|
-
|
|
10277
|
-
|
|
10278
|
-
count,
|
|
10279
|
-
time,
|
|
10280
|
-
duration: animation.duration,
|
|
10281
|
-
delay: cadence.delays[index],
|
|
10282
|
-
progress: time / animation.duration,
|
|
10283
|
-
step: evaluated.step,
|
|
10284
|
-
stepProgress: evaluated.stepProgress,
|
|
10285
|
-
label: evaluated.label,
|
|
10286
|
-
fps
|
|
10287
|
-
}
|
|
10288
|
-
};
|
|
10289
|
-
});
|
|
10344
|
+
return cadence.times.map((time, index) => sampleAnimationFrame(animation, time, {
|
|
10345
|
+
index,
|
|
10346
|
+
count,
|
|
10347
|
+
delay: cadence.delays[index],
|
|
10348
|
+
fps
|
|
10349
|
+
}));
|
|
10290
10350
|
}
|
|
10291
10351
|
|
|
10292
10352
|
// src/animate.ts
|
|
@@ -10457,16 +10517,16 @@ function cropFramePixels(pixels, canvasWidth, region) {
|
|
|
10457
10517
|
}
|
|
10458
10518
|
function deltaPixelFrame(frame, previous, enabled) {
|
|
10459
10519
|
if (!enabled || !previous) return frame;
|
|
10460
|
-
const
|
|
10461
|
-
if (!
|
|
10520
|
+
const bounds2 = changedBounds(previous, frame.pixels, frame.width, frame.height);
|
|
10521
|
+
if (!bounds2 || bounds2.width === frame.width && bounds2.height === frame.height) return frame;
|
|
10462
10522
|
return {
|
|
10463
10523
|
...frame,
|
|
10464
|
-
x:
|
|
10465
|
-
y:
|
|
10524
|
+
x: bounds2.x,
|
|
10525
|
+
y: bounds2.y,
|
|
10466
10526
|
delta: true,
|
|
10467
|
-
width:
|
|
10468
|
-
height:
|
|
10469
|
-
pixels: cropFramePixels(frame.pixels, frame.width,
|
|
10527
|
+
width: bounds2.width,
|
|
10528
|
+
height: bounds2.height,
|
|
10529
|
+
pixels: cropFramePixels(frame.pixels, frame.width, bounds2)
|
|
10470
10530
|
};
|
|
10471
10531
|
}
|
|
10472
10532
|
function encodeGif(frames, loop, deltaFrames) {
|
|
@@ -10572,8 +10632,8 @@ async function scenesToFrames(scenes, options) {
|
|
|
10572
10632
|
);
|
|
10573
10633
|
const frameDelays = transitionFrameDelays(transitionDuration, transitionFrames);
|
|
10574
10634
|
for (let frameIndex = 0; frameIndex < transitionFrames; frameIndex += 1) {
|
|
10575
|
-
const
|
|
10576
|
-
const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels,
|
|
10635
|
+
const amount2 = (frameIndex + 1) / transitionFrames;
|
|
10636
|
+
const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount2) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme, options.background), current.pixels, amount2);
|
|
10577
10637
|
frames.push({ pixels, delay: frameDelays[frameIndex], width: scaledWidth, height: scaledHeight });
|
|
10578
10638
|
}
|
|
10579
10639
|
}
|
|
@@ -10765,6 +10825,2517 @@ async function renderAnimationGifWithOutput(animation, options) {
|
|
|
10765
10825
|
};
|
|
10766
10826
|
}
|
|
10767
10827
|
|
|
10828
|
+
// src/math.ts
|
|
10829
|
+
var import_parse_css_color3 = __toESM(require("parse-css-color"), 1);
|
|
10830
|
+
var import_liteAdaptor = require("mathjax-full/js/adaptors/liteAdaptor.js");
|
|
10831
|
+
var import_html = require("mathjax-full/js/handlers/html.js");
|
|
10832
|
+
var import_tex = require("mathjax-full/js/input/tex.js");
|
|
10833
|
+
var import_AmsConfiguration = require("mathjax-full/js/input/tex/ams/AmsConfiguration.js");
|
|
10834
|
+
var import_NewcommandConfiguration = require("mathjax-full/js/input/tex/newcommand/NewcommandConfiguration.js");
|
|
10835
|
+
var import_mathjax = require("mathjax-full/js/mathjax.js");
|
|
10836
|
+
var import_svg5 = require("mathjax-full/js/output/svg.js");
|
|
10837
|
+
var DEFAULT_FONT_SIZE = 16;
|
|
10838
|
+
var EX_FACTOR = 0.5;
|
|
10839
|
+
var adaptor = (0, import_liteAdaptor.liteAdaptor)({ fontSize: DEFAULT_FONT_SIZE });
|
|
10840
|
+
(0, import_html.RegisterHTMLHandler)(adaptor);
|
|
10841
|
+
var outputJax = new import_svg5.SVG({ fontCache: "none", exFactor: EX_FACTOR });
|
|
10842
|
+
var renderCache = /* @__PURE__ */ new Map();
|
|
10843
|
+
var RENDER_CACHE_LIMIT = 128;
|
|
10844
|
+
function createDocument() {
|
|
10845
|
+
const inputJax = new import_tex.TeX({
|
|
10846
|
+
packages: ["base", "ams", "newcommand"],
|
|
10847
|
+
formatError(_jax, error) {
|
|
10848
|
+
throw new Error(`Invalid TeX: ${error.message}`, { cause: error });
|
|
10849
|
+
}
|
|
10850
|
+
});
|
|
10851
|
+
return import_mathjax.mathjax.document("", { InputJax: inputJax, OutputJax: outputJax });
|
|
10852
|
+
}
|
|
10853
|
+
function parseEx(value, name) {
|
|
10854
|
+
if (typeof value !== "string" || !value.endsWith("ex")) {
|
|
10855
|
+
throw new Error(`MathJax returned an unsupported ${name} dimension`);
|
|
10856
|
+
}
|
|
10857
|
+
const amount2 = Number(value.slice(0, -2));
|
|
10858
|
+
if (!Number.isFinite(amount2) || amount2 <= 0) {
|
|
10859
|
+
throw new Error(`MathJax returned an invalid ${name} dimension`);
|
|
10860
|
+
}
|
|
10861
|
+
return amount2;
|
|
10862
|
+
}
|
|
10863
|
+
function parseViewBox(value) {
|
|
10864
|
+
if (typeof value !== "string") throw new Error("MathJax returned an SVG without a viewBox");
|
|
10865
|
+
const values = value.trim().split(/[ ,]+/).map(Number);
|
|
10866
|
+
if (values.length !== 4 || values.some((part) => !Number.isFinite(part)) || values[2] <= 0 || values[3] <= 0) {
|
|
10867
|
+
throw new Error("MathJax returned an invalid SVG viewBox");
|
|
10868
|
+
}
|
|
10869
|
+
return [values[0], values[1], values[2], values[3]];
|
|
10870
|
+
}
|
|
10871
|
+
function renderMathSvg(tex, options = {}) {
|
|
10872
|
+
if (typeof tex !== "string" || tex.trim().length === 0) {
|
|
10873
|
+
throw new Error("TeX input must be a non-empty string");
|
|
10874
|
+
}
|
|
10875
|
+
const fontSize = options.fontSize ?? DEFAULT_FONT_SIZE;
|
|
10876
|
+
if (!Number.isFinite(fontSize) || fontSize <= 0) {
|
|
10877
|
+
throw new Error("Math SVG fontSize must be a positive finite number");
|
|
10878
|
+
}
|
|
10879
|
+
const color = options.color ?? "#000000";
|
|
10880
|
+
if (typeof color !== "string" || !(0, import_parse_css_color3.default)(color.trim())) {
|
|
10881
|
+
throw new Error("Math SVG color must be a valid CSS color");
|
|
10882
|
+
}
|
|
10883
|
+
const normalizedColor = color.trim();
|
|
10884
|
+
const display = options.display ?? false;
|
|
10885
|
+
const key = JSON.stringify([tex, fontSize, normalizedColor, display]);
|
|
10886
|
+
const cached = renderCache.get(key);
|
|
10887
|
+
if (cached) {
|
|
10888
|
+
renderCache.delete(key);
|
|
10889
|
+
renderCache.set(key, cached);
|
|
10890
|
+
return { ...cached };
|
|
10891
|
+
}
|
|
10892
|
+
let container;
|
|
10893
|
+
try {
|
|
10894
|
+
container = createDocument().convert(tex, {
|
|
10895
|
+
display,
|
|
10896
|
+
em: fontSize,
|
|
10897
|
+
ex: fontSize * EX_FACTOR,
|
|
10898
|
+
containerWidth: fontSize * 80
|
|
10899
|
+
});
|
|
10900
|
+
} catch (cause) {
|
|
10901
|
+
if (cause instanceof Error && cause.message.startsWith("Invalid TeX:")) throw cause;
|
|
10902
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
10903
|
+
throw new Error(`Unable to render TeX: ${detail}`, { cause });
|
|
10904
|
+
}
|
|
10905
|
+
const svgElement = adaptor.tags(container, "svg")[0];
|
|
10906
|
+
if (!svgElement) throw new Error("MathJax did not produce an SVG image");
|
|
10907
|
+
const width = parseEx(adaptor.getAttribute(svgElement, "width"), "width") * fontSize * EX_FACTOR;
|
|
10908
|
+
const height = parseEx(adaptor.getAttribute(svgElement, "height"), "height") * fontSize * EX_FACTOR;
|
|
10909
|
+
if (!Number.isFinite(width) || !Number.isFinite(height)) {
|
|
10910
|
+
throw new Error("MathJax returned non-finite SVG dimensions");
|
|
10911
|
+
}
|
|
10912
|
+
const [, viewBoxY, , viewBoxHeight] = parseViewBox(adaptor.getAttribute(svgElement, "viewBox"));
|
|
10913
|
+
const baseline = -viewBoxY * height / viewBoxHeight;
|
|
10914
|
+
if (!Number.isFinite(baseline)) {
|
|
10915
|
+
throw new Error("MathJax returned an invalid SVG baseline");
|
|
10916
|
+
}
|
|
10917
|
+
const drawing = adaptor.tags(svgElement, "g")[0];
|
|
10918
|
+
if (!drawing) throw new Error("MathJax returned an SVG without a drawing group");
|
|
10919
|
+
adaptor.removeAttribute(svgElement, "style");
|
|
10920
|
+
adaptor.setAttribute(svgElement, "width", `${width}px`);
|
|
10921
|
+
adaptor.setAttribute(svgElement, "height", `${height}px`);
|
|
10922
|
+
adaptor.setAttribute(drawing, "fill", normalizedColor);
|
|
10923
|
+
adaptor.setAttribute(drawing, "stroke", normalizedColor);
|
|
10924
|
+
const result = {
|
|
10925
|
+
svg: adaptor.serializeXML(svgElement),
|
|
10926
|
+
width,
|
|
10927
|
+
height,
|
|
10928
|
+
baseline
|
|
10929
|
+
};
|
|
10930
|
+
renderCache.set(key, result);
|
|
10931
|
+
if (renderCache.size > RENDER_CACHE_LIMIT) {
|
|
10932
|
+
renderCache.delete(renderCache.keys().next().value);
|
|
10933
|
+
}
|
|
10934
|
+
return { ...result };
|
|
10935
|
+
}
|
|
10936
|
+
|
|
10937
|
+
// src/motion.ts
|
|
10938
|
+
var DEFAULT_ARC_LIFT = 80;
|
|
10939
|
+
function assertFiniteProgress(progress) {
|
|
10940
|
+
if (!Number.isFinite(progress)) throw new Error("Motion progress must be finite");
|
|
10941
|
+
}
|
|
10942
|
+
function clampProgress2(progress) {
|
|
10943
|
+
assertFiniteProgress(progress);
|
|
10944
|
+
return Math.max(0, Math.min(1, progress));
|
|
10945
|
+
}
|
|
10946
|
+
function assertPoint(point, context) {
|
|
10947
|
+
if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
|
|
10948
|
+
throw new Error(`${context} coordinates must be finite`);
|
|
10949
|
+
}
|
|
10950
|
+
}
|
|
10951
|
+
function interpolate(from, to, progress) {
|
|
10952
|
+
return {
|
|
10953
|
+
x: from.x * (1 - progress) + to.x * progress,
|
|
10954
|
+
y: from.y * (1 - progress) + to.y * progress
|
|
10955
|
+
};
|
|
10956
|
+
}
|
|
10957
|
+
function smoothstep(progress) {
|
|
10958
|
+
const amount2 = clampProgress2(progress);
|
|
10959
|
+
return amount2 * amount2 * (3 - 2 * amount2);
|
|
10960
|
+
}
|
|
10961
|
+
function arcSwap(from, to, progress, options = {}) {
|
|
10962
|
+
assertPoint(from, "Arc swap start");
|
|
10963
|
+
assertPoint(to, "Arc swap end");
|
|
10964
|
+
const amount2 = clampProgress2(progress);
|
|
10965
|
+
const lift = options.lift ?? DEFAULT_ARC_LIFT;
|
|
10966
|
+
if (!Number.isFinite(lift)) throw new Error("Arc swap lift must be finite");
|
|
10967
|
+
if (amount2 === 0) return [{ x: from.x, y: from.y }, { x: to.x, y: to.y }];
|
|
10968
|
+
if (amount2 === 1) return [{ x: to.x, y: to.y }, { x: from.x, y: from.y }];
|
|
10969
|
+
const eased = (options.easing ?? smoothstep)(amount2);
|
|
10970
|
+
if (!Number.isFinite(eased)) throw new Error("Motion easing must return a finite number");
|
|
10971
|
+
const t = Math.max(0, Math.min(1, eased));
|
|
10972
|
+
if (t === 0) return [{ x: from.x, y: from.y }, { x: to.x, y: to.y }];
|
|
10973
|
+
if (t === 1) return [{ x: to.x, y: to.y }, { x: from.x, y: from.y }];
|
|
10974
|
+
const dx = to.x - from.x;
|
|
10975
|
+
const dy = to.y - from.y;
|
|
10976
|
+
const length = Math.hypot(dx, dy);
|
|
10977
|
+
if (!Number.isFinite(length)) throw new Error("Arc swap distance must be finite");
|
|
10978
|
+
if (length === 0) return [{ x: from.x, y: from.y }, { x: to.x, y: to.y }];
|
|
10979
|
+
const normalX = -dy / length;
|
|
10980
|
+
const normalY = dx / length;
|
|
10981
|
+
const arcHeight = 4 * (1 - t) * t * lift;
|
|
10982
|
+
const firstBase = interpolate(from, to, t);
|
|
10983
|
+
const secondBase = interpolate(to, from, t);
|
|
10984
|
+
const first = {
|
|
10985
|
+
x: firstBase.x + normalX * arcHeight,
|
|
10986
|
+
y: firstBase.y + normalY * arcHeight
|
|
10987
|
+
};
|
|
10988
|
+
const second = {
|
|
10989
|
+
x: secondBase.x - normalX * arcHeight,
|
|
10990
|
+
y: secondBase.y - normalY * arcHeight
|
|
10991
|
+
};
|
|
10992
|
+
assertPoint(first, "Arc swap result");
|
|
10993
|
+
assertPoint(second, "Arc swap result");
|
|
10994
|
+
return [first, second];
|
|
10995
|
+
}
|
|
10996
|
+
function pathLengths(points) {
|
|
10997
|
+
const lengths = [];
|
|
10998
|
+
let total = 0;
|
|
10999
|
+
for (let index = 0; index < points.length; index += 1) {
|
|
11000
|
+
const point = points[index];
|
|
11001
|
+
assertPoint(point, `Path point ${index}`);
|
|
11002
|
+
if (index === 0) continue;
|
|
11003
|
+
const previous = points[index - 1];
|
|
11004
|
+
const length = Math.hypot(point.x - previous.x, point.y - previous.y);
|
|
11005
|
+
if (!Number.isFinite(length)) throw new Error("Path segment length must be finite");
|
|
11006
|
+
total += length;
|
|
11007
|
+
if (!Number.isFinite(total)) throw new Error("Path length must be finite");
|
|
11008
|
+
lengths.push(length);
|
|
11009
|
+
}
|
|
11010
|
+
return lengths;
|
|
11011
|
+
}
|
|
11012
|
+
function tracePolyline(points, progress) {
|
|
11013
|
+
const amount2 = clampProgress2(progress);
|
|
11014
|
+
if (points.length === 0) return [];
|
|
11015
|
+
const lengths = pathLengths(points);
|
|
11016
|
+
if (amount2 === 1) return points.map(({ x, y }) => ({ x, y }));
|
|
11017
|
+
const traced = [{ x: points[0].x, y: points[0].y }];
|
|
11018
|
+
if (amount2 === 0 || lengths.length === 0) return traced;
|
|
11019
|
+
const total = lengths.reduce((sum, length) => sum + length, 0);
|
|
11020
|
+
if (total === 0) return traced;
|
|
11021
|
+
const target = total * amount2;
|
|
11022
|
+
let travelled = 0;
|
|
11023
|
+
for (let index = 0; index < lengths.length; index += 1) {
|
|
11024
|
+
const segmentLength = lengths[index];
|
|
11025
|
+
const next = points[index + 1];
|
|
11026
|
+
if (segmentLength === 0) continue;
|
|
11027
|
+
const segmentEnd = travelled + segmentLength;
|
|
11028
|
+
if (target >= segmentEnd) {
|
|
11029
|
+
traced.push({ x: next.x, y: next.y });
|
|
11030
|
+
travelled = segmentEnd;
|
|
11031
|
+
continue;
|
|
11032
|
+
}
|
|
11033
|
+
const segmentProgress = (target - travelled) / segmentLength;
|
|
11034
|
+
const point = interpolate(points[index], next, segmentProgress);
|
|
11035
|
+
assertPoint(point, "Polyline trace result");
|
|
11036
|
+
const previous = traced[traced.length - 1];
|
|
11037
|
+
if (point.x !== previous.x || point.y !== previous.y) traced.push(point);
|
|
11038
|
+
return traced;
|
|
11039
|
+
}
|
|
11040
|
+
return traced;
|
|
11041
|
+
}
|
|
11042
|
+
function pointAlongPath(points, progress) {
|
|
11043
|
+
if (points.length === 0) throw new Error("Cannot find a point along an empty path");
|
|
11044
|
+
const traced = tracePolyline(points, progress);
|
|
11045
|
+
return { ...traced[traced.length - 1] };
|
|
11046
|
+
}
|
|
11047
|
+
|
|
11048
|
+
// src/canvas-components.ts
|
|
11049
|
+
function finite(value, name) {
|
|
11050
|
+
if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
|
|
11051
|
+
}
|
|
11052
|
+
function nonnegative(value, name) {
|
|
11053
|
+
finite(value, name);
|
|
11054
|
+
if (value < 0) throw new Error(`${name} must be nonnegative`);
|
|
11055
|
+
}
|
|
11056
|
+
function positive(value, name) {
|
|
11057
|
+
finite(value, name);
|
|
11058
|
+
if (value <= 0) throw new Error(`${name} must be positive`);
|
|
11059
|
+
}
|
|
11060
|
+
function normalizedOpacity(value, name = "Canvas opacity") {
|
|
11061
|
+
finite(value, name);
|
|
11062
|
+
return Math.max(0, Math.min(1, value));
|
|
11063
|
+
}
|
|
11064
|
+
function validateBounds(bounds2) {
|
|
11065
|
+
finite(bounds2.x, "Canvas x");
|
|
11066
|
+
finite(bounds2.y, "Canvas y");
|
|
11067
|
+
positive(bounds2.width, "Canvas width");
|
|
11068
|
+
positive(bounds2.height, "Canvas height");
|
|
11069
|
+
nonnegative(bounds2.radius ?? 14, "Canvas radius");
|
|
11070
|
+
}
|
|
11071
|
+
function layoutTokenRow(values, options = {}) {
|
|
11072
|
+
const { advance = 24, gap = 16, minWidth = 64, paddingX = 17, width } = options;
|
|
11073
|
+
nonnegative(advance, "Token advance");
|
|
11074
|
+
nonnegative(gap, "Token gap");
|
|
11075
|
+
positive(minWidth, "Token minimum width");
|
|
11076
|
+
nonnegative(paddingX, "Token horizontal padding");
|
|
11077
|
+
if (width !== void 0) positive(width, "Token width");
|
|
11078
|
+
if (options.x !== void 0) finite(options.x, "Token x");
|
|
11079
|
+
if (options.centerX !== void 0) finite(options.centerX, "Token center x");
|
|
11080
|
+
const items = values.map((value) => {
|
|
11081
|
+
const text = String(value);
|
|
11082
|
+
return { text, x: 0, width: width ?? Math.max(minWidth, text.length * advance + 2 * paddingX) };
|
|
11083
|
+
});
|
|
11084
|
+
const totalWidth = items.reduce((total, item) => total + item.width, 0) + Math.max(0, items.length - 1) * gap;
|
|
11085
|
+
let x = options.x ?? (options.centerX ?? 0) - totalWidth / 2;
|
|
11086
|
+
finite(x, "Token row origin");
|
|
11087
|
+
for (const item of items) {
|
|
11088
|
+
item.x = x;
|
|
11089
|
+
x += item.width + gap;
|
|
11090
|
+
finite(x, "Token row extent");
|
|
11091
|
+
}
|
|
11092
|
+
return items;
|
|
11093
|
+
}
|
|
11094
|
+
function createCanvasComponents(painter) {
|
|
11095
|
+
function fade(alpha2, draw) {
|
|
11096
|
+
const amount2 = normalizedOpacity(alpha2);
|
|
11097
|
+
if (amount2 > 0) painter.opacity(amount2, draw);
|
|
11098
|
+
}
|
|
11099
|
+
function panel(options, draw) {
|
|
11100
|
+
validateBounds(options);
|
|
11101
|
+
const { x, y, width, height, fill, stroke, radius = 14, padding = 10, id, scope = "container", opacity = 1 } = options;
|
|
11102
|
+
nonnegative(padding, "Canvas padding");
|
|
11103
|
+
const alpha2 = normalizedOpacity(opacity);
|
|
11104
|
+
if (scope !== "container" && scope !== "label") throw new Error("Canvas scope must be container or label");
|
|
11105
|
+
let shape;
|
|
11106
|
+
painter.opacity(alpha2, () => {
|
|
11107
|
+
shape = painter.rect(x, y, width, height, fill, stroke, radius);
|
|
11108
|
+
if (draw) {
|
|
11109
|
+
const bounds2 = { x, y, width, height, radius };
|
|
11110
|
+
const scopeOptions = { padding, id };
|
|
11111
|
+
if (scope === "label") painter.labelScope(bounds2, draw, scopeOptions);
|
|
11112
|
+
else painter.container(bounds2, draw, scopeOptions);
|
|
11113
|
+
}
|
|
11114
|
+
});
|
|
11115
|
+
return shape;
|
|
11116
|
+
}
|
|
11117
|
+
function card(options) {
|
|
11118
|
+
const { label, x, y, width, height, fontSize = 32, font = "sans", textColor, baselineOffset = fontSize * 0.34, labelOpacity = 1 } = options;
|
|
11119
|
+
positive(fontSize, "Canvas font size");
|
|
11120
|
+
finite(baselineOffset, "Canvas text baseline offset");
|
|
11121
|
+
const labelAlpha = normalizedOpacity(labelOpacity, "Canvas label opacity");
|
|
11122
|
+
return panel(options, () => {
|
|
11123
|
+
fade(labelAlpha, () => {
|
|
11124
|
+
painter.text(String(label), x + width / 2, y + height / 2 + baselineOffset, fontSize, textColor, "center", font);
|
|
11125
|
+
});
|
|
11126
|
+
});
|
|
11127
|
+
}
|
|
11128
|
+
function matrix(options) {
|
|
11129
|
+
const { values, x, y, cellSize = 112, gap = 8, inset = 0, format = String, style = {}, cellStyle } = options;
|
|
11130
|
+
finite(x, "Matrix x");
|
|
11131
|
+
finite(y, "Matrix y");
|
|
11132
|
+
positive(cellSize, "Matrix cell size");
|
|
11133
|
+
nonnegative(gap, "Matrix gap");
|
|
11134
|
+
finite(inset, "Matrix inset");
|
|
11135
|
+
if (gap >= cellSize) throw new Error("Matrix gap must be smaller than cell size");
|
|
11136
|
+
const columns = values[0]?.length ?? 0;
|
|
11137
|
+
for (const row of values) {
|
|
11138
|
+
if (!Array.isArray(row) || row.length !== columns) throw new Error("Canvas matrix rows must be rectangular");
|
|
11139
|
+
}
|
|
11140
|
+
const shapes = [];
|
|
11141
|
+
for (let row = 0; row < values.length; row += 1) {
|
|
11142
|
+
for (let column = 0; column < columns; column += 1) {
|
|
11143
|
+
const value = values[row][column];
|
|
11144
|
+
const cell = { ...style, ...cellStyle?.(value, row, column) };
|
|
11145
|
+
finite(cell.opacity ?? 1, "Canvas opacity");
|
|
11146
|
+
if ((cell.opacity ?? 1) <= 0) continue;
|
|
11147
|
+
const shape = card({
|
|
11148
|
+
...cell,
|
|
11149
|
+
x: x + column * cellSize + inset,
|
|
11150
|
+
y: y + row * cellSize + inset,
|
|
11151
|
+
width: cellSize - gap,
|
|
11152
|
+
height: cellSize - gap,
|
|
11153
|
+
label: format(value, row, column)
|
|
11154
|
+
});
|
|
11155
|
+
shapes.push(shape);
|
|
11156
|
+
}
|
|
11157
|
+
}
|
|
11158
|
+
return shapes;
|
|
11159
|
+
}
|
|
11160
|
+
function tokenRow(options) {
|
|
11161
|
+
const { values, y, height = 68, reveal = 1, opacity = 1, ...style } = options;
|
|
11162
|
+
finite(y, "Token row y");
|
|
11163
|
+
positive(height, "Token height");
|
|
11164
|
+
finite(reveal, "Token reveal");
|
|
11165
|
+
const alpha2 = normalizedOpacity(opacity);
|
|
11166
|
+
const items = layoutTokenRow(values, options);
|
|
11167
|
+
const shapes = [];
|
|
11168
|
+
for (let index = 0; index < items.length; index += 1) {
|
|
11169
|
+
const amount2 = Math.max(0, Math.min(1, reveal * items.length - index)) * alpha2;
|
|
11170
|
+
if (amount2 <= 0) continue;
|
|
11171
|
+
const { text: label, x, width } = items[index];
|
|
11172
|
+
const shape = card({ ...style, label, x, y, width, height, opacity: amount2 });
|
|
11173
|
+
shapes.push(shape);
|
|
11174
|
+
}
|
|
11175
|
+
return shapes;
|
|
11176
|
+
}
|
|
11177
|
+
function particle(options) {
|
|
11178
|
+
const { points, progress, radius = 9, fill, stroke, strokeWidth = 3 } = options;
|
|
11179
|
+
finite(progress, "Particle progress");
|
|
11180
|
+
positive(radius, "Particle radius");
|
|
11181
|
+
nonnegative(strokeWidth, "Particle stroke width");
|
|
11182
|
+
if (progress <= 0 || progress >= 1) return null;
|
|
11183
|
+
const point = pointAlongPath(points, progress);
|
|
11184
|
+
painter.circle(point.x, point.y, radius, fill, stroke, strokeWidth);
|
|
11185
|
+
return point;
|
|
11186
|
+
}
|
|
11187
|
+
return { panel, card, matrix, tokenRow, particle, fade };
|
|
11188
|
+
}
|
|
11189
|
+
|
|
11190
|
+
// src/teaching-transfer.ts
|
|
11191
|
+
function nonnegative2(value, name) {
|
|
11192
|
+
if (!Number.isFinite(value) || value < 0) throw new Error(`${name} must be finite and nonnegative`);
|
|
11193
|
+
}
|
|
11194
|
+
function alpha(value) {
|
|
11195
|
+
if (!Number.isFinite(value)) throw new Error("Transfer opacity must be finite");
|
|
11196
|
+
return Math.max(0, Math.min(1, value));
|
|
11197
|
+
}
|
|
11198
|
+
function bounds(shape) {
|
|
11199
|
+
if (![shape.x, shape.y, shape.width, shape.height].every(Number.isFinite) || shape.width <= 0 || shape.height <= 0) {
|
|
11200
|
+
throw new Error("Transfer endpoints require finite positive rectangular bounds");
|
|
11201
|
+
}
|
|
11202
|
+
nonnegative2(shape.radius ?? 0, "Transfer corner radius");
|
|
11203
|
+
}
|
|
11204
|
+
function center(shape) {
|
|
11205
|
+
return { x: shape.x + shape.width / 2, y: shape.y + shape.height / 2 };
|
|
11206
|
+
}
|
|
11207
|
+
function edgeDistance(shape, ux, uy) {
|
|
11208
|
+
const halfWidth = shape.width / 2, halfHeight = shape.height / 2;
|
|
11209
|
+
const limit = Math.min(ux === 0 ? Infinity : halfWidth / Math.abs(ux), uy === 0 ? Infinity : halfHeight / Math.abs(uy));
|
|
11210
|
+
const radius = Math.min(shape.radius ?? 0, halfWidth, halfHeight);
|
|
11211
|
+
if (radius === 0) return limit;
|
|
11212
|
+
const outside = (distance) => Math.hypot(
|
|
11213
|
+
Math.max(0, Math.abs(ux * distance) - (halfWidth - radius)),
|
|
11214
|
+
Math.max(0, Math.abs(uy * distance) - (halfHeight - radius))
|
|
11215
|
+
) > radius;
|
|
11216
|
+
if (!outside(limit)) return limit;
|
|
11217
|
+
let low = 0, high = limit;
|
|
11218
|
+
for (let index = 0; index < 32; index += 1) {
|
|
11219
|
+
const middle = (low + high) / 2;
|
|
11220
|
+
if (outside(middle)) high = middle;
|
|
11221
|
+
else low = middle;
|
|
11222
|
+
}
|
|
11223
|
+
return low;
|
|
11224
|
+
}
|
|
11225
|
+
function safeGap(shape, ux, uy, clearance, edge) {
|
|
11226
|
+
const expanded = Math.min(
|
|
11227
|
+
ux === 0 ? Infinity : (shape.width / 2 + clearance) / Math.abs(ux),
|
|
11228
|
+
uy === 0 ? Infinity : (shape.height / 2 + clearance) / Math.abs(uy)
|
|
11229
|
+
);
|
|
11230
|
+
return expanded - edge;
|
|
11231
|
+
}
|
|
11232
|
+
function createTeachingTransfer(painter) {
|
|
11233
|
+
return (options) => {
|
|
11234
|
+
const { source, target, color = "#63DEEC", width = 3, margin = 2, progress, particle } = options;
|
|
11235
|
+
bounds(source.shape);
|
|
11236
|
+
bounds(target.shape);
|
|
11237
|
+
nonnegative2(width, "Transfer stroke width");
|
|
11238
|
+
if (width === 0) throw new Error("Transfer stroke width must be positive");
|
|
11239
|
+
nonnegative2(margin, "Transfer margin");
|
|
11240
|
+
const opacity = Math.min(alpha(source.opacity), alpha(target.opacity), alpha(options.opacity ?? 1));
|
|
11241
|
+
for (const gap of [options.gap, options.fromGap, options.toGap]) {
|
|
11242
|
+
if (gap !== void 0) nonnegative2(gap, "Transfer gap");
|
|
11243
|
+
}
|
|
11244
|
+
if (progress !== void 0 && !Number.isFinite(progress)) throw new Error("Transfer progress must be finite");
|
|
11245
|
+
if (particle && progress === void 0) throw new Error("Transfer particle requires progress");
|
|
11246
|
+
const radius = particle?.radius ?? 7, strokeWidth = particle?.strokeWidth ?? 3;
|
|
11247
|
+
nonnegative2(radius, "Transfer particle radius");
|
|
11248
|
+
if (radius === 0) throw new Error("Transfer particle radius must be positive");
|
|
11249
|
+
nonnegative2(strokeWidth, "Transfer particle stroke width");
|
|
11250
|
+
if (opacity === 0) return null;
|
|
11251
|
+
const a = center(source.shape), z = center(target.shape);
|
|
11252
|
+
const distance = Math.hypot(z.x - a.x, z.y - a.y);
|
|
11253
|
+
if (!Number.isFinite(distance) || distance === 0) throw new Error("Transfer endpoints must have distinct finite centers");
|
|
11254
|
+
const ux = (z.x - a.x) / distance, uy = (z.y - a.y) / distance;
|
|
11255
|
+
const sourceEdge = edgeDistance(source.shape, ux, uy), targetEdge = edgeDistance(target.shape, ux, uy);
|
|
11256
|
+
const markerRadius = progress === void 0 ? 0 : radius + (particle?.stroke ? strokeWidth / 2 : 0);
|
|
11257
|
+
const clearance = Math.max(width / 2, markerRadius) + margin;
|
|
11258
|
+
const fromGap = Math.max(options.fromGap ?? options.gap ?? 0, safeGap(source.shape, ux, uy, clearance, sourceEdge));
|
|
11259
|
+
const toGap = Math.max(options.toGap ?? options.gap ?? 0, safeGap(target.shape, ux, uy, clearance, targetEdge));
|
|
11260
|
+
if (distance <= sourceEdge + targetEdge + fromGap + toGap) throw new Error("Transfer endpoints leave no room for the requested clearance");
|
|
11261
|
+
let route;
|
|
11262
|
+
painter.opacity(opacity, () => {
|
|
11263
|
+
route = painter.connect(source.shape, target.shape, { color, width, fromGap, toGap });
|
|
11264
|
+
if (progress !== void 0 && progress > 0 && progress < 1) {
|
|
11265
|
+
const x = route.from.x * (1 - progress) + route.to.x * progress;
|
|
11266
|
+
const y = route.from.y * (1 - progress) + route.to.y * progress;
|
|
11267
|
+
painter.circle(x, y, radius, particle?.fill ?? color, particle?.stroke, strokeWidth);
|
|
11268
|
+
}
|
|
11269
|
+
});
|
|
11270
|
+
return route;
|
|
11271
|
+
};
|
|
11272
|
+
}
|
|
11273
|
+
|
|
11274
|
+
// src/teaching-grid.ts
|
|
11275
|
+
function positive2(value, name) {
|
|
11276
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be finite and positive`);
|
|
11277
|
+
}
|
|
11278
|
+
function layoutCellGrid(options) {
|
|
11279
|
+
const { x, y, width, height, rows, columns } = options;
|
|
11280
|
+
if (![x, y, x + width, y + height].every(Number.isFinite)) throw new Error("Grid bounds must be finite");
|
|
11281
|
+
positive2(width, "Grid width");
|
|
11282
|
+
positive2(height, "Grid height");
|
|
11283
|
+
if (![rows, columns, rows * columns].every(Number.isSafeInteger) || rows <= 0 || columns <= 0) {
|
|
11284
|
+
throw new Error("Grid rows and columns must be positive safe integers");
|
|
11285
|
+
}
|
|
11286
|
+
const bounds2 = { x, y, width, height };
|
|
11287
|
+
const cells = Array.from({ length: rows }, (_, row) => Array.from({ length: columns }, (_2, column) => ({
|
|
11288
|
+
x: x + column * width / columns,
|
|
11289
|
+
y: y + row * height / rows,
|
|
11290
|
+
width: width / columns,
|
|
11291
|
+
height: height / rows
|
|
11292
|
+
})));
|
|
11293
|
+
return {
|
|
11294
|
+
bounds: bounds2,
|
|
11295
|
+
cells,
|
|
11296
|
+
cell(row, column) {
|
|
11297
|
+
if (!Number.isSafeInteger(row) || !Number.isSafeInteger(column) || row < 0 || row >= rows || column < 0 || column >= columns) {
|
|
11298
|
+
throw new Error("Grid cell index is outside the grid");
|
|
11299
|
+
}
|
|
11300
|
+
return cells[row][column];
|
|
11301
|
+
}
|
|
11302
|
+
};
|
|
11303
|
+
}
|
|
11304
|
+
function createTeachingGrid(painter) {
|
|
11305
|
+
const components = createCanvasComponents(painter);
|
|
11306
|
+
return (options) => {
|
|
11307
|
+
const layout = layoutCellGrid(options);
|
|
11308
|
+
const {
|
|
11309
|
+
x,
|
|
11310
|
+
y,
|
|
11311
|
+
width,
|
|
11312
|
+
height,
|
|
11313
|
+
rows,
|
|
11314
|
+
columns,
|
|
11315
|
+
fill = "#18283B",
|
|
11316
|
+
stroke = "#63DEEC",
|
|
11317
|
+
lineWidth = 1,
|
|
11318
|
+
labels,
|
|
11319
|
+
highlights = [],
|
|
11320
|
+
fontSize = 28,
|
|
11321
|
+
textColor = "#FFFFFF",
|
|
11322
|
+
padding = 4
|
|
11323
|
+
} = options;
|
|
11324
|
+
positive2(lineWidth, "Grid line width");
|
|
11325
|
+
if (lineWidth >= Math.min(width / columns, height / rows)) throw new Error("Grid line width must be smaller than a cell");
|
|
11326
|
+
positive2(fontSize, "Grid font size");
|
|
11327
|
+
if (!Number.isFinite(padding) || padding < 0) throw new Error("Grid padding must be finite and nonnegative");
|
|
11328
|
+
if (labels && (labels.length !== rows || labels.some((row) => row.length !== columns))) {
|
|
11329
|
+
throw new Error("Grid labels must match rows and columns");
|
|
11330
|
+
}
|
|
11331
|
+
for (const highlight of highlights) {
|
|
11332
|
+
layout.cell(highlight.row, highlight.column);
|
|
11333
|
+
if (!Number.isFinite(highlight.opacity ?? 1)) throw new Error("Grid highlight opacity must be finite");
|
|
11334
|
+
}
|
|
11335
|
+
const shape = components.panel({ ...layout.bounds, fill, stroke, radius: 0, padding: 0 }, () => {
|
|
11336
|
+
for (const highlight of highlights) {
|
|
11337
|
+
const cell = layout.cell(highlight.row, highlight.column);
|
|
11338
|
+
const inset2 = Math.min(2, cell.width / 4, cell.height / 4);
|
|
11339
|
+
components.fade(highlight.opacity ?? 1, () => {
|
|
11340
|
+
painter.rect(cell.x + inset2, cell.y + inset2, cell.width - 2 * inset2, cell.height - 2 * inset2, highlight.fill, highlight.stroke, 0);
|
|
11341
|
+
});
|
|
11342
|
+
}
|
|
11343
|
+
const inset = lineWidth / 2;
|
|
11344
|
+
for (let column = 1; column < columns; column += 1) {
|
|
11345
|
+
const left = x + column * width / columns;
|
|
11346
|
+
painter.path([{ x: left, y: y + inset }, { x: left, y: y + height - inset }], { color: stroke, width: lineWidth });
|
|
11347
|
+
}
|
|
11348
|
+
for (let row = 1; row < rows; row += 1) {
|
|
11349
|
+
const top = y + row * height / rows;
|
|
11350
|
+
painter.path([{ x: x + inset, y: top }, { x: x + width - inset, y: top }], { color: stroke, width: lineWidth });
|
|
11351
|
+
}
|
|
11352
|
+
labels?.forEach((row, r) => row.forEach((label, column) => {
|
|
11353
|
+
const cell = layout.cell(r, column), value = String(label);
|
|
11354
|
+
const baseline = cell.y + cell.height / 2 + fontSize * 0.34 - (value.split("\n").length - 1) * fontSize * 0.7;
|
|
11355
|
+
painter.labelScope(cell, () => painter.text(value, cell.x + cell.width / 2, baseline, fontSize, textColor, "center"), { padding });
|
|
11356
|
+
}));
|
|
11357
|
+
});
|
|
11358
|
+
return { ...layout, shape };
|
|
11359
|
+
};
|
|
11360
|
+
}
|
|
11361
|
+
|
|
11362
|
+
// src/teaching-timeline.ts
|
|
11363
|
+
function createTeachingTimeline(painter) {
|
|
11364
|
+
return (options) => {
|
|
11365
|
+
const {
|
|
11366
|
+
x,
|
|
11367
|
+
y,
|
|
11368
|
+
width,
|
|
11369
|
+
height,
|
|
11370
|
+
domain: [lo, hi],
|
|
11371
|
+
lanes,
|
|
11372
|
+
intervals,
|
|
11373
|
+
time = hi,
|
|
11374
|
+
ticks = [lo, hi],
|
|
11375
|
+
formatTime = String,
|
|
11376
|
+
labelWidth = 180,
|
|
11377
|
+
laneGap = 18,
|
|
11378
|
+
fontSize = 28,
|
|
11379
|
+
color = "#8D9CB9",
|
|
11380
|
+
trackColor = "#18283B",
|
|
11381
|
+
cursorColor = "#FFCE73"
|
|
11382
|
+
} = options;
|
|
11383
|
+
if (![x, y, x + width, y + height, lo, hi, hi - lo, time, labelWidth, laneGap, fontSize].every(Number.isFinite)) throw new Error("Timeline values must be finite");
|
|
11384
|
+
if (width <= 0 || height <= 0 || hi <= lo || time < lo || time > hi) throw new Error("Timeline needs positive bounds and a current time inside its increasing domain");
|
|
11385
|
+
if (fontSize <= 0 || labelWidth <= 12 || labelWidth >= width - 6 || laneGap < 0 || !lanes.length) throw new Error("Timeline needs positive label space, font size, and at least one lane");
|
|
11386
|
+
const ids = new Set(lanes.map((lane) => lane.id));
|
|
11387
|
+
if (ids.size !== lanes.length || lanes.some((lane) => !lane.id)) throw new Error("Timeline lane IDs must be nonempty and unique");
|
|
11388
|
+
const intervalIds = /* @__PURE__ */ new Set();
|
|
11389
|
+
for (const interval of intervals) {
|
|
11390
|
+
if (!interval.id || intervalIds.has(interval.id) || !ids.has(interval.lane)) throw new Error("Timeline intervals need unique IDs and an existing lane");
|
|
11391
|
+
intervalIds.add(interval.id);
|
|
11392
|
+
if (![interval.start, interval.end, interval.opacity ?? 1].every(Number.isFinite) || interval.start < lo || interval.end > hi || interval.end <= interval.start) throw new Error("Timeline intervals must have finite positive durations inside the domain");
|
|
11393
|
+
}
|
|
11394
|
+
for (const lane of lanes) {
|
|
11395
|
+
const ordered = intervals.filter((interval) => interval.lane === lane.id).sort((a, b) => a.start - b.start);
|
|
11396
|
+
if (ordered.some((interval, i) => i > 0 && interval.start < ordered[i - 1].end)) throw new Error(`Timeline intervals overlap in lane ${lane.id}; use separate lanes for concurrent work`);
|
|
11397
|
+
}
|
|
11398
|
+
if (ticks.some((tick) => !Number.isFinite(tick) || tick < lo || tick > hi)) throw new Error("Timeline ticks must lie inside the domain");
|
|
11399
|
+
const axisHeight = Math.max(36, fontSize * 2 + 18);
|
|
11400
|
+
const laneHeight = (height - axisHeight - (lanes.length - 1) * laneGap) / lanes.length;
|
|
11401
|
+
const labelHeight = fontSize * 1.5, barHeight = laneHeight - labelHeight;
|
|
11402
|
+
if (barHeight < 12) throw new Error("Timeline height cannot fit lane labels and interval bars");
|
|
11403
|
+
const left = x + labelWidth + 3, plotWidth = width - labelWidth - 6;
|
|
11404
|
+
const point = (value) => {
|
|
11405
|
+
if (!Number.isFinite(value) || value < lo || value > hi) throw new Error("Timeline point must lie inside the domain");
|
|
11406
|
+
return left + (value - lo) / (hi - lo) * plotWidth;
|
|
11407
|
+
};
|
|
11408
|
+
const bounds2 = { x, y, width, height };
|
|
11409
|
+
const result = { bounds: bounds2, time, point, lanes: /* @__PURE__ */ Object.create(null), intervals: /* @__PURE__ */ Object.create(null) };
|
|
11410
|
+
painter.container(bounds2, () => {
|
|
11411
|
+
lanes.forEach((lane, index) => {
|
|
11412
|
+
const top = y + index * (laneHeight + laneGap);
|
|
11413
|
+
const track = { x: left - 2, y: top + labelHeight, width: plotWidth + 4, height: barHeight };
|
|
11414
|
+
const shape = painter.rect(track.x, track.y, track.width, track.height, trackColor, color, 0);
|
|
11415
|
+
result.lanes[lane.id] = { shape, bounds: track };
|
|
11416
|
+
painter.labelScope({ x, y: top, width: labelWidth - 12, height: laneHeight }, () => {
|
|
11417
|
+
painter.text(lane.label, x, top + laneHeight / 2 + fontSize * 0.34, fontSize, color, "left");
|
|
11418
|
+
}, { padding: 0 });
|
|
11419
|
+
for (const interval of intervals.filter((item) => item.lane === lane.id)) {
|
|
11420
|
+
const visibleEnd = Math.max(interval.start, Math.min(time, interval.end));
|
|
11421
|
+
const elapsed = visibleEnd - interval.start;
|
|
11422
|
+
const bar = { x: point(interval.start), y: track.y + 2, width: point(visibleEnd) - point(interval.start), height: barHeight - 4 };
|
|
11423
|
+
const opacity = Math.max(0, Math.min(1, interval.opacity ?? 1));
|
|
11424
|
+
const item = { id: interval.id, shape: null, bounds: bar, elapsed, opacity, complete: time >= interval.end };
|
|
11425
|
+
result.intervals[interval.id] = item;
|
|
11426
|
+
if (elapsed === 0 || opacity === 0) continue;
|
|
11427
|
+
painter.opacity(opacity, () => {
|
|
11428
|
+
painter.container(track, () => {
|
|
11429
|
+
item.shape = painter.rect(bar.x, bar.y, bar.width, bar.height, interval.color ?? "#63DEEC", void 0, 0);
|
|
11430
|
+
}, { padding: 0 });
|
|
11431
|
+
if (interval.label) {
|
|
11432
|
+
const labelBounds = { x: point(interval.start), y: top, width: point(interval.end) - point(interval.start), height: labelHeight };
|
|
11433
|
+
painter.labelScope(labelBounds, () => painter.text(interval.label, labelBounds.x + labelBounds.width / 2, top + fontSize, fontSize, interval.color ?? "#63DEEC", "center"), { padding: 2 });
|
|
11434
|
+
}
|
|
11435
|
+
});
|
|
11436
|
+
}
|
|
11437
|
+
});
|
|
11438
|
+
const axisY = y + height - axisHeight + Math.max(10, fontSize * 0.5);
|
|
11439
|
+
painter.line(left, axisY, left + plotWidth, axisY, color, 2);
|
|
11440
|
+
for (const tick of ticks) {
|
|
11441
|
+
const px = point(tick);
|
|
11442
|
+
painter.line(px, axisY, px, axisY + 6, color, 2);
|
|
11443
|
+
painter.labelScope({ x: left - labelWidth, y: axisY + 8, width: plotWidth + labelWidth, height: fontSize * 1.5 }, () => {
|
|
11444
|
+
painter.text(formatTime(tick), px, axisY + fontSize * 1.4, fontSize, color, tick === hi ? "right" : tick === lo ? "left" : "center");
|
|
11445
|
+
}, { padding: 0 });
|
|
11446
|
+
}
|
|
11447
|
+
painter.line(point(time), axisY - 8, point(time), axisY + 8, cursorColor, 3);
|
|
11448
|
+
}, { padding: 0 });
|
|
11449
|
+
return result;
|
|
11450
|
+
};
|
|
11451
|
+
}
|
|
11452
|
+
|
|
11453
|
+
// src/teaching-allocation.ts
|
|
11454
|
+
var COLORS = ["#63DEEC", "#79A6FF", "#D6A0FF", "#FFCE73"];
|
|
11455
|
+
function layoutAllocation(options) {
|
|
11456
|
+
const { x, y, width, height, capacity, parts } = options;
|
|
11457
|
+
if (![x, y, x + width, y + height, capacity].every(Number.isFinite) || width <= 0 || height <= 0 || capacity <= 0) throw new Error("Allocation needs finite positive bounds and capacity");
|
|
11458
|
+
const ids = /* @__PURE__ */ new Set();
|
|
11459
|
+
let used = 0;
|
|
11460
|
+
for (const part of parts) {
|
|
11461
|
+
if (!part.id || ids.has(part.id)) throw new Error("Allocation part IDs must be nonempty and unique");
|
|
11462
|
+
ids.add(part.id);
|
|
11463
|
+
if (!Number.isFinite(part.value) || part.value < 0) throw new Error("Allocation values must be finite and nonnegative");
|
|
11464
|
+
used += part.value;
|
|
11465
|
+
}
|
|
11466
|
+
if (!Number.isFinite(used) || used - capacity > Number.EPSILON * Math.max(used, capacity) * 8) throw new Error("Allocation exceeds capacity");
|
|
11467
|
+
used = Math.min(used, capacity);
|
|
11468
|
+
let offset = 0;
|
|
11469
|
+
const segments = parts.map((part) => {
|
|
11470
|
+
const start = Math.min(offset, capacity);
|
|
11471
|
+
offset += part.value;
|
|
11472
|
+
return { id: part.id, value: part.value, bounds: { x: x + width * (start / capacity), y, width: width * ((Math.min(offset, capacity) - start) / capacity), height } };
|
|
11473
|
+
});
|
|
11474
|
+
const remaining = Math.max(0, capacity - used);
|
|
11475
|
+
return { bounds: { x, y, width, height }, used, remaining, parts: segments, freeBounds: { x: x + width * (used / capacity), y, width: width * (remaining / capacity), height } };
|
|
11476
|
+
}
|
|
11477
|
+
function createTeachingAllocation(painter) {
|
|
11478
|
+
return (options) => {
|
|
11479
|
+
const { x, y, width, height, fontSize = 28, unit = "", format = String, color = "#8D9CB9", trackColor = "#18283B" } = options;
|
|
11480
|
+
if (!Number.isFinite(fontSize) || fontSize <= 0) throw new Error("Allocation font size must be finite and positive");
|
|
11481
|
+
const header = fontSize * 1.7, barHeight = fontSize * 2, rowHeight = fontSize * 1.65, gap = fontSize * 0.6;
|
|
11482
|
+
if (height < header + barHeight + gap + (options.parts.length + 1) * rowHeight || width <= 6 || width * 0.67 <= fontSize) throw new Error("Allocation bounds cannot fit the strip and ledger");
|
|
11483
|
+
const layout = layoutAllocation({ ...options, x: x + 3, y: y + header + 3, width: width - 6, height: barHeight - 6 });
|
|
11484
|
+
const suffix = unit ? ` ${unit}` : "", shapes = [];
|
|
11485
|
+
let shape;
|
|
11486
|
+
painter.container({ x, y, width, height }, () => {
|
|
11487
|
+
painter.labelScope({ x, y, width, height: header }, () => painter.text(`Used ${format(layout.used)} / ${format(options.capacity)}${suffix}`, x, y + fontSize, fontSize, color, "left"), { padding: 0 });
|
|
11488
|
+
const strip = { x: x + 1, y: y + header + 1, width: width - 2, height: barHeight - 2 };
|
|
11489
|
+
shape = painter.rect(strip.x, strip.y, strip.width, strip.height, trackColor, color, 0);
|
|
11490
|
+
painter.container(strip, () => {
|
|
11491
|
+
layout.parts.forEach((part, index) => shapes.push(part.bounds.width === 0 ? null : painter.rect(part.bounds.x, part.bounds.y, part.bounds.width, part.bounds.height, options.parts[index].color ?? COLORS[index % COLORS.length], void 0, 0)));
|
|
11492
|
+
}, { padding: 0 });
|
|
11493
|
+
const rows = [...options.parts, { id: "free", label: "Free", value: layout.remaining, color }];
|
|
11494
|
+
rows.forEach((part, index) => {
|
|
11495
|
+
const top = y + header + barHeight + gap + index * rowHeight, baseline = top + rowHeight / 2 + fontSize * 0.34;
|
|
11496
|
+
painter.rect(x, top + (rowHeight - fontSize * 0.6) / 2, fontSize * 0.6, fontSize * 0.6, part.color ?? COLORS[index % COLORS.length], void 0, 0);
|
|
11497
|
+
painter.labelScope({ x: x + fontSize, y: top, width: width * 0.67 - fontSize, height: rowHeight }, () => painter.text(part.label, x + fontSize, baseline, fontSize, color, "left"), { padding: 0 });
|
|
11498
|
+
painter.labelScope({ x: x + width * 0.7, y: top, width: width * 0.3, height: rowHeight }, () => painter.text(`${format(part.value)}${suffix}`, x + width, baseline, fontSize, color, "right"), { padding: 0 });
|
|
11499
|
+
});
|
|
11500
|
+
}, { padding: 0 });
|
|
11501
|
+
return { ...layout, shapes, shape };
|
|
11502
|
+
};
|
|
11503
|
+
}
|
|
11504
|
+
|
|
11505
|
+
// src/teaching-canvas.ts
|
|
11506
|
+
var INK = "#8D9CB9";
|
|
11507
|
+
var ACCENT = "#63DEEC";
|
|
11508
|
+
var PANEL = "#18283B";
|
|
11509
|
+
function finite2(value, name) {
|
|
11510
|
+
if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
|
|
11511
|
+
}
|
|
11512
|
+
function positive3(value, name) {
|
|
11513
|
+
finite2(value, name);
|
|
11514
|
+
if (value <= 0) throw new Error(`${name} must be positive`);
|
|
11515
|
+
}
|
|
11516
|
+
function boundsOf(options) {
|
|
11517
|
+
finite2(options.x, "Teaching x");
|
|
11518
|
+
finite2(options.y, "Teaching y");
|
|
11519
|
+
positive3(options.width, "Teaching width");
|
|
11520
|
+
positive3(options.height, "Teaching height");
|
|
11521
|
+
return { x: options.x, y: options.y, width: options.width, height: options.height };
|
|
11522
|
+
}
|
|
11523
|
+
function amount(value, name = "Teaching progress") {
|
|
11524
|
+
finite2(value, name);
|
|
11525
|
+
return Math.max(0, Math.min(1, value));
|
|
11526
|
+
}
|
|
11527
|
+
function domainOf(domain, name) {
|
|
11528
|
+
finite2(domain[0], `${name} start`);
|
|
11529
|
+
finite2(domain[1], `${name} end`);
|
|
11530
|
+
if (domain[1] <= domain[0] || !Number.isFinite(domain[1] - domain[0])) {
|
|
11531
|
+
throw new Error(`${name} must have a finite positive span`);
|
|
11532
|
+
}
|
|
11533
|
+
return [domain[0], domain[1]];
|
|
11534
|
+
}
|
|
11535
|
+
function createTeachingCanvas(painter) {
|
|
11536
|
+
const components = createCanvasComponents(painter);
|
|
11537
|
+
function axes(options) {
|
|
11538
|
+
let bounds2 = boundsOf(options);
|
|
11539
|
+
const xDomain = domainOf(options.xDomain, "Plot x domain");
|
|
11540
|
+
const yDomain = domainOf(options.yDomain, "Plot y domain");
|
|
11541
|
+
if (options.equalUnits) {
|
|
11542
|
+
const xSpan = xDomain[1] - xDomain[0];
|
|
11543
|
+
const ySpan = yDomain[1] - yDomain[0];
|
|
11544
|
+
const pixelsPerUnit = Math.min(bounds2.width / xSpan, bounds2.height / ySpan);
|
|
11545
|
+
const width2 = xSpan * pixelsPerUnit;
|
|
11546
|
+
const height2 = ySpan * pixelsPerUnit;
|
|
11547
|
+
bounds2 = boundsOf({
|
|
11548
|
+
x: bounds2.x + (bounds2.width - width2) / 2,
|
|
11549
|
+
y: bounds2.y + (bounds2.height - height2) / 2,
|
|
11550
|
+
width: width2,
|
|
11551
|
+
height: height2
|
|
11552
|
+
});
|
|
11553
|
+
}
|
|
11554
|
+
const { x, y, width, height } = bounds2;
|
|
11555
|
+
const { color = INK, gridColor, fontSize = 28, xTicks = [], yTicks = [], formatX = String, formatY = String } = options;
|
|
11556
|
+
positive3(fontSize, "Axis font size");
|
|
11557
|
+
xTicks.forEach((tick) => finite2(tick, "Axis x tick"));
|
|
11558
|
+
yTicks.forEach((tick) => finite2(tick, "Axis y tick"));
|
|
11559
|
+
const plot = {
|
|
11560
|
+
bounds: bounds2,
|
|
11561
|
+
xDomain,
|
|
11562
|
+
yDomain,
|
|
11563
|
+
point(px, py) {
|
|
11564
|
+
finite2(px, "Plot point x");
|
|
11565
|
+
finite2(py, "Plot point y");
|
|
11566
|
+
const point = {
|
|
11567
|
+
x: x + (px - xDomain[0]) / (xDomain[1] - xDomain[0]) * width,
|
|
11568
|
+
y: y + height - (py - yDomain[0]) / (yDomain[1] - yDomain[0]) * height
|
|
11569
|
+
};
|
|
11570
|
+
finite2(point.x, "Mapped point x");
|
|
11571
|
+
finite2(point.y, "Mapped point y");
|
|
11572
|
+
return point;
|
|
11573
|
+
}
|
|
11574
|
+
};
|
|
11575
|
+
for (const tick of xTicks) {
|
|
11576
|
+
if (tick < xDomain[0] || tick > xDomain[1]) continue;
|
|
11577
|
+
const point = plot.point(tick, yDomain[0]);
|
|
11578
|
+
if (gridColor) painter.path([{ x: point.x, y }, { x: point.x, y: y + height }], { color: gridColor, width: 1, clip: bounds2 });
|
|
11579
|
+
painter.line(point.x, y + height, point.x, y + height + 7, color, 2);
|
|
11580
|
+
painter.text(formatX(tick), point.x, y + height + 36, fontSize, color, "center");
|
|
11581
|
+
}
|
|
11582
|
+
for (const tick of yTicks) {
|
|
11583
|
+
if (tick < yDomain[0] || tick > yDomain[1]) continue;
|
|
11584
|
+
const point = plot.point(xDomain[0], tick);
|
|
11585
|
+
if (gridColor) painter.path([{ x, y: point.y }, { x: x + width, y: point.y }], { color: gridColor, width: 1, clip: bounds2 });
|
|
11586
|
+
painter.line(x - 7, point.y, x, point.y, color, 2);
|
|
11587
|
+
painter.text(formatY(tick), x - 18, point.y + 9, fontSize, color, "right");
|
|
11588
|
+
}
|
|
11589
|
+
painter.line(x, y + height, x + width, y + height, color, 2);
|
|
11590
|
+
painter.line(x, y, x, y + height, color, 2);
|
|
11591
|
+
if (options.xLabel) painter.text(options.xLabel, x + width / 2, y + height + 72, 30, color, "center");
|
|
11592
|
+
if (options.yLabel) painter.text(options.yLabel, x, y - 26, 30, color, "left");
|
|
11593
|
+
return plot;
|
|
11594
|
+
}
|
|
11595
|
+
function curve(options) {
|
|
11596
|
+
const { plot, points, color, width = 4, progress = 1 } = options;
|
|
11597
|
+
positive3(width, "Curve width");
|
|
11598
|
+
const mapped = points.map((point) => plot.point(point.x, point.y));
|
|
11599
|
+
const visible = tracePolyline(mapped, progress);
|
|
11600
|
+
if (visible.length > 1) painter.path(visible, { color, width, clip: plot.bounds });
|
|
11601
|
+
return visible;
|
|
11602
|
+
}
|
|
11603
|
+
function scatter(options) {
|
|
11604
|
+
const { plot, points, color = ACCENT, radius = 7, opacity = 1 } = options;
|
|
11605
|
+
positive3(radius, "Scatter radius");
|
|
11606
|
+
const alpha2 = amount(opacity, "Scatter opacity");
|
|
11607
|
+
const projected = points.map((point) => {
|
|
11608
|
+
positive3(point.radius ?? radius, "Scatter point radius");
|
|
11609
|
+
return {
|
|
11610
|
+
...plot.point(point.x, point.y),
|
|
11611
|
+
radius: point.radius ?? radius,
|
|
11612
|
+
color: point.color ?? color,
|
|
11613
|
+
inDomain: point.x >= plot.xDomain[0] && point.x <= plot.xDomain[1] && point.y >= plot.yDomain[0] && point.y <= plot.yDomain[1]
|
|
11614
|
+
};
|
|
11615
|
+
});
|
|
11616
|
+
const shapes = [];
|
|
11617
|
+
if (alpha2 === 0) return shapes;
|
|
11618
|
+
painter.opacity(alpha2, () => {
|
|
11619
|
+
for (const point of projected) {
|
|
11620
|
+
if (!point.inDomain) continue;
|
|
11621
|
+
shapes.push(painter.circle(point.x, point.y, point.radius, point.color));
|
|
11622
|
+
}
|
|
11623
|
+
});
|
|
11624
|
+
return shapes;
|
|
11625
|
+
}
|
|
11626
|
+
function bars(options) {
|
|
11627
|
+
const bounds2 = boundsOf(options);
|
|
11628
|
+
const { x, y, width, height } = bounds2;
|
|
11629
|
+
const { values, labels, colors: colors2, color = ACCENT, progress = 1, showValues = false, format = String, fontSize = 28, gap = 20 } = options;
|
|
11630
|
+
positive3(fontSize, "Bar font size");
|
|
11631
|
+
finite2(gap, "Bar gap");
|
|
11632
|
+
if (gap < 0) throw new Error("Bar gap must be nonnegative");
|
|
11633
|
+
values.forEach((value) => {
|
|
11634
|
+
finite2(value, "Bar value");
|
|
11635
|
+
if (value < 0) throw new Error("Bar values must be nonnegative");
|
|
11636
|
+
});
|
|
11637
|
+
if (labels && labels.length !== values.length) throw new Error("Bar labels must match values");
|
|
11638
|
+
if (colors2 && colors2.length !== values.length) throw new Error("Bar colors must match values");
|
|
11639
|
+
const maximumValue = values.reduce((maximum2, value) => Math.max(maximum2, value), 0);
|
|
11640
|
+
const maximum = options.max ?? (maximumValue || 1);
|
|
11641
|
+
positive3(maximum, "Bar maximum");
|
|
11642
|
+
if (maximum < maximumValue) throw new Error("Bar maximum must contain every value");
|
|
11643
|
+
const reveal = amount(progress);
|
|
11644
|
+
if (!values.length) return { bars: [], slots: [], bounds: bounds2 };
|
|
11645
|
+
const barWidth = (width - gap * (values.length - 1)) / values.length;
|
|
11646
|
+
positive3(barWidth, "Bar width after gaps");
|
|
11647
|
+
const shapes = [];
|
|
11648
|
+
const slots = [];
|
|
11649
|
+
values.forEach((value, index) => {
|
|
11650
|
+
const left = x + index * (barWidth + gap);
|
|
11651
|
+
const barHeight = value / maximum * height * reveal;
|
|
11652
|
+
slots.push({ x: left, y, width: barWidth, height });
|
|
11653
|
+
shapes.push(barHeight > 0 ? painter.rect(left, y + height - barHeight, barWidth, barHeight, colors2?.[index] ?? color, void 0, Math.min(8, barWidth / 2, barHeight / 2)) : null);
|
|
11654
|
+
if (labels) painter.text(labels[index], left + barWidth / 2, y + height + 38, fontSize, INK, "center");
|
|
11655
|
+
if (showValues && reveal > 0) painter.text(format(value), left + barWidth / 2, y + height - barHeight - 14, fontSize, colors2?.[index] ?? color, "center");
|
|
11656
|
+
});
|
|
11657
|
+
return { bars: shapes, slots, bounds: bounds2 };
|
|
11658
|
+
}
|
|
11659
|
+
function flowGraph(options) {
|
|
11660
|
+
const { nodes, edges, stroke = ACCENT, fill = PANEL, textColor = "#FFFFFF", padding = 12 } = options;
|
|
11661
|
+
finite2(padding, "Flow node padding");
|
|
11662
|
+
if (padding < 0) throw new Error("Flow node padding must be nonnegative");
|
|
11663
|
+
const descriptors = /* @__PURE__ */ Object.create(null);
|
|
11664
|
+
for (const node of nodes) {
|
|
11665
|
+
if (!node.id || Object.hasOwn(descriptors, node.id)) throw new Error("Flow node IDs must be nonempty and unique");
|
|
11666
|
+
const bounds2 = boundsOf(node);
|
|
11667
|
+
positive3(node.fontSize ?? 30, "Flow node font size");
|
|
11668
|
+
finite2(node.radius ?? 14, "Flow node radius");
|
|
11669
|
+
if ((node.radius ?? 14) < 0) throw new Error("Flow node radius must be nonnegative");
|
|
11670
|
+
descriptors[node.id] = { ...bounds2, radius: node.radius ?? 14 };
|
|
11671
|
+
}
|
|
11672
|
+
for (const edge of edges) {
|
|
11673
|
+
if (!Object.hasOwn(descriptors, edge.from) || !Object.hasOwn(descriptors, edge.to)) throw new Error("Flow edge must reference existing nodes");
|
|
11674
|
+
if (edge.from === edge.to) throw new Error("Flow edges must connect distinct nodes");
|
|
11675
|
+
if (edge.progress !== void 0) amount(edge.progress);
|
|
11676
|
+
if (edge.width !== void 0) positive3(edge.width, "Flow edge width");
|
|
11677
|
+
for (const gap of [edge.gap, edge.fromGap, edge.toGap]) {
|
|
11678
|
+
if (gap !== void 0) finite2(gap, "Flow edge gap");
|
|
11679
|
+
}
|
|
11680
|
+
}
|
|
11681
|
+
const routes = edges.map((edge) => {
|
|
11682
|
+
const { from, to, progress, ...style } = edge;
|
|
11683
|
+
const route = painter.connect(descriptors[from], descriptors[to], { color: stroke, ...style });
|
|
11684
|
+
if (progress !== void 0) components.particle({ points: [route.from, route.to], progress, radius: 7, fill: style.color ?? stroke });
|
|
11685
|
+
return route;
|
|
11686
|
+
});
|
|
11687
|
+
for (const node of nodes) {
|
|
11688
|
+
const shape = components.card({
|
|
11689
|
+
...descriptors[node.id],
|
|
11690
|
+
label: node.label,
|
|
11691
|
+
id: node.id,
|
|
11692
|
+
fill: node.fill ?? fill,
|
|
11693
|
+
stroke: node.color ?? stroke,
|
|
11694
|
+
textColor,
|
|
11695
|
+
fontSize: node.fontSize ?? 30,
|
|
11696
|
+
padding
|
|
11697
|
+
});
|
|
11698
|
+
Object.assign(descriptors[node.id], shape);
|
|
11699
|
+
}
|
|
11700
|
+
return { nodes: descriptors, routes };
|
|
11701
|
+
}
|
|
11702
|
+
return { axes, curve, scatter, bars, flowGraph, transfer: createTeachingTransfer(painter), grid: createTeachingGrid(painter), timeline: createTeachingTimeline(painter), allocation: createTeachingAllocation(painter) };
|
|
11703
|
+
}
|
|
11704
|
+
|
|
11705
|
+
// src/teaching-math.ts
|
|
11706
|
+
function finite3(value, name) {
|
|
11707
|
+
if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
|
|
11708
|
+
}
|
|
11709
|
+
function finiteValues(values, name) {
|
|
11710
|
+
values.forEach((value) => finite3(value, name));
|
|
11711
|
+
}
|
|
11712
|
+
function seededRandom(seed) {
|
|
11713
|
+
if (!Number.isSafeInteger(seed)) throw new Error("Random seed must be a safe integer");
|
|
11714
|
+
let state = seed >>> 0;
|
|
11715
|
+
return () => {
|
|
11716
|
+
state = state + 1831565813 >>> 0;
|
|
11717
|
+
let value = Math.imul(state ^ state >>> 15, 1 | state);
|
|
11718
|
+
value ^= value + Math.imul(value ^ value >>> 7, 61 | value);
|
|
11719
|
+
return ((value ^ value >>> 14) >>> 0) / 4294967296;
|
|
11720
|
+
};
|
|
11721
|
+
}
|
|
11722
|
+
function lerpArray(from, to, progress) {
|
|
11723
|
+
if (from.length !== to.length) throw new Error("Interpolation vectors must have equal lengths");
|
|
11724
|
+
finite3(progress, "Interpolation progress");
|
|
11725
|
+
finiteValues(from, "Interpolation value");
|
|
11726
|
+
finiteValues(to, "Interpolation value");
|
|
11727
|
+
const result = from.map((value, index) => {
|
|
11728
|
+
const end = to[index];
|
|
11729
|
+
const blended = value * (1 - progress) + end * progress;
|
|
11730
|
+
if (Number.isFinite(blended)) return blended;
|
|
11731
|
+
const scale = Math.max(Math.abs(value), Math.abs(end));
|
|
11732
|
+
return (value / scale + (end / scale - value / scale) * progress) * scale;
|
|
11733
|
+
});
|
|
11734
|
+
finiteValues(result, "Interpolation result");
|
|
11735
|
+
return result;
|
|
11736
|
+
}
|
|
11737
|
+
function dotProduct(left, right) {
|
|
11738
|
+
if (left.length !== right.length) throw new Error("Dot product vectors must have equal lengths");
|
|
11739
|
+
finiteValues(left, "Dot product value");
|
|
11740
|
+
finiteValues(right, "Dot product value");
|
|
11741
|
+
const result = left.reduce((sum, value, index) => sum + value * right[index], 0);
|
|
11742
|
+
finite3(result, "Dot product result");
|
|
11743
|
+
return result;
|
|
11744
|
+
}
|
|
11745
|
+
function matrixWidth(matrix, name) {
|
|
11746
|
+
const width = matrix[0]?.length ?? 0;
|
|
11747
|
+
for (const row of matrix) {
|
|
11748
|
+
if (row.length !== width) throw new Error(`${name} rows must be rectangular`);
|
|
11749
|
+
finiteValues(row, `${name} value`);
|
|
11750
|
+
}
|
|
11751
|
+
return width;
|
|
11752
|
+
}
|
|
11753
|
+
function multiplyMatrices(left, right) {
|
|
11754
|
+
const inner = matrixWidth(left, "Left matrix");
|
|
11755
|
+
const columns = matrixWidth(right, "Right matrix");
|
|
11756
|
+
if (inner !== right.length) throw new Error("Matrix inner dimensions must match");
|
|
11757
|
+
return left.map((row) => Array.from({ length: columns }, (_, column) => {
|
|
11758
|
+
const result = row.reduce((sum, value, index) => sum + value * right[index][column], 0);
|
|
11759
|
+
finite3(result, "Matrix product value");
|
|
11760
|
+
return result;
|
|
11761
|
+
}));
|
|
11762
|
+
}
|
|
11763
|
+
function stableSoftmax(values, temperature = 1) {
|
|
11764
|
+
finite3(temperature, "Softmax temperature");
|
|
11765
|
+
if (temperature <= 0) throw new Error("Softmax temperature must be positive");
|
|
11766
|
+
finiteValues(values, "Softmax logit");
|
|
11767
|
+
if (!values.length) return [];
|
|
11768
|
+
const maximum = values.reduce((largest, value) => Math.max(largest, value), -Infinity);
|
|
11769
|
+
const weights = values.map((value) => Math.exp((value - maximum) / temperature));
|
|
11770
|
+
const total = weights.reduce((sum, value) => sum + value, 0);
|
|
11771
|
+
return weights.map((value) => value / total);
|
|
11772
|
+
}
|
|
11773
|
+
function entropy(probabilities, base = 2) {
|
|
11774
|
+
finite3(base, "Entropy base");
|
|
11775
|
+
if (base <= 0 || base === 1) throw new Error("Entropy base must be positive and different from one");
|
|
11776
|
+
finiteValues(probabilities, "Entropy probability");
|
|
11777
|
+
if (!probabilities.length) return 0;
|
|
11778
|
+
if (probabilities.some((value) => value < 0 || value > 1)) {
|
|
11779
|
+
throw new Error("Entropy probabilities must lie between zero and one");
|
|
11780
|
+
}
|
|
11781
|
+
const total = probabilities.reduce((sum, value) => sum + value, 0);
|
|
11782
|
+
if (Math.abs(total - 1) > 1e-9) throw new Error("Entropy probabilities must sum to one");
|
|
11783
|
+
return -probabilities.reduce((sum, value) => value === 0 ? sum : sum + value * Math.log(value), 0) / Math.log(base);
|
|
11784
|
+
}
|
|
11785
|
+
function normalizeVector(values) {
|
|
11786
|
+
finiteValues(values, "Vector value");
|
|
11787
|
+
const scale = values.reduce((largest, value) => Math.max(largest, Math.abs(value)), 0);
|
|
11788
|
+
if (scale === 0) return values.map(() => 0);
|
|
11789
|
+
const scaled = values.map((value) => value / scale);
|
|
11790
|
+
const length = Math.sqrt(scaled.reduce((sum, value) => sum + value * value, 0));
|
|
11791
|
+
return scaled.map((value) => value / length);
|
|
11792
|
+
}
|
|
11793
|
+
function sampleFunction(fn, low, high, count = 100) {
|
|
11794
|
+
finite3(low, "Sample domain start");
|
|
11795
|
+
finite3(high, "Sample domain end");
|
|
11796
|
+
if (high <= low) throw new Error("Sample domain must increase");
|
|
11797
|
+
if (!Number.isSafeInteger(count) || count < 2) throw new Error("Sample count must be an integer of at least two");
|
|
11798
|
+
return Array.from({ length: count }, (_, index) => {
|
|
11799
|
+
const amount2 = index / (count - 1);
|
|
11800
|
+
const x = low * (1 - amount2) + high * amount2;
|
|
11801
|
+
const y = fn(x);
|
|
11802
|
+
finite3(y, "Sampled function value");
|
|
11803
|
+
return { x, y };
|
|
11804
|
+
});
|
|
11805
|
+
}
|
|
11806
|
+
function gaussian(mean, sigma, x) {
|
|
11807
|
+
finite3(mean, "Gaussian mean");
|
|
11808
|
+
finite3(sigma, "Gaussian standard deviation");
|
|
11809
|
+
finite3(x, "Gaussian x");
|
|
11810
|
+
if (sigma <= 0) throw new Error("Gaussian standard deviation must be positive");
|
|
11811
|
+
const z = (x - mean) / sigma;
|
|
11812
|
+
const density = Math.exp(-0.5 * z * z) / sigma / Math.sqrt(2 * Math.PI);
|
|
11813
|
+
finite3(density, "Gaussian density");
|
|
11814
|
+
return density;
|
|
11815
|
+
}
|
|
11816
|
+
function sampleGaussian(random) {
|
|
11817
|
+
const first = random();
|
|
11818
|
+
const second = random();
|
|
11819
|
+
if (!Number.isFinite(first) || !Number.isFinite(second) || first < 0 || first >= 1 || second < 0 || second >= 1) {
|
|
11820
|
+
throw new Error("Gaussian random draws must lie in [0, 1)");
|
|
11821
|
+
}
|
|
11822
|
+
return Math.sqrt(-2 * Math.log(1 - first)) * Math.cos(2 * Math.PI * second);
|
|
11823
|
+
}
|
|
11824
|
+
|
|
11825
|
+
// src/teaching-cues.ts
|
|
11826
|
+
function position(beat, progress) {
|
|
11827
|
+
if (!Number.isSafeInteger(beat) || beat < 0) throw new Error("Cue beat must be a nonnegative safe integer");
|
|
11828
|
+
if (!Number.isFinite(progress) || progress < 0 || progress > 1) throw new Error("Cue progress must be between zero and one");
|
|
11829
|
+
if (progress === 1) {
|
|
11830
|
+
if (!Number.isSafeInteger(beat + 1)) throw new Error("Cue position exceeds the safe integer range");
|
|
11831
|
+
return { beat: beat + 1, beatP: 0 };
|
|
11832
|
+
}
|
|
11833
|
+
return { beat, beatP: progress };
|
|
11834
|
+
}
|
|
11835
|
+
function compare(left, right) {
|
|
11836
|
+
return left.beat === right.beat ? left.beatP - right.beatP : left.beat - right.beat;
|
|
11837
|
+
}
|
|
11838
|
+
function createCueTrack(options) {
|
|
11839
|
+
const ids = /* @__PURE__ */ new Set();
|
|
11840
|
+
const entry = ({ id, snapshot }) => {
|
|
11841
|
+
if (typeof id !== "string" || !id.trim() || ids.has(id)) throw new Error("Cue IDs must be nonempty and unique");
|
|
11842
|
+
ids.add(id);
|
|
11843
|
+
return Object.freeze({ id, snapshot });
|
|
11844
|
+
};
|
|
11845
|
+
const initial = entry(options.initial);
|
|
11846
|
+
const cues = options.cues.map((cue) => ({ position: position(cue.beat, cue.at), value: entry(cue) }));
|
|
11847
|
+
for (let index = 1; index < cues.length; index += 1) {
|
|
11848
|
+
if (compare(cues[index - 1].position, cues[index].position) >= 0) {
|
|
11849
|
+
throw new Error("Cue positions must be strictly increasing");
|
|
11850
|
+
}
|
|
11851
|
+
}
|
|
11852
|
+
return Object.freeze({
|
|
11853
|
+
sample(current) {
|
|
11854
|
+
const at = position(current.beat, current.beatP);
|
|
11855
|
+
let low = 0, high = cues.length;
|
|
11856
|
+
while (low < high) {
|
|
11857
|
+
const middle = Math.floor((low + high) / 2);
|
|
11858
|
+
if (compare(cues[middle].position, at) <= 0) low = middle + 1;
|
|
11859
|
+
else high = middle;
|
|
11860
|
+
}
|
|
11861
|
+
return low === 0 ? initial : cues[low - 1].value;
|
|
11862
|
+
}
|
|
11863
|
+
});
|
|
11864
|
+
}
|
|
11865
|
+
|
|
11866
|
+
// src/camera-motion.ts
|
|
11867
|
+
function clampProgress3(progress) {
|
|
11868
|
+
if (!Number.isFinite(progress)) throw new Error("Camera progress must be finite");
|
|
11869
|
+
return Math.max(0, Math.min(1, progress));
|
|
11870
|
+
}
|
|
11871
|
+
function assertCamera(camera, context) {
|
|
11872
|
+
if (!Number.isFinite(camera.x) || !Number.isFinite(camera.y)) {
|
|
11873
|
+
throw new Error(`${context} coordinates must be finite`);
|
|
11874
|
+
}
|
|
11875
|
+
if (!Number.isFinite(camera.zoom) || camera.zoom <= 0) {
|
|
11876
|
+
throw new Error(`${context} zoom must be finite and greater than zero`);
|
|
11877
|
+
}
|
|
11878
|
+
}
|
|
11879
|
+
function assertViewport(viewport) {
|
|
11880
|
+
if (!Number.isFinite(viewport.width) || viewport.width <= 0) {
|
|
11881
|
+
throw new Error("Camera viewport width must be finite and greater than zero");
|
|
11882
|
+
}
|
|
11883
|
+
if (!Number.isFinite(viewport.height) || viewport.height <= 0) {
|
|
11884
|
+
throw new Error("Camera viewport height must be finite and greater than zero");
|
|
11885
|
+
}
|
|
11886
|
+
}
|
|
11887
|
+
function assertZoomConstraints(options) {
|
|
11888
|
+
const { minZoom, maxZoom } = options;
|
|
11889
|
+
if (minZoom !== void 0 && (!Number.isFinite(minZoom) || minZoom <= 0)) {
|
|
11890
|
+
throw new Error("Camera minZoom must be finite and greater than zero");
|
|
11891
|
+
}
|
|
11892
|
+
if (maxZoom !== void 0 && (!Number.isFinite(maxZoom) || maxZoom <= 0)) {
|
|
11893
|
+
throw new Error("Camera maxZoom must be finite and greater than zero");
|
|
11894
|
+
}
|
|
11895
|
+
if (minZoom !== void 0 && maxZoom !== void 0 && minZoom > maxZoom) {
|
|
11896
|
+
throw new Error("Camera minZoom cannot exceed maxZoom");
|
|
11897
|
+
}
|
|
11898
|
+
}
|
|
11899
|
+
function assertZoomInRange(camera, options) {
|
|
11900
|
+
if (options.minZoom !== void 0 && camera.zoom < options.minZoom || options.maxZoom !== void 0 && camera.zoom > options.maxZoom) {
|
|
11901
|
+
throw new Error("Camera zoom is outside the configured range");
|
|
11902
|
+
}
|
|
11903
|
+
}
|
|
11904
|
+
function interpolateLinear(from, to, progress) {
|
|
11905
|
+
return from * (1 - progress) + to * progress;
|
|
11906
|
+
}
|
|
11907
|
+
function interpolateCamera(from, to, progress, options = {}) {
|
|
11908
|
+
assertCamera(from, "Camera start");
|
|
11909
|
+
assertCamera(to, "Camera end");
|
|
11910
|
+
assertZoomConstraints(options);
|
|
11911
|
+
assertZoomInRange(from, options);
|
|
11912
|
+
assertZoomInRange(to, options);
|
|
11913
|
+
const amount2 = clampProgress3(progress);
|
|
11914
|
+
if (amount2 === 0) return { ...from };
|
|
11915
|
+
if (amount2 === 1) return { ...to };
|
|
11916
|
+
const eased = (options.easing ?? smoothstep)(amount2);
|
|
11917
|
+
if (!Number.isFinite(eased)) throw new Error("Camera easing must return a finite number");
|
|
11918
|
+
const t = Math.max(0, Math.min(1, eased));
|
|
11919
|
+
if (t === 0) return { ...from };
|
|
11920
|
+
if (t === 1) return { ...to };
|
|
11921
|
+
const camera = {
|
|
11922
|
+
x: interpolateLinear(from.x, to.x, t),
|
|
11923
|
+
y: interpolateLinear(from.y, to.y, t),
|
|
11924
|
+
zoom: Math.exp(Math.log(from.zoom) * (1 - t) + Math.log(to.zoom) * t)
|
|
11925
|
+
};
|
|
11926
|
+
assertCamera(camera, "Camera result");
|
|
11927
|
+
assertZoomInRange(camera, options);
|
|
11928
|
+
return camera;
|
|
11929
|
+
}
|
|
11930
|
+
function cameraSvgTransform(camera, viewport) {
|
|
11931
|
+
assertCamera(camera, "Camera");
|
|
11932
|
+
assertViewport(viewport);
|
|
11933
|
+
return `translate(${viewport.width / 2} ${viewport.height / 2}) scale(${camera.zoom}) translate(${-camera.x} ${-camera.y})`;
|
|
11934
|
+
}
|
|
11935
|
+
function projectWorldPoint(point, camera, viewport) {
|
|
11936
|
+
if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
|
|
11937
|
+
throw new Error("World point coordinates must be finite");
|
|
11938
|
+
}
|
|
11939
|
+
assertCamera(camera, "Camera");
|
|
11940
|
+
assertViewport(viewport);
|
|
11941
|
+
const projected = {
|
|
11942
|
+
x: viewport.width / 2 + (point.x - camera.x) * camera.zoom,
|
|
11943
|
+
y: viewport.height / 2 + (point.y - camera.y) * camera.zoom
|
|
11944
|
+
};
|
|
11945
|
+
if (!Number.isFinite(projected.x) || !Number.isFinite(projected.y)) {
|
|
11946
|
+
throw new Error("Projected world point coordinates must be finite");
|
|
11947
|
+
}
|
|
11948
|
+
return projected;
|
|
11949
|
+
}
|
|
11950
|
+
|
|
11951
|
+
// src/path-morph.ts
|
|
11952
|
+
var DEFAULT_MORPH_SAMPLES = 64;
|
|
11953
|
+
var MAX_MORPH_SAMPLES = 4096;
|
|
11954
|
+
function clampProgress4(progress) {
|
|
11955
|
+
if (!Number.isFinite(progress)) throw new Error("Polyline morph progress must be finite");
|
|
11956
|
+
return Math.max(0, Math.min(1, progress));
|
|
11957
|
+
}
|
|
11958
|
+
function validatePolyline(points, context) {
|
|
11959
|
+
if (!Array.isArray(points) || points.length === 0) {
|
|
11960
|
+
throw new Error(`${context} polyline must be a non-empty array`);
|
|
11961
|
+
}
|
|
11962
|
+
for (let index = 0; index < points.length; index += 1) {
|
|
11963
|
+
const point = points[index];
|
|
11964
|
+
if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {
|
|
11965
|
+
throw new Error(`${context} point ${index} coordinates must be finite`);
|
|
11966
|
+
}
|
|
11967
|
+
}
|
|
11968
|
+
}
|
|
11969
|
+
function validateSamples(samples) {
|
|
11970
|
+
if (!Number.isInteger(samples) || samples < 2) {
|
|
11971
|
+
throw new Error("Polyline morph samples must be an integer of at least 2");
|
|
11972
|
+
}
|
|
11973
|
+
if (samples > MAX_MORPH_SAMPLES) {
|
|
11974
|
+
throw new Error(`Polyline morph samples cannot exceed ${MAX_MORPH_SAMPLES}`);
|
|
11975
|
+
}
|
|
11976
|
+
}
|
|
11977
|
+
function resamplePolyline(points, samples) {
|
|
11978
|
+
const lengths = points.slice(1).map((point, index) => Math.hypot(point.x - points[index].x, point.y - points[index].y));
|
|
11979
|
+
const total = lengths.reduce((sum, length) => sum + length, 0);
|
|
11980
|
+
if (!Number.isFinite(total)) throw new Error("Polyline morph arc length must be finite");
|
|
11981
|
+
if (total === 0) return Array.from({ length: samples }, () => ({ ...points[0] }));
|
|
11982
|
+
let segment = 0;
|
|
11983
|
+
let offset = 0;
|
|
11984
|
+
return Array.from({ length: samples }, (_, index) => {
|
|
11985
|
+
if (index === samples - 1) return { ...points[points.length - 1] };
|
|
11986
|
+
const distance = total * (index / (samples - 1));
|
|
11987
|
+
while (segment < lengths.length - 1 && (lengths[segment] === 0 || distance > offset + lengths[segment])) {
|
|
11988
|
+
offset += lengths[segment++];
|
|
11989
|
+
}
|
|
11990
|
+
const t = (distance - offset) / lengths[segment];
|
|
11991
|
+
const from = points[segment], to = points[segment + 1];
|
|
11992
|
+
return { x: from.x * (1 - t) + to.x * t, y: from.y * (1 - t) + to.y * t };
|
|
11993
|
+
});
|
|
11994
|
+
}
|
|
11995
|
+
function createPolylineMorph(from, to, options = {}) {
|
|
11996
|
+
validatePolyline(from, "Start");
|
|
11997
|
+
validatePolyline(to, "End");
|
|
11998
|
+
const samples = options.samples ?? DEFAULT_MORPH_SAMPLES;
|
|
11999
|
+
validateSamples(samples);
|
|
12000
|
+
const startSamples = resamplePolyline(from, samples);
|
|
12001
|
+
const endSamples = resamplePolyline(to, samples);
|
|
12002
|
+
const easing = options.easing ?? smoothstep;
|
|
12003
|
+
return (progress) => {
|
|
12004
|
+
const amount2 = clampProgress4(progress);
|
|
12005
|
+
const eased = amount2 === 0 || amount2 === 1 ? amount2 : easing(amount2);
|
|
12006
|
+
if (!Number.isFinite(eased)) throw new Error("Polyline morph easing must return a finite number");
|
|
12007
|
+
const t = Math.max(0, Math.min(1, eased));
|
|
12008
|
+
return startSamples.map((start, index) => {
|
|
12009
|
+
const end = endSamples[index];
|
|
12010
|
+
return { x: start.x * (1 - t) + end.x * t, y: start.y * (1 - t) + end.y * t };
|
|
12011
|
+
});
|
|
12012
|
+
};
|
|
12013
|
+
}
|
|
12014
|
+
function morphPolyline(from, to, progress, options = {}) {
|
|
12015
|
+
return createPolylineMorph(from, to, options)(progress);
|
|
12016
|
+
}
|
|
12017
|
+
|
|
12018
|
+
// src/video.ts
|
|
12019
|
+
var import_child_process = require("child_process");
|
|
12020
|
+
var import_crypto = require("crypto");
|
|
12021
|
+
var import_promises3 = require("fs/promises");
|
|
12022
|
+
var import_path3 = require("path");
|
|
12023
|
+
var import_resvg_js3 = require("@resvg/resvg-js");
|
|
12024
|
+
var import_parse_css_color4 = __toESM(require("parse-css-color"), 1);
|
|
12025
|
+
var MAX_STDERR_CHARS = 8192;
|
|
12026
|
+
function validateTiming(duration, fps) {
|
|
12027
|
+
if (!Number.isFinite(duration) || duration <= 0) {
|
|
12028
|
+
throw new Error("duration must be a positive finite number");
|
|
12029
|
+
}
|
|
12030
|
+
if (!Number.isInteger(fps) || fps < 1 || fps > 120) {
|
|
12031
|
+
throw new Error("fps must be an integer between 1 and 120");
|
|
12032
|
+
}
|
|
12033
|
+
const count = Math.round(duration * fps / 1e3);
|
|
12034
|
+
if (!Number.isSafeInteger(count) || count < 1) {
|
|
12035
|
+
throw new Error("duration must round to at least one frame and no more than Number.MAX_SAFE_INTEGER frames");
|
|
12036
|
+
}
|
|
12037
|
+
return { count, duration: count * 1e3 / fps };
|
|
12038
|
+
}
|
|
12039
|
+
function frameInfo(index, schedule, fps) {
|
|
12040
|
+
return {
|
|
12041
|
+
index,
|
|
12042
|
+
count: schedule.count,
|
|
12043
|
+
time: index * 1e3 / fps,
|
|
12044
|
+
duration: schedule.duration,
|
|
12045
|
+
progress: index / schedule.count,
|
|
12046
|
+
fps
|
|
12047
|
+
};
|
|
12048
|
+
}
|
|
12049
|
+
function* videoFrameSchedule(duration, fps = 30) {
|
|
12050
|
+
const schedule = validateTiming(duration, fps);
|
|
12051
|
+
for (let index = 0; index < schedule.count; index++) {
|
|
12052
|
+
yield frameInfo(index, schedule, fps);
|
|
12053
|
+
}
|
|
12054
|
+
}
|
|
12055
|
+
async function renderAnimationVideo(animation, options) {
|
|
12056
|
+
const scale = options.scale ?? 1;
|
|
12057
|
+
if (!Number.isFinite(options.width) || options.width <= 0 || !Number.isFinite(options.height) || options.height <= 0) {
|
|
12058
|
+
throw new Error("Animation width and height must be positive finite numbers");
|
|
12059
|
+
}
|
|
12060
|
+
if (!Number.isFinite(scale) || scale <= 0) throw new Error("scale must be a positive finite number");
|
|
12061
|
+
const theme = options.theme ?? "dark";
|
|
12062
|
+
const background = options.background ?? "theme";
|
|
12063
|
+
const backgroundColor = background === "theme" ? getThemeColors(theme).bg : background;
|
|
12064
|
+
const parsedBackground = (0, import_parse_css_color4.default)(backgroundColor);
|
|
12065
|
+
if (!parsedBackground || parsedBackground.alpha !== 1) {
|
|
12066
|
+
throw new Error('MP4 requires an opaque background; use "theme" or an opaque CSS color');
|
|
12067
|
+
}
|
|
12068
|
+
return renderRgbaVideo(async (info) => {
|
|
12069
|
+
const sampled = sampleAnimationFrame(animation, info.time, {
|
|
12070
|
+
index: info.index,
|
|
12071
|
+
count: info.count,
|
|
12072
|
+
delay: 1e3 / info.fps,
|
|
12073
|
+
fps: info.fps
|
|
12074
|
+
});
|
|
12075
|
+
const edges = { top: false, right: false, bottom: false, left: false };
|
|
12076
|
+
const svg = await renderToSvg(animation.render(sampled.state, sampled.frame), options.width, options.height, {
|
|
12077
|
+
theme,
|
|
12078
|
+
background,
|
|
12079
|
+
watermark: options.watermark ?? options.brand,
|
|
12080
|
+
onNodeDetected: (node) => {
|
|
12081
|
+
edges.top ||= node.top < -0.5;
|
|
12082
|
+
edges.right ||= node.left + node.width > options.width + 0.5;
|
|
12083
|
+
edges.bottom ||= node.top + node.height > options.height + 0.5;
|
|
12084
|
+
edges.left ||= node.left < -0.5;
|
|
12085
|
+
}
|
|
12086
|
+
});
|
|
12087
|
+
const names = Object.keys(edges).filter((edge) => edges[edge]);
|
|
12088
|
+
if (names.length) {
|
|
12089
|
+
const overflow = {
|
|
12090
|
+
overflows: true,
|
|
12091
|
+
edges,
|
|
12092
|
+
message: `Content overflows canvas at: ${names.join(", ")}. Increase the illustration dimensions.`
|
|
12093
|
+
};
|
|
12094
|
+
throw new CanvasOverflowError(options.width, options.height, overflow, {
|
|
12095
|
+
frameIndex: info.index,
|
|
12096
|
+
frameCount: info.count,
|
|
12097
|
+
time: info.time,
|
|
12098
|
+
label: sampled.frame.label
|
|
12099
|
+
});
|
|
12100
|
+
}
|
|
12101
|
+
const rendered = new import_resvg_js3.Resvg(svg, {
|
|
12102
|
+
fitTo: { mode: "width", value: options.width * scale },
|
|
12103
|
+
background: backgroundColor
|
|
12104
|
+
}).render();
|
|
12105
|
+
if (rendered.width !== options.width * scale || rendered.height !== options.height * scale) {
|
|
12106
|
+
throw new Error("All video frames must match the scaled canvas dimensions");
|
|
12107
|
+
}
|
|
12108
|
+
return rendered.pixels;
|
|
12109
|
+
}, {
|
|
12110
|
+
...options,
|
|
12111
|
+
width: options.width * scale,
|
|
12112
|
+
height: options.height * scale,
|
|
12113
|
+
duration: animation.duration
|
|
12114
|
+
});
|
|
12115
|
+
}
|
|
12116
|
+
function abortError() {
|
|
12117
|
+
const error = new Error("Video export was aborted.");
|
|
12118
|
+
error.name = "AbortError";
|
|
12119
|
+
return error;
|
|
12120
|
+
}
|
|
12121
|
+
function withAbort(promise, signal) {
|
|
12122
|
+
if (!signal) return promise;
|
|
12123
|
+
if (signal.aborted) return Promise.reject(abortError());
|
|
12124
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
12125
|
+
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
12126
|
+
const onAbort = () => {
|
|
12127
|
+
cleanup();
|
|
12128
|
+
rejectPromise(abortError());
|
|
12129
|
+
};
|
|
12130
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
12131
|
+
promise.then(
|
|
12132
|
+
(value) => {
|
|
12133
|
+
cleanup();
|
|
12134
|
+
resolvePromise(value);
|
|
12135
|
+
},
|
|
12136
|
+
(error) => {
|
|
12137
|
+
cleanup();
|
|
12138
|
+
rejectPromise(error);
|
|
12139
|
+
}
|
|
12140
|
+
);
|
|
12141
|
+
});
|
|
12142
|
+
}
|
|
12143
|
+
function formatSeconds(durationMs) {
|
|
12144
|
+
return (durationMs / 1e3).toFixed(12).replace(/0+$/, "").replace(/\.$/, "");
|
|
12145
|
+
}
|
|
12146
|
+
function describeExit(code, signal, stderr) {
|
|
12147
|
+
const status = signal ? `signal ${signal}` : `exit code ${code}`;
|
|
12148
|
+
const detail = stderr.trim();
|
|
12149
|
+
return new Error(`FFmpeg failed (${status})${detail ? `: ${detail}` : ""}`);
|
|
12150
|
+
}
|
|
12151
|
+
async function stopEncoder(child, exited) {
|
|
12152
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
12153
|
+
child.kill("SIGTERM");
|
|
12154
|
+
let timer;
|
|
12155
|
+
const terminated = await Promise.race([
|
|
12156
|
+
exited.then(() => true),
|
|
12157
|
+
new Promise((resolvePromise) => {
|
|
12158
|
+
timer = setTimeout(() => resolvePromise(false), 1e3);
|
|
12159
|
+
})
|
|
12160
|
+
]);
|
|
12161
|
+
if (timer) clearTimeout(timer);
|
|
12162
|
+
if (!terminated) {
|
|
12163
|
+
child.kill("SIGKILL");
|
|
12164
|
+
await exited;
|
|
12165
|
+
}
|
|
12166
|
+
}
|
|
12167
|
+
async function renderRgbaVideo(renderFrame2, options) {
|
|
12168
|
+
const fps = options.fps ?? 30;
|
|
12169
|
+
const schedule = validateTiming(options.duration, fps);
|
|
12170
|
+
const { width, height } = options;
|
|
12171
|
+
if (!Number.isSafeInteger(width) || width <= 0 || width % 2 !== 0) {
|
|
12172
|
+
throw new Error("width must be a positive even integer");
|
|
12173
|
+
}
|
|
12174
|
+
if (!Number.isSafeInteger(height) || height <= 0 || height % 2 !== 0) {
|
|
12175
|
+
throw new Error("height must be a positive even integer");
|
|
12176
|
+
}
|
|
12177
|
+
const expectedBytes = width * height * 4;
|
|
12178
|
+
if (!Number.isSafeInteger(expectedBytes)) {
|
|
12179
|
+
throw new Error("frame dimensions are too large");
|
|
12180
|
+
}
|
|
12181
|
+
if (typeof renderFrame2 !== "function") throw new Error("renderFrame must be a function");
|
|
12182
|
+
if (typeof options.outputPath !== "string" || options.outputPath.length === 0) {
|
|
12183
|
+
throw new Error("outputPath must be a non-empty path");
|
|
12184
|
+
}
|
|
12185
|
+
const ffmpegPath = options.ffmpegPath ?? "ffmpeg";
|
|
12186
|
+
const preset = options.preset ?? "fast";
|
|
12187
|
+
const crf = options.crf ?? 18;
|
|
12188
|
+
const threads = options.threads ?? 4;
|
|
12189
|
+
if (typeof ffmpegPath !== "string" || ffmpegPath.length === 0) throw new Error("ffmpegPath must be a non-empty path");
|
|
12190
|
+
if (typeof preset !== "string" || preset.length === 0) throw new Error("preset must be a non-empty string");
|
|
12191
|
+
if (!Number.isInteger(crf) || crf < 0 || crf > 51) throw new Error("crf must be an integer between 0 and 51");
|
|
12192
|
+
if (!Number.isSafeInteger(threads) || threads < 1) throw new Error("threads must be a positive safe integer");
|
|
12193
|
+
if (options.audioPath !== void 0 && (typeof options.audioPath !== "string" || options.audioPath.length === 0)) {
|
|
12194
|
+
throw new Error("audioPath must be a non-empty path when provided");
|
|
12195
|
+
}
|
|
12196
|
+
if (options.signal?.aborted) throw abortError();
|
|
12197
|
+
const outputPath = (0, import_path3.resolve)(options.outputPath);
|
|
12198
|
+
const outputDirectory = (0, import_path3.dirname)(outputPath);
|
|
12199
|
+
await (0, import_promises3.mkdir)(outputDirectory, { recursive: true });
|
|
12200
|
+
const tempPath = (0, import_path3.join)(outputDirectory, `.${(0, import_path3.basename)(outputPath)}.${(0, import_crypto.randomUUID)()}.tmp.mp4`);
|
|
12201
|
+
const tempFile = await (0, import_promises3.open)(tempPath, "wx", 384);
|
|
12202
|
+
try {
|
|
12203
|
+
await tempFile.close();
|
|
12204
|
+
} catch (error) {
|
|
12205
|
+
await (0, import_promises3.rm)(tempPath, { force: true });
|
|
12206
|
+
throw error;
|
|
12207
|
+
}
|
|
12208
|
+
const seconds = formatSeconds(schedule.duration);
|
|
12209
|
+
const args = [
|
|
12210
|
+
"-hide_banner",
|
|
12211
|
+
"-loglevel",
|
|
12212
|
+
"error",
|
|
12213
|
+
"-nostdin",
|
|
12214
|
+
"-y",
|
|
12215
|
+
"-f",
|
|
12216
|
+
"rawvideo",
|
|
12217
|
+
"-pixel_format",
|
|
12218
|
+
"rgba",
|
|
12219
|
+
"-video_size",
|
|
12220
|
+
`${width}x${height}`,
|
|
12221
|
+
"-framerate",
|
|
12222
|
+
String(fps),
|
|
12223
|
+
"-i",
|
|
12224
|
+
"pipe:0"
|
|
12225
|
+
];
|
|
12226
|
+
if (options.audioPath) args.push("-i", (0, import_path3.resolve)(options.audioPath));
|
|
12227
|
+
args.push("-map", "0:v:0");
|
|
12228
|
+
if (options.audioPath) args.push("-map", "1:a:0", "-af", `asetpts=PTS-STARTPTS,apad,atrim=duration=${seconds}`);
|
|
12229
|
+
args.push(
|
|
12230
|
+
"-frames:v",
|
|
12231
|
+
String(schedule.count),
|
|
12232
|
+
"-t",
|
|
12233
|
+
seconds,
|
|
12234
|
+
"-c:v",
|
|
12235
|
+
"libx264",
|
|
12236
|
+
"-preset",
|
|
12237
|
+
preset,
|
|
12238
|
+
"-crf",
|
|
12239
|
+
String(crf),
|
|
12240
|
+
"-threads:v",
|
|
12241
|
+
String(threads),
|
|
12242
|
+
"-pix_fmt",
|
|
12243
|
+
"yuv420p"
|
|
12244
|
+
);
|
|
12245
|
+
if (options.audioPath) args.push("-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2");
|
|
12246
|
+
args.push("-movflags", "+faststart", tempPath);
|
|
12247
|
+
let stderr = "";
|
|
12248
|
+
let inputError;
|
|
12249
|
+
let child;
|
|
12250
|
+
try {
|
|
12251
|
+
child = (0, import_child_process.spawn)(ffmpegPath, args, { stdio: ["pipe", "ignore", "pipe"] });
|
|
12252
|
+
} catch (error) {
|
|
12253
|
+
await (0, import_promises3.rm)(tempPath, { force: true });
|
|
12254
|
+
throw error;
|
|
12255
|
+
}
|
|
12256
|
+
child.stderr?.on("data", (chunk) => {
|
|
12257
|
+
stderr += chunk.toString();
|
|
12258
|
+
if (stderr.length > MAX_STDERR_CHARS) stderr = stderr.slice(-MAX_STDERR_CHARS);
|
|
12259
|
+
});
|
|
12260
|
+
child.stdin?.on("error", (error) => {
|
|
12261
|
+
inputError = error;
|
|
12262
|
+
});
|
|
12263
|
+
let exitResult;
|
|
12264
|
+
const exited = new Promise((resolvePromise) => {
|
|
12265
|
+
child.once("error", (error) => {
|
|
12266
|
+
exitResult = { code: null, signal: null, error };
|
|
12267
|
+
resolvePromise(exitResult);
|
|
12268
|
+
});
|
|
12269
|
+
child.once("close", (code, signal) => {
|
|
12270
|
+
exitResult = { code, signal };
|
|
12271
|
+
resolvePromise(exitResult);
|
|
12272
|
+
});
|
|
12273
|
+
});
|
|
12274
|
+
function observeEncoder(operation, index, finishAfterSuccess) {
|
|
12275
|
+
const lastFrame = index === schedule.count - 1;
|
|
12276
|
+
const completed = (exit) => {
|
|
12277
|
+
if (!exit.error && exit.code === 0 && lastFrame) {
|
|
12278
|
+
return finishAfterSuccess ? Promise.resolve(void 0) : operation;
|
|
12279
|
+
}
|
|
12280
|
+
if (exit.error) return Promise.reject(new Error(`Unable to start FFmpeg: ${exit.error.message}`, { cause: exit.error }));
|
|
12281
|
+
return Promise.reject(describeExit(exit.code, exit.signal, stderr));
|
|
12282
|
+
};
|
|
12283
|
+
if (exitResult) return completed(exitResult);
|
|
12284
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
12285
|
+
const cleanup = () => {
|
|
12286
|
+
child.removeListener("error", onError);
|
|
12287
|
+
child.removeListener("close", onClose);
|
|
12288
|
+
};
|
|
12289
|
+
const onError = (error) => {
|
|
12290
|
+
cleanup();
|
|
12291
|
+
rejectPromise(new Error(`Unable to start FFmpeg: ${error.message}`, { cause: error }));
|
|
12292
|
+
};
|
|
12293
|
+
const onClose = (code, signal) => {
|
|
12294
|
+
cleanup();
|
|
12295
|
+
void completed({ code, signal }).then(resolvePromise, rejectPromise);
|
|
12296
|
+
};
|
|
12297
|
+
child.once("error", onError);
|
|
12298
|
+
child.once("close", onClose);
|
|
12299
|
+
operation.then(
|
|
12300
|
+
(value) => {
|
|
12301
|
+
cleanup();
|
|
12302
|
+
resolvePromise(value);
|
|
12303
|
+
},
|
|
12304
|
+
(error) => {
|
|
12305
|
+
cleanup();
|
|
12306
|
+
rejectPromise(error);
|
|
12307
|
+
}
|
|
12308
|
+
);
|
|
12309
|
+
});
|
|
12310
|
+
}
|
|
12311
|
+
try {
|
|
12312
|
+
const input = child.stdin;
|
|
12313
|
+
if (!input) throw new Error("FFmpeg did not provide a frame input stream");
|
|
12314
|
+
for (let index = 0; index < schedule.count; index++) {
|
|
12315
|
+
const info = frameInfo(index, schedule, fps);
|
|
12316
|
+
const rendered = await withAbort(observeEncoder(Promise.resolve(renderFrame2(info)), index, false), options.signal);
|
|
12317
|
+
if (!(rendered instanceof Uint8Array) || rendered.byteLength !== expectedBytes) {
|
|
12318
|
+
throw new Error(`Frame ${index} must contain exactly ${expectedBytes} RGBA bytes`);
|
|
12319
|
+
}
|
|
12320
|
+
if (inputError) throw describeExit(null, null, inputError.message || stderr);
|
|
12321
|
+
const pixels = Buffer.from(rendered.buffer, rendered.byteOffset, rendered.byteLength);
|
|
12322
|
+
const write = new Promise((resolvePromise, rejectPromise) => {
|
|
12323
|
+
input.write(pixels, (error) => error ? rejectPromise(error) : resolvePromise());
|
|
12324
|
+
});
|
|
12325
|
+
await withAbort(observeEncoder(write, index, true), options.signal);
|
|
12326
|
+
if (options.onProgress) {
|
|
12327
|
+
await withAbort(observeEncoder(Promise.resolve(options.onProgress(info)), index, false), options.signal);
|
|
12328
|
+
}
|
|
12329
|
+
}
|
|
12330
|
+
input.end();
|
|
12331
|
+
const exit = await withAbort(exited, options.signal);
|
|
12332
|
+
if (exit.error) throw new Error(`Unable to start FFmpeg: ${exit.error.message}`, { cause: exit.error });
|
|
12333
|
+
if (exit.code !== 0) throw describeExit(exit.code, exit.signal, stderr);
|
|
12334
|
+
const outputStat = await (0, import_promises3.stat)(tempPath);
|
|
12335
|
+
await (0, import_promises3.rename)(tempPath, outputPath);
|
|
12336
|
+
return {
|
|
12337
|
+
width,
|
|
12338
|
+
height,
|
|
12339
|
+
frameCount: schedule.count,
|
|
12340
|
+
duration: schedule.duration,
|
|
12341
|
+
fps,
|
|
12342
|
+
bytes: outputStat.size,
|
|
12343
|
+
outputPath,
|
|
12344
|
+
audioIncluded: options.audioPath !== void 0
|
|
12345
|
+
};
|
|
12346
|
+
} catch (error) {
|
|
12347
|
+
await stopEncoder(child, exited);
|
|
12348
|
+
if (inputError && error instanceof Error && (error.message === "write EPIPE" || error.code === "EPIPE")) {
|
|
12349
|
+
throw describeExit(null, null, stderr || inputError.message);
|
|
12350
|
+
}
|
|
12351
|
+
throw error;
|
|
12352
|
+
} finally {
|
|
12353
|
+
await (0, import_promises3.rm)(tempPath, { force: true });
|
|
12354
|
+
}
|
|
12355
|
+
}
|
|
12356
|
+
|
|
12357
|
+
// src/scene-renderer.ts
|
|
12358
|
+
var import_react16 = __toESM(require("react"), 1);
|
|
12359
|
+
var import_promises4 = require("fs/promises");
|
|
12360
|
+
var import_node_fs = require("fs");
|
|
12361
|
+
var import_node_path = require("path");
|
|
12362
|
+
var import_node_url = require("url");
|
|
12363
|
+
var import_node_crypto = require("crypto");
|
|
12364
|
+
var import_node_zlib = require("zlib");
|
|
12365
|
+
var import_resvg_js4 = require("@resvg/resvg-js");
|
|
12366
|
+
|
|
12367
|
+
// src/scene-runtime.ts
|
|
12368
|
+
var import_quickjs_emscripten = require("quickjs-emscripten");
|
|
12369
|
+
var import_sucrase = require("sucrase");
|
|
12370
|
+
|
|
12371
|
+
// src/bare-source.ts
|
|
12372
|
+
function readJsxTag(source, start) {
|
|
12373
|
+
if (source.startsWith("<>", start)) return { closing: false, end: start + 2, selfClosing: false };
|
|
12374
|
+
if (source.startsWith("</>", start)) return { closing: true, end: start + 3, selfClosing: false };
|
|
12375
|
+
const head = source.slice(start).match(/^<\s*(\/\s*)?[A-Za-z][\w.:$-]*/);
|
|
12376
|
+
if (!head) return void 0;
|
|
12377
|
+
const closing = Boolean(head[1]);
|
|
12378
|
+
let quote;
|
|
12379
|
+
let braces = 0;
|
|
12380
|
+
let escaped = false;
|
|
12381
|
+
for (let index = start + head[0].length; index < source.length; index += 1) {
|
|
12382
|
+
const character = source[index];
|
|
12383
|
+
if (quote) {
|
|
12384
|
+
if (escaped) escaped = false;
|
|
12385
|
+
else if (character === "\\") escaped = true;
|
|
12386
|
+
else if (character === quote) quote = void 0;
|
|
12387
|
+
continue;
|
|
12388
|
+
}
|
|
12389
|
+
if (character === '"' || character === "'" || character === "`") {
|
|
12390
|
+
quote = character;
|
|
12391
|
+
continue;
|
|
12392
|
+
}
|
|
12393
|
+
if (character === "{") {
|
|
12394
|
+
braces += 1;
|
|
12395
|
+
continue;
|
|
12396
|
+
}
|
|
12397
|
+
if (character === "}") {
|
|
12398
|
+
braces = Math.max(0, braces - 1);
|
|
12399
|
+
continue;
|
|
12400
|
+
}
|
|
12401
|
+
if (character !== ">" || braces > 0) continue;
|
|
12402
|
+
const beforeClose = source.slice(start, index).trimEnd();
|
|
12403
|
+
return {
|
|
12404
|
+
closing,
|
|
12405
|
+
end: index + 1,
|
|
12406
|
+
selfClosing: !closing && beforeClose.endsWith("/")
|
|
12407
|
+
};
|
|
12408
|
+
}
|
|
12409
|
+
return void 0;
|
|
12410
|
+
}
|
|
12411
|
+
function skipJsxExpression(source, start) {
|
|
12412
|
+
let depth = 0;
|
|
12413
|
+
let quote;
|
|
12414
|
+
let escaped = false;
|
|
12415
|
+
let blockComment = false;
|
|
12416
|
+
let lineComment = false;
|
|
12417
|
+
for (let index = start; index < source.length; index += 1) {
|
|
12418
|
+
const character = source[index];
|
|
12419
|
+
const next = source[index + 1];
|
|
12420
|
+
if (lineComment) {
|
|
12421
|
+
if (character === "\n") lineComment = false;
|
|
12422
|
+
continue;
|
|
12423
|
+
}
|
|
12424
|
+
if (blockComment) {
|
|
12425
|
+
if (character === "*" && next === "/") {
|
|
12426
|
+
blockComment = false;
|
|
12427
|
+
index += 1;
|
|
12428
|
+
}
|
|
12429
|
+
continue;
|
|
12430
|
+
}
|
|
12431
|
+
if (quote) {
|
|
12432
|
+
if (escaped) escaped = false;
|
|
12433
|
+
else if (character === "\\") escaped = true;
|
|
12434
|
+
else if (character === quote) quote = void 0;
|
|
12435
|
+
continue;
|
|
12436
|
+
}
|
|
12437
|
+
if (character === "/" && next === "/") {
|
|
12438
|
+
lineComment = true;
|
|
12439
|
+
index += 1;
|
|
12440
|
+
continue;
|
|
12441
|
+
}
|
|
12442
|
+
if (character === "/" && next === "*") {
|
|
12443
|
+
blockComment = true;
|
|
12444
|
+
index += 1;
|
|
12445
|
+
continue;
|
|
12446
|
+
}
|
|
12447
|
+
if (character === '"' || character === "'" || character === "`") {
|
|
12448
|
+
quote = character;
|
|
12449
|
+
continue;
|
|
12450
|
+
}
|
|
12451
|
+
if (character === "{") depth += 1;
|
|
12452
|
+
else if (character === "}" && --depth === 0) return index + 1;
|
|
12453
|
+
}
|
|
12454
|
+
return void 0;
|
|
12455
|
+
}
|
|
12456
|
+
function findJsxEnd(source, start) {
|
|
12457
|
+
let depth = 0;
|
|
12458
|
+
for (let index = start; index < source.length; index += 1) {
|
|
12459
|
+
if (source[index] === "{") {
|
|
12460
|
+
const expressionEnd = skipJsxExpression(source, index);
|
|
12461
|
+
if (expressionEnd == null) return void 0;
|
|
12462
|
+
index = expressionEnd - 1;
|
|
12463
|
+
continue;
|
|
12464
|
+
}
|
|
12465
|
+
if (source[index] !== "<") continue;
|
|
12466
|
+
const tag = readJsxTag(source, index);
|
|
12467
|
+
if (!tag) continue;
|
|
12468
|
+
if (tag.closing) depth -= 1;
|
|
12469
|
+
else if (!tag.selfClosing) depth += 1;
|
|
12470
|
+
index = tag.end - 1;
|
|
12471
|
+
if (depth === 0) return tag.end;
|
|
12472
|
+
}
|
|
12473
|
+
return void 0;
|
|
12474
|
+
}
|
|
12475
|
+
function hasOnlyTrailingSyntax(source) {
|
|
12476
|
+
let index = 0;
|
|
12477
|
+
while (index < source.length) {
|
|
12478
|
+
const rest = source.slice(index);
|
|
12479
|
+
const whitespace = rest.match(/^[\s;)]*/)?.[0].length ?? 0;
|
|
12480
|
+
index += whitespace;
|
|
12481
|
+
if (source.startsWith("//", index)) {
|
|
12482
|
+
const newline = source.indexOf("\n", index + 2);
|
|
12483
|
+
index = newline < 0 ? source.length : newline + 1;
|
|
12484
|
+
continue;
|
|
12485
|
+
}
|
|
12486
|
+
if (source.startsWith("/*", index)) {
|
|
12487
|
+
const end = source.indexOf("*/", index + 2);
|
|
12488
|
+
if (end < 0) return false;
|
|
12489
|
+
index = end + 2;
|
|
12490
|
+
continue;
|
|
12491
|
+
}
|
|
12492
|
+
return index >= source.length;
|
|
12493
|
+
}
|
|
12494
|
+
return true;
|
|
12495
|
+
}
|
|
12496
|
+
function extractRootJsx(source) {
|
|
12497
|
+
const body = source.replace(/^(?:\s*\()+\s*/, "");
|
|
12498
|
+
const end = findJsxEnd(body, 0);
|
|
12499
|
+
return (end == null ? body : body.slice(0, end)).trim();
|
|
12500
|
+
}
|
|
12501
|
+
function findBareRootJsxStart(source, allowNativeTags = false) {
|
|
12502
|
+
const candidates = source.matchAll(allowNativeTags ? /(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Za-z]|>))/g : /(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Z]|>))/g);
|
|
12503
|
+
for (const candidate of candidates) {
|
|
12504
|
+
if (candidate.index == null) continue;
|
|
12505
|
+
const lineStart = candidate.index + (candidate[1]?.length ?? 0);
|
|
12506
|
+
const expressionStart = lineStart + (candidate[2]?.length ?? 0);
|
|
12507
|
+
const jsxStart = candidate.index + candidate[0].lastIndexOf(candidate[3] ?? "<");
|
|
12508
|
+
const jsxEnd = findJsxEnd(source, jsxStart);
|
|
12509
|
+
if (jsxEnd != null && hasOnlyTrailingSyntax(source.slice(jsxEnd))) return expressionStart;
|
|
12510
|
+
}
|
|
12511
|
+
return -1;
|
|
12512
|
+
}
|
|
12513
|
+
|
|
12514
|
+
// src/scene-components.ts
|
|
12515
|
+
var SCENE_COMPONENT_NAMES = Object.freeze([
|
|
12516
|
+
"Arrow",
|
|
12517
|
+
"ArrowMarkerDef",
|
|
12518
|
+
"AxisPlot",
|
|
12519
|
+
"Badge",
|
|
12520
|
+
"BadgePill",
|
|
12521
|
+
"BarChart",
|
|
12522
|
+
"Board",
|
|
12523
|
+
"Box",
|
|
12524
|
+
"CalloutCard",
|
|
12525
|
+
"Canvas",
|
|
12526
|
+
"CanvasItem",
|
|
12527
|
+
"Card",
|
|
12528
|
+
"ChartFrame",
|
|
12529
|
+
"CodeBlock",
|
|
12530
|
+
"Column",
|
|
12531
|
+
"Comparison",
|
|
12532
|
+
"Connector",
|
|
12533
|
+
"DashedLine",
|
|
12534
|
+
"DataTable",
|
|
12535
|
+
"DataflowDiagram",
|
|
12536
|
+
"DeploymentDiagram",
|
|
12537
|
+
"DetailList",
|
|
12538
|
+
"DonutChart",
|
|
12539
|
+
"DotPoint",
|
|
12540
|
+
"EquationCard",
|
|
12541
|
+
"Flow",
|
|
12542
|
+
"FlowArrow",
|
|
12543
|
+
"GradientChip",
|
|
12544
|
+
"GraphDiagram",
|
|
12545
|
+
"Grid",
|
|
12546
|
+
"Heatmap",
|
|
12547
|
+
"Icon",
|
|
12548
|
+
"IntervalPlot",
|
|
12549
|
+
"KeyValueList",
|
|
12550
|
+
"LayeredNetwork",
|
|
12551
|
+
"Legend",
|
|
12552
|
+
"LineChart",
|
|
12553
|
+
"MathText",
|
|
12554
|
+
"Matrix",
|
|
12555
|
+
"MetricCard",
|
|
12556
|
+
"MiniBarChart",
|
|
12557
|
+
"Panel",
|
|
12558
|
+
"ParetoBarChart",
|
|
12559
|
+
"ParetoChart",
|
|
12560
|
+
"PieChart",
|
|
12561
|
+
"Pipeline",
|
|
12562
|
+
"ProgressList",
|
|
12563
|
+
"ProgressRow",
|
|
12564
|
+
"QuadrantChart",
|
|
12565
|
+
"Row",
|
|
12566
|
+
"ScatterPlot",
|
|
12567
|
+
"Scene",
|
|
12568
|
+
"SequenceDiagram",
|
|
12569
|
+
"Stack",
|
|
12570
|
+
"StackedBar",
|
|
12571
|
+
"StatusList",
|
|
12572
|
+
"StatusRow",
|
|
12573
|
+
"StepCard",
|
|
12574
|
+
"SvgFrame",
|
|
12575
|
+
"SvgMathText",
|
|
12576
|
+
"SvgPoint",
|
|
12577
|
+
"TextLabel",
|
|
12578
|
+
"Tile",
|
|
12579
|
+
"TileGrid",
|
|
12580
|
+
"TiledMatrix",
|
|
12581
|
+
"Timeline",
|
|
12582
|
+
"TitleBar",
|
|
12583
|
+
"ToneStrip",
|
|
12584
|
+
"TransformerTopology",
|
|
12585
|
+
"TreeDiagram",
|
|
12586
|
+
"ValuePill",
|
|
12587
|
+
"VectorArrow",
|
|
12588
|
+
"VectorSegment",
|
|
12589
|
+
"WindowFrame"
|
|
12590
|
+
]);
|
|
12591
|
+
var SCENE_DOM_TAGS = Object.freeze([
|
|
12592
|
+
"div",
|
|
12593
|
+
"span",
|
|
12594
|
+
"p",
|
|
12595
|
+
"strong",
|
|
12596
|
+
"em",
|
|
12597
|
+
"b",
|
|
12598
|
+
"i",
|
|
12599
|
+
"br",
|
|
12600
|
+
"svg",
|
|
12601
|
+
"g",
|
|
12602
|
+
"path",
|
|
12603
|
+
"rect",
|
|
12604
|
+
"circle",
|
|
12605
|
+
"ellipse",
|
|
12606
|
+
"line",
|
|
12607
|
+
"polyline",
|
|
12608
|
+
"polygon",
|
|
12609
|
+
"text",
|
|
12610
|
+
"tspan",
|
|
12611
|
+
"defs",
|
|
12612
|
+
"clipPath",
|
|
12613
|
+
"linearGradient",
|
|
12614
|
+
"radialGradient",
|
|
12615
|
+
"stop",
|
|
12616
|
+
"pattern",
|
|
12617
|
+
"marker",
|
|
12618
|
+
"mask",
|
|
12619
|
+
"title",
|
|
12620
|
+
"desc",
|
|
12621
|
+
"use"
|
|
12622
|
+
]);
|
|
12623
|
+
|
|
12624
|
+
// src/scene-contract.ts
|
|
12625
|
+
var SCENE_RUNTIME_VERSION = "vizmatic-scene/1";
|
|
12626
|
+
var SCENE_LIMITS = Object.freeze({
|
|
12627
|
+
sourceBytes: 131072,
|
|
12628
|
+
graphBytes: 2097152,
|
|
12629
|
+
nodes: 2e3,
|
|
12630
|
+
depth: 64,
|
|
12631
|
+
stringLength: 65536,
|
|
12632
|
+
canvasEdge: 1920,
|
|
12633
|
+
canvasPixels: 2073600,
|
|
12634
|
+
duration: 120,
|
|
12635
|
+
frames: 3600,
|
|
12636
|
+
memoryBytes: 64 * 1024 * 1024,
|
|
12637
|
+
stackBytes: 256 * 1024,
|
|
12638
|
+
evaluationMs: 250
|
|
12639
|
+
});
|
|
12640
|
+
var unsafeKeys = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
12641
|
+
function isUnsafeSceneKey(key) {
|
|
12642
|
+
return unsafeKeys.has(key);
|
|
12643
|
+
}
|
|
12644
|
+
function normalizeSceneRequest(request) {
|
|
12645
|
+
if (!request || typeof request !== "object") throw new Error("A scene request is required.");
|
|
12646
|
+
if (typeof request.source !== "string" || !request.source.trim() || new TextEncoder().encode(request.source).byteLength > SCENE_LIMITS.sourceBytes) {
|
|
12647
|
+
throw new Error(`Scene source must contain between 1 and ${SCENE_LIMITS.sourceBytes} UTF-8 bytes.`);
|
|
12648
|
+
}
|
|
12649
|
+
for (const name of ["width", "height"]) {
|
|
12650
|
+
const value = request[name];
|
|
12651
|
+
if (!Number.isInteger(value) || value < 2 || value > SCENE_LIMITS.canvasEdge || value % 2 !== 0) {
|
|
12652
|
+
throw new Error(`Scene ${name} must be an even integer from 2 to ${SCENE_LIMITS.canvasEdge}.`);
|
|
12653
|
+
}
|
|
12654
|
+
}
|
|
12655
|
+
if (request.width * request.height > SCENE_LIMITS.canvasPixels) {
|
|
12656
|
+
throw new Error(`Scene canvas supports at most ${SCENE_LIMITS.canvasPixels} pixels.`);
|
|
12657
|
+
}
|
|
12658
|
+
if (!Number.isFinite(request.duration) || request.duration <= 0 || request.duration > SCENE_LIMITS.duration) {
|
|
12659
|
+
throw new Error(`Scene duration must be greater than 0 and at most ${SCENE_LIMITS.duration} seconds.`);
|
|
12660
|
+
}
|
|
12661
|
+
const fps = request.fps ?? 24;
|
|
12662
|
+
if (!Number.isInteger(fps) || fps < 1 || fps > 60) throw new Error("Scene fps must be an integer from 1 to 60.");
|
|
12663
|
+
const frameCount = Math.round(request.duration * fps);
|
|
12664
|
+
if (frameCount < 1 || frameCount > SCENE_LIMITS.frames) {
|
|
12665
|
+
throw new Error(`Scene duration must round to between 1 and ${SCENE_LIMITS.frames} frames.`);
|
|
12666
|
+
}
|
|
12667
|
+
const theme = request.theme ?? "dark";
|
|
12668
|
+
if (theme !== "dark" && theme !== "light") throw new Error("Scene theme must be dark or light.");
|
|
12669
|
+
const seed = request.seed ?? 0;
|
|
12670
|
+
if (!Number.isInteger(seed) || seed < 0 || seed > 4294967295) throw new Error("Scene seed must be a uint32 integer.");
|
|
12671
|
+
const cues = /* @__PURE__ */ Object.create(null);
|
|
12672
|
+
if (request.cues !== void 0 && (!request.cues || typeof request.cues !== "object" || Array.isArray(request.cues))) {
|
|
12673
|
+
throw new Error("Scene cues must be an object containing times in seconds.");
|
|
12674
|
+
}
|
|
12675
|
+
const cueEntries = Object.entries(request.cues ?? {});
|
|
12676
|
+
if (cueEntries.length > 128) throw new Error("Scene supports at most 128 cues.");
|
|
12677
|
+
for (const [name, time] of cueEntries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
|
|
12678
|
+
if (!/^[A-Za-z][\w.-]{0,79}$/.test(name) || isUnsafeSceneKey(name) || !Number.isFinite(time) || time < 0 || time > request.duration) {
|
|
12679
|
+
throw new Error(`Invalid scene cue ${JSON.stringify(name)}. Cue times must be within the requested duration.`);
|
|
12680
|
+
}
|
|
12681
|
+
cues[name] = time;
|
|
12682
|
+
}
|
|
12683
|
+
return {
|
|
12684
|
+
source: request.source,
|
|
12685
|
+
width: request.width,
|
|
12686
|
+
height: request.height,
|
|
12687
|
+
duration: request.duration,
|
|
12688
|
+
fps,
|
|
12689
|
+
theme,
|
|
12690
|
+
cues,
|
|
12691
|
+
seed,
|
|
12692
|
+
frameCount
|
|
12693
|
+
};
|
|
12694
|
+
}
|
|
12695
|
+
function normalizeSceneTime(time, duration) {
|
|
12696
|
+
const value = time ?? 0;
|
|
12697
|
+
if (!Number.isFinite(value) || value < 0 || value > duration) {
|
|
12698
|
+
throw new Error("Scene time must be within its duration, in seconds.");
|
|
12699
|
+
}
|
|
12700
|
+
return value;
|
|
12701
|
+
}
|
|
12702
|
+
async function sceneSha256(value) {
|
|
12703
|
+
const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
|
|
12704
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));
|
|
12705
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
12706
|
+
}
|
|
12707
|
+
|
|
12708
|
+
// src/scene-prop-limits.ts
|
|
12709
|
+
function integer(value, name, min, max) {
|
|
12710
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
|
|
12711
|
+
throw new Error(`Editable scene ${name} must be an integer from ${min} to ${max}.`);
|
|
12712
|
+
}
|
|
12713
|
+
return value;
|
|
12714
|
+
}
|
|
12715
|
+
function finite4(value, name) {
|
|
12716
|
+
if (typeof value !== "number" || !Number.isFinite(value) || Math.abs(value) > 32768) {
|
|
12717
|
+
throw new Error(`Editable scene ${name} must be finite and within 32768 canvas units.`);
|
|
12718
|
+
}
|
|
12719
|
+
return value;
|
|
12720
|
+
}
|
|
12721
|
+
function entries(value, name, max) {
|
|
12722
|
+
if (value === void 0) return [];
|
|
12723
|
+
if (!Array.isArray(value) || value.length > max) throw new Error(`Editable scene ${name} supports at most ${max} entries.`);
|
|
12724
|
+
return value;
|
|
12725
|
+
}
|
|
12726
|
+
function record(value, name) {
|
|
12727
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Editable scene ${name} must be an object.`);
|
|
12728
|
+
return value;
|
|
12729
|
+
}
|
|
12730
|
+
function validateSceneComponentProps(name, props) {
|
|
12731
|
+
let values = 0;
|
|
12732
|
+
const check = (value, key) => {
|
|
12733
|
+
if (++values > 8192) throw new Error(`Editable scene ${name} props exceed their value budget.`);
|
|
12734
|
+
if (typeof value === "number") {
|
|
12735
|
+
if (/^(?:width|height|x|y|x1|y1|x2|y2|cx|cy|r|rx|ry|radius|length|padding|gap|nodeWidth|nodeHeight|cellSize|cellWidth|cellHeight|fontSize|nodeSize|tileWidth|minHeight)$/i.test(key)) finite4(value, `${name}.${key}`);
|
|
12736
|
+
if (/^(?:rows|cols|columns|count|repeat|gridCount|tickCount)$/i.test(key)) integer(value, `${name}.${key}`, key === "gridCount" ? 0 : 1, 2e3);
|
|
12737
|
+
}
|
|
12738
|
+
if (Array.isArray(value)) value.forEach((item) => check(item, ""));
|
|
12739
|
+
else if (value && typeof value === "object") {
|
|
12740
|
+
if (value.kind !== "vizmatic.element") Object.entries(value).forEach(([property, item]) => check(item, property));
|
|
12741
|
+
}
|
|
12742
|
+
};
|
|
12743
|
+
Object.entries(props).forEach(([key, value]) => check(value, key));
|
|
12744
|
+
if (name === "DashedLine") {
|
|
12745
|
+
const x1 = finite4(props.x1, "DashedLine.x1"), y1 = finite4(props.y1, "DashedLine.y1");
|
|
12746
|
+
const x2 = finite4(props.x2, "DashedLine.x2"), y2 = finite4(props.y2, "DashedLine.y2");
|
|
12747
|
+
const spacing = props.dotSpacing ?? 8;
|
|
12748
|
+
if (typeof spacing !== "number" || !Number.isFinite(spacing) || spacing <= 0 || Math.hypot(x2 - x1, y2 - y1) / spacing > 2e3) {
|
|
12749
|
+
throw new Error("Editable scene DashedLine requires positive dotSpacing and at most 2000 dots.");
|
|
12750
|
+
}
|
|
12751
|
+
}
|
|
12752
|
+
if (name === "TileGrid" && props.columns !== void 0) integer(props.columns, "TileGrid.columns", 1, 2e3);
|
|
12753
|
+
if (name === "TiledMatrix") {
|
|
12754
|
+
const rows = integer(props.rows, "TiledMatrix.rows", 1, 2e3);
|
|
12755
|
+
const cols = integer(props.cols, "TiledMatrix.cols", 1, 2e3);
|
|
12756
|
+
if (rows * cols > 2e3) throw new Error("Editable scene TiledMatrix supports at most 2000 cells.");
|
|
12757
|
+
}
|
|
12758
|
+
if (name === "AxisPlot" && props.gridCount !== void 0) integer(props.gridCount, "AxisPlot.gridCount", 0, 100);
|
|
12759
|
+
if (["GraphDiagram", "DataflowDiagram", "DeploymentDiagram", "TransformerTopology"].includes(name)) {
|
|
12760
|
+
for (const key of ["nodes", "groups", "boundaries", "blocks"]) entries(props[key], `${name}.${key}`, 128);
|
|
12761
|
+
for (const key of ["edges", "connections", "routes"]) entries(props[key], `${name}.${key}`, 256);
|
|
12762
|
+
}
|
|
12763
|
+
if (name === "TransformerTopology" && props.expandRepeats) {
|
|
12764
|
+
const blocks = entries(props.blocks, "TransformerTopology.blocks", 128);
|
|
12765
|
+
const total = blocks.reduce((sum, block) => sum + integer(record(block, "Transformer block").repeat ?? 1, "Transformer block.repeat", 1, 128), 0);
|
|
12766
|
+
if (total > 128) throw new Error("Editable scene TransformerTopology expands to at most 128 nodes.");
|
|
12767
|
+
}
|
|
12768
|
+
if (name === "LayeredNetwork") {
|
|
12769
|
+
const layers = entries(props.layers, "LayeredNetwork.layers", 16);
|
|
12770
|
+
const counts2 = layers.map((layer) => entries(record(layer, "Network layer").nodes, "Network layer.nodes", 32).length);
|
|
12771
|
+
const edges = counts2.reduce((sum, count, index) => sum + count * (counts2[index - 1] ?? 0), 0);
|
|
12772
|
+
if (edges > 1024) throw new Error("Editable scene LayeredNetwork supports at most 1024 connections.");
|
|
12773
|
+
}
|
|
12774
|
+
if (name === "TreeDiagram" && props.root !== void 0) {
|
|
12775
|
+
let count = 0;
|
|
12776
|
+
const tree = (node) => {
|
|
12777
|
+
if (++count > 128) throw new Error("Editable scene TreeDiagram supports at most 128 nodes.");
|
|
12778
|
+
entries(record(node, "Tree node").children, "Tree node.children", 128).forEach(tree);
|
|
12779
|
+
};
|
|
12780
|
+
tree(props.root);
|
|
12781
|
+
}
|
|
12782
|
+
if (name === "ParetoChart") entries(props.points, "ParetoChart.points", 512);
|
|
12783
|
+
}
|
|
12784
|
+
|
|
12785
|
+
// src/scene-graph.ts
|
|
12786
|
+
var componentNames = new Set(SCENE_COMPONENT_NAMES);
|
|
12787
|
+
var domTags = new Set(SCENE_DOM_TAGS);
|
|
12788
|
+
var localReference = /^#[A-Za-z_][\w:.-]*$/;
|
|
12789
|
+
var localPaint = /^url\(\s*#[A-Za-z_][\w:.-]*\s*\)$/;
|
|
12790
|
+
var resourceKeys = /^(?:background(?:image)?|fill|stroke|filter|clippath|mask(?:image)?|borderimage(?:source)?|liststyle(?:image)?|cursor|content)$/i;
|
|
12791
|
+
function validateResource(value, key, inStyle) {
|
|
12792
|
+
if (/^(?:src|href|xlinkhref|xlink:href|srcset|poster|action|formaction)$/i.test(key) && !localReference.test(value)) {
|
|
12793
|
+
throw new Error("Scene resource references must be local SVG fragment IDs. External assets are disabled.");
|
|
12794
|
+
}
|
|
12795
|
+
if ((inStyle || resourceKeys.test(key) || /gradient$/i.test(key)) && (/\\|\/\*/.test(value) || /(?:https?|file|ftp|data|blob|javascript):|\/\//i.test(value) || /url\s*\(/i.test(value) && !localPaint.test(value))) {
|
|
12796
|
+
throw new Error("Scene CSS cannot load external resources or escaped resource expressions.");
|
|
12797
|
+
}
|
|
12798
|
+
}
|
|
12799
|
+
function validateResolvedSceneResources(props) {
|
|
12800
|
+
let values = 0;
|
|
12801
|
+
const visit = (input, key, style, depth) => {
|
|
12802
|
+
if (++values > 32e3 || depth > SCENE_LIMITS.depth * 2) throw new Error("Resolved scene props exceed their value budget.");
|
|
12803
|
+
if (typeof input === "string") {
|
|
12804
|
+
validateResource(input, key, style);
|
|
12805
|
+
return;
|
|
12806
|
+
}
|
|
12807
|
+
if (Array.isArray(input)) {
|
|
12808
|
+
input.forEach((item) => visit(item, key, style, depth + 1));
|
|
12809
|
+
return;
|
|
12810
|
+
}
|
|
12811
|
+
if (input && typeof input === "object") {
|
|
12812
|
+
for (const [property, value] of Object.entries(input)) {
|
|
12813
|
+
if (property === "children") continue;
|
|
12814
|
+
if (property === "dangerouslySetInnerHTML" || property === "__html") throw new Error("Resolved scene cannot contain raw HTML.");
|
|
12815
|
+
visit(value, property, style || /style$/i.test(property), depth + 1);
|
|
12816
|
+
}
|
|
12817
|
+
}
|
|
12818
|
+
};
|
|
12819
|
+
visit(props, "", false, 0);
|
|
12820
|
+
}
|
|
12821
|
+
function validateSceneGraph(value) {
|
|
12822
|
+
let nodes = 0;
|
|
12823
|
+
const visit = (input, depth, key = "", inStyle = false) => {
|
|
12824
|
+
if (depth > SCENE_LIMITS.depth) throw new Error(`Scene graph exceeds depth ${SCENE_LIMITS.depth}.`);
|
|
12825
|
+
if (++nodes > SCENE_LIMITS.nodes * 32) throw new Error("Scene graph contains too many values.");
|
|
12826
|
+
if (input === null || typeof input === "boolean") return input;
|
|
12827
|
+
if (typeof input === "number") {
|
|
12828
|
+
if (!Number.isFinite(input) || Math.abs(input) > 1e9) throw new Error("Scene numbers must be finite and bounded.");
|
|
12829
|
+
return input;
|
|
12830
|
+
}
|
|
12831
|
+
if (typeof input === "string") {
|
|
12832
|
+
if (input.length > SCENE_LIMITS.stringLength) throw new Error("Scene string exceeds its length limit.");
|
|
12833
|
+
validateResource(input, key, inStyle);
|
|
12834
|
+
return input;
|
|
12835
|
+
}
|
|
12836
|
+
if (Array.isArray(input)) return input.map((item) => visit(item, depth + 1, key, inStyle));
|
|
12837
|
+
if (!input || typeof input !== "object" || Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null) throw new Error("Scene props must be plain JSON values.");
|
|
12838
|
+
const record2 = input;
|
|
12839
|
+
const output = /* @__PURE__ */ Object.create(null);
|
|
12840
|
+
for (const [property, item] of Object.entries(record2)) {
|
|
12841
|
+
if (isUnsafeSceneKey(property) || /^on/i.test(property) || /^(?:xml:base|xmlBase)$/i.test(property) || property === "dangerouslySetInnerHTML" || property === "ref" || property === "__html") throw new Error(`Scene property ${JSON.stringify(property)} is not allowed.`);
|
|
12842
|
+
output[property] = visit(item, depth + 1, property, inStyle || /style$/i.test(property));
|
|
12843
|
+
}
|
|
12844
|
+
if (record2.kind === "vizmatic.element") {
|
|
12845
|
+
if (typeof record2.type !== "string" || !componentNames.has(record2.type) && !domTags.has(record2.type)) {
|
|
12846
|
+
throw new Error(`Scene component ${JSON.stringify(record2.type)} is not supported.`);
|
|
12847
|
+
}
|
|
12848
|
+
if (!record2.props || typeof record2.props !== "object" || Array.isArray(record2.props) || !Array.isArray(record2.children) || Object.keys(record2).some((name) => !["kind", "type", "props", "children"].includes(name))) {
|
|
12849
|
+
throw new Error("Invalid scene element.");
|
|
12850
|
+
}
|
|
12851
|
+
if (componentNames.has(record2.type)) validateSceneComponentProps(record2.type, output.props);
|
|
12852
|
+
}
|
|
12853
|
+
return output;
|
|
12854
|
+
};
|
|
12855
|
+
const graph = visit(value, 0);
|
|
12856
|
+
let elementCount = 0;
|
|
12857
|
+
const checkChildren = (child) => {
|
|
12858
|
+
if (Array.isArray(child)) {
|
|
12859
|
+
child.forEach(checkChildren);
|
|
12860
|
+
return;
|
|
12861
|
+
}
|
|
12862
|
+
if (child === null || typeof child !== "object") return;
|
|
12863
|
+
if (child.kind !== "vizmatic.element") throw new Error("Scene children must be JSX elements, text or numbers.");
|
|
12864
|
+
if (++elementCount > SCENE_LIMITS.nodes) throw new Error(`Scene graph exceeds ${SCENE_LIMITS.nodes} elements.`);
|
|
12865
|
+
const element = child;
|
|
12866
|
+
element.children.forEach(checkChildren);
|
|
12867
|
+
const checkProps = (prop) => {
|
|
12868
|
+
if (Array.isArray(prop)) {
|
|
12869
|
+
prop.forEach(checkProps);
|
|
12870
|
+
return;
|
|
12871
|
+
}
|
|
12872
|
+
if (prop && typeof prop === "object") {
|
|
12873
|
+
if (prop.kind === "vizmatic.element") checkChildren(prop);
|
|
12874
|
+
else Object.values(prop).forEach(checkProps);
|
|
12875
|
+
}
|
|
12876
|
+
};
|
|
12877
|
+
Object.values(element.props).forEach(checkProps);
|
|
12878
|
+
};
|
|
12879
|
+
checkChildren(graph);
|
|
12880
|
+
return graph;
|
|
12881
|
+
}
|
|
12882
|
+
|
|
12883
|
+
// src/scene-runtime.ts
|
|
12884
|
+
var bootstrap = String.raw`
|
|
12885
|
+
const __jsonStringify = JSON.stringify.bind(JSON);
|
|
12886
|
+
const __objectEntries = Object.entries.bind(Object);
|
|
12887
|
+
const __isArray = Array.isArray.bind(Array);
|
|
12888
|
+
const __isFinite = Number.isFinite.bind(Number);
|
|
12889
|
+
const __Error = Error;
|
|
12890
|
+
const __ownDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
|
|
12891
|
+
const __freeze = (value) => {
|
|
12892
|
+
if (value && typeof value === 'object') {
|
|
12893
|
+
for (const child of Object.values(value)) __freeze(child);
|
|
12894
|
+
Object.freeze(value);
|
|
12895
|
+
}
|
|
12896
|
+
return value;
|
|
12897
|
+
};
|
|
12898
|
+
const clamp = (value, min = 0, max = 1) => Math.max(min, Math.min(max, value));
|
|
12899
|
+
const lerp = (from, to, amount) => from + (to - from) * amount;
|
|
12900
|
+
const ease = (amount) => { const x = clamp(amount); return x * x * (3 - 2 * x); };
|
|
12901
|
+
const easeInOut = ease;
|
|
12902
|
+
const easeOut = (amount) => 1 - Math.pow(1 - clamp(amount), 3);
|
|
12903
|
+
const cue = (name, span = 1) => {
|
|
12904
|
+
if (!Object.hasOwn(cues, name)) throw new __Error('Unknown scene cue: ' + name);
|
|
12905
|
+
if (!__isFinite(span) || span <= 0) throw new __Error('Cue span must be positive seconds.');
|
|
12906
|
+
return clamp((time - cues[name]) / span);
|
|
12907
|
+
};
|
|
12908
|
+
let __randomState = seed >>> 0;
|
|
12909
|
+
Math.random = () => {
|
|
12910
|
+
__randomState = (__randomState + 0x6D2B79F5) >>> 0;
|
|
12911
|
+
let v = Math.imul(__randomState ^ (__randomState >>> 15), 1 | __randomState);
|
|
12912
|
+
v ^= v + Math.imul(v ^ (v >>> 7), 61 | v);
|
|
12913
|
+
return ((v ^ (v >>> 14)) >>> 0) / 4294967296;
|
|
12914
|
+
};
|
|
12915
|
+
globalThis.Date = undefined;
|
|
12916
|
+
globalThis.performance = undefined;
|
|
12917
|
+
const __fragment = '__vizmatic_fragment';
|
|
12918
|
+
const __jsx = (type, props, ...children) => {
|
|
12919
|
+
const attributes = props == null ? {} : { ...props };
|
|
12920
|
+
const descendants = children.length ? children : Object.hasOwn(attributes, 'children') ? [attributes.children] : [];
|
|
12921
|
+
delete attributes.children;
|
|
12922
|
+
if (type === __fragment) return descendants;
|
|
12923
|
+
if (typeof type === 'function') return type({ ...attributes, children: descendants.length === 1 ? descendants[0] : descendants });
|
|
12924
|
+
if (typeof type !== 'string') throw new __Error('Invalid scene JSX component.');
|
|
12925
|
+
return { kind: 'vizmatic.element', type, props: attributes, children: descendants };
|
|
12926
|
+
};
|
|
12927
|
+
const React = __freeze({ createElement: __jsx, Fragment: __fragment });
|
|
12928
|
+
const Fragment = __fragment;
|
|
12929
|
+
const __primitive = (type) => (props) => {
|
|
12930
|
+
const attributes = { ...props };
|
|
12931
|
+
const children = Object.hasOwn(attributes, 'children') ? [attributes.children] : [];
|
|
12932
|
+
delete attributes.children;
|
|
12933
|
+
return { kind: 'vizmatic.element', type, props: attributes, children };
|
|
12934
|
+
};
|
|
12935
|
+
const __serialize = (value) => {
|
|
12936
|
+
let values = 0;
|
|
12937
|
+
return __jsonStringify(value, (key, item) => {
|
|
12938
|
+
if (++values > 64000) throw new __Error('Scene graph contains too many values.');
|
|
12939
|
+
if (typeof item === 'function' || typeof item === 'symbol' || typeof item === 'bigint') {
|
|
12940
|
+
throw new __Error('Scene props cannot contain functions, symbols or bigint.');
|
|
12941
|
+
}
|
|
12942
|
+
if (typeof item === 'number' && !__isFinite(item)) throw new __Error('Scene props must be finite.');
|
|
12943
|
+
if (item && typeof item === 'object' && typeof item.then === 'function') throw new __Error('Async scene values are not supported.');
|
|
12944
|
+
return item;
|
|
12945
|
+
});
|
|
12946
|
+
};
|
|
12947
|
+
`;
|
|
12948
|
+
function prepareSceneSource(source) {
|
|
12949
|
+
if (/^\s*(?:import|export)\b|\bimport\s*(?:[('"{*]|\/\*)/m.test(source)) {
|
|
12950
|
+
throw new Error("Editable scenes use bare TSX. Imports and exports are disabled; Vizmatic components are provided automatically.");
|
|
12951
|
+
}
|
|
12952
|
+
const start = findBareRootJsxStart(source, true);
|
|
12953
|
+
if (start < 0) throw new Error("Scene source needs one root JSX element after its local declarations.");
|
|
12954
|
+
const setup = source.slice(0, start);
|
|
12955
|
+
const jsx = extractRootJsx(source.slice(start).trim());
|
|
12956
|
+
return (0, import_sucrase.transform)(`(() => {
|
|
12957
|
+
${setup}
|
|
12958
|
+
return (
|
|
12959
|
+
${jsx}
|
|
12960
|
+
);
|
|
12961
|
+
})()`, {
|
|
12962
|
+
transforms: ["typescript", "jsx"],
|
|
12963
|
+
jsxPragma: "React.createElement",
|
|
12964
|
+
jsxFragmentPragma: "React.Fragment",
|
|
12965
|
+
production: true,
|
|
12966
|
+
disableESTransforms: true
|
|
12967
|
+
}).code;
|
|
12968
|
+
}
|
|
12969
|
+
async function prepareScene(request) {
|
|
12970
|
+
const normalized = Object.freeze(normalizeSceneRequest(request));
|
|
12971
|
+
Object.freeze(normalized.cues);
|
|
12972
|
+
const code = prepareSceneSource(normalized.source);
|
|
12973
|
+
const sourceSha256 = await sceneSha256(normalized.source);
|
|
12974
|
+
const inputSha256 = await sceneSha256(JSON.stringify({ runtimeVersion: SCENE_RUNTIME_VERSION, ...normalized }));
|
|
12975
|
+
const QuickJS = await (0, import_quickjs_emscripten.getQuickJS)();
|
|
12976
|
+
const colors2 = getThemeColors(normalized.theme);
|
|
12977
|
+
const components = `const { ${SCENE_COMPONENT_NAMES.join(", ")} } = Object.fromEntries(${JSON.stringify(SCENE_COMPONENT_NAMES)}.map(name => [name, __primitive(name)]));`;
|
|
12978
|
+
const evaluate = async (requestedTime) => {
|
|
12979
|
+
const time = normalizeSceneTime(requestedTime, normalized.duration);
|
|
12980
|
+
const runtime = QuickJS.newRuntime();
|
|
12981
|
+
runtime.setMemoryLimit(SCENE_LIMITS.memoryBytes);
|
|
12982
|
+
runtime.setMaxStackSize(SCENE_LIMITS.stackBytes);
|
|
12983
|
+
const deadline = Date.now() + SCENE_LIMITS.evaluationMs;
|
|
12984
|
+
runtime.setInterruptHandler(() => Date.now() > deadline);
|
|
12985
|
+
runtime.removeModuleLoader();
|
|
12986
|
+
const vm = runtime.newContext();
|
|
12987
|
+
const context = {
|
|
12988
|
+
width: normalized.width,
|
|
12989
|
+
height: normalized.height,
|
|
12990
|
+
duration: normalized.duration,
|
|
12991
|
+
fps: normalized.fps,
|
|
12992
|
+
time,
|
|
12993
|
+
t: time,
|
|
12994
|
+
progress: time / normalized.duration,
|
|
12995
|
+
frame: Math.floor(time * normalized.fps + 1e-9),
|
|
12996
|
+
theme: normalized.theme,
|
|
12997
|
+
cues: normalized.cues,
|
|
12998
|
+
seed: normalized.seed,
|
|
12999
|
+
c: colors2
|
|
13000
|
+
};
|
|
13001
|
+
const declaration = `const { ${Object.keys(context).join(", ")} } = ${JSON.stringify(context)};`;
|
|
13002
|
+
try {
|
|
13003
|
+
const result = vm.evalCode(`(() => { 'use strict';
|
|
13004
|
+
${declaration}
|
|
13005
|
+
${bootstrap}
|
|
13006
|
+
__freeze(c); __freeze(cues);
|
|
13007
|
+
${components}
|
|
13008
|
+
try { return __serialize(${code}); } catch (error) {
|
|
13009
|
+
if (typeof error === 'string') throw error.slice(0, 1024);
|
|
13010
|
+
const message = error && typeof error === 'object' ? __ownDescriptor(error, 'message')?.value : undefined;
|
|
13011
|
+
throw typeof message === 'string' ? message.slice(0, 1024) : 'Scene evaluation failed.';
|
|
13012
|
+
}
|
|
13013
|
+
})()`, "scene.tsx");
|
|
13014
|
+
if (result.error) {
|
|
13015
|
+
const error = result.error;
|
|
13016
|
+
try {
|
|
13017
|
+
const message = vm.typeof(error) === "string" ? vm.getString(error) : "Scene evaluation failed or exceeded its CPU, stack or memory limit.";
|
|
13018
|
+
throw new Error(message.slice(0, 1024));
|
|
13019
|
+
} finally {
|
|
13020
|
+
error.dispose();
|
|
13021
|
+
}
|
|
13022
|
+
}
|
|
13023
|
+
const handle = result.value;
|
|
13024
|
+
try {
|
|
13025
|
+
if (vm.typeof(handle) !== "string") throw new Error("Scene source must return synchronous JSX.");
|
|
13026
|
+
const length = vm.getProp(handle, "length");
|
|
13027
|
+
try {
|
|
13028
|
+
if (vm.getNumber(length) > SCENE_LIMITS.graphBytes) throw new Error("Scene graph exceeds its serialized size limit.");
|
|
13029
|
+
} finally {
|
|
13030
|
+
length.dispose();
|
|
13031
|
+
}
|
|
13032
|
+
const json = vm.getString(handle);
|
|
13033
|
+
if (new TextEncoder().encode(json).byteLength > SCENE_LIMITS.graphBytes) throw new Error("Scene graph exceeds its serialized size limit.");
|
|
13034
|
+
const graph = validateSceneGraph(JSON.parse(json));
|
|
13035
|
+
return {
|
|
13036
|
+
graph,
|
|
13037
|
+
request: normalized,
|
|
13038
|
+
time,
|
|
13039
|
+
runtimeVersion: SCENE_RUNTIME_VERSION,
|
|
13040
|
+
sourceSha256,
|
|
13041
|
+
inputSha256: await sceneSha256(JSON.stringify({ sceneInputSha256: inputSha256, time }))
|
|
13042
|
+
};
|
|
13043
|
+
} finally {
|
|
13044
|
+
handle.dispose();
|
|
13045
|
+
}
|
|
13046
|
+
} finally {
|
|
13047
|
+
vm.dispose();
|
|
13048
|
+
runtime.dispose();
|
|
13049
|
+
}
|
|
13050
|
+
};
|
|
13051
|
+
return { request: normalized, sourceSha256, inputSha256, evaluate };
|
|
13052
|
+
}
|
|
13053
|
+
async function evaluateSceneSource(request) {
|
|
13054
|
+
return (await prepareScene(request)).evaluate(request.time);
|
|
13055
|
+
}
|
|
13056
|
+
|
|
13057
|
+
// src/scene-renderer.ts
|
|
13058
|
+
function outputSettings(prepared, outputScale = 1, previewFps) {
|
|
13059
|
+
if (!Number.isFinite(outputScale) || outputScale < 0.25 || outputScale > 1) {
|
|
13060
|
+
throw new Error("Scene outputScale must be from 0.25 to 1.");
|
|
13061
|
+
}
|
|
13062
|
+
const { width: logicalWidth, height: logicalHeight, fps: logicalFps, duration } = prepared.request;
|
|
13063
|
+
const width = logicalWidth * outputScale, height = logicalHeight * outputScale;
|
|
13064
|
+
if (![width, height].every((value) => Number.isInteger(value) && value >= 2 && value % 2 === 0)) {
|
|
13065
|
+
throw new Error("Scaled scene width and height must be positive even integers.");
|
|
13066
|
+
}
|
|
13067
|
+
const fps = previewFps === void 0 ? logicalFps : previewFps;
|
|
13068
|
+
if (!Number.isInteger(fps) || fps < 1 || fps > logicalFps) {
|
|
13069
|
+
throw new Error("Scene previewFps must be an integer from 1 to the logical scene fps.");
|
|
13070
|
+
}
|
|
13071
|
+
const frameCount = Math.round(duration * fps);
|
|
13072
|
+
if (frameCount < 1) throw new Error("Scene preview duration must round to at least one output frame.");
|
|
13073
|
+
return { width, height, fps, frameCount, outputScale, preview: outputScale !== 1 || fps !== logicalFps };
|
|
13074
|
+
}
|
|
13075
|
+
var assetPins = {
|
|
13076
|
+
"fonts/Inter-Regular.ttf": "1b08e7fc267a5c7e1d614100f604b83e7e8a0be241f0f288faa2b3ac93a683ba",
|
|
13077
|
+
"fonts/Inter-SemiBold.ttf": "e7a1aaf7eda9f2fad4131725fa556265ec75ca7b2d756260173a040363e8d4f7",
|
|
13078
|
+
"fonts/Inter-Bold.ttf": "b37284b5701b6b168dfc770aa1a4ac492106422fd3ba76bc7641e37434e8019c",
|
|
13079
|
+
"fonts/JetBrainsMono-Regular.ttf": "44ce4a84f20d60f24539bd0cef11f79c29e38609e0f8adf18551c9794a5d9dc3",
|
|
13080
|
+
"fonts/NotoSans-Regular.ttf": "5be701a9511117e73603bdab95947feef4f18bd1851dbddc30659370b26c69f1",
|
|
13081
|
+
"fonts/NotoSansMath-Regular.ttf": "3cbaf44af13f592bc7f7172a50edab4c73ac2f3d19af2d697a01ebd3288e322d",
|
|
13082
|
+
"emoji.json.br": "4911e822be2ed684fe811cadf036139e3efe353ffe2990311e1763f38ae7daab"
|
|
13083
|
+
};
|
|
13084
|
+
var assetsPromise;
|
|
13085
|
+
async function sceneAssets() {
|
|
13086
|
+
assetsPromise ??= loadSceneAssets().catch((error) => {
|
|
13087
|
+
assetsPromise = void 0;
|
|
13088
|
+
throw error;
|
|
13089
|
+
});
|
|
13090
|
+
return assetsPromise;
|
|
13091
|
+
}
|
|
13092
|
+
async function loadSceneAssets() {
|
|
13093
|
+
const moduleDir = typeof __dirname !== "undefined" ? __dirname : (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(void 0));
|
|
13094
|
+
const assetDir = (0, import_node_path.join)(moduleDir, "..", "assets");
|
|
13095
|
+
const files = /* @__PURE__ */ new Map();
|
|
13096
|
+
for (const [name, expected] of Object.entries(assetPins)) {
|
|
13097
|
+
const bytes = await (0, import_promises4.readFile)((0, import_node_path.join)(assetDir, name));
|
|
13098
|
+
if (await sceneSha256(bytes) !== expected) throw new Error(`Pinned scene asset does not match: ${name}`);
|
|
13099
|
+
files.set(name, bytes);
|
|
13100
|
+
}
|
|
13101
|
+
const fontDefinitions = [
|
|
13102
|
+
["Inter", "Inter-Regular.ttf", 400],
|
|
13103
|
+
["Inter", "Inter-SemiBold.ttf", 600],
|
|
13104
|
+
["Inter", "Inter-Bold.ttf", 700],
|
|
13105
|
+
["JetBrains Mono", "JetBrainsMono-Regular.ttf", 400],
|
|
13106
|
+
["Noto Sans", "NotoSans-Regular.ttf", 400],
|
|
13107
|
+
["Noto Sans Math", "NotoSansMath-Regular.ttf", 400]
|
|
13108
|
+
];
|
|
13109
|
+
return {
|
|
13110
|
+
fonts: fontDefinitions.map(([name, filename, weight]) => ({
|
|
13111
|
+
name,
|
|
13112
|
+
weight,
|
|
13113
|
+
style: "normal",
|
|
13114
|
+
data: Uint8Array.from(files.get(`fonts/${filename}`)).buffer
|
|
13115
|
+
})),
|
|
13116
|
+
fontFiles: fontDefinitions.map(([, filename]) => (0, import_node_path.join)(assetDir, "fonts", filename)),
|
|
13117
|
+
emoji: JSON.parse((0, import_node_zlib.brotliDecompressSync)(files.get("emoji.json.br")).toString("utf8")),
|
|
13118
|
+
sha256: await sceneSha256(JSON.stringify(assetPins))
|
|
13119
|
+
};
|
|
13120
|
+
}
|
|
13121
|
+
var trustedComponents = Object.fromEntries(SCENE_COMPONENT_NAMES.map((name) => [name, primitives_exports[name]]));
|
|
13122
|
+
var svgTags = new Set(SCENE_DOM_TAGS.filter((name) => !["div", "span", "p", "strong", "em", "b", "i", "br"].includes(name)));
|
|
13123
|
+
function isElement(value) {
|
|
13124
|
+
return Boolean(value && !Array.isArray(value) && typeof value === "object" && value.kind === "vizmatic.element");
|
|
13125
|
+
}
|
|
13126
|
+
var xml = (value) => String(value).replace(/[&<>"']/g, (character) => ({
|
|
13127
|
+
"&": "&",
|
|
13128
|
+
"<": "<",
|
|
13129
|
+
">": ">",
|
|
13130
|
+
'"': """,
|
|
13131
|
+
"'": "'"
|
|
13132
|
+
})[character]);
|
|
13133
|
+
function svgAttribute(name) {
|
|
13134
|
+
if (name === "className") return "class";
|
|
13135
|
+
if (name === "xlinkHref") return "href";
|
|
13136
|
+
if (/^(?:viewBox|preserveAspectRatio|gradientUnits|gradientTransform|patternUnits|patternContentUnits|patternTransform|markerWidth|markerHeight|markerUnits|refX|refY|textLength|lengthAdjust|clipPathUnits)$/.test(name)) return name;
|
|
13137
|
+
return name.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
|
|
13138
|
+
}
|
|
13139
|
+
function serializeSvg(node, budget, depth = 0) {
|
|
13140
|
+
if (++budget.nodes > SCENE_LIMITS.nodes * 16) throw new Error("Resolved scene exceeds its host element budget.");
|
|
13141
|
+
if (depth > SCENE_LIMITS.depth * 2) throw new Error("Resolved SVG exceeds its depth limit.");
|
|
13142
|
+
const emit = (chunk) => {
|
|
13143
|
+
budget.svgBytes += Buffer.byteLength(chunk);
|
|
13144
|
+
if (budget.svgBytes > SCENE_LIMITS.graphBytes * 4) throw new Error("Resolved SVG exceeds its serialized byte budget.");
|
|
13145
|
+
return chunk;
|
|
13146
|
+
};
|
|
13147
|
+
if (node === null || node === void 0 || typeof node === "boolean") return "";
|
|
13148
|
+
if (typeof node === "string" || typeof node === "number") return emit(xml(node));
|
|
13149
|
+
if (Array.isArray(node)) return node.map((child) => serializeSvg(child, budget, depth + 1)).join("");
|
|
13150
|
+
if (!import_react16.default.isValidElement(node)) throw new Error("Invalid resolved SVG child.");
|
|
13151
|
+
if (node.type === import_react16.default.Fragment) return serializeSvg(node.props.children, budget, depth + 1);
|
|
13152
|
+
if (node.type === SvgMathText) {
|
|
13153
|
+
const { text, x, y, fill, fontSize = 13, fontFamily = "JetBrains Mono", fontWeight = 700, textAnchor = "middle", dominantBaseline = "middle", opacity = 1 } = node.props;
|
|
13154
|
+
return serializeSvg(import_react16.default.createElement("text", { x, y, fill, fontSize, fontFamily, fontWeight, textAnchor, dominantBaseline, opacity }, String(text)), budget, depth + 1);
|
|
13155
|
+
}
|
|
13156
|
+
if (typeof node.type === "function") {
|
|
13157
|
+
return serializeSvg(node.type(node.props), budget, depth + 1);
|
|
13158
|
+
}
|
|
13159
|
+
if (typeof node.type !== "string" || !svgTags.has(node.type)) throw new Error("Only SVG components may be placed inside an SVG scene.");
|
|
13160
|
+
validateResolvedSceneResources(node.props);
|
|
13161
|
+
const attributes = Object.entries(node.props).filter(([key, value]) => key !== "children" && key !== "key" && value !== void 0 && value !== null).map(([key, value]) => {
|
|
13162
|
+
if (key === "style" && typeof value === "object") {
|
|
13163
|
+
const style = Object.entries(value).map(([property, item]) => `${svgAttribute(property)}:${String(item)}`).join(";");
|
|
13164
|
+
return ` style="${xml(style)}"`;
|
|
13165
|
+
}
|
|
13166
|
+
if (!/^[A-Za-z_][\w:.-]*$/.test(key) || typeof value === "object" || typeof value === "function") throw new Error("Unsupported SVG attribute.");
|
|
13167
|
+
return ` ${svgAttribute(key)}="${xml(String(value))}"`;
|
|
13168
|
+
}).join("");
|
|
13169
|
+
return emit(`<${node.type}${attributes}>`) + serializeSvg(node.props.children, budget, depth + 1) + emit(`</${node.type}>`);
|
|
13170
|
+
}
|
|
13171
|
+
function graphToReact(value, theme) {
|
|
13172
|
+
if (Array.isArray(value)) return value.map((child) => graphToReact(child, theme));
|
|
13173
|
+
if (!isElement(value)) return value;
|
|
13174
|
+
const convertProp = (prop) => {
|
|
13175
|
+
if (isElement(prop)) return graphToReact(prop, theme);
|
|
13176
|
+
if (Array.isArray(prop)) return prop.map(convertProp);
|
|
13177
|
+
if (prop && typeof prop === "object") return Object.fromEntries(Object.entries(prop).map(([key, item]) => [key, convertProp(item)]));
|
|
13178
|
+
return prop;
|
|
13179
|
+
};
|
|
13180
|
+
const props = Object.fromEntries(Object.entries(value.props).map(([name, prop]) => [name, convertProp(prop)]));
|
|
13181
|
+
const component = trustedComponents[value.type];
|
|
13182
|
+
if (component) props.c ??= theme;
|
|
13183
|
+
return import_react16.default.createElement(component ?? value.type, props, ...value.children.map((child) => graphToReact(child, theme)));
|
|
13184
|
+
}
|
|
13185
|
+
function renderSvgImage(element, assets, width, height, budget, outputScale = 1, includePng = true) {
|
|
13186
|
+
const root = import_react16.default.cloneElement(element, { xmlns: "http://www.w3.org/2000/svg", width, height });
|
|
13187
|
+
const svg = serializeSvg(root, budget);
|
|
13188
|
+
const image = new import_resvg_js4.Resvg(svg, {
|
|
13189
|
+
font: { loadSystemFonts: false, fontFiles: assets.fontFiles, defaultFontFamily: "Inter" },
|
|
13190
|
+
background: "rgba(0,0,0,0)",
|
|
13191
|
+
...outputScale !== 1 ? { fitTo: { mode: "width", value: width * outputScale } } : {}
|
|
13192
|
+
}).render();
|
|
13193
|
+
if (image.width !== width * outputScale || image.height !== height * outputScale) throw new Error("SVG frame does not match scaled scene dimensions.");
|
|
13194
|
+
return { pixels: image.pixels, ...includePng ? { png: image.asPng() } : {} };
|
|
13195
|
+
}
|
|
13196
|
+
function rasterizeNestedSvg(node, assets, defaultWidth, defaultHeight, budget) {
|
|
13197
|
+
if (++budget.nodes > SCENE_LIMITS.nodes * 16) throw new Error("Resolved scene exceeds its host element budget.");
|
|
13198
|
+
if (Array.isArray(node)) return node.map((child) => rasterizeNestedSvg(child, assets, defaultWidth, defaultHeight, budget));
|
|
13199
|
+
if (!import_react16.default.isValidElement(node)) return node;
|
|
13200
|
+
if (node.type === "svg") {
|
|
13201
|
+
const width = typeof node.props.width === "number" ? node.props.width : defaultWidth;
|
|
13202
|
+
const height = typeof node.props.height === "number" ? node.props.height : defaultHeight;
|
|
13203
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > SCENE_LIMITS.canvasEdge || height > SCENE_LIMITS.canvasEdge || width * height > SCENE_LIMITS.canvasPixels) {
|
|
13204
|
+
throw new Error("Nested SVG dimensions exceed the scene canvas limits.");
|
|
13205
|
+
}
|
|
13206
|
+
budget.pixels += width * height;
|
|
13207
|
+
budget.count += 1;
|
|
13208
|
+
if (budget.pixels > defaultWidth * defaultHeight * 4 || budget.count > 16) {
|
|
13209
|
+
throw new Error("Nested SVG rasterization exceeds the per-frame pixel or image budget.");
|
|
13210
|
+
}
|
|
13211
|
+
const { png } = renderSvgImage(node, assets, width, height, budget);
|
|
13212
|
+
return import_react16.default.createElement("img", {
|
|
13213
|
+
width,
|
|
13214
|
+
height,
|
|
13215
|
+
src: `data:image/png;base64,${Buffer.from(png).toString("base64")}`,
|
|
13216
|
+
style: { display: "flex", flexShrink: 0, ...node.props.style }
|
|
13217
|
+
});
|
|
13218
|
+
}
|
|
13219
|
+
if (typeof node.type === "function") return rasterizeNestedSvg(node.type(node.props), assets, defaultWidth, defaultHeight, budget);
|
|
13220
|
+
validateResolvedSceneResources(node.props);
|
|
13221
|
+
return import_react16.default.cloneElement(node, {}, rasterizeNestedSvg(node.props.children, assets, defaultWidth, defaultHeight, budget));
|
|
13222
|
+
}
|
|
13223
|
+
async function renderPreparedFrame(prepared, assets, time, outputScale, includePng) {
|
|
13224
|
+
const evaluated = await prepared.evaluate(time);
|
|
13225
|
+
const { width, height, theme } = prepared.request;
|
|
13226
|
+
const c = getThemeColors(theme);
|
|
13227
|
+
let element = graphToReact(evaluated.graph, c);
|
|
13228
|
+
if (import_react16.default.isValidElement(element) && element.type === "svg") {
|
|
13229
|
+
const image = renderSvgImage(import_react16.default.cloneElement(element, {
|
|
13230
|
+
children: [import_react16.default.createElement("rect", { key: "__scene_background", width, height, fill: c.bg }), element.props.children]
|
|
13231
|
+
}), assets, width, height, { pixels: 0, count: 0, nodes: 0, svgBytes: 0 }, outputScale, includePng);
|
|
13232
|
+
return image;
|
|
13233
|
+
}
|
|
13234
|
+
element = import_react16.default.createElement("div", { style: { display: "flex", position: "relative", width, height, backgroundColor: c.bg, fontFamily: "Inter", color: c.textPrimary } }, element);
|
|
13235
|
+
return withRenderContext({ background: "theme" }, async () => {
|
|
13236
|
+
element = rasterizeNestedSvg(element, assets, width, height, { pixels: 0, count: 0, nodes: 0, svgBytes: 0 });
|
|
13237
|
+
const accessible = prepareAccessibleSvg(element);
|
|
13238
|
+
const layoutNodes = [];
|
|
13239
|
+
const rendered = await satori(accessible.element, {
|
|
13240
|
+
width,
|
|
13241
|
+
height,
|
|
13242
|
+
fonts: assets.fonts,
|
|
13243
|
+
loadAdditionalAsset: async (code, segment) => {
|
|
13244
|
+
if (code !== "emoji") return [];
|
|
13245
|
+
const points = [...segment].map((character) => character.codePointAt(0).toString(16));
|
|
13246
|
+
const candidates = [points.join("-"), points.filter((point) => point !== "fe0f").join("-")];
|
|
13247
|
+
const svg2 = candidates.map((name) => assets.emoji[`${name}.svg`]).find(Boolean);
|
|
13248
|
+
if (!svg2) throw new Error("A scene glyph is not available in the pinned offline font and emoji assets.");
|
|
13249
|
+
return `data:image/svg+xml;base64,${Buffer.from(svg2).toString("base64")}`;
|
|
13250
|
+
},
|
|
13251
|
+
onNodeDetected: (node) => layoutNodes.push(node)
|
|
13252
|
+
});
|
|
13253
|
+
const svg = addSvgAccessibility(rendered, accessible.graphs, layoutNodes);
|
|
13254
|
+
const image = new import_resvg_js4.Resvg(svg, {
|
|
13255
|
+
background: c.bg,
|
|
13256
|
+
font: { loadSystemFonts: false, fontFiles: assets.fontFiles },
|
|
13257
|
+
...outputScale !== 1 ? { fitTo: { mode: "width", value: width * outputScale } } : {}
|
|
13258
|
+
}).render();
|
|
13259
|
+
if (image.width !== width * outputScale || image.height !== height * outputScale) throw new Error("Layout frame does not match scaled scene dimensions.");
|
|
13260
|
+
return { pixels: image.pixels, ...includePng ? { png: image.asPng() } : {} };
|
|
13261
|
+
});
|
|
13262
|
+
}
|
|
13263
|
+
async function outputMetadata(prepared, assets, settings, outputPath, bytes, kind, time) {
|
|
13264
|
+
const { width, height, duration, fps, frameCount } = prepared.request;
|
|
13265
|
+
const digest = (0, import_node_crypto.createHash)("sha256");
|
|
13266
|
+
for await (const chunk of (0, import_node_fs.createReadStream)(outputPath)) digest.update(chunk);
|
|
13267
|
+
return {
|
|
13268
|
+
runtimeVersion: SCENE_RUNTIME_VERSION,
|
|
13269
|
+
sourceSha256: prepared.sourceSha256,
|
|
13270
|
+
inputSha256: await sceneSha256(JSON.stringify({
|
|
13271
|
+
requestSha256: prepared.inputSha256,
|
|
13272
|
+
fontAssetsSha256: assets.sha256,
|
|
13273
|
+
kind,
|
|
13274
|
+
...time !== void 0 ? { time } : {},
|
|
13275
|
+
...settings.preview ? { outputScale: settings.outputScale, width: settings.width, height: settings.height, fps: settings.fps, frameCount: settings.frameCount } : {}
|
|
13276
|
+
})),
|
|
13277
|
+
assetSha256: digest.digest("hex"),
|
|
13278
|
+
fontAssetsSha256: assets.sha256,
|
|
13279
|
+
width: settings.width,
|
|
13280
|
+
height: settings.height,
|
|
13281
|
+
duration,
|
|
13282
|
+
fps: settings.fps,
|
|
13283
|
+
frameCount: settings.frameCount,
|
|
13284
|
+
bytes,
|
|
13285
|
+
outputPath: (0, import_node_path.resolve)(outputPath),
|
|
13286
|
+
...settings.preview ? {
|
|
13287
|
+
outputScale: settings.outputScale,
|
|
13288
|
+
...kind === "mp4" ? { previewFps: settings.fps } : {},
|
|
13289
|
+
logicalWidth: width,
|
|
13290
|
+
logicalHeight: height,
|
|
13291
|
+
logicalFps: fps,
|
|
13292
|
+
logicalFrameCount: frameCount
|
|
13293
|
+
} : {}
|
|
13294
|
+
};
|
|
13295
|
+
}
|
|
13296
|
+
async function atomicWrite(outputPath, bytes) {
|
|
13297
|
+
const target = (0, import_node_path.resolve)(outputPath);
|
|
13298
|
+
await (0, import_promises4.mkdir)((0, import_node_path.dirname)(target), { recursive: true });
|
|
13299
|
+
const temporary = (0, import_node_path.join)((0, import_node_path.dirname)(target), `.vizmatic-scene-${(0, import_node_crypto.randomUUID)()}.tmp`);
|
|
13300
|
+
const file = await (0, import_promises4.open)(temporary, "wx", 384);
|
|
13301
|
+
try {
|
|
13302
|
+
await file.writeFile(bytes);
|
|
13303
|
+
await file.close();
|
|
13304
|
+
await (0, import_promises4.rename)(temporary, target);
|
|
13305
|
+
} catch (error) {
|
|
13306
|
+
await file.close().catch(() => {
|
|
13307
|
+
});
|
|
13308
|
+
await (0, import_promises4.rm)(temporary, { force: true });
|
|
13309
|
+
throw error;
|
|
13310
|
+
}
|
|
13311
|
+
}
|
|
13312
|
+
async function renderSceneFrame(options) {
|
|
13313
|
+
if (typeof options.outputPath !== "string" || !options.outputPath) throw new Error("Scene outputPath is required.");
|
|
13314
|
+
const prepared = await prepareScene(options);
|
|
13315
|
+
const settings = outputSettings(prepared, options.outputScale);
|
|
13316
|
+
const time = normalizeSceneTime(options.time, prepared.request.duration);
|
|
13317
|
+
const assets = await sceneAssets();
|
|
13318
|
+
const image = await renderPreparedFrame(prepared, assets, time, settings.outputScale, true);
|
|
13319
|
+
await atomicWrite(options.outputPath, image.png);
|
|
13320
|
+
return { ...await outputMetadata(prepared, assets, settings, options.outputPath, image.png.byteLength, "png", time), time };
|
|
13321
|
+
}
|
|
13322
|
+
async function renderSceneVideo(options) {
|
|
13323
|
+
if (typeof options.outputPath !== "string" || !options.outputPath) throw new Error("Scene outputPath is required.");
|
|
13324
|
+
const prepared = await prepareScene(options);
|
|
13325
|
+
const settings = outputSettings(prepared, options.outputScale, options.previewFps);
|
|
13326
|
+
const assets = await sceneAssets();
|
|
13327
|
+
const { duration } = prepared.request;
|
|
13328
|
+
const output = await renderRgbaVideo(async (frame) => (await renderPreparedFrame(prepared, assets, frame.time / 1e3, settings.outputScale, false)).pixels, {
|
|
13329
|
+
width: settings.width,
|
|
13330
|
+
height: settings.height,
|
|
13331
|
+
duration: duration * 1e3,
|
|
13332
|
+
fps: settings.fps,
|
|
13333
|
+
outputPath: options.outputPath,
|
|
13334
|
+
signal: options.signal
|
|
13335
|
+
});
|
|
13336
|
+
return { ...await outputMetadata(prepared, assets, settings, options.outputPath, output.bytes, "mp4"), encodedDuration: output.duration / 1e3 };
|
|
13337
|
+
}
|
|
13338
|
+
|
|
10768
13339
|
// src/import-types.ts
|
|
10769
13340
|
function graphImportResult(source, graph, diagnostics) {
|
|
10770
13341
|
if (graph.nodes.length === 0 && diagnostics.every(({ severity }) => severity !== "error")) {
|
|
@@ -10850,7 +13421,7 @@ function readEndpoint(line, from) {
|
|
|
10850
13421
|
{ open: "(", close: ")", lossy: true },
|
|
10851
13422
|
{ open: "{", close: "}", lossy: true }
|
|
10852
13423
|
];
|
|
10853
|
-
const delimiter = delimiters.find(({ open }) => rest.startsWith(
|
|
13424
|
+
const delimiter = delimiters.find(({ open: open3 }) => rest.startsWith(open3));
|
|
10854
13425
|
if (!delimiter) return { id, label: id, shape: "rectangle", next: index };
|
|
10855
13426
|
const content = readDelimited(line, afterId + delimiter.open.length, delimiter.close);
|
|
10856
13427
|
if (!content) return void 0;
|
|
@@ -11321,14 +13892,14 @@ function importD2Graph(source) {
|
|
|
11321
13892
|
}
|
|
11322
13893
|
|
|
11323
13894
|
// src/check.ts
|
|
11324
|
-
var
|
|
13895
|
+
var import_promises5 = require("fs/promises");
|
|
11325
13896
|
var import_async_hooks2 = require("async_hooks");
|
|
11326
13897
|
var import_os2 = require("os");
|
|
11327
|
-
var
|
|
13898
|
+
var import_path4 = require("path");
|
|
11328
13899
|
|
|
11329
13900
|
// src/diagnostics.ts
|
|
11330
|
-
var
|
|
11331
|
-
var
|
|
13901
|
+
var import_parse_css_color5 = __toESM(require("parse-css-color"), 1);
|
|
13902
|
+
var import_react17 = require("react");
|
|
11332
13903
|
var CHECK_DIAGNOSTIC_CODES = [
|
|
11333
13904
|
"accessibility.low_contrast",
|
|
11334
13905
|
"api.unsupported_prop",
|
|
@@ -11368,7 +13939,7 @@ function hslToRgb2(hue, saturation, lightness) {
|
|
|
11368
13939
|
}
|
|
11369
13940
|
function colorFromCss(value) {
|
|
11370
13941
|
if (typeof value !== "string") return void 0;
|
|
11371
|
-
const parsed = (0,
|
|
13942
|
+
const parsed = (0, import_parse_css_color5.default)(value);
|
|
11372
13943
|
if (!parsed || parsed.values.length < 3) return void 0;
|
|
11373
13944
|
const [r, g, b] = parsed.type === "hsl" ? hslToRgb2(parsed.values[0] ?? 0, parsed.values[1] ?? 0, parsed.values[2] ?? 0) : [parsed.values[0] ?? 0, parsed.values[1] ?? 0, parsed.values[2] ?? 0];
|
|
11374
13945
|
return {
|
|
@@ -11380,13 +13951,13 @@ function colorFromCss(value) {
|
|
|
11380
13951
|
}
|
|
11381
13952
|
function compositeOver(foreground, background) {
|
|
11382
13953
|
if (foreground.alpha >= 1 || !background) return foreground;
|
|
11383
|
-
const
|
|
11384
|
-
if (
|
|
13954
|
+
const alpha2 = foreground.alpha + background.alpha * (1 - foreground.alpha);
|
|
13955
|
+
if (alpha2 <= 0) return { r: 0, g: 0, b: 0, alpha: 0 };
|
|
11385
13956
|
return {
|
|
11386
|
-
r: (foreground.r * foreground.alpha + background.r * background.alpha * (1 - foreground.alpha)) /
|
|
11387
|
-
g: (foreground.g * foreground.alpha + background.g * background.alpha * (1 - foreground.alpha)) /
|
|
11388
|
-
b: (foreground.b * foreground.alpha + background.b * background.alpha * (1 - foreground.alpha)) /
|
|
11389
|
-
alpha
|
|
13957
|
+
r: (foreground.r * foreground.alpha + background.r * background.alpha * (1 - foreground.alpha)) / alpha2,
|
|
13958
|
+
g: (foreground.g * foreground.alpha + background.g * background.alpha * (1 - foreground.alpha)) / alpha2,
|
|
13959
|
+
b: (foreground.b * foreground.alpha + background.b * background.alpha * (1 - foreground.alpha)) / alpha2,
|
|
13960
|
+
alpha: alpha2
|
|
11390
13961
|
};
|
|
11391
13962
|
}
|
|
11392
13963
|
function isUnresolvedColor(value) {
|
|
@@ -11416,13 +13987,13 @@ function fontSizePixels(value, inherited) {
|
|
|
11416
13987
|
if (typeof value !== "string") return inherited;
|
|
11417
13988
|
const match = value.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(px|pt|rem|em|%)?$/);
|
|
11418
13989
|
if (!match?.[1]) return inherited;
|
|
11419
|
-
const
|
|
13990
|
+
const amount2 = Number(match[1]);
|
|
11420
13991
|
const unit = match[2] ?? "px";
|
|
11421
|
-
if (unit === "pt") return
|
|
11422
|
-
if (unit === "rem") return
|
|
11423
|
-
if (unit === "em") return
|
|
11424
|
-
if (unit === "%") return
|
|
11425
|
-
return
|
|
13992
|
+
if (unit === "pt") return amount2 * 4 / 3;
|
|
13993
|
+
if (unit === "rem") return amount2 * 16;
|
|
13994
|
+
if (unit === "em") return amount2 * (inherited ?? 16);
|
|
13995
|
+
if (unit === "%") return amount2 / 100 * (inherited ?? 16);
|
|
13996
|
+
return amount2;
|
|
11426
13997
|
}
|
|
11427
13998
|
function requiredContrast(context) {
|
|
11428
13999
|
const large = (context.fontSize ?? 16) >= 24 || (context.fontSize ?? 16) >= 18.66 && (context.fontWeight ?? 400) >= 700;
|
|
@@ -11433,14 +14004,14 @@ function styleRecord(value) {
|
|
|
11433
14004
|
return value;
|
|
11434
14005
|
}
|
|
11435
14006
|
function hasDirectText(children) {
|
|
11436
|
-
return
|
|
14007
|
+
return import_react17.Children.toArray(children).some((child) => typeof child === "string" || typeof child === "number");
|
|
11437
14008
|
}
|
|
11438
14009
|
function elementId(props) {
|
|
11439
14010
|
const value = props.id ?? props["data-vizmatic-id"];
|
|
11440
14011
|
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
11441
14012
|
}
|
|
11442
|
-
function resolveFunctionComponent(node,
|
|
11443
|
-
if (!(0,
|
|
14013
|
+
function resolveFunctionComponent(node, trustedComponents2) {
|
|
14014
|
+
if (!(0, import_react17.isValidElement)(node) || typeof node.type !== "function" || trustedComponents2.has(node.type)) return void 0;
|
|
11444
14015
|
const component = node.type;
|
|
11445
14016
|
if (component.__vizmaticPrimitive) return void 0;
|
|
11446
14017
|
if (component.prototype?.isReactComponent) return void 0;
|
|
@@ -11450,13 +14021,13 @@ function resolveFunctionComponent(node, trustedComponents) {
|
|
|
11450
14021
|
return void 0;
|
|
11451
14022
|
}
|
|
11452
14023
|
}
|
|
11453
|
-
function analyzeContrast(element, theme,
|
|
14024
|
+
function analyzeContrast(element, theme, trustedComponents2 = /* @__PURE__ */ new Set(), rootBackground2) {
|
|
11454
14025
|
const diagnostics = [];
|
|
11455
14026
|
const seen = /* @__PURE__ */ new Set();
|
|
11456
14027
|
let visited = 0;
|
|
11457
14028
|
function visit(node, inherited, path) {
|
|
11458
|
-
if (visited++ >= MAX_CONTRAST_NODES || !(0,
|
|
11459
|
-
const resolved = resolveFunctionComponent(node,
|
|
14029
|
+
if (visited++ >= MAX_CONTRAST_NODES || !(0, import_react17.isValidElement)(node)) return;
|
|
14030
|
+
const resolved = resolveFunctionComponent(node, trustedComponents2);
|
|
11460
14031
|
if (resolved !== void 0) {
|
|
11461
14032
|
visit(resolved, inherited, path);
|
|
11462
14033
|
return;
|
|
@@ -11465,7 +14036,7 @@ function analyzeContrast(element, theme, trustedComponents = /* @__PURE__ */ new
|
|
|
11465
14036
|
const style = typeof node.type === "string" ? styleRecord(props.style) : {};
|
|
11466
14037
|
const backgroundImage = typeof style.backgroundImage === "string" ? style.backgroundImage.trim().toLowerCase() : "";
|
|
11467
14038
|
const backgroundShorthand = typeof style.background === "string" ? style.background.trim() : "";
|
|
11468
|
-
const isBackgroundWrapper = typeof node.type === "function" && (
|
|
14039
|
+
const isBackgroundWrapper = typeof node.type === "function" && (trustedComponents2.has(node.type) || Boolean(node.type.__vizmaticPrimitive));
|
|
11469
14040
|
const wrapperBackground = isBackgroundWrapper ? props.background : void 0;
|
|
11470
14041
|
const hasUnresolvedBackground = backgroundImage !== "" && backgroundImage !== "none" || isUnresolvedColor(style.backgroundColor) || backgroundShorthand !== "" && backgroundShorthand.toLowerCase() !== "none" && !colorFromCss(backgroundShorthand) || isUnresolvedColor(wrapperBackground);
|
|
11471
14042
|
const ownBackground = colorFromCss(style.backgroundColor) ?? colorFromCss(style.background) ?? colorFromCss(wrapperBackground);
|
|
@@ -11496,7 +14067,7 @@ function analyzeContrast(element, theme, trustedComponents = /* @__PURE__ */ new
|
|
|
11496
14067
|
}
|
|
11497
14068
|
}
|
|
11498
14069
|
}
|
|
11499
|
-
|
|
14070
|
+
import_react17.Children.forEach(props.children, (child, index) => visit(child, context, `${path}.${index}`));
|
|
11500
14071
|
}
|
|
11501
14072
|
visit(element, { background: colorFromCss(rootBackground2) }, "root");
|
|
11502
14073
|
return diagnostics;
|
|
@@ -11519,7 +14090,7 @@ function renderedTextNodes(nodes) {
|
|
|
11519
14090
|
const style = styleRecord(node.props.style);
|
|
11520
14091
|
const fontSize = fontSizePixels(style.fontSize, inherited?.fontSize) ?? 16;
|
|
11521
14092
|
const textAlign = typeof style.textAlign === "string" ? style.textAlign : inherited?.textAlign ?? "left";
|
|
11522
|
-
const text = node.textContent
|
|
14093
|
+
const text = String(node.textContent ?? "").trim();
|
|
11523
14094
|
if (text && node.width > 0 && node.height > 0) {
|
|
11524
14095
|
const estimatedLines = Math.max(1, Math.round(node.height / Math.max(fontSize * 1.5, 1)));
|
|
11525
14096
|
const paintHeight = Math.min(
|
|
@@ -11724,12 +14295,12 @@ function analyzeRenderedLayout(nodes, theme) {
|
|
|
11724
14295
|
}
|
|
11725
14296
|
return diagnostics;
|
|
11726
14297
|
}
|
|
11727
|
-
function analyzeWhitespaceBalance(
|
|
14298
|
+
function analyzeWhitespaceBalance(bounds2, width, height, theme) {
|
|
11728
14299
|
const gutters = {
|
|
11729
|
-
left:
|
|
11730
|
-
right: width -
|
|
11731
|
-
top:
|
|
11732
|
-
bottom: height -
|
|
14300
|
+
left: bounds2.x,
|
|
14301
|
+
right: width - bounds2.x - bounds2.width,
|
|
14302
|
+
top: bounds2.y,
|
|
14303
|
+
bottom: height - bounds2.y - bounds2.height
|
|
11733
14304
|
};
|
|
11734
14305
|
const diagnostics = [];
|
|
11735
14306
|
const horizontalDifference = Math.abs(gutters.left - gutters.right);
|
|
@@ -11741,7 +14312,7 @@ function analyzeWhitespaceBalance(bounds, width, height, theme) {
|
|
|
11741
14312
|
theme,
|
|
11742
14313
|
message: `Horizontal gutters differ by ${Math.round(horizontalDifference)}px (${Math.round(gutters.left)}px left, ${Math.round(gutters.right)}px right).`,
|
|
11743
14314
|
suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally.",
|
|
11744
|
-
location: { x:
|
|
14315
|
+
location: { x: bounds2.x, y: bounds2.y, width: bounds2.width, height: bounds2.height }
|
|
11745
14316
|
});
|
|
11746
14317
|
}
|
|
11747
14318
|
if (verticalDifference > 48 && verticalDifference / height > 0.12) {
|
|
@@ -11751,7 +14322,7 @@ function analyzeWhitespaceBalance(bounds, width, height, theme) {
|
|
|
11751
14322
|
theme,
|
|
11752
14323
|
message: `Vertical gutters differ by ${Math.round(verticalDifference)}px (${Math.round(gutters.top)}px top, ${Math.round(gutters.bottom)}px bottom).`,
|
|
11753
14324
|
suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally.",
|
|
11754
|
-
location: { x:
|
|
14325
|
+
location: { x: bounds2.x, y: bounds2.y, width: bounds2.width, height: bounds2.height }
|
|
11755
14326
|
});
|
|
11756
14327
|
}
|
|
11757
14328
|
return diagnostics;
|
|
@@ -11975,7 +14546,7 @@ async function checkFrame(input, options = {}) {
|
|
|
11975
14546
|
});
|
|
11976
14547
|
const create = input.create ?? (() => input.scene);
|
|
11977
14548
|
const failOn = options.failOn ?? "error";
|
|
11978
|
-
const tempDir = await (0,
|
|
14549
|
+
const tempDir = await (0, import_promises5.mkdtemp)((0, import_path4.join)((0, import_os2.tmpdir)(), "vizmatic-check-"));
|
|
11979
14550
|
const reports = [];
|
|
11980
14551
|
try {
|
|
11981
14552
|
for (const [themeIndex, theme] of themes.entries()) {
|
|
@@ -12007,7 +14578,7 @@ async function checkFrame(input, options = {}) {
|
|
|
12007
14578
|
height,
|
|
12008
14579
|
autoSize,
|
|
12009
14580
|
background: options.background,
|
|
12010
|
-
outputPath: (0,
|
|
14581
|
+
outputPath: (0, import_path4.join)(tempDir, `${themeIndex}.png`)
|
|
12011
14582
|
}));
|
|
12012
14583
|
diagnostics2.push(...messageDiagnostics(rendered.messages, theme));
|
|
12013
14584
|
if (rendered.value) {
|
|
@@ -12048,7 +14619,7 @@ async function checkFrame(input, options = {}) {
|
|
|
12048
14619
|
height,
|
|
12049
14620
|
autoSize: { width: true, height: true },
|
|
12050
14621
|
background: options.background,
|
|
12051
|
-
outputPath: (0,
|
|
14622
|
+
outputPath: (0, import_path4.join)(tempDir, `${themeIndex}-suggestion.png`)
|
|
12052
14623
|
}));
|
|
12053
14624
|
const suggestedDimensions = suggestion.value ? { width: suggestion.value.width, height: suggestion.value.height } : void 0;
|
|
12054
14625
|
diagnostics2.push({
|
|
@@ -12075,7 +14646,7 @@ async function checkFrame(input, options = {}) {
|
|
|
12075
14646
|
});
|
|
12076
14647
|
}
|
|
12077
14648
|
} finally {
|
|
12078
|
-
await (0,
|
|
14649
|
+
await (0, import_promises5.rm)(tempDir, { recursive: true, force: true });
|
|
12079
14650
|
}
|
|
12080
14651
|
const summary = counts(reports);
|
|
12081
14652
|
const diagnostics = reports.flatMap(({ diagnostics: themeDiagnostics }) => themeDiagnostics);
|
|
@@ -12144,6 +14715,8 @@ async function checkFrame(input, options = {}) {
|
|
|
12144
14715
|
ProgressRow,
|
|
12145
14716
|
QuadrantChart,
|
|
12146
14717
|
Row,
|
|
14718
|
+
SCENE_LIMITS,
|
|
14719
|
+
SCENE_RUNTIME_VERSION,
|
|
12147
14720
|
ScatterPlot,
|
|
12148
14721
|
Scene,
|
|
12149
14722
|
SequenceDiagram,
|
|
@@ -12170,10 +14743,16 @@ async function checkFrame(input, options = {}) {
|
|
|
12170
14743
|
Watermark,
|
|
12171
14744
|
WindowFrame,
|
|
12172
14745
|
analyzeAnimationCadence,
|
|
14746
|
+
arcSwap,
|
|
14747
|
+
cameraSvgTransform,
|
|
12173
14748
|
canvas,
|
|
12174
14749
|
checkFrame,
|
|
12175
14750
|
colors,
|
|
14751
|
+
createCanvasComponents,
|
|
14752
|
+
createCueTrack,
|
|
12176
14753
|
createPlotArea,
|
|
14754
|
+
createPolylineMorph,
|
|
14755
|
+
createTeachingCanvas,
|
|
12177
14756
|
cropPixels,
|
|
12178
14757
|
defineAnimation,
|
|
12179
14758
|
defineDiagramIcon,
|
|
@@ -12182,8 +14761,12 @@ async function checkFrame(input, options = {}) {
|
|
|
12182
14761
|
detectBackgroundColor,
|
|
12183
14762
|
detectContentBounds,
|
|
12184
14763
|
detectOverflow,
|
|
14764
|
+
dotProduct,
|
|
14765
|
+
entropy,
|
|
14766
|
+
evaluateSceneSource,
|
|
12185
14767
|
formatMathText,
|
|
12186
14768
|
formatTensorShape,
|
|
14769
|
+
gaussian,
|
|
12187
14770
|
getColor,
|
|
12188
14771
|
getFonts,
|
|
12189
14772
|
getGradient,
|
|
@@ -12200,24 +14783,48 @@ async function checkFrame(input, options = {}) {
|
|
|
12200
14783
|
hold,
|
|
12201
14784
|
importD2Graph,
|
|
12202
14785
|
importMermaidGraph,
|
|
14786
|
+
interpolateCamera,
|
|
12203
14787
|
keyframe,
|
|
14788
|
+
layoutAllocation,
|
|
14789
|
+
layoutCellGrid,
|
|
14790
|
+
layoutTokenRow,
|
|
14791
|
+
lerpArray,
|
|
12204
14792
|
loadAdditionalAsset,
|
|
14793
|
+
morphPolyline,
|
|
14794
|
+
multiplyMatrices,
|
|
14795
|
+
normalizeVector,
|
|
12205
14796
|
normalizeWatermark,
|
|
12206
14797
|
parallel,
|
|
14798
|
+
pointAlongPath,
|
|
14799
|
+
prepareScene,
|
|
14800
|
+
projectWorldPoint,
|
|
12207
14801
|
renderAnimatedGif,
|
|
12208
14802
|
renderAnimatedGifWithOutput,
|
|
12209
14803
|
renderAnimationGif,
|
|
12210
14804
|
renderAnimationGifWithOutput,
|
|
14805
|
+
renderAnimationVideo,
|
|
14806
|
+
renderMathSvg,
|
|
14807
|
+
renderRgbaVideo,
|
|
14808
|
+
renderSceneFrame,
|
|
14809
|
+
renderSceneVideo,
|
|
12211
14810
|
renderToBuffer,
|
|
12212
14811
|
renderToPng,
|
|
12213
14812
|
renderToPngWithOutput,
|
|
12214
14813
|
renderToSvg,
|
|
12215
14814
|
sampleAnimation,
|
|
14815
|
+
sampleAnimationFrame,
|
|
12216
14816
|
sampleAnimationFrames,
|
|
14817
|
+
sampleFunction,
|
|
14818
|
+
sampleGaussian,
|
|
14819
|
+
seededRandom,
|
|
14820
|
+
smoothstep,
|
|
14821
|
+
stableSoftmax,
|
|
12217
14822
|
styles,
|
|
12218
14823
|
toneGradients,
|
|
14824
|
+
tracePolyline,
|
|
12219
14825
|
tween,
|
|
12220
14826
|
typography,
|
|
14827
|
+
videoFrameSchedule,
|
|
12221
14828
|
withColorAlpha,
|
|
12222
14829
|
wrapWithBrand,
|
|
12223
14830
|
wrapWithWatermark
|