@motionhub/runtime 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # @motionhub/runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ What a motion's React components draw with, in any engine: their time, their frame, the motion's tokens, seeded randomness, video and a caption. The components in a motion's `react/parts/` import only this and React, so they run unchanged wherever an engine provides it.
4
+
5
+ You do not use this package on its own: an engine binding provides it.
6
+
7
+ - **Remotion**: [`@motionhub/remotion`](../remotion/README.md)
8
+ - **HyperFrames**: [`@motionhub/hyperframes`](../hyperframes/README.md)
9
+
10
+ | Export | What it is |
11
+ | --- | --- |
12
+ | `useTime()` | Seconds since the component's sequence began (a Remotion `<Sequence>`, a HyperFrames composition) |
13
+ | `useCompositionTime()` | Seconds since the film began, for motion that must run on across sequences |
14
+ | `useCurrentFrame()`, `useVideoConfig()` | As Remotion's: the sequence's frame, and `{width, height, fps}` |
15
+ | `useTokens()` | The motion's `tokens.json` resolved: `color.ink` (a CSS colour), `font.display` (a CSS stack), `duration.light` (seconds), `easing.light` (`[x1, y1, x2, y2]`), `caption.*` |
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
+ | `<Video src startAt trimBefore playbackRate objectFit>` | The engine's video: shown from `startAt` s of the sequence, its source from `trimBefore` s |
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 |
20
+ | `<MotionRoot tokens>` | A full-frame box carrying the tokens as CSS custom properties |
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` |
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.
24
+
25
+ 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 ADDED
@@ -0,0 +1,44 @@
1
+ import type {CSSProperties, FC, ReactNode} from 'react';
2
+
3
+ /** A stream of numbers in [0, 1) for `seed`: the same seed gives the same stream everywhere */
4
+ export declare function seededRandom(seed: string | number): () => number;
5
+
6
+ /** A motion's tokens resolved, group by group: `tokens.color.ink` (a CSS colour), `tokens.font.display` (a CSS stack), `tokens.duration.light` (seconds) */
7
+ export type Tokens = {
8
+ color?: Record<string, string>;
9
+ font?: Record<string, string>;
10
+ duration?: Record<string, number>;
11
+ easing?: Record<string, [number, number, number, number]>;
12
+ caption?: Record<string, string | number>;
13
+ [group: string]: Record<string, unknown> | undefined;
14
+ };
15
+ export declare function resolveTokens(dtcg: unknown): Tokens;
16
+ export declare function tokenVariables(tokens: Tokens | undefined): Record<string, string>;
17
+
18
+ export type VideoProps = {src: string; startAt?: number; trimBefore?: number; playbackRate?: number; objectFit?: 'cover' | 'contain' | 'fill'; style?: CSSProperties};
19
+ export type MotionRuntime = {
20
+ /** seconds since the component's sequence began (a hook) */
21
+ useTime(): number;
22
+ /** seconds since the film began (a hook) */
23
+ useCompositionTime(): number;
24
+ fps: number;
25
+ width: number;
26
+ height: number;
27
+ tokens?: Tokens;
28
+ Video?: FC<VideoProps>;
29
+ };
30
+ export declare const MotionRuntimeProvider: FC<{value: MotionRuntime; children?: ReactNode}>;
31
+
32
+ export declare const useTime: () => number;
33
+ export declare const useCompositionTime: () => number;
34
+ export declare const useCurrentFrame: () => number;
35
+ export declare const useVideoConfig: () => {width: number; height: number; fps: number};
36
+ export declare const useTokens: () => Tokens;
37
+ export declare const Video: FC<VideoProps>;
38
+ export declare const MotionRoot: FC<{tokens?: Tokens; style?: CSSProperties; children?: ReactNode}>;
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 ADDED
@@ -0,0 +1,134 @@
1
+ // @motionhub/runtime: what a motion's React components draw with, in any engine. A component reads its time and its
2
+ // frame size from the engine and its values from the motion's tokens, never from a clock or a page of its own, so the same
3
+ // moment always draws the same picture. The names follow Remotion's where it has one (useCurrentFrame, useVideoConfig),
4
+ // the motion's tokens follow the W3C design tokens format, and their CSS custom properties follow Style Dictionary's
5
+ // naming (--color-ink, --font-display). An engine binding (@motionhub/remotion, @motionhub/hyperframes, or an engine's own) supplies
6
+ // the runtime through <MotionRuntimeProvider>; this package holds no engine.
7
+ import {createContext, createElement, useContext} from 'react';
8
+
9
+ // ---- seeded randomness: the same seed gives the same stream on every machine and in every engine ----
10
+ /** mulberry32 */
11
+ const prng = (seed) => {
12
+ let a = seed >>> 0;
13
+ return () => {
14
+ a = (a + 0x6d2b79f5) >>> 0;
15
+ let t = a;
16
+ t = Math.imul(t ^ (t >>> 15), t | 1);
17
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
18
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
19
+ };
20
+ };
21
+ /** FNV-1a: a string seed to 32 bits */
22
+ const hash = (key) => {
23
+ let h = 0x811c9dc5;
24
+ for (let i = 0; i < key.length; i++) {
25
+ h ^= key.charCodeAt(i);
26
+ h = Math.imul(h, 0x01000193);
27
+ }
28
+ return h >>> 0;
29
+ };
30
+ /** A stream of numbers in [0, 1) for `seed` (a string or a number): call it for each next number */
31
+ export const seededRandom = (seed) => prng(typeof seed === 'number' ? seed : hash(String(seed)));
32
+
33
+ export {resolveTokens, tokenVariables} from './tokens.js';
34
+ import {tokenVariables} from './tokens.js';
35
+
36
+ // ---- the runtime an engine provides ----
37
+ const Runtime = createContext(null);
38
+ /**
39
+ * The engine's side: `value` has `useTime()` (seconds since the component's sequence began, a hook), `useCompositionTime()` (seconds since the film
40
+ * began, a hook), `fps`, `width`, `height`, `tokens` (resolved, as resolveTokens gives them) and, if the engine plays video, `Video`.
41
+ */
42
+ export const MotionRuntimeProvider = ({value, children}) => createElement(Runtime.Provider, {value}, children);
43
+ const runtime = () => {
44
+ const r = useContext(Runtime);
45
+ if (!r) throw new Error('a motion component was drawn outside its engine: wrap the film in the binding\'s provider (@motionhub/remotion <MotionProvider>, @motionhub/hyperframes Motion.mount)');
46
+ return r;
47
+ };
48
+
49
+ /** Seconds since this component's sequence began (Remotion: a <Sequence>; HyperFrames: a composition; another engine: its scene) */
50
+ export const useTime = () => runtime().useTime();
51
+ /** Seconds since the whole film began */
52
+ export const useCompositionTime = () => runtime().useCompositionTime();
53
+ /** This sequence's frame, as Remotion's useCurrentFrame() */
54
+ export const useCurrentFrame = () => Math.round(useTime() * runtime().fps);
55
+ /** The film's frame size and rate, as Remotion's useVideoConfig() */
56
+ export const useVideoConfig = () => { const r = runtime(); return {width: r.width, height: r.height, fps: r.fps}; };
57
+ /** The motion's tokens, resolved: `useTokens().color.ink` */
58
+ export const useTokens = () => runtime().tokens ?? {};
59
+
60
+ /** A video, timed by its sequence: shown from `startAt` seconds, playing its source from `trimBefore` seconds at `playbackRate`, fitted by `objectFit` */
61
+ export const Video = (props) => {
62
+ const V = runtime().Video;
63
+ if (!V) throw new Error(`<Video src="${props.src}">: this engine's binding plays no video`);
64
+ return createElement(V, props);
65
+ };
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
+
113
+ /** The ground a motion's components expect: the tokens as custom properties, filling the frame */
114
+ export const MotionRoot = ({tokens, style, children}) => createElement('div', {
115
+ style: {position: 'absolute', inset: 0, overflow: 'hidden', ...tokenVariables(tokens), ...style},
116
+ }, children);
117
+
118
+ /**
119
+ * The motion's caption: one spoken line on the frame, drawn from the caption group of its tokens: font, size, weight, color, background, radius,
120
+ * padding-y, padding-x, bottom, max-width, shadow (a text shadow), and a rule: rule-left (a bar down its left side) or rule-top (a short bar above it).
121
+ * `opacity` fades it; it stays a function of what you pass.
122
+ */
123
+ export const Caption = ({children, opacity = 1, style}) => {
124
+ const c = useTokens().caption ?? {};
125
+ const py = c['padding-y'] ?? 10, pad = `${py}px ${c['padding-x'] ?? 26}px`;
126
+ const rule = c['rule-left']
127
+ ? createElement('div', {style: {position: 'absolute', left: 0, top: py * 0.6, bottom: py * 0.6, width: 4, borderRadius: 2, background: c['rule-left']}})
128
+ : c['rule-top'] ? createElement('div', {style: {width: 56, height: 3, background: c['rule-top'], margin: '0 auto 8px'}}) : null;
129
+ return createElement('div', {style: {position: 'absolute', left: 0, right: 0, bottom: c.bottom ?? 54, display: 'flex', justifyContent: 'center', opacity, pointerEvents: 'none'}},
130
+ createElement('div', {style: {
131
+ position: 'relative', maxWidth: c['max-width'] ?? 1500, textAlign: 'center', fontFamily: c.font, fontSize: c.size ?? 34, fontWeight: c.weight ?? 400, lineHeight: 1.35,
132
+ color: c.color, background: c.background ?? 'transparent', padding: pad, borderRadius: c.radius ?? 10, textShadow: c.shadow, ...style,
133
+ }}, rule, children));
134
+ };
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@motionhub/runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "What a motion's React components draw with (time, frame, tokens, seeded randomness, video, caption), in any engine that provides it.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/motionhub-dev/motions.git",
9
+ "directory": "packages/runtime"
10
+ },
11
+ "homepage": "https://motionhub.dev",
12
+ "type": "module",
13
+ "main": "index.js",
14
+ "types": "index.d.ts",
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
+ }
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
+