🎥 Make videos programmatically with React
Docs: Add examples page template
Igor Samokhovets6893c0c2bfcb
diff --git a/packages/docs/docusaurus.config.ts b/packages/docs/docusaurus.config.tsindex 58123c8bde..8f4a5431fc 100644--- a/packages/docs/docusaurus.config.ts+++ b/packages/docs/docusaurus.config.ts@@ -282,7 +282,12 @@ const config: Config = {'https://github.com/remotion-dev/remotion/edit/main/packages/docs/blog/',},theme: {- customCss: [require.resolve('./src/css/custom.css')],+ customCss: [+ require.resolve('./src/css/custom.css'),+ require.resolve(+ './docusaurus-theme-shiki-twoslash/theme/CodeBlock/styles.css',+ ),+ ],},},],diff --git a/packages/docs/examples-sidebars.ts b/packages/docs/examples-sidebars.tsindex 6f6736525e..a66e65b9c1 100644--- a/packages/docs/examples-sidebars.ts+++ b/packages/docs/examples-sidebars.ts@@ -4,7 +4,7 @@ import type {SidebarsConfig} from '@docusaurus/plugin-content-docs';const sidebars: SidebarsConfig = {examplesSidebar: ['index',- 'suggest-an-example',+ 'submit-an-example',{type: 'html',value:@@ -57,7 +57,10 @@ const sidebars: SidebarsConfig = {label: 'Motion design system',link: {type: 'doc', id: 'motion-design-system/index'},collapsed: false,- items: ['motion-design-system/lower-third', 'motion-design-system/code-example'],+ items: [+ 'motion-design-system/lower-third/index',+ 'motion-design-system/code-example',+ ],},{type: 'category',diff --git a/packages/docs/examples-template/example.tsx b/packages/docs/examples-template/example.tsxnew file mode 100644index 0000000000..00754cad15--- /dev/null+++ b/packages/docs/examples-template/example.tsx@@ -0,0 +1,39 @@+import React from 'react';+import {AbsoluteFill, Composition} from 'remotion';++export const width = 1920;+export const height = 1080;+export const fps = 30;+export const durationInFrames = 120;++export const ExampleComponent: React.FC = () => {+ return (+ <AbsoluteFill+ style={{+ alignItems: 'center',+ backgroundColor: '#111827',+ color: 'white',+ display: 'flex',+ fontFamily: 'Inter, system-ui, sans-serif',+ fontSize: 96,+ fontWeight: 700,+ justifyContent: 'center',+ }}+ >+ Example+ </AbsoluteFill>+ );+};++export const RemotionRoot: React.FC = () => {+ return (+ <Composition+ id="Example"+ component={ExampleComponent}+ durationInFrames={durationInFrames}+ fps={fps}+ height={height}+ width={width}+ />+ );+};diff --git a/packages/docs/examples-template/index.mdx b/packages/docs/examples-template/index.mdxnew file mode 100644index 0000000000..fafe4b573f--- /dev/null+++ b/packages/docs/examples-template/index.mdx@@ -0,0 +1,31 @@+---+title: Example title+description: One sentence describing what this example shows.+---++import {ExamplePage} from '@site/src/components/Examples/ExamplePage';+import {+ ExampleComponent,+ durationInFrames,+ fps,+ height,+ width,+} from './example';++# Example title++One short paragraph explaining what this example demonstrates and when to use it.++<ExamplePage+ component={ExampleComponent}+ durationInFrames={durationInFrames}+ fps={fps}+ height={height}+ width={width}+>++```tsx twoslash title="example.tsx"+source:./example.tsx+```++</ExamplePage>diff --git a/packages/docs/examples/index.mdx b/packages/docs/examples/index.mdxindex fde1b9258f..f835527ca8 100644--- a/packages/docs/examples/index.mdx+++ b/packages/docs/examples/index.mdx@@ -6,13 +6,15 @@ description: Small, remixable motion graphics examples for Remotion.# Examples-This section will collect small, remixable motion graphics examples for Remotion.+:::warning Work in progress-The goal is to make examples that are easy to understand, easy to adapt, and useful as building blocks in real projects.+This section is being shaped. The format and example list may change.-## Status+:::-This section is currently a structure preview. Individual example pages will be added later.+This section will collect small, remixable motion graphics examples for Remotion.++The goal is to make examples that are easy to understand, easy to adapt, and useful as building blocks in real projects.## What belongs here?@@ -20,4 +22,4 @@ Examples should be focused on one visual idea, technique, or workflow. They shouThe final example format is still being defined. A good format should work both for previewing the result and for helping users quickly use the example in their own project.-If you have an idea, see [Suggest an example](/examples/suggest-an-example).+If you want to contribute one, see [Submit an example](/examples/submit-an-example).diff --git a/packages/docs/examples/motion-design-system/lower-third.mdx b/packages/docs/examples/motion-design-system/lower-third.mdxdeleted file mode 100644index e4360bafe7..0000000000--- a/packages/docs/examples/motion-design-system/lower-third.mdx+++ /dev/null@@ -1,10 +0,0 @@-----title: Lower third-description: Create a reusable lower-third title animation.------import {PlannedExample} from '../../src/components/Examples/PlannedExample';--# Lower third--<PlannedExample category="Motion design system" description="Create a reusable lower-third title animation." />diff --git a/packages/docs/examples/motion-design-system/lower-third/index.mdx b/packages/docs/examples/motion-design-system/lower-third/index.mdxnew file mode 100644index 0000000000..135242b1e7--- /dev/null+++ b/packages/docs/examples/motion-design-system/lower-third/index.mdx@@ -0,0 +1,31 @@+---+title: Lower third+description: Create a reusable lower-third title animation.+---++import {ExamplePage} from '@site/src/components/Examples/ExamplePage';+import {+ LowerThird,+ durationInFrames,+ fps,+ height,+ width,+} from './lower-third';++# Lower third++Create a reusable lower-third title animation.++<ExamplePage+ component={LowerThird}+ durationInFrames={durationInFrames}+ fps={fps}+ height={height}+ width={width}+>++```tsx twoslash title="lower-third.tsx"+source:./lower-third.tsx+```++</ExamplePage>diff --git a/packages/docs/examples/motion-design-system/lower-third/lower-third.tsx b/packages/docs/examples/motion-design-system/lower-third/lower-third.tsxnew file mode 100644index 0000000000..7943abfd15--- /dev/null+++ b/packages/docs/examples/motion-design-system/lower-third/lower-third.tsx@@ -0,0 +1,107 @@+import React from 'react';+import {+ AbsoluteFill,+ Composition,+ interpolate,+ spring,+ useCurrentFrame,+ useVideoConfig,+} from 'remotion';++export const durationInFrames = 120;+export const fps = 30;+export const width = 1920;+export const height = 1080;++export const LowerThird: React.FC = () => {+ const frame = useCurrentFrame();+ const {fps: videoFps} = useVideoConfig();++ const entrance = spring({+ frame,+ fps: videoFps,+ config: {+ damping: 18,+ stiffness: 120,+ },+ });++ const exit = interpolate(frame, [95, 115], [1, 0], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ });++ const progress = entrance * exit;++ return (+ <AbsoluteFill+ style={{+ background: 'linear-gradient(135deg, #0b1020, #15234a)',+ fontFamily: 'Inter, system-ui, sans-serif',+ }}+ >+ <div+ style={{+ position: 'absolute',+ left: 120,+ bottom: 130,+ transform: `translateX(${interpolate(progress, [0, 1], [-90, 0])}px)`,+ opacity: progress,+ }}+ >+ <div+ style={{+ width: 660,+ padding: '34px 42px',+ borderRadius: 28,+ background: 'rgba(255, 255, 255, 0.92)',+ boxShadow: '0 24px 80px rgba(0, 0, 0, 0.3)',+ }}+ >+ <div+ style={{+ fontSize: 54,+ fontWeight: 800,+ color: '#111827',+ letterSpacing: -1.5,+ }}+ >+ Alex Morgan+ </div>+ <div+ style={{+ fontSize: 30,+ fontWeight: 600,+ color: '#2563eb',+ marginTop: 10,+ }}+ >+ Creative Developer+ </div>+ </div>+ <div+ style={{+ width: interpolate(progress, [0, 1], [0, 520]),+ height: 10,+ borderRadius: 999,+ background: '#60a5fa',+ marginTop: 18,+ }}+ />+ </div>+ </AbsoluteFill>+ );+};++export const RemotionRoot: React.FC = () => {+ return (+ <Composition+ id="LowerThird"+ component={LowerThird}+ durationInFrames={durationInFrames}+ fps={fps}+ height={height}+ width={width}+ />+ );+};diff --git a/packages/docs/examples/submit-an-example.mdx b/packages/docs/examples/submit-an-example.mdxnew file mode 100644index 0000000000..f38f88fa95--- /dev/null+++ b/packages/docs/examples/submit-an-example.mdx@@ -0,0 +1,133 @@+---+title: Submit an example+description: Submit a Remotion example for the examples gallery.+---++# Submit an example++Have a small, remixable Remotion example? We'd love to see it.++Examples should be submitted with code. A strong submission is easy to preview, easy to copy into a Remotion project, and useful as a building block in real videos.++## Preferred example format++An example should ideally be a single, self-contained TSX file.++Each example should live in its own folder: `packages/docs/examples/<category>/<slug>/`.+Put the MDX page at `packages/docs/examples/<category>/<slug>/index.mdx` and the TSX source next to it.++Start from the reusable template in `packages/docs/examples-template/`.++The same TSX file should be used for both the live preview and the displayed source code whenever possible.++The preferred format is:++- Export the example component+- Export fixed `width`, `height`, `fps`, and `durationInFrames`+- Define the Remotion [`<Composition>`](/docs/composition) directly in the file+- No local imports, except from npm packages+- No multiple files required to understand or use the example+- Copy-pastable into a Remotion project+- Binary assets use remote URLs only+- Remote assets are publicly accessible and stable++For example:++```tsx twoslash title="Example.tsx"+import {Composition} from 'remotion';++export const width = 1920;+export const height = 1080;+export const fps = 30;+export const durationInFrames = 120;++export const MyExample = () => {+ return <div>...</div>;+};++export const RemotionRoot = () => {+ return (+ <Composition+ id="MyExample"+ component={MyExample}+ width={width}+ height={height}+ fps={fps}+ durationInFrames={durationInFrames}+ />+ );+};+```++The MDX page can then use the shared page template, which renders a preview, a "Use it" section, and the source code:++````mdx title="index.mdx"+import {ExamplePage} from '@site/src/components/Examples/ExamplePage';+import {+ MyExample,+ durationInFrames,+ fps,+ height,+ width,+} from './my-example';++<ExamplePage+ component={MyExample}+ durationInFrames={durationInFrames}+ fps={fps}+ height={height}+ width={width}+>++```tsx twoslash title="my-example.tsx"+source:./my-example.tsx+```++</ExamplePage>+````++If an example needs binary assets, they should be referenced by URL:++```tsx twoslash title="Remote assets"+const imageUrl = 'https://remotion.media/example-image.png';+const videoUrl = 'https://remotion.media/example-video.mp4';+```++## What makes a good example?++A good example is:++- Small enough to understand quickly+- Useful in more than one project+- Easy to remix+- Focused on one visual idea, technique, or workflow+- Possible to preview with a short rendered video or still image+- Actionable for a Remotion user++## What to include++When submitting an example as a pull request, include:++- An example folder in `packages/docs/examples/<category>/<slug>/`+- An `index.mdx` page and the single-file TSX source code in that folder+- What the viewer should see+- A rendered preview, if available+- What makes it useful+- Required npm dependencies or remote asset URLs+- Links to inspiration, if any++## Not a great fit++These are usually less suitable:++- Full video templates with many unrelated parts+- Highly specific branded videos+- Examples requiring private APIs or private assets+- Large apps with many moving parts+- Examples that cannot be previewed meaningfully++## Submit your example++Submit examples by opening a pull request against the Remotion repository.++[Open a pull request on GitHub](https://github.com/remotion-dev/remotion/compare)diff --git a/packages/docs/examples/suggest-an-example.mdx b/packages/docs/examples/suggest-an-example.mdxdeleted file mode 100644index 727b613aad..0000000000--- a/packages/docs/examples/suggest-an-example.mdx+++ /dev/null@@ -1,46 +0,0 @@-----title: Suggest an example-description: Suggest a Remotion example for the examples gallery.------# Suggest an example--Have an idea for a small, remixable Remotion example? We'd love to hear it.--We are still defining the final example format. Suggestions are welcome even if you do not have code.--## What makes a good example?--A good example is:--- Small enough to understand quickly-- Useful in more than one project-- Easy to remix-- Focused on one visual idea, technique, or workflow-- Possible to preview with a short rendered video or still image-- Actionable for a Remotion user--## What to include--When suggesting an example, include:--- A short title-- What the viewer should see-- What makes it useful-- Links to inspiration, if any-- Required dependencies or assets, if known-- Whether you imagine it as a copy-pastable component, a larger project, or a workflow/tutorial-style example--## Not a great fit--These are usually less suitable:--- Full video templates with many unrelated parts-- Highly specific branded videos-- Examples requiring private APIs or private assets-- Large apps with many moving parts-- Examples that cannot be previewed meaningfully--## Submit your suggestion--[Suggest an example on GitHub](https://github.com/remotion-dev/remotion/issues/new?title=%5BExample%20suggestion%5D%20&body=%23%23%23%20Example%20idea%0A%0A%23%23%23%20What%20should%20the%20viewer%20see%3F%0A%0A%23%23%23%20Why%20would%20this%20be%20useful%20to%20Remotion%20users%3F%0A%0A%23%23%23%20Inspiration%20or%20references%0A%0A%23%23%23%20Dependencies%20or%20assets%2C%20if%20known%0A%0A%23%23%23%20Preferred%20format%0A%0A-%20%5B%20%5D%20Copy-pastable%20component%0A-%20%5B%20%5D%20Larger%20project%0A-%20%5B%20%5D%20Workflow%2Ftutorial-style%20example%0A-%20%5B%20%5D%20Not%20sure)diff --git a/packages/docs/prewarm-twoslash.ts b/packages/docs/prewarm-twoslash.tsindex 6bfb940a64..f97fe88654 100644--- a/packages/docs/prewarm-twoslash.ts+++ b/packages/docs/prewarm-twoslash.ts@@ -93,6 +93,27 @@ function replaceIncludes(map: Map<string, string>, code: string): string {return newCode;}+function replaceSourceDirective(code: string, filePath: string): string {+ const sourcePrefix = 'source:';+ const trimmed = code.trim();++ if (!trimmed.startsWith(sourcePrefix)) {+ return code;+ }++ const sourcePath = trimmed.slice(sourcePrefix.length).trim();+ const resolved = resolve(+ sourcePath.startsWith('.') ? resolve(filePath, '..') : DOCS_ROOT,+ sourcePath,+ );++ if (!resolved.startsWith(DOCS_ROOT + '/')) {+ throw new Error(`Cannot read source code outside of ${DOCS_ROOT}: ${sourcePath}`);+ }++ return readFileSync(resolved, 'utf8').trimEnd();+}+function extractTwoslashBlocks(content: string,filePath: string,@@ -123,7 +144,10 @@ function extractTwoslashBlocks(continue;}- const importedCode = replaceIncludes(includes, code);+ const importedCode = replaceSourceDirective(+ replaceIncludes(includes, code),+ filePath,+ );const cachePath = computeCachePath(importedCode);validCachePaths.add(cachePath);@@ -234,7 +258,7 @@ async function main() {const startTime = performance.now();const glob = new Glob('**/*.{mdx,md}');- const dirs = ['docs', 'blog', 'learn', 'new-docs'];+ const dirs = ['docs', 'blog', 'learn', 'new-docs', 'examples'];const allFiles: string[] = [];for (const dir of dirs) {diff --git a/packages/docs/src/components/Examples/ExamplePage.tsx b/packages/docs/src/components/Examples/ExamplePage.tsxnew file mode 100644index 0000000000..e7d83ad2cb--- /dev/null+++ b/packages/docs/src/components/Examples/ExamplePage.tsx@@ -0,0 +1,44 @@+import React, {type ComponentType, type ReactNode} from 'react';+import {ExamplePreview} from './ExamplePreview';++type ExamplePageProps = {+ readonly component: ComponentType<Record<string, never>>;+ readonly durationInFrames: number;+ readonly fps: number;+ readonly height: number;+ readonly width: number;+ readonly children: ReactNode;+};++export const ExamplePage: React.FC<ExamplePageProps> = ({+ children,+ component,+ durationInFrames,+ fps,+ height,+ width,+}) => {+ return (+ <>+ <h2>Preview</h2>+ <ExamplePreview+ component={component}+ durationInFrames={durationInFrames}+ fps={fps}+ height={height}+ width={width}+ />++ <h2>Use it</h2>+ <p>+ Copy the source code into your Remotion project. The file exports the+ component, dimensions, frame rate, duration, and a{' '}+ <code>RemotionRoot</code>+ composition.+ </p>++ <h2>Source</h2>+ {children}+ </>+ );+};diff --git a/packages/docs/src/components/Examples/ExamplePreview.tsx b/packages/docs/src/components/Examples/ExamplePreview.tsxnew file mode 100644index 0000000000..58480db50a--- /dev/null+++ b/packages/docs/src/components/Examples/ExamplePreview.tsx@@ -0,0 +1,43 @@+import {Player} from '@remotion/player';+import React, {type ComponentType} from 'react';++type ExamplePreviewProps = {+ readonly component: ComponentType<Record<string, never>>;+ readonly durationInFrames: number;+ readonly fps: number;+ readonly width: number;+ readonly height: number;+};++export const ExamplePreview: React.FC<ExamplePreviewProps> = ({+ component,+ durationInFrames,+ fps,+ width,+ height,+}) => {+ return (+ <div+ style={{+ border: '1px solid var(--ifm-color-emphasis-300)',+ borderRadius: 12,+ overflow: 'hidden',+ backgroundColor: 'var(--ifm-color-emphasis-100)',+ marginBottom: 24,+ }}+ >+ <Player+ acknowledgeRemotionLicense+ component={component}+ durationInFrames={durationInFrames}+ fps={fps}+ compositionWidth={width}+ compositionHeight={height}+ controls+ style={{+ width: '100%',+ }}+ />+ </div>+ );+};diff --git a/packages/docusaurus-plugin/src/index.ts b/packages/docusaurus-plugin/src/index.tsindex 29d24ef0b6..c275d2909a 100644--- a/packages/docusaurus-plugin/src/index.ts+++ b/packages/docusaurus-plugin/src/index.ts@@ -1,6 +1,7 @@import path from 'path';import type {DocusaurusContext} from '@docusaurus/types';import {remarkTwoslash} from './shiki';+import {remarkSourceCode} from './source-code';/*** @param {import("@docusaurus/types").DocusaurusContext} context* @param {import("remark-shiki-twoslash").Settings} pluginOptions@@ -58,6 +59,7 @@ export function shiki(context: DocusaurusContext, pluginOptions: any) {a.beforeDefaultRemarkPlugins = [];}+ a.beforeDefaultRemarkPlugins.push([remarkSourceCode, {root: process.cwd()}]);a.beforeDefaultRemarkPlugins.push([remarkTwoslash, options]);return a;};@@ -69,6 +71,10 @@ export function shiki(context: DocusaurusContext, pluginOptions: any) {a[1].beforeDefaultRemarkPlugins = [];}+ a[1].beforeDefaultRemarkPlugins.push([+ remarkSourceCode,+ {root: process.cwd()},+ ]);a[1].beforeDefaultRemarkPlugins.push([remarkTwoslash, options]);return a;};@@ -117,7 +123,7 @@ export function shiki(context: DocusaurusContext, pluginOptions: any) {return plugin;}- return addTwoslash(structure(plugin));+ return addTwoslashArray(structure(plugin));});if (!flag) {diff --git a/packages/docusaurus-plugin/src/source-code.ts b/packages/docusaurus-plugin/src/source-code.tsnew file mode 100644index 0000000000..301f7ce83c--- /dev/null+++ b/packages/docusaurus-plugin/src/source-code.ts@@ -0,0 +1,47 @@+import fs from 'fs';+import path from 'path';+import {visit} from 'unist-util-visit';++type UnistTree = {+ type: string;+ children?: UnistTree[];+ [key: string]: unknown;+};++type CodeNode = {+ type: 'code';+ value: string;+};++type Options = {+ root?: string;+};++const sourcePrefix = 'source:';++export const remarkSourceCode = (options: Options = {}) => {+ return (tree: UnistTree, file: {path?: string}) => {+ const root = path.resolve(options.root ?? process.cwd());+ const fileDir = file.path ? path.dirname(file.path) : root;++ visit(tree, 'code', (node: CodeNode) => {+ const value = node.value.trim();++ if (!value.startsWith(sourcePrefix)) {+ return;+ }++ const sourcePath = value.slice(sourcePrefix.length).trim();+ const resolved = path.resolve(+ sourcePath.startsWith('.') ? fileDir : root,+ sourcePath,+ );++ if (!resolved.startsWith(root + path.sep)) {+ throw new Error(`Cannot read source code outside of ${root}: ${sourcePath}`);+ }++ node.value = fs.readFileSync(resolved, 'utf8').trimEnd();+ });+ };+};