Skip to content

πŸŽ₯ Make videos programmatically with React

Docs: Inline example source, enforce format with a test

Igor Samokhovetsfadd1ba7cc19
diff --git a/packages/docs/examples-template/index.mdx b/packages/docs/examples-template/index.mdx
index fafe4b573f..623fb38b66 100644
--- a/packages/docs/examples-template/index.mdx
+++ b/packages/docs/examples-template/index.mdx
@@ -25,7 +25,45 @@ One short paragraph explaining what this example demonstrates and when to use it
>
```tsx twoslash title="example.tsx"
-source:./example.tsx
+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}
+ />
+ );
+};
```
</ExamplePage>
diff --git a/packages/docs/examples/motion-design-system/lower-third/index.mdx b/packages/docs/examples/motion-design-system/lower-third/index.mdx
index 135242b1e7..26f493b306 100644
--- a/packages/docs/examples/motion-design-system/lower-third/index.mdx
+++ b/packages/docs/examples/motion-design-system/lower-third/index.mdx
@@ -25,7 +25,113 @@ Create a reusable lower-third title animation.
>
```tsx twoslash title="lower-third.tsx"
-source:./lower-third.tsx
+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}
+ />
+ );
+};
```
</ExamplePage>
diff --git a/packages/docs/examples/submit-an-example.mdx b/packages/docs/examples/submit-an-example.mdx
index f38f88fa95..116cb4438c 100644
--- a/packages/docs/examples/submit-an-example.mdx
+++ b/packages/docs/examples/submit-an-example.mdx
@@ -18,7 +18,7 @@ Put the MDX page at `packages/docs/examples/<category>/<slug>/index.mdx` and the
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 MDX page imports that TSX file for the live preview, and shows the exact same code in a fenced `tsx` code block. Keeping the displayed code inline (rather than generating it at build time) means both readers in the browser and AI agents reading the served Markdown see the full source. A test (`src/test/examples.test.ts`) enforces that the code block stays identical to the source file.
The preferred format is:
@@ -80,12 +80,15 @@ import {
>
```tsx twoslash title="my-example.tsx"
-source:./my-example.tsx
+// Paste the full contents of my-example.tsx here.
+// It must match the file exactly β€” a test enforces this.
```
</ExamplePage>
````
+The fenced code block must be an exact copy of the colocated TSX file. This is intentional: it keeps the source visible in the served Markdown for agents while the imported module powers the live preview.
+
If an example needs binary assets, they should be referenced by URL:
```tsx twoslash title="Remote assets"
diff --git a/packages/docs/prewarm-twoslash.ts b/packages/docs/prewarm-twoslash.ts
index f97fe88654..1dd9e66ed3 100644
--- a/packages/docs/prewarm-twoslash.ts
+++ b/packages/docs/prewarm-twoslash.ts
@@ -93,27 +93,6 @@ 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,
@@ -144,10 +123,7 @@ function extractTwoslashBlocks(
continue;
}
- const importedCode = replaceSourceDirective(
- replaceIncludes(includes, code),
- filePath,
- );
+ const importedCode = replaceIncludes(includes, code);
const cachePath = computeCachePath(importedCode);
validCachePaths.add(cachePath);
diff --git a/packages/docs/src/test/examples.test.ts b/packages/docs/src/test/examples.test.ts
new file mode 100644
index 0000000000..b1a342261d
--- /dev/null
+++ b/packages/docs/src/test/examples.test.ts
@@ -0,0 +1,101 @@
+import {describe, expect, test} from 'bun:test';
+import {existsSync, readdirSync, readFileSync, statSync} from 'fs';
+import path from 'path';
+
+const examplesRoot = path.join(__dirname, '..', '..', 'examples');
+const templateRoot = path.join(__dirname, '..', '..', 'examples-template');
+
+// Exports every example source file must define so that the colocated MDX page
+// can import them and pass them to <Player>.
+const requiredExports = [
+ 'durationInFrames',
+ 'fps',
+ 'width',
+ 'height',
+ 'RemotionRoot',
+];
+
+type Example = {
+ name: string;
+ mdxPath: string;
+ tsxPath: string;
+};
+
+const findExamples = (root: string): Example[] => {
+ const examples: Example[] = [];
+
+ const walk = (dir: string) => {
+ const indexMdx = path.join(dir, 'index.mdx');
+ if (existsSync(indexMdx)) {
+ const tsxFiles = readdirSync(dir).filter(
+ (f) => f.endsWith('.tsx') && !f.endsWith('.test.tsx'),
+ );
+ if (tsxFiles.length > 0) {
+ examples.push({
+ name: path.relative(root, dir) || path.basename(dir),
+ mdxPath: indexMdx,
+ tsxPath: path.join(dir, tsxFiles[0]),
+ });
+ return;
+ }
+ }
+
+ for (const entry of readdirSync(dir)) {
+ const full = path.join(dir, entry);
+ if (statSync(full).isDirectory()) {
+ walk(full);
+ }
+ }
+ };
+
+ walk(root);
+ return examples;
+};
+
+// Extracts the first ```tsx fenced code block from an MDX file.
+const extractTsxBlock = (mdx: string): string | null => {
+ const match = mdx.match(/```tsx[^\n]*\n([\s\S]*?)\n```/);
+ return match ? match[1] : null;
+};
+
+const allExamples = [
+ ...findExamples(examplesRoot),
+ ...findExamples(templateRoot),
+];
+
+describe('Examples must follow the colocated single-file format', () => {
+ test('at least one example exists', () => {
+ expect(allExamples.length).toBeGreaterThan(0);
+ });
+
+ for (const example of allExamples) {
+ describe(example.name, () => {
+ const tsx = readFileSync(example.tsxPath, 'utf8');
+ const mdx = readFileSync(example.mdxPath, 'utf8');
+
+ test('source file defines the required exports', () => {
+ for (const exp of requiredExports) {
+ expect(tsx).toContain(`export const ${exp}`);
+ }
+
+ expect(tsx).toContain('<Composition');
+ });
+
+ test('MDX uses the ExamplePage template', () => {
+ expect(mdx).toContain('ExamplePage');
+ });
+
+ test('MDX imports the colocated source module', () => {
+ expect(mdx).toMatch(/from '\.\/[\w-]+';/);
+ });
+
+ test('displayed code block matches the source file', () => {
+ const block = extractTsxBlock(mdx);
+ expect(block).not.toBeNull();
+ // The fenced code block is the single source of truth shown to both
+ // humans and agents; it must be identical to the runnable .tsx file.
+ expect(block?.trim()).toBe(tsx.trim());
+ });
+ });
+ }
+});
diff --git a/packages/docusaurus-plugin/src/index.ts b/packages/docusaurus-plugin/src/index.ts
index c275d2909a..7866d08d90 100644
--- a/packages/docusaurus-plugin/src/index.ts
+++ b/packages/docusaurus-plugin/src/index.ts
@@ -1,7 +1,6 @@
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
@@ -59,7 +58,6 @@ export function shiki(context: DocusaurusContext, pluginOptions: any) {
a.beforeDefaultRemarkPlugins = [];
}
- a.beforeDefaultRemarkPlugins.push([remarkSourceCode, {root: process.cwd()}]);
a.beforeDefaultRemarkPlugins.push([remarkTwoslash, options]);
return a;
};
@@ -71,10 +69,6 @@ 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;
};
diff --git a/packages/docusaurus-plugin/src/source-code.ts b/packages/docusaurus-plugin/src/source-code.ts
deleted file mode 100644
index 301f7ce83c..0000000000
--- a/packages/docusaurus-plugin/src/source-code.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-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();
- });
- };
-};