🎥 Make videos programmatically with React
Docs: Add Element Studio previews and asset rendering (#9062)
Igor Samokhovets5554898f68ee
diff --git a/packages/docs/.gitignore b/packages/docs/.gitignoreindex 787b85c5bb..38a01380ee 100644--- a/packages/docs/.gitignore+++ b/packages/docs/.gitignore@@ -7,6 +7,7 @@# Generated files.docusaurus.cache-loader+.element-previewsstatic/_raw# Twoslash prewarm temp filesdiff --git a/packages/docs/elements-template/index.mdx b/packages/docs/elements-template/index.mdxindex a174fb954b..49cb94145e 100644--- a/packages/docs/elements-template/index.mdx+++ b/packages/docs/elements-template/index.mdx@@ -6,6 +6,23 @@ description: One sentence describing what this element shows.import {ElementPage} from '@site/src/components/Elements/ElementPage';import {ElementComponent} from './element';+export const elementDefinition = {+ category: 'category',+ component: ElementComponent,+ contributors: [],+ description: 'One short sentence explaining what this Element demonstrates and when to use it.',+ displayName: 'Element title',+ durationInFrames: 120,+ elementHeight: null,+ elementWidth: null,+ fps: 30,+ height: 1080,+ posterFrame: 60,+ previewPadding: 0,+ slug: 'category/element-title',+ width: 1920,+};+# Element title-<ElementPage component={ElementComponent} description="One short sentence explaining what this element demonstrates and when to use it." sourceFile="./element.tsx" />+<ElementPage definition={elementDefinition} sourceFile="./element.tsx" />diff --git a/packages/docs/elements/backgrounds/paper-texture/index.mdx b/packages/docs/elements/backgrounds/paper-texture/index.mdxindex 99a618e0a7..913add5962 100644--- a/packages/docs/elements/backgrounds/paper-texture/index.mdx+++ b/packages/docs/elements/backgrounds/paper-texture/index.mdx@@ -4,8 +4,8 @@ description: A white animated paper texture background.---import {ElementPage} from '@site/src/components/Elements/ElementPage';-import {PaperTexture} from './paper-texture';+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';# Paper Texture-<ElementPage component={PaperTexture} description="A white paper texture background with a slowly changing posterized seed." displayName="Paper Texture" slug="backgrounds/paper-texture" sourceFile="./paper-texture.tsx" />+<ElementPage definition={elementDefinitions['backgrounds/paper-texture']} sourceFile="./paper-texture.tsx" />diff --git a/packages/docs/elements/backgrounds/rotating-starburst/index.mdx b/packages/docs/elements/backgrounds/rotating-starburst/index.mdxindex c75ff00e08..58b9fa64ab 100644--- a/packages/docs/elements/backgrounds/rotating-starburst/index.mdx+++ b/packages/docs/elements/backgrounds/rotating-starburst/index.mdx@@ -4,15 +4,8 @@ description: A Solid background with a slowly rotating starburst effect.---import {ElementPage} from '@site/src/components/Elements/ElementPage';-import {RotatingStarburst} from './rotating-starburst';+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';# Rotating Starburst-<ElementPage- component={RotatingStarburst}- description="A Solid background with a slowly rotating starburst effect."- displayName="Rotating Starburst"- durationInFrames={240}- slug="backgrounds/rotating-starburst"- sourceFile="./rotating-starburst.tsx"-/>+<ElementPage definition={elementDefinitions['backgrounds/rotating-starburst']} sourceFile="./rotating-starburst.tsx" />diff --git a/packages/docs/elements/data/number-counter/index.mdx b/packages/docs/elements/data/number-counter/index.mdxindex 758ab97df6..e4f74139b2 100644--- a/packages/docs/elements/data/number-counter/index.mdx+++ b/packages/docs/elements/data/number-counter/index.mdx@@ -4,23 +4,8 @@ description: A simple animated counter that counts up from a start value to an e---import {ElementPage} from '@site/src/components/Elements/ElementPage';-import {NumberCounter} from './number-counter';+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';# Number Counter-<ElementPage- component={NumberCounter}- contributors={[- {- username: 'KapishDima',- contribution: 'Author',- },- ]}- description="A simple animated counter that smoothly counts from a start value to an end value."- displayName="Number Counter"- elementHeight={200}- elementWidth={640}- previewPadding={120}- slug="data/number-counter"- sourceFile="./number-counter.tsx"-/>+<ElementPage definition={elementDefinitions['data/number-counter']} sourceFile="./number-counter.tsx" />diff --git a/packages/docs/elements/overlays/lower-third/index.mdx b/packages/docs/elements/overlays/lower-third/index.mdxindex f8bf020340..f7112a3108 100644--- a/packages/docs/elements/overlays/lower-third/index.mdx+++ b/packages/docs/elements/overlays/lower-third/index.mdx@@ -4,8 +4,8 @@ description: A clean animated lower third for names and titles.---import {ElementPage} from '@site/src/components/Elements/ElementPage';-import {LowerThird} from './lower-third';+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';# Lower Third-<ElementPage component={LowerThird} description="A clean animated lower third for introducing a speaker, guest, or section." displayName="Lower Third" elementHeight={138} elementWidth={680} previewPadding={300} slug="overlays/lower-third" sourceFile="./lower-third.tsx" />+<ElementPage definition={elementDefinitions['overlays/lower-third']} sourceFile="./lower-third.tsx" />diff --git a/packages/docs/elements/submit-an-element.mdx b/packages/docs/elements/submit-an-element.mdxindex a18fb53a51..7ff8bd1cbd 100644--- a/packages/docs/elements/submit-an-element.mdx+++ b/packages/docs/elements/submit-an-element.mdx@@ -33,6 +33,7 @@ Add:- An Element folder in `packages/docs/elements/<category>/<slug>/`- An `index.mdx` page- One self-contained TSX source file exporting a React component+- An entry in `packages/docs/src/components/Elements/element-definitions.ts`For example:@@ -53,14 +54,19 @@ The source file should work when dragged or copied into a project.## 4. Define size-To give an Element a fixed size, set `elementWidth` and `elementHeight` on the `ElementPage` in `index.mdx`:--```tsx title="index.mdx"-<ElementPage- component={MyElement}- elementWidth={900}- elementHeight={260}->+To give an Element a fixed size, set `elementWidth` and `elementHeight` in its definition entry. Use `null` for both values if the Element should inherit the full composition dimensions.++```tsx title="element-definitions.ts"+export const elementDefinitions = {+ // The object key must match the slug.+ 'overlays/my-element': {+ // Other metadata...+ slug: 'overlays/my-element',+ elementWidth: 900,+ elementHeight: 260,+ previewPadding: 120,+ },+};```Then make the Element fill that area in its source file:@@ -75,7 +81,7 @@ export const MyElement = () => {Size the Element to the smallest useful bounding box.-Use `previewPadding` on the `ElementPage` if the docs preview needs more breathing room without changing the Element's drag dimensions or adding source padding.+Use `previewPadding` in the definition entry if the docs preview needs more breathing room without changing the Element's drag dimensions or adding source padding.Do not put the wrapper [`<Sequence>`](/docs/sequence) into the Element source file.@@ -179,13 +185,26 @@ export const Badge = () => {};```-## 7. Open the pull request+## 7. Check the preview assets++Set an intentional `posterFrame` in the definition entry. It should show the Element in a representative, visible state.++Render the PNG and MP4 locally:++```bash+cd packages/docs+bun run render-element-previews+```++Inspect both files under `.element-previews/`. The MP4 should cover the Element's full configured duration. Production uploads require maintainer R2 credentials.++## 8. Open the pull requestWhen submitting an Element as a pull request, include:-- The Element folder+- The Element folder and definition entry- What makes it useful-- A rendered preview, if available+- The rendered preview- Links to inspiration, if any[Open a pull request on GitHub](https://github.com/remotion-dev/remotion/compare)diff --git a/packages/docs/elements/text/circle-marker/index.mdx b/packages/docs/elements/text/circle-marker/index.mdxindex 5ababee34d..bfae4d0d53 100644--- a/packages/docs/elements/text/circle-marker/index.mdx+++ b/packages/docs/elements/text/circle-marker/index.mdx@@ -3,9 +3,9 @@ title: Circle Markerdescription: An animated hand-drawn circle around text.---+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';import {ElementPage} from '@site/src/components/Elements/ElementPage';-import {CircleMarker} from './circle-marker';# Circle Marker-<ElementPage component={CircleMarker} description="An animated hand-drawn circle with posterized drawing progress and shape changes." displayName="Circle Marker" elementHeight={220} elementWidth={900} previewPadding={120} slug="text/circle-marker" sourceFile="./circle-marker.tsx" />+<ElementPage definition={elementDefinitions['text/circle-marker']} sourceFile="./circle-marker.tsx" />diff --git a/packages/docs/elements/text/crossed-off/index.mdx b/packages/docs/elements/text/crossed-off/index.mdxindex 6cd8b1333b..73dd6dc98f 100644--- a/packages/docs/elements/text/crossed-off/index.mdx+++ b/packages/docs/elements/text/crossed-off/index.mdx@@ -3,9 +3,9 @@ title: Crossed Offdescription: Animated hand-drawn crossed-off text.---+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';import {ElementPage} from '@site/src/components/Elements/ElementPage';-import {CrossedOffText} from './crossed-off';# Crossed Off-<ElementPage component={CrossedOffText} description="An animated hand-drawn cross for removing a word or phrase with emphasis." displayName="Crossed Off" elementHeight={220} elementWidth={900} previewPadding={120} slug="text/crossed-off" sourceFile="./crossed-off.tsx" />+<ElementPage definition={elementDefinitions['text/crossed-off']} sourceFile="./crossed-off.tsx" />diff --git a/packages/docs/elements/text/strike-through/index.mdx b/packages/docs/elements/text/strike-through/index.mdxindex ea0a8b3cf7..22231eb952 100644--- a/packages/docs/elements/text/strike-through/index.mdx+++ b/packages/docs/elements/text/strike-through/index.mdx@@ -3,9 +3,9 @@ title: Strike Throughdescription: Animated hand-drawn strike-through text.---+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';import {ElementPage} from '@site/src/components/Elements/ElementPage';-import {StrikeThroughText} from './strike-through';# Strike Through-<ElementPage component={StrikeThroughText} description="An animated hand-drawn line for striking through a word or phrase." displayName="Strike Through" elementHeight={220} elementWidth={900} previewPadding={120} slug="text/strike-through" sourceFile="./strike-through.tsx" />+<ElementPage definition={elementDefinitions['text/strike-through']} sourceFile="./strike-through.tsx" />diff --git a/packages/docs/elements/text/text-marker/index.mdx b/packages/docs/elements/text/text-marker/index.mdxindex 48c7e33f9b..c69c083a9b 100644--- a/packages/docs/elements/text/text-marker/index.mdx+++ b/packages/docs/elements/text/text-marker/index.mdx@@ -3,9 +3,9 @@ title: Text Markerdescription: A hand-drawn animated text highlight.---+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';import {ElementPage} from '@site/src/components/Elements/ElementPage';-import {TextMarker} from './text-marker';# Text Marker-<ElementPage component={TextMarker} description="A hand-drawn animated text marker for calling attention to one phrase." displayName="Text Marker" elementHeight={220} elementWidth={900} previewPadding={120} slug="text/text-marker" sourceFile="./text-marker.tsx" />+<ElementPage definition={elementDefinitions['text/text-marker']} sourceFile="./text-marker.tsx" />diff --git a/packages/docs/package.json b/packages/docs/package.jsonindex 37386e7484..cd984017b5 100644--- a/packages/docs/package.json+++ b/packages/docs/package.json@@ -18,7 +18,8 @@"lint": "eslint src components","test": "bun test src","remotion": "remotion studio src/remotion/entry.ts",- "render-cards": "bun run render-cards.ts"+ "render-cards": "bun run render-cards.ts",+ "render-element-previews": "bun run render-element-previews.ts"},"dependencies": {"@aws-sdk/s3-request-presigner": "catalog:",diff --git a/packages/docs/render-element-previews.ts b/packages/docs/render-element-previews.tsnew file mode 100644index 0000000000..7839008dd5--- /dev/null+++ b/packages/docs/render-element-previews.ts@@ -0,0 +1,184 @@+import {mkdirSync, rmSync} from 'fs';+import path from 'path';+import {bundle} from '@remotion/bundler';+import {getCompositions, renderMedia, renderStill} from '@remotion/renderer';+import {S3Client} from 'bun';+import {elementDefinitions} from './src/components/Elements/element-definitions';+import {+ getElementCompositionId,+ getElementPreviewUrls,+} from './src/components/Elements/element-utils';++const r2Endpoint =+ 'https://2fe488b3b0f4deee223aef7464784c46.r2.cloudflarestorage.com';+const r2Bucket = 'parser-media';+const upload = process.argv.includes('--upload');+const outputDirectoryArgument = process.argv.find((argument) =>+ argument.startsWith('--output-dir='),+);+const outputDirectory = outputDirectoryArgument+ ? path.resolve(outputDirectoryArgument.slice('--output-dir='.length))+ : path.join(process.cwd(), '.element-previews');++const ensureUploadCredentials = () => {+ if (!Bun.env.AWS_ACCESS_KEY_ID || !Bun.env.AWS_SECRET_ACCESS_KEY) {+ throw new Error(+ '--upload requires AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY',+ );+ }++ return {+ accessKeyId: Bun.env.AWS_ACCESS_KEY_ID,+ secretAccessKey: Bun.env.AWS_SECRET_ACCESS_KEY,+ };+};++const uploadAsset = async ({+ client,+ contentType,+ filePath,+ key,+ publicUrl,+}: {+ client: S3Client;+ contentType: string;+ filePath: string;+ key: string;+ publicUrl: string;+}) => {+ const file = Bun.file(filePath, {type: contentType});+ await client.write(key, file);++ const remote = await client.stat(key);+ if (remote.size !== file.size) {+ throw new Error(+ `Uploaded size mismatch for ${key}: expected ${file.size}, got ${remote.size}`,+ );+ }++ const response = await fetch(`${publicUrl}?verify=${Date.now()}`, {+ method: 'HEAD',+ });+ if (!response.ok) {+ throw new Error(`Could not verify ${publicUrl}: HTTP ${response.status}`);+ }++ const remoteContentType = response.headers.get('content-type');+ if (remoteContentType !== contentType) {+ throw new Error(+ `Unexpected content type for ${publicUrl}: expected ${contentType}, got ${remoteContentType}`,+ );+ }++ console.log(`Uploaded ${publicUrl} (${file.size} bytes)`);+};++const credentials = upload ? ensureUploadCredentials() : null;+const client = credentials+ ? new S3Client({+ ...credentials,+ bucket: r2Bucket,+ endpoint: r2Endpoint,+ })+ : null;++rmSync(outputDirectory, {force: true, recursive: true});+mkdirSync(outputDirectory, {recursive: true});++const serveUrl = await bundle({+ entryPoint: path.join(process.cwd(), 'src', 'remotion', 'entry.ts'),+ publicDir: path.join(process.cwd(), 'static'),+});+const compositions = await getCompositions(serveUrl);+const elementCompositions = compositions.filter((composition) =>+ composition.id.startsWith('element-'),+);++const expectedCompositionIds = new Set(+ Object.values(elementDefinitions).map((definition) =>+ getElementCompositionId(definition.slug),+ ),+);+const actualCompositionIds = new Set(+ elementCompositions.map((composition) => composition.id),+);++for (const expectedId of expectedCompositionIds) {+ if (!actualCompositionIds.has(expectedId)) {+ throw new Error(`Missing Element composition: ${expectedId}`);+ }+}++for (const actualId of actualCompositionIds) {+ if (!expectedCompositionIds.has(actualId)) {+ throw new Error(`Unexpected Element composition: ${actualId}`);+ }+}++for (const definition of Object.values(elementDefinitions)) {+ const compositionId = getElementCompositionId(definition.slug);+ const composition = elementCompositions.find(+ (candidate) => candidate.id === compositionId,+ );+ if (!composition) {+ throw new Error(`Could not find composition ${compositionId}`);+ }++ const elementOutputDirectory = path.join(+ outputDirectory,+ ...definition.slug.split('/'),+ );+ mkdirSync(elementOutputDirectory, {recursive: true});+ const pngPath = path.join(elementOutputDirectory, 'preview.png');+ const mp4Path = path.join(elementOutputDirectory, 'preview.mp4');++ console.log(`Rendering ${definition.displayName} poster`);+ await renderStill({+ chromiumOptions: {gl: 'angle'},+ composition,+ frame: definition.posterFrame,+ output: pngPath,+ serveUrl,+ });++ console.log(`Rendering ${definition.displayName} video`);+ await renderMedia({+ chromiumOptions: {gl: 'angle'},+ codec: 'h264',+ composition,+ crf: 23,+ imageFormat: 'png',+ muted: true,+ outputLocation: mp4Path,+ pixelFormat: 'yuv420p',+ serveUrl,+ });++ console.log(`Rendered ${pngPath}`);+ console.log(`Rendered ${mp4Path}`);++ if (client) {+ const urls = getElementPreviewUrls(definition.slug);+ const baseKey = `elements/${definition.slug}`;+ await uploadAsset({+ client,+ contentType: 'image/png',+ filePath: pngPath,+ key: `${baseKey}/preview.png`,+ publicUrl: urls.png,+ });+ await uploadAsset({+ client,+ contentType: 'video/mp4',+ filePath: mp4Path,+ key: `${baseKey}/preview.mp4`,+ publicUrl: urls.mp4,+ });+ }+}++console.log(+ upload+ ? 'Rendered and uploaded all Element previews.'+ : `Rendered all Element previews to ${outputDirectory}.`,+);diff --git a/packages/docs/src/components/Elements/ElementPage.tsx b/packages/docs/src/components/Elements/ElementPage.tsxindex df17191b22..7846399317 100644--- a/packages/docs/src/components/Elements/ElementPage.tsx+++ b/packages/docs/src/components/Elements/ElementPage.tsx@@ -7,31 +7,22 @@ import React, {useId,useMemo,useState,- type ComponentType,type ReactNode,} from 'react';-import {AbsoluteFill, Sequence} from 'remotion';import {BlueButton, PlainButton} from '../../../components/layout/Button';-import {type Contributor} from '../Credits';+import type {ElementDefinition} from './element-definitions';import {setElementDragData, setElementDragImage} from './element-drag-data';import {ElementPreview} from './ElementPreview';+import {+ ElementPreviewComposition,+ getElementPreviewDimensions,+} from './ElementPreviewComposition';import styles from './ElementPage.module.css';type ElementPageProps = {readonly children?: ReactNode;- readonly component: ComponentType<Record<string, never>>;- readonly contributors?: Contributor[];- readonly description: ReactNode;- readonly displayName?: string;- readonly durationInFrames?: number;- readonly elementHeight?: number;- readonly elementWidth?: number;- readonly fps?: number;- readonly height?: number;- readonly previewPadding?: number;- readonly slug?: string;+ readonly definition: ElementDefinition;readonly sourceCode?: string;- readonly width?: number;};type ElementInstallTarget = {@@ -106,43 +97,34 @@ const findBestInstallTarget = async (): Promise<export const ElementPage: React.FC<ElementPageProps> = ({children,- component,- contributors,- description,- displayName,- durationInFrames = 120,- elementHeight,- elementWidth,- fps = 30,- height = 1080,- previewPadding = 0,- slug,+ definition,sourceCode,- width = 1920,}) => {+ const {+ contributors,+ description,+ displayName,+ durationInFrames,+ elementHeight,+ elementWidth,+ fps,+ slug,+ } = definition;const [installStatus, setInstallStatus] = useState<InstallStatus>({type: 'idle',});const [isSourceVisible, setIsSourceVisible] = useState(false);const sourceId = useId();- const hasElementDimensions =- elementWidth !== undefined && elementHeight !== undefined;- const previewWidth =- hasElementDimensions && previewPadding > 0- ? elementWidth + previewPadding * 2- : width;- const previewHeight =- hasElementDimensions && previewPadding > 0- ? elementHeight + previewPadding * 2- : height;+ const {height: previewHeight, width: previewWidth} =+ getElementPreviewDimensions(definition);const dragData = useMemo(() => {- if (!slug || !displayName || !sourceCode) {+ if (!sourceCode) {return null;}const dimensions: ComponentDimensions | null =- elementWidth !== undefined && elementHeight !== undefined+ elementWidth !== null && elementHeight !== null? {width: elementWidth,height: elementHeight,@@ -213,49 +195,8 @@ export const ElementPage: React.FC<ElementPageProps> = ({}, [dragData]);const PreviewComponent = useMemo(() => {- if (!hasElementDimensions) {- return component;- }-- const Component = component;-- return () => {- if (previewPadding > 0) {- return (- <AbsoluteFill- style={{- alignItems: 'center',- justifyContent: 'center',- }}- >- <Sequence height={elementHeight} layout="none" width={elementWidth}>- <div- style={{- height: elementHeight,- position: 'relative',- width: elementWidth,- }}- >- <Component />- </div>- </Sequence>- </AbsoluteFill>- );- }-- return (- <Sequence height={elementHeight} width={elementWidth}>- <Component />- </Sequence>- );- };- }, [- component,- elementHeight,- elementWidth,- hasElementDimensions,- previewPadding,- ]);+ return () => <ElementPreviewComposition definition={definition} />;+ }, [definition]);return (<div className={styles.workbench}>@@ -368,13 +309,14 @@ export const ElementPage: React.FC<ElementPageProps> = ({<div><dt>Dimensions</dt><dd>- {elementWidth ?? width} × {elementHeight ?? height}px+ {elementWidth ?? definition.width} ×{' '}+ {elementHeight ?? definition.height}px</dd></div></dl></div>- {contributors?.length ? (+ {contributors.length ? (<div aria-label="Contributors" className={styles.contributors}><span className={styles.contributorsLabel}>Created by</span><div className={styles.contributorList}>diff --git a/packages/docs/src/components/Elements/ElementPreviewComposition.tsx b/packages/docs/src/components/Elements/ElementPreviewComposition.tsxnew file mode 100644index 0000000000..f55c3bd4e8--- /dev/null+++ b/packages/docs/src/components/Elements/ElementPreviewComposition.tsx@@ -0,0 +1,79 @@+import React from 'react';+import {AbsoluteFill, Sequence} from 'remotion';+import type {ElementDefinition} from './element-definitions';+import {getElementDefinition} from './element-utils';++export const ELEMENT_PREVIEW_BACKGROUND = '#eef1f4';++export const getElementPreviewDimensions = (definition: ElementDefinition) => {+ const hasElementDimensions =+ definition.elementWidth !== null && definition.elementHeight !== null;++ return {+ height:+ hasElementDimensions && definition.previewPadding > 0+ ? definition.elementHeight! + definition.previewPadding * 2+ : definition.height,+ width:+ hasElementDimensions && definition.previewPadding > 0+ ? definition.elementWidth! + definition.previewPadding * 2+ : definition.width,+ };+};++export const ElementPreviewComposition: React.FC<{+ readonly definition: ElementDefinition;+}> = ({definition}) => {+ const {+ component: Component,+ elementHeight,+ elementWidth,+ previewPadding,+ } = definition;+ const hasElementDimensions = elementWidth !== null && elementHeight !== null;++ if (!hasElementDimensions) {+ return <Component />;+ }++ if (previewPadding > 0) {+ return (+ <AbsoluteFill+ style={{+ alignItems: 'center',+ justifyContent: 'center',+ }}+ >+ <Sequence height={elementHeight} layout="none" width={elementWidth}>+ <div+ style={{+ height: elementHeight,+ position: 'relative',+ width: elementWidth,+ }}+ >+ <Component />+ </div>+ </Sequence>+ </AbsoluteFill>+ );+ }++ return (+ <Sequence height={elementHeight} width={elementWidth}>+ <Component />+ </Sequence>+ );+};++export const ElementAssetComposition: React.FC<{+ readonly slug: string;+}> = ({slug}) => {+ const definition = getElementDefinition(slug);++ return (+ <AbsoluteFill style={{backgroundColor: ELEMENT_PREVIEW_BACKGROUND}}>+ <ElementPreviewComposition definition={definition} />+ </AbsoluteFill>+ );+};diff --git a/packages/docs/src/components/Elements/element-definitions.ts b/packages/docs/src/components/Elements/element-definitions.tsnew file mode 100644index 0000000000..4a77f4aaf3--- /dev/null+++ b/packages/docs/src/components/Elements/element-definitions.ts@@ -0,0 +1,170 @@+import type {ComponentType} from 'react';+import {PaperTexture} from '../../../elements/backgrounds/paper-texture/paper-texture';+import {RotatingStarburst} from '../../../elements/backgrounds/rotating-starburst/rotating-starburst';+import {NumberCounter} from '../../../elements/data/number-counter/number-counter';+import {LowerThird} from '../../../elements/overlays/lower-third/lower-third';+import {CircleMarker} from '../../../elements/text/circle-marker/circle-marker';+import {CrossedOffText} from '../../../elements/text/crossed-off/crossed-off';+import {StrikeThroughText} from '../../../elements/text/strike-through/strike-through';+import {TextMarker} from '../../../elements/text/text-marker/text-marker';+import type {Contributor} from '../Credits';++export type ElementDefinition = {+ readonly category: string;+ readonly component: ComponentType<Record<string, never>>;+ readonly contributors: readonly Contributor[];+ readonly description: string;+ readonly displayName: string;+ readonly durationInFrames: number;+ readonly elementHeight: number | null;+ readonly elementWidth: number | null;+ readonly fps: number;+ readonly height: number;+ readonly posterFrame: number;+ readonly previewPadding: number;+ readonly slug: string;+ readonly width: number;+};++export const elementDefinitions = {+ 'backgrounds/paper-texture': {+ category: 'backgrounds',+ component: PaperTexture,+ contributors: [],+ description:+ 'A white paper texture background with a slowly changing posterized seed.',+ displayName: 'Paper Texture',+ durationInFrames: 120,+ elementHeight: null,+ elementWidth: null,+ fps: 30,+ height: 1080,+ posterFrame: 60,+ previewPadding: 0,+ slug: 'backgrounds/paper-texture',+ width: 1920,+ },+ 'backgrounds/rotating-starburst': {+ category: 'backgrounds',+ component: RotatingStarburst,+ contributors: [],+ description: 'A solid background with a slowly rotating starburst effect.',+ displayName: 'Rotating Starburst',+ durationInFrames: 240,+ elementHeight: null,+ elementWidth: null,+ fps: 30,+ height: 1080,+ posterFrame: 120,+ previewPadding: 0,+ slug: 'backgrounds/rotating-starburst',+ width: 1920,+ },+ 'overlays/lower-third': {+ category: 'overlays',+ component: LowerThird,+ contributors: [],+ description:+ 'A clean animated lower third for introducing a speaker, guest, or section.',+ displayName: 'Lower Third',+ durationInFrames: 120,+ elementHeight: 138,+ elementWidth: 680,+ fps: 30,+ height: 1080,+ posterFrame: 60,+ previewPadding: 300,+ slug: 'overlays/lower-third',+ width: 1920,+ },+ 'data/number-counter': {+ category: 'data',+ component: NumberCounter,+ contributors: [+ {+ username: 'KapishDima',+ contribution: 'Author',+ },+ ],+ description:+ 'A simple animated counter that smoothly counts from a start value to an end value.',+ displayName: 'Number Counter',+ durationInFrames: 120,+ elementHeight: 200,+ elementWidth: 640,+ fps: 30,+ height: 1080,+ posterFrame: 60,+ previewPadding: 120,+ slug: 'data/number-counter',+ width: 1920,+ },+ 'text/circle-marker': {+ category: 'text',+ component: CircleMarker,+ contributors: [],+ description:+ 'An animated hand-drawn circle with posterized drawing progress and shape changes.',+ displayName: 'Circle Marker',+ durationInFrames: 120,+ elementHeight: 220,+ elementWidth: 900,+ fps: 30,+ height: 1080,+ posterFrame: 60,+ previewPadding: 120,+ slug: 'text/circle-marker',+ width: 1920,+ },+ 'text/crossed-off': {+ category: 'text',+ component: CrossedOffText,+ contributors: [],+ description:+ 'An animated hand-drawn cross for removing a word or phrase with emphasis.',+ displayName: 'Crossed Off',+ durationInFrames: 120,+ elementHeight: 220,+ elementWidth: 900,+ fps: 30,+ height: 1080,+ posterFrame: 60,+ previewPadding: 120,+ slug: 'text/crossed-off',+ width: 1920,+ },+ 'text/strike-through': {+ category: 'text',+ component: StrikeThroughText,+ contributors: [],+ description:+ 'An animated hand-drawn line for striking through a word or phrase.',+ displayName: 'Strike Through',+ durationInFrames: 120,+ elementHeight: 220,+ elementWidth: 900,+ fps: 30,+ height: 1080,+ posterFrame: 60,+ previewPadding: 120,+ slug: 'text/strike-through',+ width: 1920,+ },+ 'text/text-marker': {+ category: 'text',+ component: TextMarker,+ contributors: [],+ description:+ 'A hand-drawn animated text marker for calling attention to one phrase.',+ displayName: 'Text Marker',+ durationInFrames: 120,+ elementHeight: 220,+ elementWidth: 900,+ fps: 30,+ height: 1080,+ posterFrame: 60,+ previewPadding: 120,+ slug: 'text/text-marker',+ width: 1920,+ },+} satisfies Record<string, ElementDefinition>;diff --git a/packages/docs/src/components/Elements/element-utils.ts b/packages/docs/src/components/Elements/element-utils.tsnew file mode 100644index 0000000000..4659dc38e8--- /dev/null+++ b/packages/docs/src/components/Elements/element-utils.ts@@ -0,0 +1,25 @@+import {elementDefinitions} from './element-definitions';++export const getElementCompositionId = (slug: string) => {+ return `element-${slug.replaceAll('/', '-')}`;+};++export const getElementPreviewUrls = (slug: string) => {+ const base = `https://remotion.media/elements/${slug}`;++ return {+ mp4: `${base}/preview.mp4`,+ png: `${base}/preview.png`,+ };+};++export const getElementDefinition = (slug: string) => {+ const definition =+ elementDefinitions[slug as keyof typeof elementDefinitions];++ if (!definition) {+ throw new Error(`No Element definition found for ${slug}`);+ }++ return definition;+};diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsxindex 128da6901d..fbff2cdc7a 100644--- a/packages/docs/src/remotion/Root.tsx+++ b/packages/docs/src/remotion/Root.tsx@@ -1,7 +1,7 @@import {experts} from '@remotion/promo-pages/dist/experts/experts-data.js';import {CreateVideoInternals} from 'create-video';import React from 'react';-import {Folder, Still} from 'remotion';+import {Composition, Folder, Still} from 'remotion';import {EffectsBarrelDistortionPreview} from '../../components/effects/effects-barrel-distortion-preview';import {EffectsBlurPreview} from '../../components/effects/effects-blur-preview';import {EffectsBrightnessPreview} from '../../components/effects/effects-brightness-preview';@@ -94,6 +94,12 @@ import {EffectsWavesPreview} from '../../components/effects/effects-waves-previeimport {EffectsWhiteNoisePreview} from '../../components/effects/effects-white-noise-preview';import {EffectsZigzagPreview} from '../../components/effects/effects-zigzag-preview';import {EffectsZoomBlurPreview} from '../../components/effects/effects-zoom-blur-preview';+import {elementDefinitions} from '../components/Elements/element-definitions';+import {getElementCompositionId} from '../components/Elements/element-utils';+import {+ ElementAssetComposition,+ getElementPreviewDimensions,+} from '../components/Elements/ElementPreviewComposition';import {articles} from '../data/articles';import {AllTemplates} from './AllTemplates';import {Article} from './Article';@@ -115,6 +121,24 @@ const DEFAULT_THERMAL_PALETTE = [export const RemotionRoot: React.FC = () => {return (<>+ <Folder name="elements">+ {Object.values(elementDefinitions).map((definition) => {+ const dimensions = getElementPreviewDimensions(definition);++ return (+ <Composition+ key={definition.slug}+ component={ElementAssetComposition}+ defaultProps={{slug: definition.slug}}+ durationInFrames={definition.durationInFrames}+ fps={definition.fps}+ height={dimensions.height}+ id={getElementCompositionId(definition.slug)}+ width={dimensions.width}+ />+ );+ })}+ </Folder><Folder name="experts">{experts.map((e) => {return (diff --git a/packages/docs/src/test/elements.test.ts b/packages/docs/src/test/elements.test.tsindex 540c412707..258ca99cba 100644--- a/packages/docs/src/test/elements.test.ts+++ b/packages/docs/src/test/elements.test.ts@@ -3,9 +3,16 @@ import {existsSync, readdirSync, readFileSync, statSync} from 'fs';import path from 'path';import {expandElementSourceReferences} from '../../plugins/element-source-utils';import remarkElementSource from '../../plugins/remark-element-source';+import {elementDefinitions} from '../components/Elements/element-definitions';+import {+ getElementCompositionId,+ getElementPreviewUrls,+} from '../components/Elements/element-utils';+import {getElementPreviewDimensions} from '../components/Elements/ElementPreviewComposition';const elementsRoot = path.join(__dirname, '..', '..', 'elements');const templateRoot = path.join(__dirname, '..', '..', 'elements-template');+const elementDefinitionList = Object.values(elementDefinitions);type Element = {name: string;@@ -23,8 +30,9 @@ const findElements = (root: string): Element[] => {(f) => f.endsWith('.tsx') && !f.endsWith('.test.tsx'),);if (tsxFiles.length > 0) {+ const relativeName = path.relative(root, dir) || path.basename(dir);elements.push({- name: path.relative(root, dir) || path.basename(dir),+ name: relativeName.split(path.sep).join('/'),mdxPath: indexMdx,tsxPath: path.join(dir, tsxFiles[0]),});@@ -49,10 +57,8 @@ const getRelativeTsxPath = (tsxPath: string, mdxPath: string) => {return relative.startsWith('.') ? relative : `./${relative}`;};-const allElements = [- ...findElements(elementsRoot),- ...findElements(templateRoot),-];+const productionElements = findElements(elementsRoot);+const allElements = [...productionElements, ...findElements(templateRoot)];describe('Elements must follow the colocated single-file format', () => {test('at least one element exists', () => {@@ -111,10 +117,6 @@ describe('Elements must follow the colocated single-file format', () => {expect(mdx).toContain('ElementPage');});- test('MDX imports the colocated source module', () => {- expect(mdx).toMatch(/from '\.\/[\w-]+';/);- });-test('MDX references the source file from ElementPage', () => {const relativeTsxPath = getRelativeTsxPath(element.tsxPath,@@ -146,15 +148,19 @@ describe('Elements must follow the colocated single-file format', () => {expect(mdx).not.toMatch(/export const \w+Source = /);});- test('Element drag file name is derived from the slug', () => {+ test('Element drag file name is derived from the definition slug', () => {expect(mdx).not.toContain('fileName=');- const match = mdx.match(/slug="([^"]+)"/);- if (!match) {+ if (element.mdxPath.startsWith(templateRoot)) {return;}- const lastSlugSegment = match[1].split('/').at(-1);+ const definition = elementDefinitionList.find(+ (entry) => entry.slug === element.name,+ );+ expect(definition).toBeDefined();++ const lastSlugSegment = definition?.slug.split('/').at(-1);expect(lastSlugSegment).toBeTruthy();expect(lastSlugSegment).toBe(lastSlugSegment?.toLowerCase());expect(lastSlugSegment).not.toContain('..');@@ -162,3 +168,68 @@ describe('Elements must follow the colocated single-file format', () => {});}});++describe('Element preview definitions', () => {+ test('contains every production Element exactly once', () => {+ const elementSlugs = productionElements+ .map((element) => element.name)+ .sort();+ const definitionSlugs = elementDefinitionList+ .map((definition) => definition.slug)+ .sort();+ const definitionKeys = Object.keys(elementDefinitions).sort();++ expect(definitionKeys).toEqual(elementSlugs);+ expect(definitionSlugs).toEqual(elementSlugs);+ expect(new Set(definitionSlugs).size).toBe(definitionSlugs.length);++ for (const [slug, definition] of Object.entries(elementDefinitions)) {+ expect(definition.slug).toBe(slug);+ }+ });++ test('contains valid render metadata', () => {+ for (const definition of elementDefinitionList) {+ expect(Number.isInteger(definition.width)).toBe(true);+ expect(Number.isInteger(definition.height)).toBe(true);+ expect(Number.isInteger(definition.fps)).toBe(true);+ expect(Number.isInteger(definition.durationInFrames)).toBe(true);+ expect(Number.isInteger(definition.posterFrame)).toBe(true);+ expect(definition.width).toBeGreaterThan(0);+ expect(definition.height).toBeGreaterThan(0);+ expect(definition.fps).toBeGreaterThan(0);+ expect(definition.durationInFrames).toBeGreaterThan(0);+ expect(definition.posterFrame).toBeGreaterThanOrEqual(0);+ expect(definition.posterFrame).toBeLessThan(definition.durationInFrames);+ expect(definition.elementWidth === null).toBe(+ definition.elementHeight === null,+ );++ const dimensions = getElementPreviewDimensions(definition);+ expect(dimensions.width % 2).toBe(0);+ expect(dimensions.height % 2).toBe(0);+ }+ });++ test('derives stable composition IDs and preview URLs', () => {+ const compositionIds = elementDefinitionList.map((definition) =>+ getElementCompositionId(definition.slug),+ );+ expect(new Set(compositionIds).size).toBe(compositionIds.length);++ for (const definition of elementDefinitionList) {+ expect(getElementPreviewUrls(definition.slug)).toEqual({+ mp4: `https://remotion.media/elements/${definition.slug}/preview.mp4`,+ png: `https://remotion.media/elements/${definition.slug}/preview.png`,+ });+ }+ });++ test('registers Element compositions in a Folder', () => {+ const root = readFileSync(+ path.join(__dirname, '..', 'remotion', 'Root.tsx'),+ 'utf8',+ );+ expect(root).toContain('<Folder name="elements">');+ });+});diff --git a/packages/docs/tsconfig.json b/packages/docs/tsconfig.jsonindex cdbf74df3e..3e79b82ca7 100644--- a/packages/docs/tsconfig.json+++ b/packages/docs/tsconfig.json@@ -54,5 +54,9 @@{"path": "../elevenlabs"},{"path": "../cli"}],- "exclude": ["copy-convert.ts", "render-cards.ts"]+ "exclude": [+ "copy-convert.ts",+ "render-cards.ts",+ "render-element-previews.ts"+ ]}