@motionhub/runtime 0.1.0 → 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.
package/README.md CHANGED
@@ -16,6 +16,7 @@ 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
 
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,38 @@
1
1
  {
2
2
  "name": "@motionhub/runtime",
3
- "version": "0.1.0",
3
+ "version": "0.2.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
+ },
22
+ "files": [
23
+ "index.js",
24
+ "tokens.js",
25
+ "index.d.ts",
26
+ "README.md"
27
+ ],
28
+ "scripts": {
29
+ "test": "node --test test.mjs"
30
+ },
31
+ "devDependencies": {
32
+ "react": "19.1.1",
33
+ "react-dom": "19.1.1"
34
+ },
35
+ "peerDependencies": {
36
+ "react": ">=18"
37
+ }
16
38
  }
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
+