@motionhub/remotion 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.
Files changed (4) hide show
  1. package/README.md +39 -2
  2. package/index.d.ts +13 -0
  3. package/index.js +112 -0
  4. package/package.json +29 -4
package/README.md CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ # @motionhub/remotion
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
+ 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.
4
+
5
+ ```sh
6
+ npx @motionhub/cli get @iamsuosi/stage-light # into ./motion
7
+ npm i @motionhub/remotion @motionhub/runtime
8
+ ```
9
+
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.
11
+
12
+ ```tsx
13
+ import {Sequence, interpolate, useCurrentFrame} from 'remotion';
14
+ import {Caption} from '@motionhub/runtime';
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';
19
+
20
+ export const Film = () => {
21
+ const frame = useCurrentFrame();
22
+ const value = interpolate(frame, [30, 90], [0, 3], {extrapolateLeft: 'clamp', extrapolateRight: 'clamp'});
23
+ return (
24
+ <MotionProvider tokens={tokens}>
25
+ <MotionFonts />
26
+ <div style={{position: 'absolute', left: 200, top: 170, width: 680, height: 200}}><Plate title="Heat pump" sub="1 kWh in" /></div>
27
+ <div style={{position: 'absolute', left: 200, top: 420, width: 680, height: 360}}><Numeral value={value} unit="kWh" accent /></div>
28
+ <Sequence from={30} durationInFrames={90}><Caption>A heat pump moves three units of heat for each one it uses.</Caption></Sequence>
29
+ </MotionProvider>
30
+ );
31
+ };
32
+ ```
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`.
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
+ - A face the motion carries in `motion/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`.
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.
39
+ - A component that draws in 3D imports `three`: `npm i three`.
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`.
package/index.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type {FC, ReactNode} from 'react';
2
+ import type {Tokens} from '@motionhub/runtime';
3
+
4
+ export declare const MotionProvider: FC<{tokens: unknown; root?: boolean; children?: ReactNode}>;
5
+ export declare const MotionFonts: FC<{han?: boolean}>;
6
+ export declare function families(tokens: Tokens | undefined): string[];
7
+ export declare function useMotion(): {
8
+ tokens: Tokens;
9
+ fps: number;
10
+ frames(duration: string): number;
11
+ ease(easing: string): (t: number) => number;
12
+ progress(frame: number, start: number, duration: string, easing?: string): number;
13
+ };
package/index.js ADDED
@@ -0,0 +1,112 @@
1
+ // @motionhub/remotion: a motion in Remotion. <MotionProvider> gives a motion's React components the runtime they draw with
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.
4
+ import {createElement, useEffect, useMemo, useState} from 'react';
5
+ import {Easing, OffthreadVideo, Sequence, continueRender, delayRender, interpolate, staticFile, useCurrentFrame, useVideoConfig} from 'remotion';
6
+ import {MotionRoot, MotionRuntimeProvider, resolveTokens, useTokens} from '@motionhub/runtime';
7
+
8
+ const sequenceSeconds = () => useCurrentFrame() / useVideoConfig().fps;
9
+
10
+ /** The runtime's <Video> on Remotion's: `src` (a URL, or a path in public/), shown from `startAt` s, its source from `trimBefore` s */
11
+ const RemotionVideo = ({src, startAt = 0, trimBefore = 0, playbackRate = 1, objectFit = 'cover', style}) => {
12
+ const {fps} = useVideoConfig();
13
+ const url = /^(https?:|\/|data:|blob:)/.test(src) ? src : staticFile(src);
14
+ return createElement(Sequence, {from: Math.round(startAt * fps), layout: 'none'},
15
+ createElement(OffthreadVideo, {src: url, trimBefore: Math.round(trimBefore * fps), playbackRate, style: {width: '100%', height: '100%', objectFit, ...style}}));
16
+ };
17
+
18
+ /**
19
+ * Wrap the composition in it once, outside every <Sequence>, with the motion's tokens.json: `import tokens from '../motion/tokens.json'`. Its components
20
+ * then draw by Remotion's frame: useTime() inside a <Sequence> counts from its start. `root={false}` leaves out the full-frame root that sets the
21
+ * tokens' custom properties (--color-*, --font-*).
22
+ */
23
+ export const MotionProvider = ({tokens, root = true, children}) => {
24
+ const frame = useCurrentFrame();
25
+ const {fps, width, height} = useVideoConfig();
26
+ const resolved = useMemo(() => resolveTokens(tokens), [tokens]);
27
+ const value = {useTime: sequenceSeconds, useCompositionTime: () => frame / fps, fps, width, height, tokens: resolved, Video: RemotionVideo};
28
+ return createElement(MotionRuntimeProvider, {value}, root ? createElement(MotionRoot, {tokens: resolved}, children) : children);
29
+ };
30
+
31
+ // ---- the motion's faces, from Google Fonts (or where it has none), before the first frame ----
32
+ const GENERIC = /^(serif|sans-serif|monospace|cursive|fantasy|system-ui|math|emoji|ui-[a-z-]+)$/;
33
+ const HAN = /^(Noto (Sans|Serif) (SC|TC|JP|KR)|LXGW WenKai|Fusion Pixel.*)$/;
34
+ /** The family names in the tokens' font stacks */
35
+ 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));
36
+ /**
37
+ * 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
38
+ * 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
39
+ * in @motionhub/hyperframes (tests/bindings.test.mjs keeps them equal).
40
+ */
41
+ const ELSEWHERE = {
42
+ 'LXGW WenKai': ['regular', 'bold'].map((w) => `https://cdn.jsdelivr.net/npm/lxgw-wenkai-webfont@1.7.0/lxgwwenkai-${w}.css`),
43
+ };
44
+ /** A stylesheet from a URL, its relative `url()`s made absolute: it is set in a <style>, where they would not resolve */
45
+ const sheet = async (href) => {
46
+ const res = await fetch(href).catch(() => undefined);
47
+ if (!res?.ok) return undefined;
48
+ return (await res.text()).replace(/url\((["']?)(?![a-z]+:|\/\/|data:)([^)"']+)\1\)/gi, (_, q, path) => `url(${q}${new URL(path, href).href}${q})`);
49
+ };
50
+ /** The stylesheet texts for a family, [] when no source has it */
51
+ const css = async (family) => {
52
+ if (ELSEWHERE[family]) return (await Promise.all(ELSEWHERE[family].map(sheet))).filter(Boolean);
53
+ const text = await google(family);
54
+ return text ? [text] : [];
55
+ };
56
+ const google = async (family) => {
57
+ const name = encodeURIComponent(family).replace(/%20/g, '+');
58
+ // Google Fonts refuses a weight range a face does not span, so ask for the common ones in turn, then its default weight
59
+ 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', '']) {
60
+ const res = await fetch(`https://fonts.googleapis.com/css2?family=${name}${axes}&display=block`).catch(() => undefined);
61
+ if (res?.ok) return res.text();
62
+ }
63
+ return undefined;
64
+ };
65
+ /**
66
+ * Loads the faces the tokens name, inside <MotionProvider>. Faces for Chinese, Japanese and Korean are large and load only with `han`; one no source
67
+ * has is named in the console and left to the stack's next face (bundle it with @remotion/fonts).
68
+ */
69
+ export const MotionFonts = ({han = false}) => {
70
+ const tokens = useTokens();
71
+ const [handle] = useState(() => delayRender('the motion\'s faces'));
72
+ useEffect(() => {
73
+ const wanted = families(tokens).filter((f) => han || !HAN.test(f));
74
+ Promise.all(wanted.map(async (family) => {
75
+ const texts = await css(family);
76
+ if (!texts.length) {
77
+ // a face a Chinese, Japanese or Korean motion is written for must not fall back unseen
78
+ const message = `@motionhub/remotion: no source has "${family}"; load it with @remotion/fonts`;
79
+ if (HAN.test(family)) console.error(message); else console.warn(message);
80
+ return;
81
+ }
82
+ for (const text of texts) {
83
+ const el = document.createElement('style');
84
+ el.textContent = text;
85
+ document.head.appendChild(el);
86
+ }
87
+ // 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
88
+ // Korean face, whose text no one knows beforehand, is loaded whole; the others need only their latin part, which these loads fetch
89
+ if (HAN.test(family)) await Promise.all([...document.fonts].filter((f) => f.family.replace(/^["']|["']$/g, '') === family).map((f) => f.load().catch(() => undefined)));
90
+ else await Promise.all(['400', '700'].map((w) => document.fonts.load(`${w} 32px "${family}"`).catch(() => undefined)));
91
+ })).finally(() => continueRender(handle));
92
+ }, [handle]);
93
+ return null;
94
+ };
95
+
96
+ /**
97
+ * The tokens as Remotion values, inside <MotionProvider>: `tokens`, `frames('light')` (a duration token in frames), `ease('light')` (an easing token as
98
+ * Easing.bezier), and `progress(frame, start, 'light', 'light')`: 0 to 1 over that duration with that curve, clamped.
99
+ */
100
+ export function useMotion() {
101
+ const tokens = useTokens();
102
+ const {fps} = useVideoConfig();
103
+ const need = (group, name) => {
104
+ const v = tokens[group]?.[name];
105
+ if (v === undefined) throw new Error(`the motion has no ${group} token "${name}": it has ${Object.keys(tokens[group] ?? {}).join(', ') || 'none'}`);
106
+ return v;
107
+ };
108
+ const frames = (name) => Math.max(1, Math.round(need('duration', name) * fps));
109
+ const ease = (name) => Easing.bezier(...need('easing', name));
110
+ const progress = (frame, start, duration, easing) => interpolate(frame, [start, start + frames(duration)], [0, 1], {easing: easing ? ease(easing) : undefined, extrapolateLeft: 'clamp', extrapolateRight: 'clamp'});
111
+ return {tokens, fps, frames, ease, progress};
112
+ }
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@motionhub/remotion",
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": "Use a motion from motionhub.dev in Remotion: its React components as they are, and its tokens as Remotion values.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/motionhub-dev/motions.git",
9
+ "directory": "packages/remotion"
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
+ },
21
+ "files": [
22
+ "index.js",
23
+ "index.d.ts",
24
+ "README.md"
25
+ ],
26
+ "peerDependencies": {
27
+ "@motionhub/runtime": "^0.3.0",
28
+ "react": ">=18",
29
+ "remotion": ">=4"
30
+ }
31
+ }