Skip to content

🎥 Make videos programmatically with React

Studio: Add Pre-compose quick action with connected compositions

JonnyBurger5183c47ed2e5
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 7dfec9ae73..7d5330d061 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -17,6 +17,8 @@ import {
canWrapNode,
wrapNode as wrapNodeCodemod,
getNodeProps,
+ canPrecomposeJsxNodes,
+ precomposeJsxNodes as precomposeJsxNodesCodemod,
moveComposition,
moveFolder,
renameComposition,
@@ -1585,6 +1587,76 @@ export const createBrowserStudioOperations = ({
}
};
+ const precomposeJsxNodes: BrowserStudioOperations['precomposeJsxNodes'] = ({
+ nodes,
+ dryRun,
+ compositionFile,
+ compositionId,
+ metadata,
+ existingCompositionIds,
+ }) => {
+ try {
+ if (nodes.length === 0) {
+ throw new Error('No JSX sequences were selected');
+ }
+
+ const project = getProject();
+ const resolved = nodes.map(({fileName, nodePath}) => ({
+ filePath: findProjectFile({project, filePath: fileName}),
+ nodePath,
+ }));
+ const {filePath} = resolved[0];
+ if (resolved.some((node) => node.filePath !== filePath)) {
+ throw new Error('Selected sequences must be in the same source file');
+ }
+
+ const resolvedCompositionFile = findProjectFile({
+ project,
+ filePath: compositionFile,
+ });
+ const options = {
+ project,
+ nodes: resolved,
+ compositionFile: resolvedCompositionFile,
+ compositionId,
+ metadata,
+ existingCompositionIds,
+ };
+ const eligibility = canPrecomposeJsxNodes(options);
+ if (dryRun) {
+ return Promise.resolve({
+ success: true,
+ ...eligibility,
+ nodePathMutation: null,
+ });
+ }
+
+ if (!eligibility.canPrecompose) {
+ throw new Error(
+ eligibility.reason ?? 'Cannot pre-compose this selection',
+ );
+ }
+
+ const result = precomposeJsxNodesCodemod(options);
+ const nodePathMutation = controller.applyMutation({
+ undoRedoNavigation: null,
+ timelineSelection: null,
+ fileName: result.changes
+ .map(({filePath: changed}) => changed)
+ .join(', '),
+ mutate: (current) => applyCodemodChanges(current, result.changes),
+ nodePathMutationFiles: getNodePathMutationFiles(result),
+ });
+ if (nodePathMutation === null) {
+ throw new Error('Could not pre-compose selected sequences');
+ }
+
+ return Promise.resolve({success: true, ...eligibility, nodePathMutation});
+ } catch (error) {
+ return Promise.resolve(getStructuredError(error));
+ }
+ };
+
const splitJsxSequence: BrowserStudioOperations['splitJsxSequence'] = async ({
sequences,
}) => {
@@ -2292,6 +2364,7 @@ export const createBrowserStudioOperations = ({
duplicateComposition,
duplicateJsxNode,
wrapJsxNode,
+ precomposeJsxNodes,
effects: effectOperations,
emitEvent: controller.emitEvent,
findInFile: controller.findInFile,
diff --git a/packages/codemods/src/add-composition.ts b/packages/codemods/src/add-composition.ts
index c8f1e4e5e5..582bd287e4 100644
--- a/packages/codemods/src/add-composition.ts
+++ b/packages/codemods/src/add-composition.ts
@@ -22,7 +22,7 @@ import {
export type AddCompositionOptions<Project extends CodemodProject> =
CompositionTarget & {
project: Project;
- component: {importName: string; importPath: string};
+ component: {importName: string; importPath: string | null};
metadata: CompositionMetadata;
folder?: FolderReference;
};
@@ -46,6 +46,37 @@ export const addComposition = <Project extends CodemodProject>({
const filePath = findProjectFile({project, filePath: compositionFile});
const input = project.files[filePath];
const ast = parseAst(input);
+ if (
+ component.importPath === null &&
+ !ast.program.body.some((statement) => {
+ const declaration =
+ statement.type === 'ExportNamedDeclaration' ||
+ statement.type === 'ExportDefaultDeclaration'
+ ? statement.declaration
+ : statement;
+ if (
+ declaration?.type === 'FunctionDeclaration' ||
+ declaration?.type === 'ClassDeclaration'
+ ) {
+ return declaration.id?.name === component.importName;
+ }
+
+ return (
+ declaration?.type === 'VariableDeclaration' &&
+ declaration.declarations.some(
+ (item) =>
+ item.id.type === 'Identifier' &&
+ item.id.name === component.importName &&
+ item.init !== null,
+ )
+ );
+ })
+ ) {
+ throw new Error(
+ `Component "${component.importName}" is not declared in ${compositionFile}`,
+ );
+ }
+
const snapshots = captureImportSnapshots(ast);
const tag = ensureNamedImport({
ast,
@@ -53,12 +84,15 @@ export const addComposition = <Project extends CodemodProject>({
sourcePath: 'remotion',
localName: 'Composition',
});
- const componentName = ensureNamedImport({
- ast,
- importedName: component.importName,
- sourcePath: component.importPath,
- localName: component.importName,
- });
+ const componentName =
+ component.importPath === null
+ ? component.importName
+ : ensureNamedImport({
+ ast,
+ importedName: component.importName,
+ sourcePath: component.importPath,
+ localName: component.importName,
+ });
const b = recast.types.builders;
const insertion = b.jsxElement(
b.jsxOpeningElement(
diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.ts
index b5f84124b6..1fbcc96377 100644
--- a/packages/codemods/src/index.ts
+++ b/packages/codemods/src/index.ts
@@ -136,6 +136,10 @@ export type {
export {applyCodemodChanges} from './codemod-project';
export {deleteNodes, type DeleteNodesOptions} from './delete-nodes';
export {canWrapNode, wrapNode, type WrapNodeOptions} from './wrap-node';
+export {
+ canPrecomposeJsxNodes,
+ precomposeJsxNodes,
+} from './precompose-jsx-nodes';
export type {
EffectArrayElement,
EffectDeletionTarget,
diff --git a/packages/codemods/src/precompose-jsx-nodes.ts b/packages/codemods/src/precompose-jsx-nodes.ts
new file mode 100644
index 0000000000..c58cbc3530
--- /dev/null
+++ b/packages/codemods/src/precompose-jsx-nodes.ts
@@ -0,0 +1,1442 @@
+import {
+ isReferenced,
+ type File,
+ type JSXElement,
+ type JSXFragment,
+ type Node,
+} from '@babel/types';
+import * as recast from 'recast';
+import type {SequenceNodePath} from 'remotion';
+import {addComposition} from './add-composition';
+import type {CodemodProject} from './codemod-project';
+import {
+ assertNewCompositionId,
+ requireComposition,
+ validateMetadata,
+ type CompositionMetadata,
+} from './composition-editing';
+import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';
+import {
+ captureJsxNodePaths,
+ getNodePathRemappings,
+} from './get-node-path-remappings';
+import {getNodeProps} from './get-node-props';
+import {findProjectFile} from './internals';
+import {
+ getNodeEditResult,
+ type NodeReference,
+ type NodeSourceEdit,
+} from './node-references';
+import {recastLocToOffset} from './recast-loc-to-offset';
+import {ensureNamedImport, getImportedName} from './sequence-props/imports';
+import {parseAst} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+} from './source-edits';
+import {getEndOfLine, getIndentationUnit, getLineIndent} from './source-style';
+
+type PrecompositionPlan = {
+ ast: File;
+ children: JSXFragment['children'];
+ end: number;
+ firstIndex: number;
+ hookProps: {name: string; hookName: string; kind: 'frame' | 'duration'}[];
+ logLine: number;
+ parent: JSXElement | JSXFragment | null;
+ rootPath: recast.types.NodePath | null;
+ sequenceName: string | null;
+ selectedSequence: JSXElement | null;
+ sequenceDuration: number | null;
+ start: number;
+};
+
+const getPrecompositionPlan = ({
+ input,
+ nodePaths,
+}: {
+ input: string;
+ nodePaths: SequenceNodePath[];
+}): PrecompositionPlan => {
+ if (nodePaths.length === 0) {
+ throw new Error('Select at least one sequence to pre-compose');
+ }
+
+ const uniquePaths = new Set(nodePaths.map((path) => JSON.stringify(path)));
+ if (uniquePaths.size !== nodePaths.length) {
+ throw new Error('A sequence was selected more than once');
+ }
+
+ const ast = parseAst(input);
+ const selectedPaths = nodePaths.map((nodePath) => {
+ const path = findJsxElementPathForDeletion(ast, nodePath);
+ if (!path || !(path.node as JSXElement).loc) {
+ throw new Error('Could not identify every selected JSX sequence');
+ }
+
+ const element = path.node as JSXElement;
+ if (
+ element.openingElement.attributes.some(
+ (attribute) =>
+ attribute.type === 'JSXSpreadAttribute' ||
+ (attribute.name.type === 'JSXIdentifier' &&
+ attribute.name.name === 'key'),
+ )
+ ) {
+ throw new Error(
+ 'Sequences with a key or spread props cannot be pre-composed safely',
+ );
+ }
+
+ return path;
+ });
+ let expression = selectedPaths[0].node;
+ let enclosingPath = selectedPaths[0].parentPath;
+ while (
+ enclosingPath?.node.type === 'ParenthesizedExpression' &&
+ enclosingPath.node.expression === expression
+ ) {
+ expression = enclosingPath.node;
+ enclosingPath = enclosingPath.parentPath;
+ }
+
+ const enclosingNode = enclosingPath?.node;
+ const parent =
+ enclosingNode?.type === 'JSXElement' ||
+ enclosingNode?.type === 'JSXFragment'
+ ? enclosingNode
+ : null;
+ const rootPath = parent === null ? selectedPaths[0] : null;
+ const isSingleDirectReturn =
+ nodePaths.length === 1 &&
+ enclosingNode?.type === 'ReturnStatement' &&
+ enclosingNode.argument === expression;
+ const isSingleArrowBody =
+ nodePaths.length === 1 &&
+ enclosingNode?.type === 'ArrowFunctionExpression' &&
+ enclosingNode.body === expression;
+ if (
+ (parent === null && !isSingleDirectReturn && !isSingleArrowBody) ||
+ (parent !== null &&
+ selectedPaths.some((path) => path.parentPath?.node !== enclosingNode))
+ ) {
+ throw new Error('Selected sequences must have the same JSX parent');
+ }
+
+ if (parent === null) {
+ let functionPath = enclosingPath;
+ if (isSingleDirectReturn) {
+ functionPath = functionPath?.parentPath;
+ while (functionPath?.node.type === 'BlockStatement') {
+ functionPath = functionPath.parentPath;
+ }
+ }
+
+ const functionNode = functionPath?.node;
+ const isTopLevelFunction =
+ functionNode?.type === 'FunctionDeclaration' &&
+ ast.program.body.some(
+ (statement) =>
+ (statement === functionNode &&
+ Boolean(functionNode.id && /^[A-Z]/.test(functionNode.id.name))) ||
+ ((statement.type === 'ExportNamedDeclaration' ||
+ statement.type === 'ExportDefaultDeclaration') &&
+ statement.declaration === functionNode &&
+ (statement.type === 'ExportDefaultDeclaration' ||
+ Boolean(functionNode.id && /^[A-Z]/.test(functionNode.id.name)))),
+ );
+ const isTopLevelArrow =
+ functionNode?.type === 'ArrowFunctionExpression' &&
+ ast.program.body.some((statement) => {
+ if (
+ statement.type === 'ExportDefaultDeclaration' &&
+ statement.declaration === functionNode
+ ) {
+ return true;
+ }
+
+ const declaration =
+ statement.type === 'ExportNamedDeclaration'
+ ? statement.declaration
+ : statement;
+ return (
+ declaration?.type === 'VariableDeclaration' &&
+ declaration.kind === 'const' &&
+ declaration.declarations.some(
+ (item) =>
+ item.init === functionNode &&
+ item.id.type === 'Identifier' &&
+ /^[A-Z]/.test(item.id.name),
+ )
+ );
+ });
+ if (!isTopLevelFunction && !isTopLevelArrow) {
+ throw new Error('The sequence is not directly returned by a component');
+ }
+ }
+
+ const transparentNamedParents = new Set<string>();
+ const remotionNamespaces = new Set<string>();
+ const remotionImports = new Map<string, string>();
+ const transitionNamespaces = new Set<string>();
+ const transitionSeriesNames = new Set<string>();
+ const transitionSeriesMembers = new Set([
+ 'Overlay',
+ 'Sequence',
+ 'Transition',
+ ]);
+ const staticFileNames = new Set<string>();
+ const importedNames = new Set<string>();
+ const stablePrimitiveNames = new Set<string>();
+ const stableComponentNames = new Set<string>();
+ for (const statement of ast.program.body) {
+ const valueDeclaration =
+ statement.type === 'ExportNamedDeclaration' ||
+ statement.type === 'ExportDefaultDeclaration'
+ ? statement.declaration
+ : statement;
+ if (
+ valueDeclaration?.type === 'FunctionDeclaration' &&
+ valueDeclaration.id
+ ) {
+ stableComponentNames.add(valueDeclaration.id.name);
+ }
+
+ if (
+ valueDeclaration?.type === 'VariableDeclaration' &&
+ valueDeclaration.kind === 'const'
+ ) {
+ for (const declaration of valueDeclaration.declarations) {
+ if (declaration.id.type !== 'Identifier' || !declaration.init) {
+ continue;
+ }
+
+ stableComponentNames.add(declaration.id.name);
+ if (
+ [
+ 'StringLiteral',
+ 'NumericLiteral',
+ 'BooleanLiteral',
+ 'NullLiteral',
+ 'BigIntLiteral',
+ ].includes(declaration.init.type) ||
+ (declaration.init.type === 'UnaryExpression' &&
+ declaration.init.operator === '-' &&
+ declaration.init.argument.type === 'NumericLiteral')
+ ) {
+ stablePrimitiveNames.add(declaration.id.name);
+ }
+ }
+ }
+
+ if (
+ statement.type === 'ImportDeclaration' &&
+ statement.importKind !== 'type'
+ ) {
+ for (const specifier of statement.specifiers ?? []) {
+ if (
+ specifier.type !== 'ImportSpecifier' ||
+ specifier.importKind !== 'type'
+ ) {
+ importedNames.add(specifier.local.name);
+ }
+
+ if (statement.source.value === '@remotion/transitions') {
+ if (specifier.type === 'ImportNamespaceSpecifier') {
+ transitionNamespaces.add(specifier.local.name);
+ } else if (
+ specifier.type === 'ImportSpecifier' &&
+ specifier.importKind !== 'type' &&
+ getImportedName(specifier) === 'TransitionSeries'
+ ) {
+ transitionSeriesNames.add(specifier.local.name);
+ }
+ }
+ }
+ }
+
+ if (
+ statement.type !== 'ImportDeclaration' ||
+ statement.source.value !== 'remotion' ||
+ statement.importKind === 'type'
+ ) {
+ continue;
+ }
+
+ for (const specifier of statement.specifiers ?? []) {
+ if (specifier.type === 'ImportNamespaceSpecifier') {
+ remotionNamespaces.add(specifier.local.name);
+ } else if (
+ specifier.type === 'ImportSpecifier' &&
+ specifier.importKind !== 'type'
+ ) {
+ const imported = getImportedName(specifier);
+ remotionImports.set(specifier.local.name, imported);
+ if (imported === 'Sequence' || imported === 'AbsoluteFill') {
+ transparentNamedParents.add(specifier.local?.name ?? imported);
+ }
+
+ if (imported === 'staticFile') {
+ staticFileNames.add(specifier.local?.name ?? imported);
+ }
+ }
+ }
+ }
+
+ const sequenceBinding = [...remotionImports].find(
+ ([, imported]) => imported === 'Sequence',
+ )?.[0];
+ if (
+ sequenceBinding &&
+ selectedPaths.some(
+ (path) => path.scope.lookup(sequenceBinding)?.path.node !== ast.program,
+ )
+ ) {
+ throw new Error('The Remotion Sequence import is shadowed');
+ }
+
+ let ancestor = selectedPaths[0].parentPath;
+ let foundTransparentParent = false;
+ let foundReturn = false;
+ while (ancestor) {
+ const ancestorNode = ancestor.node;
+ if (ancestorNode.type === 'JSXElement') {
+ const {name} = ancestorNode.openingElement;
+ const transparent =
+ (name.type === 'JSXIdentifier' &&
+ (/^[a-z]/.test(name.name) ||
+ (transparentNamedParents.has(name.name) &&
+ ancestor.scope.lookup(name.name)?.path.node === ast.program))) ||
+ (name.type === 'JSXMemberExpression' &&
+ name.object.type === 'JSXIdentifier' &&
+ remotionNamespaces.has(name.object.name) &&
+ ancestor.scope.lookup(name.object.name)?.path.node === ast.program &&
+ (name.property.name === 'Sequence' ||
+ name.property.name === 'AbsoluteFill'));
+ if (!transparent) {
+ throw new Error('The JSX parent may depend on its direct children');
+ }
+
+ foundTransparentParent = true;
+ break;
+ }
+
+ if (
+ ancestorNode.type === 'ReturnStatement' ||
+ ancestorNode.type === 'ArrowFunctionExpression'
+ ) {
+ foundReturn = true;
+ } else if (
+ foundReturn &&
+ ancestorNode.type !== 'BlockStatement' &&
+ ancestorNode.type !== 'FunctionDeclaration' &&
+ ancestorNode.type !== 'VariableDeclarator' &&
+ ancestorNode.type !== 'VariableDeclaration' &&
+ ancestorNode.type !== 'ExportNamedDeclaration' &&
+ ancestorNode.type !== 'ExportDefaultDeclaration' &&
+ ancestorNode.type !== 'Program' &&
+ ancestorNode.type !== 'File'
+ ) {
+ throw new Error('The JSX fragment is not directly returned or rendered');
+ } else if (
+ !foundReturn &&
+ ancestorNode.type !== 'JSXFragment' &&
+ ancestorNode.type !== 'JSXExpressionContainer' &&
+ ancestorNode.type !== 'ParenthesizedExpression'
+ ) {
+ throw new Error('The JSX fragment is not directly returned or rendered');
+ }
+
+ ancestor = ancestor.parentPath;
+ }
+
+ if (!foundTransparentParent && !foundReturn) {
+ throw new Error('The JSX fragment is not directly returned or rendered');
+ }
+
+ let firstIndex = 0;
+ let children: JSXFragment['children'] = [selectedPaths[0].node as JSXElement];
+ if (parent !== null) {
+ const indices = selectedPaths
+ .map((path) => parent.children.indexOf(path.node as JSXElement))
+ .sort((a, b) => a - b);
+ if (indices.some((index) => index === -1)) {
+ throw new Error('Selected sequences must be direct JSX children');
+ }
+
+ firstIndex = indices[0];
+ const lastIndex = indices[indices.length - 1];
+ const selectedNodes = new Set(selectedPaths.map((path) => path.node));
+ if (selectedNodes.size !== selectedPaths.length) {
+ throw new Error('A sequence was selected more than once');
+ }
+
+ for (let index = firstIndex; index <= lastIndex; index++) {
+ const child = parent.children[index];
+ if (child.type === 'JSXElement' && selectedNodes.has(child)) {
+ continue;
+ }
+
+ if (
+ child.type === 'JSXText' &&
+ child.value.trim() === '' &&
+ /\r?\n/.test(child.value)
+ ) {
+ continue;
+ }
+
+ throw new Error('Selected sequences must be contiguous JSX siblings');
+ }
+
+ children = parent.children.slice(firstIndex, lastIndex + 1);
+ }
+
+ let unsafeReason: string | null = null;
+ // Captured hook values are passed from the original render. The extracted
+ // component falls back to its own hooks when opened as a composition.
+ const hookProps = new Map<
+ string,
+ {name: string; hookName: string; kind: 'frame' | 'duration'}
+ >();
+ const easingMethods = new Set([
+ 'back',
+ 'bezier',
+ 'bounce',
+ 'circle',
+ 'cubic',
+ 'ease',
+ 'elastic',
+ 'exp',
+ 'in',
+ 'inOut',
+ 'linear',
+ 'out',
+ 'poly',
+ 'quad',
+ 'sin',
+ 'spring',
+ 'step0',
+ 'step1',
+ ]);
+ for (const path of selectedPaths) {
+ recast.visit(path as unknown as Parameters<typeof recast.visit>[0], {
+ visitIdentifier(p) {
+ if (
+ isReferenced(
+ p.node as Node,
+ p.parentPath.node as Node,
+ p.parentPath.parentPath?.node as Node | undefined,
+ )
+ ) {
+ const binding = p.scope.lookup(p.node.name);
+ const remotionImport =
+ binding?.path.node === ast.program
+ ? remotionImports.get(p.node.name)
+ : undefined;
+ const isInterpolating =
+ remotionImport === 'interpolate' &&
+ p.parentPath.node.type === 'CallExpression' &&
+ p.parentPath.node.callee === p.node;
+ const isEasingMember =
+ remotionImport === 'Easing' &&
+ p.parentPath.node.type === 'MemberExpression' &&
+ p.parentPath.node.object === p.node &&
+ !p.parentPath.node.computed &&
+ p.parentPath.node.property.type === 'Identifier' &&
+ easingMethods.has(p.parentPath.node.property.name);
+ const isStaticFileCallee =
+ staticFileNames.has(p.node.name) &&
+ p.parentPath.node.type === 'CallExpression' &&
+ p.parentPath.node.callee === p.node;
+ const isStaticFileNamespace =
+ remotionNamespaces.has(p.node.name) &&
+ p.parentPath.node.type === 'MemberExpression' &&
+ p.parentPath.node.object === p.node &&
+ !p.parentPath.node.computed &&
+ p.parentPath.node.property.type === 'Identifier' &&
+ p.parentPath.node.property.name === 'staticFile';
+ let hookProp: {
+ name: string;
+ hookName: string;
+ kind: 'frame' | 'duration';
+ } | null = null;
+ const functionNode = binding?.path.node as Node | undefined;
+ if (
+ p.node.name !== 'key' &&
+ p.node.name !== 'ref' &&
+ functionNode &&
+ (functionNode.type === 'FunctionDeclaration' ||
+ functionNode.type === 'FunctionExpression' ||
+ functionNode.type === 'ArrowFunctionExpression') &&
+ functionNode.body.type === 'BlockStatement'
+ ) {
+ functionNode.body.body.some(
+ (statement) =>
+ statement.type === 'VariableDeclaration' &&
+ statement.kind === 'const' &&
+ statement.declarations.some((declaration) => {
+ const {init} = declaration;
+ if (
+ init?.type !== 'CallExpression' ||
+ init.callee.type !== 'Identifier' ||
+ init.arguments.length !== 0 ||
+ p.scope.lookup(init.callee.name)?.path.node !== ast.program
+ ) {
+ return false;
+ }
+
+ const hook = remotionImports.get(init.callee.name);
+ if (hook === 'useCurrentFrame') {
+ const isMatchingFrame =
+ declaration.id.type === 'Identifier' &&
+ declaration.id.name === p.node.name;
+ if (isMatchingFrame) {
+ hookProp = {
+ name: p.node.name,
+ hookName: init.callee.name,
+ kind: 'frame',
+ };
+ }
+
+ return isMatchingFrame;
+ }
+
+ if (
+ hook !== 'useVideoConfig' ||
+ declaration.id.type !== 'ObjectPattern'
+ ) {
+ return false;
+ }
+
+ const matches = declaration.id.properties.some(
+ (property) =>
+ property.type === 'ObjectProperty' &&
+ !property.computed &&
+ property.key.type === 'Identifier' &&
+ property.key.name === 'durationInFrames' &&
+ property.value.type === 'Identifier' &&
+ property.value.name === p.node.name,
+ );
+ if (matches) {
+ hookProp = {
+ name: p.node.name,
+ hookName: init.callee.name,
+ kind: 'duration',
+ };
+ }
+
+ return matches;
+ }),
+ );
+ }
+
+ if (hookProp !== null) {
+ hookProps.set(p.node.name, hookProp);
+ }
+
+ if (
+ !(
+ binding?.path.node === ast.program &&
+ (stablePrimitiveNames.has(p.node.name) ||
+ isStaticFileCallee ||
+ isStaticFileNamespace ||
+ isInterpolating ||
+ isEasingMember)
+ ) &&
+ !hookProp &&
+ !(
+ binding === undefined &&
+ ['undefined', 'Infinity', 'NaN'].includes(p.node.name)
+ )
+ ) {
+ unsafeReason = `The selected JSX reads ${p.node.name} from an unstable scope`;
+ }
+ }
+
+ this.traverse(p);
+ },
+ visitJSXIdentifier(p) {
+ if (
+ isReferenced(
+ p.node as Node,
+ p.parentPath.node as Node,
+ p.parentPath.parentPath?.node as Node | undefined,
+ ) &&
+ !/^[a-z]/.test(p.node.name)
+ ) {
+ const isSimpleTag =
+ p.parentPath.node.type === 'JSXOpeningElement' ||
+ p.parentPath.node.type === 'JSXClosingElement';
+ const memberNames: string[] = [];
+ let memberNode: Node = p.node as Node;
+ let memberPath = p.parentPath;
+ while (
+ memberPath?.node.type === 'JSXMemberExpression' &&
+ memberPath.node.object === memberNode
+ ) {
+ memberNames.push(memberPath.node.property.name);
+ memberNode = memberPath.node as Node;
+ memberPath = memberPath.parentPath;
+ }
+
+ const isMemberTag =
+ memberNames.length > 0 &&
+ (memberPath?.node.type === 'JSXOpeningElement' ||
+ memberPath?.node.type === 'JSXClosingElement') &&
+ memberPath.node.name === memberNode;
+ const remotionImport = remotionImports.get(p.node.name);
+ const isNamedRemotionMember =
+ memberNames.length === 1 &&
+ ((remotionImport === 'Interactive' &&
+ /^[A-Z]/.test(memberNames[0])) ||
+ (remotionImport === 'Series' && memberNames[0] === 'Sequence'));
+ const isNamedTransitionMember =
+ transitionSeriesNames.has(p.node.name) &&
+ memberNames.length === 1 &&
+ transitionSeriesMembers.has(memberNames[0]);
+ const isRemotionNamespaceMember =
+ remotionNamespaces.has(p.node.name) &&
+ (memberNames.length === 1 ||
+ (memberNames.length === 2 &&
+ ((memberNames[0] === 'Interactive' &&
+ /^[A-Z]/.test(memberNames[1])) ||
+ (memberNames[0] === 'Series' &&
+ memberNames[1] === 'Sequence'))));
+ const isTransitionNamespaceMember =
+ transitionNamespaces.has(p.node.name) &&
+ memberNames[0] === 'TransitionSeries' &&
+ (memberNames.length === 1 ||
+ (memberNames.length === 2 &&
+ transitionSeriesMembers.has(memberNames[1])));
+ const isKnownMemberTag =
+ isMemberTag &&
+ (isNamedRemotionMember ||
+ isNamedTransitionMember ||
+ isRemotionNamespaceMember ||
+ isTransitionNamespaceMember);
+ if (
+ p.scope.lookup(p.node.name)?.path.node !== ast.program ||
+ (!(
+ isSimpleTag &&
+ (importedNames.has(p.node.name) ||
+ stableComponentNames.has(p.node.name))
+ ) &&
+ !isKnownMemberTag)
+ ) {
+ unsafeReason = `The selected JSX uses ${p.node.name} from an unstable scope`;
+ }
+ }
+
+ this.traverse(p);
+ },
+ visitJSXNamespacedName() {
+ unsafeReason = 'Namespaced JSX cannot be pre-composed safely';
+ return false;
+ },
+ visitThisExpression() {
+ unsafeReason = 'JSX using this cannot be pre-composed safely';
+ return false;
+ },
+ visitSuper() {
+ unsafeReason = 'JSX using super cannot be pre-composed safely';
+ return false;
+ },
+ visitMetaProperty() {
+ unsafeReason =
+ 'JSX using meta properties cannot be pre-composed safely';
+ return false;
+ },
+ visitAwaitExpression() {
+ unsafeReason = 'JSX using await cannot be pre-composed safely';
+ return false;
+ },
+ visitYieldExpression() {
+ unsafeReason = 'JSX using yield cannot be pre-composed safely';
+ return false;
+ },
+ visitCallExpression(p) {
+ const {callee, arguments: args} = p.node;
+ const isNamedInterpolate =
+ callee.type === 'Identifier' &&
+ remotionImports.get(callee.name) === 'interpolate' &&
+ p.scope.lookup(callee.name)?.path.node === ast.program;
+ const isEasingMethod =
+ callee.type === 'MemberExpression' &&
+ !callee.computed &&
+ callee.object.type === 'Identifier' &&
+ callee.property.type === 'Identifier' &&
+ easingMethods.has(callee.property.name) &&
+ remotionImports.get(callee.object.name) === 'Easing' &&
+ p.scope.lookup(callee.object.name)?.path.node === ast.program;
+ const isNamedStaticFile =
+ callee.type === 'Identifier' &&
+ staticFileNames.has(callee.name) &&
+ p.scope.lookup(callee.name)?.path.node === ast.program;
+ const isNamespacedStaticFile =
+ callee.type === 'MemberExpression' &&
+ !callee.computed &&
+ callee.object.type === 'Identifier' &&
+ callee.property.type === 'Identifier' &&
+ callee.property.name === 'staticFile' &&
+ remotionNamespaces.has(callee.object.name) &&
+ p.scope.lookup(callee.object.name)?.path.node === ast.program;
+ const isSafeStaticFile =
+ (isNamedStaticFile || isNamespacedStaticFile) &&
+ args.length === 1 &&
+ args[0].type === 'StringLiteral';
+ if (!isSafeStaticFile && !isNamedInterpolate && !isEasingMethod) {
+ unsafeReason =
+ 'The selected JSX contains a call that may change behavior';
+ }
+
+ this.traverse(p);
+ },
+ visitOptionalCallExpression() {
+ unsafeReason =
+ 'The selected JSX contains a call that may change behavior';
+ return false;
+ },
+ visitNewExpression() {
+ unsafeReason = 'The selected JSX contains a constructor call';
+ return false;
+ },
+ visitAssignmentExpression() {
+ unsafeReason = 'The selected JSX contains an assignment';
+ return false;
+ },
+ visitUpdateExpression() {
+ unsafeReason = 'The selected JSX contains an update expression';
+ return false;
+ },
+ visitTaggedTemplateExpression() {
+ unsafeReason = 'The selected JSX contains a tagged template';
+ return false;
+ },
+ visitArrowFunctionExpression() {
+ unsafeReason = 'The selected JSX contains a function';
+ return false;
+ },
+ visitFunctionExpression() {
+ unsafeReason = 'The selected JSX contains a function';
+ return false;
+ },
+ visitObjectMethod() {
+ unsafeReason = 'The selected JSX contains a function';
+ return false;
+ },
+ visitClassExpression() {
+ unsafeReason = 'The selected JSX contains a class';
+ return false;
+ },
+ visitTemplateLiteral(p) {
+ if (p.node.loc?.start.line !== p.node.loc?.end.line) {
+ unsafeReason = 'The selected JSX contains a multiline template';
+ }
+
+ this.traverse(p);
+ },
+ visitStringLiteral(p) {
+ if (p.node.loc?.start.line !== p.node.loc?.end.line) {
+ unsafeReason = 'The selected JSX contains a multiline string';
+ }
+
+ this.traverse(p);
+ },
+ visitJSXText(p) {
+ if (
+ p.node.loc?.start.line !== p.node.loc?.end.line &&
+ p.node.value.split(/\r?\n/).filter((line) => line.trim().length > 0)
+ .length > 1
+ ) {
+ unsafeReason = 'The selected JSX contains multiline text';
+ }
+
+ this.traverse(p);
+ },
+ });
+ }
+
+ if (unsafeReason !== null) {
+ throw new Error(unsafeReason);
+ }
+
+ if (
+ hookProps.size > 0 &&
+ [...hookProps.values()].some((prop) => prop.kind === 'frame')
+ ) {
+ let frameAncestor = selectedPaths[0].parentPath;
+ while (frameAncestor) {
+ if (frameAncestor.node.type === 'JSXElement') {
+ const {name} = frameAncestor.node.openingElement;
+ const isSequence =
+ (name.type === 'JSXIdentifier' &&
+ (remotionImports.get(name.name) === 'Sequence' ||
+ name.name === 'Sequence')) ||
+ (name.type === 'JSXMemberExpression' &&
+ name.property.name === 'Sequence');
+ if (isSequence) {
+ throw new Error(
+ 'The selected markup captures a frame outside its sequence',
+ );
+ }
+ }
+
+ frameAncestor = frameAncestor.parentPath;
+ }
+ }
+
+ const selectedElement = selectedPaths[0].node as JSXElement;
+ const selectedTag = selectedElement.openingElement.name;
+ const selectedSequence =
+ nodePaths.length === 1 &&
+ selectedTag.type === 'JSXIdentifier' &&
+ remotionImports.get(selectedTag.name) === 'Sequence'
+ ? selectedElement
+ : null;
+ let sequenceDuration: number | null = null;
+ if (selectedSequence) {
+ if (
+ !selectedSequence.closingElement?.loc ||
+ selectedSequence.children.length === 0 ||
+ selectedSequence.children.some(
+ (child) => child.type === 'JSXText' && child.value.trim() !== '',
+ )
+ ) {
+ throw new Error('The selected sequence has no extractable JSX children');
+ }
+
+ let hasDuration = false;
+ let hasNonzeroFrom = false;
+ for (const attribute of selectedSequence.openingElement.attributes) {
+ if (
+ attribute.type !== 'JSXAttribute' ||
+ attribute.name.type !== 'JSXIdentifier'
+ ) {
+ throw new Error('The selected sequence has unsupported props');
+ }
+
+ const key = attribute.name.name;
+ if (!['name', 'from', 'durationInFrames', 'layout'].includes(key)) {
+ throw new Error('The selected sequence has unsupported props');
+ }
+
+ if (key !== 'from' && key !== 'durationInFrames') {
+ continue;
+ }
+
+ const value =
+ attribute.value?.type === 'JSXExpressionContainer' &&
+ attribute.value.expression.type === 'NumericLiteral'
+ ? attribute.value.expression.value
+ : null;
+ if (value === null || !Number.isInteger(value) || value < 0) {
+ throw new Error('The selected sequence timing is not static');
+ }
+
+ if (key === 'from') {
+ hasNonzeroFrom = value !== 0;
+ } else {
+ if (value === 0) {
+ throw new Error('The selected sequence has no duration');
+ }
+
+ hasDuration = true;
+ sequenceDuration = value;
+ }
+ }
+
+ if (!hasDuration && hasNonzeroFrom) {
+ throw new Error('The selected sequence duration is not explicit');
+ }
+
+ if (
+ hasNonzeroFrom &&
+ [...hookProps.values()].some((prop) => prop.kind === 'frame')
+ ) {
+ throw new Error(
+ 'The selected sequence captures a frame before its start',
+ );
+ }
+
+ children = [...selectedSequence.children];
+ }
+
+ const first = children[0];
+ const last = children[children.length - 1];
+ if (!selectedSequence && (!first.loc || !last.loc)) {
+ throw new Error('Could not locate every selected JSX sequence');
+ }
+
+ const sequenceStart = selectedSequence?.openingElement.loc?.end;
+ const sequenceEnd = selectedSequence?.closingElement?.loc?.start;
+ if (selectedSequence && (!sequenceStart || !sequenceEnd)) {
+ throw new Error('Could not locate the selected sequence contents');
+ }
+
+ return {
+ ast,
+ children,
+ end: recastLocToOffset(input, sequenceEnd ?? last.loc!.end),
+ firstIndex,
+ hookProps: [...hookProps.values()].sort((left, right) =>
+ left.name.localeCompare(right.name),
+ ),
+ logLine: selectedSequence?.loc?.start.line ?? first.loc!.start.line,
+ parent,
+ rootPath,
+ selectedSequence,
+ sequenceDuration,
+ sequenceName:
+ nodePaths.length === 1
+ ? ((
+ selectedPaths[0].node as JSXElement
+ ).openingElement.attributes.flatMap((attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ attribute.name.name === 'name' &&
+ attribute.value?.type === 'StringLiteral'
+ ? [attribute.value.value]
+ : [],
+ )[0] ?? null)
+ : null,
+ start: recastLocToOffset(input, sequenceStart ?? first.loc!.start),
+ };
+};
+
+type PrecomposeOptions<Project extends CodemodProject> = {
+ project: Project;
+ nodes: NodeReference[];
+ compositionFile: string;
+ compositionId: string;
+ metadata: CompositionMetadata;
+ existingCompositionIds: string[];
+};
+
+const getRegistrationPathChanges = ({
+ before,
+ after,
+ compositionId,
+}: {
+ before: string;
+ after: string;
+ compositionId: string;
+}) => {
+ const original = captureJsxNodePaths(parseAst(before));
+ const updated = captureJsxNodePaths(parseAst(after));
+ const inserted = updated.filter(({node: {attributes}}) => {
+ return (
+ attributes.some(
+ (attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ attribute.name.name === 'id' &&
+ attribute.value?.type === 'StringLiteral' &&
+ attribute.value.value === compositionId,
+ ) &&
+ attributes.some(
+ (attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ attribute.name.name === 'component',
+ )
+ );
+ });
+ if (inserted.length !== 1 || updated.length !== original.length + 1) {
+ throw new Error('Could not track the new composition registration');
+ }
+
+ const preserved = updated.filter((entry) => entry !== inserted[0]);
+ const byOriginalPath = new Map<string, SequenceNodePath>();
+ for (let index = 0; index < original.length; index++) {
+ if (original[index].signature !== preserved[index].signature) {
+ throw new Error('Composition registration changed unrelated JSX');
+ }
+
+ byOriginalPath.set(
+ JSON.stringify(original[index].nodePath),
+ preserved[index].nodePath,
+ );
+ }
+
+ return {original, byOriginalPath, insertedPath: inserted[0].nodePath};
+};
+
+export const precomposeJsxNodes = <Project extends CodemodProject>({
+ project,
+ nodes,
+ compositionFile,
+ compositionId,
+ metadata,
+ existingCompositionIds,
+}: PrecomposeOptions<Project>) => {
+ if (nodes.length === 0) {
+ throw new Error('Select at least one sequence to pre-compose');
+ }
+
+ validateMetadata(metadata);
+ const filePath = findProjectFile({project, filePath: nodes[0].filePath});
+ const registrationFile = findProjectFile({
+ project,
+ filePath: compositionFile,
+ });
+ if (
+ nodes.some(
+ (node) =>
+ findProjectFile({project, filePath: node.filePath}) !== filePath,
+ )
+ ) {
+ throw new Error('Selected sequences must be in one source file');
+ }
+
+ const parentComposition = requireComposition({
+ project,
+ compositionFile: registrationFile,
+ compositionId,
+ });
+ const parentMetadata = getNodeProps({
+ project,
+ node: parentComposition,
+ keys: ['width', 'height', 'fps', 'durationInFrames'],
+ }).props;
+ for (const key of ['width', 'height', 'fps', 'durationInFrames'] as const) {
+ const value = parentMetadata[key];
+ if (value.status !== 'static' || value.codeValue !== metadata[key]) {
+ throw new Error('The parent composition metadata is not static');
+ }
+ }
+
+ const input = project.files[filePath];
+ const {
+ ast,
+ children,
+ end,
+ firstIndex,
+ hookProps,
+ logLine,
+ parent,
+ rootPath,
+ sequenceName,
+ selectedSequence,
+ sequenceDuration,
+ start,
+ } = getPrecompositionPlan({
+ input,
+ nodePaths: nodes.map((node) => node.nodePath),
+ });
+ if (
+ sequenceDuration !== null &&
+ sequenceDuration !== metadata.durationInFrames
+ ) {
+ throw new Error('The selected sequence uses a different video duration');
+ }
+
+ const captured = captureJsxNodePaths(ast);
+ const registrationAst =
+ registrationFile === filePath
+ ? ast
+ : parseAst(project.files[registrationFile]);
+ const occupiedNames = new Set<string>();
+ for (const candidateAst of new Set([ast, registrationAst])) {
+ recast.visit(candidateAst, {
+ visitIdentifier(path) {
+ occupiedNames.add(path.node.name);
+ this.traverse(path);
+ },
+ visitJSXIdentifier(path) {
+ occupiedNames.add(path.node.name);
+ this.traverse(path);
+ },
+ });
+ }
+
+ const labelWords = sequenceName?.match(/[A-Za-z][A-Za-z0-9]*/g) ?? [];
+ const baseName =
+ labelWords.length === 0
+ ? 'Precomposition'
+ : labelWords
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join('');
+ const knownIds = new Set(existingCompositionIds);
+ let name: string | null = null;
+ for (let suffix = 1; suffix < 10000; suffix++) {
+ const candidate = `${baseName}${suffix === 1 ? '' : suffix}`;
+ if (occupiedNames.has(candidate) || knownIds.has(candidate)) {
+ continue;
+ }
+
+ try {
+ assertNewCompositionId({
+ project,
+ compositionFile: registrationFile,
+ compositionId: candidate,
+ });
+ name = candidate;
+ break;
+ } catch (error) {
+ if (!(error as Error).message.includes('already exists')) {
+ throw error;
+ }
+ }
+ }
+
+ if (name === null) {
+ throw new Error('Could not choose a unique composition name');
+ }
+
+ const resolvedHookProps = hookProps.map((prop) => {
+ const suffix = prop.name.charAt(0).toUpperCase() + prop.name.slice(1);
+ let parentAlias = `precomposeParent${suffix}`;
+ for (let index = 2; occupiedNames.has(parentAlias); index++) {
+ parentAlias = `precomposeParent${suffix}${index}`;
+ }
+
+ occupiedNames.add(parentAlias);
+ let standaloneAlias = `precomposeStandalone${suffix}`;
+ for (let index = 2; occupiedNames.has(standaloneAlias); index++) {
+ standaloneAlias = `precomposeStandalone${suffix}${index}`;
+ }
+
+ occupiedNames.add(standaloneAlias);
+ return {...prop, parentAlias, standaloneAlias};
+ });
+ const destructuredProps = resolvedHookProps
+ .map(({name: propName, parentAlias}) => `${propName}: ${parentAlias}`)
+ .join(', ');
+ const typedProps = resolvedHookProps
+ .map(({name: propName}) => `${propName}?: number | null`)
+ .join('; ');
+ const parameters =
+ resolvedHookProps.length === 0
+ ? ''
+ : `{${destructuredProps}}${filePath.endsWith('.tsx') ? `: {${typedProps}}` : ''}`;
+ const signature = `export function ${name}(${parameters}) {`;
+ const hookStatements = resolvedHookProps.flatMap(
+ ({name: propName, parentAlias, standaloneAlias, hookName, kind}) => [
+ kind === 'frame'
+ ? `const ${standaloneAlias} = ${hookName}();`
+ : `const ${standaloneAlias} = ${metadata.durationInFrames};`,
+ `const ${propName} = ${parentAlias} ?? ${standaloneAlias};`,
+ ],
+ );
+
+ const snapshots = captureImportSnapshots(ast);
+ const sequenceImport = [...ast.program.body]
+ .filter((statement) => statement.type === 'ImportDeclaration')
+ .flatMap((statement) =>
+ statement.source.value === 'remotion' && statement.importKind !== 'type'
+ ? (statement.specifiers ?? []).flatMap((specifier) =>
+ specifier.type === 'ImportSpecifier' &&
+ specifier.importKind !== 'type' &&
+ getImportedName(specifier) === 'Sequence'
+ ? [specifier.local.name]
+ : [],
+ )
+ : [],
+ )[0];
+ let sequenceLocalName = sequenceImport;
+ if (!sequenceLocalName) {
+ sequenceLocalName = 'Sequence';
+ for (let suffix = 2; occupiedNames.has(sequenceLocalName); suffix++) {
+ sequenceLocalName = `RemotionSequence${suffix}`;
+ }
+ }
+
+ const sequenceTag = ensureNamedImport({
+ ast,
+ importedName: 'Sequence',
+ sourcePath: 'remotion',
+ localName: sequenceLocalName,
+ });
+ const endOfLine = getEndOfLine(input);
+ const unit = getIndentationUnit(input, null);
+ const originalIndent = getLineIndent({input, offset: start});
+ const wrapperName = sequenceName ?? name;
+ const childSource = `<${name}${resolvedHookProps.map(({name: propName}) => ` ${propName}={${propName}}`).join('')} />`;
+ const replacementSource = selectedSequence
+ ? `${endOfLine}${originalIndent}${unit}${childSource}${endOfLine}${originalIndent}`
+ : [
+ `<${sequenceTag} layout="none" name={${JSON.stringify(wrapperName)}}>`,
+ `${originalIndent}${unit}${childSource}`,
+ `${originalIndent}</${sequenceTag}>`,
+ ].join(endOfLine);
+ const replacementStatement = parseAst(
+ selectedSequence
+ ? `const replacement = ${childSource};`
+ : `const replacement = <${sequenceTag} layout="none" name={${JSON.stringify(wrapperName)}}>${childSource}</${sequenceTag}>;`,
+ ).program.body[0];
+ if (replacementStatement.type !== 'VariableDeclaration') {
+ throw new Error('Could not create the pre-composed JSX');
+ }
+
+ const replacement = replacementStatement.declarations[0].init;
+ if (replacement?.type !== 'JSXElement') {
+ throw new Error('Could not create the pre-composed JSX');
+ }
+
+ const declarationStatement = parseAst(
+ `${signature} ${hookStatements.join(' ')} return <></>; }`,
+ ).program.body[0];
+ if (
+ declarationStatement.type !== 'ExportNamedDeclaration' ||
+ declarationStatement.declaration?.type !== 'FunctionDeclaration'
+ ) {
+ throw new Error('Could not create the pre-composed component');
+ }
+
+ const {declaration} = declarationStatement;
+ const returnStatement = declaration.body.body.at(-1);
+ if (
+ returnStatement?.type !== 'ReturnStatement' ||
+ returnStatement.argument?.type !== 'JSXFragment'
+ ) {
+ throw new Error('Could not create the pre-composed fragment');
+ }
+
+ returnStatement.argument.children = children;
+ if (selectedSequence) {
+ selectedSequence.children = [replacement];
+ } else if (parent === null) {
+ if (!rootPath) {
+ throw new Error('Could not replace the selected sequence');
+ }
+
+ rootPath.replace(replacement);
+ } else {
+ parent.children.splice(firstIndex, children.length, replacement);
+ }
+
+ ast.program.body.push(declarationStatement);
+ const source = input.slice(start, end);
+ const sourceLines = source.split(/\r?\n/);
+ if (selectedSequence) {
+ while (sourceLines[0]?.trim() === '') {
+ sourceLines.shift();
+ }
+
+ while (sourceLines.at(-1)?.trim() === '') {
+ sourceLines.pop();
+ }
+ }
+
+ const movedIndent = selectedSequence
+ ? (sourceLines[0]?.match(/^[\t ]*/)?.[0] ?? '')
+ : originalIndent;
+ const movedSource = sourceLines
+ .map((line, index) => {
+ const withoutOriginalIndent =
+ index === 0 && !selectedSequence
+ ? line
+ : line.startsWith(movedIndent)
+ ? line.slice(movedIndent.length)
+ : line.trimStart();
+ return withoutOriginalIndent.length === 0
+ ? ''
+ : `${unit}${unit}${unit}${withoutOriginalIndent}`;
+ })
+ .join(endOfLine);
+ const componentSignature =
+ signature.length <= 80 || resolvedHookProps.length === 0
+ ? signature
+ : filePath.endsWith('.tsx')
+ ? [
+ `export function ${name}({`,
+ ...resolvedHookProps.map(
+ ({name: propName, parentAlias}) =>
+ `${unit}${propName}: ${parentAlias},`,
+ ),
+ `}: {`,
+ ...resolvedHookProps.map(
+ ({name: propName}) => `${unit}${propName}?: number | null;`,
+ ),
+ '}) {',
+ ].join(endOfLine)
+ : [
+ `export function ${name}({`,
+ ...resolvedHookProps.map(
+ ({name: propName, parentAlias}) =>
+ `${unit}${propName}: ${parentAlias},`,
+ ),
+ '}) {',
+ ].join(endOfLine);
+ const component = [
+ ...(resolvedHookProps.length > 0 && !filePath.endsWith('.tsx')
+ ? [
+ `/** @param {{${resolvedHookProps.map(({name: propName}) => `${propName}?: number | null`).join(', ')}}} props */`,
+ ]
+ : []),
+ componentSignature,
+ ...hookStatements.map((statement) => `${unit}${statement}`),
+ `${unit}return (`,
+ `${unit}${unit}<>`,
+ movedSource,
+ `${unit}${unit}</>`,
+ `${unit});`,
+ '}',
+ ].join(endOfLine);
+ const sourceOutput = applySourceEdits({
+ input,
+ edits: [
+ {start, end, replacement: replacementSource},
+ {
+ start: input.length,
+ end: input.length,
+ replacement: `${input.endsWith(endOfLine) ? endOfLine : `${endOfLine}${endOfLine}`}${component}${endOfLine}`,
+ },
+ ...getInsertImportSourceEdits({
+ ast,
+ input,
+ snapshots,
+ prettierConfigOverride: null,
+ }),
+ ],
+ });
+ const firstPhase = getNodePathRemappings({
+ ast,
+ captured,
+ output: sourceOutput,
+ });
+ const wrapperPath = firstPhase.finalNodePathByNode.get(
+ (selectedSequence ?? replacement).openingElement,
+ );
+ if (!wrapperPath) {
+ throw new Error('Could not locate the connected sequence');
+ }
+
+ const registrationProject = {
+ ...project,
+ files: {...project.files, [filePath]: sourceOutput},
+ };
+ const registrationDir = registrationFile
+ .replaceAll('\\', '/')
+ .split('/')
+ .slice(0, -1);
+ const sourceParts = filePath.replaceAll('\\', '/').split('/');
+ while (registrationDir.length > 0 && registrationDir[0] === sourceParts[0]) {
+ registrationDir.shift();
+ sourceParts.shift();
+ }
+
+ const relativeSource = [...registrationDir.map(() => '..'), ...sourceParts]
+ .join('/')
+ .replace(/\.(?:tsx?|jsx?|mjs)$/, '');
+ const importPath =
+ registrationFile === filePath
+ ? null
+ : relativeSource.startsWith('.')
+ ? relativeSource
+ : `./${relativeSource}`;
+ const registrationResult = addComposition({
+ project: registrationProject,
+ compositionFile: registrationFile,
+ compositionId: name,
+ component: {importName: name, importPath},
+ metadata: {
+ ...metadata,
+ durationInFrames: sequenceDuration ?? metadata.durationInFrames,
+ },
+ });
+ const registrationOutput = registrationResult.changes.find(
+ (change) => change.filePath === registrationFile,
+ )?.nextContents;
+ if (!registrationOutput) {
+ throw new Error('Could not register the pre-composed composition');
+ }
+
+ const registrationPaths = getRegistrationPathChanges({
+ before:
+ registrationFile === filePath
+ ? sourceOutput
+ : project.files[registrationFile],
+ after: registrationOutput,
+ compositionId: name,
+ });
+ const selectedPaths = new Set(
+ nodes.map((node) => JSON.stringify(node.nodePath)),
+ );
+ const firstPhaseByOldPath = new Map(
+ firstPhase.nodePathRemappings
+ .filter((entry) => entry.oldNodePath !== null)
+ .map((entry) => [JSON.stringify(entry.oldNodePath), entry.newNodePath]),
+ );
+ const finalSourcePath = (intermediate: SequenceNodePath) => {
+ if (registrationFile !== filePath) {
+ return intermediate;
+ }
+
+ const path = registrationPaths.byOriginalPath.get(
+ JSON.stringify(intermediate),
+ );
+ if (!path) {
+ throw new Error('Could not track the moved sequence');
+ }
+
+ return path;
+ };
+
+ const sourceRemappings: NodeSourceEdit['nodePathRemappings'] = captured.map(
+ ({nodePath}) => {
+ const oldPath = JSON.stringify(nodePath);
+ const intermediate = firstPhaseByOldPath.has(oldPath)
+ ? firstPhaseByOldPath.get(oldPath)
+ : nodePath;
+ return {
+ oldNodePath: nodePath,
+ newNodePath: selectedPaths.has(oldPath)
+ ? finalSourcePath(wrapperPath)
+ : intermediate
+ ? finalSourcePath(intermediate)
+ : null,
+ };
+ },
+ );
+ sourceRemappings.push(
+ ...firstPhase.nodePathRemappings
+ .filter(
+ (entry): entry is typeof entry & {newNodePath: SequenceNodePath} =>
+ entry.oldNodePath === null && entry.newNodePath !== null,
+ )
+ .map((entry) => ({
+ oldNodePath: null,
+ newNodePath: finalSourcePath(entry.newNodePath),
+ })),
+ );
+ const sourceOutputFinal =
+ registrationFile === filePath ? registrationOutput : sourceOutput;
+ const edits: NodeSourceEdit[] = [
+ {filePath, output: sourceOutputFinal, nodePathRemappings: sourceRemappings},
+ ];
+ if (registrationFile === filePath) {
+ sourceRemappings.push({
+ oldNodePath: null,
+ newNodePath: registrationPaths.insertedPath,
+ });
+ } else {
+ edits.push({
+ filePath: registrationFile,
+ output: registrationOutput,
+ nodePathRemappings: [
+ ...registrationPaths.original.map(({nodePath}) => ({
+ oldNodePath: nodePath,
+ newNodePath: registrationPaths.byOriginalPath.get(
+ JSON.stringify(nodePath),
+ )!,
+ })),
+ {oldNodePath: null, newNodePath: registrationPaths.insertedPath},
+ ],
+ });
+ }
+
+ return {...getNodeEditResult({project, edits}), logLine};
+};
+
+export const canPrecomposeJsxNodes = <Project extends CodemodProject>(
+ options: PrecomposeOptions<Project>,
+): {canPrecompose: boolean; reason: string | null} => {
+ try {
+ precomposeJsxNodes(options);
+ return {canPrecompose: true, reason: null};
+ } catch (error) {
+ return {canPrecompose: false, reason: (error as Error).message};
+ }
+};
diff --git a/packages/example/src/BarChart.tsx b/packages/example/src/BarChart.tsx
index 1dff1dda25..a414868297 100644
--- a/packages/example/src/BarChart.tsx
+++ b/packages/example/src/BarChart.tsx
@@ -2,6 +2,7 @@ import {
AbsoluteFill,
Easing,
Interactive,
+ Sequence,
interpolate,
useCurrentFrame,
useVideoConfig,
@@ -131,46 +132,13 @@ export const BarChart: React.FC = () => {
overflow: 'hidden',
}}
>
- <Interactive.Div
- name="Ambient glow"
- style={{
- position: 'absolute',
- width: 520,
- height: 520,
- right: -150,
- top: -230,
- borderRadius: 999,
- background: 'rgba(115, 91, 255, 0.18)',
- filter: 'blur(90px)',
- scale: interpolate(frame, [0, durationInFrames - 1], [0.92, 1.08], {
- extrapolateLeft: 'clamp',
- extrapolateRight: 'clamp',
- easing: Easing.inOut(Easing.sin),
- output: 'perceptual-scale',
- }),
- }}
- />
+ <Sequence layout="none" name="Ambient glow">
+ <AmbientGlow frame={frame} durationInFrames={durationInFrames} />
+ </Sequence>
- <Interactive.Div
- name="Eyebrow"
- style={{
- position: 'absolute',
- left: 86,
- top: 66,
- color: '#8E9AB8',
- fontSize: 20,
- fontWeight: 750,
- letterSpacing: 4.4,
- textTransform: 'uppercase',
- opacity: interpolate(frame, [3, 20], [0, 1], {
- extrapolateLeft: 'clamp',
- extrapolateRight: 'clamp',
- easing: Easing.bezier(0.16, 1, 0.3, 1),
- }),
- }}
- >
- Performance overview
- </Interactive.Div>
+ <Sequence layout="none" name={'Eyebrow'}>
+ <Eyebrow frame={frame} />
+ </Sequence>
<Interactive.Div
name="Title"
@@ -283,6 +251,58 @@ export const BarChart: React.FC = () => {
</Interactive.Div>
</Interactive.Div>
+ <Sequence layout="none" name={'Peak badge'}>
+ <PeakBadge frame={frame} />
+ </Sequence>
+ </AbsoluteFill>
+ );
+};
+
+export function AmbientGlow({
+ frame: parentFrame,
+ durationInFrames: parentDurationInFrames,
+}: {
+ frame?: number | null;
+ durationInFrames?: number | null;
+}) {
+ const standaloneFrame = useCurrentFrame();
+ const {durationInFrames: standaloneDurationInFrames} = useVideoConfig();
+ const frame = parentFrame ?? standaloneFrame;
+ const durationInFrames = parentDurationInFrames ?? standaloneDurationInFrames;
+ return (
+ <>
+ <Interactive.Div
+ name="Ambient glow"
+ style={{
+ position: 'absolute',
+ width: 520,
+ height: 520,
+ right: -150,
+ top: -230,
+ borderRadius: 999,
+ background: 'rgba(115, 91, 255, 0.18)',
+ filter: 'blur(90px)',
+ scale: interpolate(frame, [0, durationInFrames - 1], [0.92, 1.08], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ easing: Easing.inOut(Easing.sin),
+ output: 'perceptual-scale',
+ }),
+ }}
+ />
+ </>
+ );
+}
+
+export function PeakBadge({
+ frame: precomposeParentFrame,
+}: {
+ frame?: number | null;
+}) {
+ const precomposeStandaloneFrame = useCurrentFrame();
+ const frame = precomposeParentFrame ?? precomposeStandaloneFrame;
+ return (
+ <>
<Interactive.Div
name="Peak badge"
style={{
@@ -314,6 +334,39 @@ export const BarChart: React.FC = () => {
>
<span style={{fontSize: 13}}>●</span> West leads at 87%
</Interactive.Div>
- </AbsoluteFill>
+ </>
);
-};
+}
+
+export function Eyebrow({
+ frame: precomposeParentFrame2,
+}: {
+ frame?: number | null;
+}) {
+ const precomposeStandaloneFrame2 = useCurrentFrame();
+ const frame = precomposeParentFrame2 ?? precomposeStandaloneFrame2;
+ return (
+ <>
+ <Interactive.Div
+ name="Eyebrow"
+ style={{
+ position: 'absolute',
+ left: 86,
+ top: 66,
+ color: '#8E9AB8',
+ fontSize: 20,
+ fontWeight: 750,
+ letterSpacing: 4.4,
+ textTransform: 'uppercase',
+ opacity: interpolate(frame, [3, 20], [0, 1], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ easing: Easing.bezier(0.16, 1, 0.3, 1),
+ }),
+ }}
+ >
+ Performance overview
+ </Interactive.Div>
+ </>
+ );
+}
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index bec6c7f339..c821ebc0a6 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -11,7 +11,7 @@ import {
import {z} from 'zod';
import {TwentyTwoKHzAudio} from './22KhzAudio';
import {UseanimatedEmojis} from './AnimatedEmojis';
-import {BarChart} from './BarChart';
+import {AmbientGlow, BarChart, PeakBadge, Eyebrow} from './BarChart';
import BetaText, {betaTextSchema} from './BetaText';
import {NativeBufferStateForImage} from './BufferState/Image';
import {NativeBufferState} from './BufferState/Simple';
@@ -469,6 +469,14 @@ export const Index: React.FC = () => {
width={1280}
height={720}
/>
+ <Composition
+ id="AmbientGlow"
+ component={AmbientGlow}
+ durationInFrames={180}
+ fps={30}
+ width={1280}
+ height={720}
+ />
<Folder name="maptiler">
<Composition
id="switzerland-map"
@@ -3240,6 +3248,22 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={180}
/>
+ <Composition
+ id="PeakBadge"
+ component={PeakBadge}
+ durationInFrames={180}
+ fps={30}
+ width={1280}
+ height={720}
+ />
+ <Composition
+ id="Eyebrow"
+ component={Eyebrow}
+ durationInFrames={180}
+ fps={30}
+ width={1280}
+ height={720}
+ />
</>
);
};
diff --git a/packages/skills/skills/remotion-markup/SKILL.md b/packages/skills/skills/remotion-markup/SKILL.md
index 26e93f61d0..8a03e07e15 100644
--- a/packages/skills/skills/remotion-markup/SKILL.md
+++ b/packages/skills/skills/remotion-markup/SKILL.md
@@ -249,6 +249,10 @@ See [multi-scene-video.md](multi-scene-video.md) if planning to make a video wit
When a scene or group of layers deserves its own editable timeline, follow [connected-compositions.md](connected-compositions.md). Prefer this structure for substantial scenes in a multi-scene video.
+For a Studio request such as `Pre-compose Ambient glow (src/BarChart.tsx:134)`, find the selected sequence markup at the given location. Make a connected composition, following [connected-compositions.md](connected-compositions.md): extract the markup into a named component, render one direct instance of it as the only child of a `<Sequence>`, `<Series.Sequence>`, or `<TransitionSeries.Sequence>`, and register that same component reference with a unique `<Composition>` in the root. If the selected node is already a sequence, keep its props and extract its children. The registration needs dimensions, fps, duration, and `defaultProps` equivalent to its parent use. A component extraction without a registered composition does not complete a pre-compose request.
+
+The extracted component may return a fragment; do not add a DOM wrapper. Preserve sibling order, props, keys, conditional rendering, dimensions, appearance, and timing. Trace values used by the selected markup: move their derivations only when the same scope and lifecycle are preserved, otherwise pass them as props. In particular, moving `useCurrentFrame()` or `useVideoConfig()` across a sequence boundary can change its result; pass the parent value when needed. If the selection or a behavior-preserving connected composition is unclear, ask for clarification instead of guessing.
+
## Voiceover
See [voiceover.md](voiceover.md) for adding an AI-generated voiceover to Remotion compositions using ElevenLabs TTS.
diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.ts
index 03b967e5ad..6c5e1ef88a 100644
--- a/packages/studio-server/src/preview-server/api-routes.ts
+++ b/packages/studio-server/src/preview-server/api-routes.ts
@@ -40,6 +40,7 @@ import {handleOpenInFileExplorer} from './routes/open-in-file-explorer';
import {openInGitClientHandler} from './routes/open-in-git-client';
import {openInTerminalHandler} from './routes/open-in-terminal';
import {pasteEffectsHandler} from './routes/paste-effects';
+import {precomposeJsxNodesHandler} from './routes/precompose-jsx-nodes';
import {prepareElementInstallHandler} from './routes/prepare-element-install';
import {projectInfoHandler} from './routes/project-info';
import {redoHandler} from './routes/redo';
@@ -130,6 +131,7 @@ export const allApiRoutes: {
'/api/delete-jsx-nodes': deleteJsxNodesHandler,
'/api/duplicate-jsx-node': duplicateJsxNodeHandler,
'/api/wrap-jsx-node': wrapJsxNodeHandler,
+ '/api/precompose-jsx-nodes': precomposeJsxNodesHandler,
'/api/split-jsx-sequence': splitJsxSequenceHandler,
'/api/split-video-from-audio': splitVideoFromAudioHandler,
'/api/insert-basic-captions': insertBasicCaptionsHandler,
diff --git a/packages/studio-server/src/preview-server/routes/precompose-jsx-nodes.ts b/packages/studio-server/src/preview-server/routes/precompose-jsx-nodes.ts
new file mode 100644
index 0000000000..41933c6e98
--- /dev/null
+++ b/packages/studio-server/src/preview-server/routes/precompose-jsx-nodes.ts
@@ -0,0 +1,210 @@
+import {readFileSync} from 'node:fs';
+import {canPrecomposeJsxNodes, precomposeJsxNodes} from '@remotion/codemods';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ PrecomposeJsxNodesRequest,
+ PrecomposeJsxNodesResponse,
+} from '@remotion/studio-shared';
+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
+import type {ApiHandler} from '../api-types';
+import {formatLogFileLocation} from '../format-log-file-location';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
+import {
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const precomposeJsxNodesHandler: ApiHandler<
+ PrecomposeJsxNodesRequest,
+ PrecomposeJsxNodesResponse
+> = ({
+ input: {
+ nodes,
+ dryRun,
+ compositionFile,
+ compositionId,
+ metadata,
+ existingCompositionIds,
+ },
+ remotionRoot,
+ logLevel,
+}) =>
+ withSourceFileWriteQueue((): Promise<PrecomposeJsxNodesResponse> => {
+ try {
+ if (nodes.length === 0) {
+ throw new Error('No JSX sequences were selected');
+ }
+
+ const resolved = nodes.map(({fileName, nodePath}) => ({
+ ...resolveFileInsideProject({
+ remotionRoot,
+ fileName,
+ action: 'modify',
+ }),
+ nodePath,
+ }));
+ const {absolutePath} = resolved[0];
+ if (resolved.some((node) => node.absolutePath !== absolutePath)) {
+ throw new Error('Selected sequences must be in the same source file');
+ }
+
+ const registration = resolveFileInsideProject({
+ remotionRoot,
+ fileName: compositionFile,
+ action: 'modify',
+ });
+ const fileContents = readFileSync(absolutePath, 'utf-8');
+ const registrationContents =
+ registration.absolutePath === absolutePath
+ ? fileContents
+ : readFileSync(registration.absolutePath, 'utf-8');
+ const files = {
+ [absolutePath]: fileContents,
+ [registration.absolutePath]: registrationContents,
+ };
+ const project = {files, rootDir: remotionRoot};
+ const codemodInput = {
+ project,
+ nodes: resolved.map(({nodePath}) => ({
+ filePath: absolutePath,
+ nodePath,
+ })),
+ compositionFile: registration.absolutePath,
+ compositionId,
+ metadata,
+ existingCompositionIds,
+ };
+ const eligibility = canPrecomposeJsxNodes(codemodInput);
+ if (dryRun) {
+ return Promise.resolve({
+ success: true,
+ ...eligibility,
+ nodePathMutation: null,
+ });
+ }
+
+ if (!eligibility.canPrecompose) {
+ throw new Error(
+ eligibility.reason ?? 'Cannot pre-compose this selection',
+ );
+ }
+
+ const result = precomposeJsxNodes(codemodInput);
+ const changes = [...result.changes].sort(
+ (a, b) =>
+ Number(b.filePath === absolutePath) -
+ Number(a.filePath === absolutePath),
+ );
+ if (
+ !changes.some(({filePath}) => filePath === absolutePath) ||
+ !changes.some(({filePath}) => filePath === registration.absolutePath)
+ ) {
+ throw new Error('Could not pre-compose selected sequences');
+ }
+
+ for (const change of changes) {
+ if (
+ !Object.hasOwn(files, change.filePath) ||
+ change.previousContents !== files[change.filePath] ||
+ change.nextContents === null ||
+ readFileSync(change.filePath, 'utf-8') !== change.previousContents
+ ) {
+ throw new Error('Source changed before applying pre-compose');
+ }
+ }
+
+ const remappingsByFile = changes.map(({filePath}) => ({
+ absolutePath: filePath,
+ remappings: result.nodePathRemappings
+ .filter((remapping) => remapping.filePath === filePath)
+ .map(({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath})),
+ }));
+ const mutationFiles = remappingsByFile.filter(
+ ({remappings}) => remappings.length > 0,
+ );
+ const nodePathMutation =
+ mutationFiles.length === 0
+ ? null
+ : broadcastSequenceNodePathMutation(mutationFiles, null);
+ pushTransactionToUndoStack({
+ snapshots: changes.map((change) => {
+ const remappings = remappingsByFile.find(
+ ({absolutePath: filePath}) => filePath === change.filePath,
+ )?.remappings;
+ return {
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === absolutePath ? result.logLine : 1,
+ nodePathRemappings:
+ remappings && remappings.length > 0 ? remappings : null,
+ };
+ }),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: '↩️ Pre-compose sequences',
+ redoMessage: '↪️ Pre-compose sequences',
+ },
+ entryType: 'precompose-jsx-nodes',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: null,
+ });
+ for (const change of changes) {
+ const output = change.nextContents;
+ if (output === null) {
+ throw new Error('Could not write a pre-composed source file');
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: output,
+ originatorClientId: undefined,
+ metadata: remappingsByFile.some(
+ ({absolutePath: filePath, remappings}) =>
+ filePath === change.filePath && remappings.length > 0,
+ )
+ ? {skipSequencePropsUpdate: true}
+ : null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath,
+ line: result.logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Pre-composed ${nodes.length} sequence${nodes.length === 1 ? '' : 's'}`,
+ );
+ for (const change of changes) {
+ RenderInternals.Log.verbose(
+ {indent: false, logLevel},
+ `[precompose-jsx-nodes] Wrote ${
+ resolveFileInsideProject({
+ remotionRoot,
+ fileName: change.filePath,
+ action: 'modify',
+ }).fileRelativeToRoot
+ }`,
+ );
+ }
+
+ printUndoHint(logLevel);
+ return Promise.resolve({success: true, ...eligibility, nodePathMutation});
+ } catch (err) {
+ return Promise.resolve({
+ success: false,
+ reason: (err as Error).message,
+ stack: (err as Error).stack ?? '',
+ });
+ }
+ });
diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.ts
index 4cd51e06dd..051210c9e0 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -41,6 +41,7 @@ type UndoEntryType =
| 'delete-jsx-nodes'
| 'duplicate-jsx-node'
| 'wrap-jsx-node'
+ | 'precompose-jsx-nodes'
| 'split-jsx-sequence'
| 'split-video-from-audio'
| 'insert-basic-captions'
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index d603c5c792..713b93905d 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -914,6 +914,34 @@ export type WrapJsxNodeResponse =
}
| {success: false; reason: string; stack: string};
+export type PrecomposeJsxNodesRequestItem = {
+ fileName: string;
+ nodePath: SequenceNodePath;
+};
+
+export type PrecomposeJsxNodesRequest = {
+ nodes: PrecomposeJsxNodesRequestItem[];
+ compositionFile: string;
+ compositionId: string;
+ existingCompositionIds: string[];
+ metadata: {
+ width: number;
+ height: number;
+ fps: number;
+ durationInFrames: number;
+ };
+ dryRun: boolean;
+};
+
+export type PrecomposeJsxNodesResponse =
+ | {
+ success: true;
+ canPrecompose: boolean;
+ reason: string | null;
+ nodePathMutation: SequenceNodePathMutation | null;
+ }
+ | {success: false; reason: string; stack: string};
+
export type SplitJsxSequenceRequestItem = {
fileName: string;
nodePath: SequenceNodePath;
@@ -1468,6 +1496,10 @@ export type ApiRoutes = {
DuplicateJsxNodeResponse
>;
'/api/wrap-jsx-node': ReqAndRes<WrapJsxNodeRequest, WrapJsxNodeResponse>;
+ '/api/precompose-jsx-nodes': ReqAndRes<
+ PrecomposeJsxNodesRequest,
+ PrecomposeJsxNodesResponse
+ >;
'/api/split-jsx-sequence': ReqAndRes<
SplitJsxSequenceRequest,
SplitJsxSequenceResponse
diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.ts
index b65b921362..cf0a22879e 100644
--- a/packages/studio-shared/src/browser-studio-operations.ts
+++ b/packages/studio-shared/src/browser-studio-operations.ts
@@ -29,6 +29,8 @@ import type {
DuplicateEffectResponse,
DuplicateJsxNodeRequest,
DuplicateJsxNodeResponse,
+ PrecomposeJsxNodesRequest,
+ PrecomposeJsxNodesResponse,
WrapJsxNodeRequest,
WrapJsxNodeResponse,
InsertJsxElementRequest,
@@ -191,6 +193,9 @@ export type BrowserStudioOperations = {
duplicateJsxNode: (
request: DuplicateJsxNodeRequest,
) => Promise<DuplicateJsxNodeResponse>;
+ precomposeJsxNodes: (
+ request: PrecomposeJsxNodesRequest,
+ ) => Promise<PrecomposeJsxNodesResponse>;
wrapJsxNode: (request: WrapJsxNodeRequest) => Promise<WrapJsxNodeResponse>;
effects: BrowserStudioEffectOperations;
findInFile: (request: FindInFileRequest) => Promise<FindInFileResponse>;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index f2495560b5..eb2dd17602 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -53,6 +53,9 @@ export {
DuplicateJsxNodeRequest,
DuplicateJsxNodeRequestItem,
DuplicateJsxNodeResponse,
+ PrecomposeJsxNodesRequest,
+ PrecomposeJsxNodesRequestItem,
+ PrecomposeJsxNodesResponse,
JsxWrapper,
WrapJsxNodeRequest,
WrapJsxNodeResponse,
diff --git a/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx b/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx
index 2cb5668de4..f3cc60e68d 100644
--- a/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx
@@ -7,6 +7,7 @@ import React, {
} from 'react';
import {Internals} from 'remotion';
import {calculateTimeline} from '../../helpers/calculate-timeline';
+import {StudioServerConnectionCtx} from '../../helpers/client-id';
import {LIGHT_TEXT} from '../../helpers/colors';
import {isStudioInteractivityEnabled} from '../../helpers/interactivity-enabled';
import {
@@ -36,6 +37,7 @@ import {
MultiSequenceField,
type MultiSequenceTarget,
} from './MultiSequenceField';
+import {SequencePrecomposeAction} from './SequencePrecomposeAction';
import {scrollableContainer, sequenceHeaderDivider} from './styles';
const selectionCountStyle: React.CSSProperties = {
@@ -57,6 +59,7 @@ export const MultiSequenceInspector: React.FC<{
>[];
readonly readOnlyStudio: boolean;
}> = ({selections, readOnlyStudio}) => {
+ const {previewServerState} = useContext(StudioServerConnectionCtx);
const {sequences} = useContext(Internals.SequenceManager);
const timelinePosition = Internals.Timeline.useTimelinePosition();
const {overrideIdToNodePathMappings} = useContext(
@@ -103,6 +106,30 @@ export const MultiSequenceInspector: React.FC<{
return result;
}, [overrideIdToNodePathMappings, selections, sequences]);
+ const precomposeTargets = useMemo(() => {
+ const tracks = calculateTimeline({
+ sequences,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ });
+ return selections.map(({nodePathInfo}) => {
+ const key = stringifySequenceExpandedRowKey(
+ nodePathInfo.sequenceSubscriptionKey,
+ );
+ const track = tracks.find(
+ (candidate) =>
+ candidate.nodePathInfo !== null &&
+ stringifySequenceExpandedRowKey(
+ candidate.nodePathInfo.sequenceSubscriptionKey,
+ ) === key &&
+ candidate.nodePathInfo.index === nodePathInfo.index,
+ );
+ return {
+ nodePathInfo,
+ displayName: track?.sequence.displayName ?? null,
+ line: null,
+ };
+ });
+ }, [overrideIdToNodePathMappings, selections, sequences]);
const store = useMemo(() => {
const stores = (targets ?? []).map(
(target) => target.controls.runtimeValues,
@@ -231,6 +258,14 @@ export const MultiSequenceInspector: React.FC<{
>
Split selected
</InspectorQuickAction>
+ <SequencePrecomposeAction
+ targets={precomposeTargets}
+ sourceActionsDisabled={
+ previewServerState.type !== 'connected' ||
+ readOnlyStudio ||
+ !isStudioInteractivityEnabled()
+ }
+ />
</InspectorQuickActionsSection>
</CollapsibleInspectorSection>
</div>
diff --git a/packages/studio/src/components/InspectorPanel/SequencePrecomposeAction.tsx b/packages/studio/src/components/InspectorPanel/SequencePrecomposeAction.tsx
new file mode 100644
index 0000000000..0bdaf7688d
--- /dev/null
+++ b/packages/studio/src/components/InspectorPanel/SequencePrecomposeAction.tsx
@@ -0,0 +1,166 @@
+import React, {useCallback, useContext, useState} from 'react';
+import {Internals, useVideoConfig} from 'remotion';
+import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';
+import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';
+import {FilmIcon} from '../../icons/video';
+import {SetSelectedModalContext} from '../../state/modals';
+import {showNotification} from '../Notifications/NotificationCenter';
+import {precomposeJsxNodes} from '../precompose-jsx-nodes-api';
+import {useResolvedStack} from '../Timeline/use-resolved-stack';
+import {InspectorQuickAction} from './common';
+
+const iconStyle: React.CSSProperties = {
+ display: 'block',
+ height: 16,
+ width: 16,
+};
+
+export const SequencePrecomposeAction: React.FC<{
+ readonly targets: readonly {
+ readonly nodePathInfo: SequenceNodePathInfo;
+ readonly displayName: string | null;
+ readonly line: number | null;
+ }[];
+ readonly sourceActionsDisabled: boolean;
+}> = ({targets, sourceActionsDisabled}) => {
+ const {setSelectedModal} = useContext(SetSelectedModalContext);
+ const {compositions, canvasContent} = useContext(
+ Internals.CompositionManager,
+ );
+ const {width, height, fps, durationInFrames} = useVideoConfig();
+ const [busy, setBusy] = useState(false);
+ const browserStudioOperations = getBrowserStudioOperations();
+ const compositionId =
+ canvasContent?.type === 'composition' ? canvasContent.compositionId : null;
+ const composition = compositions.find((item) => item.id === compositionId);
+ const resolvedCompositionLocation = useResolvedStack(
+ composition?.stack ?? null,
+ );
+ const compositionFile =
+ resolvedCompositionLocation?.source ??
+ (compositionId && browserStudioOperations
+ ? browserStudioOperations.getCompositionFile(compositionId)
+ : null);
+ const canChangeSource =
+ !sourceActionsDisabled &&
+ (browserStudioOperations === null ||
+ typeof browserStudioOperations.precomposeJsxNodes === 'function');
+
+ const onPrecompose = useCallback(() => {
+ if (busy || !canChangeSource || targets.length === 0) {
+ return;
+ }
+
+ const nodes = targets.map(({nodePathInfo}) => ({
+ fileName: nodePathInfo.sequenceSubscriptionKey.absolutePath,
+ nodePath: nodePathInfo.sequenceSubscriptionKey.nodePath,
+ }));
+ const modalTargets = targets.map(({nodePathInfo, displayName, line}) => ({
+ fileName: nodePathInfo.sequenceSubscriptionKey.absolutePath,
+ displayName,
+ line,
+ }));
+ const openRefactorModal = () => {
+ setSelectedModal({
+ type: 'precompose-refactor',
+ targets: modalTargets,
+ });
+ };
+
+ if (compositionFile === null || compositionId === null) {
+ openRefactorModal();
+ return;
+ }
+
+ const request = {
+ compositionFile,
+ compositionId,
+ existingCompositionIds: compositions.map(({id}) => id),
+ metadata: {width, height, fps, durationInFrames},
+ };
+
+ const uniqueSourceNodes =
+ targets.every(
+ ({nodePathInfo}) =>
+ nodePathInfo.numberOfSequencesWithThisNodePath === 1,
+ ) &&
+ new Set(nodes.map((node) => JSON.stringify(node))).size === nodes.length;
+
+ if (!uniqueSourceNodes) {
+ openRefactorModal();
+ return;
+ }
+
+ if (nodes.some((node) => node.fileName !== nodes[0].fileName)) {
+ openRefactorModal();
+ return;
+ }
+
+ setBusy(true);
+ precomposeJsxNodes({...request, nodes, dryRun: true})
+ .then(async (eligibility) => {
+ if (!eligibility.success) {
+ showNotification(eligibility.reason, 4000);
+ return;
+ }
+
+ if (!eligibility.canPrecompose) {
+ openRefactorModal();
+ return;
+ }
+
+ const result = await precomposeJsxNodes({
+ ...request,
+ nodes,
+ dryRun: false,
+ });
+ if (result.success) {
+ return;
+ }
+
+ // The file can change between eligibility and the write. Distinguish a
+ // newly ineligible selection from a transport or filesystem error.
+ const currentEligibility = await precomposeJsxNodes({
+ ...request,
+ nodes,
+ dryRun: true,
+ });
+ if (currentEligibility.success && !currentEligibility.canPrecompose) {
+ openRefactorModal();
+ return;
+ }
+
+ showNotification(result.reason, 4000);
+ })
+ .catch((error) => {
+ showNotification((error as Error).message, 4000);
+ })
+ .finally(() => setBusy(false));
+ }, [
+ busy,
+ canChangeSource,
+ compositionFile,
+ compositionId,
+ compositions,
+ durationInFrames,
+ fps,
+ height,
+ setSelectedModal,
+ targets,
+ width,
+ ]);
+
+ if (!canChangeSource || targets.length === 0) {
+ return null;
+ }
+
+ return (
+ <InspectorQuickAction
+ disabled={busy}
+ onClick={onPrecompose}
+ renderIcon={(color) => <FilmIcon color={color} style={iconStyle} />}
+ >
+ Pre-compose
+ </InspectorQuickAction>
+ );
+};
diff --git a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
index 6ee1c2d370..ad6c4ab5b7 100644
--- a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
@@ -52,6 +52,7 @@ import {
SequenceInspectorHeader,
useSequenceInspectorSourceLocation,
} from './SequenceInspectorHeader';
+import {SequencePrecomposeAction} from './SequencePrecomposeAction';
import {SequenceWrapAction} from './SequenceWrapAction';
import {selectedContainer} from './styles';
import {useTrackForSelection} from './use-track-for-selection';
@@ -121,7 +122,8 @@ const SequenceSourceQuickActions: React.FC<{
readonly selection: Extract<TimelineSelection, {type: 'sequence'}>;
readonly track: TimelineTrackData;
readonly validatedSource: string;
-}> = ({selection, track, validatedSource}) => {
+ readonly sourceLine: number;
+}> = ({selection, track, validatedSource, sourceLine}) => {
const timelinePosition = Internals.Timeline.useTimelinePosition();
const {previewServerState} = useContext(StudioServerConnectionCtx);
const {setSelectedModal} = useContext(SetSelectedModalContext);
@@ -356,6 +358,16 @@ const SequenceSourceQuickActions: React.FC<{
sequence={track.sequence}
sourceActionsDisabled={sourceActionsDisabled}
/>
+ <SequencePrecomposeAction
+ targets={[
+ {
+ nodePathInfo: selection.nodePathInfo,
+ displayName: track.sequence.displayName,
+ line: sourceLine,
+ },
+ ]}
+ sourceActionsDisabled={sourceActionsDisabled}
+ />
<InspectorQuickAction
disabled={sourceActionsDisabled}
iconContainerStyle={largeInspectorActionIconContainerStyle}
@@ -480,12 +492,37 @@ const SequenceExpandedInspector: React.FC<{
selection={sequenceSelection}
track={track}
validatedSource={validatedLocation.source}
+ sourceLine={validatedLocation.line}
/>
</InspectorQuickActionsSection>
</CollapsibleInspectorSection>
</>
) : (
- <InspectorMessage>Source controls unavailable</InspectorMessage>
+ <>
+ <InspectorMessage>Source controls unavailable</InspectorMessage>
+ <CollapsibleInspectorSection
+ collapsible
+ label="Actions"
+ sectionId="sequence-actions"
+ >
+ <InspectorQuickActionsSection>
+ <SequencePrecomposeAction
+ targets={[
+ {
+ nodePathInfo: sequenceSelection.nodePathInfo,
+ displayName: track.sequence.displayName,
+ line: null,
+ },
+ ]}
+ sourceActionsDisabled={
+ previewServerState.type !== 'connected' ||
+ readOnlyStudio ||
+ !isStudioInteractivityEnabled()
+ }
+ />
+ </InspectorQuickActionsSection>
+ </CollapsibleInspectorSection>
+ </>
)}
</div>
);
diff --git a/packages/studio/src/components/Modals.tsx b/packages/studio/src/components/Modals.tsx
index 58eb04cb95..8460d47ba8 100644
--- a/packages/studio/src/components/Modals.tsx
+++ b/packages/studio/src/components/Modals.tsx
@@ -25,6 +25,7 @@ import {RenameFolder} from './NewComposition/RenameFolder';
import {RenameStaticFileModal} from './NewComposition/RenameStaticFile';
import {showNotification} from './Notifications/NotificationCenter';
import {OverrideInputPropsModal} from './OverrideInputProps';
+import {PrecomposeRefactorModal} from './PrecomposeRefactorModal';
import QuickSwitcher from './QuickSwitcher/QuickSwitcher';
import {RenderStatusModal} from './RenderModal/RenderStatusModal';
import {RenderModalWithLoader} from './RenderModal/ServerRenderModal';
@@ -282,6 +283,9 @@ export const Modals: React.FC<{
{modalContextType && modalContextType.type === 'fix-computed-value' && (
<FixComputedValueModal state={modalContextType} />
)}
+ {modalContextType && modalContextType.type === 'precompose-refactor' && (
+ <PrecomposeRefactorModal state={modalContextType} />
+ )}
{modalContextType && modalContextType.type === 'generate-with-agent' ? (
<GenerateWithAgentModal state={modalContextType} />
) : null}
diff --git a/packages/studio/src/components/PrecomposeRefactorModal.tsx b/packages/studio/src/components/PrecomposeRefactorModal.tsx
new file mode 100644
index 0000000000..2d3fd699a3
--- /dev/null
+++ b/packages/studio/src/components/PrecomposeRefactorModal.tsx
@@ -0,0 +1,93 @@
+import React, {useContext} from 'react';
+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
+import {StudioServerConnectionCtx} from '../helpers/client-id';
+import {LIGHT_TEXT} from '../helpers/colors';
+import {formatFileLocation} from '../helpers/format-file-location';
+import type {ModalState} from '../state/modals';
+import {AgentPrompt} from './AgentPrompt';
+import {getMaxModalHeight, getMaxModalWidth} from './ModalContainer';
+import {ModalHeader} from './ModalHeader';
+import {DismissableModal} from './NewComposition/DismissableModal';
+import {useSettings} from './SettingsContext';
+
+const panelStyle: React.CSSProperties = {
+ borderRadius: 6,
+ display: 'flex',
+ flexDirection: 'column',
+ maxHeight: getMaxModalHeight(800),
+ minWidth: 0,
+ overflow: 'hidden',
+ width: getMaxModalWidth(560),
+};
+
+const container: React.CSSProperties = {
+ minHeight: 0,
+ overflowY: 'auto',
+ padding: 16,
+};
+
+const text: React.CSSProperties = {
+ color: LIGHT_TEXT,
+ fontFamily: 'sans-serif',
+ fontSize: 14,
+ lineHeight: 1.5,
+ marginBottom: 16,
+};
+
+type State = Extract<ModalState, {type: 'precompose-refactor'}>;
+
+export const PrecomposeRefactorModal: React.FC<{readonly state: State}> = ({
+ state,
+}) => {
+ const {previewServerState} = useContext(StudioServerConnectionCtx);
+ const {error, remotionSkillsInfo} = useSettings();
+ const isBrowserStudio = getBrowserStudioOperations() !== null;
+ const canSuggestAgent =
+ !isBrowserStudio &&
+ !window.remotion_isReadOnlyStudio &&
+ previewServerState.type === 'connected' &&
+ remotionSkillsInfo?.skills.some(({name}) => name === 'remotion-markup');
+ const targets = [
+ ...new Set(
+ state.targets.map(({fileName, displayName, line}) => {
+ const location =
+ formatFileLocation({
+ location: {source: fileName, line},
+ root: window.remotion_cwd,
+ }) ?? fileName;
+ return displayName ? `${displayName} (${location})` : location;
+ }),
+ ),
+ ];
+ const promptDetails =
+ targets.length === 1
+ ? ` Pre-compose ${targets[0]}`
+ : ` Pre-compose these sequences: ${targets.join('; ')}`;
+
+ return (
+ <DismissableModal panelStyle={panelStyle}>
+ <ModalHeader title="Pre-compose needs a refactor" />
+ <div style={container}>
+ <div style={text}>
+ The item cannot be automatically pre-composed because the code is too
+ complex.
+ </div>
+ {canSuggestAgent ? (
+ <AgentPrompt
+ availableText="You can pre-compose it using an agent:"
+ promptDetails={promptDetails}
+ skillId="remotion-markup"
+ />
+ ) : (
+ <div style={text}>
+ {isBrowserStudio
+ ? 'Agent-assisted refactoring is unavailable in Browser Studio.'
+ : remotionSkillsInfo === null && error === null
+ ? 'Checking whether /remotion-markup is available...'
+ : 'The /remotion-markup Agent Skill is unavailable in this Studio.'}
+ </div>
+ )}
+ </div>
+ </DismissableModal>
+ );
+};
diff --git a/packages/studio/src/components/precompose-jsx-nodes-api.ts b/packages/studio/src/components/precompose-jsx-nodes-api.ts
new file mode 100644
index 0000000000..824d3d583c
--- /dev/null
+++ b/packages/studio/src/components/precompose-jsx-nodes-api.ts
@@ -0,0 +1,17 @@
+import type {
+ PrecomposeJsxNodesRequest,
+ PrecomposeJsxNodesResponse,
+} from '@remotion/studio-shared';
+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
+import {callApi} from './call-api';
+
+export const precomposeJsxNodes = (
+ request: PrecomposeJsxNodesRequest,
+): Promise<PrecomposeJsxNodesResponse> => {
+ const browserStudioOperations = getBrowserStudioOperations();
+ if (browserStudioOperations) {
+ return browserStudioOperations.precomposeJsxNodes(request);
+ }
+
+ return callApi('/api/precompose-jsx-nodes', request);
+};
diff --git a/packages/studio/src/state/modals.ts b/packages/studio/src/state/modals.ts
index a697a0d505..855d696889 100644
--- a/packages/studio/src/state/modals.ts
+++ b/packages/studio/src/state/modals.ts
@@ -286,6 +286,14 @@ export type ModalState =
column: number;
};
}
+ | {
+ type: 'precompose-refactor';
+ targets: {
+ fileName: string;
+ displayName: string | null;
+ line: number | null;
+ }[];
+ }
| {
type: 'generate-with-agent';
location: {
diff --git a/packages/studio/src/test/make-browser-studio-operations.ts b/packages/studio/src/test/make-browser-studio-operations.ts
index 3d31837ef3..f16aa7dc62 100644
--- a/packages/studio/src/test/make-browser-studio-operations.ts
+++ b/packages/studio/src/test/make-browser-studio-operations.ts
@@ -16,6 +16,7 @@ export const makeBrowserStudioOperations = (
downloadProject: () => unusedOperation('downloadProject'),
duplicateComposition: () => unusedOperation('duplicateComposition'),
duplicateJsxNode: () => unusedOperation('duplicateJsxNode'),
+ precomposeJsxNodes: () => unusedOperation('precomposeJsxNodes'),
wrapJsxNode: () => unusedOperation('wrapJsxNode'),
effects: {
addEffect: () => unusedOperation('effects'),