beatsheet 0.0.0-stage → 0.2.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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  3. package/bin/beatsheet.js +14 -0
  4. package/bin/register-fallback.mjs +23 -0
  5. package/bin/resolve-fallback.mjs +83 -0
  6. package/package.json +45 -4
  7. package/player/env.d.ts +5 -0
  8. package/player/gallery-audio.ts +147 -0
  9. package/player/gallery-css.ts +144 -0
  10. package/player/gallery-detail.ts +385 -0
  11. package/player/gallery-music.ts +257 -0
  12. package/player/gallery-pick-state.ts +167 -0
  13. package/player/gallery-pick.ts +749 -0
  14. package/player/gallery-sounds.ts +137 -0
  15. package/player/gallery-state.ts +457 -0
  16. package/player/gallery.ts +612 -0
  17. package/player/index.html +49 -0
  18. package/player/main.ts +83 -0
  19. package/skill/SKILL.md +658 -0
  20. package/skill/examples/library/assets/tour/avatar-mk.svg +1 -0
  21. package/skill/examples/library/assets/tour/dashboard-insights.svg +1 -0
  22. package/skill/examples/library/assets/tour/dashboard.svg +1 -0
  23. package/skill/examples/library/assets/tour/settings.svg +1 -0
  24. package/skill/examples/library/library-tour.plan.md +32 -0
  25. package/skill/examples/library/library-tour.video.json +268 -0
  26. package/skill/reference/scene-techniques.md +306 -0
  27. package/skill/scripts/beats.ts +34 -0
  28. package/skill/scripts/catalogue.ts +120 -0
  29. package/skill/scripts/frames.ts +105 -0
  30. package/src/args.ts +344 -0
  31. package/src/cli.ts +95 -0
  32. package/src/commands.ts +812 -0
  33. package/src/default-project.config.ts +9 -0
  34. package/src/index.ts +47 -0
  35. package/src/packages.ts +17 -0
  36. package/src/paths.ts +32 -0
  37. package/src/project.ts +200 -0
  38. package/src/render/browser.ts +185 -0
  39. package/src/render/capture.ts +320 -0
  40. package/src/render/ffmpeg.ts +229 -0
  41. package/src/render/gif-info.ts +61 -0
  42. package/src/render/render.ts +220 -0
  43. package/src/samples.ts +557 -0
  44. package/src/server/api.ts +494 -0
  45. package/src/server/jobs.ts +210 -0
  46. package/src/server/security.ts +47 -0
  47. package/src/server/server.ts +191 -0
  48. package/src/server/sse.ts +76 -0
  49. package/src/server/static.ts +127 -0
  50. package/src/server/vite.ts +100 -0
  51. package/src/skill.ts +111 -0
  52. package/src/snap.ts +212 -0
  53. package/src/speech.ts +689 -0
  54. package/src/svg-text.ts +136 -0
  55. package/src/voicefx.ts +311 -0
  56. package/studio/3rdpartylicenses.txt +287 -0
  57. package/studio/favicon.ico +0 -0
  58. package/studio/icons/apple-touch-icon.png +0 -0
  59. package/studio/icons/icon-192.png +0 -0
  60. package/studio/icons/icon-512.png +0 -0
  61. package/studio/icons/icon.svg +1 -0
  62. package/studio/icons/maskable-512.png +0 -0
  63. package/studio/index.html +18 -0
  64. package/studio/main-KMYDBWZH.js +15 -0
  65. package/studio/manifest.webmanifest +17 -0
  66. package/studio/offline.html +92 -0
  67. package/studio/styles-NJ2CULOW.css +1 -0
  68. package/studio/sw.js +71 -0
@@ -0,0 +1,306 @@
1
+ # Scene techniques: SVG, masks, 3D, canvas, shaders, three.js, GSAP
2
+
3
+ Recipes for a scene type of your own (SKILL.md, section 6). Every one is the same idea: **nothing plays, everything
4
+ is seeked.** `update(frame)` gets a time and sets the picture for that time; the renderer calls it once per frame,
5
+ the studio in any order. A library that animates by itself is paused and set to `t`.
6
+
7
+ Measured through the real render path (headless Chromium, 1920×1080, 2026-11): what works, and what a frame costs.
8
+
9
+ | Technique | Frame-exact | ms per frame | Notes |
10
+ |---|---|---|---|
11
+ | plain DOM (a built-in scene) | yes | 35 | the baseline |
12
+ | SVG attributes (`diagram`) | yes | 40–50 | |
13
+ | masks and clip paths (`type-reveal`) | yes | 45–100 | a full-frame picture under a clip costs more than text |
14
+ | CSS 3D (`product-shot`) | yes | 75–85 | keep an element's layer state constant (rule 2) |
15
+ | GSAP, a paused timeline | yes, with the two settings below | 40 | its defaults are **not** frame-exact |
16
+ | canvas 2D | yes | 50 | noise from a seeded rng |
17
+ | three.js, a small lit scene | yes | 95 | WebGL runs on the CPU in the renderer |
18
+ | a full-frame fragment shader | yes | 95–310 | 95: `shader-title` at half size; 310: full size, 15 noise octaves per pixel |
19
+
20
+ A 4 s scene is 120 frames: a 300 ms shader adds half a minute to a render, a 95 ms one 7 seconds.
21
+
22
+ ## Rules for all of them
23
+
24
+ 1. **A pure function of `frame.t`.** No timers, `requestAnimationFrame`, CSS animations or transitions,
25
+ `Math.random`, `Date`. Randomness: `mulberry32(seed)` from `@beatsheet/core`, drawn once in `mount()`.
26
+ 2. **One layer state per element.** Do not switch an element between 2D and 3D transforms over time
27
+ (`translate()` at rest, `translate3d()` while moving), and do not add or remove `will-change`: Chromium promotes
28
+ and demotes a compositor layer, and the antialiasing of those frames differs from run to run. Always 2D, or
29
+ always 3D, is fine. This is what GSAP's default `force3D: 'auto'` gets wrong.
30
+ 3. **Times from the beats.** `const at = (id) => frame.beats?.[id] ?? defaults[id] ?? 0`, so the user can retime the
31
+ scene in the studio. Durations from the theme: `const mo = sceneMotion(ctx.theme)`, `mo.enter`, `mo.stagger`,
32
+ `mo.in(t, start)`, and `mo.out(t, duration, frame.next)` as the opacity factor before a dip.
33
+ 4. **Colours from the theme.** In CSS `var(--bs-accent)`; for a canvas, a shader or a material
34
+ `tokenRgb(ctx, 'bs-accent')` (`[r, g, b]`, 0..1), read in `mount()`. No literal colours: the scene must follow
35
+ the theme and a video's own look.
36
+ 5. **Text stays DOM.** `check` measures layout and read time on elements: text painted into a canvas is invisible
37
+ to it, to the entrance styles and to captions. Draw the picture in the canvas, lay the words over it.
38
+ 6. **Release what you hold.** Every scene of a video is mounted at once and stays mounted; the studio remounts on
39
+ every edit. `destroy()` kills timelines and releases WebGL contexts (a browser allows about 16).
40
+ 7. **A fallback where there is no canvas.** The unit tests run in jsdom (no layout, no canvas, no WebGL): guard
41
+ `getContext()` results, and compute positions in TS from `ctx.format` instead of measuring the DOM.
42
+ 8. **Hide with `visibility: hidden`, show with `inherit`.** The player hides every scene but the current one with
43
+ `visibility` on its layer; a child set to `visible` overrides that and shows through all other scenes.
44
+ 9. **No large CSS gradients.** Chromium dithers a CSS gradient, and a frame full of that noise takes 270–430 ms to
45
+ capture as PNG (measured on `type-reveal`'s first version; 46–99 ms after the change). Draw a big soft field
46
+ once in `mount()` as a small bitmap (a quarter-size canvas filled from `tokenRgb`, `toDataURL()`, scaled up) or
47
+ with `shaderLayer`; small gradients (a button, a scrim under a card) are fine.
48
+ 10. **`check` measures boxes, not paint.** A full-width layer moved by `translateX(100%)` counts as sticking out of
49
+ the stage though it paints one line. Move thin things with `left` / `top` in %, or make the moved element as
50
+ small as what it paints.
51
+ 11. **Prove it.** `npx tsx <repo>/skills/beatsheet/scripts/frames.ts videos/<name>.video.json --scene <id>` renders
52
+ the scene twice in fresh browsers and compares every frame byte for byte, and prints its ms per frame. Add
53
+ `--backwards`: a frame must be the same picture in whatever order it is reached, and the renderer repaints
54
+ every seek from scratch so that it is (so does the studio's preview while it is not playing; its playback
55
+ frames are not repainted). A scene that still differs keeps state between updates.
56
+ 12. **SVG images with text.** In an `.svg` used as an image, put `text-rendering="geometricPrecision"` on the
57
+ `<svg>` (or outline the text). Without it Chromium may reuse a font it made for another text of almost the
58
+ same size on screen, and the glyphs then depend on what was drawn before. `check videos/<name>.video.json`
59
+ warns about every such file the video loads: `image "tour/dashboard.svg" has live text ("Shopboard" and 30
60
+ more) that can render a few pixels differently depending on the frames sought before: add
61
+ text-rendering="geometricPrecision" to its <svg> element, or convert the text to outlines [svg-text]`.
62
+ Cure the file. Only for a file that must stay as it is (a supplied logo the user will not have changed), and
63
+ with that reason given to the user, silence the warning by its id: `"ignoreWarnings": ["svg-text"]` in the
64
+ video, or `rules: { ignoreWarnings: ['svg-text'] }` in `beatsheet.config.ts` for every video of the project.
65
+ `check` then ends with `… 1 silenced (svg-text)`; the frames can still differ by a few pixels.
66
+ 13. **Mark the ground.** The element that paints your scene's full-frame background, when that is a gradient, a
67
+ picture, a canvas or a shader: `markGround(el)` from the kit (`markGround(layer.el)` for a `shaderLayer`, only
68
+ when `layer.ok`). The player holds a marked ground still while a `slide` or `zoom` moves the scene, so the
69
+ content moves over it; unmarked, the edge the layer moves away from shows a band in one flat colour, up to a
70
+ tenth of the frame wide. The marked element covers the whole frame, is opaque, and holds no content (text in it
71
+ would stay still too); give it no `translate` or `scale` property of its own (the player sets those; a
72
+ `transform` is fine). Keep the opaque `background-color` on the scene's full-frame element as well: it is what
73
+ shows while nothing is marked.
74
+
75
+ Imports: `@beatsheet/core` (`defineScene`, `h`, `z`, `seg`, `ease`, `clamp`, `lerp`, `mulberry32`, `renderRichText`)
76
+ and `@beatsheet/scenes/kit` (`sceneMotion`, `baseCss`, `sp`, `narrow`, `toBeats`, `beatOffsets`, `READ_SKIP`,
77
+ `markGround`, and the helpers below: `s`, `drawable`, `strokeDraw`, `cubicPoint`, `tokenRgb`, `shaderLayer`).
78
+
79
+ ## SVG: lines that draw, shapes that morph, a dot that travels
80
+
81
+ Use it for diagrams, routes, charts, signatures, logos that assemble. Built-in example: `diagram`
82
+ (`packages/scenes/src/feature/diagram.ts`).
83
+
84
+ ```ts
85
+ import { drawable, s, strokeDraw, cubicPoint } from '@beatsheet/scenes/kit';
86
+
87
+ // mount(): build once. Coordinates in the format's pixels, computed in TS.
88
+ const { width: W, height: H } = ctx.format;
89
+ const a = { x: W * 0.2, y: H * 0.5 }, b = { x: W * 0.8, y: H * 0.5 };
90
+ const c1 = { x: W * 0.4, y: H * 0.3 }, c2 = { x: W * 0.6, y: H * 0.7 };
91
+ const line = drawable(s('path', { class: 'x-line', d: `M${a.x} ${a.y}C${c1.x} ${c1.y} ${c2.x} ${c2.y} ${b.x} ${b.y}` }));
92
+ const dot = s('circle', { class: 'x-dot', r: 8 });
93
+ ctx.root.appendChild(s('svg', { class: 'x-svg', viewBox: `0 0 ${W} ${H}` }, line, dot));
94
+
95
+ // update(): the line draws over 0.9 x enter from its beat, then the dot runs along it every 1.6 s.
96
+ strokeDraw(line, mo.move(t, at('line'), 0.9));
97
+ const u = ((t - at('line') - mo.enter) / 1.6) % 1;
98
+ const p = cubicPoint(a, c1, c2, b, u < 0 ? 0 : u);
99
+ dot.setAttribute('cx', p.x.toFixed(2));
100
+ dot.setAttribute('cy', p.y.toFixed(2));
101
+ dot.style.opacity = u < 0 ? '0' : '1';
102
+ ```
103
+
104
+ - `drawable()` sets `pathLength="1"`, so `strokeDraw(el, p)` needs no `getTotalLength()` (jsdom has none).
105
+ - Stroke and fill in CSS: `.x-line{fill:none;stroke:var(--bs-accent);stroke-width:4;stroke-linecap:round}`.
106
+ - A morph: two paths with the same commands and point count; interpolate the numbers with `lerp` and set `d`.
107
+ - Round numbers you write into attributes (`toFixed`), so the DOM of a frame is the same however it was reached.
108
+
109
+ ## Masks and clip paths: reveals
110
+
111
+ Use it for a picture opening behind type, a wipe across a screenshot, text rising out of a line. Built-in example:
112
+ `type-reveal` (`packages/scenes/src/opener/type-reveal.ts`).
113
+
114
+ ```ts
115
+ // An iris opening from the centre: radius 0 to the frame's half diagonal.
116
+ const p = mo.settle(t, at('open'), 1.6);
117
+ picture.style.clipPath = p >= 1 ? '' : `circle(${(p * 100).toFixed(2)}% at 50% 50%)`;
118
+ // Type as a window onto a picture: one full-frame element, the picture as its background.
119
+ // css: .x-cut{background:var(--x-picture) center/cover;-webkit-background-clip:text;background-clip:text;color:transparent}
120
+ // A line rising out of a mask: a wrapper with overflow:hidden, the line inside moved by translateY.
121
+ line.style.transform = `translateY(${((1 - mo.settle(t, at('type'))) * 110).toFixed(2)}%)`;
122
+ ```
123
+
124
+ - Remove a clip once it is open (`''`), like the built-in entrances do: an open clip still costs a layer.
125
+ - Two layers showing the same picture must get the same `background-size` and position on every frame.
126
+ - Text that rises from behind a mask: clip it with a per-frame `clip-path` on the line, not `overflow:hidden` on a
127
+ wrapper (`check` reports the hidden part as overflow or as sticking out of the stage).
128
+ - A blend mode or filter on an element stays for the whole scene (rule 2): set it in CSS, change opacity and clip.
129
+
130
+ ## CSS 3D: tilted screens, card stacks
131
+
132
+ Use it for a product shot in space, a deck of cards fanning out, a flip. Built-in example: `product-shot`
133
+ (`packages/scenes/src/demo/product-shot.ts`).
134
+
135
+ ```ts
136
+ // css: .x-stage{perspective:1600px} .x-window{transform-style:preserve-3d}
137
+ const p = mo.settle(t, at('shot'), 1.6);
138
+ const ry = lerp(-32, -14, p) - (t - at('shot')) * 0.6; // eases to the rest pose, then drifts on
139
+ const rx = lerp(14, 6, p);
140
+ win.style.transform = `translateZ(${lerp(-260, 0, p).toFixed(2)}px) rotateX(${rx.toFixed(3)}deg) rotateY(${ry.toFixed(3)}deg)`;
141
+ win.style.opacity = String(mo.in(t, at('shot')));
142
+ ```
143
+
144
+ - Rule 2: the window has a 3D transform on every frame, also at rest. Never end on `transform:none`.
145
+ - `check` measures the transformed boxes: a callout that leaves the frame in 4:5 is reported.
146
+ - Depth reads from the shadow and from things at different `translateZ`, not from the angle: keep angles calm.
147
+
148
+ ## Canvas 2D: particles, fields, hand-drawn charts
149
+
150
+ ```ts
151
+ import { mulberry32 } from '@beatsheet/core';
152
+ import { tokenRgb } from '@beatsheet/scenes/kit';
153
+
154
+ // mount()
155
+ const canvas = h('canvas', { width: ctx.format.width, height: ctx.format.height, 'aria-hidden': 'true' });
156
+ const g = canvas.getContext('2d'); // null in jsdom
157
+ const [r, gr, b] = tokenRgb(ctx, 'bs-accent').map((v) => Math.round(v * 255));
158
+ const rng = mulberry32(7); // the same dots on every mount
159
+ const dots = Array.from({ length: 300 }, () => ({ x: rng(), y: rng(), speed: 0.2 + rng() * 0.8 }));
160
+
161
+ // update(): clear and redraw everything from t. Never accumulate from the frame before.
162
+ if (!g) return;
163
+ g.clearRect(0, 0, canvas.width, canvas.height);
164
+ g.fillStyle = `rgb(${r},${gr},${b})`;
165
+ for (const d of dots) {
166
+ g.globalAlpha = 0.25 + 0.6 * d.speed;
167
+ g.beginPath();
168
+ g.arc(((d.x + t * 0.03 * d.speed) % 1) * canvas.width, d.y * canvas.height, 2 + d.speed * 5, 0, Math.PI * 2);
169
+ g.fill();
170
+ }
171
+ ```
172
+
173
+ - A simulation (physics, flocking) is not a function of `t`. Either make it one (closed-form positions as above),
174
+ or precompute its states for every frame in `mount()` and index them by `Math.round(t * fps)`.
175
+ - Size the canvas to the format (`width`/`height` attributes); the renderer's device pixel ratio is 1.
176
+
177
+ ## A fragment shader: flowing fields, glows
178
+
179
+ Use it for a background that looks expensive. Built-in example: `shader-title`
180
+ (`packages/scenes/src/brand/shader-title.ts`).
181
+
182
+ ```ts
183
+ import { shaderLayer, tokenRgb } from '@beatsheet/scenes/kit';
184
+
185
+ const FRAG = `
186
+ uniform vec3 u_a; uniform vec3 u_b;
187
+ void main() {
188
+ vec2 uv = gl_FragCoord.xy / u_res;
189
+ float w = 0.5 + 0.5 * sin(uv.x * 6.0 + u_t * 0.6 + sin(uv.y * 4.0 - u_t * 0.4));
190
+ gl_FragColor = vec4(mix(u_a, u_b, w * w), 1.0);
191
+ }`;
192
+
193
+ // mount()
194
+ const layer = shaderLayer(ctx, FRAG); // half resolution by default: { scale: 1 } for hard edges
195
+ const a = tokenRgb(ctx, 'bs-dark-bg'), b = tokenRgb(ctx, 'bs-accent');
196
+ ctx.root.appendChild(layer.el); // css: canvas{position:absolute;inset:0;width:100%;height:100%}, a token gradient on its parent
197
+
198
+ // update() and destroy()
199
+ layer.draw(t, { u_a: a, u_b: b });
200
+ layer.destroy();
201
+ ```
202
+
203
+ - `shaderLayer` adds `precision highp float; uniform float u_t; uniform vec2 u_res;` and the full-frame triangle
204
+ strip. `layer.ok` is false where there is no WebGL or the shader does not compile: the canvas is hidden then, so
205
+ put a token gradient on the element behind it as the fallback.
206
+ - The renderer has no GPU. A WebGL canvas at half size costs about 60 ms a frame on top of a plain scene whatever
207
+ it draws (`shader-title`: 95 ms with noise, 93 ms without); at full size with three 5-octave noise lookups per
208
+ pixel it took 310 ms. Draw soft fields at half size; going below 0.5 saved nothing.
209
+ - No per-pixel dither against banding: it took `shader-title` from 99 to 259 ms a frame.
210
+ - GLSL has no random either: hash functions of the position are fine, they are pure.
211
+ - Rendered on another machine or architecture the pixels can differ in the last bit; on one machine they do not.
212
+
213
+ ## three.js
214
+
215
+ Use it for real 3D: an object turning, a scene with light. Install it in the project with the skill's install line,
216
+ so beatsheet and three.js land in one install: `npm install -D beatsheet @beatsheet/core @beatsheet/scenes three`.
217
+
218
+ ```ts
219
+ import * as THREE from 'three';
220
+
221
+ // mount()
222
+ const { width: W, height: H } = ctx.format;
223
+ const canvas = h('canvas', { width: W, height: H, 'aria-hidden': 'true' });
224
+ ctx.root.appendChild(canvas);
225
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
226
+ renderer.setPixelRatio(1);
227
+ renderer.setSize(W, H, false);
228
+ const scene = new THREE.Scene();
229
+ const camera = new THREE.PerspectiveCamera(35, W / H, 0.1, 50);
230
+ camera.position.set(0, 0.6, 7);
231
+ const [r, g, b] = tokenRgb(ctx, 'bs-accent');
232
+ const knot = new THREE.Mesh(
233
+ new THREE.TorusKnotGeometry(1, 0.34, 160, 24),
234
+ new THREE.MeshStandardMaterial({ color: new THREE.Color().setRGB(r, g, b, THREE.SRGBColorSpace), roughness: 0.3 }),
235
+ );
236
+ const key = new THREE.DirectionalLight(0xffffff, 2.2);
237
+ key.position.set(3, 4, 5);
238
+ scene.add(knot, new THREE.AmbientLight(0xffffff, 0.5), key);
239
+
240
+ // update(): set every transform from t, then render once.
241
+ knot.rotation.set(t * 0.7, t * 1.1, 0);
242
+ renderer.render(scene, camera);
243
+
244
+ // destroy()
245
+ renderer.dispose();
246
+ renderer.forceContextLoss();
247
+ ```
248
+
249
+ - No `renderer.setAnimationLoop`, no `THREE.Clock`, no `AnimationMixer.update(delta)`: for a loaded animation use
250
+ `mixer.setTime(t)`. Controls and physics add-ons that integrate over time are out.
251
+ - Guard the renderer for jsdom (`typeof WebGLRenderingContext === 'undefined'` → skip, show a fallback).
252
+ - Textures and models load asynchronously: a frame rendered before they arrive is a different frame. Build the
253
+ geometry in code, or embed small assets, so `mount()` is complete when it returns.
254
+
255
+ ## GSAP
256
+
257
+ Use it when a sequence is easier to write as a timeline than as formulas: many staggered parts, overshoots,
258
+ choreography. Worked example with its test: `examples/beatsheet-promo/scenes/timeline-hero.ts`. Install it in the
259
+ project with the skill's install line, `npm install -D beatsheet @beatsheet/core @beatsheet/scenes gsap` (free to use,
260
+ not open source: its licence applies to the project).
261
+
262
+ ```ts
263
+ import gsap from 'gsap';
264
+
265
+ // mount(): build paused; 2D transforms only and no lazy rendering (rule 2).
266
+ function build(beats: Record<string, number>): gsap.core.Timeline {
267
+ const tl = gsap.timeline({ paused: true, defaults: { force3D: false, lazy: false, ease: 'power3.out' } });
268
+ tl.from(blocks, { y: -120, rotation: -6, opacity: 0, duration: mo.enter * 1.2, stagger: mo.stagger, ease: 'back.out(1.6)' }, beats['blocks'] ?? 0.4);
269
+ tl.from(ruler, { scaleX: 0, transformOrigin: 'left center', duration: mo.enter }, beats['ruler'] ?? 1.4);
270
+ // Warm it: every tween writes its start values once, so the DOM of a frame is the same seeking forwards and backwards.
271
+ tl.progress(1, true).progress(0, true);
272
+ return tl;
273
+ }
274
+ let key = '';
275
+ let tl: gsap.core.Timeline | null = null;
276
+
277
+ // update(): rebuild when the user retimed a beat, then seek. Nothing else moves the timeline.
278
+ const k = Object.values(frame.beats ?? {}).join(',');
279
+ if (!tl || k !== key) {
280
+ tl?.kill();
281
+ gsap.set([...blocks, ruler], { clearProps: 'all' });
282
+ tl = build({ ...defaults, ...frame.beats });
283
+ key = k;
284
+ }
285
+ tl.seek(Math.max(0, frame.t), true);
286
+
287
+ // destroy()
288
+ tl?.kill();
289
+ ```
290
+
291
+ - **`force3D: false` and `lazy: false` are required.** With GSAP's defaults 12–15 of 60 frames differed between
292
+ two renders of the same file (measured); with them, none.
293
+ - No `gsap.to()` outside the paused timeline, no `gsap.ticker` callbacks, no `ScrollTrigger`, `Draggable`,
294
+ `Observer`, no `ease: 'rough'` or `random()` values without a seed.
295
+ - The warm-up pass matters for `to` tweens (a `from` writes its start values when it is created); keep it always.
296
+ - `clearProps: 'all'` wipes an element's whole inline style: give GSAP's targets no inline style in `mount()` and
297
+ set nothing inline on them in `update()`.
298
+ - No CSS `transform` on an element GSAP moves (it would be overwritten): draw a rotated shape on its `::before`.
299
+ - GSAP's inline opacity and transform beat a class: put state classes (active, played) on a parent GSAP does not
300
+ touch, and keep colours in CSS classes with tokens instead of tweening them.
301
+ - What is a plain function of `t` (a playhead's position, which item is active) is simpler without GSAP: mix both.
302
+
303
+ ## Lottie
304
+
305
+ Not measured here. The same rule would apply: load with `autoplay: false`, call `anim.goToAndStop(t * 1000, false)`
306
+ in `update()`, use the SVG renderer, embed the JSON so `mount()` is synchronous. Run `frames.ts` before relying on it.
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Prints a video's resolved timeline: per scene its start, length and beats (id, gap, time in the scene and in
3
+ * the video), and how long the scene stays on screen after its last beat.
4
+ *
5
+ * Usage, from the project folder: npx beatsheet beats videos/<name>.video.json
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { discoverProject } from 'beatsheet';
10
+ import { parseDoc, resolveTimeline } from '@beatsheet/core';
11
+
12
+ const file = process.argv[2];
13
+ if (!file) {
14
+ console.error('usage: npx beatsheet beats videos/<name>.video.json');
15
+ process.exit(2);
16
+ }
17
+ // The nearest beatsheet.config.ts up from the video, else the default project (default theme, built-in scenes).
18
+ const project = (await discoverProject(path.resolve(file))).config;
19
+ const timeline = resolveTimeline(parseDoc(JSON.parse(fs.readFileSync(file, 'utf8'))), project);
20
+ const s2 = (n: number): string => n.toFixed(2).padStart(6);
21
+
22
+ console.log(`${path.basename(file)} · ${timeline.scenes.length} scenes · ${timeline.duration.toFixed(2)} s`);
23
+ for (const scene of timeline.scenes) {
24
+ console.log(`\n${scene.id} (${scene.type}) ${scene.start.toFixed(2)}–${scene.end.toFixed(2)} s, ${scene.duration} s`);
25
+ for (const b of scene.beats) {
26
+ const gap = `gap ${b.gap.toFixed(2)}${b.overridden ? '*' : ' '}`;
27
+ console.log(` ${b.id.padEnd(18)} ${gap} +${s2(b.offset)} @${s2(b.at)} ${b.label}`);
28
+ }
29
+ const last = scene.beats.at(-1);
30
+ if (last) console.log(` on screen after the last beat: ${(scene.duration - last.offset).toFixed(2)} s`);
31
+ for (const w of scene.warnings) console.log(` warning: ${w}`);
32
+ }
33
+ for (const w of timeline.warnings) console.log(`warning: ${w}`);
34
+ console.log('\n* = gap overridden in the video file. A gap counts from the beat listed above it.');
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Prints the scene, sound and music catalogue of a project as Markdown, from the code:
3
+ * npx beatsheet catalogue [path/to/beatsheet.config.ts] [--props]
4
+ * Default: the nearest beatsheet.config.ts up from the current folder, else the default project (default theme,
5
+ * built-in scenes). --props adds every prop with its label,
6
+ * nested fields included (`nodes[].icon`), an enum with its values (the icon names).
7
+ * Music lists each track's tempo and beat length: scene durations in whole beats keep every cut on the beat.
8
+ */
9
+ import { discoverProject, loadProject } from 'beatsheet';
10
+ import { MUSIC_CATEGORIES, SCENE_CATEGORIES, SOUND_CATEGORIES, beatSeconds, isFileTrack, sceneSamples, trackBpm, trackParts, z } from '@beatsheet/core';
11
+ import type { MusicTrack, SceneType } from '@beatsheet/core';
12
+
13
+ const args = process.argv.slice(2);
14
+ const withProps = args.includes('--props');
15
+ const configPath = args.find((a) => !a.startsWith('--'));
16
+ const context = configPath ? await loadProject(configPath) : await discoverProject(process.cwd());
17
+ const project = context.config;
18
+
19
+ interface JsonNode {
20
+ type?: string | string[];
21
+ description?: string;
22
+ properties?: Record<string, JsonNode>;
23
+ items?: JsonNode;
24
+ enum?: unknown[];
25
+ anyOf?: JsonNode[];
26
+ }
27
+
28
+ function typeOf(n: JsonNode): string {
29
+ if (n.enum) return n.enum.map(String).join('\\|');
30
+ if (n.anyOf) return n.anyOf.map(typeOf).filter((t) => t !== 'null').join('\\|');
31
+ if (n.type === 'array') return n.items?.properties ? `{${Object.keys(n.items.properties).join(', ')}}[]` : `${typeOf(n.items ?? {})}[]`;
32
+ if (n.type === 'object' && n.properties) return `{${Object.keys(n.properties).join(', ')}}`;
33
+ return Array.isArray(n.type) ? n.type.join('\\|') : (n.type ?? 'any');
34
+ }
35
+
36
+ interface PropRow {
37
+ name: string;
38
+ type: string;
39
+ label: string;
40
+ }
41
+
42
+ /**
43
+ * A prop and, under it, the fields of its objects (`nodes[].icon`, `zoom.x`), each with its type:
44
+ * an enum lists its values, so the names an `icon` or a `kind` takes are in the catalogue.
45
+ */
46
+ function propRows(name: string, n: JsonNode): PropRow[] {
47
+ const fields = n.type === 'array' ? n.items?.properties : n.type === 'object' ? n.properties : undefined;
48
+ const prefix = n.type === 'array' ? `${name}[]` : name;
49
+ return [
50
+ { name, type: typeOf(n), label: (n.description ?? '').replace(/\|/g, '\\|') },
51
+ ...Object.entries(fields ?? {}).flatMap(([field, child]) => propRows(`${prefix}.${field}`, child)),
52
+ ];
53
+ }
54
+
55
+ /** The top-level props of a scene type. */
56
+ function propsOf(type: SceneType): PropRow[] {
57
+ const json = z.toJSONSchema(type.schema as z.ZodType, { unrepresentable: 'any' }) as JsonNode;
58
+ return Object.entries(json.properties ?? {}).map(([name, n]) => propRows(name, n)[0]!);
59
+ }
60
+
61
+ /** Every prop of a scene type, nested fields included (--props). */
62
+ function allPropsOf(type: SceneType): PropRow[] {
63
+ const json = z.toJSONSchema(type.schema as z.ZodType, { unrepresentable: 'any' }) as JsonNode;
64
+ return Object.entries(json.properties ?? {}).flatMap(([name, n]) => propRows(name, n));
65
+ }
66
+
67
+ function beatIds(type: SceneType): string {
68
+ // Beat ids over every sample (optional content adds beats), numbered ones folded into -N.
69
+ const ids = sceneSamples(type).flatMap((s) => type.beats(s.props).map((b) => b.id.replace(/-\d+(?=$|-)/g, '-N')));
70
+ return [...new Set(ids)].join(', ');
71
+ }
72
+
73
+ /** `120 bpm · beat 0.5 s` (the beat to the millisecond); a file track without a bpm: `–` (no grid). */
74
+ function tempo(track: MusicTrack): string {
75
+ const bpm = trackBpm(track);
76
+ return bpm === undefined ? '–' : `${bpm} bpm · beat ${Math.round(beatSeconds(bpm) * 1000) / 1000} s`;
77
+ }
78
+
79
+ // The context's name: the config's, else the folder's (the default project's config has none).
80
+ const out: string[] = [`# ${context.name}: scene types, sounds and music`, ''];
81
+ const groups = [...SCENE_CATEGORIES.map((c) => ({ id: c.id as string, title: c.title })), { id: 'other', title: 'Other' }];
82
+ for (const g of groups) {
83
+ const types = project.scenes.filter((t) => (t.category ?? 'other') === g.id);
84
+ if (types.length === 0) continue;
85
+ out.push(`## ${g.title}`, '', '| Type | For | Props | Beats | Samples |', '|---|---|---|---|---|');
86
+ for (const t of types) {
87
+ const props = propsOf(t).map((p) => `\`${p.name}\``).join(', ');
88
+ const samples = sceneSamples(t).map((s) => s.id).join(', ');
89
+ out.push(`| \`${t.id}\` | ${(t.description ?? t.title).replace(/\|/g, '\\|')} | ${props} | ${beatIds(t)} | ${samples} |`);
90
+ }
91
+ out.push('');
92
+ if (withProps) {
93
+ for (const t of types) {
94
+ out.push(`### ${t.id}`, '', '| Prop | Type | Label |', '|---|---|---|');
95
+ for (const p of allPropsOf(t)) out.push(`| \`${p.name}\` | ${p.type} | ${p.label} |`);
96
+ out.push('');
97
+ }
98
+ }
99
+ }
100
+
101
+ const soundGroups = [...SOUND_CATEGORIES.map((c) => ({ id: c.id as string, title: c.title })), { id: 'other', title: 'Other' }];
102
+ out.push('## Sounds', '', '| Id | Group | Description |', '|---|---|---|');
103
+ for (const g of soundGroups) {
104
+ for (const [id, s] of Object.entries(project.theme.sounds)) {
105
+ if ((s.category ?? 'other') === g.id) out.push(`| \`${id}\` | ${g.title} | ${s.description ?? s.title} |`);
106
+ }
107
+ }
108
+ out.push('', '## Music', '', 'Parts: the names a video levels with `music.mix` (0 muted, 1 as designed, up to 1.5).');
109
+ out.push('Tempo: one beat grid from video time 0 for the whole video. Write scene durations in whole beats of it, so every');
110
+ out.push('cut lands on a beat (`check` warns about a scene end off it). `–`: a file track without a `bpm`, nothing snaps.', '');
111
+ out.push('| Id | Mood | Kind | Tempo | Parts | Description |', '|---|---|---|---|---|---|');
112
+ const moods = [...MUSIC_CATEGORIES.map((c) => ({ id: c.id as string, title: c.title })), { id: 'other', title: 'Other' }];
113
+ for (const g of moods) {
114
+ for (const [id, m] of Object.entries(project.theme.music ?? {})) {
115
+ if ((m.category ?? 'other') !== g.id) continue;
116
+ const parts = trackParts(m).map((p) => `\`${p}\``).join(', ') || '–';
117
+ out.push(`| \`${id}\` | ${g.title} | ${isFileTrack(m) ? 'file' : 'generated'} | ${tempo(m)} | ${parts} | ${m.description ?? m.title} |`);
118
+ }
119
+ }
120
+ console.log(out.join('\n'));
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Checks that a video renders the same frames twice, and what each scene costs: seeks every frame through
3
+ * the real player and screenshot path in two fresh browsers and compares the PNGs byte for byte. Use it for
4
+ * every scene type that draws with more than plain DOM (a canvas, a shader, three.js, GSAP, Lottie).
5
+ *
6
+ * Usage, from the project folder:
7
+ * npx beatsheet frames videos/<name>.video.json [--format 4:5] [--scene <id>] [--backwards]
8
+ *
9
+ * Prints per scene: frames, ms per frame (seek + screenshot; a built-in scene takes about 40 ms at 16:9) and
10
+ * the frames that differ on the second run. --backwards adds a pass from the last frame to the first on the
11
+ * first browser: a frame has to be the same picture in whatever order it is reached. Exits 1 when the two
12
+ * forward runs differ, or the backward pass from the first.
13
+ */
14
+ import { createHash } from 'node:crypto';
15
+ import { frameTime, launchBrowser, loadVideo, openPlayer, videoServer } from 'beatsheet';
16
+ import type { FormatId } from '@beatsheet/core';
17
+
18
+ const args = process.argv.slice(2);
19
+ const flag = (name: string): string | undefined => {
20
+ const i = args.indexOf(name);
21
+ return i >= 0 ? args[i + 1] : undefined;
22
+ };
23
+ const file = args.find((a) => !a.startsWith('--') && a !== flag('--format') && a !== flag('--scene'));
24
+ if (!file) {
25
+ console.error('usage: npx beatsheet frames videos/<name>.video.json [--format 4:5] [--scene <id>] [--backwards]');
26
+ process.exit(2);
27
+ }
28
+ const only = flag('--scene');
29
+ const backwards = args.includes('--backwards');
30
+
31
+ const video = await loadVideo(file);
32
+ const format = (flag('--format') ?? video.doc.formats[0] ?? '16:9') as FormatId;
33
+ const server = await videoServer(video);
34
+
35
+ interface Pass {
36
+ hashes: Map<number, string>;
37
+ ms: Map<number, number>;
38
+ scenes: { id: string; type: string; frames: number[] }[];
39
+ }
40
+
41
+ async function pass(browser: Awaited<ReturnType<typeof launchBrowser>>, order: 'forwards' | 'backwards'): Promise<Pass> {
42
+ const bp = await openPlayer(browser, server.url, video.file, format);
43
+ try {
44
+ const { fps, frameCount } = bp.timeline;
45
+ const scenes = bp.timeline.scenes
46
+ .filter((s) => !only || s.id === only)
47
+ .map((s) => {
48
+ const frames: number[] = [];
49
+ // Frame 0 is the poster frame, not the first scene's.
50
+ for (let i = Math.max(1, Math.ceil(s.start * fps - 1e-6)); i < Math.min(frameCount, Math.ceil(s.end * fps - 1e-6)); i++) frames.push(i);
51
+ return { id: s.id, type: s.type, frames };
52
+ });
53
+ const all = scenes.flatMap((s) => s.frames);
54
+ if (order === 'backwards') all.reverse();
55
+ const hashes = new Map<number, string>();
56
+ const ms = new Map<number, number>();
57
+ for (const i of all) {
58
+ const from = performance.now();
59
+ await bp.seek(frameTime(i, bp.timeline));
60
+ const png = await bp.page.screenshot({ type: 'png' });
61
+ ms.set(i, performance.now() - from);
62
+ hashes.set(i, createHash('sha1').update(png).digest('hex'));
63
+ }
64
+ return { hashes, ms, scenes };
65
+ } finally {
66
+ await bp.close();
67
+ }
68
+ }
69
+
70
+ let failed = false;
71
+ try {
72
+ const first = await launchBrowser();
73
+ let a: Pass;
74
+ let back: Pass | null = null;
75
+ try {
76
+ a = await pass(first, 'forwards');
77
+ if (backwards) back = await pass(first, 'backwards');
78
+ } finally {
79
+ await first.close();
80
+ }
81
+ const second = await launchBrowser();
82
+ let b: Pass;
83
+ try {
84
+ b = await pass(second, 'forwards');
85
+ } finally {
86
+ await second.close();
87
+ }
88
+ if (a.scenes.length === 0) throw new Error(only ? `no scene "${only}" in ${video.file}` : `${video.file} has no scenes`);
89
+ console.log(`${video.file} · ${format} · ${a.hashes.size} frames, each rendered twice${backwards ? ' and once backwards' : ''}`);
90
+ for (const s of a.scenes) {
91
+ const differ = (other: Pass): number[] => s.frames.filter((i) => a.hashes.get(i) !== other.hashes.get(i));
92
+ const mean = s.frames.reduce((sum, i) => sum + (a.ms.get(i) ?? 0), 0) / Math.max(1, s.frames.length);
93
+ const again = differ(b);
94
+ const reversed = back ? differ(back) : [];
95
+ if (again.length || reversed.length) failed = true;
96
+ const list = (frames: number[]): string => (frames.length ? `${frames.length} differ (frames ${frames.slice(0, 8).join(', ')}${frames.length > 8 ? ', …' : ''})` : 'identical');
97
+ console.log(
98
+ ` ${s.id.padEnd(18)} ${s.type.padEnd(16)} ${String(s.frames.length).padStart(4)} frames ${mean.toFixed(0).padStart(4)} ms/frame second run: ${list(again)}${back ? ` backwards: ${list(reversed)}` : ''}`,
99
+ );
100
+ }
101
+ console.log(failed ? 'failed: a run differs from the first (the same file must give the same frames, in any order)' : `ok: ${back ? 'all three' : 'both'} runs gave the same frames`);
102
+ } finally {
103
+ await server.close();
104
+ }
105
+ process.exit(failed ? 1 : 0);