Skip to content

🎥 Make videos programmatically with React

Elements: Drag listing cards into Studio (#10450)

Igor Samokhovetsc1882d825e31
diff --git a/packages/docs/docusaurus.config.ts b/packages/docs/docusaurus.config.ts
index 248b267c64..5888728123 100644
--- a/packages/docs/docusaurus.config.ts
+++ b/packages/docs/docusaurus.config.ts
@@ -1,6 +1,8 @@
import type {Config} from '@docusaurus/types';
+import elementSourceDependencies from './plugins/element-source-dependencies.js';
import remarkElementSource from './plugins/remark-element-source.js';
import remarkExportRaw from './plugins/remark-export-raw.js';
+import {elementRegistry} from './src/components/Elements/element-registry';
const lowMemoryBuild =
process.env.VERCEL === '1' ||
@@ -348,6 +350,7 @@ const config: Config = {
],
],
plugins: [
+ elementSourceDependencies,
[
'@docusaurus/plugin-content-docs',
{
@@ -358,7 +361,7 @@ const config: Config = {
editUrl:
'https://github.com/remotion-dev/remotion/edit/main/packages/docs/',
showLastUpdateTime: showGitLastUpdate,
- beforeDefaultRemarkPlugins: [remarkElementSource],
+ beforeDefaultRemarkPlugins: [[remarkElementSource, {elementRegistry}]],
remarkPlugins: [remarkExportRaw],
},
],
diff --git a/packages/docs/plugins/element-source-dependencies.js b/packages/docs/plugins/element-source-dependencies.js
new file mode 100644
index 0000000000..447c570696
--- /dev/null
+++ b/packages/docs/plugins/element-source-dependencies.js
@@ -0,0 +1,32 @@
+import path from 'path';
+
+export default function elementSourceDependencies({siteDir}) {
+ const elementsRoot = path.join(siteDir, 'elements');
+
+ return {
+ name: 'element-source-dependencies',
+ configureWebpack() {
+ return {
+ module: {
+ rules: [
+ {
+ test: /\.mdx?$/i,
+ include: elementsRoot,
+ enforce: 'pre',
+ use: [
+ {
+ loader: path.join(
+ siteDir,
+ 'plugins',
+ 'element-source-dependency-loader.cjs',
+ ),
+ options: {elementsRoot},
+ },
+ ],
+ },
+ ],
+ },
+ };
+ },
+ };
+}
diff --git a/packages/docs/plugins/element-source-dependency-loader.cjs b/packages/docs/plugins/element-source-dependency-loader.cjs
new file mode 100644
index 0000000000..60d0b1f618
--- /dev/null
+++ b/packages/docs/plugins/element-source-dependency-loader.cjs
@@ -0,0 +1,19 @@
+const fs = require('fs');
+const path = require('path');
+
+module.exports = function elementSourceDependencyLoader(source) {
+ const {elementsRoot} = this.getOptions();
+ const walk = (directory) => {
+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {
+ const absolutePath = path.join(directory, entry.name);
+ if (entry.isDirectory()) {
+ walk(absolutePath);
+ } else if (entry.name.endsWith('.tsx')) {
+ this.addDependency(absolutePath);
+ }
+ }
+ };
+
+ walk(elementsRoot);
+ return source;
+};
diff --git a/packages/docs/plugins/element-source-utils.d.ts b/packages/docs/plugins/element-source-utils.d.ts
index d9eb15b279..82fbb1dbf1 100644
--- a/packages/docs/plugins/element-source-utils.d.ts
+++ b/packages/docs/plugins/element-source-utils.d.ts
@@ -8,7 +8,13 @@ export function getElementSourceCodeBlock(input: {
sourceFilePath: string;
}): string;
+export function getRemotionElementDependencies(source: string): string[];
+
export function getRemotionElementSource(input: {
file: string;
sourceFilePath: string;
}): string;
+
+export function getRemotionElementSourceMap(input: {
+ elementsRoot: string;
+}): Record<string, string>;
diff --git a/packages/docs/plugins/element-source-utils.js b/packages/docs/plugins/element-source-utils.js
index 782f968033..aed548bf42 100644
--- a/packages/docs/plugins/element-source-utils.js
+++ b/packages/docs/plugins/element-source-utils.js
@@ -125,6 +125,68 @@ const parseAttributes = (attributes) => {
return parsed;
};
+export const getRemotionElementSourceMap = ({elementsRoot}) => {
+ const indexFiles = [];
+ const walk = (directory) => {
+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {
+ const absolutePath = path.join(directory, entry.name);
+ if (entry.isDirectory()) {
+ walk(absolutePath);
+ } else if (entry.name === 'index.mdx') {
+ indexFiles.push(absolutePath);
+ }
+ }
+ };
+
+ walk(elementsRoot);
+ const sourceCodeBySlug = {};
+
+ for (const sourceFilePath of indexFiles.sort()) {
+ const raw = fs.readFileSync(sourceFilePath, 'utf8');
+ const elementPages = Array.from(
+ raw.matchAll(/<ElementPage\b([\s\S]*?)\/>/g),
+ );
+ if (elementPages.length === 0) {
+ continue;
+ }
+
+ if (elementPages.length > 1) {
+ throw new Error(
+ `Expected one ElementPage in "${sourceFilePath}", found ${elementPages.length}.`,
+ );
+ }
+
+ const file = parseAttributes(elementPages[0][1]).get('sourceFile');
+ if (!file) {
+ throw new Error(
+ `ElementPage in "${sourceFilePath}" must have a sourceFile attribute.`,
+ );
+ }
+
+ const relativeDirectory = path.relative(
+ elementsRoot,
+ path.dirname(sourceFilePath),
+ );
+ const slug = relativeDirectory.split(path.sep).join('/');
+ if (!slug || slug.startsWith('../') || path.isAbsolute(relativeDirectory)) {
+ throw new Error(
+ `Could not derive an Element slug for "${sourceFilePath}" relative to "${elementsRoot}".`,
+ );
+ }
+
+ if (Object.hasOwn(sourceCodeBySlug, slug)) {
+ throw new Error(`Duplicate Element source found for slug "${slug}".`);
+ }
+
+ sourceCodeBySlug[slug] = getRemotionElementSource({
+ file,
+ sourceFilePath,
+ });
+ }
+
+ return sourceCodeBySlug;
+};
+
const appendSourceCodeBlock = ({attributes, match, sourceFilePath}) => {
const parsed = parseAttributes(attributes);
const file = parsed.get('sourceFile');
diff --git a/packages/docs/plugins/remark-element-source.js b/packages/docs/plugins/remark-element-source.js
index ebc9c1715a..7a541e2a1e 100644
--- a/packages/docs/plugins/remark-element-source.js
+++ b/packages/docs/plugins/remark-element-source.js
@@ -1,7 +1,15 @@
-import {getRemotionElementSource} from './element-source-utils.js';
+import path from 'path';
+import {
+ getRemotionElementSource,
+ getRemotionElementSourceMap,
+} from './element-source-utils.js';
-const getAttributeValue = (node, name) => {
- const attribute = node.attributes?.find((attr) => attr.name === name);
+const getAttribute = (node, name) => {
+ return node.attributes?.find((attribute) => attribute.name === name) ?? null;
+};
+
+const getStringAttributeValue = (node, name) => {
+ const attribute = getAttribute(node, name);
if (!attribute || typeof attribute.value !== 'string') {
return null;
@@ -10,12 +18,18 @@ const getAttributeValue = (node, name) => {
return attribute.value;
};
-const sourceCodeAttribute = (sourceCode) => {
- const value = JSON.stringify(sourceCode);
+const literal = (value) => {
+ return {
+ type: 'Literal',
+ value,
+ raw: JSON.stringify(value),
+ };
+};
+const expressionAttribute = ({expression, name, value}) => {
return {
type: 'mdxJsxAttribute',
- name: 'sourceCode',
+ name,
value: {
type: 'mdxJsxAttributeValueExpression',
value,
@@ -25,11 +39,7 @@ const sourceCodeAttribute = (sourceCode) => {
body: [
{
type: 'ExpressionStatement',
- expression: {
- type: 'Literal',
- value: sourceCode,
- raw: value,
- },
+ expression,
},
],
sourceType: 'module',
@@ -39,17 +49,41 @@ const sourceCodeAttribute = (sourceCode) => {
};
};
-const setElementPageSource = ({node, sourceCode}) => {
- const attributesWithoutSourceFile = (node.attributes ?? []).filter(
- (attribute) => attribute.name !== 'sourceFile',
- );
- const attributesWithoutGeneratedValues = attributesWithoutSourceFile.filter(
- (attribute) => attribute.name !== 'sourceCode',
- );
+const sourceCodeAttribute = (sourceCode) => {
+ return expressionAttribute({
+ expression: literal(sourceCode),
+ name: 'sourceCode',
+ value: JSON.stringify(sourceCode),
+ });
+};
+const sourceCodeBySlugAttribute = (sourceCodeBySlug) => {
+ return expressionAttribute({
+ expression: {
+ type: 'ObjectExpression',
+ properties: Object.entries(sourceCodeBySlug).map(
+ ([slug, sourceCode]) => ({
+ type: 'Property',
+ method: false,
+ shorthand: false,
+ computed: false,
+ key: literal(slug),
+ value: literal(sourceCode),
+ kind: 'init',
+ }),
+ ),
+ },
+ name: 'sourceCodeBySlug',
+ value: JSON.stringify(sourceCodeBySlug),
+ });
+};
+
+const setGeneratedAttribute = ({attribute, name, node}) => {
node.attributes = [
- ...attributesWithoutGeneratedValues,
- sourceCodeAttribute(sourceCode),
+ ...(node.attributes ?? []).filter(
+ (existingAttribute) => existingAttribute.name !== name,
+ ),
+ attribute,
];
};
@@ -58,14 +92,20 @@ const getSourceCodeNode = ({node, sourceFilePath}) => {
return null;
}
- const file = getAttributeValue(node, 'sourceFile');
-
+ const file = getStringAttributeValue(node, 'sourceFile');
if (!file) {
return null;
}
const sourceCode = getRemotionElementSource({file, sourceFilePath});
- setElementPageSource({node, sourceCode});
+ node.attributes = (node.attributes ?? []).filter(
+ (attribute) => attribute.name !== 'sourceFile',
+ );
+ setGeneratedAttribute({
+ attribute: sourceCodeAttribute(sourceCode),
+ name: 'sourceCode',
+ node,
+ });
return {
type: 'code',
@@ -75,30 +115,140 @@ const getSourceCodeNode = ({node, sourceFilePath}) => {
};
};
-const attachElementPageSourceNodes = ({node, sourceFilePath}) => {
+const getElementLibraryCategory = (node) => {
+ const attribute = getAttribute(node, 'category');
+ if (!attribute) {
+ throw new Error('ElementLibrary must have a category attribute.');
+ }
+
+ if (typeof attribute.value === 'string') {
+ return attribute.value;
+ }
+
+ if (
+ attribute.value?.type === 'mdxJsxAttributeValueExpression' &&
+ attribute.value.value.trim() === 'null'
+ ) {
+ return null;
+ }
+
+ throw new Error('ElementLibrary category must be a string or null.');
+};
+
+const findElementsRoot = (sourceFilePath) => {
+ let directory = path.dirname(sourceFilePath);
+
+ while (true) {
+ if (path.basename(directory) === 'elements') {
+ return directory;
+ }
+
+ const parent = path.dirname(directory);
+ if (parent === directory) {
+ throw new Error(
+ `Could not find the Elements root for "${sourceFilePath}".`,
+ );
+ }
+
+ directory = parent;
+ }
+};
+
+const attachElementSourceNodes = ({
+ elementRegistry,
+ getSourceCodeBySlug,
+ node,
+ sourceFilePath,
+}) => {
if (!node.children) {
return;
}
- const children = [];
-
for (const child of node.children) {
- attachElementPageSourceNodes({node: child, sourceFilePath});
+ attachElementSourceNodes({
+ elementRegistry,
+ getSourceCodeBySlug,
+ node: child,
+ sourceFilePath,
+ });
const sourceCodeNode = getSourceCodeNode({node: child, sourceFilePath});
if (sourceCodeNode) {
child.children = [...(child.children ?? []), sourceCodeNode];
}
- children.push(child);
- }
+ if (child.type !== 'mdxJsxFlowElement' || child.name !== 'ElementLibrary') {
+ continue;
+ }
+
+ const category = getElementLibraryCategory(child);
+ const registryEntries = Object.entries(elementRegistry);
+ if (
+ category !== null &&
+ !registryEntries.some(([, metadata]) => metadata.category === category)
+ ) {
+ throw new Error(`Invalid Element category: ${category}`);
+ }
+
+ const completeSourceCodeBySlug = getSourceCodeBySlug();
+ const registrySlugs = registryEntries.map(([slug]) => slug).sort();
+ const sourceSlugs = Object.keys(completeSourceCodeBySlug).sort();
+ const missingSources = registrySlugs.filter(
+ (slug) => !Object.hasOwn(completeSourceCodeBySlug, slug),
+ );
+ const unregisteredSources = sourceSlugs.filter(
+ (slug) => !Object.hasOwn(elementRegistry, slug),
+ );
+ if (missingSources.length > 0 || unregisteredSources.length > 0) {
+ throw new Error(
+ [
+ 'Element registry and source pages do not match.',
+ missingSources.length > 0
+ ? `Missing source pages: ${missingSources.join(', ')}.`
+ : null,
+ unregisteredSources.length > 0
+ ? `Unregistered source pages: ${unregisteredSources.join(', ')}.`
+ : null,
+ ]
+ .filter(Boolean)
+ .join(' '),
+ );
+ }
- node.children = children;
+ const selectedSourceCodeBySlug = Object.fromEntries(
+ registryEntries
+ .filter(
+ ([, metadata]) => category === null || metadata.category === category,
+ )
+ .map(([slug]) => [slug, completeSourceCodeBySlug[slug]])
+ .sort(([a], [b]) => a.localeCompare(b)),
+ );
+ setGeneratedAttribute({
+ attribute: sourceCodeBySlugAttribute(selectedSourceCodeBySlug),
+ name: 'sourceCodeBySlug',
+ node: child,
+ });
+ }
};
-export default function remarkElementSource() {
+export default function remarkElementSource({elementRegistry}) {
+ if (!elementRegistry || typeof elementRegistry !== 'object') {
+ throw new Error('remarkElementSource requires an Element registry.');
+ }
+
return (tree, file) => {
- attachElementPageSourceNodes({
+ let sourceCodeBySlug = null;
+ attachElementSourceNodes({
+ elementRegistry,
+ getSourceCodeBySlug: () => {
+ if (sourceCodeBySlug === null) {
+ sourceCodeBySlug = getRemotionElementSourceMap({
+ elementsRoot: findElementsRoot(file.path),
+ });
+ }
+
+ return sourceCodeBySlug;
+ },
node: tree,
sourceFilePath: file.path,
});
diff --git a/packages/docs/src/components/Elements/ElementLibrary.tsx b/packages/docs/src/components/Elements/ElementLibrary.tsx
index 9a7e6070c8..253422d478 100644
--- a/packages/docs/src/components/Elements/ElementLibrary.tsx
+++ b/packages/docs/src/components/Elements/ElementLibrary.tsx
@@ -1,5 +1,10 @@
-import React, {useEffect, useRef, useState} from 'react';
+import {setStudioDragData} from '@remotion/studio-protocol';
+import React, {useEffect, useMemo, useRef, useState} from 'react';
import type {ElementDefinition} from './element-definitions';
+import {
+ createElementPayloadFromDefinition,
+ setElementDragImage,
+} from './element-drag-data';
import {
getElementDocumentationUrl,
getElementLibrarySections,
@@ -34,7 +39,8 @@ const ElementCard: React.FC<{
readonly definition: ElementDefinition;
readonly headingLevel: 2 | 3;
readonly prefersReducedMotion: boolean;
-}> = ({definition, headingLevel, prefersReducedMotion}) => {
+ readonly sourceCode: string;
+}> = ({definition, headingLevel, prefersReducedMotion, sourceCode}) => {
const [isFocused, setIsFocused] = useState(false);
const [isPointerOver, setIsPointerOver] = useState(false);
const [playbackFailed, setPlaybackFailed] = useState(false);
@@ -42,6 +48,10 @@ const ElementCard: React.FC<{
const shouldPlay =
!prefersReducedMotion && !playbackFailed && (isFocused || isPointerOver);
const Heading = headingLevel === 2 ? 'h2' : 'h3';
+ const elementPayload = useMemo(
+ () => createElementPayloadFromDefinition({definition, sourceCode}),
+ [definition, sourceCode],
+ );
useEffect(() => {
const video = videoRef.current;
@@ -79,14 +89,23 @@ const ElementCard: React.FC<{
<li className={styles.cardItem}>
<a
className={styles.card}
+ draggable
href={getElementDocumentationUrl(definition)}
onBlur={() => setIsFocused(false)}
onFocus={() => {
setPlaybackFailed(false);
setIsFocused(true);
}}
+ onDragStart={(event) => {
+ setStudioDragData({
+ dataTransfer: event.dataTransfer,
+ payload: elementPayload,
+ });
+ setElementDragImage(event.dataTransfer);
+ }}
onPointerEnter={activateFromPointer}
onPointerLeave={() => setIsPointerOver(false)}
+ title="Click to view details, or drag this Element into Remotion Studio"
>
<div
aria-hidden="true"
@@ -128,24 +147,36 @@ const ElementGrid: React.FC<{
readonly definitions: readonly ElementDefinition[];
readonly headingLevel: 2 | 3;
readonly prefersReducedMotion: boolean;
-}> = ({definitions, headingLevel, prefersReducedMotion}) => {
+ readonly sourceCodeBySlug: Readonly<Record<string, string>>;
+}> = ({definitions, headingLevel, prefersReducedMotion, sourceCodeBySlug}) => {
return (
<ul className={styles.grid} role="list">
- {definitions.map((definition) => (
- <ElementCard
- key={definition.slug}
- definition={definition}
- headingLevel={headingLevel}
- prefersReducedMotion={prefersReducedMotion}
- />
- ))}
+ {definitions.map((definition) => {
+ const sourceCode = sourceCodeBySlug[definition.slug];
+ if (!sourceCode) {
+ throw new Error(
+ `Missing generated source code for Element "${definition.slug}".`,
+ );
+ }
+
+ return (
+ <ElementCard
+ key={definition.slug}
+ definition={definition}
+ headingLevel={headingLevel}
+ prefersReducedMotion={prefersReducedMotion}
+ sourceCode={sourceCode}
+ />
+ );
+ })}
</ul>
);
};
export const ElementLibrary: React.FC<{
readonly category: ElementCategory | null;
-}> = ({category}) => {
+ readonly sourceCodeBySlug: Readonly<Record<string, string>>;
+}> = ({category, sourceCodeBySlug}) => {
const sections = getElementLibrarySections(category);
const prefersReducedMotion = usePrefersReducedMotion();
@@ -163,6 +194,7 @@ export const ElementLibrary: React.FC<{
definitions={section.definitions}
headingLevel={2}
prefersReducedMotion={prefersReducedMotion}
+ sourceCodeBySlug={sourceCodeBySlug}
/>
</section>
);
@@ -183,6 +215,7 @@ export const ElementLibrary: React.FC<{
definitions={section.definitions}
headingLevel={3}
prefersReducedMotion={prefersReducedMotion}
+ sourceCodeBySlug={sourceCodeBySlug}
/>
</section>
);
diff --git a/packages/docs/src/components/Elements/ElementPage.tsx b/packages/docs/src/components/Elements/ElementPage.tsx
index 08d05f6c34..74714509c0 100644
--- a/packages/docs/src/components/Elements/ElementPage.tsx
+++ b/packages/docs/src/components/Elements/ElementPage.tsx
@@ -1,9 +1,5 @@
import Head from '@docusaurus/Head';
-import {
- createElementPayload,
- installInStudio,
- setStudioDragData,
-} from '@remotion/studio-protocol';
+import {installInStudio, setStudioDragData} from '@remotion/studio-protocol';
import React, {
useCallback,
useId,
@@ -14,7 +10,10 @@ import React, {
import {BlueButton} from '../../../components/layout/Button';
import {Seo} from '../Seo';
import type {ElementDefinition} from './element-definitions';
-import {setElementDragImage} from './element-drag-data';
+import {
+ createElementPayloadFromDefinition,
+ setElementDragImage,
+} from './element-drag-data';
import {getElementDimensionsLabel} from './element-utils';
import {ElementPreview} from './ElementPreview';
import {
@@ -40,17 +39,7 @@ export const ElementPage: React.FC<ElementPageProps> = ({
definition,
sourceCode,
}) => {
- const {
- contributors,
- description,
- displayName,
- durationInFrames,
- elementHeight,
- elementWidth,
- fps,
- slug,
- installationMode,
- } = definition;
+ const {contributors, description, durationInFrames, fps} = definition;
const [installStatus, setInstallStatus] = useState<InstallStatus>({
type: 'idle',
});
@@ -65,33 +54,8 @@ export const ElementPage: React.FC<ElementPageProps> = ({
return null;
}
- const dimensions =
- elementWidth !== null && elementHeight !== null
- ? {
- width: elementWidth,
- height: elementHeight,
- }
- : null;
-
- return createElementPayload({
- dependencies: definition.dependencies,
- dimensions,
- displayName,
- durationInFrames,
- slug,
- sourceCode,
- installationMode,
- });
- }, [
- definition.dependencies,
- displayName,
- durationInFrames,
- elementHeight,
- elementWidth,
- slug,
- sourceCode,
- installationMode,
- ]);
+ return createElementPayloadFromDefinition({definition, sourceCode});
+ }, [definition, sourceCode]);
const installElement = useCallback(async () => {
if (elementPayload === null) {
diff --git a/packages/docs/src/components/Elements/element-drag-data.ts b/packages/docs/src/components/Elements/element-drag-data.ts
index 3c9c9dcfcb..4ed3d4fd39 100644
--- a/packages/docs/src/components/Elements/element-drag-data.ts
+++ b/packages/docs/src/components/Elements/element-drag-data.ts
@@ -1,3 +1,35 @@
+import {
+ createElementPayload,
+ type StudioElementPayload,
+} from '@remotion/studio-protocol';
+import type {ElementDefinition} from './element-definitions';
+
+export const createElementPayloadFromDefinition = ({
+ definition,
+ sourceCode,
+}: {
+ readonly definition: ElementDefinition;
+ readonly sourceCode: string;
+}): StudioElementPayload => {
+ const dimensions =
+ definition.elementWidth !== null && definition.elementHeight !== null
+ ? {
+ width: definition.elementWidth,
+ height: definition.elementHeight,
+ }
+ : null;
+
+ return createElementPayload({
+ dependencies: definition.dependencies,
+ dimensions,
+ displayName: definition.displayName,
+ durationInFrames: definition.durationInFrames,
+ installationMode: definition.installationMode,
+ slug: definition.slug,
+ sourceCode,
+ });
+};
+
const ELEMENT_ICON_PATH =
'M3 3.5C3 2.67157 3.67157 2 4.5 2H11.5C12.3284 2 13 2.67157 13 3.5V12.5C13 13.3284 12.3284 14 11.5 14H4.5C3.67157 14 3 13.3284 3 12.5V3.5ZM4.5 3.5V6H11.5V3.5H4.5ZM11.5 7.5H4.5V12.5H11.5V7.5Z';
diff --git a/packages/docs/src/test/elements.test.ts b/packages/docs/src/test/elements.test.ts
index b919680072..a76a9a82d1 100644
--- a/packages/docs/src/test/elements.test.ts
+++ b/packages/docs/src/test/elements.test.ts
@@ -7,9 +7,11 @@ import elementSidebars from '../../elements-sidebars';
import {
expandElementSourceReferences,
getRemotionElementDependencies,
+ getRemotionElementSourceMap,
} from '../../plugins/element-source-utils';
import remarkElementSource from '../../plugins/remark-element-source';
import {elementDefinitions} from '../components/Elements/element-definitions';
+import {createElementPayloadFromDefinition} from '../components/Elements/element-drag-data';
import {
getElementDocumentationUrl,
getElementLibrarySections,
@@ -107,7 +109,7 @@ describe('Elements must follow the colocated single-file format', () => {
};
const tree = {type: 'root', children: [elementPage]};
- remarkElementSource()(tree, {path: element.mdxPath});
+ remarkElementSource({elementRegistry})(tree, {path: element.mdxPath});
expect(tree.children).toHaveLength(1);
expect(elementPage.children).toHaveLength(1);
@@ -217,9 +219,98 @@ describe('Elements must follow the colocated single-file format', () => {
});
describe('Element library', () => {
- test('renders every definition and filters the real category entry points', () => {
+ test('injects the exact source files needed by each listing', () => {
+ const completeSourceCodeBySlug = getRemotionElementSourceMap({
+ elementsRoot,
+ });
+ expect(Object.keys(completeSourceCodeBySlug).sort()).toEqual(
+ productionElements.map((element) => element.name).sort(),
+ );
+ for (const element of productionElements) {
+ expect(completeSourceCodeBySlug[element.name]).toBe(
+ readFileSync(element.tsxPath, 'utf8').trimEnd(),
+ );
+ }
+
+ const makeLibraryNode = (category: string | null) => ({
+ type: 'mdxJsxFlowElement',
+ name: 'ElementLibrary',
+ attributes: [
+ {
+ type: 'mdxJsxAttribute',
+ name: 'category',
+ value:
+ category === null
+ ? {
+ type: 'mdxJsxAttributeValueExpression',
+ value: 'null',
+ }
+ : category,
+ },
+ ],
+ children: [],
+ });
+ const getInjectedSourceCodeBySlug = (node: {
+ attributes: readonly {readonly name?: string; readonly value?: unknown}[];
+ }) => {
+ const attribute = node.attributes.find(
+ (candidate) => candidate.name === 'sourceCodeBySlug',
+ );
+ if (
+ typeof attribute?.value !== 'object' ||
+ attribute.value === null ||
+ !('value' in attribute.value) ||
+ typeof attribute.value.value !== 'string'
+ ) {
+ throw new Error('ElementLibrary source map was not injected');
+ }
+
+ return JSON.parse(attribute.value.value) as Record<string, string>;
+ };
+
+ const overview = makeLibraryNode(null);
+ remarkElementSource({elementRegistry})(
+ {type: 'root', children: [overview]},
+ {path: path.join(elementsRoot, 'index.mdx')},
+ );
+ expect(getInjectedSourceCodeBySlug(overview)).toEqual(
+ completeSourceCodeBySlug,
+ );
+
+ const storytelling = makeLibraryNode('storytelling');
+ remarkElementSource({elementRegistry})(
+ {type: 'root', children: [storytelling]},
+ {path: path.join(elementsRoot, 'storytelling', 'index.mdx')},
+ );
+ expect(getInjectedSourceCodeBySlug(storytelling)).toEqual({
+ 'text/news-article-highlight':
+ completeSourceCodeBySlug['text/news-article-highlight'],
+ });
+
+ const missingSource = makeLibraryNode(null);
+ expect(() =>
+ remarkElementSource({
+ elementRegistry: {
+ ...elementRegistry,
+ 'missing/source': {
+ category: 'text',
+ displayName: 'Missing Source',
+ },
+ },
+ })(
+ {type: 'root', children: [missingSource]},
+ {path: path.join(elementsRoot, 'index.mdx')},
+ ),
+ ).toThrow('Missing source pages: missing/source.');
+ });
+
+ test('renders draggable cards and filters the real category entry points', () => {
+ const sourceCodeBySlug = getRemotionElementSourceMap({elementsRoot});
const overviewMarkup = renderToStaticMarkup(
- React.createElement(ElementLibrary, {category: null}),
+ React.createElement(ElementLibrary, {
+ category: null,
+ sourceCodeBySlug,
+ }),
);
const sections = getElementLibrarySections(null);
@@ -234,10 +325,19 @@ describe('Element library', () => {
expect(overviewMarkup).not.toContain('.mp4');
expect(overviewMarkup).toContain('>YouTube</h2>');
+ expect(overviewMarkup.match(/draggable="true"/g)).toHaveLength(
+ elementDefinitionList.length,
+ );
+ expect(overviewMarkup).toContain(
+ 'title="Click to view details, or drag this Element into Remotion Studio"',
+ );
for (const section of sections) {
const categoryMarkup = renderToStaticMarkup(
- React.createElement(ElementLibrary, {category: section.category}),
+ React.createElement(ElementLibrary, {
+ category: section.category,
+ sourceCodeBySlug,
+ }),
);
const categoryIndex = readFileSync(
path.join(elementsRoot, section.category, 'index.mdx'),
@@ -260,6 +360,43 @@ describe('Element library', () => {
}
}
});
+
+ test('creates canonical fixed-size and adaptive drag payloads', () => {
+ const sourceCodeBySlug = getRemotionElementSourceMap({elementsRoot});
+ for (const slug of [
+ 'overlays/name-lower-third',
+ 'backgrounds/paper-texture',
+ ] as const) {
+ const definition = elementDefinitions[slug];
+ const sourceCode = sourceCodeBySlug[slug];
+ const payload = createElementPayloadFromDefinition({
+ definition,
+ sourceCode,
+ });
+
+ expect(payload).toMatchObject({
+ type: 'remotion-element',
+ version: 1,
+ durationInFrames: definition.durationInFrames,
+ element: {
+ dependencies: definition.dependencies,
+ displayName: definition.displayName,
+ durationInFrames: definition.durationInFrames,
+ installationMode: definition.installationMode,
+ slug,
+ sourceCode,
+ },
+ });
+ const expectedDimensions =
+ definition.elementWidth !== null && definition.elementHeight !== null
+ ? {
+ width: definition.elementWidth,
+ height: definition.elementHeight,
+ }
+ : null;
+ expect(payload.element.dimensions).toEqual(expectedDimensions);
+ }
+ });
});
describe('Element social previews', () => {
diff --git a/packages/docs/src/test/replace-raw-markdown-components.test.ts b/packages/docs/src/test/replace-raw-markdown-components.test.ts
index 2eb69c990f..5970258eaa 100644
--- a/packages/docs/src/test/replace-raw-markdown-components.test.ts
+++ b/packages/docs/src/test/replace-raw-markdown-components.test.ts
@@ -1,6 +1,7 @@
import {expect, test} from 'bun:test';
import {readFileSync} from 'fs';
import path from 'path';
+import {getRemotionElementSourceMap} from '../../plugins/element-source-utils';
import {elementDefinitions} from '../components/Elements/element-definitions';
import {
getElementDocumentationUrl,
@@ -36,6 +37,11 @@ test('expands the actual Element overview into categorized Markdown', () => {
});
expect(output).not.toContain('ElementLibrary');
+ expect(output).not.toContain('sourceCodeBySlug');
+ const sourceCodeBySlug = getRemotionElementSourceMap({
+ elementsRoot: path.dirname(sourcePath),
+ });
+ expect(output).not.toContain(sourceCodeBySlug['backgrounds/liquid-contours']);
for (const section of getElementLibrarySections(null)) {
expect(output).toContain(`## ${section.label}`);
}