Skip to content

🎥 Make videos programmatically with React

`@remotion/studio-codemods`: Reuse composition resolver

JonnyBurger93d7c595e59e
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index c59bf22d8b..8bbd7dd2e5 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -8,6 +8,7 @@ import type {
} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
+import {resolveCompositionComponentInProject} from './resolve-composition-component-location';
import {getNodePathForRecastPath} from './sequence-props';
import {parseAst} from './sequence-props/parse-ast';
@@ -111,15 +112,6 @@ type AstNode = {
[key: string]: unknown;
};
-type ResolvedComponent = {
- canAddSequence: boolean;
- declaration: AstNode;
- exportName: string | 'default';
- filePath: string;
- root: AstNode;
- source: string;
-};
-
type TextEdit = {
end: number;
start: number;
@@ -367,47 +359,6 @@ const jsxAttributeString = (attribute: AstNode | null) => {
: null;
};
-const jsxAttributeIdentifier = (attribute: AstNode | null) => {
- const value = attribute ? getNode(attribute, 'value') : null;
- const expression =
- value?.type === 'JSXExpressionContainer'
- ? getNode(value, 'expression')
- : null;
-
- return expression?.type === 'Identifier'
- ? getString(expression, 'name')
- : null;
-};
-
-const findDynamicImport = (attribute: AstNode | null) => {
- let importPath: string | null = null;
- const value = attribute ? getNode(attribute, 'value') : null;
- visit(value, (node) => {
- if (node.type === 'ImportExpression') {
- const source = getNode(node, 'source');
- if (source?.type === 'StringLiteral') {
- importPath = getString(source, 'value');
- return true;
- }
- }
-
- if (
- node.type === 'CallExpression' &&
- getNode(node, 'callee')?.type === 'Import'
- ) {
- const argument = getNodes(node, 'arguments')[0];
- if (argument?.type === 'StringLiteral') {
- importPath = getString(argument, 'value');
- return true;
- }
- }
-
- return false;
- });
-
- return importPath;
-};
-
const findCompositionElement = ({
ast,
compositionId,
@@ -508,36 +459,6 @@ const findDefaultDeclaration = (ast: AstNode) => {
return null;
};
-const findImport = ({ast, localName}: {ast: AstNode; localName: string}) => {
- for (const statement of programStatements(ast)) {
- if (statement.type !== 'ImportDeclaration') {
- continue;
- }
-
- const source = getString(getNode(statement, 'source'), 'value');
- for (const specifier of getNodes(statement, 'specifiers')) {
- if (getString(getNode(specifier, 'local'), 'name') !== localName) {
- continue;
- }
-
- if (specifier.type === 'ImportDefaultSpecifier') {
- return {exportName: 'default' as const, importPath: source};
- }
-
- if (specifier.type === 'ImportSpecifier') {
- const imported = getNode(specifier, 'imported');
- return {
- exportName:
- getString(imported, 'name') ?? getString(imported, 'value'),
- importPath: source,
- };
- }
- }
- }
-
- return null;
-};
-
const unwrapExpression = (node: AstNode | null): AstNode | null => {
let current = node;
while (
@@ -621,196 +542,6 @@ const canAddToRoot = (root: AstNode | null): root is AstNode => {
);
};
-const resolveReExport = ({
- ast,
- exportName,
- filePath,
- project,
-}: {
- ast: AstNode;
- exportName: string;
- filePath: string;
- project: CodemodProject;
-}): {exportName: string | 'default'; filePath: string} | null => {
- for (const statement of programStatements(ast)) {
- if (
- statement.type !== 'ExportNamedDeclaration' ||
- !getNode(statement, 'source')
- ) {
- continue;
- }
-
- const importPath = getString(getNode(statement, 'source'), 'value');
- for (const specifier of getNodes(statement, 'specifiers')) {
- const exported =
- getString(getNode(specifier, 'exported'), 'name') ??
- getString(getNode(specifier, 'exported'), 'value');
- if (exported !== exportName) {
- continue;
- }
-
- const imported =
- getString(getNode(specifier, 'local'), 'name') ??
- getString(getNode(specifier, 'local'), 'value');
- if (!importPath || !imported) {
- return null;
- }
-
- return {
- exportName: imported,
- filePath: resolveImportFile({fromFile: filePath, importPath, project}),
- };
- }
- }
-
- return null;
-};
-
-const resolveComponentDeclaration = ({
- exportName,
- filePath,
- project,
- visited,
-}: {
- exportName: string | 'default';
- filePath: string;
- project: CodemodProject;
- visited: Set<string>;
-}): {
- ast: AstNode;
- declaration: AstNode;
- exportName: string | 'default';
- filePath: string;
- source: string;
-} => {
- const key = `${filePath}:${exportName}`;
- if (visited.has(key)) {
- throw new Error(
- `Circular component export while resolving "${exportName}"`,
- );
- }
-
- visited.add(key);
- const source = project.files[filePath];
- if (typeof source !== 'string') {
- throw new Error(`Could not read source file "${filePath}"`);
- }
-
- const ast = parseSource(source);
- const declaration =
- exportName === 'default'
- ? findDefaultDeclaration(ast)
- : findNamedDeclaration(ast, exportName);
- if (declaration) {
- return {ast, declaration, exportName, filePath, source};
- }
-
- if (exportName !== 'default') {
- const reExport = resolveReExport({
- ast,
- exportName,
- filePath,
- project,
- });
- if (reExport) {
- return resolveComponentDeclaration({
- ...reExport,
- project,
- visited,
- });
- }
- }
-
- throw new Error(`Could not find composition component "${exportName}"`);
-};
-
-const resolveCompositionComponent = ({
- compositionFile,
- compositionId,
- project,
-}: {
- compositionFile: string;
- compositionId: string;
- project: CodemodProject;
-}): ResolvedComponent => {
- const registrationFile = findProjectFile({
- filePath: compositionFile,
- project,
- });
- const registrationSource = project.files[registrationFile];
- if (typeof registrationSource !== 'string') {
- throw new Error(`Could not read source file "${registrationFile}"`);
- }
-
- const registrationAst = parseSource(registrationSource);
- const compositionElement = findCompositionElement({
- ast: registrationAst,
- compositionId,
- });
- if (!compositionElement) {
- throw new Error(`Could not find composition "${compositionId}"`);
- }
-
- const lazyImportPath = findDynamicImport(
- getJsxAttribute(compositionElement, 'lazyComponent'),
- );
- let componentFile = registrationFile;
- let exportName: string | 'default';
- if (lazyImportPath) {
- componentFile = resolveImportFile({
- fromFile: registrationFile,
- importPath: lazyImportPath,
- project,
- });
- exportName = 'default';
- } else {
- const componentName = jsxAttributeIdentifier(
- getJsxAttribute(compositionElement, 'component'),
- );
- if (!componentName) {
- throw new Error(
- `Could not find a component prop for composition "${compositionId}"`,
- );
- }
-
- const componentImport = findImport({
- ast: registrationAst,
- localName: componentName,
- });
- if (componentImport?.importPath && componentImport.exportName) {
- componentFile = resolveImportFile({
- fromFile: registrationFile,
- importPath: componentImport.importPath,
- project,
- });
- exportName = componentImport.exportName;
- } else {
- exportName = componentName;
- }
- }
-
- const resolved = resolveComponentDeclaration({
- exportName,
- filePath: componentFile,
- project,
- visited: new Set(),
- });
- const root = getReturnedRoot(resolved.declaration);
-
- return {
- canAddSequence: canAddToRoot(root),
- declaration: resolved.declaration,
- exportName: resolved.exportName,
- filePath: resolved.filePath,
- root:
- root ??
- (() => {
- throw new Error('Composition component does not return JSX');
- })(),
- source: resolved.source,
- };
-};
-
const collectBindings = (ast: AstNode) => {
const bindings = new Set<string>();
visit(ast, (node) => {
@@ -1305,7 +1036,7 @@ export const insertSolidIntoProjectWithNodePathRemappings = <
throw new Error('from must be a non-negative integer');
}
- const resolved = resolveCompositionComponent({
+ const resolved = resolveCompositionComponentInProject({
compositionFile: request.compositionFile,
compositionId: request.compositionId,
project,
@@ -1364,7 +1095,7 @@ export const getCompositionComponentInfo = ({
project: CodemodProject;
request: CompositionComponentInfoRequest;
}) => {
- const resolved = resolveCompositionComponent({
+ const resolved = resolveCompositionComponentInProject({
compositionFile: request.compositionFile,
compositionId: request.compositionId,
project,
@@ -1372,11 +1103,7 @@ export const getCompositionComponentInfo = ({
return {
canAddSequence: resolved.canAddSequence,
- location: {
- source: relativeToRoot(resolved.filePath, project.rootDir),
- line: resolved.declaration.loc?.start.line ?? 1,
- column: resolved.declaration.loc?.start.column ?? 0,
- },
+ location: resolved.location,
};
};
diff --git a/packages/studio-codemods/src/resolve-composition-component-location.ts b/packages/studio-codemods/src/resolve-composition-component-location.ts
index 15ea8f5ef8..c516962e56 100644
--- a/packages/studio-codemods/src/resolve-composition-component-location.ts
+++ b/packages/studio-codemods/src/resolve-composition-component-location.ts
@@ -17,6 +17,20 @@ export type SourceMapProject = {
rootDir: string;
};
+export type ResolvedCompositionComponentInProject = {
+ canAddSequence: boolean;
+ declaration: Node;
+ exportName: string | 'default';
+ filePath: string;
+ location: {
+ column: number;
+ line: number;
+ source: string;
+ };
+ root: Node;
+ source: string;
+};
+
const parseSource = (source: string): File => {
return parse(source, {
errorRecovery: false,
@@ -315,7 +329,12 @@ const resolveDeclaration = ({
exportName: string | 'default';
project: SourceMapProject;
visited: Set<string>;
-}): {declaration: Node; filePath: string} => {
+}): {
+ declaration: Node;
+ exportName: string | 'default';
+ filePath: string;
+ source: string;
+} => {
const key = `${filePath}:${exportName}`;
if (visited.has(key)) {
throw new Error(
@@ -338,19 +357,22 @@ const resolveDeclaration = ({
defaultExport?.type === 'ExportDefaultDeclaration' &&
defaultExport.declaration.type === 'Identifier'
) {
- return resolveDeclaration({
- filePath,
- exportName: defaultExport.declaration.name,
- project,
- visited,
- });
+ for (const statement of file.program.body) {
+ const declaration = getDeclaration(
+ statement,
+ defaultExport.declaration.name,
+ );
+ if (declaration) {
+ return {declaration, exportName, filePath, source};
+ }
+ }
}
}
for (const statement of file.program.body) {
const declaration = getDeclaration(statement, exportName);
if (declaration) {
- return {declaration, filePath};
+ return {declaration, exportName, filePath, source};
}
}
@@ -415,7 +437,84 @@ const findImportedComponent = (file: File, localName: string) => {
return null;
};
-export const resolveCompositionComponentLocation = ({
+const unwrapExpression = (node: Node | null): Node | null => {
+ let current = node;
+ while (
+ current &&
+ (current.type === 'TSAsExpression' ||
+ current.type === 'TSSatisfiesExpression' ||
+ current.type === 'TypeCastExpression' ||
+ current.type === 'ParenthesizedExpression')
+ ) {
+ current = current.expression;
+ }
+
+ return current;
+};
+
+const getReturnedRoot = (declaration: Node) => {
+ let fn: Node | null = declaration;
+ if (declaration.type === 'VariableDeclarator') {
+ fn = unwrapExpression(declaration.init ?? null);
+ }
+
+ if (
+ !fn ||
+ (fn.type !== 'ArrowFunctionExpression' &&
+ fn.type !== 'FunctionExpression' &&
+ fn.type !== 'FunctionDeclaration')
+ ) {
+ return null;
+ }
+
+ const body = unwrapExpression(fn.body);
+ if (!body) {
+ return null;
+ }
+
+ if (body.type !== 'BlockStatement') {
+ return body;
+ }
+
+ const returnStatements = body.body.filter(
+ (statement) => statement.type === 'ReturnStatement',
+ );
+ if (
+ returnStatements.length !== 1 ||
+ returnStatements[0] !== body.body.at(-1)
+ ) {
+ return null;
+ }
+
+ return unwrapExpression(returnStatements[0].argument ?? null);
+};
+
+const isCanvasRoot = (root: Node) => {
+ if (root.type !== 'JSXElement') {
+ return false;
+ }
+
+ const name = jsxName(root.openingElement.name);
+ return (
+ name === 'ThreeCanvas' ||
+ name === 'RiveCanvas' ||
+ name === 'SkiaCanvas' ||
+ name === 'canvas'
+ );
+};
+
+const canAddToRoot = (root: Node) => {
+ if (root.type === 'NullLiteral') {
+ return true;
+ }
+
+ return (
+ (root.type === 'JSXElement' || root.type === 'JSXFragment') &&
+ !isCanvasRoot(root)
+ );
+};
+
+const resolveCompositionComponentDeclaration = ({
compositionFile,
compositionId,
project,
@@ -471,21 +570,66 @@ export const resolveCompositionComponentLocation = ({
}
}
- const {declaration, filePath} = resolveDeclaration({
+ const resolved = resolveDeclaration({
filePath: componentFile,
exportName,
project,
visited: new Set(),
});
- const normalizedFile = normalizePath(filePath);
+ const normalizedFile = normalizePath(resolved.filePath);
const normalizedRoot = normalizePath(project.rootDir).replace(/\/$/, '');
const source = normalizedFile.startsWith(`${normalizedRoot}/`)
? normalizedFile.slice(normalizedRoot.length + 1)
: normalizedFile.replace(/^\//, '');
return {
- source,
- line: declaration.loc?.start.line ?? 1,
- column: declaration.loc?.start.column ?? 0,
+ ...resolved,
+ location: {
+ source,
+ line: resolved.declaration.loc?.start.line ?? 1,
+ column: resolved.declaration.loc?.start.column ?? 0,
+ },
};
};
+
+export const resolveCompositionComponentInProject = ({
+ compositionFile,
+ compositionId,
+ project,
+}: {
+ compositionFile: string;
+ compositionId: string;
+ project: SourceMapProject;
+}): ResolvedCompositionComponentInProject => {
+ const resolved = resolveCompositionComponentDeclaration({
+ compositionFile,
+ compositionId,
+ project,
+ });
+ const root = getReturnedRoot(resolved.declaration);
+ if (!root) {
+ throw new Error('Composition component does not return JSX');
+ }
+
+ return {
+ ...resolved,
+ canAddSequence: canAddToRoot(root),
+ root,
+ };
+};
+
+export const resolveCompositionComponentLocation = ({
+ compositionFile,
+ compositionId,
+ project,
+}: {
+ compositionFile: string;
+ compositionId: string;
+ project: SourceMapProject;
+}) => {
+ return resolveCompositionComponentDeclaration({
+ compositionFile,
+ compositionId,
+ project,
+ }).location;
+};
diff --git a/packages/studio-codemods/src/test/resolve-composition-component-location.test.ts b/packages/studio-codemods/src/test/resolve-composition-component-location.test.ts
index fb0fc50f5a..f51bcfe1b4 100644
--- a/packages/studio-codemods/src/test/resolve-composition-component-location.test.ts
+++ b/packages/studio-codemods/src/test/resolve-composition-component-location.test.ts
@@ -1,36 +1,40 @@
import {expect, test} from 'bun:test';
-import {resolveCompositionComponentLocation} from '../resolve-composition-component-location';
+import {
+ resolveCompositionComponentInProject,
+ resolveCompositionComponentLocation,
+} from '../resolve-composition-component-location';
test('resolves a composition component from source map contents', () => {
+ const project = {
+ rootDir: '.',
+ files: {
+ './src/Root.tsx': [
+ "import {Composition} from 'remotion';",
+ "import {WidthHeightSequences} from './Sequence/WidthHeightSequences';",
+ 'export const Root = () => (',
+ ' <Composition',
+ ' id="WidthHeight"',
+ ' component={WidthHeightSequences}',
+ ' durationInFrames={120}',
+ ' fps={30}',
+ ' width={1080}',
+ ' height={1080}',
+ ' />',
+ ');',
+ ].join('\n'),
+ './src/Sequence/WidthHeightSequences.tsx': [
+ "import {Sequence} from 'remotion';",
+ '',
+ 'export const WidthHeightSequences = () => {',
+ ' return <Sequence />;',
+ '};',
+ ].join('\n'),
+ },
+ };
const location = resolveCompositionComponentLocation({
compositionFile: './src/Root.tsx',
compositionId: 'WidthHeight',
- project: {
- rootDir: '.',
- files: {
- './src/Root.tsx': [
- "import {Composition} from 'remotion';",
- "import {WidthHeightSequences} from './Sequence/WidthHeightSequences';",
- 'export const Root = () => (',
- ' <Composition',
- ' id="WidthHeight"',
- ' component={WidthHeightSequences}',
- ' durationInFrames={120}',
- ' fps={30}',
- ' width={1080}',
- ' height={1080}',
- ' />',
- ');',
- ].join('\n'),
- './src/Sequence/WidthHeightSequences.tsx': [
- "import {Sequence} from 'remotion';",
- '',
- 'export const WidthHeightSequences = () => {',
- ' return <Sequence />;',
- '};',
- ].join('\n'),
- },
- },
+ project,
});
expect(location).toEqual({
@@ -38,4 +42,49 @@ test('resolves a composition component from source map contents', () => {
line: 3,
source: 'src/Sequence/WidthHeightSequences.tsx',
});
+
+ const resolved = resolveCompositionComponentInProject({
+ compositionFile: './src/Root.tsx',
+ compositionId: 'WidthHeight',
+ project,
+ });
+ expect({
+ canAddSequence: resolved.canAddSequence,
+ exportName: resolved.exportName,
+ filePath: resolved.filePath,
+ location: resolved.location,
+ source: resolved.source,
+ }).toEqual({
+ canAddSequence: true,
+ exportName: 'WidthHeightSequences',
+ filePath: './src/Sequence/WidthHeightSequences.tsx',
+ location,
+ source: project.files['./src/Sequence/WidthHeightSequences.tsx'],
+ });
+});
+
+test('preserves default exports when resolving a named declaration', () => {
+ const project = {
+ rootDir: '.',
+ files: {
+ './src/Root.tsx': [
+ "import {Composition} from 'remotion';",
+ "import Video from './Video';",
+ 'export const Root = () => <Composition id="Video" component={Video} />;',
+ ].join('\n'),
+ './src/Video.tsx': [
+ 'const Video = () => <div />;',
+ 'export default Video;',
+ ].join('\n'),
+ },
+ };
+ const resolved = resolveCompositionComponentInProject({
+ compositionFile: './src/Root.tsx',
+ compositionId: 'Video',
+ project,
+ });
+
+ expect(resolved.exportName).toBe('default');
+ expect(resolved.filePath).toBe('./src/Video.tsx');
+ expect(resolved.canAddSequence).toBe(true);
});