@motionhub/runtime 0.4.0 → 0.5.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 (4) hide show
  1. package/README.md +32 -1
  2. package/index.d.ts +19 -0
  3. package/index.js +108 -2
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -19,12 +19,43 @@ You do not use this package on its own: an engine binding provides it.
19
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
20
  | `<MotionRoot tokens>` | A full-frame box carrying the tokens as CSS custom properties |
21
21
  | `<MotionScope tokens root>` | Its children drawn in another motion, on the engine's clock: `useTokens()` under it gives that motion's tokens (a `tokens.json`, or tokens already resolved), set as custom properties on a full-frame root (`root={false}` leaves it out). A film in several motions wraps each scene, or each part of a frame, in one |
22
+ | `<Film>`, `<Scene id duration>`, `<Layer id x y w h z>`, `<Line id text>` | A film made of scenes, for an engine that plays a whole film rather than one component: below |
22
23
  | `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` |
23
24
 
24
25
  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.
25
26
 
27
+ ## A film of scenes
28
+
29
+ A film written for an engine that draws it whole (the Open Motion Studio's, for one) can say what it is made of, so the engine can show and
30
+ check it scene by scene without running it:
31
+
32
+ ```tsx
33
+ <Film>
34
+ <Layer id="logo" x={60} y={50} w={240} h={80}>…</Layer>
35
+ <Scene id="intro" duration={4}>
36
+ <Line id="l1">Heat moves uphill.</Line>
37
+ <Layer id="title" y={320} h={440}>…</Layer>
38
+ </Scene>
39
+ <Scene id="how" duration={6}>…</Scene>
40
+ </Film>
41
+ ```
42
+
43
+ - **`<Scene id duration>`**: the scenes are laid end to end, so the film is as long as their durations together (each a finite number of
44
+ seconds above 0). A scene is drawn only in its span, and `useTime()` inside it counts from its start; the last one holds at the film's
45
+ end, and past the end no scene is drawn.
46
+ - **`<Layer id x y w h z>`**: a box of the frame in its pixels (the whole frame when left out), stacked by `z`, shown for the whole of its
47
+ scene. How its content moves is the content's own, from `useTime()`. A layer that is a child of `<Film>` is the film's own: drawn across
48
+ every scene, on the film's clock, and no scene's layer may take its id, since a picked element is told by its layer.
49
+ - **`<Line id text>`**: what a scene says, its words as children (`text` where the caption differs). It draws nothing; an engine may speak
50
+ it or caption it.
51
+ - Anything else among `<Film>`'s children is drawn across the whole film.
52
+ - `filmOutline(children, {width, height})` reads that structure from the elements themselves, without drawing them: `{seconds, scenes:
53
+ [{id, start, duration, layers, lines}], layers}`. `<Film>` reports it to the engine's `onFilm` while it is drawn, once for each structure (a new `onFilm` function on every
54
+ render is not called again for the same structure), when its value has one. A scene without an
55
+ id or a positive duration, and an id used twice (scenes, lines, layers in one scene, the film's own layers), is an error.
56
+
26
57
  ## Sound
27
58
 
28
59
  `@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.
29
60
 
30
- 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`.
61
+ An engine binding passes `<MotionRuntimeProvider value>` an object with `useTime` and `useCompositionTime` (hooks returning seconds), `fps`, `width`, `height`, `tokens` (resolved), if it plays video `Video`, and, if it wants a `<Film>`'s structure, `onFilm(outline)`.
package/index.d.ts CHANGED
@@ -26,6 +26,8 @@ export type MotionRuntime = {
26
26
  height: number;
27
27
  tokens?: Tokens;
28
28
  Video?: FC<VideoProps>;
29
+ /** called with a <Film>'s structure when it is drawn */
30
+ onFilm?(outline: FilmOutline): void;
29
31
  };
30
32
  export declare const MotionRuntimeProvider: FC<{value: MotionRuntime; children?: ReactNode}>;
31
33
 
@@ -44,3 +46,20 @@ export type EasingFn = (x: number) => number;
44
46
  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};
45
47
  export declare function interpolate(input: number, inputRange: number[], outputRange: number[], options?: {easing?: EasingFn; clamp?: boolean}): number;
46
48
  export declare const Sequence: FC<{from?: number; duration?: number; children?: ReactNode}>;
49
+
50
+ /** A box of the frame, in its pixels */
51
+ export type LayerBox = {id: string; x: number; y: number; w: number; h: number; z: number};
52
+ /** A <Film>'s structure: its length, its scenes in order (each from `start` seconds), and its own layers, drawn across every scene */
53
+ export type FilmOutline = {
54
+ seconds: number;
55
+ scenes: {id: string; start: number; duration: number; layers: LayerBox[]; lines: {id: string; text: string}[]}[];
56
+ layers: LayerBox[];
57
+ };
58
+ export declare function filmOutline(children: ReactNode, frame?: {width?: number; height?: number}): FilmOutline;
59
+ /** Its <Scene>s laid end to end, each drawn in its span on its own clock; anything else drawn across them all */
60
+ export declare const Film: FC<{children?: ReactNode}>;
61
+ export declare const Scene: FC<{id: string; duration: number; children?: ReactNode}>;
62
+ /** A box of the frame (`x`, `y`, `w`, `h` in pixels, the whole frame when left out), stacked by `z`, shown for its whole scene */
63
+ export declare const Layer: FC<{id: string; x?: number; y?: number; w?: number; h?: number; z?: number; style?: CSSProperties; children?: ReactNode}>;
64
+ /** What a scene says; it draws nothing */
65
+ export declare const Line: FC<{id: string; text?: string; children?: ReactNode}>;
package/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // the motion's tokens follow the W3C design tokens format, and their CSS custom properties follow Style Dictionary's
5
5
  // naming (--color-ink, --font-display). An engine binding (@motionhub/remotion, @motionhub/hyperframes, or an engine's own) supplies
6
6
  // the runtime through <MotionRuntimeProvider>; this package holds no engine.
7
- import {createContext, createElement, useContext, useMemo} from 'react';
7
+ import {Children, Fragment, createContext, createElement, isValidElement, useContext, useMemo} from 'react';
8
8
 
9
9
  // ---- seeded randomness: the same seed gives the same stream on every machine and in every engine ----
10
10
  /** mulberry32 */
@@ -37,7 +37,8 @@ import {resolveTokens, tokenVariables} from './tokens.js';
37
37
  const Runtime = createContext(null);
38
38
  /**
39
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`.
40
+ * began, a hook), `fps`, `width`, `height`, `tokens` (resolved, as resolveTokens gives them), if the engine plays video `Video`, and, if it wants a
41
+ * <Film>'s structure, `onFilm(outline)`.
41
42
  */
42
43
  export const MotionRuntimeProvider = ({value, children}) => createElement(Runtime.Provider, {value}, children);
43
44
  const runtime = () => {
@@ -110,6 +111,111 @@ export const Sequence = ({from = 0, duration = Infinity, children}) => {
110
111
  return createElement(Runtime.Provider, {value}, children);
111
112
  };
112
113
 
114
+ // ---- a film's structure: scenes laid end to end, each with its layers (boxes of React) and its lines (what it says) ----
115
+ const InFilm = createContext(false);
116
+
117
+ /** The elements among `children`, fragments opened */
118
+ const elements = (children) => Children.toArray(children).flatMap((c) => (isValidElement(c) && c.type === Fragment ? elements(c.props.children) : [c]));
119
+ /** The words of a node's text, its markup left out */
120
+ const words = (node) => (typeof node === 'string' || typeof node === 'number' ? String(node) : isValidElement(node) ? words(node.props.children) : Array.isArray(node) ? node.map(words).join('') : '');
121
+ const named = (what, id) => {
122
+ if (typeof id !== 'string' || !id) throw new Error(`a <${what}> needs an id`);
123
+ return id;
124
+ };
125
+
126
+ /**
127
+ * The structure of a <Film>'s children, read from the elements themselves without drawing them, so it is known before the first frame:
128
+ * `{seconds, scenes: [{id, start, duration, layers, lines}], layers}`, a layer `{id, x, y, w, h, z}` in the frame's pixels (a box left out
129
+ * fills the frame), a line `{id, text}`. `layers` are the film's own, drawn across every scene. A scene without an id or a positive
130
+ * duration, and an id used twice where it must be unique, are errors.
131
+ */
132
+ export function filmOutline(children, {width = 1920, height = 1080} = {}) {
133
+ const box = (e) => ({id: named('Layer', e.props.id), x: e.props.x ?? 0, y: e.props.y ?? 0, w: e.props.w ?? width, h: e.props.h ?? height, z: e.props.z ?? 0});
134
+ const unique = (what, items) => {
135
+ const seen = new Set();
136
+ for (const {id} of items) {
137
+ if (seen.has(id)) throw new Error(`two ${what} are called "${id}"`);
138
+ seen.add(id);
139
+ }
140
+ return items;
141
+ };
142
+ const scenes = [];
143
+ const layers = [];
144
+ let start = 0;
145
+ for (const e of elements(children)) {
146
+ if (!isValidElement(e)) continue;
147
+ if (e.type === Scene) {
148
+ const id = named('Scene', e.props.id);
149
+ const {duration} = e.props;
150
+ if (!(Number.isFinite(duration) && duration > 0)) throw new Error(`<Scene id="${id}"> needs its duration in seconds: duration={4}`);
151
+ const inner = elements(e.props.children).filter(isValidElement);
152
+ const lines = inner.filter((c) => c.type === Line).map((c) => ({id: named('Line', c.props.id), text: c.props.text ?? words(c.props.children)}));
153
+ scenes.push({id, start, duration, layers: unique(`layers in scene "${id}"`, inner.filter((c) => c.type === Layer).map(box)), lines});
154
+ start += duration;
155
+ } else if (e.type === Layer) {
156
+ layers.push(box(e));
157
+ }
158
+ }
159
+ if (!scenes.length) throw new Error('a <Film> needs at least one <Scene>');
160
+ unique('scenes', scenes);
161
+ unique('lines', scenes.flatMap((scene) => scene.lines));
162
+ unique('of the film\'s own layers', layers);
163
+ // A picked element is told by its layer's id, so a scene's layer may not take the name of one drawn across the film.
164
+ for (const scene of scenes) {
165
+ const taken = scene.layers.find((layer) => layers.some((own) => own.id === layer.id));
166
+ if (taken) throw new Error(`scene "${scene.id}" has a layer called "${taken.id}", the name of one of the film's own layers`);
167
+ }
168
+ return {seconds: start, scenes, layers};
169
+ }
170
+
171
+ /**
172
+ * A film made of scenes: its <Scene>s laid end to end, each drawn only in its span with useTime() counting from its start (the last one holds
173
+ * at the film's end), and anything else among its children (a <Layer>, a background) drawn across them all. It reports its structure
174
+ * (filmOutline) to the engine's `onFilm`, if the engine has one, while it is drawn: the engine learns the length from the scenes.
175
+ */
176
+ export const Film = ({children}) => {
177
+ const r = runtime();
178
+ // Read on every frame (it is cheap: a film's children are new elements each frame), and reported while drawing, once for each
179
+ // structure, whether or not the engine's onFilm is the same function each time: an engine that renders the film once, off the
180
+ // page, learns it before the first frame is shown.
181
+ const outline = filmOutline(children, r);
182
+ const reported = JSON.stringify(outline);
183
+ const onFilm = r.onFilm;
184
+ useMemo(() => onFilm?.(JSON.parse(reported)), [reported]); // eslint-disable-line react-hooks/exhaustive-deps
185
+ const t = r.useTime();
186
+ let index = 0;
187
+ return createElement(InFilm.Provider, {value: true}, elements(children).map((e) => {
188
+ if (!isValidElement(e) || e.type !== Scene) return e;
189
+ const scene = outline.scenes[index++];
190
+ const last = index === outline.scenes.length;
191
+ if (t < scene.start || (t >= scene.start + scene.duration && !(last && t <= outline.seconds))) return null;
192
+ const value = {...r, useTime: () => r.useTime() - scene.start};
193
+ return createElement(Runtime.Provider, {key: e.key ?? scene.id, value}, e);
194
+ }));
195
+ };
196
+
197
+ /** One scene of a <Film>: `duration` seconds of it, `id` naming it. Its children (<Layer>s, <Line>s) belong to it and end with it */
198
+ export const Scene = ({id, children}) => {
199
+ if (!useContext(InFilm)) throw new Error(`<Scene id="${id}"> is drawn only inside a <Film>`);
200
+ return createElement('div', {'data-scene': id, style: {position: 'absolute', inset: 0}}, children);
201
+ };
202
+
203
+ /**
204
+ * A box of the frame, `x`, `y`, `w`, `h` in its pixels (the whole frame when left out), stacked by `z`: what it draws is its children, on the
205
+ * clock of the scene it is in (of the film, for one of the film's own). It is shown for the whole of its scene; how its content moves is the
206
+ * content's own, from useTime().
207
+ */
208
+ export const Layer = ({id, x = 0, y = 0, w, h, z = 0, style, children}) => {
209
+ const {width, height} = runtime();
210
+ return createElement('div', {
211
+ 'data-layer': id,
212
+ style: {position: 'absolute', left: x, top: y, width: w ?? width, height: h ?? height, zIndex: z, ...style},
213
+ }, children);
214
+ };
215
+
216
+ /** What a scene says: its words (the children, or `text` where the caption differs). It draws nothing; an engine may speak or caption it */
217
+ export const Line = () => null;
218
+
113
219
  /** The ground a motion's components expect: the tokens as custom properties, filling the frame */
114
220
  export const MotionRoot = ({tokens, style, children}) => createElement('div', {
115
221
  style: {position: 'absolute', inset: 0, overflow: 'hidden', ...tokenVariables(tokens), ...style},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@motionhub/runtime",
3
- "version": "0.4.0",
3
+ "version": "0.5.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
6
  "repository": {