@motionhub/runtime 0.1.0 → 0.3.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.
package/README.md CHANGED
@@ -16,9 +16,14 @@ You do not use this package on its own: an engine binding provides it.
16
16
  | `seededRandom(seed)` | A stream of numbers in [0, 1) for a string or number seed: the same seed draws the same picture in every engine |
17
17
  | `<Video src startAt trimBefore playbackRate objectFit>` | The engine's video: shown from `startAt` s of the sequence, its source from `trimBefore` s |
18
18
  | `<Caption opacity>` | One spoken line, drawn from the `caption` tokens (font, size, weight, color, background, radius, padding-y, padding-x, bottom, max-width, shadow, rule-left or rule-top) |
19
+ | `<Sequence from duration>`, `interpolate(t, input, output, {easing})`, `Easing` | As Remotion's, in seconds: a span whose children count time from its start, a value mapped through a curve, and the curves (`Easing.bezier` takes a cubicBezier token). For composing components, as a reel does |
19
20
  | `<MotionRoot tokens>` | A full-frame box carrying the tokens as CSS custom properties |
20
21
  | `resolveTokens(dtcg)`, `tokenVariables(tokens)` | `tokens.json` (W3C design tokens) as values, and those values as custom properties: `--color-ink`, `--font-display`, `--duration-light`, `--easing-light`, `--caption-size` |
21
22
 
22
23
  A component colours with `var(--color-<name>)` and sets type with `var(--font-<name>)`, reads its time from `useTime()`, never from a clock, a timer or `Math.random`, and takes what changes (words, a progress from 0 to 1, a video's `src`) as props. So the same moment draws the same picture every time.
23
24
 
25
+ ## Sound
26
+
27
+ `@motionhub/runtime/sound` synthesises a motion's sound, with no React and no audio API: `renderSound({seconds, cues, sound, rate})` returns mono samples from the motion's `react/sound.json` (a bed at a tempo, and a voice for each role: `land`, `move`, `draw`, `count`, `cut`, `out`) and a list of cues (`[{at, role, dur}]`, a reel's `export const cues`). The same input gives the same samples, so a player plays them and a renderer can write them to a WAV for Remotion's `<Audio>` or a HyperFrames track.
28
+
24
29
  An engine binding passes `<MotionRuntimeProvider value>` an object with `useTime` and `useCompositionTime` (hooks returning seconds), `fps`, `width`, `height`, `tokens` (resolved) and, if it plays video, `Video`.
package/index.d.ts CHANGED
@@ -37,3 +37,8 @@ export declare const useTokens: () => Tokens;
37
37
  export declare const Video: FC<VideoProps>;
38
38
  export declare const MotionRoot: FC<{tokens?: Tokens; style?: CSSProperties; children?: ReactNode}>;
39
39
  export declare const Caption: FC<{children?: ReactNode; opacity?: number; style?: CSSProperties}>;
40
+
41
+ export type EasingFn = (x: number) => number;
42
+ export declare const Easing: {linear: EasingFn; bezier(x1: number, y1: number, x2: number, y2: number): EasingFn; inOutSine: EasingFn; outCubic: EasingFn; outQuart: EasingFn; inOutCubic: EasingFn; outBack: EasingFn};
43
+ export declare function interpolate(input: number, inputRange: number[], outputRange: number[], options?: {easing?: EasingFn; clamp?: boolean}): number;
44
+ export declare const Sequence: FC<{from?: number; duration?: number; children?: ReactNode}>;
package/index.js CHANGED
@@ -30,62 +30,8 @@ const hash = (key) => {
30
30
  /** A stream of numbers in [0, 1) for `seed` (a string or a number): call it for each next number */
31
31
  export const seededRandom = (seed) => prng(typeof seed === 'number' ? seed : hash(String(seed)));
32
32
 
33
- // ---- the motion's tokens (W3C design tokens) as values ----
34
- const GENERIC = /^(serif|sans-serif|monospace|cursive|fantasy|system-ui|math|emoji|ui-[a-z-]+)$/;
35
- const hex = (v) => (typeof v === 'string' ? v : v?.hex ?? `#${(v?.components ?? [0, 0, 0]).map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')}`);
36
- const color = (v) => (typeof v === 'string' ? v : v?.alpha !== undefined && v.alpha < 1 ? `color-mix(in srgb, ${hex(v)} ${+(v.alpha * 100).toFixed(2)}%, transparent)` : hex(v));
37
- const px = (v) => (typeof v === 'number' ? v : v?.unit === 'rem' ? v.value * 16 : v?.value);
38
- // a spread of 0 is left out, so a shadow works as a text-shadow too
39
- const shadow = (v) => [].concat(v).map((s) => (typeof s === 'string' ? s : `${s.inset ? 'inset ' : ''}${px(s.offsetX) ?? 0}px ${px(s.offsetY) ?? 0}px ${px(s.blur) ?? 0}px${px(s.spread) ? ` ${px(s.spread)}px` : ''} ${color(s.color)}`)).join(', ');
40
- const VALUE = {
41
- color,
42
- fontFamily: (v) => [].concat(v).map((f) => (GENERIC.test(f) ? f : `"${f}"`)).join(', '),
43
- duration: (v) => (v?.unit === 'ms' ? v.value / 1000 : v?.value),
44
- cubicBezier: (v) => v,
45
- dimension: px,
46
- fontWeight: (v) => v,
47
- number: (v) => v,
48
- shadow,
49
- };
50
-
51
- /**
52
- * A motion's tokens.json as values, group by group: a color as a CSS colour, a fontFamily as a CSS font stack, a duration in seconds, a cubicBezier as
53
- * [x1, y1, x2, y2], a dimension in pixels, a shadow as a CSS box-shadow; aliases (`{color.ink}`) resolved. `tokens.color.ink`, `tokens.duration.light`.
54
- */
55
- export function resolveTokens(dtcg) {
56
- if (!dtcg) return {};
57
- const lookup = (path) => path.split('.').reduce((o, k) => o?.[k], dtcg);
58
- const out = {};
59
- const walk = (node, path, inherited) => {
60
- const type = node.$type ?? inherited;
61
- if ('$value' in node) {
62
- let value = node.$value, t = type, seen = 0;
63
- while (typeof value === 'string' && /^\{[^{}]+\}$/.test(value) && seen++ < 8) {
64
- const target = lookup(value.slice(1, -1));
65
- value = target?.$value;
66
- t = t ?? target?.$type;
67
- }
68
- const [group, ...rest] = path;
69
- (out[group] ??= {})[rest.join('-')] = (VALUE[t] ?? ((x) => x))(value);
70
- return;
71
- }
72
- for (const [k, child] of Object.entries(node)) if (!k.startsWith('$') && child && typeof child === 'object') walk(child, [...path, k], type);
73
- };
74
- for (const [group, node] of Object.entries(dtcg)) if (!group.startsWith('$') && node && typeof node === 'object') walk(node, [group], node.$type);
75
- return out;
76
- }
77
-
78
- /** Resolved tokens as CSS custom properties, Style Dictionary's way: --color-ink, --font-display, --duration-light (s), --easing-light, --caption-size (px) */
79
- export function tokenVariables(tokens) {
80
- const vars = {};
81
- for (const [group, values] of Object.entries(tokens ?? {})) {
82
- for (const [name, v] of Object.entries(values)) {
83
- const key = `--${group}-${name}`;
84
- vars[key] = group === 'duration' && typeof v === 'number' ? `${v}s` : Array.isArray(v) && v.length === 4 && v.every((n) => typeof n === 'number') ? `cubic-bezier(${v.join(', ')})` : typeof v === 'number' && /^(caption|size|space|radius)/.test(group) && !/weight/.test(name) ? `${v}px` : String(v);
85
- }
86
- }
87
- return vars;
88
- }
33
+ export {resolveTokens, tokenVariables} from './tokens.js';
34
+ import {tokenVariables} from './tokens.js';
89
35
 
90
36
  // ---- the runtime an engine provides ----
91
37
  const Runtime = createContext(null);
@@ -118,6 +64,52 @@ export const Video = (props) => {
118
64
  return createElement(V, props);
119
65
  };
120
66
 
67
+ // ---- timing, for a composition of components: Remotion's names, in seconds ----
68
+ const bezier = (x1, y1, x2, y2) => {
69
+ const at = (a, b, t) => 3 * a * t * (1 - t) * (1 - t) + 3 * b * t * t * (1 - t) + t * t * t;
70
+ return (x) => {
71
+ if (x <= 0 || x >= 1) return Math.min(1, Math.max(0, x));
72
+ let lo = 0, hi = 1, t = x;
73
+ for (let i = 0; i < 30; i++) { t = (lo + hi) / 2; if (at(x1, x2, t) < x) lo = t; else hi = t; }
74
+ return at(y1, y2, t);
75
+ };
76
+ };
77
+ /** Easing curves, each from [0, 1] to [0, 1]; `Easing.bezier(x1, y1, x2, y2)` takes a motion's cubicBezier token */
78
+ export const Easing = {
79
+ linear: (x) => x,
80
+ bezier,
81
+ inOutSine: (x) => -(Math.cos(Math.PI * x) - 1) / 2,
82
+ outCubic: (x) => 1 - (1 - x) ** 3,
83
+ outQuart: (x) => 1 - (1 - x) ** 4,
84
+ inOutCubic: (x) => (x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2),
85
+ outBack: (x) => 1 + 2.70158 * (x - 1) ** 3 + 1.70158 * (x - 1) ** 2,
86
+ };
87
+
88
+ /**
89
+ * `input` mapped from the range `inputRange` onto `outputRange` (as many points in each), through `easing`, held at the ends: as Remotion's interpolate,
90
+ * with time in seconds. `interpolate(useTime(), [1, 2.2], [0, 2300], {easing: Easing.outQuart})`
91
+ */
92
+ export function interpolate(input, inputRange, outputRange, {easing = Easing.linear, clamp = true} = {}) {
93
+ let i = 1;
94
+ while (i < inputRange.length - 1 && input > inputRange[i]) i++;
95
+ const [a, b] = [inputRange[i - 1], inputRange[i]], [x, y] = [outputRange[i - 1], outputRange[i]];
96
+ let p = b === a ? 1 : (input - a) / (b - a);
97
+ if (clamp) p = Math.min(1, Math.max(0, p));
98
+ return x + (y - x) * easing(p);
99
+ }
100
+
101
+ /**
102
+ * Its children from `from` seconds for `duration` seconds (to the end without one), their useTime() counting from its start: as Remotion's
103
+ * <Sequence>, in seconds. Outside that span it draws nothing.
104
+ */
105
+ export const Sequence = ({from = 0, duration = Infinity, children}) => {
106
+ const parent = runtime();
107
+ const t = parent.useTime();
108
+ if (t < from || t >= from + duration) return null;
109
+ const value = {...parent, useTime: () => parent.useTime() - from};
110
+ return createElement(Runtime.Provider, {value}, children);
111
+ };
112
+
121
113
  /** The ground a motion's components expect: the tokens as custom properties, filling the frame */
122
114
  export const MotionRoot = ({tokens, style, children}) => createElement('div', {
123
115
  style: {position: 'absolute', inset: 0, overflow: 'hidden', ...tokenVariables(tokens), ...style},
package/package.json CHANGED
@@ -1,16 +1,41 @@
1
1
  {
2
2
  "name": "@motionhub/runtime",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "What a motion's React components draw with (time, frame, tokens, seeded randomness, video, caption), in any engine that provides it.",
5
5
  "license": "MIT",
6
- "repository": {"type": "git", "url": "git+https://github.com/motionhub-dev/motions.git", "directory": "packages/runtime"},
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/motionhub-dev/motions.git",
9
+ "directory": "packages/runtime"
10
+ },
7
11
  "homepage": "https://motionhub.dev",
8
12
  "type": "module",
9
13
  "main": "index.js",
10
14
  "types": "index.d.ts",
11
- "exports": { ".": {"types": "./index.d.ts", "default": "./index.js"}, "./package.json": "./package.json" },
12
- "files": ["index.js", "index.d.ts", "README.md"],
13
- "scripts": { "test": "node --test test.mjs" },
14
- "devDependencies": { "react": "19.1.1", "react-dom": "19.1.1" },
15
- "peerDependencies": { "react": ">=18" }
15
+ "exports": {
16
+ ".": {
17
+ "types": "./index.d.ts",
18
+ "default": "./index.js"
19
+ },
20
+ "./package.json": "./package.json",
21
+ "./sound": "./sound.js"
22
+ },
23
+ "files": [
24
+ "index.js",
25
+ "tokens.js",
26
+ "sound.js",
27
+ "index.d.ts",
28
+ "sound.d.ts",
29
+ "README.md"
30
+ ],
31
+ "scripts": {
32
+ "test": "node --test test.mjs"
33
+ },
34
+ "devDependencies": {
35
+ "react": "19.1.1",
36
+ "react-dom": "19.1.1"
37
+ },
38
+ "peerDependencies": {
39
+ "react": ">=18"
40
+ }
16
41
  }
package/sound.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export type Role = 'land' | 'move' | 'draw' | 'count' | 'cut' | 'out';
2
+ /** One thing that happens in the picture: when (seconds), what kind, and for how long (a move or a stroke) */
3
+ export type Cue = {at: number; role: Role; dur?: number};
4
+ /** A voice and its settings: `{voice: 'click', lo: 1500, hi: 5000, len: 0.03, gain: 0.7}`; several layer into one sound */
5
+ export type Voice = {voice: string; gain?: number; [setting: string]: unknown};
6
+ /** A motion's react/sound.json */
7
+ export type Sound = {bpm?: number; root?: number; kit?: string[]; bed?: number; roles: Partial<Record<Role, Voice | Voice[]>>};
8
+ export declare const ROLES: Role[];
9
+ export declare const VOICES: string[];
10
+ export declare const KIT: string[];
11
+ /** The sound of `seconds` with `cues` in `sound`, as mono samples at `rate` (44100): the same input gives the same samples */
12
+ export declare function renderSound(options: {seconds: number; cues?: Cue[]; sound: Sound; rate?: number}): Float32Array;
13
+ export declare function soundIssues(sound: unknown): string[];
package/sound.js ADDED
@@ -0,0 +1,172 @@
1
+ // @motionhub/runtime/sound: a motion's sound, synthesised. A motion describes how its world sounds in react/sound.json (a
2
+ // rhythmic bed and a voice for each kind of thing that happens: something lands, moves, draws, counts, cuts or leaves), and
3
+ // a reel lists when those things happen (`export const cues`). `renderSound` turns the two into samples, the same every time,
4
+ // in any JavaScript engine: a player plays them, a renderer can write them to a file. No React, no Web Audio, no files.
5
+
6
+ /** The roles a cue can have: what happened in the picture */
7
+ export const ROLES = ['land', 'move', 'draw', 'count', 'cut', 'out'];
8
+ /** The voices a role can be drawn with, and the instruments a bed can use */
9
+ export const VOICES = ['click', 'thump', 'tone', 'pluck', 'swish', 'scratch', 'chime', 'marimba', 'square', 'squares', 'swell', 'keys', 'noise'];
10
+ export const KIT = ['kick', 'hat', 'rim', 'bass', 'arp', 'pluck', 'chip', 'pad', 'room'];
11
+
12
+ const mulberry = (seed) => () => {
13
+ seed = (seed + 0x6d2b79f5) >>> 0;
14
+ let t = seed;
15
+ t = Math.imul(t ^ (t >>> 15), t | 1);
16
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
17
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
18
+ };
19
+
20
+ /** A synthesiser at `rate` samples a second, with its own seeded noise */
21
+ function synth(rate, seed = 7) {
22
+ const rand = mulberry(seed);
23
+ const gauss = () => { let u = 0; while (!u) u = rand(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * rand()); };
24
+ const n = (s) => Math.max(1, Math.round(s * rate));
25
+
26
+ // RBJ biquads, run twice for a steeper slope
27
+ const biquad = (x, type, f) => {
28
+ const w = (2 * Math.PI * Math.min(f, rate * 0.45)) / rate, c = Math.cos(w), a = Math.sin(w) / (2 * Math.SQRT1_2);
29
+ const [b0, b1, b2] = type === 'low' ? [(1 - c) / 2, 1 - c, (1 - c) / 2] : [(1 + c) / 2, -(1 + c), (1 + c) / 2];
30
+ const a0 = 1 + a, a1 = -2 * c, a2 = 1 - a;
31
+ const y = new Float32Array(x.length);
32
+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
33
+ for (let i = 0; i < x.length; i++) {
34
+ const v = (b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2) / a0;
35
+ x2 = x1; x1 = x[i]; y2 = y1; y1 = v; y[i] = v;
36
+ }
37
+ return y;
38
+ };
39
+ const band = (x, lo, hi) => biquad(biquad(biquad(biquad(x, 'high', lo), 'high', lo), 'low', hi), 'low', hi);
40
+ const noise = (s) => Float32Array.from({length: n(s)}, gauss);
41
+ const env = (len, attack = 0.002, decay = 0.2, curve = 4) => Float32Array.from({length: len}, (_, i) => {
42
+ const t = i / rate;
43
+ return Math.min(1, t / Math.max(attack, 1e-4)) * Math.exp((-curve * t) / Math.max(decay, 1e-4));
44
+ });
45
+ const mul = (x, y) => x.map((v, i) => v * (typeof y === 'number' ? y : y[i] ?? 0));
46
+ const shape = (len, f) => Float32Array.from({length: len}, (_, i) => f(i / Math.max(1, len - 1)));
47
+
48
+ const tone = (freq, s, partials = [[1, 1]], decay = 0.6, attack = 0.003, glide = 0) => {
49
+ const len = n(s), out = new Float32Array(len), e = env(len, attack, s * 4, 0);
50
+ let phase = 0;
51
+ for (let i = 0; i < len; i++) {
52
+ const t = i / rate;
53
+ phase += (2 * Math.PI * freq * (1 - glide * Math.min(t / s, 1))) / rate;
54
+ let v = 0;
55
+ for (const [r, g] of partials) v += g * Math.sin(r * phase) * Math.exp((-t * r) / Math.max(decay, 1e-3));
56
+ out[i] = v * e[i];
57
+ }
58
+ return out;
59
+ };
60
+ const V = {
61
+ click: ({lo = 2000, hi = 8000, len = 0.025}) => { const x = band(noise(len), lo, hi); return mul(x, env(x.length, 0.0005, len * 0.4)); },
62
+ thump: ({freq = 70, len = 0.35, drop = 0.5}) => tone(freq, len, [[1, 1], [2, 0.15]], len * 0.5, 0.001, drop),
63
+ tone: ({freq = 440, len = 0.2, decay = 0.08, partials = [[1, 1], [2, 0.3]]}) => tone(freq, len, partials, decay, 0.0005),
64
+ pluck: ({freq = 440, len = 0.9, bright = 0.5}) => {
65
+ const len_ = n(len), period = Math.max(2, Math.round(rate / freq)), buf = Float32Array.from({length: period}, () => (rand() * 2 - 1) * bright + (rand() * 2 - 1) * (1 - bright) * 0.3);
66
+ const out = new Float32Array(len_);
67
+ for (let i = 0; i < len_; i++) { const k = i % period; out[i] = buf[k]; buf[k] = 0.4985 * (buf[k] + buf[(k + 1) % period]); }
68
+ return out;
69
+ },
70
+ swish: ({lo = 300, hi = 3000, rise = 0.5}, dur) => { const x = band(noise(Math.max(dur, 0.25)), lo, hi); return mul(x, shape(x.length, (t) => (t < rise ? t / rise : (1 - t) / (1 - rise)) ** 1.6)); },
71
+ scratch: ({lo = 1800, hi = 6000}, dur) => {
72
+ const x = band(noise(Math.max(dur, 0.25)), lo, hi);
73
+ let ph = 0;
74
+ return x.map((v, i) => { ph += (2 * Math.PI * (18 + rand() * 22)) / rate; const t = i / x.length; return v * (0.55 + 0.45 * Math.abs(Math.sin(ph))) * Math.min(1, Math.min(t, 1 - t) * 12); });
75
+ },
76
+ chime: ({freq = 1046, len = 1.2}) => tone(freq, len, [[1, 1], [2.76, 0.4], [5.4, 0.2], [8.9, 0.08]], len * 0.45),
77
+ marimba: ({freq = 392, len = 0.6}) => tone(freq, len, [[1, 1], [4, 0.25], [9.2, 0.06]], len * 0.35, 0.001),
78
+ square: ({freq = 880, len = 0.08}) => { const l = n(len), e = env(l, 0.001, len, 2); return Float32Array.from({length: l}, (_, i) => Math.sign(Math.sin((2 * Math.PI * freq * i) / rate)) * e[i] * 0.5); },
79
+ squares: ({freqs = [440, 554, 659], len = 0.06}) => concat(freqs.map((freq) => V.square({freq, len}))),
80
+ swell: ({freq = 110}, dur) => {
81
+ const s = Math.max(dur, 0.6), l = n(s), ph = [rand(), rand(), rand(), rand()].map((v) => v * 6);
82
+ return Float32Array.from({length: l}, (_, i) => {
83
+ const t = i / rate;
84
+ const v = [[1, 1], [1.5, 0.5], [2, 0.35], [3, 0.12]].reduce((a, [r, g], k) => a + Math.sin(2 * Math.PI * freq * r * t + ph[k]) * g, 0);
85
+ return v * Math.sin(Math.PI * Math.min(t / s, 1)) ** 2;
86
+ });
87
+ },
88
+ keys: (_, dur) => {
89
+ const s = Math.max(dur, 0.2), out = new Float32Array(n(s + 0.1));
90
+ for (let t = 0; t < s; t += 0.07 + rand() * 0.04) { const x = V.click({lo: 2500, hi: 8000, len: 0.018}), at = n(t), g = 0.6 + rand() * 0.4; for (let i = 0; i < x.length && at + i < out.length; i++) out[at + i] += x[i] * g; }
91
+ return out;
92
+ },
93
+ noise: ({lo = 300, hi = 3000, len, fade = 'hit'}, dur) => {
94
+ const s = len ?? Math.max(dur, 0.1), x = band(noise(s), lo, hi);
95
+ return mul(x, fade === 'hit' ? env(x.length, 0.002, s * 0.4) : fade === 'out' ? shape(x.length, (t) => 1 - t) : shape(x.length, (t) => Math.sin(Math.PI * t)));
96
+ },
97
+ };
98
+ const concat = (parts) => { const out = new Float32Array(parts.reduce((a, p) => a + p.length, 0)); let at = 0; for (const p of parts) { out.set(p, at); at += p.length; } return out; };
99
+ return {V, n, band, noise, env, tone};
100
+ }
101
+
102
+ const peak = (x) => x.reduce((m, v) => Math.max(m, Math.abs(v)), 1e-9);
103
+ const add = (out, x, at, g) => { for (let i = 0; i < x.length && at + i < out.length; i++) if (at + i >= 0) out[at + i] += x[i] * g; };
104
+
105
+ /** A voice spec (one layer or several) drawn for a cue of `dur` seconds */
106
+ function voice(S, spec, dur) {
107
+ const layers = [].concat(spec);
108
+ const parts = layers.map((l) => { const make = S.V[l.voice]; if (!make) throw new Error(`no voice "${l.voice}": one of ${VOICES.join(', ')}`); const x = make(l, dur); return [x, l.gain ?? 1]; });
109
+ const out = new Float32Array(Math.max(...parts.map(([x]) => x.length)));
110
+ for (const [x, g] of parts) add(out, x, 0, g / peak(x));
111
+ return out;
112
+ }
113
+
114
+ /** The bed: a pattern at `bpm` over `seconds`, from the instruments in `kit` (KIT), on the note `root` (Hz) */
115
+ function bed(S, rate, seconds, {bpm = 90, root = 147, kit = []}) {
116
+ const out = new Float32Array(Math.ceil((seconds + 1) * rate)), beat = 60 / bpm, scale = [0, 3, 5, 7, 10, 12];
117
+ const put = (x, t, g) => add(out, x, Math.round(t * rate), g);
118
+ const has = (k) => kit.includes(k);
119
+ for (let s = 0; s * beat / 2 < seconds; s++) {
120
+ const t = (s * beat) / 2, on = s % 2 === 0, step = s % 8;
121
+ if (has('kick') && (step === 0 || step === 4)) put(S.V.thump({freq: 55, len: 0.4, drop: 0.6}), t, 0.7);
122
+ if (has('hat') && !on) put(S.V.click({lo: 6000, hi: 14000, len: 0.03}), t, 0.18);
123
+ if (has('rim') && (step === 2 || step === 6)) put(S.V.click({lo: 900, hi: 4000, len: 0.04}), t, 0.35);
124
+ if (has('bass') && step === 0) put(S.tone(root / 2, beat * 3.5, [[1, 1], [2, 0.2]], beat * 3), t, 0.35);
125
+ if (has('arp') && on) put(S.V.marimba({freq: root * 2 ** (scale[(s / 2) % scale.length | 0] / 12) * 2, len: beat}), t, 0.12);
126
+ if (has('pluck') && [0, 3, 6].includes(step)) put(S.V.pluck({freq: root * 2 ** (scale[(s * 5) % scale.length] / 12) * 2, len: beat * 2}), t, 0.2);
127
+ if (has('chip') && on) put(S.V.square({freq: root * 2 ** (scale[(s / 2 | 0) % 4] / 12) * 2, len: beat * 0.4}), t, 0.1);
128
+ }
129
+ if (has('pad')) for (let k = 0; k * beat * 8 < seconds; k++) put(S.V.swell({freq: root * [1, 1.2, 0.84, 1.12][k % 4]}, beat * 8), k * beat * 8, 0.1);
130
+ if (has('room')) put(S.band(S.noise(seconds + 1), 80, 1200), 0, 0.05);
131
+ return out.subarray(0, Math.ceil(seconds * rate));
132
+ }
133
+
134
+ /**
135
+ * The sound of `seconds` with `cues` ([{at, role, dur}]) in the motion's `sound` (react/sound.json: {bpm, root, kit, roles: {land: voice, …}}), as
136
+ * mono samples at `rate`: the cues' voices over the bed, faded in and out at the ends, at a steady loudness. The same input gives the same samples.
137
+ */
138
+ export function renderSound({seconds, cues = [], sound, rate = 44100}) {
139
+ const S = synth(rate);
140
+ const len = Math.ceil(seconds * rate), hits = new Float32Array(len + rate * 4);
141
+ for (const c of cues) {
142
+ const spec = sound.roles?.[c.role];
143
+ if (!spec || c.at >= seconds) continue;
144
+ const x = voice(S, spec, c.dur ?? 0);
145
+ add(hits, x, Math.round(c.at * rate), ({land: 0.8, move: 0.9, draw: 0.8, count: 0.8, cut: 0.6, out: 0.5})[c.role] ?? 0.7);
146
+ }
147
+ const b = bed(S, rate, seconds, sound), h = peak(hits.subarray(0, len)), p = peak(b);
148
+ const out = new Float32Array(len), fadeIn = 0.25 * rate, fadeOut = 1.5 * rate;
149
+ for (let i = 0; i < len; i++) {
150
+ let v = (hits[i] / h) * 0.9 + (b[i] / p) * (sound.bed ?? 0.45);
151
+ if (i < fadeIn) v *= i / fadeIn;
152
+ if (i > len - fadeOut) v *= ((len - i) / fadeOut) ** 2;
153
+ out[i] = Math.tanh(v * 1.2) / Math.tanh(1.2);
154
+ }
155
+ const top = peak(out);
156
+ for (let i = 0; i < len; i++) out[i] *= 0.8 / top;
157
+ return out;
158
+ }
159
+
160
+ /** What is wrong with a sound.json, one sentence each */
161
+ export function soundIssues(sound) {
162
+ const issues = [];
163
+ if (!sound || typeof sound !== 'object') return ['sound.json is an object: {bpm, root, kit, roles}'];
164
+ if (sound.bpm !== undefined && !(sound.bpm >= 40 && sound.bpm <= 200)) issues.push('bpm is 40 to 200');
165
+ if (sound.root !== undefined && !(sound.root >= 40 && sound.root <= 2000)) issues.push('root is a note in Hz, 40 to 2000');
166
+ for (const k of [].concat(sound.kit ?? [])) if (!KIT.includes(k)) issues.push(`kit has no "${k}": ${KIT.join(', ')}`);
167
+ for (const [role, spec] of Object.entries(sound.roles ?? {})) {
168
+ if (!ROLES.includes(role)) issues.push(`roles has no "${role}": ${ROLES.join(', ')}`);
169
+ for (const l of [].concat(spec)) if (!VOICES.includes(l?.voice)) issues.push(`${role} has no voice "${l?.voice}": ${VOICES.join(', ')}`);
170
+ }
171
+ return issues;
172
+ }
package/tokens.js ADDED
@@ -0,0 +1,59 @@
1
+ // A motion's tokens.json (W3C design tokens) as values and as CSS custom properties. No React here, so a build script
2
+ // can read tokens without it; index.js re-exports both.
3
+
4
+ const GENERIC = /^(serif|sans-serif|monospace|cursive|fantasy|system-ui|math|emoji|ui-[a-z-]+)$/;
5
+ const hex = (v) => (typeof v === 'string' ? v : v?.hex ?? `#${(v?.components ?? [0, 0, 0]).map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')}`);
6
+ const color = (v) => (typeof v === 'string' ? v : v?.alpha !== undefined && v.alpha < 1 ? `color-mix(in srgb, ${hex(v)} ${+(v.alpha * 100).toFixed(2)}%, transparent)` : hex(v));
7
+ const px = (v) => (typeof v === 'number' ? v : v?.unit === 'rem' ? v.value * 16 : v?.value);
8
+ // a spread of 0 is left out, so a shadow works as a text-shadow too
9
+ const shadow = (v) => [].concat(v).map((s) => (typeof s === 'string' ? s : `${s.inset ? 'inset ' : ''}${px(s.offsetX) ?? 0}px ${px(s.offsetY) ?? 0}px ${px(s.blur) ?? 0}px${px(s.spread) ? ` ${px(s.spread)}px` : ''} ${color(s.color)}`)).join(', ');
10
+ const VALUE = {
11
+ color,
12
+ fontFamily: (v) => [].concat(v).map((f) => (GENERIC.test(f) ? f : `"${f}"`)).join(', '),
13
+ duration: (v) => (v?.unit === 'ms' ? v.value / 1000 : v?.value),
14
+ cubicBezier: (v) => v,
15
+ dimension: px,
16
+ fontWeight: (v) => v,
17
+ number: (v) => v,
18
+ shadow,
19
+ };
20
+
21
+ /**
22
+ * A motion's tokens.json as values, group by group: a color as a CSS colour, a fontFamily as a CSS font stack, a duration in seconds, a cubicBezier as
23
+ * [x1, y1, x2, y2], a dimension in pixels, a shadow as a CSS box-shadow; aliases (`{color.ink}`) resolved. `tokens.color.ink`, `tokens.duration.light`.
24
+ */
25
+ export function resolveTokens(dtcg) {
26
+ if (!dtcg) return {};
27
+ const lookup = (path) => path.split('.').reduce((o, k) => o?.[k], dtcg);
28
+ const out = {};
29
+ const walk = (node, path, inherited) => {
30
+ const type = node.$type ?? inherited;
31
+ if ('$value' in node) {
32
+ let value = node.$value, t = type, seen = 0;
33
+ while (typeof value === 'string' && /^\{[^{}]+\}$/.test(value) && seen++ < 8) {
34
+ const target = lookup(value.slice(1, -1));
35
+ value = target?.$value;
36
+ t = t ?? target?.$type;
37
+ }
38
+ const [group, ...rest] = path;
39
+ (out[group] ??= {})[rest.join('-')] = (VALUE[t] ?? ((x) => x))(value);
40
+ return;
41
+ }
42
+ for (const [k, child] of Object.entries(node)) if (!k.startsWith('$') && child && typeof child === 'object') walk(child, [...path, k], type);
43
+ };
44
+ for (const [group, node] of Object.entries(dtcg)) if (!group.startsWith('$') && node && typeof node === 'object') walk(node, [group], node.$type);
45
+ return out;
46
+ }
47
+
48
+ /** Resolved tokens as CSS custom properties, Style Dictionary's way: --color-ink, --font-display, --duration-light (s), --easing-light, --caption-size (px) */
49
+ export function tokenVariables(tokens) {
50
+ const vars = {};
51
+ for (const [group, values] of Object.entries(tokens ?? {})) {
52
+ for (const [name, v] of Object.entries(values)) {
53
+ const key = `--${group}-${name}`;
54
+ vars[key] = group === 'duration' && typeof v === 'number' ? `${v}s` : Array.isArray(v) && v.length === 4 && v.every((n) => typeof n === 'number') ? `cubic-bezier(${v.join(', ')})` : typeof v === 'number' && /^(caption|size|space|radius)/.test(group) && !/weight/.test(name) ? `${v}px` : String(v);
55
+ }
56
+ }
57
+ return vars;
58
+ }
59
+