@skilldeck/studio 0.0.0-stage → 0.1.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.
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env node
2
+ // studio / init.mjs
3
+ //
4
+ // Copy the starter composition (runtime included) to a new file, optionally
5
+ // setting its size and frame rate and embedding an SRT/VTT caption file.
6
+ //
7
+ // node init.mjs [path] [--width N] [--height N] [--fps N] [--captions file] [--force] [--json]
8
+ //
9
+ // `path` defaults to ./composition.html; a directory gets composition.html inside it.
10
+ // Exit 0 on success, 1 when the target exists (use --force), 2 on bad usage.
11
+
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import { fileURLToPath, pathToFileURL } from 'node:url'
15
+ import { parseArgs } from 'node:util'
16
+
17
+ export const TEMPLATE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'templates', 'composition.html')
18
+
19
+ const HELP = `init: start a new composition from the studio template
20
+
21
+ node init.mjs [path] [options]
22
+
23
+ --width <px> composition width (default 1920)
24
+ --height <px> composition height (default 1080)
25
+ --fps <n> frames per second (default 30)
26
+ --captions <file> embed an .srt or .vtt file as the caption track
27
+ --force overwrite an existing file
28
+ --json machine-readable result
29
+
30
+ Exit codes: 0 ok, 1 target exists, 2 usage error.
31
+ `
32
+
33
+ /** Apply size, fps and captions to the template HTML. Pure. */
34
+ export function customize(html, { width, height, fps, captions, captionsFormat } = {}) {
35
+ let out = html
36
+ const setAttr = (name, value) => {
37
+ if (value === undefined) return
38
+ out = out.replace(new RegExp(`(<[^>]*\\bdata-composition\\b[^>]*\\b${name}=")[^"]*(")`), `$1${value}$2`)
39
+ }
40
+ setAttr('data-width', width)
41
+ setAttr('data-height', height)
42
+ setAttr('data-fps', fps)
43
+ if (captions !== undefined) {
44
+ const fmt = captionsFormat ?? (/^?WEBVTT/.test(captions) ? 'vtt' : 'srt')
45
+ const body = captions.replace(/\r\n?/g, '\n').replace(/^/, '').trim().replace(/<\/script/gi, '<\\/script')
46
+ out = out.replace(/<script type="text\/plain" data-captions="[^"]*">[\s\S]*?<\/script>/, () => `<script type="text/plain" data-captions="${fmt}">\n${body}\n</script>`)
47
+ }
48
+ return out
49
+ }
50
+
51
+ /** Write a new composition. Returns { file, created }. Throws with .exitCode on failure. */
52
+ export function initComposition(target = 'composition.html', opts = {}) {
53
+ let file = path.resolve(target)
54
+ if ((fs.existsSync(file) && fs.statSync(file).isDirectory()) || !path.extname(file)) file = path.join(file, 'composition.html')
55
+ if (fs.existsSync(file) && !opts.force) throw Object.assign(new Error(`${file} already exists (use --force to overwrite)`), { exitCode: 1 })
56
+ let captions
57
+ if (opts.captions) {
58
+ if (!fs.existsSync(opts.captions)) throw Object.assign(new Error(`captions file not found: ${opts.captions}`), { exitCode: 2 })
59
+ captions = fs.readFileSync(opts.captions, 'utf8')
60
+ }
61
+ const ext = opts.captions ? path.extname(opts.captions).toLowerCase() : ''
62
+ const html = customize(fs.readFileSync(TEMPLATE, 'utf8'), {
63
+ width: opts.width,
64
+ height: opts.height,
65
+ fps: opts.fps,
66
+ captions,
67
+ captionsFormat: ext === '.vtt' ? 'vtt' : ext === '.srt' ? 'srt' : undefined,
68
+ })
69
+ fs.mkdirSync(path.dirname(file), { recursive: true })
70
+ fs.writeFileSync(file, html)
71
+ return { file, created: true }
72
+ }
73
+
74
+ function main(argv) {
75
+ let parsed
76
+ try {
77
+ parsed = parseArgs({
78
+ args: argv,
79
+ allowPositionals: true,
80
+ options: {
81
+ width: { type: 'string' },
82
+ height: { type: 'string' },
83
+ fps: { type: 'string' },
84
+ captions: { type: 'string' },
85
+ force: { type: 'boolean', default: false },
86
+ json: { type: 'boolean', default: false },
87
+ help: { type: 'boolean', short: 'h', default: false },
88
+ },
89
+ })
90
+ } catch (e) {
91
+ process.stderr.write(`init: ${e.message}\n\n${HELP}`)
92
+ return 2
93
+ }
94
+ const { values: v, positionals } = parsed
95
+ if (v.help) {
96
+ process.stdout.write(HELP)
97
+ return 0
98
+ }
99
+ const opts = { force: v.force, captions: v.captions }
100
+ for (const k of ['width', 'height', 'fps']) {
101
+ if (v[k] === undefined) continue
102
+ const n = Number(v[k])
103
+ if (!Number.isInteger(n) || n <= 0) {
104
+ process.stderr.write(`init: --${k} must be a positive whole number\n`)
105
+ return 2
106
+ }
107
+ opts[k] = n
108
+ }
109
+ try {
110
+ const r = initComposition(positionals[0], opts)
111
+ if (v.json) console.log(JSON.stringify(r))
112
+ else console.log(`created ${r.file}\nnext: open it in a browser to preview, then lint and snapshot it`)
113
+ return 0
114
+ } catch (e) {
115
+ process.stderr.write(`init: ${e.message}\n`)
116
+ return e.exitCode ?? 1
117
+ }
118
+ }
119
+
120
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) process.exitCode = main(process.argv.slice(2))
@@ -0,0 +1,350 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Studio composition</title>
7
+ <style>
8
+ /* ---- studio base: keep these rules ---------------------------------- */
9
+ html, body { margin: 0; background: #000; }
10
+ [data-composition] { position: relative; overflow: hidden; contain: strict; }
11
+ [data-scene] { position: absolute; inset: 0; visibility: hidden; }
12
+ [data-scene][data-active] { visibility: visible; }
13
+
14
+ /* ---- theme ----------------------------------------------------------- */
15
+ /* --u is 1% of the composition height, set by the runtime: size everything in it. */
16
+ :root { --bg: #0e1015; --fg: #f3efe6; --muted: #8c909b; --accent: #ff6a3d; --accent-2: #3dd6c6; }
17
+ [data-composition] {
18
+ background: var(--bg); color: var(--fg);
19
+ font-family: ui-sans-serif, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
20
+ }
21
+
22
+ /* ---- scene 1: title card -------------------------------------------- */
23
+ #title { display: grid; place-content: center; text-align: center; }
24
+ #title .kicker { font-size: calc(var(--u) * 2.4); letter-spacing: .3em; text-transform: uppercase; color: var(--accent);
25
+ animation: rise .6s cubic-bezier(.2,.7,.2,1) .15s both; }
26
+ #title h1 { margin: calc(var(--u) * 2) 0 0; font-size: calc(var(--u) * 11); line-height: .95; font-weight: 800; letter-spacing: -.02em;
27
+ animation: rise .7s cubic-bezier(.2,.7,.2,1) .3s both; }
28
+ #title .rule { height: calc(var(--u) * .5); width: calc(var(--u) * 18); margin: calc(var(--u) * 4) auto 0; background: var(--accent);
29
+ transform-origin: left; animation: grow .6s cubic-bezier(.6,0,.2,1) .6s both; }
30
+
31
+ /* ---- scene 2: data chart reveal ------------------------------------- */
32
+ #chart { padding: calc(var(--u) * 10) calc(var(--u) * 14); box-sizing: border-box; }
33
+ #chart h2 { margin: 0; font-size: calc(var(--u) * 5); font-weight: 700; animation: rise .5s ease-out both; }
34
+ #chart .bars { display: flex; align-items: flex-end; gap: calc(var(--u) * 3); height: calc(var(--u) * 52); margin-top: calc(var(--u) * 6); }
35
+ #chart .bar { flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; height: 100%; }
36
+ #chart .fill { width: 100%; height: var(--h); background: var(--accent-2); border-radius: calc(var(--u) * .6) calc(var(--u) * .6) 0 0;
37
+ transform-origin: bottom; animation: grow-y .8s cubic-bezier(.2,.7,.2,1) calc(.3s + var(--i) * .12s) both; }
38
+ #chart .bar:last-child .fill { background: var(--accent); }
39
+ #chart .value { font-size: calc(var(--u) * 3.4); font-weight: 700; margin-bottom: calc(var(--u) * 1); font-variant-numeric: tabular-nums;
40
+ animation: fade .3s ease-out calc(.3s + var(--i) * .12s) both; }
41
+ #chart .label { font-size: calc(var(--u) * 2.2); color: var(--muted); margin-top: calc(var(--u) * 1.4); }
42
+
43
+ /* ---- scene 3: end card ----------------------------------------------- */
44
+ #end { display: grid; place-content: center; text-align: center; }
45
+ #end p { margin: 0; font-size: calc(var(--u) * 7); font-weight: 800; animation: zoom-in .6s cubic-bezier(.2,.7,.2,1) both; }
46
+ #end small { display: block; margin-top: calc(var(--u) * 2); font-size: calc(var(--u) * 2.6); color: var(--muted); animation: fade .5s ease-out .35s both; }
47
+
48
+ /* ---- caption overlay (track 1) --------------------------------------- */
49
+ #captions { pointer-events: none; }
50
+ [data-caption-target] {
51
+ position: absolute; left: 50%; bottom: calc(var(--u) * 7); transform: translateX(-50%); max-width: 80%; margin: 0;
52
+ padding: calc(var(--u) * 1) calc(var(--u) * 2.2); border-radius: calc(var(--u) * .8);
53
+ background: rgba(0,0,0,.72); color: #fff; font-size: calc(var(--u) * 3.6); line-height: 1.25; text-align: center; white-space: pre-line;
54
+ }
55
+ [data-caption-target]:empty { display: none; }
56
+
57
+ @keyframes rise { from { opacity: 0; transform: translateY(calc(var(--u) * 4)); } to { opacity: 1; transform: none; } }
58
+ @keyframes grow { from { transform: scaleX(0); } to { transform: scaleX(1); } }
59
+ @keyframes grow-y { from { transform: scaleY(0); } to { transform: scaleY(1); } }
60
+ @keyframes zoom-in { from { opacity: 0; transform: scale(.92); } to { opacity: 1; transform: none; } }
61
+ @keyframes fade { from { opacity: 0; } to { opacity: 1; } }
62
+ </style>
63
+
64
+ <!-- studio runtime: the seekable clock. Do not edit; render.mjs drives window.__studio.seek(t). -->
65
+ <script data-studio-runtime>
66
+ (function () {
67
+ 'use strict'
68
+ var EPS = 1e-6
69
+ var hooks = []
70
+ var root = null
71
+ var scenes = []
72
+ var cues = []
73
+ var resolveReady, rejectReady
74
+ var ready = new Promise(function (res, rej) { resolveReady = res; rejectReady = rej })
75
+
76
+ function clamp01(x) { return x < 0 ? 0 : x > 1 ? 1 : x }
77
+ var ease = {
78
+ linear: function (x) { return x },
79
+ inCubic: function (x) { return x * x * x },
80
+ outCubic: function (x) { return 1 - Math.pow(1 - x, 3) },
81
+ inOutCubic: function (x) { return x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2 }
82
+ }
83
+ // value at time t, moving from v0 to v1 between t0 and t1
84
+ function interp(t, t0, t1, v0, v1, fn) {
85
+ var p = clamp01((t - t0) / ((t1 - t0) || 1))
86
+ return v0 + (v1 - v0) * (fn || ease.linear)(p)
87
+ }
88
+ // seeded PRNG (mulberry32): same seed, same sequence, every render
89
+ function random(seed) {
90
+ var a = (seed >>> 0) || 1
91
+ return function () {
92
+ a = (a + 0x6D2B79F5) >>> 0
93
+ var t = a
94
+ t = Math.imul(t ^ (t >>> 15), t | 1)
95
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
96
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
97
+ }
98
+ }
99
+
100
+ function parseTime(s) {
101
+ var m = /^(?:(\d+):)?(\d{1,2}):(\d{2})[.,](\d{1,3})$/.exec(String(s).trim())
102
+ if (!m) return NaN
103
+ return (+(m[1] || 0)) * 3600 + (+m[2]) * 60 + (+m[3]) + (+(m[4] + '00').slice(0, 3)) / 1000
104
+ }
105
+ function parseCaptions(text) {
106
+ var out = []
107
+ String(text).replace(/\r\n?/g, '\n').trim().split(/\n[ \t]*\n/).forEach(function (block) {
108
+ var lines = block.split('\n')
109
+ var i = -1
110
+ for (var k = 0; k < lines.length; k++) if (lines[k].indexOf('-->') >= 0) { i = k; break }
111
+ if (i < 0) return
112
+ var parts = lines[i].split('-->')
113
+ var start = parseTime(parts[0])
114
+ var end = parseTime((parts[1] || '').trim().split(/\s+/)[0])
115
+ if (isFinite(start) && isFinite(end) && end > start) {
116
+ out.push({ start: start, end: end, text: lines.slice(i + 1).join('\n').replace(/<[^>]+>/g, '').trim() })
117
+ }
118
+ })
119
+ return out
120
+ }
121
+
122
+ function sceneOf(el) { return el && el.closest ? el.closest('[data-scene]') : null }
123
+ function startOf(scene) { return scene ? +scene.getAttribute('data-start') || 0 : 0 }
124
+
125
+ function info(t) {
126
+ var cfg = studio.config
127
+ var byId = {}
128
+ scenes.forEach(function (s) {
129
+ var local = t - s.start
130
+ byId[s.id] = { active: local >= -EPS && local < s.duration - EPS, local: local, progress: clamp01(local / s.duration) }
131
+ })
132
+ return { t: t, frame: Math.round(t * cfg.fps), fps: cfg.fps, duration: cfg.duration, progress: clamp01(t / cfg.duration), scenes: byId }
133
+ }
134
+
135
+ function seekMedia(t) {
136
+ var waits = []
137
+ root.querySelectorAll('video, audio').forEach(function (m) {
138
+ var local = Math.max(0, t - startOf(sceneOf(m))) + (+m.getAttribute('data-offset') || 0)
139
+ if (m.duration && isFinite(m.duration)) local = m.hasAttribute('loop') ? local % m.duration : Math.min(local, m.duration - 0.001)
140
+ m.pause()
141
+ if (Math.abs(m.currentTime - local) < 0.0005) return
142
+ waits.push(new Promise(function (res) {
143
+ var timer
144
+ function done() { clearTimeout(timer); m.removeEventListener('seeked', done); res() }
145
+ m.addEventListener('seeked', done)
146
+ timer = setTimeout(done, 3000)
147
+ m.currentTime = local
148
+ }))
149
+ })
150
+ return Promise.all(waits)
151
+ }
152
+
153
+ function nextFrame() { return new Promise(function (res) { requestAnimationFrame(function () { requestAnimationFrame(res) }) }) }
154
+
155
+ // The clock. Everything visible must be a function of t.
156
+ function seek(t) {
157
+ var cfg = studio.config
158
+ t = Math.min(Math.max(+t || 0, 0), cfg.duration)
159
+ studio.time = t
160
+ root.style.setProperty('--t', String(t))
161
+ scenes.forEach(function (s) {
162
+ var local = t - s.start
163
+ var on = local >= -EPS && local < s.duration - EPS
164
+ if (on) s.el.setAttribute('data-active', '')
165
+ else s.el.removeAttribute('data-active')
166
+ s.el.style.setProperty('--scene-t', String(Math.max(0, local)))
167
+ s.el.style.setProperty('--scene-progress', String(clamp01(local / s.duration)))
168
+ })
169
+ var cue = null
170
+ for (var i = 0; i < cues.length; i++) if (t >= cues[i].start - EPS && t < cues[i].end - EPS) { cue = cues[i]; break }
171
+ root.querySelectorAll('[data-caption-target]').forEach(function (el) {
172
+ var text = cue ? cue.text : ''
173
+ if (el.textContent !== text) el.textContent = text
174
+ })
175
+ var state = info(t)
176
+ hooks.forEach(function (fn) { fn(t, state) })
177
+ // pause every CSS animation / transition / WAAPI animation and set its time from t
178
+ document.getAnimations().forEach(function (a) {
179
+ var target = a.effect && a.effect.target
180
+ if (!target || !root.contains(target)) return
181
+ a.pause()
182
+ a.currentTime = Math.max(0, t - startOf(sceneOf(target))) * 1000
183
+ })
184
+ return seekMedia(t).then(function () { return document.fonts.ready }).then(nextFrame).then(function () { return t })
185
+ }
186
+
187
+ var studio = window.__studio = {
188
+ version: 1,
189
+ config: null,
190
+ scenes: scenes,
191
+ cues: cues,
192
+ time: 0,
193
+ ready: ready,
194
+ seek: seek,
195
+ onSeek: function (fn) { hooks.push(fn); return studio },
196
+ random: random,
197
+ ease: ease,
198
+ interp: interp,
199
+ clamp01: clamp01,
200
+ parseCaptions: parseCaptions
201
+ }
202
+
203
+ function waitForMedia() {
204
+ var list = []
205
+ root.querySelectorAll('img').forEach(function (img) { if (img.decode) list.push(img.decode().catch(function () {})) })
206
+ root.querySelectorAll('video, audio').forEach(function (m) {
207
+ if (m.readyState >= 2) return
208
+ list.push(new Promise(function (res) {
209
+ m.addEventListener('loadeddata', res, { once: true })
210
+ m.addEventListener('error', res, { once: true })
211
+ setTimeout(res, 5000)
212
+ }))
213
+ })
214
+ return Promise.all(list)
215
+ }
216
+
217
+ function previewControls() {
218
+ var cfg = studio.config
219
+ var bar = document.createElement('div')
220
+ bar.style.cssText = 'position:fixed;left:0;right:0;bottom:0;display:flex;gap:12px;align-items:center;padding:10px 16px;background:#111;color:#ddd;font:13px ui-monospace,monospace;z-index:2147483647'
221
+ bar.innerHTML = '<button type="button">play</button><input type="range" min="0" step="1" style="flex:1"><span></span>'
222
+ var btn = bar.children[0], range = bar.children[1], label = bar.children[2]
223
+ var frames = Math.round(cfg.duration * cfg.fps)
224
+ range.max = String(frames - 1)
225
+ var playing = false, busy = false, t0 = 0, from = 0
226
+ function show(t) { label.textContent = t.toFixed(2) + 's / ' + cfg.duration + 's f' + Math.round(t * cfg.fps) }
227
+ function go(t) { busy = true; seek(t).then(function () { busy = false; show(t); range.value = String(Math.round(t * cfg.fps)) }) }
228
+ range.addEventListener('input', function () { playing = false; btn.textContent = 'play'; go(+range.value / cfg.fps) })
229
+ btn.addEventListener('click', function () {
230
+ playing = !playing
231
+ btn.textContent = playing ? 'pause' : 'play'
232
+ if (playing) { from = studio.time >= cfg.duration - 1 / cfg.fps ? 0 : studio.time; t0 = performance.now(); requestAnimationFrame(tick) }
233
+ })
234
+ function tick(now) {
235
+ if (!playing) return
236
+ var t = from + (now - t0) / 1000
237
+ if (t >= cfg.duration) { t = 0; from = 0; t0 = now }
238
+ if (!busy) go(Math.floor(t * cfg.fps) / cfg.fps)
239
+ requestAnimationFrame(tick)
240
+ }
241
+ document.body.appendChild(bar)
242
+ function fit() {
243
+ var s = Math.min(window.innerWidth / cfg.width, (window.innerHeight - bar.offsetHeight) / cfg.height, 1)
244
+ root.style.transformOrigin = '0 0'
245
+ root.style.transform = 'scale(' + s + ')'
246
+ }
247
+ window.addEventListener('resize', fit)
248
+ fit()
249
+ show(0)
250
+ }
251
+
252
+ function init() {
253
+ root = document.querySelector('[data-composition]')
254
+ if (!root) return rejectReady(new Error('no [data-composition] root element'))
255
+ var cfg = {
256
+ width: +root.getAttribute('data-width'),
257
+ height: +root.getAttribute('data-height'),
258
+ fps: +root.getAttribute('data-fps'),
259
+ duration: +root.getAttribute('data-duration')
260
+ }
261
+ studio.config = cfg
262
+ root.style.width = cfg.width + 'px'
263
+ root.style.height = cfg.height + 'px'
264
+ root.style.setProperty('--u', (cfg.height / 100) + 'px')
265
+ root.querySelectorAll('[data-scene]').forEach(function (el, i) {
266
+ scenes.push({
267
+ id: el.id || el.getAttribute('data-scene') || 'scene#' + (i + 1),
268
+ el: el,
269
+ start: +el.getAttribute('data-start') || 0,
270
+ duration: +el.getAttribute('data-duration') || 0,
271
+ track: +el.getAttribute('data-track') || 0
272
+ })
273
+ })
274
+ document.querySelectorAll('script[data-captions]').forEach(function (s) {
275
+ parseCaptions(s.textContent).forEach(function (c) { cues.push(c) })
276
+ })
277
+ cues.sort(function (a, b) { return a.start - b.start })
278
+ document.fonts.ready.then(waitForMedia).then(function () { return seek(0) }).then(function () {
279
+ if (!window.__STUDIO_RENDER__) previewControls()
280
+ resolveReady(cfg)
281
+ }, rejectReady)
282
+ }
283
+
284
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init)
285
+ else init()
286
+ })()
287
+ </script>
288
+ </head>
289
+ <body>
290
+ <main id="comp" data-composition data-width="1920" data-height="1080" data-fps="30" data-duration="6">
291
+
292
+ <section data-scene id="title" data-start="0" data-duration="2">
293
+ <div>
294
+ <div class="kicker">Release 2.0</div>
295
+ <h1>Your headline<br>goes here</h1>
296
+ <div class="rule"></div>
297
+ </div>
298
+ </section>
299
+
300
+ <section data-scene id="chart" data-start="2" data-duration="2.5">
301
+ <h2>Weekly active teams</h2>
302
+ <div class="bars">
303
+ <div class="bar" style="--i:0"><div class="value" data-count="1200">0</div><div class="fill" style="--h:24%"></div><div class="label">Jan</div></div>
304
+ <div class="bar" style="--i:1"><div class="value" data-count="2100">0</div><div class="fill" style="--h:42%"></div><div class="label">Feb</div></div>
305
+ <div class="bar" style="--i:2"><div class="value" data-count="2900">0</div><div class="fill" style="--h:58%"></div><div class="label">Mar</div></div>
306
+ <div class="bar" style="--i:3"><div class="value" data-count="4800">0</div><div class="fill" style="--h:96%"></div><div class="label">Apr</div></div>
307
+ </div>
308
+ </section>
309
+
310
+ <section data-scene id="end" data-start="4.5" data-duration="1.5">
311
+ <div>
312
+ <p>Try it today</p>
313
+ <small>example.com/start</small>
314
+ </div>
315
+ </section>
316
+
317
+ <!-- Overlays live on track 1 so they can span the main scenes without overlapping them. -->
318
+ <section data-scene id="captions" data-track="1" data-start="0" data-duration="6">
319
+ <p data-caption-target></p>
320
+ </section>
321
+ </main>
322
+
323
+ <!-- Captions: paste SRT or WebVTT here (or run `studio-skills init --captions file.srt`). -->
324
+ <script type="text/plain" data-captions="vtt">
325
+ WEBVTT
326
+
327
+ 00:00.300 --> 00:01.900
328
+ Here is what changed this release.
329
+
330
+ 00:02.200 --> 00:04.300
331
+ Teams using it grew four times since January.
332
+
333
+ 00:04.600 --> 00:05.900
334
+ Try it today.
335
+ </script>
336
+
337
+ <script>
338
+ // Scene code. Everything is a pure function of the seek time t: no timers, no wall clock.
339
+ var counters = document.querySelectorAll('#chart [data-count]')
340
+ __studio.onSeek(function (t, s) {
341
+ var local = s.scenes.chart.local
342
+ counters.forEach(function (el, i) {
343
+ var start = 0.3 + i * 0.12
344
+ var value = __studio.interp(local, start, start + 0.8, 0, +el.dataset.count, __studio.ease.outCubic)
345
+ el.textContent = Math.round(value).toLocaleString('en-US')
346
+ })
347
+ })
348
+ </script>
349
+ </body>
350
+ </html>
@@ -0,0 +1,102 @@
1
+ ---
2
+ name: video-render
3
+ description: Use when turning an HTML composition into an MP4, WebM, MOV or GIF, or when a rendered video flickers, drifts, shows black frames or differs between renders; covers lint, snapshot and frame-by-frame render with local headless Chrome over CDP and ffmpeg, nothing uploaded.
4
+ ---
5
+
6
+ # Video Render
7
+
8
+ Rendering is the expensive, slow step, and its failures (a black frame at 4.2s, a font that pops in, a counter that jitters) are found by watching the whole clip. So render last. Lint catches timeline and determinism bugs in milliseconds, snapshots show the real pixels at a handful of times in seconds, and only then does the full frame-by-frame render run.
9
+
10
+ Announce: "Using video-render to lint, snapshot and render <file>."
11
+
12
+ ## The Rule
13
+
14
+ ```
15
+ Lint clean, snapshots reviewed, then render. Never render to find out.
16
+ ```
17
+
18
+ **Script location.** The scripts live in `${CLAUDE_SKILL_DIR}/scripts/`. If `CLAUDE_SKILL_DIR` is not set, use the directory holding this SKILL.md. Below, `$S` is that folder. Node 22+, no dependencies; the same commands are available as `npx @skilldeck/studio <command>`. Everything runs locally: a headless Chrome on 127.0.0.1 and ffmpeg. Nothing is uploaded.
19
+
20
+ Every script takes `--json` and uses the same exit codes: `0` ok, `1` findings or failure, `2` usage or environment error.
21
+
22
+ ## Checklist
23
+
24
+ ```
25
+ - [ ] 1. doctor: Node 22, Chrome, ffmpeg found
26
+ - [ ] 2. lint: zero errors; warnings read and either fixed or accepted
27
+ - [ ] 3. snapshot: each scene's midpoint looked at, plus any tricky moment
28
+ - [ ] 4. render: a short range first, then the full clip
29
+ - [ ] 5. Verified the output: duration, frame count, size, a final look
30
+ ```
31
+
32
+ ## 1. Check the machine
33
+
34
+ ```bash
35
+ node $S/scripts/doctor.mjs # Node, Chrome (or CHROME_PATH), ffmpeg + encoders
36
+ node $S/scripts/doctor.mjs --launch # also start headless Chrome and round-trip CDP
37
+ ```
38
+
39
+ Exit 1 means frames can render but ffmpeg is missing: `render` will write PNGs and print the exact ffmpeg command. Exit 2 means install Chrome/Chromium (or set `CHROME_PATH`) or Node 22.
40
+
41
+ ## 2. Lint
42
+
43
+ ```bash
44
+ node $S/scripts/lint-comp.mjs video/launch.html # --strict fails on warnings too
45
+ ```
46
+
47
+ | Rule | Severity | Fix |
48
+ |---|---|---|
49
+ | `gap`, `overlap`, `scene-past-end`, `no-scenes` | error | Retime scenes; overlays go on `data-track="1"` |
50
+ | `missing-asset`, `absolute-asset` | error | Put the file next to the HTML; use a relative path |
51
+ | `remote-asset`, `remote-font`, `network` | error | Download it; inline data as JSON |
52
+ | `math-random`, `wall-clock`, `timer-animation` (setInterval) | error | `__studio.random(seed)`, derive from `t`, `onSeek` |
53
+ | `no-root`, `root-config`, `no-clock`, `caption-parse` | error | Follow the contract in [[video-compose]] |
54
+ | `off-frame`, `font-not-preloaded`, `css-transition`, `raf-animation`, `autoplay`, `caption-*`, `odd-dimensions` | warn | Usually fix; each message says how |
55
+
56
+ ## 3. Snapshot
57
+
58
+ ```bash
59
+ node $S/scripts/render.mjs snapshot video/launch.html # t=0 + every scene midpoint
60
+ node $S/scripts/render.mjs snapshot video/launch.html --at 2.4,2.5,7.4 --out snaps/
61
+ ```
62
+
63
+ Open the PNGs and look. Check the frames either side of every cut, the moment a counter or zoom lands, and the last frame. A snapshot is a real render of that frame, so if it is right, the video is right at that time.
64
+
65
+ ## 4. Render
66
+
67
+ ```bash
68
+ node $S/scripts/render.mjs render video/launch.html --from 2 --to 4 --out draft.mp4 # a slice first
69
+ node $S/scripts/render.mjs render video/launch.html --out launch.mp4 --audio music.m4a
70
+ ```
71
+
72
+ For each frame `i` it calls `__studio.seek(i / fps)`, waits for media, fonts and paint, and captures a PNG into `<out>_frames/`. Then it runs ffmpeg (H.264 `yuv420p`, CRF 18, `+faststart` for `.mp4`; VP9 for `.webm`; ProRes for `.mov`; palette GIF for `.gif`) and deletes the frames unless `--keep-frames`. Without ffmpeg, or with `--no-encode`, it prints the command, ready to paste.
73
+
74
+ Other flags: `--fps` overrides `data-fps`, `--scale 2` renders at 2x pixel density, `--crf` sets quality. Page exceptions, console errors and failed requests during the render are reported as `issues`; treat any as a bug in the composition.
75
+
76
+ ## 5. Verify
77
+
78
+ ```bash
79
+ ffprobe -v error -show_entries stream=width,height,nb_frames,r_frame_rate -of compact launch.mp4
80
+ ```
81
+
82
+ Frame count should equal `round(fps * duration)` for a full render. Watch it once end to end.
83
+
84
+ ## Output
85
+
86
+ ```
87
+ Rendered: launch.mp4 1920x1080 @ 30fps, 9.0s, 270 frames, 41s render
88
+ Lint: 0 errors, 1 warning (off-frame: end starts at 7.55s, accepted)
89
+ Snapshots checked: 0, 1.25, 5, 8.25 (+ cuts at 2.5, 7.5)
90
+ Issues during render: none
91
+ ```
92
+
93
+ ## Red flags
94
+
95
+ | Thought | Reality |
96
+ |---|---|
97
+ | "Skip lint, rendering will show problems." | A gap or `Math.random` costs a full render to find and seconds to lint. |
98
+ | "The snapshot is just a preview." | It is the same seek and capture as the render. Trust it, and look at it. |
99
+ | "Render the whole thing to check one moment." | `snapshot --at` or `render --from/--to` that moment. |
100
+ | "Two renders differ slightly, that's normal." | It is not. Something reads wall-clock time, randomness or the network. Lint it. |
101
+ | "ffmpeg is missing, so I can't finish." | Frames are written and the exact command is printed. Hand it to the user. |
102
+ | "I'll upload it to a cloud renderer." | Never. Everything runs locally; the composition and its assets stay on this machine. |
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env node
2
+ // studio / doctor.mjs
3
+ //
4
+ // Check that this machine can render compositions: Node 22+ (global WebSocket),
5
+ // a local Chrome/Chromium, and ffmpeg with an H.264 encoder. --launch also starts
6
+ // headless Chrome and round-trips a CDP command to prove the whole path works.
7
+ //
8
+ // node doctor.mjs [--launch] [--json]
9
+ //
10
+ // Exit 0 when everything is ready, 1 when frames can render but ffmpeg is missing
11
+ // (render prints the command instead of encoding), 2 when rendering cannot work
12
+ // (Node too old, no Chrome, or the launch check failed).
13
+
14
+ import { spawnSync } from 'node:child_process'
15
+ import { pathToFileURL } from 'node:url'
16
+ import { chromeVersion, findChrome, withChrome } from './lib/cdp.mjs'
17
+ import { which } from './render.mjs'
18
+
19
+ const HELP = `doctor: can this machine render studio compositions?
20
+
21
+ node doctor.mjs [--launch] [--json]
22
+
23
+ --launch also start headless Chrome and talk CDP to it
24
+ --json machine-readable output
25
+
26
+ Exit codes: 0 ready, 1 ffmpeg missing (frames only), 2 cannot render.
27
+ `
28
+
29
+ /** Node 22+ is required for the global WebSocket the CDP client uses. */
30
+ export function checkNode(version = process.versions.node, hasWebSocket = typeof WebSocket === 'function') {
31
+ const major = Number(String(version).split('.')[0])
32
+ const ok = major >= 22 && hasWebSocket
33
+ return { name: 'node', ok, level: ok ? 'ok' : 'fatal', detail: `v${version}${hasWebSocket ? '' : ' (no global WebSocket)'}`, fix: ok ? undefined : 'install Node.js 22 or newer' }
34
+ }
35
+
36
+ export function checkChrome(env = process.env) {
37
+ const found = findChrome({ env })
38
+ if (!found.path) return { name: 'chrome', ok: false, level: 'fatal', detail: found.error, fix: 'install Google Chrome or Chromium, or set CHROME_PATH to its executable' }
39
+ const version = chromeVersion(found.path)
40
+ return { name: 'chrome', ok: true, level: 'ok', detail: `${version ?? 'version unknown'} at ${found.path}${found.source === 'CHROME_PATH' ? ' (CHROME_PATH)' : ''}`, path: found.path }
41
+ }
42
+
43
+ export function checkFfmpeg(env = process.env) {
44
+ const bin = which('ffmpeg', env)
45
+ if (!bin) return { name: 'ffmpeg', ok: false, level: 'warn', detail: 'not on PATH: render writes PNG frames and prints the ffmpeg command', fix: 'brew install ffmpeg | apt install ffmpeg | winget install ffmpeg' }
46
+ const v = spawnSync(bin, ['-hide_banner', '-version'], { encoding: 'utf8' })
47
+ const version = (v.stdout || '').split('\n')[0].replace(/^ffmpeg version\s*/, '').split(' ')[0] || 'unknown'
48
+ const enc = spawnSync(bin, ['-hide_banner', '-encoders'], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 })
49
+ const encoders = ['libx264', 'libvpx-vp9', 'prores_ks'].filter((e) => new RegExp(`\\b${e}\\b`).test(enc.stdout || ''))
50
+ const ok = encoders.includes('libx264')
51
+ return { name: 'ffmpeg', ok, level: ok ? 'ok' : 'warn', detail: `${version} at ${bin}; encoders: ${encoders.join(', ') || 'none of libx264/libvpx-vp9/prores_ks'}`, fix: ok ? undefined : 'install an ffmpeg build with libx264 for .mp4 output' }
52
+ }
53
+
54
+ export async function checkLaunch(chromePath) {
55
+ try {
56
+ const product = await withChrome(async ({ cdp }) => (await cdp.send('Browser.getVersion')).product, { chromePath, timeoutMs: 30000 })
57
+ return { name: 'launch', ok: true, level: 'ok', detail: `headless ${product} answered over CDP` }
58
+ } catch (e) {
59
+ return { name: 'launch', ok: false, level: 'fatal', detail: e.message.split('\n')[0], fix: 'run with CHROME_PATH pointing at a working Chrome; on Linux containers you may need --no-sandbox via a wrapper script' }
60
+ }
61
+ }
62
+
63
+ /** Exit status from a list of checks: 2 if any fatal, 1 if any warning, else 0. */
64
+ export function statusOf(checks) {
65
+ if (checks.some((c) => !c.ok && c.level === 'fatal')) return 2
66
+ if (checks.some((c) => !c.ok)) return 1
67
+ return 0
68
+ }
69
+
70
+ export async function doctor({ launch = false, env = process.env } = {}) {
71
+ const checks = [checkNode(), checkChrome(env), checkFfmpeg(env)]
72
+ if (launch && checks[0].ok && checks[1].ok) checks.push(await checkLaunch(checks[1].path))
73
+ const status = statusOf(checks)
74
+ return { ok: status === 0, status, checks }
75
+ }
76
+
77
+ async function main(argv) {
78
+ if (argv.includes('--help') || argv.includes('-h')) {
79
+ process.stdout.write(HELP)
80
+ return 0
81
+ }
82
+ const unknown = argv.filter((a) => !['--launch', '--json'].includes(a))
83
+ if (unknown.length) {
84
+ process.stderr.write(`doctor: unknown argument ${unknown[0]}\n\n${HELP}`)
85
+ return 2
86
+ }
87
+ const r = await doctor({ launch: argv.includes('--launch') })
88
+ if (argv.includes('--json')) console.log(JSON.stringify(r, null, 2))
89
+ else {
90
+ for (const c of r.checks) console.log(`${c.ok ? 'ok ' : c.level === 'fatal' ? 'FAIL' : 'warn'} ${c.name.padEnd(7)} ${c.detail}${c.fix ? `\n fix: ${c.fix}` : ''}`)
91
+ console.log(r.status === 0 ? 'ready to render' : r.status === 1 ? 'can render frames; install ffmpeg to encode video' : 'cannot render yet')
92
+ }
93
+ return r.status
94
+ }
95
+
96
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) process.exitCode = await main(process.argv.slice(2))