vizmatic 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/PROMPT.md +75 -531
  2. package/README.md +85 -1052
  3. package/ROADMAP.md +49 -67
  4. package/SCIENCE.md +250 -0
  5. package/assets/THIRD_PARTY_LICENSES.md +44 -1
  6. package/assets/fonts/InstrumentSerif-Italic.ttf +0 -0
  7. package/assets/fonts/InstrumentSerif-Regular.ttf +0 -0
  8. package/assets/fonts/SourceSerif4-24pt-Italic.ttf +0 -0
  9. package/assets/fonts/SourceSerif4-24pt-Regular.ttf +0 -0
  10. package/assets/licenses/raster-codecs-MIT.txt +74 -0
  11. package/dist/chunk-3F2VQ7NW.js +1 -0
  12. package/dist/{chunk-FEIPTPBZ.js → chunk-4XE64I2U.js} +53 -463
  13. package/dist/chunk-5ZAFH2JC.js +4231 -0
  14. package/dist/chunk-JHHPLALU.js +79 -0
  15. package/dist/chunk-LTX44BAE.js +112 -0
  16. package/dist/chunk-MLKGABMK.js +9 -0
  17. package/dist/chunk-PSBF4TEK.js +1 -0
  18. package/dist/chunk-RPAHMKAR.js +605 -0
  19. package/dist/chunk-RWF4VBUL.js +3617 -0
  20. package/dist/cli.js +369 -12
  21. package/dist/index.cjs +7413 -1810
  22. package/dist/index.d.cts +900 -599
  23. package/dist/index.d.ts +900 -599
  24. package/dist/index.js +5019 -3278
  25. package/dist/math-LXB4FH4E.js +7 -0
  26. package/dist/math-QVCETQDQ.js +1 -0
  27. package/dist/scene-browser-assets.d.ts +38 -0
  28. package/dist/scene-browser-assets.js +53 -0
  29. package/dist/scene-browser-chunks/chunk-5MVLYGXM.js +70 -0
  30. package/dist/scene-browser-chunks/chunk-ASXKN3NU.js +1 -0
  31. package/dist/scene-browser-chunks/chunk-CM5Y5LZP.js +1 -0
  32. package/dist/scene-browser-chunks/chunk-DP7NB4EW.js +6 -0
  33. package/dist/scene-browser-chunks/emscripten-module.browser-M5AEKJGE.js +1 -0
  34. package/dist/scene-browser-chunks/ffi-FL6ORJU3.js +1 -0
  35. package/dist/scene-browser-chunks/module-ES6BEMUI-JD5S5VKR.js +1 -0
  36. package/dist/scene-browser-chunks/module-asyncify-2EFITU5U-HWPFJFJC.js +1 -0
  37. package/dist/scene-browser-chunks/scene-browser-layout-M3XSXMV4.js +27 -0
  38. package/dist/scene-browser.d.ts +117 -0
  39. package/dist/scene-browser.js +220 -0
  40. package/dist/scene-cli.js +1 -1
  41. package/dist/scene-runtime.cjs +168 -103
  42. package/dist/scene-runtime.d.cts +3 -2
  43. package/dist/scene-runtime.d.ts +3 -2
  44. package/dist/scene-runtime.js +3 -1
  45. package/dist/server-2FYHZ4UO.js +331 -0
  46. package/dist/stage-browser/browser.d.ts +2483 -0
  47. package/dist/stage-browser/chunk-SQE76S5B.js +1 -0
  48. package/dist/stage-browser/chunk-VZNL6JY2.js +59 -0
  49. package/dist/stage-browser/dagre.esm-N2NIVIAZ.js +6 -0
  50. package/dist/stage-browser/math-4WFNHVV2.js +18 -0
  51. package/dist/stage-browser/stage.js +19 -0
  52. package/dist/stage-export.cjs +4980 -0
  53. package/dist/stage-export.d.cts +112 -0
  54. package/dist/stage-export.d.ts +112 -0
  55. package/dist/stage-export.js +544 -0
  56. package/dist/stage.cjs +9789 -0
  57. package/dist/stage.d.cts +1679 -0
  58. package/dist/stage.d.ts +1679 -0
  59. package/dist/stage.js +5418 -0
  60. package/dist/svg-import-Djj2q7Pc.d.cts +742 -0
  61. package/dist/svg-import-Djj2q7Pc.d.ts +742 -0
  62. package/dist/video-CcHW1qhV.d.cts +532 -0
  63. package/dist/video-CcHW1qhV.d.ts +532 -0
  64. package/examples/README.md +18 -0
  65. package/examples/agent-pipeline.tsx +4 -4
  66. package/examples/animated-pipeline.tsx +1 -5
  67. package/examples/attention-head.tsx +12 -12
  68. package/examples/aurora-incident.tsx +4 -3
  69. package/examples/building-blocks.tsx +8 -9
  70. package/examples/catalog-charts.tsx +4 -4
  71. package/examples/catalog-content.tsx +7 -9
  72. package/examples/catalog-convolution-kernel.tsx +116 -0
  73. package/examples/catalog-data.tsx +2 -8
  74. package/examples/catalog-dataflow.tsx +5 -9
  75. package/examples/catalog-dense.tsx +80 -0
  76. package/examples/catalog-deployment.tsx +5 -11
  77. package/examples/catalog-diagrams.tsx +13 -16
  78. package/examples/catalog-drawing.tsx +7 -7
  79. package/examples/catalog-flows.tsx +4 -4
  80. package/examples/catalog-foundations.tsx +11 -11
  81. package/examples/catalog-gaussian-blur.tsx +146 -0
  82. package/examples/catalog-image-tensors.tsx +115 -0
  83. package/examples/catalog-ml.tsx +36 -31
  84. package/examples/catalog-numeric-matrices.tsx +93 -0
  85. package/examples/catalog-photo-blur.tsx +209 -0
  86. package/examples/catalog-science-ai.tsx +130 -0
  87. package/examples/catalog-science-chemistry.tsx +103 -0
  88. package/examples/catalog-science-math.tsx +93 -0
  89. package/examples/catalog-science-physics.tsx +84 -0
  90. package/examples/catalog-sequence.tsx +59 -38
  91. package/examples/data-pipeline-lineage-presentation.tsx +5 -0
  92. package/examples/data-pipeline-lineage.tsx +85 -0
  93. package/examples/daybreak-launch.tsx +1 -0
  94. package/examples/desired-quadrant.tsx +7 -8
  95. package/examples/engineering-dashboard-presentation.tsx +13 -0
  96. package/examples/engineering-dashboard.tsx +160 -0
  97. package/examples/engineering-flow.tsx +2 -4
  98. package/examples/eval-dashboard.tsx +6 -6
  99. package/examples/films/attention.ts +278 -0
  100. package/examples/films/cache-miss.ts +431 -0
  101. package/examples/films/catalog.json +132 -0
  102. package/examples/films/central-limit.ts +269 -0
  103. package/examples/films/complex-maps.ts +273 -0
  104. package/examples/films/deck-example.ts +224 -0
  105. package/examples/films/euler-circle.ts +179 -0
  106. package/examples/films/fourier-epicycles.ts +265 -0
  107. package/examples/films/gradient-descent.ts +345 -0
  108. package/examples/films/linear-maps.ts +175 -0
  109. package/examples/films/lorenz.ts +207 -0
  110. package/examples/films/pythagoras.ts +185 -0
  111. package/examples/films/taylor-series.ts +159 -0
  112. package/examples/films/vizmatic-title.ts +117 -0
  113. package/examples/llm-serving-stack-presentation.tsx +5 -0
  114. package/examples/llm-serving-stack.tsx +94 -0
  115. package/examples/model-garden.tsx +1 -0
  116. package/examples/model-router.tsx +6 -6
  117. package/examples/nccl-all-gather.tsx +3 -3
  118. package/examples/nccl-all-reduce.tsx +3 -3
  119. package/examples/nccl-all-to-all.tsx +1 -1
  120. package/examples/nccl-broadcast.tsx +1 -1
  121. package/examples/nccl-reduce-scatter.tsx +5 -5
  122. package/examples/orthogonal-routing.tsx +4 -4
  123. package/examples/pareto-frontier.tsx +9 -10
  124. package/examples/presentation-frame.tsx +6 -6
  125. package/examples/production-system-map-presentation.tsx +5 -0
  126. package/examples/production-system-map.tsx +130 -0
  127. package/examples/rag-graph.tsx +7 -7
  128. package/examples/release-card.tsx +5 -5
  129. package/examples/spec-anatomy.tsx +5 -5
  130. package/examples/system-architecture.tsx +19 -32
  131. package/examples/theme-system.tsx +1 -1
  132. package/examples/token-matrix.tsx +4 -2
  133. package/examples/transparent-badge.tsx +1 -2
  134. package/examples/videos/README.md +36 -2
  135. package/examples/videos/calculus-tangent.tsx +101 -0
  136. package/examples/videos/catalyst-pathway.tsx +56 -0
  137. package/examples/videos/causal-attention.tsx +91 -0
  138. package/examples/videos/convolution-kernel.tsx +34 -0
  139. package/examples/videos/gaussian-blur.tsx +32 -0
  140. package/examples/videos/image-to-matrix.tsx +22 -0
  141. package/examples/videos/matrix-multiplication.tsx +128 -0
  142. package/examples/videos/photo-gaussian-blur.tsx +39 -0
  143. package/examples/videos/wave-interference.tsx +80 -0
  144. package/examples/vizmatic-bare.d.ts +1 -0
  145. package/examples/vizmatic-hero.tsx +9 -18
  146. package/examples/website-workflow.tsx +7 -7
  147. package/examples/weekend-field-notes.tsx +3 -2
  148. package/package.json +65 -11
  149. package/dist/chunk-TH3F4SDB.js +0 -79
package/README.md CHANGED
@@ -1,1117 +1,150 @@
1
1
  <p align="center">
2
- <img src="https://bvolpato.github.io/vizmatic/assets/logo.svg" alt="Vizmatic logo" width="460" />
2
+ <a href="https://bvolpato.github.io/vizmatic/"><img src="https://bvolpato.github.io/vizmatic/assets/logo.svg" alt="Vizmatic" width="360" /></a>
3
3
  </p>
4
4
 
5
5
  <p align="center">
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.
6
+ <strong>Explain things in motion, from code.</strong><br/>
7
+ Vector films that play live in a browser and export frame-exact to MP4. Dense technical figures from TSX.
8
8
  </p>
9
9
 
10
10
  <p align="center">
11
11
  <a href="https://github.com/bvolpato/vizmatic/actions/workflows/ci.yml"><img src="https://github.com/bvolpato/vizmatic/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
12
- <a href="https://github.com/bvolpato/vizmatic/actions/workflows/pages.yml"><img src="https://github.com/bvolpato/vizmatic/actions/workflows/pages.yml/badge.svg" alt="Pages" /></a>
13
- <a href="https://github.com/bvolpato/vizmatic/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License: MIT" /></a>
14
12
  <a href="https://www.npmjs.com/package/vizmatic"><img src="https://img.shields.io/npm/v/vizmatic?color=%2334d058" alt="npm version" /></a>
13
+ <a href="https://github.com/bvolpato/vizmatic/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License: MIT" /></a>
15
14
  </p>
16
15
 
17
16
  <p align="center">
18
- <img src="https://bvolpato.github.io/vizmatic/assets/examples/animated-pipeline_dark.gif" alt="Vizmatic animated render pipeline" width="760" />
17
+ <a href="https://bvolpato.github.io/vizmatic/films.html"><img src="https://bvolpato.github.io/vizmatic/assets/films/fourier-epicycles.png" alt="A still from a Vizmatic film: rotating circles trace a curve" width="820" /></a>
19
18
  </p>
20
19
 
21
20
  <p align="center">
22
- <a href="https://bvolpato.github.io/vizmatic/">Website</a> ·
23
- <a href="https://bvolpato.github.io/vizmatic/playground.html">Playground</a> ·
21
+ <a href="https://bvolpato.github.io/vizmatic/films.html">Films</a> ·
22
+ <a href="https://bvolpato.github.io/vizmatic/docs/">Docs</a> ·
23
+ <a href="https://bvolpato.github.io/vizmatic/studio.html">Studio</a> ·
24
24
  <a href="https://bvolpato.github.io/vizmatic/components.html">Components</a> ·
25
- <a href="https://bvolpato.github.io/vizmatic/agents.html">For agents</a> ·
26
- <a href="examples">Examples</a> ·
27
- <a href="PROMPT.md">Agent Prompt</a> ·
28
- <a href="#api">API</a>
25
+ <a href="https://bvolpato.github.io/vizmatic/agents.html">For agents</a>
29
26
  </p>
30
27
 
31
- ---
32
-
33
- ## Quick start
34
-
35
- Vizmatic requires Node.js 20 or newer. Install its CLI:
36
-
37
- ```bash
38
- npm install -g vizmatic
39
- ```
40
-
41
- Create `frame.tsx`:
42
-
43
- ```tsx
44
- <Scene title="Agent visual pipeline">
45
- <Flow
46
- stages={[
47
- { title: "Prompt", subtitle: "intent", tone: "blue" },
48
- { title: "Scene spec", subtitle: "typed structure", tone: "purple" },
49
- { title: "PNG / SVG / GIF", subtitle: "files", tone: "green" },
50
- ]}
51
- />
52
- </Scene>
53
- ```
54
-
55
- `Scene` title and subtitle are optional. Omit both when surrounding copy already names the visual.
56
-
57
- Render it directly:
58
-
59
- ```bash
60
- vizmatic ./frame.tsx --out ./dist/frames --theme dark,light
61
- ```
62
-
63
- Check both themes before publishing. `--json` reports overflow, contrast, small text, overlapping labels, uneven panel whitespace, connector congestion, asset failures, and suggested dimensions:
64
-
65
- ```bash
66
- vizmatic check ./frame.tsx --theme dark,light --json
67
- ```
68
-
69
- PNG and SVG renders have transparent backgrounds by default. Add `--background theme` for an opaque dark or light canvas:
70
-
71
- ```bash
72
- vizmatic ./frame.tsx --out ./dist/frames --theme dark,light --background theme
73
- ```
74
-
75
- CSS alpha colors stay semi-transparent in PNG and SVG output. Set the canvas background in the frame or pass a quoted CSS color to `--background`:
76
-
77
- ```tsx
78
- <Scene background="rgba(15, 23, 42, 0.5)">
79
- <CalloutCard title="Alpha background" detail="The host page remains visible through the canvas." />
80
- </Scene>
81
- ```
82
-
83
- ```bash
84
- vizmatic ./frame.tsx --background 'rgba(15, 23, 42, 0.5)'
85
- ```
86
-
87
- When a frame omits `width` or `height`, Vizmatic starts at `960x540` and grows that axis if content overflows. Set `autoSize = false` when dimensions must remain fixed and clipping should fail the render.
88
-
89
- Bare CLI frames do not need imports. Use a regular module when a frame needs helper code, data loading, other dependencies, animation, or direct renderer APIs.
28
+ ## A film in 15 lines
90
29
 
91
- Add Vizmatic to a project for scripts, editor types, or direct renderer APIs:
30
+ Vizmatic needs Node.js 20 or newer. MP4 export also needs [FFmpeg](https://ffmpeg.org/download.html).
92
31
 
93
32
  ```bash
94
- pnpm add vizmatic react
33
+ npm install vizmatic
95
34
  ```
96
35
 
97
- To use the current GitHub version:
98
-
99
- ```bash
100
- pnpm add github:bvolpato/vizmatic react
101
- ```
102
-
103
- ## Agent skill
104
-
105
- Install the Vizmatic skill for Codex, Claude Code, Cursor, OpenCode, or another compatible agent:
106
-
107
- ```bash
108
- npx skills add bvolpato/vizmatic --skill vizmatic -g -y
109
- ```
110
-
111
- Choose agents explicitly when needed:
112
-
113
- ```bash
114
- npx skills add bvolpato/vizmatic --skill vizmatic -g -a codex -a claude-code -a cursor -a opencode -y
115
- ```
116
-
117
- Example prompts:
118
-
119
- ```text
120
- Use the Vizmatic skill to create a theme-aware architecture diagram and render dark/light PNG files.
121
- Use the Vizmatic skill to turn this release workflow into an animated GIF for docs.
122
- ```
123
-
124
- Skill source lives in [`.agents/skills/vizmatic`](.agents/skills/vizmatic). Review it before installing with `npx skills add bvolpato/vizmatic --list`.
125
-
126
- The [agent guide](https://bvolpato.github.io/vizmatic/agents.html) explains installation and the check/render workflow. Agents can discover instructions through [llms.txt](https://bvolpato.github.io/vizmatic/llms.txt), load the [full context bundle](https://bvolpato.github.io/vizmatic/llms-full.txt), or read [runnable component examples as JSON](https://bvolpato.github.io/vizmatic/components.json).
127
-
128
- Codex and Claude Code can also install Vizmatic as a plugin:
129
-
130
- ```bash
131
- codex plugin marketplace add bvolpato/vizmatic --ref main
132
- codex plugin add vizmatic@vizmatic
133
- ```
134
-
135
- ```bash
136
- claude plugin marketplace add bvolpato/vizmatic
137
- claude plugin install vizmatic@vizmatic --scope user
138
- ```
139
-
140
- ## Rendering options
141
-
142
- Add a text or image watermark when output needs branding:
143
-
144
- ```bash
145
- vizmatic ./frame.tsx --out ./dist/frames --theme dark,light --watermark "Acme" --watermark-image ./logo.svg
146
- ```
147
-
148
- Each output directory includes `manifest.json`. `outputs` lists generated files, and `outputDetails` records theme, path, and pixel dimensions.
149
-
150
- Static CLI renders default to PNG. Use `--format svg` for vector output or `--format both` to export PNG and SVG together. Each manifest output detail includes its `format`; both formats support themes, backgrounds, watermarks, cropping, and automatic canvas growth.
151
-
152
- ```bash
153
- vizmatic ./frame.tsx --out ./visuals --theme dark,light --format both
154
- ```
155
-
156
- Render an animation:
157
-
158
- ```bash
159
- vizmatic gif ./animated-frame.tsx --out ./dist/frames --theme dark,light --fps 20 --watermark "Acme" --watermark-image ./logo.svg
160
- ```
161
-
162
- Or call the renderer directly:
36
+ Create `intro.ts`:
163
37
 
164
38
  ```ts
165
- import { renderToPng } from "vizmatic"
166
- import { create, width, height } from "./frame"
167
-
168
- await renderToPng(create("dark"), {
169
- width,
170
- height,
171
- outputPath: "dist/agent-pipeline.png",
172
- background: "theme", // omit for alpha-transparent output
173
- watermark: { text: "Acme", image: "data:image/svg+xml;base64,...", position: "top-right" },
39
+ import { axes, draw, fadeIn, film, tex, write } from 'vizmatic/stage'
40
+
41
+ export default film({ title: 'My first film' }, (s) => {
42
+ const plot = s.add(axes({ x: [-3, 3], y: [-1, 9], grid: true }).at(-240, 40))
43
+ s.play(draw(plot.grid, { lag: 0.02 }), draw(plot.lines), fadeIn(plot.numbers))
44
+ s.play(draw(plot.plot((x) => x * x, { stroke: 'blue', width: 5 })))
45
+ s.play(write(s.add(tex('y = x^2', { size: 72 }).at(600, -200))))
46
+ s.wait(1)
174
47
  })
175
48
  ```
176
49
 
177
- Frames can export their own watermark:
178
-
179
- ```tsx
180
- import { Watermark } from "vizmatic"
181
-
182
- export const watermark = (
183
- <Watermark position="bottom-right" opacity={0.82}>
184
- <div style={{ display: "flex", alignItems: "center", gap: 6, color: "#7c3aed", fontWeight: 800 }}>
185
- <img src="data:image/svg+xml;base64,..." width={14} height={14} />
186
- Acme
187
- </div>
188
- </Watermark>
189
- )
190
- ```
191
-
192
- ## What Vizmatic handles
193
-
194
- Coding agents can write a small component tree more reliably than raw SVG paths and hand-tuned coordinates.
195
-
196
- Vizmatic provides reusable layout, diagram, and chart primitives:
197
-
198
- | Need | Vizmatic answer |
199
- |---|---|
200
- | More than flowcharts | Charts, cards, matrices, timelines, trees, icons, and custom composition |
201
- | Editable output | Source-controlled TSX stays inspectable and renders consistently |
202
- | Headless rendering | Node produces assets directly in local workflows and CI |
203
- | Theme variants | One command renders dark and light output from semantic color tokens |
204
- | Layout checks | Overflow, contrast, small text, label overlap, uneven panel whitespace, and connector congestion |
205
- | Animation | Typed state timelines, tweens, easing, holds, keyframes, and parallel tracks export as GIFs |
206
-
207
- ## Gallery
208
-
209
- <p>
210
- <img src="https://bvolpato.github.io/vizmatic/assets/examples/animated-pipeline_dark.gif" alt="Animated pipeline" width="380" />
211
- <img src="https://bvolpato.github.io/vizmatic/assets/examples/nccl-broadcast_dark.gif" alt="Animated NCCL Broadcast: root rank sends one buffer to every rank" width="300" />
212
- <img src="https://bvolpato.github.io/vizmatic/assets/examples/nccl-all-reduce_dark.gif" alt="Animated NCCL AllReduce: every rank reduces values and receives the sum" width="300" />
213
- </p>
214
- <p>
215
- <img src="https://bvolpato.github.io/vizmatic/assets/examples/nccl-all-gather_dark.gif" alt="Animated NCCL AllGather: every rank receives concatenated tensors" width="300" />
216
- <img src="https://bvolpato.github.io/vizmatic/assets/examples/nccl-reduce-scatter_dark.gif" alt="Animated NCCL ReduceScatter: each rank receives one reduced chunk" width="300" />
217
- <img src="https://bvolpato.github.io/vizmatic/assets/examples/nccl-all-to-all_dark.gif" alt="Animated NCCL AllToAll: every rank exchanges one chunk with every rank" width="300" />
218
- </p>
219
- <p>
220
- <picture><source media="(prefers-color-scheme: dark)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/rag-graph_dark.png" /><source media="(prefers-color-scheme: light)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/rag-graph_light.png" /><img src="https://bvolpato.github.io/vizmatic/assets/examples/rag-graph_light.png" alt="RAG graph" width="380" /></picture>
221
- <picture><source media="(prefers-color-scheme: dark)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/eval-dashboard_dark.png" /><source media="(prefers-color-scheme: light)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/eval-dashboard_light.png" /><img src="https://bvolpato.github.io/vizmatic/assets/examples/eval-dashboard_light.png" alt="Evaluation dashboard" width="380" /></picture>
222
- </p>
223
- <p>
224
- <picture><source media="(prefers-color-scheme: dark)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/token-matrix_dark.png" /><source media="(prefers-color-scheme: light)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/token-matrix_light.png" /><img src="https://bvolpato.github.io/vizmatic/assets/examples/token-matrix_light.png" alt="Token matrix" width="380" /></picture>
225
- <picture><source media="(prefers-color-scheme: dark)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/theme-system_dark.png" /><source media="(prefers-color-scheme: light)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/theme-system_light.png" /><img src="https://bvolpato.github.io/vizmatic/assets/examples/theme-system_light.png" alt="Theme system" width="380" /></picture>
226
- </p>
227
- <p>
228
- <picture><source media="(prefers-color-scheme: dark)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/system-architecture_dark.png" /><source media="(prefers-color-scheme: light)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/system-architecture_light.png" /><img src="https://bvolpato.github.io/vizmatic/assets/examples/system-architecture_light.png" alt="System architecture" width="380" /></picture>
229
- <picture><source media="(prefers-color-scheme: dark)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/presentation-frame_dark.png" /><source media="(prefers-color-scheme: light)" srcset="https://bvolpato.github.io/vizmatic/assets/examples/presentation-frame_light.png" /><img src="https://bvolpato.github.io/vizmatic/assets/examples/presentation-frame_light.png" alt="Presentation frame" width="380" /></picture>
230
- </p>
231
-
232
- NCCL gallery examples cover five operations: Broadcast, AllReduce, AllGather, ReduceScatter, and AllToAll. Their diagrams follow NVIDIA's documented [collective operation semantics](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/collectives.html): rooted transfer, reduction, rank-ordered gathering, reduced chunk ownership, and pairwise exchange.
233
-
234
- More examples live in [`examples/`](examples). Browse the searchable [component catalog on the homepage](https://bvolpato.github.io/vizmatic/#component-browser), copy a focused example, or open it in the playground to edit and render both themes. The [full catalog](https://bvolpato.github.io/vizmatic/components.html) also includes category previews and source. [`PROMPT.md`](PROMPT.md) contains the full install, syntax, component, and verification reference for coding agents. [`ROADMAP.md`](ROADMAP.md) tracks the next C4, provider pack, UML, layout, and interoperability capabilities.
235
-
236
- ## Repository checks
237
-
238
- Generated examples and website files are committed. CI fails when a build changes them without a matching source update.
239
-
240
- | Gate | What it protects |
241
- |---|---|
242
- | `pnpm lint` | TypeScript coverage plus GitHub Actions validation with actionlint |
243
- | `pnpm test` | Render pipeline behavior, watermark options, and output validation |
244
- | `pnpm render:examples` | Dark/light PNGs, animated GIFs, source snippets, and website HTML |
245
- | `pnpm check:examples` | Every example renders in both themes without errors or visual warnings |
246
- | `pnpm docs:check` | Local asset references, `PROMPT.md` sync, source modal themes, and homepage affordances |
247
- | `pnpm deps:check` | npm audit plus package tarball contents, size, and file-count budgets before release |
248
- | `./test.sh` drift check | Confirms render and docs commands leave no uncommitted output |
249
-
250
- Run the full local gate:
251
-
252
- ```bash
253
- ./test.sh
254
- ```
255
-
256
- ## Runtime assets
257
-
258
- Vizmatic uses `react` for JSX frames, `satori` for layout, `@resvg/resvg-js` for PNG output, `gifenc` for GIFs, and `tsx` to load frame files.
259
-
260
- Published packages include Inter, JetBrains Mono, Noto Sans, Noto Sans Math, and a compressed Twemoji bundle under `assets/`, so normal CLI rendering does not fetch them at runtime. Set `VIZMATIC_FONT_DIR` or `VIZMATIC_ASSET_DIR` to use other local assets. Set `VIZMATIC_DISABLE_NETWORK=1` or `VIZMATIC_OFFLINE=1` to disable public fallbacks.
261
-
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
-
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.
50
+ Then watch it, check it, and export it:
269
51
 
270
52
  ```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' })
53
+ npx vizmatic preview intro.ts # live player with a timeline. Reloads when you save.
54
+ npx vizmatic check intro.ts # finds clipped text, overlaps, and strokes through labels
55
+ npx vizmatic film intro.ts --out dist # 1080p60 MP4
295
56
  ```
296
57
 
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
-
362
- ## API
363
-
364
- ### Themes
365
-
366
- ```ts
367
- import { getThemeColors, getToneFill } from "vizmatic"
368
-
369
- const dark = getThemeColors("dark")
370
- const light = getThemeColors("light")
371
- const engineering = getThemeColors("light", "engineering")
372
- const engineeringNodeFill = getToneFill("purple", engineering)
373
- ```
374
-
375
- Primitives receive `c`, the resolved theme object, for colors and typography.
376
-
377
- Bare frames select the same style with `preset = "engineering";`. Full modules pass the preset as the second argument to `getThemeColors`.
378
-
379
- ### Component catalog
58
+ `npx vizmatic new intro --template architecture` starts from a working film. The templates are `explainer`, `equation`, `architecture`, `chart`, and `deck`.
380
59
 
381
- Use these primitives before writing raw SVG or absolute-positioned layouts.
60
+ ## What makes it different
382
61
 
383
- #### Frame and layout
62
+ **Everything on stage is real geometry.** Lines, glyphs, equations, and grids are all Bezier paths. Any shape can trace itself, morph into any other shape, or bend through a function. Equations use TeX glyphs, and `morphMatching` moves the shared terms from one line of a derivation to the next.
384
63
 
385
- | Component | Use |
386
- |---|---|
387
- | `defineIllustration` | Wraps a theme-aware frame builder and exports `create(theme)` plus a default element. |
388
- | `Canvas` | Low-level full-frame root with alpha-transparent default background, optional background fill, padding, and vertical alignment. |
389
- | `Board` | Fixed canvas for freely positioned components, with explicit dimensions and an optional background. |
390
- | `CanvasItem` | Positions and sizes a component at logical-pixel `x` / `y` coordinates. Charts fit their complete plotting layers, labels, and frame inside the item. |
391
- | `Scene` | Standard frame wrapper with optional title/subtitle, content column, and theme-aware typography. |
392
- | `TitleBar` | Shared title/subtitle block used by `Scene`. |
393
- | `Row` / `Column` | Flex layout primitives with gap, alignment, wrapping, width, and height props. |
394
- | `Stack` | Layered vertical stack for repeated cards, tokens, or processing layers. |
395
-
396
- Use `Board` with `CanvasItem` for layouts that people can move and resize in the browser builder. Coordinates and sizes remain in the TSX source. Set the frame dimensions to match the board; the board clips content outside its bounds. With both item dimensions set, chart primitives scale proportionally to fit the complete chart, including wrapped headings, legends, and footers.
397
-
398
- ```tsx
399
- width = 960;
400
- height = 540;
401
-
402
- <Board width={960} height={540}>
403
- <CanvasItem x={40} y={40} width={280} height={160}>
404
- <MetricCard label="Requests" value="1,240" tone="green" />
405
- </CanvasItem>
406
- <CanvasItem x={360} y={40} width={540} height={340}>
407
- <PieChart title="Requests by outcome" format="integer" segments={[
408
- { label: "Successful", value: 82, color: "positive" },
409
- { label: "Retried", value: 18, color: "warning" },
410
- ]} />
411
- </CanvasItem>
412
- </Board>
413
- ```
64
+ **A film is a pure function of time.** The build function runs once and writes a timeline. Any frame can then be sampled at any time, in any order. Scrubbing is instant, and identical input gives identical frames.
414
65
 
415
- #### Surfaces, labels, and cards
66
+ **One film, two destinations.** The same source paints live on a canvas with `<vz-film>`, and renders to MP4, WebM, GIF, PNG, or SVG in Node. Frames rasterize on worker threads, with real motion blur and bloom when you ask for them.
416
67
 
417
- | Component | Use |
418
- |---|---|
419
- | `Panel` | Titled card surface with tone strip, subtitle, footer, shadow, and body controls. |
420
- | `Card` | Flexible surface for custom content without a forced title. |
421
- | `StepCard` | Compact stage card for flows, choices, and process steps. |
422
- | `MetricCard` | KPI/value card with label, value, detail, tone, and monospace value support. |
423
- | `CalloutCard` | Highlight block for takeaways, warnings, decisions, and summaries. |
424
- | `WindowFrame` | Browser/terminal-style framed panel for code, UI, or tool output. |
425
- | `Box` | Gradient or outlined labeled rectangle with optional icon and sublabel. |
426
- | `Tile` / `TileGrid` | Uniform repeated tiles with tone, title, detail, and metric layouts. |
427
- | `Badge` / `BadgePill` | Small labels for status, categories, and annotations. |
428
- | `ValuePill` | Compact value badge for numbers or short state labels. |
429
- | `GradientChip` | Small colored chip with gradient fill for legends and tone keys. |
430
- | `ToneStrip` | Small semantic accent strip for visual grouping. |
431
- | `Icon` | Curated SVG icon set for cards, callouts, compact rows, and presentation frames. |
432
- | `TextLabel` | Wrapping-safe text with variant, color, math formatting, width, and alignment. |
433
- | `MathText` / `formatMathText` | Converts simple `x_i` / `x^2` style strings into readable unicode math text. |
434
- | `SvgMathText` | Positioned HTML overlay for math labels aligned to custom plot coordinates. Place it beside, not inside, raw SVG geometry in a relative container. |
68
+ **It looks right by default.** Five looks set the background, ink, pigments, and light. Authors write `color: 'yellow'`, so one film renders in `midnight`, `paper`, `blueprint`, `chalk`, and `neon`.
435
69
 
436
- #### Arrows, connectors, and SVG helpers
70
+ **Figures pack information.** The TSX components default to the `dense` density: small type, hairlines, and tight gutters, like a figure in a good engineering paper. Set `density="presentation"` to use the same source on a slide.
437
71
 
438
- | Component | Use |
439
- |---|---|
440
- | `Arrow` | Simple directional arrow element. |
441
- | `FlowArrow` / `Connector` | Theme-aware connector between flow stages. |
442
- | `VectorArrow` | SVG vector arrow for coordinate-style diagrams. |
443
- | `VectorSegment` | Labeled segment/vector primitive for geometry and embedding visuals. |
444
- | `SvgFrame` | SVG container with theme-aware background and border. |
445
- | `SvgPoint` / `DotPoint` | Point markers with optional labels. |
446
- | `ArrowMarkerDef` | SVG arrowhead marker definition for custom line charts and graph edges. |
447
- | `DashedLine` | Dotted/dashed SVG line helper. |
448
- | `Legend` | Reusable legend block with colored items and optional title. |
72
+ **Defects come back as data.** `vizmatic check --json` reports problems with their times and bounding boxes, so a coding agent can find and fix them without watching anything.
449
73
 
450
- #### Lists, comparisons, and status blocks
451
-
452
- | Component | Use |
453
- |---|---|
454
- | `DetailList` | Compact repeated detail rows inside panels and flow stages. |
455
- | `ProgressRow` / `ProgressList` | Progress bars with labels, values, tones, and optional math text. |
456
- | `StatusRow` / `StatusList` | Check, cross, warning, info, pending, and dot rows. |
457
- | `Timeline` | Vertical or horizontal milestone list with tone markers, time labels, and compact event cards. |
458
- | `KeyValueList` | Structured label/value rows for configs and metadata. |
459
- | `CodeBlock` | Themed code panel with highlighted lines and optional annotations. |
460
- | `EquationCard` | Formula card with title, equation, and supporting detail. |
461
- | `Comparison` | Side-by-side comparison panel with two titled sides and detail rows. |
74
+ ## Figures
462
75
 
463
- #### Flows, pipelines, and graph diagrams
464
-
465
- | Component | Use |
466
- |---|---|
467
- | `Flow` | Horizontal or vertical staged process diagram with optional detail rows. |
468
- | `Pipeline` | Process pipeline with stage labels and a shared title. |
469
- | `LayeredNetwork` | Neural-network/DAG diagram with layers, nodes, active path, annotations, and formula. |
470
- | `GraphDiagram` | Auto-laid architecture graph with nested boundaries, technical icons, typed relationships, and custom icon definitions. |
471
- | `TreeDiagram` | Auto-laid parent/child hierarchy for ownership, routing, taxonomy, and decision trees. |
472
- | `SequenceDiagram` | Participants, lifelines, activations, notes, sync/async/return messages, and control fragments. |
473
- | `DataflowDiagram` | Schema-aware source, transform, store, and sink lineage with batch or streaming edges. |
474
- | `DeploymentDiagram` | Nested infrastructure boundaries with workload kinds, ports, protocols, and trust direction. |
475
- | `TransformerTopology` | Transformer blocks, tensor shapes, repeated layers, residual paths, caches, experts, and collectives. |
476
-
477
- `GraphDiagram` uses deterministic layered layout when node coordinates are omitted. Groups become nested system boundaries, while built-in technical icons keep common architecture nodes concise:
76
+ Render a TSX figure in each theme:
478
77
 
479
78
  ```tsx
480
- <GraphDiagram
481
- ariaLabel="Checkout architecture"
482
- groups={[
483
- { id: "prod", label: "Production", tone: "blue" },
484
- { id: "data", label: "Data", parent: "prod", tone: "green" },
485
- ]}
486
- nodes={[
487
- { id: "client", label: "Client", icon: "browser", tone: "cyan" },
488
- { id: "api", label: "API", icon: "server", group: "prod", tone: "purple" },
489
- { id: "db", label: "Postgres", icon: "database", group: "data", tone: "green" },
490
- ]}
491
- edges={[
492
- { from: "client", to: "api", label: "HTTPS", kind: "sync" },
493
- { from: "api", to: "db", label: "SQL", kind: "data", arrow: "both" },
494
- ]}
495
- />
496
- ```
497
-
498
- Groups support unlimited nesting in automatic layout, reserve a boundary-header gutter, and clip long headers inside the boundary. Set `icon` to a built-in `IconName`, a React element, or a reusable icon from `defineDiagramIcon`; `defineIconRegistry` groups provider packs without a runtime registry. Icon size stays inside its node. Custom React elements own their theme colors and accessible label. Relationship `kind` selects solid, dashed, or dotted defaults, `style` overrides them, and `arrow` accepts `forward`, `backward`, `both`, or `none`. Associations default to no arrow.
499
-
500
- Set `id`, `title`, and `description` for accessible SVG exports. Nodes and edges accept safe `href` links and tooltip `title` text. These semantics are included by `renderToSvg` and the playground SVG download; see the [SVG accessibility guide](docs/accessibility.md) for supported links and stable ID behavior.
501
-
502
- Set `x` and `y` on every node for normalized manual positioning when no groups are present. Mixed coordinate modes fail with a clear error. Automatic layout treats node and edge array order as its stable tie-breaker and expands `width` or `height` when needed. Set `sizing="fixed"` to keep exact graph dimensions and let overflow checks report a canvas that is too small. Use `direction`, `nodeGap`, `rankGap`, and `edgeGap` to tune the result.
503
-
504
- Connector routing is separate from node layout. The default `routing="dagre"` preserves existing geometry. Choose `routing="straight"` for direct connectors or `routing="orthogonal"` for right-angle routes that avoid node boxes and group headers. `routingClearance` defaults to 12 logical pixels; `edgeGap` separates parallel traffic. Orthogonal routing supports automatic and manual node positions, self-loops with distinct anchors, and separated parallel routes.
505
-
506
- Declare node `ports` as `{ id, side, offset? }`, then reference them with edge `fromPort` / `toPort`. Sides are `top`, `right`, `bottom`, or `left`; offsets run from 0 to 1 along the side and default to 0.5. An edge can instead specify `fromSide` / `toSide`. Use either a port reference or a side for each endpoint. Explicit anchors also opt an edge into orthogonal geometry when the routing mode is Dagre. With explicit straight or orthogonal routing, `DeploymentDiagram` anchors declared port references and accepts port `side` / `offset` overrides.
507
-
508
- Routing runs synchronously offline with limits of 64 node/header obstacles and 256 edges, plus bounded grid and search work. A blocked route, repeated route with no separate lane, or exhausted limit omits the affected connector and makes the checker report `layout.connector_unroutable` as an error. Increase spacing or canvas size, change anchors, or reduce clearance before publishing. Missing port references fail validation. See the [routed graph example](examples/orthogonal-routing.tsx).
509
-
510
- The [import guide](docs/import.md) documents the supported Mermaid and D2 subsets and their structured source diagnostics.
511
-
512
- #### Matrices, tables, and grids
513
-
514
- | Component | Use |
515
- |---|---|
516
- | `Matrix` | Numeric matrix visualization for linear algebra and attention examples. |
517
- | `Heatmap` | Color-scaled matrix/attention heatmap. |
518
- | `TiledMatrix` | Matrix with region labels and grouped tiles. |
519
- | `DataTable` | Compact text table with header rows/columns and monospace cells. |
520
- | `Grid` | General-purpose cell grid with per-cell label, tone, color, border, and opacity. |
521
-
522
- #### Charts and plots
523
-
524
- | Component | Use |
525
- |---|---|
526
- | `ChartFrame` | Shared chart wrapper with title, subtitle, footer, and theme-aware shell. |
527
- | `AxisPlot` | Low-level axis plot for custom lines, paths, and plotted values. |
528
- | `PieChart` | Full-circle part-to-whole chart with segment values, percentages, and a legend. |
529
- | `DonutChart` | Part-to-whole chart with center label/value, segment labels, and shared chart styling. |
530
- | `MiniBarChart` | Small bar chart for cards and dashboards. |
531
- | `StackedBar` | Segmented horizontal bar with labels and percentages. |
532
- | `BarChart` | Full bar chart with ticks, labels, values, grids, and formats. |
533
- | `LineChart` | Multi-series line chart with optional area fill, points, labels, and grid. |
534
- | `ScatterPlot` | Labeled scatter plot with axes, ticks, point sizing, and collision-aware labels. |
535
- | `ParetoBarChart` | Categories sorted by descending count with a cumulative percentage line and separate count/share axes. |
536
- | `ParetoChart` | Automatic non-dominated frontier for competing objectives, including log-scaled cost axes. |
537
- | `QuadrantChart` | 2x2 decision matrix with numeric axes, configurable thresholds, labeled points, and optional region emphasis. |
538
- | `IntervalPlot` | Timeline/range plot for spans, phases, latencies, and schedules. |
539
-
540
- Use `PieChart` for category shares, `BarChart` for category values, `ScatterPlot` for paired numeric observations, and `ParetoBarChart` to identify the categories behind most of a total. Pie and Pareto bar values must be finite and non-negative; zero-valued pie slices are omitted. Pareto bars sort descending without changing the input array and preserve input order for equal values. The cumulative line reaches 100% when the total is positive. See the [pie](examples/pie-chart.tsx) and [Pareto bar](examples/pareto-bar-chart.tsx) examples.
541
-
542
- `ParetoChart` shows a non-dominated scatter frontier for competing objectives. It defaults to minimizing x and maximizing y, which fits cost-versus-score comparisons. Set `xObjective` or `yObjective` for other tradeoffs. Non-positive x values are omitted on a logarithmic x-axis. `QuadrantChart` accepts raw numeric domains, threshold values, tick formats, and optional grid lines; omit them to keep normalized 0-1 coordinates and centered splits. Regions accept `emphasis: true` to give one decision region a stronger fill and border.
543
-
544
- #### Rendering and verification
545
-
546
- | API | Use |
547
- |---|---|
548
- | `checkFrame` | Check a React scene or themed frame and return typed diagnostics with configurable severity-based pass/fail. |
549
- | `renderToPng` | Render React scene to PNG through Satori and resvg, with optional watermark, crop, scale, and overflow check. |
550
- | `renderToPngWithOutput` | Render PNG and return logical dimensions, physical pixel dimensions, and painted `contentBounds`. |
551
- | `CanvasOverflowError` | Typed clipping failure with canvas dimensions and per-edge overflow details. |
552
- | `renderAnimatedGif` | Render ordered `AnimatedScene[]` states to GIF with `fade`, `appear`, or no transition. |
553
- | `renderAnimatedGifWithOutput` | Render GIF and return dimensions, timing, encoded-frame, delta-frame, and byte metrics. |
554
- | `defineAnimation` | Define a typed state timeline rendered at deterministic sample times. |
555
- | `hold`, `tween`, `keyframe`, `parallel` | Compose sequential pauses, eased property transitions, instant state changes, and staggered concurrent tracks. |
556
- | `sampleAnimation` | Evaluate timeline state at an exact millisecond without rendering. |
557
- | `analyzeAnimationCadence` | Inspect sampled frame count, target interval, encoded duration, and delay range. |
558
- | `renderAnimationGif` | Stream sampled timeline frames into a GIF without retaining every RGBA frame. |
559
- | `renderToBuffer` | Render PNG to memory for tests and pipelines. |
560
- | `renderToSvg` | Render SVG markup directly. |
561
- | `Watermark` | JSX marker component for expressive frame-module watermarks. |
562
- | `wrapWithWatermark` | Add optional watermark text, image/icon, custom element, and position to a frame. |
563
- | `normalizeWatermark` | Normalize boolean, string, object, or React-element watermark input to `WatermarkOptions`. |
564
- | `wrapWithBrand` | Compatibility wrapper for adding a text watermark through `wrapWithWatermark`. |
565
- | `getFonts` | Load and cache bundled Satori font data for advanced renderer integrations. |
566
- | `loadAdditionalAsset` | Resolve Satori missing-glyph requests, including bundled or cached Twemoji assets. |
567
- | `detectBackgroundColor` | Find dominant transparent/background color for cropping. |
568
- | `detectContentBounds` | Compute non-background bounds for autocrop. |
569
- | `cropPixels` | Crop raw pixel buffers. |
570
- | `detectOverflow` | Fail frames that clip content at canvas edges. |
571
-
572
- Theme and chart helpers are public for custom primitives: `getReadableColor(name, c)` selects the highest-contrast semantic variant, `getReadableToneColor(tone, c, background?)` adapts tone text to a background, and `getReadableTextColor(background, c)` chooses a foreground meeting 4.5:1 contrast when possible. `createPlotArea(width, height, margin)` returns clamped chart geometry for custom axes and marks.
573
-
574
- ### Programmatic checking
575
-
576
- Use `checkFrame` when a build, editor, or agent already has a React scene in memory. Pass `scene` for one fixed element or `create(theme)` for theme-specific elements:
577
-
578
- ```tsx
579
- import { CalloutCard, Scene, checkFrame, getThemeColors } from "vizmatic"
580
-
581
- const report = await checkFrame({
582
- source: "agent-pipeline",
583
- width: 640,
584
- height: 360,
585
- create(theme) {
586
- const c = getThemeColors(theme)
587
- return (
588
- <Scene c={c}>
589
- <CalloutCard c={c} title="Ready" detail="Checked in-process" tone="green" />
590
- </Scene>
591
- )
592
- },
593
- }, {
594
- themes: ["dark", "light"],
595
- background: "theme",
596
- failOn: "warning",
597
- })
598
-
599
- if (!report.ok) throw new Error(`Visual check failed: ${report.summary.errors} errors`)
600
- ```
601
-
602
- `failOn` accepts `"error"` (the default), `"warning"`, `"info"`, or `"never"`. `report.ok` means the diagnostics pass that policy; `report.rendered` means every requested theme completed rendering. Each theme report includes resolved and output dimensions, stable diagnostic codes, and severity counts. Diagnostics expose `elementId`, related IDs, and a `location` path or rendered bounds when available. Import `CHECK_DIAGNOSTIC_CODES`, `CheckDiagnostic`, `CheckFrameInput`, and `CheckFrameReport` for typed integrations. Use `vizmatic check ... --json` when the checker should discover and load frame files itself.
603
-
604
- ### Rendering
605
-
606
- ```ts
607
- import { renderAnimatedGif, renderAnimationGif, renderToPng, renderToBuffer, renderToSvg } from "vizmatic"
608
- ```
609
-
610
- `renderToPng` renders at 2x scale, checks for clipping, and crops extra whitespace while keeping 24 source pixels around detected content. Output stays transparent unless `background` is set.
611
-
612
- Use `background: "theme"` to paint `c.bg`, or pass a CSS color. Use `crop: "height"` to keep canvas width while trimming vertical whitespace. `watermark.image` accepts a URL or data URI; CLI flag `--watermark-image` also accepts a local path. A frame module can export `watermark = <Watermark>...</Watermark>`. `brand` remains a compatibility alias.
613
-
614
- ```ts
615
- await renderToPng(element, {
616
- width: 1040,
617
- height: 560,
618
- outputPath: "dist/frame.png",
619
- background: "theme",
620
- theme: "dark",
621
- watermark: { text: "Your Product", image: "https://example.com/logo.svg", position: "top-right" },
622
- crop: "height",
623
- scale: 2,
624
- })
625
- ```
626
-
627
- Frame modules can export watermark config directly:
628
-
629
- ```tsx
630
- import { Watermark } from "vizmatic"
631
-
632
- export const watermark = (
633
- <Watermark position="bottom-right">
634
- <div style={{ color: "#7c3aed", fontFamily: "Inter", fontWeight: 800 }}>
635
- Acme Research
636
- </div>
637
- </Watermark>
638
- )
639
- ```
640
-
641
- Prefer `defineAnimation` when values should move, resize, or fade continuously. Timeline array runs sequentially; every property in one `tween` moves in parallel. `parallel` adds independent property tracks for staggered or overlapping motion. Renderer samples exact cadence boundaries plus terminal state, checks every rendered frame for overflow, coalesces unchanged frames, and delta-encodes changed rectangles on opaque GIFs. Infinite loops should end on same visual state where they begin. Fade moving content out and reset it with a `keyframe` while hidden instead of reversing a one-way operation. Keep `create(theme)` as static fallback for PNG, docs previews, and reduced-motion users.
642
-
643
- ```tsx
644
- import { defineAnimation, hold, keyframe, tween } from "vizmatic"
645
-
646
- export function createAnimation(theme: ThemeMode) {
647
- return defineAnimation({
648
- initial: { operation: 0, progress: 0 },
649
- timeline: [
650
- hold(500, "Broadcast input"),
651
- tween({ progress: 1 }, { duration: 900, easing: "ease-in-out", label: "Transfer" }),
652
- hold(500, "Broadcast output"),
653
- keyframe({ operation: 1, progress: 0 }),
654
- tween({ progress: 1 }, { duration: 900, easing: "ease-in-out", label: "AllReduce" }),
655
- ],
656
- fps: 20,
657
- render: (state, frame) => buildFrame(theme, state, frame),
658
- })
659
- }
660
- ```
661
-
662
- ```ts
663
- await renderAnimationGif(createAnimation("dark"), {
664
- width: 1040,
665
- height: 560,
666
- outputPath: "dist/collective.gif",
667
- watermark: { text: "Your Product", image: "data:image/png;base64,...", position: "bottom-right" },
668
- theme: "dark",
669
- scale: 1,
670
- })
671
- ```
672
-
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.
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
79
+ <Scene title="Checkout, read path">
80
+ <Flow
81
+ stages={[
82
+ { title: "Gateway", subtitle: "Envoy, p99 9 ms", tone: "blue" },
83
+ { title: "Cart", subtitle: "Go, 840 rps", tone: "purple" },
84
+ { title: "Orders DB", subtitle: "Postgres, primary + 3", tone: "green" },
85
+ ]}
86
+ />
87
+ </Scene>
682
88
  ```
683
89
 
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
90
  ```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
91
+ npx vizmatic ./frame.tsx --out ./figures --theme dark,light --format both
709
92
  ```
710
93
 
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).
94
+ Read [Diagrams and density](https://bvolpato.github.io/vizmatic/docs/diagrams.html) and the [figures reference](https://bvolpato.github.io/vizmatic/docs/figures.html), or browse the [component catalog](https://bvolpato.github.io/vizmatic/components.html).
717
95
 
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
- ```
96
+ ## For coding agents
731
97
 
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:
98
+ Install the skill. It teaches the engine, the object catalog, and the check workflow.
747
99
 
748
100
  ```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
- })
101
+ npx skills add bvolpato/vizmatic --skill vizmatic -g -y
795
102
  ```
796
103
 
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.
104
+ Agents can also read [`llms.txt`](https://bvolpato.github.io/vizmatic/llms.txt), and `vizmatic objects --json` and `vizmatic looks --json` list what the installed version offers.
829
105
 
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.
106
+ ## Documentation
836
107
 
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.
108
+ | Read this | For |
109
+ |---|---|
110
+ | [Getting started](https://bvolpato.github.io/vizmatic/docs/) | Your first film, in two minutes |
111
+ | [Core concepts](https://bvolpato.github.io/vizmatic/docs/concepts.html) | The stage, the timeline, and why frames are pure |
112
+ | [Objects](https://bvolpato.github.io/vizmatic/docs/objects.html) | Axes, planes, charts, graphs, code, and 3D |
113
+ | [CLI](https://bvolpato.github.io/vizmatic/docs/cli.html) and [Exporting](https://bvolpato.github.io/vizmatic/docs/exporting.html) | Every command, format, and quality level |
114
+ | [Embedding](https://bvolpato.github.io/vizmatic/docs/embedding.html) | A live, seekable film in any page |
115
+ | [Editable scenes](https://bvolpato.github.io/vizmatic/docs/editable-scenes.html) | Running untrusted TSX in a bounded sandbox |
116
+ | [TSX animation](https://bvolpato.github.io/vizmatic/docs/tsx-animation.html) | Animating an existing figure with typed timelines |
117
+ | [Science guide](SCIENCE.md) | Accurate diagrams for math, physics, chemistry, and machine learning |
118
+ | [Roadmap](ROADMAP.md) | What shipped and what comes next |
119
+ | [Contributing](CONTRIBUTING.md) | Setup, checks, and the release process |
120
+
121
+ ## Consumer security overrides
122
+
123
+ Vizmatic 0.6.0's MathJax tree resolves `speech-rule-engine`, which uses `@xmldom/xmldom`. Its Satori tree resolves `fflate`. Pin these patched transitive versions in a consuming project before you install Vizmatic.
124
+
125
+ For npm, add these root-level entries to `package.json`:
126
+
127
+ ```json
128
+ {
129
+ "overrides": {
130
+ "@xmldom/xmldom": "0.9.12",
131
+ "fflate": "0.7.5"
132
+ }
858
133
  }
859
134
  ```
860
135
 
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
-
1053
- ## Development
1054
-
1055
- See [`CONTRIBUTING.md`](CONTRIBUTING.md) for setup, testing, visual review, dependency updates, and pull request guidance.
1056
-
1057
- ```bash
1058
- pnpm install
1059
- pnpm verify
1060
- pnpm site:serve
1061
- ```
1062
-
1063
- The homepage, Components page, and Playground share a live component explorer. Choose a component to open its focused example, or use Add to scene to compose several components. Select an element to edit its literal props, add optional properties, duplicate or remove it, and move it within its group. Controls follow inline text and TSX edits. Computed props and expression-generated structure stay editable in the TSX. Preview framing and zoom preserve the full canvas in downloaded PNG and SVG files.
1064
-
1065
- Choose the Freeform canvas template for a positioned builder. Move and resize `CanvasItem` components through the preview handles, use grid snapping, or adjust their literal coordinates in the inspector. Arrow keys nudge a focused handle; Shift makes a larger move and Alt bypasses snapping. The layout remains ordinary `Board` / `CanvasItem` TSX.
1066
-
1067
- Structured data editors let you add, remove, and change pie segments, bar categories, scatter points, and table cells. Nested styles, arrays, and objects also have JSON editors. Invalid shapes and missing graph node references report an error before changing the source. Computed data remains editable in TSX.
1068
-
1069
- Open Canvas and palette to change the frame dimensions, style preset, and any theme color. Choose a transparent, theme, or custom CSS background. These settings are saved in the TSX and participate in undo, project files, share links, and exports. Bare CLI frames support the same metadata:
136
+ For pnpm 11, add these entries to the root `pnpm-workspace.yaml`. The CLI uses esbuild to compile films and frames, so allow its install script:
1070
137
 
1071
- ```tsx
1072
- width = 960;
1073
- height = 540;
1074
- preset = "default";
1075
- background = "#101827";
1076
- themeColors = {"primary":"#22c55e","primaryLight":"hsl(140, 70%, 65%)"};
1077
-
1078
- <Board width={960} height={540}>
1079
- <CanvasItem x={40} y={40} width={300} height={120}>
1080
- <CalloutCard title="Your palette" detail="Colors travel with the frame." />
1081
- </CanvasItem>
1082
- </Board>
138
+ ```yaml
139
+ overrides:
140
+ '@xmldom/xmldom': 0.9.12
141
+ fflate: 0.7.5
142
+ allowBuilds:
143
+ esbuild: true
1083
144
  ```
1084
145
 
1085
- Copy block copies the selected element as reusable bare TSX, including its setup and canvas settings. Inside a Board it keeps the enclosing CanvasItem and its geometry, so the copied block renders on its own. Ctrl/Command+C copies a block when its canvas handle is focused. Copy source copies the complete composition.
1086
-
1087
- Edits are saved locally in this browser and restore after reload. Component, shared-source, and gallery links open their own examples. Editing clears the original example or source bookmark so reload can recover your draft. Undo and redo cover source typing, controls, inline text, and scene operations, with up to 100 source snapshots for the current session. Use the buttons or Ctrl/Command+Z and Ctrl/Command+Shift+Z. Drafts do not sync between devices; use Save project to download a named `.vizmatic.json` file containing source, output theme, and canvas background, then Open project to restore it. Share and Copy source also let you move your TSX between tools.
1088
-
1089
- Double-click a text label in the preview to edit its literal TSX value. Press Enter or click outside to save, Shift+Enter for a new line, or Escape to cancel. Keyboard users can focus a label and press Enter or F2. Labels derived from computed expressions or ambiguous source values stay editable in the TSX editor.
1090
-
1091
- Choose the Animation scene template to play, pause, scrub time, and export a GIF in the browser. Bare animated source declares `animationDuration = 3` and optionally `animationFps = 10` before setup code. The injected `t` variable is time in seconds; Vizmatic timeline helpers continue to use milliseconds. Gallery timeline animations are adapted to the same browser workflow. Browser GIFs use an opaque canvas fill, with limits of 120 frames, 2 million pixels per frame, and 60 million pixels total. Static CLI render and check evaluate these snippets at `t=0`. Use a CLI animation module for larger animations or transparent GIF output.
1092
-
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.
1094
-
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.
1096
-
1097
- ## Publishing
1098
-
1099
- Prepare release commit locally, push it to protected `main`, and wait for required CI before pushing its tag:
1100
-
1101
- ```bash
1102
- npm version patch --no-git-tag-version
1103
- pnpm sync:plugin-versions
1104
- pnpm docs:check
1105
- git add package.json plugins/vizmatic/.codex-plugin/plugin.json plugins/vizmatic/.claude-plugin/plugin.json .claude-plugin/marketplace.json
1106
- git commit -m "Release v$(node -p "require('./package.json').version")"
1107
- git push origin main
1108
- # Push annotated vX.Y.Z tag only after CI passes on release commit.
1109
- ```
1110
-
1111
- Tag push starts GitHub `Release` workflow. It verifies exact commit again, publishes npm provenance, and creates release notes with compare link and commits since previous version. Retry existing tag with `gh workflow run release.yml --ref vX.Y.Z -f tag=vX.Y.Z`. Workflow requires `NPM_TOKEN` repository secret with publish access.
1112
-
1113
- The workflow keeps package version, plugin metadata, tag, release notes, and npm provenance in sync.
146
+ Then add Vizmatic with your package manager. The install updates the lockfile with these transitive pins.
1114
147
 
1115
148
  ## License
1116
149
 
1117
- MIT
150
+ MIT. Bundled fonts and other third-party assets keep their own licenses. See [`assets/THIRD_PARTY_LICENSES.md`](assets/THIRD_PARTY_LICENSES.md).