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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # Vizmatic agent prompt
2
2
 
3
- Use Vizmatic to create diagrams, figures, dashboards, presentation frames, and animated GIFs from React scene primitives. Render dark and light files locally or in CI.
3
+ Use Vizmatic to create diagrams, figures, dashboards, presentation frames, animated GIFs, and MP4 videos from React scene primitives. Render dark and light files locally or in CI.
4
4
 
5
5
  ## Quick start
6
6
 
@@ -175,7 +175,7 @@ export const watermark = (
175
175
  fontSize: 12,
176
176
  }}>
177
177
  <img src="data:image/svg+xml;base64,..." width={14} height={14} />
178
- LeetLLM
178
+ Your Product
179
179
  </div>
180
180
  </Watermark>
181
181
  )
@@ -189,7 +189,9 @@ vizmatic gif frames/animated-pipeline.tsx --out public/vizmatic --theme dark,lig
189
189
 
190
190
  ## Animated frames
191
191
 
192
- An animated module exports `createAnimation(theme)` for GIF output and keeps `create(theme)` for a static or reduced-motion fallback. Define state once, then describe holds, eased transitions, instant keyframes, and parallel property tracks. Vizmatic samples absolute timeline time and renders every GIF frame.
192
+ An animated module exports `createAnimation(theme)` for GIF or MP4 output and keeps `create(theme)` for a static or reduced-motion fallback. Define state once, then describe holds, eased transitions, instant keyframes, and parallel property tracks. Vizmatic samples absolute timeline time and renders every frame.
193
+
194
+ For MP4, export `createAnimation(theme)` and run `vizmatic video frames/lesson.tsx --out public/videos --theme dark --fps 30`. This requires Node.js 20 or newer and FFmpeg with the `libx264` encoder; add `--audio narration.wav` for AAC audio. The CLI pads or trims audio to the animation duration. Exported canvas dimensions after `--scale` must be positive even integers. MP4 uses an opaque theme background by default and supports 1–120 fps independently of GIF cadence. The browser builder exports GIF; MP4 runs in Node.js. Keep `.vtt` or `.srt` captions as separate files and synchronize them to the finished timeline. Use `examples/videos/request-lifecycle.tsx` as a short, generic starting point and `examples/videos/signal-to-story.tsx` for a longer film with parallel tracks, path tracing, camera motion, and an ending held on screen. Animate the data or mechanism the lesson explains; avoid decorative logo or icon reveals. For package consumers, install Vizmatic and React in the project and FFmpeg separately. In the repository, `pnpm render:video` regenerates the showcase media.
193
195
 
194
196
  ```tsx
195
197
  import React from "react"
@@ -409,9 +411,13 @@ Theme and render APIs:
409
411
  - `keyframe(value, label?)`: apply instant partial state update.
410
412
  - `parallel(tracks, label?)`: run property tracks concurrently; each track accepts `hold`, `tween`, and `keyframe` steps.
411
413
  - `sampleAnimation(animation, time)`: evaluate state at exact millisecond.
414
+ - `sampleAnimationFrame(animation, time, { index, count, delay, fps })`: sample state and timeline context at an exact video timestamp.
412
415
  - `sampleAnimationFrames(animation, { fps? })`: return deterministic state/frame samples with GIF-compatible delays.
413
416
  - `analyzeAnimationCadence(animation, { fps? })`: return frame count, encoded duration, target interval, and delay range without rendering.
414
417
  - `renderAnimationGif(animation, options)`: stream timeline samples into GIF.
418
+ - `renderAnimationVideo(animation, { width, height, outputPath, fps?, scale?, theme?, background?, watermark?, audioPath?, crf?, preset?, threads?, signal? })`: render typed TSX frames to H.264 MP4. Defaults to 30 fps and an opaque theme background; streams frames and checks overflow at each timestamp. FFmpeg is installed separately.
419
+ - `renderRgbaVideo(renderFrame, { width, height, duration, outputPath, fps?, audioPath?, crf?, preset?, signal? })`: encode caller-painted RGBA frames without buffering the whole film.
420
+ - `tracePolyline(points, progress)` and `pointAlongPath(points, progress)`: reveal and follow a path by arc length; `arcSwap(from, to, progress, options?)` exchanges positions along mirrored arcs; `smoothstep(progress)` clamps and eases progress.
415
421
  - `renderAnimationGifWithOutput(animation, options)`: same arguments and returns dimensions, input/encoded frame counts, delta-frame count, duration, and byte size.
416
422
  - `renderAnimatedGif(scenes, options)`: legacy `AnimatedScene[]` renderer for scene cuts and pixel transitions. It also accepts a defined animation.
417
423
  - `renderAnimatedGifWithOutput(scenes, options)`: same arguments as `renderAnimatedGif`; returns dimensions and encoding metrics.
package/README.md CHANGED
@@ -3,8 +3,8 @@
3
3
  </p>
4
4
 
5
5
  <p align="center">
6
- <strong>Diagrams, charts, dashboards, and GIFs from TSX.</strong><br/>
7
- Render dark and light PNG, SVG, and GIF files locally or in CI.
6
+ <strong>Diagrams, charts, dashboards, GIFs, and MP4 videos from TSX.</strong><br/>
7
+ Render theme-aware PNG, SVG, and GIF in the browser; export H.264 MP4 from Node.js or CI.
8
8
  </p>
9
9
 
10
10
  <p align="center">
@@ -261,6 +261,104 @@ Published packages include Inter, JetBrains Mono, Noto Sans, Noto Sans Math, and
261
261
 
262
262
  The complete Twemoji set stays available offline but ships as one Brotli bundle instead of 3,720 individual SVG files. `pnpm deps:check` keeps the package below 2.5 MB compressed, 5 MB unpacked, and 100 files.
263
263
 
264
+ ## Editable scenes for video applications
265
+
266
+ Use `vizmatic-scene` when an application stores editable TSX from a user or an
267
+ agent. The regular `vizmatic` CLI loads trusted Node modules; it is not the entry
268
+ point for running editable source inside an application.
269
+
270
+ ```bash
271
+ vizmatic-scene --input examples/pressure-mechanism.scene.json --output pressure.mp4
272
+ ```
273
+
274
+ The JSON request contains `source`, `width`, `height`, `duration`, optional `fps`
275
+ (24 by default), `theme`, `cues`, `seed`, and optional preview `time`. All times
276
+ are **seconds**. Output is PNG for an exact preview time or a silent H.264 MP4.
277
+ FFmpeg must be on PATH for MP4. Narration, captions and final assembly remain the
278
+ calling application's responsibility.
279
+
280
+ ```ts
281
+ import { renderSceneFrame, renderSceneVideo } from 'vizmatic'
282
+
283
+ const scene = {
284
+ width: 1920, height: 1080, duration: 12, fps: 24, theme: 'dark' as const,
285
+ cues: { reveal: 3.2 }, seed: 0,
286
+ source: `const amount = ease(cue('reveal', 2));
287
+ <svg width={width} height={height}>
288
+ <rect width={width} height={height} fill={c.bg}/>
289
+ <circle cx={lerp(300, 1600, amount)} cy={540} r={70} fill={c.info}/>
290
+ <text x={150} y={200} fontSize={64} fill={c.textPrimary}>Follow the mechanism</text>
291
+ </svg>`,
292
+ }
293
+ await renderSceneFrame({ ...scene, time: 4, outputPath: './preview.png' })
294
+ await renderSceneVideo({ ...scene, outputPath: './scene.mp4' })
295
+ ```
296
+
297
+ For editor previews, add `outputScale: 0.5` to either renderer and
298
+ `previewFps: 12` to `renderSceneVideo`. The renderer still evaluates and lays out
299
+ the original logical `width`, `height`, `duration`, `fps`, `frame`, and cues; it
300
+ only rasterizes fewer pixels and samples fewer video frames. `outputScale` must
301
+ be from 0.25 to 1 and produce even integer dimensions. `previewFps` must be an
302
+ integer from 1 to the scene's logical fps. These options also work in the
303
+ `vizmatic-scene` JSON request (`previewFps` is MP4-only).
304
+
305
+ Preview metadata reports effective `width`, `height`, `fps`, and `frameCount`,
306
+ plus `logicalWidth`, `logicalHeight`, `logicalFps`, `logicalFrameCount`,
307
+ `outputScale`, and, for video, `previewFps`. Its input hash binds the effective
308
+ output settings. Omitting the options preserves full-quality rendering and its
309
+ existing input hash.
310
+
311
+ Source uses local JavaScript/TypeScript declarations and helper components followed
312
+ by one JSX root. Imports, exports and module wrappers are not supported. Vizmatic
313
+ JSX primitives are provided automatically. SVG geometry and `<text>`/`<tspan>` use
314
+ the bundled fonts through Resvg, including inside HTML layouts. `Scene`, `Board`,
315
+ `CanvasItem`, charts and other trusted Vizmatic components use the same rendering
316
+ path in previews and video frames. Function-valued props are unsupported; calculate
317
+ formatted values and geometry in the source before returning JSX.
318
+
319
+ | Source value | Meaning |
320
+ | --- | --- |
321
+ | `width`, `height` | Logical canvas dimensions before optional preview scaling |
322
+ | `time` / `t`, `duration` | Current position and narration duration in seconds |
323
+ | `progress`, `frame`, `fps` | Normalized progress, zero-based frame and cadence |
324
+ | `theme`, `c` | Theme name and frozen Vizmatic theme colors |
325
+ | `cues` | Named narration cue positions in seconds |
326
+ | `seed`, `Math.random()` | Explicit uint32 seed and deterministic random sequence |
327
+ | `clamp(x, min=0, max=1)`, `lerp(a,b,p)` | Clamp and linear interpolation |
328
+ | `ease(p)`, `easeInOut(p)`, `easeOut(p)` | Clamped smoothstep and cubic ease-out |
329
+ | `cue(name, span=1)` | Progress from a named cue over a span in seconds |
330
+
331
+ A missing named cue fails preparation rather than inventing a timing. Applications
332
+ should resolve production cues against actual narration and label estimated preview
333
+ cues as estimates. Source can be evaluated without Node rendering through
334
+ `evaluateSceneSource` or `prepareScene` from `vizmatic/scene-runtime`, suitable for
335
+ a browser Worker. The same evaluator produces a validated JSON scene graph in both
336
+ environments.
337
+
338
+ Editable JavaScript executes inside QuickJS WebAssembly with no host objects,
339
+ callbacks, filesystem, network, browser storage or module loader. Each frame gets
340
+ a fresh context, a 64 MiB guest memory limit, a 256 KiB stack and a 250 ms evaluation
341
+ deadline. Only bounded JSON reaches trusted components. External image references,
342
+ resource URLs, event handlers, raw HTML and executable props are rejected. The
343
+ renderer uses fingerprinted package fonts and emoji assets, with no environment
344
+ overrides, system fonts or network fallback. Local SVG fragment references work.
345
+
346
+ Limits are 128 KiB of source, 2 MiB of serialized graph, 2,000 JSX elements, 64
347
+ levels of nesting, at most 1,920 pixels per edge and 2,073,600 pixels per canvas,
348
+ 120 seconds per scene, 1–60 fps and 3,600 frames. Nested SVGs also share a per-frame
349
+ allocation budget. Run the CLI in a subprocess with a bounded environment, captured
350
+ stderr, memory limit and total deadline; the QuickJS deadline governs author code,
351
+ while the caller's process deadline also covers trusted layout and FFmpeg.
352
+
353
+ The CLI writes one JSON metadata line on success. `runtimeVersion`,
354
+ `sourceSha256`, `inputSha256`, `assetSha256`, `fontAssetsSha256`, dimensions,
355
+ duration, fps, timeline `frameCount`, output byte count and output path identify the
356
+ result. `assetSha256` hashes the actual output file. Preview metadata adds `time`;
357
+ MP4 adds `encodedDuration`. Cache inputs include the runtime, exact source, cues,
358
+ seed, theme, dimensions, duration, cadence, pinned assets, output kind and preview
359
+ time. Like the existing video API, MP4 duration rounds to the nearest frame.
360
+ Existing output files survive a failed render.
361
+
264
362
  ## API
265
363
 
266
364
  ### Themes
@@ -574,6 +672,384 @@ await renderAnimationGif(createAnimation("dark"), {
574
672
 
575
673
  `createScenes(theme)` and `renderAnimatedGif(AnimatedScene[])` remain supported for intentional scene cuts and pixel crossfades. `fps` controls their transition sampling as well as typed timelines. GIF output uses one shared 256-color palette and centisecond timing. Opaque animations use changed rectangles by default; set `deltaFrames: false` only for legacy decoder debugging. Transparent animations stay full-frame to preserve one-bit compositing. Use PNG/SVG for smooth alpha edges.
576
674
 
675
+ ## MP4 export and mathematical motion
676
+
677
+ Export an existing TSX animation directly with `vizmatic video`:
678
+
679
+ ```bash
680
+ vizmatic video ./lesson.tsx --out ./videos --theme dark --fps 30
681
+ vizmatic video ./lesson.tsx --out ./videos --theme dark,light --fps 60 --audio narration.wav
682
+ ```
683
+
684
+ The module exports `width`, `height`, and `createAnimation(theme)`, just like the
685
+ GIF examples. The video command samples the timeline at exact video timestamps,
686
+ renders each React scene, and streams it to FFmpeg. It writes `lesson_dark.mp4`
687
+ and a `video-manifest.json`. Use `--crf 18` for crisp text, `--preset medium` for
688
+ a smaller file, and `--scale 2` for twice the pixel dimensions. FFmpeg with
689
+ libx264 is required; audio export also needs AAC. MP4 requires an opaque
690
+ background, with the theme background used by default. Set `--background` to
691
+ an opaque CSS color to choose another fill. The browser builder exports GIF;
692
+ MP4 encoding runs in Node.js.
693
+
694
+ ### Render a complete video example
695
+
696
+ The short [request lifecycle starter](examples/videos/request-lifecycle.tsx)
697
+ shows one request moving through a three-step workflow. It uses only Vizmatic's
698
+ published package and keeps the motion tied to the work being explained. The
699
+ longer [From noise to signal film](examples/videos/signal-to-story.tsx) shows a
700
+ chart, synthetic observations, and a fitted trend.
701
+
702
+ In a Node.js 20 or newer project, install Vizmatic and React. [Install FFmpeg](https://ffmpeg.org/download.html)
703
+ separately and check that its encoder list includes `libx264`. Audio output
704
+ also needs the `aac` encoder.
705
+
706
+ ```bash
707
+ npm install --save-dev vizmatic@0.4.0 react
708
+ npx vizmatic video ./request-lifecycle.tsx --out ./dist/videos --theme dark --fps 30
709
+ ```
710
+
711
+ The CLI writes `request-lifecycle_dark.mp4` and `video-manifest.json` under
712
+ `./dist/videos`. Add narration with `--audio ./narration.wav`; the audio is
713
+ trimmed or padded to the animation duration and encoded as AAC. Vizmatic renders
714
+ the picture and optional audio. Keep `.vtt` or `.srt` captions as separate files
715
+ and synchronize their cues to the finished timeline. The downloadable source
716
+ and a copyable command are also on the [website video example](https://bvolpato.github.io/vizmatic/#video).
717
+
718
+ The same workflow is available through the API:
719
+
720
+ ```ts
721
+ import { renderAnimationVideo } from "vizmatic"
722
+ import { createAnimation, width, height } from "./lesson"
723
+
724
+ await renderAnimationVideo(createAnimation("dark"), {
725
+ width, height, fps: 30, theme: "dark",
726
+ outputPath: "videos/lesson.mp4",
727
+ crf: 18, preset: "medium",
728
+ // audioPath: "narration.wav",
729
+ })
730
+ ```
731
+
732
+ Video supports 1–120 fps independently of the GIF cadence. Canvas dimensions
733
+ after scaling must be positive even integers. Every frame is checked for
734
+ overflow; failures report its timestamp and timeline label and preserve an
735
+ existing output file. `signal`, audio alignment, and streaming use the same
736
+ contracts as `renderRgbaVideo` below. Keep a finite film's last state visible
737
+ long enough to read. Use `parallel` tracks for overlapping transitions and
738
+ path helpers for continuous motion.
739
+
740
+ Watch **[From noise to signal](https://bvolpato.github.io/vizmatic/#video)**,
741
+ an 18-second motion design example built from
742
+ [`examples/videos/signal-to-story.tsx`](examples/videos/signal-to-story.tsx).
743
+ Its chart fits actual least-squares coefficients to explicitly synthetic data.
744
+ The source demonstrates staggered entrances, arc-length line reveals,
745
+ parallel tracks, camera motion, and an ending held on screen. From a repository
746
+ checkout, generate the film, posters, captions, and downloadable source with:
747
+
748
+ ```bash
749
+ pnpm install --frozen-lockfile
750
+ pnpm render:video
751
+ ```
752
+
753
+ The repository's `pnpm render:video` script regenerates the showcase poster,
754
+ captions, downloadable sources, and MP4. `pnpm site:build` regenerates the
755
+ website preview and source downloads without encoding the MP4. Those generated
756
+ media files live under `docs/assets/video/` and are excluded from Git. Pages
757
+ builds the MP4 and verifies it with `pnpm docs:check --require-video` before
758
+ publication. The website loads the poster until playback is requested and
759
+ provides chapter controls and a text description.
760
+
761
+ `renderRgbaVideo` streams caller-rendered RGBA frames to FFmpeg as an H.264 MP4.
762
+ It supports 1–120 fps, even pixel dimensions, optional audio, and backpressure,
763
+ without retaining the whole film in memory. Install FFmpeg with libx264 and AAC
764
+ support separately. Canvas painters can use the optional `@napi-rs/canvas` package:
765
+
766
+ ```ts
767
+ import { createCanvas } from '@napi-rs/canvas'
768
+ import { renderRgbaVideo, pointAlongPath, tracePolyline } from 'vizmatic'
769
+
770
+ const canvas = createCanvas(1280, 720)
771
+ const ctx = canvas.getContext('2d')
772
+ const path = [{ x: 150, y: 550 }, { x: 640, y: 200 }, { x: 1130, y: 550 }]
773
+
774
+ await renderRgbaVideo((frame) => {
775
+ ctx.fillStyle = '#101827'
776
+ ctx.fillRect(0, 0, 1280, 720)
777
+ const progress = Math.min(1, frame.time / 2000)
778
+ const visible = tracePolyline(path, progress)
779
+ ctx.beginPath()
780
+ visible.forEach((point, i) => i ? ctx.lineTo(point.x, point.y) : ctx.moveTo(point.x, point.y))
781
+ ctx.strokeStyle = '#63deec'
782
+ ctx.lineWidth = 5
783
+ ctx.stroke()
784
+ const point = pointAlongPath(path, progress)
785
+ ctx.beginPath()
786
+ ctx.arc(point.x, point.y, 14, 0, Math.PI * 2)
787
+ ctx.fillStyle = '#f4d477'
788
+ ctx.fill()
789
+ return canvas.data()
790
+ }, {
791
+ width: 1280, height: 720, duration: 3000, fps: 30,
792
+ outputPath: 'lesson.mp4',
793
+ // audioPath: 'narration.wav',
794
+ })
795
+ ```
796
+
797
+ Durations and `frame.time` are milliseconds, as in typed animation timelines.
798
+ `videoFrameSchedule(duration, fps)` lazily yields the same frame timestamps;
799
+ the endpoint is not emitted as an extra frame. The callback can be async and
800
+ must return exactly `width * height * 4` bytes. Each frame is consumed before
801
+ requesting the next. Optional audio is padded or trimmed to the video duration
802
+ and encoded as stereo AAC at 48 kHz. `signal` cancels an export. A failed
803
+ callback or encoder removes temporary files and preserves an existing output.
804
+
805
+ Use `defineAnimation` and `sampleAnimation(animation, frame.time)` to drive
806
+ multiple properties from a shared timeline. Sample per frame rather than
807
+ building a GIF frame array for a long video.
808
+
809
+ Motion helpers operate on `{ x, y }` points:
810
+
811
+ - `tracePolyline(points, progress)` reveals a path by actual arc length.
812
+ - `pointAlongPath(points, progress)` locates a moving marker on the same path.
813
+ - `morphPolyline(from, to, progress, { samples, easing })` smoothly changes one
814
+ path into another, including paths with different vertex counts. It matches
815
+ equal arc-length positions, uses 64 samples and `smoothstep` by default,
816
+ and preserves the inputs. Use it for trajectories and changing curves.
817
+ - `createPolylineMorph(from, to, options)` prepares the same arc-length
818
+ correspondence once and returns a `(progress) => points` sampler. Reuse it
819
+ across frames to avoid repeating path measurement and resampling.
820
+ - `arcSwap(from, to, progress, { lift, easing })` exchanges positions along
821
+ opposite arcs. `lift` is the maximum perpendicular displacement, defaulting
822
+ to 80; the default easing is `smoothstep`.
823
+ - `smoothstep(progress)` clamps and eases progress between zero and one.
824
+
825
+ Path results use fresh points and handle repeated vertices. Empty paths trace
826
+ to an empty array; following an empty path throws. These helpers let a lesson
827
+ draw a curve, trace a computation graph, or exchange token positions while
828
+ keeping the underlying numerical state explicit.
829
+
830
+ `createCanvasComponents(painter)` provides reusable panels, labeled cards,
831
+ matrices, token rows, and moving particles for a Canvas video renderer. Inject
832
+ the renderer's drawing interface, including its containment and opacity
833
+ scopes. Every component uses those methods, so host layout checks and shape
834
+ metadata remain available. The components use no raw Canvas operations or
835
+ raster intermediates.
836
+
837
+ ```ts
838
+ import { createCanvasComponents, type CanvasPainter } from 'vizmatic'
839
+
840
+ // The host supplies checked primitives. Scope callbacks must keep those
841
+ // checks active, and opacity must restore drawing state with try/finally.
842
+ function drawLesson<Shape>(painter: CanvasPainter<Shape>) {
843
+ const scene = createCanvasComponents(painter)
844
+ const node = scene.card({
845
+ x: 40, y: 40, width: 160, height: 68, label: 'query',
846
+ fill: '#18283b', stroke: '#63deec', textColor: '#fff',
847
+ })
848
+ scene.matrix({
849
+ values: [[1, -2], [3, 4]], x: 240, y: 40, cellSize: 80,
850
+ style: { fill: '#18283b', textColor: '#fff', fontSize: 26 },
851
+ cellStyle: (value) => ({ labelOpacity: value < 0 ? 0.5 : 1 }),
852
+ })
853
+ scene.tokenRow({
854
+ values: ['dogs', 'chase', 'cats'], centerX: 300, y: 240,
855
+ fill: '#18283b', textColor: '#fff', reveal: 0.6,
856
+ })
857
+ return node // Original host geometry, usable for connector anchors.
858
+ }
859
+ ```
860
+
861
+ Panels default to a container scope with 10 pixels of padding and a 14 pixel
862
+ corner radius; pass `scope: 'label'` for a label-only scope. Cards center their
863
+ label with a baseline offset of `fontSize * 0.34`. `opacity` affects the whole
864
+ card; `labelOpacity` reveals the text independently. Panel and card geometry
865
+ remains available at zero opacity. Finite opacity values are clamped to the
866
+ range from zero to one before composing fades or token reveals. Non-finite
867
+ opacity values throw. Matrices and token rows skip invisible
868
+ cells or items. Matrix `format(value, row, column)` and
869
+ `cellStyle(value, row, column)` customize individual cells without rebuilding
870
+ the component.
871
+
872
+ `layoutTokenRow(values, options)` returns `{ text, x, width }` items for shared
873
+ layout and connector placement. Automatic widths use the literal spelling;
874
+ pass `width` for fixed-width cards. `x` takes precedence over `centerX`.
875
+ `tokenRow` adds staggered reveal, with each item's opacity equal to
876
+ `clamp(reveal * itemCount - index, 0, 1)`. Use `particle({ points, progress,
877
+ fill })` to move a marker by route length; endpoints remain unpainted.
878
+
879
+ `createTeachingCanvas(painter)` adds checked axes, traced curves, scatter plots,
880
+ positive bar charts, and explicit-layout flow graphs. Supply a `TeachingPainter`
881
+ with the same checked methods plus `math`, `line`, `arrow`, `path`, and `connect`.
882
+ Its `connect` method returns `{ from, to }` endpoints. No component bypasses the
883
+ host's paint, containment, or opacity checks.
884
+
885
+ Scatter markers with centers inside the closed data domains remain fully
886
+ visible, including points on axis endpoints. Their circles can extend beyond
887
+ the axis rectangle; the host audits that complete geometry. Leave room around
888
+ the axes or pad the data domains when a surrounding container needs clearance.
889
+ Centers outside the data domains are omitted.
890
+
891
+ ```ts
892
+ import { createTeachingCanvas, sampleFunction, stableSoftmax } from 'vizmatic'
893
+
894
+ const charts = createTeachingCanvas(painter)
895
+ const plot = charts.axes({
896
+ x: 160, y: 140, width: 640, height: 360,
897
+ xDomain: [-3, 3], yDomain: [0, 1],
898
+ xTicks: [-3, 0, 3], yTicks: [0, 0.5, 1],
899
+ xLabel: 'Input', yLabel: 'Probability', gridColor: '#283447',
900
+ })
901
+ charts.curve({
902
+ plot, points: sampleFunction(x => 1 / (1 + Math.exp(-x)), -3, 3),
903
+ color: '#63deec', progress: 0.7,
904
+ })
905
+ charts.bars({
906
+ x: 980, y: 140, width: 480, height: 360,
907
+ values: stableSoftmax([2, 1, 0]), labels: ['cat', 'dog', 'bird'], max: 1,
908
+ })
909
+ ```
910
+
911
+ Axes return `{ point(x, y), bounds, xDomain, yDomain }`; plot bounds contain the
912
+ data marks, while tick labels and titles occupy space outside the plot. Use
913
+ `axes({ ..., equalUnits: true })` to preserve angles and distances. This
914
+ fits both requested domains at equal pixels per data unit and centers the
915
+ resulting plot inside the requested rectangle. Returned bounds, axes, labels,
916
+ point projection, and curve clipping use that fitted plot. The default fills
917
+ the requested rectangle with independent horizontal and vertical scales. Curves
918
+ return the visible mapped polyline and delegate clipping to the checked host.
919
+ Scatter omits circles whose complete mark would extend beyond the plot.
920
+ Bars accept nonnegative values and return `{ bars, slots, bounds }`, preserving
921
+ input indices with `null` for zero-height bars. `slots` describe full-height
922
+ columns, including zero values. Progress is clamped to the unit interval.
923
+
924
+ `flowGraph({ nodes, edges })` takes explicit node bounds and ID-based edges. It
925
+ draws edges and optional moving particles behind the cards, then transfers host
926
+ geometry metadata onto the connector references. The returned `{ nodes, routes }`
927
+ supports subsequent annotations and movement. Keep topic-specific numerical
928
+ models in the lesson; share their chart and graph composition through this API.
929
+
930
+ `transfer` coordinates an attached connector and optional particle. Supply each
931
+ painted card and its matching local opacity. Both marks use the minimum endpoint
932
+ and edge opacity; a shared host frame scope multiplies that opacity once.
933
+
934
+ ```ts
935
+ const route = charts.transfer({
936
+ source: { shape: source, opacity: 1 }, target: { shape: target, opacity: 0.6 },
937
+ progress: 0.5, color: '#63deec', particle: { radius: 9, fill: '#ffce73' },
938
+ })
939
+ ```
940
+
941
+ Hidden endpoints return `null`; progress outside `(0, 1)` omits the particle.
942
+ Gaps clear both cards by the marker/stroke extent plus `margin` (default 2),
943
+ preserving larger requests. Coincident centers or insufficient room throw.
944
+ The host must anchor rounded cards along their center ray and offset gaps along
945
+ that ray. Original routes and shape references retain audit evidence; the host
946
+ still checks intervening obstacles.
947
+
948
+ `grid` uses one panel and `rows + columns - 2` paths. `lineWidth` controls internal
949
+ lines; the border uses the host's rectangle stroke. Highlights and literal text
950
+ labels stay scoped; label dimensions must match the grid.
951
+
952
+ Supply `{ x, y, width, height, rows, columns }`; returns
953
+ `{ shape, bounds, cells, cell(row, column) }`. Connect to the painted `shape`;
954
+ cells are label/math geometry. `layoutCellGrid` returns layout without paint.
955
+
956
+ `timeline` draws supplied intervals on named lanes. One `time` controls elapsed
957
+ fills, completion flags, and the axis cursor. Intervals on the same lane must
958
+ not overlap; use separate lanes for concurrent work. Bounds include the lane
959
+ labels and time axis. Labels occupy their full planned span above the fill;
960
+ omit labels on spans too narrow for the chosen font. Future intervals paint
961
+ nothing, and visible interval labels use the same local opacity as their fill.
962
+
963
+ `allocation` draws a capacity-scaled strip and a value ledger from the same
964
+ nonnegative parts. Unused capacity remains visible; over-allocation throws.
965
+ Supply bounds tall enough for the header, strip, and one row per part plus Free.
966
+ `format` and `unit` apply to the computed totals and ledger values.
967
+
968
+ ```ts
969
+ const trace = charts.timeline({
970
+ x: 140, y: 260, width: 1640, height: 300, domain: [0, 100], time: 50,
971
+ lanes: [{ id: 'cpu', label: 'CPU' }, { id: 'gpu', label: 'GPU' }],
972
+ intervals: [
973
+ { id: 'submit', lane: 'cpu', start: 0, end: 20, label: 'Submit' },
974
+ { id: 'kernel', lane: 'gpu', start: 20, end: 80, label: 'Kernel' },
975
+ ],
976
+ })
977
+ const memory = charts.allocation({
978
+ x: 260, y: 650, width: 1400, height: 370, capacity: 100, unit: 'GB',
979
+ parts: [{ id: 'weights', label: 'Weights', value: 20 },
980
+ { id: 'state', label: 'Optimizer state', value: 30 }],
981
+ })
982
+ // trace.intervals.kernel.elapsed === 30; memory.remaining === 50
983
+ ```
984
+
985
+ Timeline results expose `time`, `point(time)` (the canvas x coordinate), live
986
+ lane shapes, and ID-keyed intervals with `shape`, `bounds`, `elapsed`,
987
+ `complete`, and local `opacity`.
988
+ Zero elapsed time or zero opacity returns a null interval shape. Allocation
989
+ returns `used`, `remaining`, capacity-strip `bounds`, `freeBounds`, ordered
990
+ part geometry, the painted strip `shape`, and per-part `shapes` (null at zero
991
+ area). Connect only to those painted references. `layoutAllocation` computes
992
+ pure strip geometry for custom diagrams, with the supplied bounds as the strip.
993
+
994
+ `createCueTrack` holds one simulation snapshot until an explicit beat cue.
995
+ Sample once and derive tables, metrics and decisions from that same snapshot.
996
+
997
+ ```ts
998
+ import { createCueTrack } from 'vizmatic'
999
+
1000
+ const cutoffs = createCueTrack({
1001
+ initial: { id: 'morning', snapshot: { cutoff: 540, ageHours: 8 } },
1002
+ cues: [
1003
+ { id: 'noon', beat: 3, at: 0.2, snapshot: { cutoff: 720, ageHours: 3.5 } },
1004
+ ],
1005
+ })
1006
+ const { id, snapshot } = cutoffs.sample({ beat: state.beat, beatP: state.beatP })
1007
+ ```
1008
+
1009
+ Cue IDs are unique and positions increase strictly. Commits are inclusive;
1010
+ beat-end `1` equals next-beat `0`. End snapshots hold outside the cues. Beats are
1011
+ nonnegative safe integers; progress is `[0, 1]`. Definitions are copied and result
1012
+ records frozen; snapshots retain identity without mutation or cloning. Treat
1013
+ snapshots as immutable. The timeline still owns audio timing and motion.
1014
+
1015
+ Numerical helpers include `seededRandom(seed)`, `lerpArray`, `dotProduct`,
1016
+ `multiplyMatrices`, `stableSoftmax(values, temperature)`, `entropy`,
1017
+ `normalizeVector`, `sampleFunction`, `gaussian(mean, sigma, x)`, and
1018
+ `sampleGaussian(random)`. Softmax subtracts the largest logit before scaling;
1019
+ entropy accepts normalized probabilities; normalization preserves zero vectors.
1020
+ Seeded sampling makes simulations reproducible during rendering and review.
1021
+ Camera helpers keep world geometry and screen annotations aligned:
1022
+
1023
+ - `interpolateCamera(from, to, progress)` eases a camera's world-space center
1024
+ and interpolates zoom logarithmically. Optional `minZoom` and `maxZoom`
1025
+ constrain both endpoints.
1026
+ - `cameraSvgTransform(camera, { width, height })` centers an SVG group on that
1027
+ camera. `projectWorldPoint(point, camera, viewport)` applies the same transform
1028
+ to a label anchor rendered outside the group.
1029
+
1030
+ Keep event progress separate from camera progress when cutting between views.
1031
+ The event can continue from its previous state while each shot has its own
1032
+ pan or zoom. Simulation time and camera movement can follow separate timelines.
1033
+
1034
+ Use `renderMathSvg` to typeset TeX into standalone SVG paths for a canvas,
1035
+ figure, or video frame:
1036
+
1037
+ ```ts
1038
+ import { renderMathSvg } from 'vizmatic'
1039
+
1040
+ const formula = renderMathSvg(String.raw`\frac{\partial L}{\partial W_x} + x^2`, {
1041
+ fontSize: 48,
1042
+ color: '#63deec',
1043
+ })
1044
+ // formula.svg contains glyph paths; width, height, and baseline are pixels.
1045
+ ```
1046
+
1047
+ The synchronous renderer supports AMS equations, fractions, subscripts, and
1048
+ superscripts. It returns baseline metrics for alignment with other labels,
1049
+ caches formulas, and isolates macro definitions between calls. Invalid TeX
1050
+ throws an error. SVG paths render with local assets and require no browser or
1051
+ network access.
1052
+
577
1053
  ## Development
578
1054
 
579
1055
  See [`CONTRIBUTING.md`](CONTRIBUTING.md) for setup, testing, visual review, dependency updates, and pull request guidance.
@@ -616,7 +1092,7 @@ Choose the Animation scene template to play, pause, scrub time, and export a GIF
616
1092
 
617
1093
  The generated `components.json` includes compiler-derived prop types, requiredness, and finite allowed-value references. Shared value lists live in `propEnums`; defaults are not inferred. Full TypeScript definitions remain the contract for structured data and React values.
618
1094
 
619
- The website is generated from `docs/*.template.html`, the shared shell in `scripts/site-shell.ts`, and the component registry. Run `pnpm site:build` after editing these sources, then `pnpm docs:check`. Use `pnpm site:serve` for browser validation. The generated agent references, property controls, and example adapters update with the same build. If the bundled fonts change, regenerate the website's WOFF2 files with `pnpm site:fonts` using uv.
1095
+ The website is generated from `docs/*.template.html`, the shared shell in `scripts/site-shell.ts`, and the component registry. Run `pnpm site:build` after editing these sources, then `pnpm docs:check`. Use `pnpm site:serve` for browser validation. The generated agent references, property controls, and example adapters update with the same build. If the bundled fonts change, regenerate the website's WOFF2 files with `pnpm site:fonts` using uv 0.9.17 or newer.
620
1096
 
621
1097
  ## Publishing
622
1098