Skip to content

πŸŽ₯ Make videos programmatically with React

`docs`: Make Element TSX files source of truth (#8641)

Igor Samokhovetsab903b0bd53a
diff --git a/packages/docs/copy-raw-docs.ts b/packages/docs/copy-raw-docs.ts
index 1aebde4c14..2c26856bbf 100644
--- a/packages/docs/copy-raw-docs.ts
+++ b/packages/docs/copy-raw-docs.ts
@@ -1,19 +1,45 @@
import fs from 'fs';
import path from 'path';
+import {expandElementSourceReferences} from './plugins/element-source-utils.js';
import {articles} from './src/data/articles';
const DOCS_DIR = path.join(__dirname, 'docs');
-const OUTPUT_DIR = path.join(__dirname, 'static', '_raw', 'docs');
+const ELEMENTS_DIR = path.join(__dirname, 'elements');
+const RAW_DIR = path.join(__dirname, 'static', '_raw');
+const DOCS_OUTPUT_DIR = path.join(RAW_DIR, 'docs');
+const ELEMENTS_OUTPUT_DIR = path.join(RAW_DIR, 'elements');
+
+const writeRawMarkdown = ({
+ destPath,
+ sourcePath,
+}: {
+ destPath: string;
+ sourcePath: string;
+}) => {
+ const destDir = path.dirname(destPath);
+ if (!fs.existsSync(destDir)) {
+ fs.mkdirSync(destDir, {recursive: true});
+ }
+
+ const raw = fs.readFileSync(sourcePath, 'utf8');
+ fs.writeFileSync(
+ destPath,
+ expandElementSourceReferences({
+ raw,
+ sourceFilePath: sourcePath,
+ }),
+ );
+};
+
+const hasNoAiFrontmatter = (contents: string) => {
+ const frontmatter = contents.match(/^---\n([\s\S]*?)\n---/);
+ return frontmatter ? /^noAi:\s*true\s*$/m.test(frontmatter[1]) : false;
+};
function copyRawDocs() {
console.log('πŸ“„ Copying raw docs to static/_raw/docs/...');
- // Clean output directory
- if (fs.existsSync(OUTPUT_DIR)) {
- fs.rmSync(OUTPUT_DIR, {recursive: true});
- }
-
- fs.mkdirSync(OUTPUT_DIR, {recursive: true});
+ fs.mkdirSync(DOCS_OUTPUT_DIR, {recursive: true});
let copiedCount = 0;
@@ -34,14 +60,9 @@ function copyRawDocs() {
// Use slug to determine destination path (handles cases like transitions.mdx β†’ transitioning.md)
// Special case: empty slug (homepage) should be index.md
const slugPath = article.slug === '' ? 'index' : article.slug;
- const destPath = path.join(OUTPUT_DIR, `${slugPath}.md`);
+ const destPath = path.join(DOCS_OUTPUT_DIR, `${slugPath}.md`);
- const destDir = path.dirname(destPath);
- if (!fs.existsSync(destDir)) {
- fs.mkdirSync(destDir, {recursive: true});
- }
-
- fs.copyFileSync(sourcePath, destPath);
+ writeRawMarkdown({destPath, sourcePath});
copiedCount++;
// For index routes, also create a flat .md file so /player.md works
@@ -49,12 +70,8 @@ function copyRawDocs() {
if (article.slug.endsWith('/index')) {
const slugWithoutIndex = article.slug.replace(/\/index$/, '');
if (slugWithoutIndex) {
- const flatPath = path.join(OUTPUT_DIR, `${slugWithoutIndex}.md`);
- const flatDir = path.dirname(flatPath);
- if (!fs.existsSync(flatDir)) {
- fs.mkdirSync(flatDir, {recursive: true});
- }
- fs.copyFileSync(sourcePath, flatPath);
+ const flatPath = path.join(DOCS_OUTPUT_DIR, `${slugWithoutIndex}.md`);
+ writeRawMarkdown({destPath: flatPath, sourcePath});
copiedCount++;
}
}
@@ -63,4 +80,68 @@ function copyRawDocs() {
console.log(`βœ… Copied ${copiedCount} files to static/_raw/docs/`);
}
-copyRawDocs();
+const findElementMdxFiles = (dir: string): string[] => {
+ const files: string[] = [];
+
+ for (const entry of fs.readdirSync(dir)) {
+ const fullPath = path.join(dir, entry);
+ const stat = fs.statSync(fullPath);
+
+ if (stat.isDirectory()) {
+ files.push(...findElementMdxFiles(fullPath));
+ continue;
+ }
+
+ if (entry.endsWith('.mdx')) {
+ files.push(fullPath);
+ }
+ }
+
+ return files;
+};
+
+function copyRawElements() {
+ console.log('🧩 Copying raw Elements docs to static/_raw/elements/...');
+
+ fs.mkdirSync(ELEMENTS_OUTPUT_DIR, {recursive: true});
+
+ let copiedCount = 0;
+
+ for (const sourcePath of findElementMdxFiles(ELEMENTS_DIR)) {
+ const contents = fs.readFileSync(sourcePath, 'utf8');
+ if (hasNoAiFrontmatter(contents)) {
+ continue;
+ }
+
+ const relativePath = path.relative(ELEMENTS_DIR, sourcePath);
+ const parsed = path.parse(relativePath);
+ const slug =
+ parsed.name === 'index'
+ ? parsed.dir || 'index'
+ : path.join(parsed.dir, parsed.name);
+ const destPath = path.join(ELEMENTS_OUTPUT_DIR, `${slug}.md`);
+
+ writeRawMarkdown({destPath, sourcePath});
+ copiedCount++;
+
+ if (parsed.name === 'index' && parsed.dir) {
+ const indexPath = path.join(ELEMENTS_OUTPUT_DIR, parsed.dir, 'index.md');
+ writeRawMarkdown({destPath: indexPath, sourcePath});
+ copiedCount++;
+ }
+ }
+
+ console.log(`βœ… Copied ${copiedCount} files to static/_raw/elements/`);
+}
+
+function copyRawContent() {
+ // Clean output directory
+ if (fs.existsSync(RAW_DIR)) {
+ fs.rmSync(RAW_DIR, {recursive: true});
+ }
+
+ copyRawDocs();
+ copyRawElements();
+}
+
+copyRawContent();
diff --git a/packages/docs/docusaurus.config.ts b/packages/docs/docusaurus.config.ts
index eb2dd9a2b7..2874254f61 100644
--- a/packages/docs/docusaurus.config.ts
+++ b/packages/docs/docusaurus.config.ts
@@ -1,4 +1,5 @@
import type {Config} from '@docusaurus/types';
+import remarkElementSource from './plugins/remark-element-source.js';
import remarkExportRaw from './plugins/remark-export-raw.js';
const lowMemoryBuild =
@@ -333,6 +334,7 @@ const config: Config = {
editUrl:
'https://github.com/remotion-dev/remotion/edit/main/packages/docs/',
showLastUpdateTime: showGitLastUpdate,
+ beforeDefaultRemarkPlugins: [remarkElementSource],
remarkPlugins: [remarkExportRaw],
},
],
diff --git a/packages/docs/elements-template/index.mdx b/packages/docs/elements-template/index.mdx
index bfbdcf5266..bb590dc5a9 100644
--- a/packages/docs/elements-template/index.mdx
+++ b/packages/docs/elements-template/index.mdx
@@ -10,30 +10,4 @@ import {ElementComponent} from './element';
One short paragraph explaining what this element demonstrates and when to use it.
-<ElementPage component={ElementComponent}>
-
-```tsx twoslash title="element.tsx"
-import React from 'react';
-import {AbsoluteFill} from 'remotion';
-
-export const ElementComponent: 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',
- }}
- >
- Element
- </AbsoluteFill>
- );
-};
-```
-
-</ElementPage>
+<ElementPage component={ElementComponent} sourceFile="./element.tsx" />
diff --git a/packages/docs/elements/overlays/lower-third/index.mdx b/packages/docs/elements/overlays/lower-third/index.mdx
index 19f5ef45ba..06d232af2c 100644
--- a/packages/docs/elements/overlays/lower-third/index.mdx
+++ b/packages/docs/elements/overlays/lower-third/index.mdx
@@ -6,116 +6,8 @@ description: A clean animated lower third for names and titles.
import {ElementPage} from '@site/src/components/Elements/ElementPage';
import {LowerThird} from './lower-third';
-{/* TODO: Unify the runnable Element source, visible code block, and drag payload source instead of duplicating it in three places. This is a separate task. */}
-export const lowerThirdSource = "import React from 'react';\nimport {\n\tAbsoluteFill,\n\tinterpolate,\n\tspring,\n\tuseCurrentFrame,\n\tuseVideoConfig,\n} from 'remotion';\n\nexport const LowerThird: React.FC = () => {\n\tconst frame = useCurrentFrame();\n\tconst {durationInFrames, fps: videoFps} = useVideoConfig();\n\n\tconst entrance = spring({\n\t\tframe,\n\t\tfps: videoFps,\n\t\tconfig: {\n\t\t\tdamping: 18,\n\t\t\tstiffness: 120,\n\t\t},\n\t});\n\n\tconst exitStart = Math.max(0, durationInFrames - 25);\n\tconst exitEnd = Math.max(exitStart + 1, durationInFrames - 5);\n\n\tconst exit = interpolate(frame, [exitStart, exitEnd], [1, 0], {\n\t\textrapolateLeft: 'clamp',\n\t\textrapolateRight: 'clamp',\n\t});\n\n\tconst progress = entrance * exit;\n\n\treturn (\n\t\t<AbsoluteFill\n\t\t\tstyle={{\n\t\t\t\tfontFamily: 'Inter, system-ui, sans-serif',\n\t\t\t\tpointerEvents: 'none',\n\t\t\t}}\n\t\t>\n\t\t\t<div\n\t\t\t\tstyle={{\n\t\t\t\t\tposition: 'absolute',\n\t\t\t\t\tleft: 0,\n\t\t\t\t\tbottom: 0,\n\t\t\t\t\ttransform: `translateX(${interpolate(progress, [0, 1], [-90, 0])}px)`,\n\t\t\t\t\topacity: progress,\n\t\t\t\t}}\n\t\t\t>\n\t\t\t\t<div\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\twidth: 660,\n\t\t\t\t\t\tpadding: '34px 42px',\n\t\t\t\t\t\tborderRadius: 28,\n\t\t\t\t\t\tbackground: 'rgba(255, 255, 255, 0.92)',\n\t\t\t\t\t\tboxShadow: '0 24px 80px rgba(0, 0, 0, 0.3)',\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t<div\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfontSize: 54,\n\t\t\t\t\t\t\tfontWeight: 800,\n\t\t\t\t\t\t\tcolor: '#111827',\n\t\t\t\t\t\t\tletterSpacing: -1.5,\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\tAlex Morgan\n\t\t\t\t\t</div>\n\t\t\t\t\t<div\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfontSize: 30,\n\t\t\t\t\t\t\tfontWeight: 600,\n\t\t\t\t\t\t\tcolor: '#2563eb',\n\t\t\t\t\t\t\tmarginTop: 10,\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\tCreative Developer\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<div\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\twidth: interpolate(progress, [0, 1], [0, 520]),\n\t\t\t\t\t\theight: 10,\n\t\t\t\t\t\tborderRadius: 999,\n\t\t\t\t\t\tbackground: '#60a5fa',\n\t\t\t\t\t\tmarginTop: 18,\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t</AbsoluteFill>\n\t);\n};\n";
-
# Lower Third
A clean animated lower third for introducing a speaker, guest, or section.
-<ElementPage
- category="overlays"
- component={LowerThird}
- componentName="LowerThird"
- displayName="Lower Third"
- elementHeight={1080}
- elementWidth={1920}
- slug="overlays/lower-third"
- sourceCode={lowerThirdSource}
->
-
-```tsx twoslash title="lower-third.tsx"
-import React from 'react';
-import {
- AbsoluteFill,
- interpolate,
- spring,
- useCurrentFrame,
- useVideoConfig,
-} from 'remotion';
-
-export const LowerThird: React.FC = () => {
- const frame = useCurrentFrame();
- const {durationInFrames, fps: videoFps} = useVideoConfig();
-
- const entrance = spring({
- frame,
- fps: videoFps,
- config: {
- damping: 18,
- stiffness: 120,
- },
- });
-
- const exitStart = Math.max(0, durationInFrames - 25);
- const exitEnd = Math.max(exitStart + 1, durationInFrames - 5);
-
- const exit = interpolate(frame, [exitStart, exitEnd], [1, 0], {
- extrapolateLeft: 'clamp',
- extrapolateRight: 'clamp',
- });
-
- const progress = entrance * exit;
-
- return (
- <AbsoluteFill
- style={{
- fontFamily: 'Inter, system-ui, sans-serif',
- pointerEvents: 'none',
- }}
- >
- <div
- style={{
- position: 'absolute',
- left: 0,
- bottom: 0,
- 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>
- );
-};
-```
-
-</ElementPage>
+<ElementPage component={LowerThird} displayName="Lower Third" elementHeight={1080} elementWidth={1920} slug="overlays/lower-third" sourceFile="./lower-third.tsx" />
diff --git a/packages/docs/middleware.ts b/packages/docs/middleware.ts
index 54f39e6c10..1c1bce760b 100644
--- a/packages/docs/middleware.ts
+++ b/packages/docs/middleware.ts
@@ -1,7 +1,7 @@
import {rewrite} from '@vercel/functions';
export const config = {
- matcher: '/docs/:path*',
+ matcher: ['/docs/:path*', '/elements/:path*'],
};
function parseAcceptHeader(acceptHeader: string): string[] {
@@ -59,20 +59,21 @@ export default function middleware(request: Request) {
const url = new URL(request.url);
const pathname = url.pathname;
- if (!pathname.startsWith('/docs/')) {
+ if (!pathname.startsWith('/docs/') && !pathname.startsWith('/elements/')) {
return;
}
// Case 1: .md extension - rewrite to raw markdown
// Example: /docs/preview.md β†’ /_raw/docs/preview.md
+ // Example: /elements/overlays/lower-third.md β†’ /_raw/elements/overlays/lower-third.md
if (pathname.endsWith('.md')) {
- const targetPath = pathname.replace(/^\/docs\//, '/_raw/docs/');
+ const targetPath = pathname.replace(/^\/(docs|elements)\//, '/_raw/$1/');
return rewrite(new URL(targetPath, request.url));
}
// Case 2: Accept header or user agent prefers markdown - rewrite to raw markdown
// Example: /docs/preview + Accept: text/markdown β†’ /_raw/docs/preview.md
- // Example: /docs/preview + User-Agent: Claude β†’ /_raw/docs/preview.md
+ // Example: /elements/overlays/lower-third + User-Agent: Claude β†’ /_raw/elements/overlays/lower-third.md
const acceptHeader = request.headers.get('accept');
const userAgent = request.headers.get('user-agent');
if (prefersMarkdown(acceptHeader, userAgent)) {
diff --git a/packages/docs/plugins/element-source-utils.d.ts b/packages/docs/plugins/element-source-utils.d.ts
new file mode 100644
index 0000000000..d9eb15b279
--- /dev/null
+++ b/packages/docs/plugins/element-source-utils.d.ts
@@ -0,0 +1,14 @@
+export function expandElementSourceReferences(input: {
+ raw: string;
+ sourceFilePath: string;
+}): string;
+
+export function getElementSourceCodeBlock(input: {
+ file: string;
+ sourceFilePath: string;
+}): string;
+
+export function getRemotionElementSource(input: {
+ file: string;
+ sourceFilePath: string;
+}): string;
diff --git a/packages/docs/plugins/element-source-utils.js b/packages/docs/plugins/element-source-utils.js
new file mode 100644
index 0000000000..9d2db59f24
--- /dev/null
+++ b/packages/docs/plugins/element-source-utils.js
@@ -0,0 +1,67 @@
+import fs from 'fs';
+import path from 'path';
+
+const getFence = (source) => {
+ const longestBacktickRun = Math.max(
+ 0,
+ ...Array.from(source.matchAll(/`+/g)).map((match) => match[0].length),
+ );
+
+ return '`'.repeat(Math.max(3, longestBacktickRun + 1));
+};
+
+export const getRemotionElementSource = ({file, sourceFilePath}) => {
+ const absoluteSourcePath = path.resolve(path.dirname(sourceFilePath), file);
+
+ try {
+ return fs.readFileSync(absoluteSourcePath, 'utf8').trimEnd();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+
+ throw new Error(
+ `Could not read Element source file "${absoluteSourcePath}" ` +
+ `referenced from "${sourceFilePath}": ${message}`,
+ );
+ }
+};
+
+export const getElementSourceCodeBlock = ({file, sourceFilePath}) => {
+ const source = getRemotionElementSource({file, sourceFilePath});
+ const extension = path.extname(file).slice(1) || 'tsx';
+ const fence = getFence(source);
+
+ return `${fence}${extension} twoslash title="${path.basename(file)}"\n${source}\n${fence}`;
+};
+
+const parseAttributes = (attributes) => {
+ const parsed = new Map();
+ const regex = /(\w+)="([^"]*)"/g;
+ let match = regex.exec(attributes);
+
+ while (match) {
+ parsed.set(match[1], match[2]);
+ match = regex.exec(attributes);
+ }
+
+ return parsed;
+};
+
+const appendSourceCodeBlock = ({attributes, match, sourceFilePath}) => {
+ const parsed = parseAttributes(attributes);
+ const file = parsed.get('sourceFile');
+
+ if (!file) {
+ return match;
+ }
+
+ return `${match}\n\n${getElementSourceCodeBlock({
+ file,
+ sourceFilePath,
+ })}`;
+};
+
+export const expandElementSourceReferences = ({raw, sourceFilePath}) => {
+ return raw.replace(/<ElementPage\b([\s\S]*?)\/>/g, (match, attributes) => {
+ return appendSourceCodeBlock({attributes, match, sourceFilePath});
+ });
+};
diff --git a/packages/docs/plugins/remark-element-source.js b/packages/docs/plugins/remark-element-source.js
new file mode 100644
index 0000000000..b0960443c1
--- /dev/null
+++ b/packages/docs/plugins/remark-element-source.js
@@ -0,0 +1,104 @@
+import {getRemotionElementSource} from './element-source-utils.js';
+
+const getAttributeValue = (node, name) => {
+ const attribute = node.attributes?.find((attr) => attr.name === name);
+
+ if (!attribute || typeof attribute.value !== 'string') {
+ return null;
+ }
+
+ return attribute.value;
+};
+
+const sourceCodeAttribute = (sourceCode) => {
+ const value = JSON.stringify(sourceCode);
+
+ return {
+ type: 'mdxJsxAttribute',
+ name: 'sourceCode',
+ value: {
+ type: 'mdxJsxAttributeValueExpression',
+ value,
+ data: {
+ estree: {
+ type: 'Program',
+ body: [
+ {
+ type: 'ExpressionStatement',
+ expression: {
+ type: 'Literal',
+ value: sourceCode,
+ raw: value,
+ },
+ },
+ ],
+ sourceType: 'module',
+ },
+ },
+ },
+ };
+};
+
+const setElementPageSourceCode = ({node, sourceCode}) => {
+ const attributesWithoutSourceFile = (node.attributes ?? []).filter(
+ (attribute) => attribute.name !== 'sourceFile',
+ );
+ const existingSourceCode = attributesWithoutSourceFile.find(
+ (attribute) => attribute.name === 'sourceCode',
+ );
+
+ node.attributes = existingSourceCode
+ ? attributesWithoutSourceFile
+ : [...attributesWithoutSourceFile, sourceCodeAttribute(sourceCode)];
+};
+
+const getSourceCodeNode = ({node, sourceFilePath}) => {
+ if (node.type !== 'mdxJsxFlowElement' || node.name !== 'ElementPage') {
+ return null;
+ }
+
+ const file = getAttributeValue(node, 'sourceFile');
+
+ if (!file) {
+ return null;
+ }
+
+ const sourceCode = getRemotionElementSource({file, sourceFilePath});
+ setElementPageSourceCode({node, sourceCode});
+
+ return {
+ type: 'code',
+ lang: file.split('.').at(-1) ?? 'tsx',
+ meta: `twoslash title="${file.split('/').at(-1) ?? file}"`,
+ value: sourceCode,
+ };
+};
+
+const insertElementPageSourceNodes = ({node, sourceFilePath}) => {
+ if (!node.children) {
+ return;
+ }
+
+ const children = [];
+
+ for (const child of node.children) {
+ insertElementPageSourceNodes({node: child, sourceFilePath});
+ children.push(child);
+
+ const sourceCodeNode = getSourceCodeNode({node: child, sourceFilePath});
+ if (sourceCodeNode) {
+ children.push(sourceCodeNode);
+ }
+ }
+
+ node.children = children;
+};
+
+export default function remarkElementSource() {
+ return (tree, file) => {
+ insertElementPageSourceNodes({
+ node: tree,
+ sourceFilePath: file.path,
+ });
+ };
+}
diff --git a/packages/docs/plugins/remark-export-raw.js b/packages/docs/plugins/remark-export-raw.js
index 51fa5853d0..c530ddc1d4 100644
--- a/packages/docs/plugins/remark-export-raw.js
+++ b/packages/docs/plugins/remark-export-raw.js
@@ -1,6 +1,11 @@
+import {expandElementSourceReferences} from './element-source-utils.js';
+
export default function remarkExportRaw() {
return (tree, file) => {
- const raw = String(file.value ?? '');
+ const raw = expandElementSourceReferences({
+ raw: String(file.value ?? ''),
+ sourceFilePath: file.path,
+ });
const escaped = JSON.stringify(raw);
tree.children.unshift({
diff --git a/packages/docs/prewarm-twoslash.ts b/packages/docs/prewarm-twoslash.ts
index 56bbc3c969..ba11301a82 100644
--- a/packages/docs/prewarm-twoslash.ts
+++ b/packages/docs/prewarm-twoslash.ts
@@ -1,3 +1,4 @@
+import {Glob} from 'bun';
import type {ChildProcessWithoutNullStreams} from 'child_process';
import {spawn} from 'child_process';
import {createHash} from 'crypto';
@@ -6,7 +7,7 @@ import {createRequire} from 'module';
import {availableParallelism, cpus, totalmem} from 'os';
import {join, resolve} from 'path';
import {createInterface} from 'readline';
-import {Glob} from 'bun';
+import {expandElementSourceReferences} from './plugins/element-source-utils';
const DOCS_ROOT = resolve(import.meta.dirname);
const CACHE_ROOT = join(DOCS_ROOT, 'node_modules', '.cache', 'twoslash');
@@ -293,7 +294,10 @@ async function main() {
const validCachePaths = new Set<string>();
const cachePathToFiles = new Map<string, string[]>();
for (const file of allFiles) {
- const content = readFileSync(file, 'utf8');
+ const content = expandElementSourceReferences({
+ raw: readFileSync(file, 'utf8'),
+ sourceFilePath: file,
+ });
allBlocks.push(
...extractTwoslashBlocks(
content,
diff --git a/packages/docs/src/components/Elements/ElementPage.tsx b/packages/docs/src/components/Elements/ElementPage.tsx
index 60a3cec180..0ca2cb2df4 100644
--- a/packages/docs/src/components/Elements/ElementPage.tsx
+++ b/packages/docs/src/components/Elements/ElementPage.tsx
@@ -8,10 +8,8 @@ import {setElementDragData, setElementDragImage} from './element-drag-data';
import {ElementPreview} from './ElementPreview';
type ElementPageProps = {
- readonly category?: string;
- readonly children: ReactNode;
+ readonly children?: ReactNode;
readonly component: ComponentType<Record<string, never>>;
- readonly componentName?: string;
readonly displayName?: string;
readonly durationInFrames?: number;
readonly elementHeight?: number;
@@ -38,10 +36,8 @@ const dragButtonStyle: React.CSSProperties = {
};
export const ElementPage: React.FC<ElementPageProps> = ({
- category,
children,
component,
- componentName,
displayName,
durationInFrames = 120,
elementHeight,
@@ -56,7 +52,6 @@ export const ElementPage: React.FC<ElementPageProps> = ({
if (
!slug ||
!displayName ||
- !componentName ||
!sourceCode ||
elementWidth === undefined ||
elementHeight === undefined
@@ -70,22 +65,12 @@ export const ElementPage: React.FC<ElementPageProps> = ({
};
return makeElementDragData({
- category,
- componentName,
dimensions,
displayName,
slug,
sourceCode,
});
- }, [
- category,
- componentName,
- displayName,
- elementHeight,
- elementWidth,
- slug,
- sourceCode,
- ]);
+ }, [displayName, elementHeight, elementWidth, slug, sourceCode]);
const PreviewComponent = useMemo(() => {
if (elementWidth === undefined || elementHeight === undefined) {
diff --git a/packages/docs/src/test/elements.test.ts b/packages/docs/src/test/elements.test.ts
index de7cd2b275..d5bb080c14 100644
--- a/packages/docs/src/test/elements.test.ts
+++ b/packages/docs/src/test/elements.test.ts
@@ -1,6 +1,7 @@
import {describe, expect, test} from 'bun:test';
import {existsSync, readdirSync, readFileSync, statSync} from 'fs';
import path from 'path';
+import {expandElementSourceReferences} from '../../plugins/element-source-utils';
const elementsRoot = path.join(__dirname, '..', '..', 'elements');
const templateRoot = path.join(__dirname, '..', '..', 'elements-template');
@@ -42,15 +43,9 @@ const findElements = (root: string): Element[] => {
return elements;
};
-// 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 extractLowerThirdSource = (mdx: string): string | null => {
- const match = mdx.match(/export const lowerThirdSource = ("[\s\S]*?");\n/);
- return match ? (JSON.parse(match[1]) as string) : null;
+const getRelativeTsxPath = (tsxPath: string, mdxPath: string) => {
+ const relative = path.relative(path.dirname(mdxPath), tsxPath);
+ return relative.startsWith('.') ? relative : `./${relative}`;
};
const allElements = [
@@ -86,21 +81,35 @@ describe('Elements must follow the colocated single-file format', () => {
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 must be identical to the runnable .tsx file.
- expect(block?.trim()).toBe(tsx.trim());
+ test('MDX references the source file from ElementPage', () => {
+ const relativeTsxPath = getRelativeTsxPath(
+ element.tsxPath,
+ element.mdxPath,
+ );
+
+ expect(mdx).toContain(`sourceFile="${relativeTsxPath}"`);
+ expect(mdx).not.toContain('<ElementSource');
+ expect(mdx).not.toContain('<RemotionElementSource');
+ expect(mdx).not.toContain('remotion-element-source');
+ expect(mdx).not.toContain(tsx.trim());
});
- test('drag payload source matches the source file if present', () => {
- const source = extractLowerThirdSource(mdx);
- if (source === null) {
- return;
- }
+ test('ElementPage sourceFile expands to the source file', () => {
+ const expanded = expandElementSourceReferences({
+ raw: mdx,
+ sourceFilePath: element.mdxPath,
+ });
+
+ expect(expanded).toContain(
+ `\`\`\`tsx twoslash title="${path.basename(element.tsxPath)}"\n${tsx.trim()}\n\`\`\``,
+ );
+ });
- expect(source.trim()).toBe(tsx.trim());
- expect(mdx).toContain('sourceCode={lowerThirdSource}');
+ test('MDX does not duplicate source metadata for drag payloads', () => {
+ expect(mdx).not.toContain('?raw');
+ expect(mdx).not.toContain('sourceCode=');
+ expect(mdx).not.toContain('componentName=');
+ expect(mdx).not.toMatch(/export const \w+Source = /);
});
test('Element drag file name is derived from the slug', () => {
diff --git a/packages/docs/vercel.ts b/packages/docs/vercel.ts
index 0b5941beee..b89b5073b6 100644
--- a/packages/docs/vercel.ts
+++ b/packages/docs/vercel.ts
@@ -13,6 +13,10 @@ export const config: VercelConfig = {
{key: 'Content-Type', value: 'text/plain; charset=utf-8'},
{key: 'Vary', value: 'Accept'},
]),
+ routes.header('/_raw/elements/(.*).md', [
+ {key: 'Content-Type', value: 'text/plain; charset=utf-8'},
+ {key: 'Vary', value: 'Accept'},
+ ]),
routes.header('/img/gt-planar(.*)', [
{key: 'Access-Control-Allow-Credentials', value: 'true'},
{key: 'Access-Control-Allow-Origin', value: '*'},
diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.ts
index 3de4f8bff8..8b317f6290 100644
--- a/packages/studio-server/src/preview-server/routes/insert-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts
@@ -2,7 +2,7 @@ import {existsSync, readFileSync} from 'node:fs';
import path from 'node:path';
import {RenderInternals} from '@remotion/renderer';
import {
- isComponentIdentifier,
+ getElementComponentNameFromSourceCode,
makeElementFileNameFromSlug,
type InsertElementRequest,
type InsertElementResponse,
@@ -71,26 +71,6 @@ const makeRelativeImportPath = ({
return relative;
};
-const validateSourceExportsComponent = ({
- componentName,
- sourceCode,
-}: {
- componentName: string;
- sourceCode: string;
-}) => {
- const escaped = componentName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const patterns = [
- new RegExp(`export\\s+const\\s+${escaped}\\b`),
- new RegExp(`export\\s+function\\s+${escaped}\\b`),
- ];
-
- if (!patterns.some((pattern) => pattern.test(sourceCode))) {
- throw new Error(
- `Element source must export a named component called ${componentName}`,
- );
- }
-};
-
const validateDimensions = (
dimensions: InsertElementRequest['element']['dimensions'],
) => {
@@ -105,10 +85,6 @@ const validateDimensions = (
};
const validateElement = (element: InsertElementRequest['element']) => {
- if (!isComponentIdentifier(element.componentName)) {
- throw new Error('Unsupported Element component name');
- }
-
if (makeElementFileNameFromSlug(element.slug) === null) {
throw new Error(
'Element slug must produce a safe lowercase .tsx file name',
@@ -123,10 +99,10 @@ const validateElement = (element: InsertElementRequest['element']) => {
throw new Error('Unsupported Element source code');
}
- validateSourceExportsComponent({
- componentName: element.componentName,
- sourceCode: element.sourceCode,
- });
+ if (getElementComponentNameFromSourceCode(element.sourceCode) === null) {
+ throw new Error('Element source must export exactly one named component');
+ }
+
validateDimensions(element.dimensions);
};
@@ -142,6 +118,14 @@ export const insertElementHandler: ApiHandler<
try {
validateElement(element);
validatePosition(position);
+ const componentName = getElementComponentNameFromSourceCode(
+ element.sourceCode,
+ );
+ if (componentName === null) {
+ throw new Error(
+ 'Element source must export exactly one named component',
+ );
+ }
RenderInternals.Log.trace(
{indent: false, logLevel},
@@ -198,8 +182,8 @@ export const insertElementHandler: ApiHandler<
compositionId,
element: {
type: 'component',
- componentName: element.componentName,
- importName: element.componentName,
+ componentName,
+ importName: componentName,
importPath,
props: [],
position: null,
@@ -276,7 +260,7 @@ export const insertElementHandler: ApiHandler<
);
RenderInternals.Log.info(
{indent: false, logLevel},
- `${RenderInternals.chalk.blueBright(compositionLocationLabel)} Added <${element.componentName}>`,
+ `${RenderInternals.chalk.blueBright(compositionLocationLabel)} Added <${componentName}>`,
);
if (!inserted.formatted) {
warnAboutPrettierOnce(logLevel);
diff --git a/packages/studio-shared/src/element-drag-data.ts b/packages/studio-shared/src/element-drag-data.ts
index 92cf32531b..3735847db1 100644
--- a/packages/studio-shared/src/element-drag-data.ts
+++ b/packages/studio-shared/src/element-drag-data.ts
@@ -11,10 +11,8 @@ export type ElementDragData = {
element: {
slug: string;
displayName: string;
- componentName: string;
sourceCode: string;
dimensions: ComponentDimensions;
- category?: string;
};
};
@@ -74,10 +72,6 @@ const isSourceCode = (value: unknown): value is string => {
);
};
-const isCategory = (value: unknown): value is string => {
- return typeof value === 'string' && /^[a-z0-9][a-z0-9/-]*$/.test(value);
-};
-
const isDimensions = (value: unknown): value is ComponentDimensions => {
if (!isRecord(value)) {
return false;
@@ -93,9 +87,24 @@ const isDimensions = (value: unknown): value is ComponentDimensions => {
);
};
+export const getElementComponentNameFromSourceCode = (sourceCode: string) => {
+ const componentNames = Array.from(
+ sourceCode.matchAll(
+ /export\s+(?:const|function)\s+([A-Z_$][A-Za-z0-9_$]*)\b/g,
+ ),
+ ).map((match) => match[1]);
+
+ const uniqueComponentNames = Array.from(new Set(componentNames));
+
+ if (uniqueComponentNames.length !== 1) {
+ return null;
+ }
+
+ const [componentName] = uniqueComponentNames;
+ return isComponentIdentifier(componentName) ? componentName : null;
+};
+
export const makeElementDragData = ({
- category,
- componentName,
dimensions,
displayName,
slug,
@@ -107,10 +116,8 @@ export const makeElementDragData = ({
element: {
slug,
displayName,
- componentName,
sourceCode,
dimensions,
- ...(category ? {category} : {}),
},
};
};
@@ -130,17 +137,15 @@ export const parseElementDragData = (value: string): ElementDragData | null => {
return null;
}
- const {category, componentName, dimensions, displayName, slug, sourceCode} =
- parsed.element;
+ const {dimensions, displayName, slug, sourceCode} = parsed.element;
if (
!isSlug(slug) ||
!isDisplayName(displayName) ||
- !isComponentIdentifier(componentName) ||
- makeElementFileNameFromSlug(slug) === null ||
!isSourceCode(sourceCode) ||
- !isDimensions(dimensions) ||
- (typeof category !== 'undefined' && !isCategory(category))
+ getElementComponentNameFromSourceCode(sourceCode) === null ||
+ makeElementFileNameFromSlug(slug) === null ||
+ !isDimensions(dimensions)
) {
return null;
}
@@ -148,10 +153,8 @@ export const parseElementDragData = (value: string): ElementDragData | null => {
return makeElementDragData({
slug,
displayName,
- componentName,
sourceCode,
dimensions,
- ...(category ? {category} : {}),
});
} catch {
return null;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index bcea3f69f6..67029559eb 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -2,10 +2,10 @@ export {splitAnsi, stripAnsi} from './ansi';
export {
AddEffectKeyframeRequest,
AddEffectKeyframeResponse,
- AddKeyframesRequest,
- AddKeyframesResponse,
AddEffectRequest,
AddEffectResponse,
+ AddKeyframesRequest,
+ AddKeyframesResponse,
AddRenderRequest,
AddSequenceKeyframeRequest,
AddSequenceKeyframeResponse,
@@ -99,9 +99,9 @@ export {
UpdateEffectKeyframeSettingsResponse,
UpdateSequenceKeyframeSettingsRequest,
UpdateSequenceKeyframeSettingsResponse,
- type KeyframeSettings,
type AddEffectKeyframe,
type AddSequenceKeyframe,
+ type KeyframeSettings,
} from './api-requests';
export {
ASSET_DRAG_MIME_TYPE,
@@ -122,12 +122,6 @@ export {
type ComponentProp,
} from './component-drag-data';
export {DEFAULT_BUFFER_STATE_DELAY_IN_MILLISECONDS} from './default-buffer-state-delay-in-milliseconds';
-export {
- KEYFRAME_EASING_PRESETS,
- LINEAR_KEYFRAME_EASING,
- type KeyframeEasing,
- type KeyframeEasingPreset,
-} from './keyframe-easing-presets';
export {
detectFileType,
isImageFileType,
@@ -141,6 +135,17 @@ export {
type EasingClipboardData,
type EasingClipboardDataParseResult,
} from './easing-clipboard-data';
+export {
+ EFFECT_CATALOG,
+ getEffectCatalogCategories,
+ getEffectDocumentationLink,
+ getEffectDocumentationPath,
+ getEffectPreviewAlt,
+ getEffectPreviewSource,
+ makeEffectDragDataFromCatalogItem,
+ type EffectCatalogCategory,
+ type EffectCatalogItem,
+} from './effect-catalog';
export {
parseEffectClipboardData,
parseEffectClipboardDataResult,
@@ -168,23 +173,13 @@ export {
} from './effect-drag-data';
export {
ELEMENT_DRAG_MIME_TYPE,
+ getElementComponentNameFromSourceCode,
isLowercaseElementFileName,
makeElementDragData,
makeElementFileNameFromSlug,
parseElementDragData,
type ElementDragData,
} from './element-drag-data';
-export {
- EFFECT_CATALOG,
- getEffectCatalogCategories,
- getEffectDocumentationLink,
- getEffectDocumentationPath,
- getEffectPreviewAlt,
- getEffectPreviewSource,
- makeEffectDragDataFromCatalogItem,
- type EffectCatalogCategory,
- type EffectCatalogItem,
-} from './effect-catalog';
export {EventSourceEvent} from './event-source-event';
export {formatBytes} from './format-bytes';
export {getAllSchemaKeys} from './get-all-keys';
@@ -201,20 +196,21 @@ export {
ModuleMap,
hotMiddlewareOptions,
} from './hot-middleware';
+export {
+ KEYFRAME_EASING_PRESETS,
+ LINEAR_KEYFRAME_EASING,
+ type KeyframeEasing,
+ type KeyframeEasingPreset,
+} from './keyframe-easing-presets';
export {
getKeyframeInterpolationFunction,
getKeyframeInterpolationFunctionForSchemaField,
+ isInteractivitySchemaFieldKeyframable,
isKeyframeInterpolationFunction,
isSchemaFieldKeyframable,
- isInteractivitySchemaFieldKeyframable,
keyframeInterpolationFunctions,
type KeyframeInterpolationFunction,
} from './keyframe-interpolation-function';
-export {
- DEFAULT_SPRING_EASING,
- parseSpringEasingConfig,
- type SpringKeyframeEasing,
-} from './parse-spring-easing-config';
export {DEFAULT_TIMELINE_TRACKS} from './max-timeline-tracks';
export {
Pkgs,
@@ -226,6 +222,11 @@ export {
type ExtraPackage,
} from './package-info';
export {PackageManager} from './package-manager';
+export {
+ DEFAULT_SPRING_EASING,
+ parseSpringEasingConfig,
+ type SpringKeyframeEasing,
+} from './parse-spring-easing-config';
export {ProjectInfo} from './project-info';
export type {RenderDefaults} from './render-defaults';
export {
@@ -258,10 +259,10 @@ export type {
AnySchemaFieldInfo,
DragOverrides,
EffectSchemaFieldInfo,
+ InteractivitySchemaFieldInfo,
PropStatuses,
SchemaFieldInfo,
SequenceControls,
- InteractivitySchemaFieldInfo,
} from './schema-field-info';
export {
SFX_DRAG_MIME_TYPE,
diff --git a/packages/studio-shared/src/test/element-drag-data.test.ts b/packages/studio-shared/src/test/element-drag-data.test.ts
index e069055fe0..0db18c74a8 100644
--- a/packages/studio-shared/src/test/element-drag-data.test.ts
+++ b/packages/studio-shared/src/test/element-drag-data.test.ts
@@ -8,10 +8,8 @@ import {
const validElement = {
slug: 'overlays/lower-third',
displayName: 'Lower Third',
- componentName: 'LowerThird',
sourceCode: 'export const LowerThird = () => null;',
dimensions: {width: 900, height: 260},
- category: 'overlays',
};
test('parses element drag data', () => {
@@ -24,32 +22,6 @@ test('parses element drag data', () => {
});
});
-test('parses element drag data without optional category', () => {
- expect(
- parseElementDragData(
- JSON.stringify(
- makeElementDragData({
- slug: 'lower-third',
- displayName: 'Lower Third',
- componentName: 'LowerThird',
- sourceCode: 'export const LowerThird = () => null;',
- dimensions: {width: 900, height: 260},
- }),
- ),
- ),
- ).toEqual({
- type: 'remotion-element',
- version: 1,
- element: {
- slug: 'lower-third',
- displayName: 'Lower Third',
- componentName: 'LowerThird',
- sourceCode: 'export const LowerThird = () => null;',
- dimensions: {width: 900, height: 260},
- },
- });
-});
-
test('derives element file name from slug', () => {
expect(makeElementFileNameFromSlug('overlays/lower-third')).toBe(
'lower-third.element.tsx',
@@ -84,7 +56,10 @@ test('rejects invalid element drag data', () => {
JSON.stringify({
type: 'remotion-element',
version: 1,
- element: {...validElement, componentName: 'lowerThird'},
+ element: {
+ ...validElement,
+ sourceCode: 'export const lowerThird = () => null;',
+ },
}),
),
).toBe(null);