@motionhub/remotion 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
@@ -1,10 +1,10 @@
1
1
  # @motionhub/remotion
2
2
 
3
- Use a motion from [motionhub.dev](https://motionhub.dev) in Remotion. Its React components (`motion/react/parts/`) run as they are, drawn by Remotion's frame; its tokens become Remotion values for anything you draw yourself.
3
+ Use a motion from [motionhub.dev](https://motionhub.dev) in Remotion. Its React components (`react/parts/`) run as they are, drawn by Remotion's frame; its tokens become Remotion values for anything you draw yourself.
4
4
 
5
5
  ```sh
6
- npx @motionhub/cli get stage-light # into ./motion
7
- npm i @motionhub/remotion
6
+ npx @motionhub/cli get @iamsuosi/stage-light # into ./motions/@iamsuosi/stage-light/
7
+ npm i @motionhub/remotion @motionhub/runtime
8
8
  ```
9
9
 
10
10
  Wrap the composition once, outside every `<Sequence>`, with the motion's tokens, and use the components with props. Inside a `<Sequence>`, a component's `useTime()` starts with it.
@@ -13,9 +13,9 @@ Wrap the composition once, outside every `<Sequence>`, with the motion's tokens,
13
13
  import {Sequence, interpolate, useCurrentFrame} from 'remotion';
14
14
  import {Caption} from '@motionhub/runtime';
15
15
  import {MotionFonts, MotionProvider} from '@motionhub/remotion';
16
- import tokens from '../motion/tokens.json';
17
- import {Plate} from '../motion/react/parts/plate.tsx';
18
- import {Numeral} from '../motion/react/parts/numeral.tsx';
16
+ import tokens from '../motions/@iamsuosi/stage-light/tokens.json';
17
+ import {Plate} from '../motions/@iamsuosi/stage-light/react/parts/plate.tsx';
18
+ import {Numeral} from '../motions/@iamsuosi/stage-light/react/parts/numeral.tsx';
19
19
 
20
20
  export const Film = () => {
21
21
  const frame = useCurrentFrame();
@@ -31,9 +31,71 @@ export const Film = () => {
31
31
  };
32
32
  ```
33
33
 
34
- - Each component's props are in its file's `meta` (what it is for, what fits it, each parameter) and signature, and `motion/react/previews/<file>.jpg` shows it. A parameter of type `progress` runs from 0 to 1: animate it with `interpolate`.
34
+ - Each component's props are in its file's `meta` (what it is for, what fits it, each parameter) and signature, and the motion's `react/previews/<file>.jpg` shows it. A parameter of type `progress` runs from 0 to 1: animate it with `interpolate`.
35
35
  - `MotionProvider` gives the components their runtime (`@motionhub/runtime`) from Remotion's frame, and sets the tokens as `--color-*`, `--font-*` and `--caption-*` on a full-frame root (`root={false}` leaves it out). A component's `<Video src>` is an `<OffthreadVideo>`: `src` is a URL or a path in `public/`.
36
- - `MotionFonts` loads the faces the tokens name from Google Fonts before the first frame (`han` adds the large Chinese, Japanese and Korean ones). A face it cannot find is named in the console: bundle it with `@remotion/fonts`.
36
+ - A face the motion carries in its `react/fonts/` (`fonts.json` names each) is loaded with `@remotion/fonts`' `loadFont`, from a copy in `public/`.
37
+ - `MotionFonts` loads the faces the tokens name before the first frame, from Google Fonts or, for one it lacks (LXGW WenKai), from where it is. `han` adds the Chinese, Japanese and Korean faces, every part of them (several MB each), since a part fetched only when its text is first drawn arrives too late for that frame. A face no source has is named in the console: bundle it with `@remotion/fonts`.
37
38
  - `useMotion()` turns the tokens into Remotion values: `tokens`, `frames('light')` (a duration in frames), `ease('light')` (an `Easing.bezier`), `progress(frame, start, 'light', 'light')`, for a motion with `duration` and `easing` tokens.
38
39
  - A component that draws in 3D imports `three`: `npm i three`.
39
40
  - The components are imported with their `.tsx` extension; set `"allowImportingTsExtensions": true` and `"noEmit": true` in `tsconfig.json` if you type-check them, and `"resolveJsonModule": true` for `tokens.json`.
41
+
42
+ ## A film of scenes
43
+
44
+ A film drawn as `@motionhub/runtime`'s `<Film>` of `<Scene>`s (0.6 or later; the Open Motion Studio's films are, and its Remotion export
45
+ writes this for one) plays in Remotion with each scene in a `Series.Sequence` of its own, so the scenes are named clips on the Studio's
46
+ timeline. `<FilmScene id>` draws one scene of the film on the sequence's clock; `sceneFrames` gives each its length in frames, and
47
+ `filmMetadata` the composition's, checking that the film's scenes are the ones placed:
48
+
49
+ ```tsx
50
+ import {Composition, Series} from 'remotion';
51
+ import {FilmScene} from '@motionhub/runtime';
52
+ import {MotionProvider, filmMetadata, sceneFrames} from '@motionhub/remotion';
53
+ import Main, {film} from '../film';
54
+
55
+ const frames = sceneFrames(Main, film);
56
+ const scene = (id: string) => <FilmScene id={id}><Main /></FilmScene>;
57
+
58
+ const Film = () => (
59
+ <MotionProvider tokens={{}} root={false}>
60
+ <Series>
61
+ <Series.Sequence name="intro" durationInFrames={frames.intro}>{scene('intro')}</Series.Sequence>
62
+ <Series.Sequence name="how" durationInFrames={frames.how}>{scene('how')}</Series.Sequence>
63
+ </Series>
64
+ </MotionProvider>
65
+ );
66
+
67
+ export const Root = () => (
68
+ <Composition id="film" component={Film} durationInFrames={1} fps={film.fps ?? 30} width={film.width ?? 1920} height={film.height ?? 1080}
69
+ calculateMetadata={() => filmMetadata(Main, film, ['intro', 'how'])} />
70
+ );
71
+ ```
72
+
73
+ Each `Series.Sequence` is written on a line of its own because Remotion Studio's timeline tells sequences apart by where they are written:
74
+ made in a loop, they would show as one row. A scene's seconds are put on whole frames that meet end to end. A scene's length changed in
75
+ the film follows by itself; a scene added, taken out or moved is an error until the `Series` places it. The film's own motions are its
76
+ `<MotionScope>`s, so the provider's tokens can be empty.
77
+
78
+ ## Several motions in one film
79
+
80
+ A film can change motion from scene to scene, or hold two in one frame ([a project's motions](../../SPEC.md#13-a-projects-motions)). Keep one `<MotionProvider>` outside every `<Sequence>`, and wrap each scene in `<MotionScope tokens>` from `@motionhub/runtime` (0.4 or later): the components under it read that motion's tokens and custom properties, and keep Remotion's frame and the film's time. Load every motion's faces before the first frame, each `<MotionFonts>` in its own scope with `root={false}`:
81
+
82
+ ```tsx
83
+ import {Sequence} from 'remotion';
84
+ import {MotionScope} from '@motionhub/runtime';
85
+ import {MotionFonts, MotionProvider} from '@motionhub/remotion';
86
+ import notebook from '../motions/@iamsuosi/lab-notebook/tokens.json';
87
+ import pencil from '../motions/@iamsuosi/red-pencil/tokens.json';
88
+ import {Opening} from '../motions/@iamsuosi/lab-notebook/react/parts/opening.tsx';
89
+ import {Headline} from '../motions/@iamsuosi/red-pencil/react/parts/headline.tsx';
90
+
91
+ export const Film = () => (
92
+ <MotionProvider tokens={notebook} root={false}>
93
+ <MotionScope tokens={notebook} root={false}><MotionFonts /></MotionScope>
94
+ <MotionScope tokens={pencil} root={false}><MotionFonts /></MotionScope>
95
+ <Sequence durationInFrames={150}><MotionScope tokens={notebook}><Opening lines={["Heat pumps"]} /></MotionScope></Sequence>
96
+ <Sequence from={150} durationInFrames={210}><MotionScope tokens={pencil}><Headline title="Where they came from" /></MotionScope></Sequence>
97
+ </MotionProvider>
98
+ );
99
+ ```
100
+
101
+ Do not nest a second `<MotionProvider>` inside a `<Sequence>` for this: it would count the film's time from that sequence's start.
package/film.js ADDED
@@ -0,0 +1,50 @@
1
+ // A film of scenes (@motionhub/runtime's <Film>) in Remotion's frames: each scene's length and the composition's, learned by drawing the
2
+ // film once, off the page, at its start. No Remotion here, so it is tested on its own (test.mjs).
3
+ import {createElement} from 'react';
4
+ import {renderToStaticMarkup} from 'react-dom/server';
5
+ import {MotionRuntimeProvider} from '@motionhub/runtime';
6
+
7
+ /** The structure of the <Film> a component draws */
8
+ function outlineOf(Component, {fps = 30, width = 1920, height = 1080, props = {}}) {
9
+ let outline = null;
10
+ const value = {useTime: () => 0, useCompositionTime: () => 0, fps, width, height, tokens: {}, Video: () => null, onFilm: (o) => { outline = o; }};
11
+ try {
12
+ renderToStaticMarkup(createElement(MotionRuntimeProvider, {value}, createElement(Component, props)));
13
+ } catch (error) {
14
+ throw new Error(`drawing the film once, off the page, at its start, to learn its scenes: ${error.message}. Its motions' tokens are its own <MotionScope>s: the provider here has none`, {cause: error});
15
+ }
16
+ if (!outline) throw new Error('the component draws no <Film> (@motionhub/runtime 0.6)');
17
+ return outline;
18
+ }
19
+
20
+ /** Each scene's frames at `fps`, rounded where it starts and ends so the scenes meet end to end and add up to the film */
21
+ function framesOf(outline, fps) {
22
+ return outline.scenes.map(({id, start, duration}) => {
23
+ const frames = Math.round((start + duration) * fps) - Math.round(start * fps);
24
+ if (frames < 1) throw new Error(`scene "${id}" lasts ${duration} s, less than a frame at ${fps} fps`);
25
+ return [id, frames];
26
+ });
27
+ }
28
+
29
+ /**
30
+ * Each scene of the <Film> a component draws, by id, in whole frames at `fps` that meet end to end and add up to the film: the
31
+ * `durationInFrames` of a Series.Sequence that holds `<FilmScene id>` around the film. A scene shorter than a frame is an error.
32
+ */
33
+ export function sceneFrames(Component, film = {}) {
34
+ return Object.fromEntries(framesOf(outlineOf(Component, film), film.fps ?? 30));
35
+ }
36
+
37
+ /**
38
+ * A composition's metadata for a component that draws a <Film> (`calculateMetadata: () => filmMetadata(Main, film, ['intro', 'how'])`): its
39
+ * length in frames from the film's scenes, so it follows them as they change. With `ids`, the scenes the composition places one by one,
40
+ * the film's scenes must be those, in that order: a scene added, taken out or moved is named in the error.
41
+ */
42
+ export function filmMetadata(Component, film = {}, ids) {
43
+ const {fps = 30, width = 1920, height = 1080} = film;
44
+ const frames = framesOf(outlineOf(Component, film), fps);
45
+ const has = frames.map(([id]) => id);
46
+ if (ids && has.join('\n') !== ids.join('\n')) {
47
+ throw new Error(`the film's scenes are ${has.map((id) => `"${id}"`).join(', ')}, the composition places ${ids.map((id) => `"${id}"`).join(', ')}: give each scene its Series.Sequence, in order`);
48
+ }
49
+ return {durationInFrames: frames.reduce((sum, [, n]) => sum + n, 0), fps, width, height};
50
+ }
package/index.d.ts CHANGED
@@ -2,6 +2,11 @@ import type {FC, ReactNode} from 'react';
2
2
  import type {Tokens} from '@motionhub/runtime';
3
3
 
4
4
  export declare const MotionProvider: FC<{tokens: unknown; root?: boolean; children?: ReactNode}>;
5
+ type FilmOf<P> = {fps?: number; width?: number; height?: number; props?: P};
6
+ /** Each scene of the <Film> a component draws, by id, in whole frames that meet end to end */
7
+ export declare function sceneFrames<P extends object>(Component: FC<P>, film?: FilmOf<P>): Record<string, number>;
8
+ /** A composition's metadata for a component that draws a <Film>: its length in frames from the scenes; with `ids`, the scenes must be those, in order */
9
+ export declare function filmMetadata<P extends object>(Component: FC<P>, film?: FilmOf<P>, ids?: string[]): {durationInFrames: number; fps: number; width: number; height: number};
5
10
  export declare const MotionFonts: FC<{han?: boolean}>;
6
11
  export declare function families(tokens: Tokens | undefined): string[];
7
12
  export declare function useMotion(): {
package/index.js CHANGED
@@ -1,10 +1,13 @@
1
1
  // @motionhub/remotion: a motion in Remotion. <MotionProvider> gives a motion's React components the runtime they draw with
2
2
  // (@motionhub/runtime) from Remotion's own frame, so they run unchanged; <MotionFonts> loads its faces; useMotion() turns its
3
- // tokens into Remotion values (frames, Easing) for anything you draw yourself.
3
+ // tokens into Remotion values (frames, Easing) for anything you draw yourself. For a film of scenes (@motionhub/runtime's <Film>),
4
+ // sceneFrames() and filmMetadata() give each scene and the composition their length in frames, from the scenes.
4
5
  import {createElement, useEffect, useMemo, useState} from 'react';
5
6
  import {Easing, OffthreadVideo, Sequence, continueRender, delayRender, interpolate, staticFile, useCurrentFrame, useVideoConfig} from 'remotion';
6
7
  import {MotionRoot, MotionRuntimeProvider, resolveTokens, useTokens} from '@motionhub/runtime';
7
8
 
9
+ export {filmMetadata, sceneFrames} from './film.js';
10
+
8
11
  const sequenceSeconds = () => useCurrentFrame() / useVideoConfig().fps;
9
12
 
10
13
  /** The runtime's <Video> on Remotion's: `src` (a URL, or a path in public/), shown from `startAt` s, its source from `trimBefore` s */
@@ -28,12 +31,32 @@ export const MotionProvider = ({tokens, root = true, children}) => {
28
31
  return createElement(MotionRuntimeProvider, {value}, root ? createElement(MotionRoot, {tokens: resolved}, children) : children);
29
32
  };
30
33
 
31
- // ---- the motion's faces, from Google Fonts, before the first frame ----
34
+ // ---- the motion's faces, from Google Fonts (or where it has none), before the first frame ----
32
35
  const GENERIC = /^(serif|sans-serif|monospace|cursive|fantasy|system-ui|math|emoji|ui-[a-z-]+)$/;
33
36
  const HAN = /^(Noto (Sans|Serif) (SC|TC|JP|KR)|LXGW WenKai|Fusion Pixel.*)$/;
34
37
  /** The family names in the tokens' font stacks */
35
38
  export const families = (resolved) => [...new Set(Object.values(resolved?.font ?? {}).flatMap((s) => String(s).split(',').map((f) => f.trim().replace(/^["']|["']$/g, ''))))].filter((f) => f && !GENERIC.test(f));
39
+ /**
40
+ * Faces Google Fonts does not have, by family: stylesheets that split them by unicode-range, at an exact version so that a film renders the same
41
+ * next year. Google has only "LXGW WenKai TC", so LXGW WenKai comes from its OFL-1.1 webfont package on npm, through jsDelivr. The same table is
42
+ * in @motionhub/hyperframes (tests/bindings.test.mjs keeps them equal).
43
+ */
44
+ const ELSEWHERE = {
45
+ 'LXGW WenKai': ['regular', 'bold'].map((w) => `https://cdn.jsdelivr.net/npm/lxgw-wenkai-webfont@1.7.0/lxgwwenkai-${w}.css`),
46
+ };
47
+ /** A stylesheet from a URL, its relative `url()`s made absolute: it is set in a <style>, where they would not resolve */
48
+ const sheet = async (href) => {
49
+ const res = await fetch(href).catch(() => undefined);
50
+ if (!res?.ok) return undefined;
51
+ return (await res.text()).replace(/url\((["']?)(?![a-z]+:|\/\/|data:)([^)"']+)\1\)/gi, (_, q, path) => `url(${q}${new URL(path, href).href}${q})`);
52
+ };
53
+ /** The stylesheet texts for a family, [] when no source has it */
36
54
  const css = async (family) => {
55
+ if (ELSEWHERE[family]) return (await Promise.all(ELSEWHERE[family].map(sheet))).filter(Boolean);
56
+ const text = await google(family);
57
+ return text ? [text] : [];
58
+ };
59
+ const google = async (family) => {
37
60
  const name = encodeURIComponent(family).replace(/%20/g, '+');
38
61
  // Google Fonts refuses a weight range a face does not span, so ask for the common ones in turn, then its default weight
39
62
  for (const axes of [':wght@100..900', ':wght@200..900', ':wght@100..800', ':wght@200..800', ':wght@300..800', ':wght@300..700', ':wght@400..700', ':wght@400;700', '']) {
@@ -43,8 +66,8 @@ const css = async (family) => {
43
66
  return undefined;
44
67
  };
45
68
  /**
46
- * Loads the faces the tokens name, inside <MotionProvider>. Faces for Chinese, Japanese and Korean are large and load only with `han`; one Google Fonts
47
- * does not have is named in the console and left to the stack's next face (bundle it with @remotion/fonts).
69
+ * Loads the faces the tokens name, inside <MotionProvider>. Faces for Chinese, Japanese and Korean are large and load only with `han`; one no source
70
+ * has is named in the console and left to the stack's next face (bundle it with @remotion/fonts).
48
71
  */
49
72
  export const MotionFonts = ({han = false}) => {
50
73
  const tokens = useTokens();
@@ -52,12 +75,22 @@ export const MotionFonts = ({han = false}) => {
52
75
  useEffect(() => {
53
76
  const wanted = families(tokens).filter((f) => han || !HAN.test(f));
54
77
  Promise.all(wanted.map(async (family) => {
55
- const text = await css(family);
56
- if (!text) { console.warn(`@motionhub/remotion: Google Fonts has no "${family}"; load it with @remotion/fonts`); return; }
57
- const el = document.createElement('style');
58
- el.textContent = text;
59
- document.head.appendChild(el);
60
- await Promise.all(['400', '700'].map((w) => document.fonts.load(`${w} 32px "${family}"`).catch(() => undefined)));
78
+ const texts = await css(family);
79
+ if (!texts.length) {
80
+ // a face a Chinese, Japanese or Korean motion is written for must not fall back unseen
81
+ const message = `@motionhub/remotion: no source has "${family}"; load it with @remotion/fonts`;
82
+ if (HAN.test(family)) console.error(message); else console.warn(message);
83
+ return;
84
+ }
85
+ for (const text of texts) {
86
+ const el = document.createElement('style');
87
+ el.textContent = text;
88
+ document.head.appendChild(el);
89
+ }
90
+ // a face split by unicode-range fetches a part only when its text is first drawn, too late for that frame: so a Chinese, Japanese or
91
+ // Korean face, whose text no one knows beforehand, is loaded whole; the others need only their latin part, which these loads fetch
92
+ if (HAN.test(family)) await Promise.all([...document.fonts].filter((f) => f.family.replace(/^["']|["']$/g, '') === family).map((f) => f.load().catch(() => undefined)));
93
+ else await Promise.all(['400', '700'].map((w) => document.fonts.load(`${w} 32px "${family}"`).catch(() => undefined)));
61
94
  })).finally(() => continueRender(handle));
62
95
  }, [handle]);
63
96
  return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@motionhub/remotion",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Use a motion from motionhub.dev in Remotion: its React components as they are, and its tokens as Remotion values.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -20,14 +20,22 @@
20
20
  },
21
21
  "files": [
22
22
  "index.js",
23
+ "film.js",
23
24
  "index.d.ts",
24
25
  "README.md"
25
26
  ],
26
- "dependencies": {
27
- "@motionhub/runtime": "0.1.0"
28
- },
29
27
  "peerDependencies": {
28
+ "@motionhub/runtime": "^0.6.0",
29
+ "react-dom": ">=18",
30
30
  "react": ">=18",
31
31
  "remotion": ">=4"
32
+ },
33
+ "scripts": {
34
+ "test": "node --test test.mjs"
35
+ },
36
+ "devDependencies": {
37
+ "@motionhub/runtime": "file:../runtime",
38
+ "react": "19.1.1",
39
+ "react-dom": "19.1.1"
32
40
  }
33
41
  }