vizmatic 0.7.0 → 0.7.2

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
@@ -11,6 +11,8 @@ Vizmatic requires Node.js 20 or newer. MP4 and WebM also need FFmpeg.
11
11
  npm install vizmatic
12
12
  ```
13
13
 
14
+ For pnpm 11, allow esbuild's install script with `allowBuilds: { esbuild: true }` in the root `pnpm-workspace.yaml`.
15
+
14
16
  ## Films
15
17
 
16
18
  Start from a template, or write the function yourself. Templates are `explainer`, `equation`, `architecture`, `chart`, and `deck`.
@@ -51,6 +53,8 @@ Rules of the engine:
51
53
  - `s.play(...)` writes animation and moves time forward. `s.wait(seconds)` holds. `s.at(time, build)` authors at another time.
52
54
  - A `dynamic(() => ...)` drawing rebuilds on every frame. Read `value.value` inside it to drive anything.
53
55
  - `morph(a, b)` leaves `b` on stage and `a` hidden. Later code refers to `b`.
56
+ - A `duration` on `s.play` stretches every animation to fill it, and a `duration` inside one of those animations has no effect. For different lengths, leave it off `s.play`, set it on each animation, and use `delay` for an offset: `s.play(fadeOut(oldText, { duration: 0.15 }), delay(fadeIn(newText, { duration: 0.25 }), 0.1))`.
57
+ - Use `font: 'text-serif'` for sentences, labels, and numbers. Use `font: 'serif'` only for short titles at a large size.
54
58
  - Colors are look tokens such as `'blue'`, `'yellow'`, `'ink'`, and `'dim'`, so a film renders in every look.
55
59
  - Run `vizmatic objects` and `vizmatic looks` to see what the installed version offers.
56
60
 
@@ -64,7 +68,11 @@ npx vizmatic film intro.ts --frame 3,6.5,12 --width 1280 --out stills
64
68
  npx vizmatic film intro.ts --out dist/films --look midnight,paper --quality high
65
69
  ```
66
70
 
67
- `vizmatic check` samples the moments where the film comes to rest. It reports `film.off_canvas`, `film.text_overlap`, `film.text_crossed`, and `film.missing_glyph`, each with times, a `box` in canvas pixels, and a `stage` center in authoring coordinates. Fix every error, then open the stills and look at them. `vizmatic preview intro.ts` opens a live player with a timeline for a person to review.
71
+ `vizmatic check` samples the moments where the film comes to rest. It reports `film.off_canvas`, `film.text_overlap`, `film.text_crossed`, and `film.missing_glyph`, each with times, a `box` in canvas pixels, and a `stage` center in authoring coordinates. Fix every error, then open the stills and look at them. `vizmatic preview intro.ts` opens a live player with a timeline for a person to review. The [Studio](https://bvolpato.github.io/vizmatic/studio.html) is a visual film editor in the browser for a person who wants to edit by hand.
72
+
73
+ The check does not look at motion, so a crossfade where two sentences overlap and a blank gap between two pictures both pass it. `checkFilm(film, { times })` from `vizmatic/stage` inspects any times you pass. For a long film, pass every frame.
74
+
75
+ `--audio narration.wav` adds sound, padded or trimmed to the film's length, so hold until the voice ends. `s.caption(text, seconds)` writes a WebVTT file beside the video and draws nothing into the picture. MP4 output is H.264 with settings that QuickTime can play. To join a clip to a film without encoding it again, encode the clip with `filmEncoderSettings(quality)` from `vizmatic/stage/export`.
68
76
 
69
77
  Motion guidance:
70
78
 
@@ -73,6 +81,20 @@ Motion guidance:
73
81
  - Give color a meaning and keep it. A quantity keeps its color from its first appearance to its last.
74
82
  - Use chapters. They mark the player's timeline and are the steps of a presentation.
75
83
 
84
+ ### Lessons
85
+
86
+ When a film must teach a topic, [lessons.md](https://bvolpato.github.io/vizmatic/references/lessons.md) has the full method. In short:
87
+
88
+ - Put accuracy first, then completeness, clarity, and brevity. There is no target length, so keep every passage that teaches.
89
+ - Finish the script before the film. Teach the problem, then the mechanism, then the limits. Keep one worked example throughout.
90
+ - Compute every number in the film, and check it with `assert`. The voice and the screen use the same values and the same rounding.
91
+ - Keep each title true for as long as it is visible. List every text block with its visible times, and read each one against the picture and the voice.
92
+ - Change pictures cleanly. Old text drops under about 25% opacity before new text reaches it, and something stays on screen through the change.
93
+ - A person must watch the film at full speed with sound before it is published. You cannot do this, so say that it has not happened.
94
+ - Use the computed states from `vizmatic` where they fit: `weightedVectorState`, `categoricalSampling`, `planTeachingRoutedTransfer`, `byteDifferenceState`, and `tokenHistoryState`. Show the limits of each. `check` and `film` accept this import, and `preview` refuses it because it runs in the browser. A project with a checked canvas host can use the same constructions through `createTeachingCanvas(painter)`.
95
+
96
+ Read a finished film before you write a similar one. `examples/films/` in the package holds them with full source, and the [Films](https://bvolpato.github.io/vizmatic/films.html) page plays them.
97
+
76
98
  ## Figures
77
99
 
78
100
  Create `frame.tsx`. `Scene` title and subtitle are optional.
@@ -134,3 +156,5 @@ After creating a visual, report:
134
156
  - which looks or themes rendered
135
157
  - whether `vizmatic check` passed
136
158
  - any overflow or layout fixes made
159
+ - for a film, which stills you opened, and whether you scanned the motion
160
+ - anything you could not verify, including that nobody has watched the film with sound
package/ROADMAP.md CHANGED
@@ -42,11 +42,11 @@ This page states what Vizmatic can do now and what comes next. Vizmatic aims to
42
42
  ### Figures
43
43
 
44
44
  - C4 semantics: one reusable model with context, container, component, deployment, and dynamic views.
45
- - UML class and component diagrams, state machines with nested states, and ER diagrams with keys and cardinality.
45
+ - UML class and component diagrams, and state machines with nested states. ER diagrams with keys and cardinality are implemented.
46
46
  - Swimlanes and activity diagrams.
47
47
  - A layout adapter interface with Dagre as the default and ELK as an option. Per-boundary direction and collapsed groups.
48
48
  - Build-time icon packs for GCP and Kubernetes from pinned Apache-2.0 data, as optional modules. User-supplied AWS and Azure adapters until redistribution terms support bundled packs.
49
- - Structured accessibility for charts and other primitives, as graph diagrams have today.
49
+ - Structured accessibility for more scientific and drawing primitives. Charts and entity-relationship diagrams now preserve their semantic summaries in SVG exports.
50
50
  - Wider Mermaid and D2 import, and Structurizr, Kubernetes, and Terraform adapters where semantics map safely.
51
51
 
52
52
  ## Design constraints
@@ -177,6 +177,7 @@ var SCENE_COMPONENT_NAMES = Object.freeze([
177
177
  "DiagramLegend",
178
178
  "DonutChart",
179
179
  "DotPoint",
180
+ "EntityRelationshipDiagram",
180
181
  "EquationCard",
181
182
  "FactRows",
182
183
  "Flow",
@@ -387,7 +388,7 @@ function validateSceneComponentProps(name, props) {
387
388
  const check = (value, key) => {
388
389
  if (++values > 8192) throw new Error(`Editable scene ${name} props exceed their value budget.`);
389
390
  if (typeof value === "number") {
390
- if (/^(?:width|height|x|y|x1|y1|x2|y2|cx|cy|r|rx|ry|radius|length|padding|gap|nodeWidth|nodeHeight|cellSize|cellWidth|cellHeight|fontSize|nodeSize|tileWidth|minHeight)$/i.test(key)) finite(value, `${name}.${key}`);
391
+ if (/^(?:width|height|x|y|x1|y1|x2|y2|cx|cy|r|rx|ry|radius|length|padding|gap|nodeWidth|nodeHeight|entityWidth|cellSize|cellWidth|cellHeight|fontSize|nodeSize|tileWidth|minHeight)$/i.test(key)) finite(value, `${name}.${key}`);
391
392
  if (/^(?:rows|cols|columns|count|repeat|gridCount|tickCount)$/i.test(key)) integer(value, `${name}.${key}`, key === "gridCount" ? 0 : 1, 2e3);
392
393
  }
393
394
  if (Array.isArray(value)) value.forEach((item) => check(item, ""));
@@ -415,6 +416,12 @@ function validateSceneComponentProps(name, props) {
415
416
  for (const key of ["nodes", "groups", "boundaries", "blocks"]) entries(props[key], `${name}.${key}`, 128);
416
417
  for (const key of ["edges", "connections", "routes"]) entries(props[key], `${name}.${key}`, 256);
417
418
  }
419
+ if (name === "EntityRelationshipDiagram") {
420
+ entries(props.entities, "EntityRelationshipDiagram.entities", 128).forEach((entity) => {
421
+ entries(record(entity, "Entity relationship entity").attributes, "EntityRelationshipDiagram.attributes", 64);
422
+ });
423
+ entries(props.relationships, "EntityRelationshipDiagram.relationships", 256);
424
+ }
418
425
  if (name === "TransformerTopology" && props.expandRepeats) {
419
426
  const blocks = entries(props.blocks, "TransformerTopology.blocks", 128);
420
427
  const total = blocks.reduce((sum, block) => sum + integer(record(block, "Transformer block").repeat ?? 1, "Transformer block.repeat", 1, 128), 0);
@@ -471,6 +471,20 @@ var satori = (element, options) => renderWithCanvasChartFit(renderSatori, elemen
471
471
  // src/svg-accessibility.ts
472
472
  import { cloneElement, isValidElement as isValidElement2 } from "react";
473
473
  var SVG_ACCESSIBILITY_COMPONENT = /* @__PURE__ */ Symbol.for("vizmatic.svgAccessibilityComponent");
474
+ function chartAccessibilityAttributes({ id, ariaLabel, description }) {
475
+ const title = ariaLabel?.trim() || "Chart";
476
+ return {
477
+ role: "img",
478
+ "aria-label": title,
479
+ "aria-description": description,
480
+ "data-vizmatic-chart-id": id,
481
+ "data-vizmatic-chart-title": title,
482
+ "data-vizmatic-chart-description": description
483
+ };
484
+ }
485
+ function chartDescription(description, entries) {
486
+ return [description, entries.length ? `${entries.join("; ")}.` : "No data."].filter(Boolean).join(" ");
487
+ }
474
488
  function componentHasSvgMetadata(type) {
475
489
  return typeof type === "function" && type[SVG_ACCESSIBILITY_COMPONENT] === true;
476
490
  }
@@ -625,9 +639,21 @@ function edgeGroup(graph, edge, root) {
625
639
  return `${accessible}${hitTarget}</g>`;
626
640
  }
627
641
  function addSvgAccessibility(svg, graphs, layoutNodes) {
628
- if (graphs.length === 0) return svg;
629
- const title = graphs.map((graph) => graph.title).join(". ");
630
- const description = graphs.map((graph) => `${graph.title}. ${graph.description}`).join(" ");
642
+ const chartIds = /* @__PURE__ */ new Set();
643
+ const charts = layoutNodes.filter((node) => textProperty(node.props, "data-vizmatic-chart-title")).map((node, index) => {
644
+ const id = textProperty(node.props, "data-vizmatic-chart-id");
645
+ if (id && chartIds.has(id)) throw new Error(`Chart SVG id "${id}" must be unique in one exported SVG.`);
646
+ if (id) chartIds.add(id);
647
+ return {
648
+ token: id ? `id-${svgToken(id)}` : `index-${index}`,
649
+ title: textProperty(node.props, "data-vizmatic-chart-title"),
650
+ description: textProperty(node.props, "data-vizmatic-chart-description")
651
+ };
652
+ });
653
+ if (graphs.length === 0 && charts.length === 0) return svg;
654
+ const items = [...graphs, ...charts];
655
+ const title = items.map((item) => item.title).join(". ");
656
+ const description = items.map((item) => `${item.title}. ${item.description}`).join(" ");
631
657
  const hasLinks = graphs.some(
632
658
  (graph) => graph.nodes.some((node) => node.href) || graph.edges.some((edge) => edge.href)
633
659
  );
@@ -653,11 +679,15 @@ function addSvgAccessibility(svg, graphs, layoutNodes) {
653
679
  }).join("");
654
680
  return `<g ${attribute("id", baseId)} role="group" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"><title id="${titleId}">${escapeXml(graph.title)}</title><desc id="${descriptionId}">${escapeXml(graph.description)}</desc>${nodes}${edges}</g>`;
655
681
  }).join("");
682
+ const chartMarkup = charts.map((chart) => {
683
+ const id = `vizmatic-chart-${chart.token}`;
684
+ return `<g ${attribute("id", id)} role="group" aria-labelledby="${id}-title" aria-describedby="${id}-description"><title id="${id}-title">${escapeXml(chart.title)}</title><desc id="${id}-description">${escapeXml(chart.description)}</desc></g>`;
685
+ }).join("");
656
686
  const metadata = `<title id="${rootTitleId}">${escapeXml(title)}</title><desc id="${rootDescriptionId}">${escapeXml(description)}</desc>`;
657
687
  return svg.replace(
658
688
  /^<svg\b([^>]*)>/,
659
689
  (_match, attrs) => `<svg${attrs} role="${hasLinks ? "group" : "img"}" aria-labelledby="${rootTitleId}" aria-describedby="${rootDescriptionId}">${metadata}`
660
- ).replace(/<\/svg>\s*$/, `${groupMarkup}</svg>`);
690
+ ).replace(/<\/svg>\s*$/, `${groupMarkup}${chartMarkup}</svg>`);
661
691
  }
662
692
 
663
693
  // src/render.ts
@@ -1440,10 +1470,39 @@ function sampleAnimationFrames(animation, options = {}) {
1440
1470
  // src/video.ts
1441
1471
  import { spawn } from "child_process";
1442
1472
  import { randomUUID } from "crypto";
1443
- import { chmod, mkdir as mkdir2, open, rename, rm, stat } from "fs/promises";
1473
+ import { chmod, mkdir as mkdir2, open, rename, rm, stat, writeFile as writeFile2 } from "fs/promises";
1444
1474
  import { basename, dirname as dirname2, join as join2, resolve } from "path";
1445
1475
  import { Resvg as Resvg2 } from "@resvg/resvg-js";
1446
1476
  import parseCssColor from "parse-css-color";
1477
+ function chapterMetadata(title, chapters, duration) {
1478
+ const escape = (value) => value.replace(/[\\=;#]/g, (c) => `\\${c}`).replace(/\r?\n/g, " ");
1479
+ const marks = chapters.filter((chapter) => Number.isFinite(chapter.time) && chapter.time < duration).map((chapter) => ({ title: chapter.title, time: Math.max(0, chapter.time) })).sort((a, b) => a.time - b.time);
1480
+ if (marks.length > 0) marks[0].time = 0;
1481
+ let out = ";FFMETADATA1\n";
1482
+ if (title) out += `title=${escape(title)}
1483
+ `;
1484
+ marks.forEach((mark, index) => {
1485
+ const end = index + 1 < marks.length ? marks[index + 1].time : duration;
1486
+ out += `[CHAPTER]
1487
+ TIMEBASE=1/1000
1488
+ START=${Math.round(mark.time * 1e3)}
1489
+ END=${Math.round(end * 1e3)}
1490
+ title=${escape(mark.title)}
1491
+ `;
1492
+ });
1493
+ return out;
1494
+ }
1495
+ function captionsToSrt(captions, duration) {
1496
+ const stamp = (seconds) => {
1497
+ const ms = Math.round(seconds * 1e3);
1498
+ const pad = (value, size = 2) => String(value).padStart(size, "0");
1499
+ return `${pad(Math.floor(ms / 36e5))}:${pad(Math.floor(ms / 6e4) % 60)}:${pad(Math.floor(ms / 1e3) % 60)},${pad(ms % 1e3, 3)}`;
1500
+ };
1501
+ return captions.filter((cue) => cue.t1 > 0 && cue.t0 < duration && cue.t1 > cue.t0 && cue.text.trim().length > 0).sort((a, b) => a.t0 - b.t0).map((cue, index) => `${index + 1}
1502
+ ${stamp(Math.max(0, cue.t0))} --> ${stamp(Math.min(duration, cue.t1))}
1503
+ ${cue.text.trim()}
1504
+ `).join("\n");
1505
+ }
1447
1506
  var MAX_STDERR_CHARS = 8192;
1448
1507
  var COLOR_FILTER = "scale=in_range=pc:out_range=tv:out_color_matrix=bt709:flags=lanczos+accurate_rnd+full_chroma_int,format=yuv420p,setparams=range=tv:color_primaries=bt709:color_trc=bt709:colorspace=bt709";
1449
1508
  var COLOR_TAGS = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv"];
@@ -1657,12 +1716,37 @@ async function renderRgbaVideo(renderFrame, options) {
1657
1716
  "-i",
1658
1717
  "pipe:0"
1659
1718
  ];
1719
+ let inputs = 1;
1720
+ let audioInput = -1;
1660
1721
  if (options.audioPath) {
1661
1722
  if (options.audioOffset) args.push("-ss", String(options.audioOffset));
1662
1723
  args.push("-i", resolve(options.audioPath));
1724
+ audioInput = inputs++;
1725
+ }
1726
+ const sidecars = [];
1727
+ let metadataInput = -1, captionInput = -1;
1728
+ if (codec === "h264") {
1729
+ const chapters = options.chapters ?? [];
1730
+ if (options.title || chapters.length > 0) {
1731
+ const path = join2(outputDirectory, `.${basename(outputPath)}.${randomUUID()}.tmp.ffmeta`);
1732
+ await writeFile2(path, chapterMetadata(options.title, chapters, schedule.duration), { mode: 384 });
1733
+ sidecars.push(path);
1734
+ args.push("-f", "ffmetadata", "-i", path);
1735
+ metadataInput = inputs++;
1736
+ }
1737
+ const srt = captionsToSrt(options.captions ?? [], schedule.duration);
1738
+ if (srt) {
1739
+ const path = join2(outputDirectory, `.${basename(outputPath)}.${randomUUID()}.tmp.srt`);
1740
+ await writeFile2(path, srt, { mode: 384 });
1741
+ sidecars.push(path);
1742
+ args.push("-f", "srt", "-i", path);
1743
+ captionInput = inputs++;
1744
+ }
1663
1745
  }
1664
1746
  args.push("-map", "0:v:0");
1665
- if (options.audioPath) args.push("-map", "1:a:0", "-af", `asetpts=PTS-STARTPTS,apad,atrim=duration=${seconds}`);
1747
+ if (options.audioPath) args.push("-map", `${audioInput}:a:0`, "-af", `asetpts=PTS-STARTPTS,apad,atrim=duration=${seconds}`);
1748
+ if (captionInput >= 0) args.push("-map", `${captionInput}:0`, "-c:s", "mov_text", "-metadata:s:s:0", "language=eng");
1749
+ if (metadataInput >= 0) args.push("-map_metadata", String(metadataInput), "-map_chapters", String(metadataInput));
1666
1750
  args.push("-frames:v", String(schedule.count), "-t", seconds, "-vf", COLOR_FILTER);
1667
1751
  if (codec === "vp9") {
1668
1752
  args.push("-c:v", "libvpx-vp9", "-crf", String(crf), "-b:v", "0", "-deadline", "good", "-cpu-used", "2", "-row-mt", "1", "-threads:v", String(threads));
@@ -1686,6 +1770,7 @@ async function renderRgbaVideo(renderFrame, options) {
1686
1770
  child = spawn(ffmpegPath, args, { stdio: ["pipe", "ignore", "pipe"] });
1687
1771
  } catch (error) {
1688
1772
  await rm(tempPath, { force: true });
1773
+ for (const path of sidecars) await rm(path, { force: true });
1689
1774
  throw error;
1690
1775
  }
1691
1776
  child.stderr?.on("data", (chunk) => {
@@ -1787,6 +1872,7 @@ async function renderRgbaVideo(renderFrame, options) {
1787
1872
  throw error;
1788
1873
  } finally {
1789
1874
  await rm(tempPath, { force: true });
1875
+ for (const path of sidecars) await rm(path, { force: true });
1790
1876
  }
1791
1877
  }
1792
1878
 
@@ -3577,6 +3663,8 @@ export {
3577
3663
  getRenderBackground,
3578
3664
  withRenderContext,
3579
3665
  SVG_ACCESSIBILITY_COMPONENT,
3666
+ chartAccessibilityAttributes,
3667
+ chartDescription,
3580
3668
  prepareAccessibleSvg,
3581
3669
  addSvgAccessibility,
3582
3670
  CANVAS_CHART_COMPONENT,
@@ -3612,6 +3700,8 @@ export {
3612
3700
  sampleAnimationFrame,
3613
3701
  analyzeAnimationCadence,
3614
3702
  sampleAnimationFrames,
3703
+ chapterMetadata,
3704
+ captionsToSrt,
3615
3705
  videoFrameSchedule,
3616
3706
  renderAnimationVideo,
3617
3707
  renderRgbaVideo