paper-motion 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.
Files changed (47) hide show
  1. package/README.md +45 -2
  2. package/bin/pamo.mjs +535 -0
  3. package/examples/breath/brief.md +11 -0
  4. package/examples/breath/poster.jpg +0 -0
  5. package/examples/breath/scene.html +59 -0
  6. package/examples/chrome-endcard/brief.md +7 -0
  7. package/examples/chrome-endcard/fonts/GeistMono-Variable.woff2 +0 -0
  8. package/examples/chrome-endcard/fonts/GeistSerif-Regular.woff2 +0 -0
  9. package/examples/chrome-endcard/poster.jpg +0 -0
  10. package/examples/chrome-endcard/scene.html +68 -0
  11. package/examples/chrome-endcard/wordmark.js +16 -0
  12. package/examples/install-loop/brief.md +7 -0
  13. package/examples/install-loop/fonts/GeistMono-Variable.woff2 +0 -0
  14. package/examples/install-loop/fonts/GeistSerif-Regular.woff2 +0 -0
  15. package/examples/install-loop/poster.jpg +0 -0
  16. package/examples/install-loop/scene.html +46 -0
  17. package/examples/signal/brief.md +10 -0
  18. package/examples/signal/poster.jpg +0 -0
  19. package/examples/signal/scene.html +50 -0
  20. package/lib/board.mjs +95 -0
  21. package/lib/browser.mjs +88 -0
  22. package/lib/catalog.mjs +77 -0
  23. package/lib/keys.mjs +93 -0
  24. package/lib/modules.mjs +23 -0
  25. package/lib/react-hooks.mjs +9 -0
  26. package/lib/render.mjs +193 -0
  27. package/lib/server.mjs +88 -0
  28. package/lib/sfx.mjs +285 -0
  29. package/lib/shaderset.mjs +65 -0
  30. package/lib/wordmark.mjs +64 -0
  31. package/package.json +46 -4
  32. package/runtime/brand.js +71 -0
  33. package/runtime/index.js +606 -0
  34. package/runtime/jsx-shim.js +3 -0
  35. package/runtime/moves.js +174 -0
  36. package/runtime/player.js +69 -0
  37. package/runtime/react-shim.js +15 -0
  38. package/templates/blank/brief.md +39 -0
  39. package/templates/blank/scene.html +44 -0
  40. package/templates/brand-sheet/index.html +241 -0
  41. package/templates/move-demo/brief.md +4 -0
  42. package/templates/move-demo/scene.html +157 -0
  43. package/templates/piece/brief.md +39 -0
  44. package/templates/piece/scene.html +62 -0
  45. package/templates/shader-set/shot.js +47 -0
  46. package/templates/still/brief.md +3 -0
  47. package/templates/still/scene.html +56 -0
@@ -0,0 +1,65 @@
1
+ // A brand's shader set: entries in brand/shader-set/set.json, one format for all.
2
+ // build → one scene per entry (shots/) and review boards (boards/), from the template's shot.js.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const ENGINE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
8
+
9
+ export function readSet(dir) {
10
+ const file = path.join(dir, 'set.json');
11
+ if (!fs.existsSync(file)) throw new Error(`No ${file}`);
12
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
13
+ // older sets were a plain list of { id, video }
14
+ const set = Array.isArray(raw) ? { format: { width: 1920, height: 1080, duration: 6, fps: 30 }, entries: raw } : raw;
15
+ set.format = { width: 1920, height: 1080, duration: 6, fps: 30, ...(set.format ?? {}) };
16
+ return set;
17
+ }
18
+
19
+ export function writeSet(dir, set) {
20
+ fs.writeFileSync(path.join(dir, 'set.json'), JSON.stringify(set, null, 1) + '\n');
21
+ }
22
+
23
+ const page = (title, call) => `<!doctype html>
24
+ <html>
25
+ <head>
26
+ <meta charset="utf-8">
27
+ <title>${title}</title>
28
+ <style>#stage { overflow: hidden; }</style>
29
+ </head>
30
+ <body>
31
+ <main id="stage"></main>
32
+ <script type="module">
33
+ import { mount } from '../shot.js';
34
+ ${call}
35
+ </script>
36
+ </body>
37
+ </html>
38
+ `;
39
+
40
+ export const shotName = (e, i) => `${String(i + 1).padStart(2, '0')}-${e.id}`;
41
+
42
+ /** Writes shot.js, shots/<nn>-<id>.html and boards/board-<k>.html (12 per board). Entries without a shader or file are skipped. */
43
+ export function buildSet(dir) {
44
+ const set = readSet(dir);
45
+ fs.copyFileSync(path.join(ENGINE, 'templates', 'shader-set', 'shot.js'), path.join(dir, 'shot.js'));
46
+ for (const sub of ['shots', 'boards']) { fs.rmSync(path.join(dir, sub), { recursive: true, force: true }); fs.mkdirSync(path.join(dir, sub), { recursive: true }); }
47
+ // shaders that only filter an image need one; say which entry instead of failing inside a render
48
+ const NEEDS_IMAGE = ['ImageDithering', 'HalftoneDots', 'HalftoneCmyk', 'FlutedGlass', 'LensDistortion', 'LiquidMetal', 'GemSmoke', 'Heatmap'];
49
+ const skipped = [];
50
+ const live = set.entries.map((e, i) => ({ e, i })).filter(({ e, i }) => {
51
+ if (!e.shader && !e.file) { skipped.push(`${i + 1} · ${e.id}: no shader or file`); return false; }
52
+ if (NEEDS_IMAGE.includes(e.shader) && !e.image) { skipped.push(`${i + 1} · ${e.id}: ${e.shader} filters an image; give it "image" (wordmark, wordmark-dark or a path in brand/)`); return false; }
53
+ return true;
54
+ });
55
+ const F = JSON.stringify(set.format);
56
+ for (const { e, i } of live) fs.writeFileSync(path.join(dir, 'shots', `${shotName(e, i)}.html`), page(`shader set · ${e.id}`, `await mount([${JSON.stringify(e)}], ${F});`));
57
+ const boards = [];
58
+ for (let k = 0; k * 12 < live.length; k++) {
59
+ const chunk = live.slice(k * 12, k * 12 + 12);
60
+ const f = path.join(dir, 'boards', `board-${k + 1}.html`);
61
+ fs.writeFileSync(f, page(`shader set · board ${k + 1}`, `await mount(${JSON.stringify(chunk.map((c) => c.e))}, ${F}, { board: true, numbers: ${JSON.stringify(chunk.map((c) => c.i + 1))} });`));
62
+ boards.push(f);
63
+ }
64
+ return { set, skipped, shots: live.map(({ e, i }) => ({ entry: e, index: i, file: path.join(dir, 'shots', `${shotName(e, i)}.html`) })), boards };
65
+ }
@@ -0,0 +1,64 @@
1
+ // Wordmarks: a brand name set in its typeface, rendered to a transparent PNG cropped to the ink
2
+ // (for scenes, logo shaders such as LiquidMetal, and the brand folder).
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { launch } from './browser.mjs';
6
+
7
+ const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
8
+
9
+ /**
10
+ * @param {object} o
11
+ * @param {string} o.text the name, already cased as the brand writes it
12
+ * @param {string} o.family font family name
13
+ * @param {string} [o.css] stylesheet URL that provides the family (e.g. Google Fonts css2)
14
+ * @param {string} [o.file] local font file (woff2/ttf/otf), used instead of css
15
+ * @param {number} [o.weight] font weight (default 400)
16
+ * @param {string} [o.tracking] letter-spacing in em, e.g. "-0.02em"
17
+ * @param {string} [o.color] fill color (default #ffffff)
18
+ * @param {number} [o.size] font size in px (default 400)
19
+ * @param {number} [o.pad] transparent margin around the ink, as a fraction of the size (default 0)
20
+ * @param {string} o.out output .png path
21
+ */
22
+ export async function renderWordmark({ text, family, css, file, weight = 400, tracking = '0em', color = '#ffffff', size = 400, pad = 0, out }) {
23
+ const face = file
24
+ ? `@font-face { font-family: 'WM'; src: url(data:font/${path.extname(file).slice(1)};base64,${fs.readFileSync(file).toString('base64')}); font-weight: ${weight}; }`
25
+ : '';
26
+ const fam = file ? 'WM' : family;
27
+ const html = `<!doctype html><html><head>${css ? `<link rel="stylesheet" href="${esc(css)}">` : ''}<style>${face}
28
+ html,body{margin:0;background:transparent}</style></head><body><span style="font-family:'${esc(fam)}';font-weight:${weight}">${esc(text)}</span></body></html>`;
29
+ const browser = await launch();
30
+ try {
31
+ const page = await browser.newPage();
32
+ await page.setContent(html, { waitUntil: 'networkidle' });
33
+ const r = await page.evaluate(async ({ fam, weight, size, text, tracking, color, pad }) => {
34
+ const font = `${weight} ${size}px '${fam}'`;
35
+ await document.fonts.load(font).catch(() => {});
36
+ await document.fonts.ready;
37
+ // fonts.check() is true when no face matches at all, so look for a loaded face of this family instead.
38
+ if (![...document.fonts].some((f) => f.family.replace(/['"]/g, '') === fam && f.status === 'loaded')) return { error: 'font' };
39
+ const em = parseFloat(tracking) || 0;
40
+ // Draw generously, then crop to the exact ink so clear space is a brand rule, not a file accident.
41
+ const big = document.createElement('canvas');
42
+ const g = big.getContext('2d');
43
+ g.font = font; g.letterSpacing = `${em * size}px`;
44
+ const m = g.measureText(text);
45
+ big.width = Math.ceil(m.width + size * 2); big.height = Math.ceil(size * 2.4);
46
+ g.font = font; g.letterSpacing = `${em * size}px`; g.fillStyle = color; g.textBaseline = 'alphabetic';
47
+ g.fillText(text, size, size * 1.6);
48
+ const { data, width: W, height: H } = g.getImageData(0, 0, big.width, big.height);
49
+ let x0 = W, y0 = H, x1 = -1, y1 = -1;
50
+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) if (data[(y * W + x) * 4 + 3] > 0) { if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }
51
+ if (x1 < 0) return { error: 'empty' };
52
+ const p = Math.round(size * pad);
53
+ const c = document.createElement('canvas');
54
+ c.width = x1 - x0 + 1 + p * 2; c.height = y1 - y0 + 1 + p * 2;
55
+ c.getContext('2d').drawImage(big, x0, y0, x1 - x0 + 1, y1 - y0 + 1, p, p, x1 - x0 + 1, y1 - y0 + 1);
56
+ return { url: c.toDataURL('image/png'), width: c.width, height: c.height };
57
+ }, { fam, weight, size, text: String(text), tracking, color, pad });
58
+ if (r.error === 'font') throw new Error(`wordmark: font "${family}" (${weight}) did not load; check --css / --file`);
59
+ if (r.error) throw new Error('wordmark: nothing was drawn');
60
+ fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true });
61
+ fs.writeFileSync(out, Buffer.from(r.url.split(',')[1], 'base64'));
62
+ return { out, width: r.width, height: r.height };
63
+ } finally { await browser.close(); }
64
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "paper-motion",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Frame-exact video renderer for HTML scenes built with Paper Shaders: the engine behind the paper-motion agent skills.",
5
+ "keywords": [
6
+ "video",
7
+ "motion-graphics",
8
+ "paper-shaders",
9
+ "shaders",
10
+ "render",
11
+ "ffmpeg",
12
+ "agent-skills",
13
+ "claude-code"
14
+ ],
15
+ "homepage": "https://github.com/solanodz/paper-motion#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/solanodz/paper-motion/issues"
18
+ },
19
+ "license": "MIT",
20
+ "author": "Solano de Zuasnabar",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/solanodz/paper-motion.git",
24
+ "directory": "packages/engine"
25
+ },
26
+ "type": "module",
27
+ "bin": {
28
+ "pamo": "bin/pamo.mjs",
29
+ "paper-motion": "bin/pamo.mjs"
30
+ },
31
+ "files": [
32
+ "bin/",
33
+ "lib/",
34
+ "runtime/",
35
+ "templates/",
36
+ "examples/",
37
+ "!examples/**/renders/",
38
+ "README.md"
39
+ ],
40
+ "engines": {
41
+ "node": ">=18.17"
42
+ },
43
+ "dependencies": {
44
+ "@paper-design/shaders": "0.0.82",
45
+ "@paper-design/shaders-react": "0.0.82",
46
+ "playwright-core": "^1.49.0"
47
+ }
48
+ }
@@ -0,0 +1,71 @@
1
+ // paper-motion/brand: the brand folder inside a scene, so a piece takes its look, motion, sound and
2
+ // material from brand/ instead of re-deciding them.
3
+ // import { loadBrand } from 'paper-motion/brand';
4
+ // const B = await loadBrand(); // reads /brand/* (serve from the project root)
5
+ // const s = scene({ ..., background: B.color('ground') });
6
+ // B.style(title, 'display'); B.shader(s, '#bg', 'mesh-ground'); B.cue(s, 'transition', 2.4); B.sound(s);
7
+ import { PACE } from './moves.js';
8
+
9
+ const get = (p, json) => fetch(p).then((r) => (r.ok ? (json ? r.json() : r.text()) : null)).catch(() => null);
10
+ const sections = (md) => Object.fromEntries((md ?? '').split(/^## /m).slice(1).map((b) => { const i = b.indexOf('\n'); return [b.slice(0, i).trim(), b.slice(i + 1).trim()]; }));
11
+
12
+ export async function loadBrand(root = '/brand') {
13
+ const [tokens, identityMd, motion, sound, setRaw] = await Promise.all([
14
+ get(`${root}/tokens.json`, true), get(`${root}/IDENTITY.md`), get(`${root}/motion.json`, true), get(`${root}/sound.json`, true), get(`${root}/shader-set/set.json`, true),
15
+ ]);
16
+ const identity = sections(identityMd);
17
+ const set = Array.isArray(setRaw) ? { entries: setRaw } : setRaw ?? { entries: [] };
18
+
19
+ // fonts: stylesheets and files, all loaded before the first frame
20
+ const fonts = Object.values(tokens?.fonts ?? {}).filter(Boolean);
21
+ await Promise.all(fonts.filter((f) => f.css).map((f) => new Promise((res) => document.head.append(Object.assign(document.createElement('link'), { rel: 'stylesheet', href: f.css, onload: res, onerror: res })))));
22
+ for (const f of fonts) if (f.file) document.head.append(Object.assign(document.createElement('style'), { textContent: `@font-face { font-family: '${f.family}'; src: url('${root}/${f.file}'); font-weight: 100 900; }` }));
23
+ await Promise.all(fonts.flatMap((f) => (f.weights ?? [400]).map((w) => document.fonts.load(`${w} 40px '${f.family}'`).catch(() => {}))));
24
+
25
+ const C = tokens?.colors ?? {};
26
+ const T = tokens?.type ?? {};
27
+ const fam = (key) => (tokens?.fonts?.[key]?.family ? `'${tokens.fonts[key].family}', system-ui, sans-serif` : 'system-ui, sans-serif');
28
+ const wm = tokens?.wordmark ?? {};
29
+ const pal = sound?.cues ?? {};
30
+
31
+ const B = {
32
+ tokens, identity, motion, sound, set,
33
+ name: wm.text ?? tokens?.brand ?? 'brand',
34
+ /** A color by role (ground, figure, muted, surface, accent…), with a fallback. */
35
+ color: (role, fallback = '#888888') => C[role]?.hex ?? fallback,
36
+ ramp: tokens?.ramp ?? [C.ground?.hex, C.surface?.hex, C.accent?.hex].filter(Boolean),
37
+ /** CSS font-family for a font key (display, text, mono). */
38
+ font: fam,
39
+ /** The type role's numbers (display, title, body, caption), scaled for a short side of `short` px. */
40
+ type: (role, short = 1080) => { const r = T[role] ?? {}; const k = short / (T.reference ?? 1080); return { family: fam(r.font ?? 'text'), weight: r.weight ?? 400, size: (r.size ?? 32) * k, lineHeight: r.lineHeight ?? 1.2, tracking: r.tracking ?? '0em' }; },
41
+ /** Apply a type role to an element. */
42
+ style: (el, role, { short = 1080, color = 'figure' } = {}) => {
43
+ const t = B.type(role, short);
44
+ Object.assign(el.style, { fontFamily: t.family, fontWeight: t.weight, fontSize: `${t.size}px`, lineHeight: t.lineHeight, letterSpacing: t.tracking, color: B.color(color) });
45
+ return el;
46
+ },
47
+ wordmark: { text: wm.text ?? tokens?.brand, onLight: wm.files?.onLight && `${root}/${wm.files.onLight}`, onDark: wm.files?.onDark && `${root}/${wm.files.onDark}` },
48
+ /** Timing for the brand's pace: { enter, hold, stagger } in seconds. */
49
+ pace: { ...PACE[motion?.pace ?? 'medium'], ...(motion?.timing ?? {}) },
50
+ /** Mount a shader-set entry by id on an element (or selector). Returns the layer. */
51
+ shader: (s, el, id, options = {}) => {
52
+ const e = set.entries.find((x) => x.id === id);
53
+ if (!e?.shader) throw new Error(`paper-motion/brand: no shader entry "${id}" in brand/shader-set/set.json`);
54
+ const props = { ...e.props };
55
+ if (e.image) props.image = e.image === 'wordmark' ? B.wordmark.onDark ?? B.wordmark.onLight : e.image === 'wordmark-dark' ? B.wordmark.onLight ?? B.wordmark.onDark : `${root}/${e.image}`;
56
+ const layer = s.shader(el, e.shader, props, { ...(e.loop ? { loop: e.loop } : {}), ...options });
57
+ // the entry's periodic motion, as in its rendered loop (static shaders stay alive)
58
+ if (e.motion) { const D = set.format?.duration ?? s.duration, { param, from, to, cycles = 1 } = e.motion; s.update((t) => layer.set({ [param]: from + (to - from) * (0.5 - 0.5 * Math.cos((2 * Math.PI * cycles * t) / D)) })); }
59
+ return layer;
60
+ },
61
+ /** Schedule the brand's sound for a gesture (transition, land, text) at time t. */
62
+ cue: (s, gesture, t, extra = {}) => { const c = pal[gesture]; if (c) s.sfx(t, c.type, { ...c, ...extra }); },
63
+ /** The brand's keystroke options for keySounds(): { bank, style, gain }. */
64
+ keys: { ...(sound?.keys?.bank ? { bank: sound.keys.bank } : {}), ...(sound?.keys?.style ? { style: sound.keys.style } : {}), gain: sound?.keys?.gain ?? 0.16 },
65
+ /** Apply the brand's master sound settings (and its bed, if any) to a scene. */
66
+ sound: (s) => { if (pal.bed) s.sfx(0, pal.bed.type, { dur: s.duration, ...pal.bed }); s.sound({ lowpass: sound?.lowpass ?? 2000, gain: 1 }); },
67
+ /** The loudness to render at (LUFS). */
68
+ loudness: sound?.loudness ?? -16,
69
+ };
70
+ return B;
71
+ }