Skip to content

🎥 Make videos programmatically with React

`@remotion/codemods`: Split generic Studio codemods into public operations

Jonny Burger26f0e4b422c3
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 6df84ad97f..e075470586 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -1,6 +1,7 @@
import {
CodemodsInternals,
addComposition,
+ addCanvasCaptureComposition,
addEffect as addEffectCodemod,
addFolder,
addSolid,
@@ -36,6 +37,7 @@ import {
type StudioElementPayload,
} from '@remotion/studio-protocol';
import {
+ emptyCompositionComponent,
getAllSchemaKeys,
getRequiredPackageForEffectImportPath,
getRequiredPackageForInsertableElement,
@@ -81,8 +83,6 @@ const {
insertVideoLayers: insertVideoLayersCodemod,
JsxElementIdentityMismatchError,
JsxElementNotFoundAtLocationError,
- makeNewCompositionComponentSource,
- parseAndApplyCodemod,
pasteEffects: pasteEffectsCodemod,
simpleDiff,
} = CodemodsInternals;
@@ -324,22 +324,19 @@ const applyCompositionCodemod = ({
}): VirtualProject => {
const target = {project, compositionFile};
switch (codemod.type) {
- case 'new-composition':
- if (codemod.canvasCapture !== null) {
- const {newContents} = parseAndApplyCodemod({
- input: project.files[compositionFile],
- codeMod: codemod,
- });
- return {
- ...project,
- files: {...project.files, [compositionFile]: newContents},
- };
+ case 'new-composition': {
+ const componentFilePath = `${dirname(compositionFile)}/${codemod.componentName}.tsx`;
+ if (project.files[componentFilePath] !== undefined) {
+ throw new Error(
+ `Cannot create ${relativeToRoot(componentFilePath, project.rootDir)} because it already exists`,
+ );
}
- return addComposition({
+ const composition = {
...target,
compositionId: codemod.newId,
component: {
+ filePath: componentFilePath,
importName: codemod.componentName,
importPath: codemod.componentImportPath,
},
@@ -353,7 +350,24 @@ const applyCompositionCodemod = ({
codemod.folderName === null
? undefined
: {name: codemod.folderName, parentName: codemod.parentName},
- }).project;
+ };
+ if (codemod.canvasCapture !== null) {
+ return addCanvasCaptureComposition({
+ ...composition,
+ capture: codemod.canvasCapture,
+ }).project;
+ }
+
+ const result = addComposition(composition).project;
+ return {
+ ...result,
+ files: {
+ ...result.files,
+ [componentFilePath]: emptyCompositionComponent(codemod.componentName),
+ },
+ };
+ }
+
case 'duplicate-composition':
return duplicateCompositionCodemod({
...target,
@@ -1496,21 +1510,10 @@ export const createBrowserStudioOperations = ({
? newContents
: (await formatCodemodFile({contents: newContents})).output;
const files: Record<string, string> = {
- ...project.files,
+ ...nextProject.files,
[absolutePath]: output,
};
- if (codemod.type === 'new-composition') {
- const componentFilePath = `${dirname(absolutePath)}/${codemod.componentName}.tsx`;
- if (project.files[componentFilePath] !== undefined) {
- throw new Error(
- `Cannot create ${relativeToRoot(componentFilePath, project.rootDir)} because it already exists`,
- );
- }
-
- files[componentFilePath] = makeNewCompositionComponentSource(codemod);
- }
-
const diff = simpleDiff({
oldLines: input.split('\n'),
newLines: output.split('\n'),
@@ -2218,29 +2221,11 @@ export const createBrowserStudioOperations = ({
);
}
- const compositionProject = applyCompositionCodemod({
+ project = applyCompositionCodemod({
project,
compositionFile: absolutePath,
codemod: request.newComposition.codemod,
});
- const newContents = compositionProject.files[absolutePath];
- const componentFilePath = `${dirname(absolutePath)}/${request.newComposition.codemod.componentName}.tsx`;
- if (project.files[componentFilePath] !== undefined) {
- throw new Error(
- `Cannot create ${relativeToRoot(componentFilePath, project.rootDir)} because it already exists`,
- );
- }
-
- project = {
- ...project,
- files: {
- ...project.files,
- [absolutePath]: newContents,
- [componentFilePath]: makeNewCompositionComponentSource(
- request.newComposition.codemod,
- ),
- },
- };
}
const plan = await getElementInstallPlanForProject({
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index b87a45a6e9..9129620b4a 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -1,5 +1,5 @@
import {expect, test} from 'bun:test';
-import {addSolid, CodemodsInternals} from '@remotion/codemods';
+import {CodemodsInternals} from '@remotion/codemods';
import {createElementPayload} from '@remotion/studio-protocol';
import type {EventSourceEvent} from '@remotion/studio-shared';
import type {InteractivitySchema} from 'remotion';
@@ -8,19 +8,30 @@ import {createBrowserStudioOperations} from '../browser-studio-operations';
import {createBlankTemplateProject} from '../templates/blank';
import type {VirtualProject} from '../types';
-const {basicCaptionsElementSource} = CodemodsInternals;
+const {
+ basicCaptionsElementSource,
+ insertSolidIntoProject,
+ insertSolidIntoProjectWithNodePathRemappings,
+} = CodemodsInternals;
const insertSolid = (
project: VirtualProject,
compositionFile = '/project/src/Composition.tsx',
) => {
- return addSolid({
+ return insertSolidIntoProject({
project,
- compositionFile,
- compositionId: 'MyComp',
- width: 1280,
- height: 720,
- }).project;
+ request: {
+ compositionFile,
+ compositionId: 'MyComp',
+ element: {
+ type: 'solid',
+ width: 1280,
+ height: 720,
+ position: null,
+ },
+ from: null,
+ },
+ });
};
test('consumes an initial Element payload only once', () => {
@@ -80,15 +91,20 @@ test('adds multiple Solids without duplicating the import', () => {
test('adds a Solid at a timeline frame', () => {
const project = createBlankTemplateProject();
- const updated = addSolid({
+ const updated = insertSolidIntoProject({
project,
- compositionFile: '/project/src/Composition.tsx',
- compositionId: 'MyComp',
- from: 42,
- width: 1280,
- height: 720,
- position: {x: 100, y: 50},
- }).project;
+ request: {
+ compositionFile: '/project/src/Composition.tsx',
+ compositionId: 'MyComp',
+ from: 42,
+ element: {
+ type: 'solid',
+ width: 1280,
+ height: 720,
+ position: {x: 100, y: 50},
+ },
+ },
+ });
const composition = updated.files['/project/src/Composition.tsx'];
expect(composition).toContain('<Sequence from={42}');
@@ -185,13 +201,21 @@ registerRoot(Root);
`,
},
};
- const {project: updated, nodePathRemappings} = addSolid({
- project,
- compositionFile: '/project/src/index.tsx',
- compositionId: 'MyComp',
- width: 1280,
- height: 720,
- });
+ const {project: updated, nodePathRemappings} =
+ insertSolidIntoProjectWithNodePathRemappings({
+ project,
+ request: {
+ compositionFile: '/project/src/index.tsx',
+ compositionId: 'MyComp',
+ from: null,
+ element: {
+ type: 'solid',
+ width: 1280,
+ height: 720,
+ position: null,
+ },
+ },
+ });
const output = updated.files['/project/src/index.tsx'];
expect(output).toContain(
@@ -2057,7 +2081,7 @@ export const Comp = () => (
]),
).toEqual({
success: false,
- reason: 'Effect index is out of range',
+ reason: 'Cannot duplicate effect: not-found',
stack: expect.any(String),
});
expect(
diff --git a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
index 85325885e6..e6246c91db 100644
--- a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
@@ -393,21 +393,6 @@ test('previews and duplicates compositions as an undoable project mutation', asy
expect(project.files['/project/src/Composition.tsx']).toBe(
initialProject.files['/project/src/Composition.tsx'],
);
-
- const stillResult = await operations.duplicateComposition({
- ...request,
- codemod: {...request.codemod, newId: 'MyStill', tag: 'Still'},
- dryRun: false,
- });
- expect(stillResult.success).toBe(true);
- const stillSource =
- project.files['/project/src/Composition.tsx'].match(
- /<Still[\s\S]*?\/>/,
- )?.[0];
- expect(stillSource).toContain('id="MyStill"');
- expect(stillSource).toContain('width={1920}');
- expect(stillSource).not.toContain('fps=');
- expect(stillSource).not.toContain('durationInFrames=');
});
test('imports an Element with pinned Remotion dependencies as one undoable mutation', async () => {
diff --git a/packages/codemods/src/add-canvas-capture-composition.ts b/packages/codemods/src/add-canvas-capture-composition.ts
new file mode 100644
index 0000000000..19fa17c0f2
--- /dev/null
+++ b/packages/codemods/src/add-canvas-capture-composition.ts
@@ -0,0 +1,117 @@
+import type {JSXElement} from '@babel/types';
+import type {CanvasCaptureData} from '@remotion/studio-shared';
+import * as recast from 'recast';
+import {
+ getCodemodResult,
+ type CodemodProject,
+ type CodemodResult,
+} from './codemod-project';
+import {
+ assertNewCompositionId,
+ validateMetadata,
+ type CompositionTarget,
+ type CompositionMetadata,
+ type FolderReference,
+} from './composition-editing';
+import {generateCanvasCaptureComposition} from './generate-canvas-capture-composition';
+import {findProjectFile} from './internals';
+import {getRegistrationInsertionSourceEdit} from './registration-source-edits';
+import {ensureNamedImport} from './sequence-props/imports';
+import {parseAst} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+} from './source-edits';
+
+export type AddCanvasCaptureCompositionOptions<Project extends CodemodProject> =
+ CompositionTarget & {
+ project: Project;
+ component: {filePath: string; importName: string; importPath: string};
+ metadata: CompositionMetadata;
+ folder?: FolderReference;
+ capture: {
+ data: CanvasCaptureData;
+ keyframeFps: number;
+ videoFileName: string;
+ videoHeight: number;
+ videoWidth: number;
+ };
+ };
+
+export const addCanvasCaptureComposition = <Project extends CodemodProject>({
+ project,
+ compositionFile,
+ compositionId,
+ component,
+ metadata,
+ folder,
+ capture,
+}: AddCanvasCaptureCompositionOptions<Project>): CodemodResult<Project> => {
+ assertNewCompositionId({project, compositionFile, compositionId});
+ validateMetadata(metadata);
+ if (!/^[A-Z_$][\w$]*$/.test(component.importName)) {
+ throw new Error(
+ 'component.importName must be a named component export beginning with an uppercase letter, _ or $',
+ );
+ }
+
+ if (project.files[component.filePath] !== undefined) {
+ throw new Error(
+ `Cannot create ${component.filePath} because it already exists`,
+ );
+ }
+
+ const filePath = findProjectFile({project, filePath: compositionFile});
+ const input = project.files[filePath];
+ const ast = parseAst(input);
+ const snapshots = captureImportSnapshots(ast);
+ const componentName = ensureNamedImport({
+ ast,
+ importedName: component.importName,
+ sourcePath: component.importPath,
+ localName: component.importName,
+ });
+ const b = recast.types.builders;
+ const insertion = b.jsxElement(
+ b.jsxOpeningElement(b.jsxIdentifier(componentName), [], true),
+ null,
+ [],
+ );
+ const output = applySourceEdits({
+ input,
+ edits: [
+ getRegistrationInsertionSourceEdit({
+ input,
+ ast,
+ insertion: insertion as JSXElement,
+ folder: folder ?? null,
+ }),
+ ...getInsertImportSourceEdits({
+ ast,
+ input,
+ snapshots,
+ prettierConfigOverride: null,
+ }),
+ ],
+ });
+ const componentSource = generateCanvasCaptureComposition({
+ componentName: component.importName,
+ compositionId,
+ ...metadata,
+ ...capture,
+ });
+ parseAst(output);
+ parseAst(componentSource);
+ return getCodemodResult({
+ project,
+ nextProject: {
+ ...project,
+ files: {
+ ...project.files,
+ [filePath]: output,
+ [component.filePath]: componentSource,
+ },
+ },
+ });
+};
diff --git a/packages/codemods/src/add-composition.ts b/packages/codemods/src/add-composition.ts
index 19e942574d..c2b1efdb34 100644
--- a/packages/codemods/src/add-composition.ts
+++ b/packages/codemods/src/add-composition.ts
@@ -1,12 +1,23 @@
+import type {JSXElement} from '@babel/types';
+import * as recast from 'recast';
import type {CodemodProject, CodemodResult} from './codemod-project';
+import {getCodemodResult} from './codemod-project';
import {
type CompositionTarget,
type CompositionMetadata,
type FolderReference,
assertNewCompositionId,
validateMetadata,
- editCompositionProject,
} from './composition-editing';
+import {findProjectFile} from './internals';
+import {getRegistrationInsertionSourceEdit} from './registration-source-edits';
+import {ensureNamedImport} from './sequence-props/imports';
+import {parseAst} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+} from './source-edits';
export type AddCompositionOptions<Project extends CodemodProject> =
CompositionTarget & {
@@ -32,21 +43,65 @@ export const addComposition = <Project extends CodemodProject>({
);
}
- return editCompositionProject({
+ const filePath = findProjectFile({project, filePath: compositionFile});
+ const input = project.files[filePath];
+ const ast = parseAst(input);
+ const snapshots = captureImportSnapshots(ast);
+ const tag = ensureNamedImport({
+ ast,
+ importedName: 'Composition',
+ sourcePath: 'remotion',
+ localName: 'Composition',
+ });
+ const componentName = ensureNamedImport({
+ ast,
+ importedName: component.importName,
+ sourcePath: component.importPath,
+ localName: component.importName,
+ });
+ const b = recast.types.builders;
+ const insertion = b.jsxElement(
+ b.jsxOpeningElement(
+ b.jsxIdentifier(tag),
+ [
+ b.jsxAttribute(b.jsxIdentifier('id'), b.stringLiteral(compositionId)),
+ b.jsxAttribute(
+ b.jsxIdentifier('component'),
+ b.jsxExpressionContainer(b.identifier(componentName)),
+ ),
+ ...(['durationInFrames', 'fps', 'width', 'height'] as const).map(
+ (name) =>
+ b.jsxAttribute(
+ b.jsxIdentifier(name),
+ b.jsxExpressionContainer(b.numericLiteral(metadata[name])),
+ ),
+ ),
+ ],
+ true,
+ ),
+ null,
+ [],
+ );
+ const output = applySourceEdits({
+ input,
+ edits: [
+ getRegistrationInsertionSourceEdit({
+ input,
+ ast,
+ insertion: insertion as JSXElement,
+ folder: folder ?? null,
+ }),
+ ...getInsertImportSourceEdits({
+ ast,
+ input,
+ snapshots,
+ prettierConfigOverride: null,
+ }),
+ ],
+ });
+ parseAst(output);
+ return getCodemodResult({
project,
- compositionFile,
- codemod: {
- type: 'new-composition',
- newId: compositionId,
- componentName: component.importName,
- componentImportPath: component.importPath,
- newWidth: metadata.width,
- newHeight: metadata.height,
- newFps: metadata.fps,
- newDurationInFrames: metadata.durationInFrames,
- folderName: folder?.name ?? null,
- parentName: folder?.parentName ?? null,
- canvasCapture: null,
- },
+ nextProject: {...project, files: {...project.files, [filePath]: output}},
});
};
diff --git a/packages/codemods/src/add-folder.ts b/packages/codemods/src/add-folder.ts
index 65c469b783..5c0c946436 100644
--- a/packages/codemods/src/add-folder.ts
+++ b/packages/codemods/src/add-folder.ts
@@ -1,9 +1,17 @@
+import * as recast from 'recast';
import type {CodemodProject} from './codemod-project';
-import {
- type FolderReference,
- editCompositionProject,
-} from './composition-editing';
+import {getCodemodResult} from './codemod-project';
+import type {FolderReference} from './composition-editing';
import {getTreeEntries, requireTreeItem} from './folder-editing';
+import {findProjectFile} from './internals';
+import {getRegistrationInsertionSourceEdit} from './registration-source-edits';
+import {ensureNamedImport} from './sequence-props/imports';
+import {parseAst} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+} from './source-edits';
export type AddFolderOptions<Project extends CodemodProject> = {
project: Project;
@@ -20,7 +28,10 @@ export const addFolder = <Project extends CodemodProject>({
throw new Error('Folder names must be non-empty and cannot contain /');
}
- const entries = getTreeEntries({project, compositionFile});
+ const filePath = findProjectFile({project, filePath: compositionFile});
+ const input = project.files[filePath];
+ const ast = parseAst(input);
+ const entries = getTreeEntries({ast});
if (
entries.some(
({item}) =>
@@ -42,13 +53,51 @@ export const addFolder = <Project extends CodemodProject>({
});
}
- return editCompositionProject({
+ const snapshots = captureImportSnapshots(ast);
+ const localName = ensureNamedImport({
+ ast,
+ importedName: 'Folder',
+ sourcePath: 'remotion',
+ localName: 'Folder',
+ });
+ const b = recast.types.builders;
+ const insertion = b.jsxElement(
+ b.jsxOpeningElement(
+ b.jsxIdentifier(localName),
+ [b.jsxAttribute(b.jsxIdentifier('name'), b.stringLiteral(folder.name))],
+ true,
+ ),
+ null,
+ [],
+ );
+ const parentParts = folder.parentName?.split('/') ?? [];
+ const parentName = parentParts.pop();
+ const nextContents = applySourceEdits({
+ input,
+ edits: [
+ getRegistrationInsertionSourceEdit({
+ input,
+ ast,
+ insertion: insertion as never,
+ folder:
+ parentName === undefined
+ ? null
+ : {name: parentName, parentName: parentParts.join('/') || null},
+ }),
+ ...getInsertImportSourceEdits({
+ ast,
+ input,
+ snapshots,
+ prettierConfigOverride: null,
+ }),
+ ],
+ });
+ parseAst(nextContents);
+ return getCodemodResult({
project,
- compositionFile,
- codemod: {
- type: 'new-folder',
- folderName: folder.name,
- parentName: folder.parentName,
+ nextProject: {
+ ...project,
+ files: {...project.files, [filePath]: nextContents},
},
});
};
diff --git a/packages/codemods/src/composition-editing.ts b/packages/codemods/src/composition-editing.ts
index 9002b3be5a..c06c279db0 100644
--- a/packages/codemods/src/composition-editing.ts
+++ b/packages/codemods/src/composition-editing.ts
@@ -1,12 +1,7 @@
-import type {RecastCodemod} from '@remotion/studio-shared';
-import type {CodemodProject, CodemodResult} from './codemod-project';
-import {getCodemodResult} from './codemod-project';
+import type {CodemodProject} from './codemod-project';
import {getJsxNodeProps} from './get-jsx-node-props';
import {getJsxNodes} from './get-jsx-nodes';
-import {findProjectFile} from './internals';
-import {parseAndApplyCodemod} from './parse-and-apply-codemod';
import type {ResolveCompositionComponentOptions} from './resolve-composition-component';
-import {parseAst} from './sequence-props/parse-ast';
export type CompositionTarget = {
compositionFile: string;
@@ -35,12 +30,21 @@ const getCompositionNodes = ({
return getJsxNodes({project, filePath: compositionFile})
.filter(
(node) =>
- (node.tagName === 'Composition' || node.tagName === 'Still') &&
- node.componentIdentity === `dev.remotion.remotion.${node.tagName}`,
+ node.componentIdentity === 'dev.remotion.remotion.Composition' ||
+ node.componentIdentity === 'dev.remotion.remotion.Still',
)
.map((node) => {
const status = getJsxNodeProps({project, node, keys: ['id']}).props.id;
- return {node, id: status.status === 'static' ? status.codeValue : null};
+ return {
+ node: {
+ ...node,
+ tagName:
+ node.componentIdentity === 'dev.remotion.remotion.Still'
+ ? 'Still'
+ : 'Composition',
+ },
+ id: status.status === 'static' ? status.codeValue : null,
+ };
});
};
@@ -100,28 +104,3 @@ export const validateMetadata = (metadata: Partial<CompositionMetadata>) => {
}
}
};
-
-export const editCompositionProject = <Project extends CodemodProject>({
- project,
- compositionFile,
- codemod,
-}: {
- project: Project;
- compositionFile: string;
- codemod: RecastCodemod;
-}): CodemodResult<Project> => {
- const filePath = findProjectFile({project, filePath: compositionFile});
-
- const {newContents} = parseAndApplyCodemod({
- input: project.files[filePath],
- codeMod: codemod,
- });
- parseAst(newContents);
- return getCodemodResult({
- project,
- nextProject: {
- ...project,
- files: {...project.files, [filePath]: newContents},
- },
- });
-};
diff --git a/packages/codemods/src/composition-source-edits.ts b/packages/codemods/src/composition-source-edits.ts
deleted file mode 100644
index fb585a5f2c..0000000000
--- a/packages/codemods/src/composition-source-edits.ts
+++ /dev/null
@@ -1,314 +0,0 @@
-import type {JSXElement} from '@babel/types';
-import type {RecastCodemod} from '@remotion/studio-shared';
-import {namedTypes} from 'ast-types';
-import * as recast from 'recast';
-import {getNodeSourceEdit} from './delete-jsx-nodes-internal';
-import {getCompositionId} from './duplicate-composition-in-source';
-import {getInsertionRootSourceEdit} from './insert-jsx-element';
-import {printInsertedJsx} from './print-jsx';
-import {recastLocToOffset} from './recast-loc-to-offset';
-import {applyCodemod, type Change} from './recast-mods';
-import {ensureNamedImport} from './sequence-props/imports';
-import {parseAst} from './sequence-props/parse-ast';
-import {
- applySourceEdits,
- captureImportSnapshots,
- getInsertImportSourceEdits,
- getJsxStringAttributeValueSourceEdit,
- type SourceEdit,
-} from './source-edits';
-import {getEndOfLine, getIndentationUnit, getLineIndent} from './source-style';
-
-export const editCompositionInSource = ({
- input,
- codeMod,
-}: {
- input: string;
- codeMod: Extract<
- RecastCodemod,
- {
- type:
- | 'new-composition'
- | 'rename-composition'
- | 'delete-composition'
- | 'update-composition-metadata';
- }
- >;
-}): {newContents: string; changesMade: Change[]} => {
- const ast = parseAst(input);
- const edits: SourceEdit[] = [];
- let changesMade: Change[] = [];
- if (codeMod.type === 'new-composition') {
- const snapshots = captureImportSnapshots(ast);
- const result = applyCodemod({file: ast, codeMod});
- changesMade = result.changesMade;
- const {newAst} = result;
- const tag =
- codeMod.canvasCapture === null
- ? ensureNamedImport({
- ast: newAst,
- importedName: 'Composition',
- sourcePath: 'remotion',
- localName: 'Composition',
- })
- : null;
- const component = ensureNamedImport({
- ast: newAst,
- importedName: codeMod.componentName,
- sourcePath: codeMod.componentImportPath,
- localName: codeMod.componentName,
- });
- recast.types.visit(newAst, {
- visitNode(path) {
- const {node} = path;
- if (
- !namedTypes.JSXElement.check(node) &&
- !namedTypes.JSXFragment.check(node)
- ) {
- this.traverse(path);
- return undefined;
- }
-
- const inserted = node.children?.find(
- (child) => child.type === 'JSXElement' && !child.loc,
- );
- if (!inserted || inserted.type !== 'JSXElement') {
- this.traverse(path);
- return undefined;
- }
-
- inserted.openingElement.name = recast.types.builders.jsxIdentifier(
- tag ?? component,
- );
- if (tag !== null) {
- const attribute = inserted.openingElement.attributes?.find(
- (attr) =>
- attr.type === 'JSXAttribute' && attr.name.name === 'component',
- );
- if (attribute?.type === 'JSXAttribute') {
- attribute.value = recast.types.builders.jsxExpressionContainer(
- recast.types.builders.identifier(component),
- );
- }
- }
-
- // A newly generated fragment wraps the existing lone root.
- const root = node.loc
- ? node
- : node.children?.find(
- (child) => child.type === 'JSXElement' && child.loc,
- );
- if (
- !root ||
- (root.type !== 'JSXElement' && root.type !== 'JSXFragment')
- ) {
- throw new Error('Could not locate the composition insertion target');
- }
-
- edits.push(
- getInsertionRootSourceEdit({
- input,
- insertion: printInsertedJsx({
- element: inserted,
- input,
- prettierConfigOverride: null,
- }),
- root,
- nullRoot: null,
- prettierConfigOverride: null,
- insertInside: Boolean(node.loc),
- }),
- );
- return false;
- },
- });
- edits.push(
- ...getInsertImportSourceEdits({
- ast: newAst,
- input,
- snapshots,
- prettierConfigOverride: null,
- }),
- );
- } else {
- recast.types.visit(ast, {
- visitJSXElement(path) {
- const element = path.node as unknown as JSXElement;
- const compositionId =
- codeMod.type === 'rename-composition'
- ? codeMod.idToRename
- : codeMod.type === 'delete-composition'
- ? codeMod.idToDelete
- : codeMod.idToUpdate;
- if (getCompositionId(element) !== compositionId) {
- this.traverse(path);
- return undefined;
- }
-
- if (codeMod.type === 'delete-composition') {
- edits.push(
- getNodeSourceEdit({input, jsxPath: path as recast.types.NodePath}),
- );
- changesMade.push({description: 'Deleted composition'});
- return false;
- }
-
- if (codeMod.type === 'update-composition-metadata') {
- const metadata = [
- {name: 'fps', value: codeMod.newFps, description: 'FPS'},
- {
- name: 'durationInFrames',
- value: codeMod.newDurationInFrames,
- description: 'durationInFrames',
- },
- {name: 'width', value: codeMod.newWidth, description: 'width'},
- {name: 'height', value: codeMod.newHeight, description: 'height'},
- ] as const;
- const existingMetadata = new Set<string>();
-
- for (const metadataAttribute of element.openingElement.attributes) {
- if (
- metadataAttribute.type !== 'JSXAttribute' ||
- metadataAttribute.name.type !== 'JSXIdentifier'
- ) {
- continue;
- }
-
- const update = metadata.find(
- (item) => item.name === metadataAttribute.name.name,
- );
- if (!update || update.value === null) {
- continue;
- }
-
- existingMetadata.add(update.name);
- if (metadataAttribute.value?.loc) {
- edits.push({
- start: recastLocToOffset(
- input,
- metadataAttribute.value.loc.start,
- ),
- end: recastLocToOffset(input, metadataAttribute.value.loc.end),
- replacement: `{${update.value}}`,
- });
- } else if (metadataAttribute.loc) {
- const offset = recastLocToOffset(
- input,
- metadataAttribute.loc.end,
- );
- edits.push({
- start: offset,
- end: offset,
- replacement: `={${update.value}}`,
- });
- } else {
- throw new Error(
- `Could not locate the "${update.name}" attribute`,
- );
- }
-
- changesMade.push({
- description: `Replaced ${update.description}`,
- });
- }
-
- const missingMetadata = metadata.filter(
- (item) => item.value !== null && !existingMetadata.has(item.name),
- );
- if (missingMetadata.length > 0) {
- const {openingElement} = element;
- if (!openingElement.loc || !openingElement.name.loc) {
- throw new Error(
- 'Could not locate the composition opening element',
- );
- }
-
- const openingEnd = recastLocToOffset(input, openingElement.loc.end);
- const closingStart =
- openingEnd - (openingElement.selfClosing ? 2 : 1);
- const lastAttribute = openingElement.attributes.findLast(
- (candidate) => candidate.loc,
- );
- const anchor =
- lastAttribute?.loc?.end ?? openingElement.name.loc.end;
- const anchorOffset = recastLocToOffset(input, anchor);
- const rendered = missingMetadata.map(
- (item) => `${item.name}={${item.value}}`,
- );
-
- if (input.slice(anchorOffset, closingStart).includes('\n')) {
- const closingLineStart =
- input.lastIndexOf('\n', closingStart - 1) + 1;
- const attributeIndent =
- lastAttribute?.loc &&
- lastAttribute.loc.start.line > openingElement.name.loc.end.line
- ? getLineIndent({
- input,
- offset: recastLocToOffset(input, lastAttribute.loc.start),
- })
- : getLineIndent({
- input,
- offset: recastLocToOffset(
- input,
- openingElement.loc.start,
- ),
- }) + getIndentationUnit(input, null);
- const endOfLine = getEndOfLine(input);
- edits.push({
- start: closingLineStart,
- end: closingLineStart,
- replacement:
- rendered
- .map(
- (renderedAttribute) =>
- `${attributeIndent}${renderedAttribute}`,
- )
- .join(endOfLine) + endOfLine,
- });
- } else {
- edits.push({
- start: anchorOffset,
- end: anchorOffset,
- replacement: ` ${rendered.join(' ')}`,
- });
- }
-
- for (const item of missingMetadata) {
- changesMade.push({description: `Added ${item.description}`});
- }
- }
-
- return false;
- }
-
- const idAttribute = element.openingElement.attributes.find(
- (attr) =>
- attr.type === 'JSXAttribute' &&
- attr.name.type === 'JSXIdentifier' &&
- attr.name.name === 'id',
- );
- if (idAttribute?.type !== 'JSXAttribute') {
- throw new Error('Could not locate the composition id');
- }
-
- edits.push(
- getJsxStringAttributeValueSourceEdit({
- attribute: idAttribute,
- input,
- newValue: codeMod.newId,
- }),
- );
- changesMade.push({description: 'Replaced composition id'});
- return false;
- },
- });
- }
-
- if (changesMade.length === 0) {
- throw new Error(
- 'Unable to calculate the changes needed for this file. Edit the file manually.',
- );
- }
-
- return {newContents: applySourceEdits({input, edits}), changesMade};
-};
diff --git a/packages/codemods/src/delete-composition.ts b/packages/codemods/src/delete-composition.ts
index 8a0ea03d6e..d63aedebbb 100644
--- a/packages/codemods/src/delete-composition.ts
+++ b/packages/codemods/src/delete-composition.ts
@@ -1,9 +1,15 @@
import type {CodemodProject, CodemodResult} from './codemod-project';
+import {getCodemodResult} from './codemod-project';
import {
type CompositionTarget,
requireComposition,
- editCompositionProject,
} from './composition-editing';
+import {
+ findJsxElementPathForDeletion,
+ getNodeSourceEdit,
+} from './delete-jsx-nodes-internal';
+import {parseAst} from './sequence-props/parse-ast';
+import {applySourceEdits} from './source-edits';
export type DeleteCompositionOptions<Project extends CodemodProject> =
CompositionTarget & {project: Project};
@@ -13,10 +19,23 @@ export const deleteComposition = <Project extends CodemodProject>({
compositionFile,
compositionId,
}: DeleteCompositionOptions<Project>): CodemodResult<Project> => {
- requireComposition({project, compositionFile, compositionId});
- return editCompositionProject({
+ const node = requireComposition({project, compositionFile, compositionId});
+ const input = project.files[node.filePath];
+ const ast = parseAst(input);
+ const jsxPath = findJsxElementPathForDeletion(ast, node.nodePath);
+ if (!jsxPath) {
+ throw new Error('Could not locate the composition to delete');
+ }
+
+ const output = applySourceEdits({
+ input,
+ edits: [getNodeSourceEdit({input, jsxPath})],
+ });
+ return getCodemodResult({
project,
- compositionFile,
- codemod: {type: 'delete-composition', idToDelete: compositionId},
+ nextProject: {
+ ...project,
+ files: {...project.files, [node.filePath]: output},
+ },
});
};
diff --git a/packages/codemods/src/duplicate-composition-in-source.ts b/packages/codemods/src/duplicate-composition-in-source.ts
index f02a13a46d..a6d5b8a13d 100644
--- a/packages/codemods/src/duplicate-composition-in-source.ts
+++ b/packages/codemods/src/duplicate-composition-in-source.ts
@@ -1,12 +1,8 @@
-import type {
- Expression,
- JSXAttribute,
- JSXElement,
- JSXIdentifier,
- JSXOpeningElement,
-} from '@babel/types';
-import type {RecastCodemod} from '@remotion/studio-shared';
+import type {JSXAttribute, JSXElement, JSXOpeningElement} from '@babel/types';
import * as recast from 'recast';
+import type {SequenceNodePath} from 'remotion';
+import type {CompositionMetadata} from './composition-editing';
+import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';
import {getInsertionRootSourceEdit} from './insert-jsx-element';
import {indentInsertedJsx, printInsertedJsx} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
@@ -21,75 +17,20 @@ import {
const b = recast.types.builders;
-type DuplicateCompositionCodemod = Extract<
- RecastCodemod,
- {type: 'duplicate-composition'}
->;
-
-export const getCompositionId = (jsxElement: JSXElement) => {
- const {openingElement} = jsxElement;
- if (
- openingElement.name.type !== 'JSXIdentifier' ||
- (openingElement.name.name !== 'Composition' &&
- openingElement.name.name !== 'Still')
- ) {
- return null;
- }
-
- for (const attribute of openingElement.attributes) {
- const value = attribute.type === 'JSXAttribute' ? attribute.value : null;
- if (
- attribute.type !== 'JSXAttribute' ||
- attribute.name.type !== 'JSXIdentifier' ||
- attribute.name.name !== 'id' ||
- !value
- ) {
- continue;
- }
-
- if (value.type === 'StringLiteral') {
- return value.value;
- }
-
- if (
- value.type === 'JSXExpressionContainer' &&
- value.expression.type === 'StringLiteral'
- ) {
- return value.expression.value;
- }
- }
-
- return null;
-};
-
-const jsxId = (name: string): JSXIdentifier => ({type: 'JSXIdentifier', name});
-
-const jsxAttributeWithExpression = (
- name: string,
- expression: Expression,
-): JSXAttribute => ({
- type: 'JSXAttribute',
- name: jsxId(name),
- value: {
- type: 'JSXExpressionContainer',
- expression,
- },
-});
-
const changeComposition = ({
jsxElement,
- codemod,
- changesMade,
+ newId,
+ tag,
+ tagName,
+ metadata,
}: {
jsxElement: JSXElement;
- codemod: DuplicateCompositionCodemod;
- changesMade: {description: string}[];
+ newId: string;
+ tag: 'Composition' | 'Still';
+ tagName: string;
+ metadata: Partial<CompositionMetadata>;
}): JSXElement => {
const {openingElement} = jsxElement;
- const {name} = openingElement;
- if (name.type !== 'JSXIdentifier') {
- return jsxElement;
- }
const attributes = openingElement.attributes
.map((attribute) => {
@@ -101,11 +42,10 @@ const changeComposition = ({
}
if (
- codemod.tag === 'Still' &&
+ tag === 'Still' &&
(attribute.name.name === 'fps' ||
attribute.name.name === 'durationInFrames')
) {
- changesMade.push({description: `Removed ${attribute.name.name}`});
return null;
}
@@ -113,10 +53,9 @@ const changeComposition = ({
attribute.name.name === 'id' &&
attribute.value?.type === 'StringLiteral'
) {
- changesMade.push({description: 'Replaced composition id'});
return {
...attribute,
- value: {...attribute.value, value: codemod.newId},
+ value: {...attribute.value, value: newId},
};
}
@@ -125,14 +64,13 @@ const changeComposition = ({
attribute.value?.type === 'JSXExpressionContainer' &&
attribute.value.expression.type === 'StringLiteral'
) {
- changesMade.push({description: 'Replaced composition id'});
return {
...attribute,
value: {
...attribute.value,
expression: {
...attribute.value.expression,
- value: codemod.newId,
+ value: newId,
},
},
};
@@ -140,19 +78,18 @@ const changeComposition = ({
const newValue =
attribute.name.name === 'fps'
- ? codemod.newFps
+ ? (metadata.fps ?? null)
: attribute.name.name === 'durationInFrames'
- ? codemod.newDurationInFrames
+ ? (metadata.durationInFrames ?? null)
: attribute.name.name === 'width'
- ? codemod.newWidth
+ ? (metadata.width ?? null)
: attribute.name.name === 'height'
- ? codemod.newHeight
+ ? (metadata.height ?? null)
: null;
if (newValue === null) {
return attribute;
}
- changesMade.push({description: `Replaced ${attribute.name.name}`});
return {
...attribute,
value: b.jsxExpressionContainer(
@@ -165,14 +102,14 @@ const changeComposition = ({
) as JSXOpeningElement['attributes'];
for (const [nameToAdd, value] of [
- ['fps', codemod.newFps],
- ['durationInFrames', codemod.newDurationInFrames],
- ['width', codemod.newWidth],
- ['height', codemod.newHeight],
+ ['fps', metadata.fps ?? null],
+ ['durationInFrames', metadata.durationInFrames ?? null],
+ ['width', metadata.width ?? null],
+ ['height', metadata.height ?? null],
] as const) {
if (
value === null ||
- (codemod.tag === 'Still' &&
+ (tag === 'Still' &&
(nameToAdd === 'fps' || nameToAdd === 'durationInFrames')) ||
attributes.some(
(attribute) =>
@@ -184,27 +121,25 @@ const changeComposition = ({
continue;
}
- changesMade.push({description: `Added ${nameToAdd}`});
attributes.push(
- jsxAttributeWithExpression(
- nameToAdd,
- b.numericLiteral(value) as Expression,
- ),
+ b.jsxAttribute(
+ b.jsxIdentifier(nameToAdd),
+ b.jsxExpressionContainer(b.numericLiteral(value)),
+ ) as JSXAttribute,
);
}
- if (codemod.tag !== name.name) {
- changesMade.push({description: 'Changed tag'});
- }
-
return {
...jsxElement,
closingElement: jsxElement.closingElement
- ? {...jsxElement.closingElement, name: {...name, name: codemod.tag}}
+ ? {
+ ...jsxElement.closingElement,
+ name: {type: 'JSXIdentifier', name: tagName},
+ }
: null,
openingElement: {
...openingElement,
- name: {...name, name: codemod.tag},
+ name: {type: 'JSXIdentifier', name: tagName},
attributes,
},
};
@@ -212,97 +147,80 @@ const changeComposition = ({
export const duplicateCompositionInSource = ({
input,
- codemod,
+ nodePath,
+ newId,
+ tag,
+ metadata,
}: {
input: string;
- codemod: DuplicateCompositionCodemod;
-}): {newContents: string; changesMade: {description: string}[]} => {
+ nodePath: SequenceNodePath;
+ newId: string;
+ tag: 'Composition' | 'Still';
+ metadata: Partial<CompositionMetadata>;
+}): string => {
const ast = parseAst(input);
- const changesMade: {description: string}[] = [];
- const edits: SourceEdit[] = [];
const snapshots = captureImportSnapshots(ast);
-
- recast.types.visit(ast, {
- visitJSXElement(astPath) {
- const original = astPath.node as unknown as JSXElement;
- if (getCompositionId(original) !== codemod.idToDuplicate) {
- this.traverse(astPath);
- return undefined;
- }
-
- const duplicate = changeComposition({
- jsxElement: original,
- codemod,
- changesMade,
- });
- if (!original.loc) {
- throw new Error('Could not locate the composition to duplicate');
- }
-
- const insertion = printInsertedJsx({
- element: duplicate as never,
- input,
- prettierConfigOverride: null,
- });
- const parent = astPath.parentPath?.node;
- if (
- parent &&
- (parent.type === 'JSXElement' || parent.type === 'JSXFragment')
- ) {
- const end = recastLocToOffset(input, original.loc.end);
- const start = recastLocToOffset(input, original.loc.start);
- const lineStart = input.lastIndexOf('\n', start - 1) + 1;
- const indent =
- input.slice(lineStart, start).match(/^[\t ]*/)?.[0] ?? '';
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
- edits.push({
- start: end,
- end,
- replacement: endOfLine + indentInsertedJsx({indent, insertion}),
- });
- } else {
- edits.push(
- getInsertionRootSourceEdit({
- input,
- insertion,
- root: original as never,
- nullRoot: null,
- prettierConfigOverride: null,
- insertInside: false,
- }),
- );
- }
-
- return false;
- },
- });
-
- if (changesMade.length === 0) {
- throw new Error(
- `Could not find composition "${codemod.idToDuplicate}" to duplicate`,
- );
+ const astPath = findJsxElementPathForDeletion(ast, nodePath);
+ const original = astPath?.node as JSXElement | undefined;
+ if (!astPath || !original?.loc) {
+ throw new Error('Could not locate the composition to duplicate');
}
- ensureNamedImport({
+ const tagName = ensureNamedImport({
ast,
- importedName: codemod.tag,
+ importedName: tag,
sourcePath: 'remotion',
- localName: codemod.tag,
+ localName: tag,
});
-
- return {
- newContents: applySourceEdits({
+ const duplicate = changeComposition({
+ jsxElement: original,
+ newId,
+ tag,
+ tagName,
+ metadata,
+ });
+ const insertion = printInsertedJsx({
+ element: duplicate as never,
+ input,
+ prettierConfigOverride: null,
+ });
+ const parent = astPath.parentPath?.node;
+ let insertionEdit: SourceEdit;
+ if (
+ parent &&
+ (parent.type === 'JSXElement' || parent.type === 'JSXFragment')
+ ) {
+ const end = recastLocToOffset(input, original.loc.end);
+ const start = recastLocToOffset(input, original.loc.start);
+ const lineStart = input.lastIndexOf('\n', start - 1) + 1;
+ const indent = input.slice(lineStart, start).match(/^[\t ]*/)?.[0] ?? '';
+ const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
+ insertionEdit = {
+ start: end,
+ end,
+ replacement: endOfLine + indentInsertedJsx({indent, insertion}),
+ };
+ } else {
+ insertionEdit = getInsertionRootSourceEdit({
input,
- edits: [
- ...edits,
- ...getInsertImportSourceEdits({
- ast,
- input,
- snapshots,
- prettierConfigOverride: null,
- }),
- ],
- }),
- changesMade,
- };
+ insertion,
+ root: original as never,
+ nullRoot: null,
+ prettierConfigOverride: null,
+ insertInside: false,
+ });
+ }
+
+ return applySourceEdits({
+ input,
+ edits: [
+ insertionEdit,
+ ...getInsertImportSourceEdits({
+ ast,
+ input,
+ snapshots,
+ prettierConfigOverride: null,
+ }),
+ ],
+ });
};
diff --git a/packages/codemods/src/duplicate-composition.ts b/packages/codemods/src/duplicate-composition.ts
index 8a0e71f66c..0d347cc06a 100644
--- a/packages/codemods/src/duplicate-composition.ts
+++ b/packages/codemods/src/duplicate-composition.ts
@@ -1,12 +1,14 @@
import type {CodemodProject, CodemodResult} from './codemod-project';
+import {getCodemodResult} from './codemod-project';
import {
type CompositionTarget,
type CompositionMetadata,
requireComposition,
assertNewCompositionId,
validateMetadata,
- editCompositionProject,
} from './composition-editing';
+import {duplicateCompositionInSource} from './duplicate-composition-in-source';
+import {parseAst} from './sequence-props/parse-ast';
export type DuplicateCompositionOptions<Project extends CodemodProject> =
CompositionTarget & {
@@ -35,18 +37,19 @@ export const duplicateComposition = <Project extends CodemodProject>({
throw new Error('Still registrations do not have fps or durationInFrames');
}
- return editCompositionProject({
+ const output = duplicateCompositionInSource({
+ input: project.files[node.filePath],
+ nodePath: node.nodePath,
+ newId,
+ tag: newTag,
+ metadata,
+ });
+ parseAst(output);
+ return getCodemodResult({
project,
- compositionFile,
- codemod: {
- type: 'duplicate-composition',
- idToDuplicate: compositionId,
- newId,
- tag: newTag,
- newWidth: metadata.width ?? null,
- newHeight: metadata.height ?? null,
- newFps: metadata.fps ?? null,
- newDurationInFrames: metadata.durationInFrames ?? null,
+ nextProject: {
+ ...project,
+ files: {...project.files, [node.filePath]: output},
},
});
};
diff --git a/packages/codemods/src/folder-editing.ts b/packages/codemods/src/folder-editing.ts
index 9566f03718..9dab3c2ad6 100644
--- a/packages/codemods/src/folder-editing.ts
+++ b/packages/codemods/src/folder-editing.ts
@@ -1,18 +1,16 @@
-import type {JSXElement} from '@babel/types';
-import type {CompositionOrFolder, RecastCodemod} from '@remotion/studio-shared';
+import type {File, JSXElement} from '@babel/types';
import * as recast from 'recast';
import type {CodemodProject} from './codemod-project';
import {getCodemodResult} from './codemod-project';
-import {
- type FolderReference,
- editCompositionProject,
-} from './composition-editing';
+import type {FolderReference} from './composition-editing';
+import {getMoveTreeItemSourceEdits} from './folder-source-edits';
import {findProjectFile} from './internals';
import {
getCompositionIdFromJSXElement,
getFolderNameFromJSXElement,
-} from './recast-mods';
+} from './registration-source-edits';
import {parseAst} from './sequence-props/parse-ast';
+import {applySourceEdits} from './source-edits';
export type CompositionTreeItem =
| {type: 'composition'; compositionId: string}
@@ -23,37 +21,45 @@ export type CompositionDestination =
| {type: 'folder'; folder: FolderReference}
| {type: 'before' | 'after'; target: CompositionTreeItem};
-type TreeEntry = {item: CompositionTreeItem; parentName: string | null};
+export type TreeEntry = {
+ item: CompositionTreeItem;
+ parentName: string | null;
+ node: JSXElement;
+ path: recast.types.NodePath;
+ directJsxChild: boolean;
+};
-export const getTreeEntries = ({
- project,
- compositionFile,
-}: {
- project: CodemodProject;
- compositionFile: string;
-}): TreeEntry[] => {
- const filePath = findProjectFile({project, filePath: compositionFile});
- const ast = parseAst(project.files[filePath]);
+export const getTreeEntries = ({ast}: {ast: File}): TreeEntry[] => {
const entries: TreeEntry[] = [];
const folders: string[] = [];
recast.visit(ast, {
visitJSXElement(path) {
- const element = path.node as JSXElement;
- const name = getFolderNameFromJSXElement(element);
- const compositionId = getCompositionIdFromJSXElement(element);
+ const node = path.node as JSXElement;
+ const name = getFolderNameFromJSXElement(node, ast);
+ const compositionId = getCompositionIdFromJSXElement(node, ast);
const parentName = folders.join('/') || null;
- if (name !== null) {
- entries.push({item: {type: 'folder', name, parentName}, parentName});
- folders.push(name);
- } else if (compositionId) {
- entries.push({item: {type: 'composition', compositionId}, parentName});
+ const parent = path.parentPath?.node;
+ const item: CompositionTreeItem | null =
+ name !== null
+ ? {type: 'folder', name, parentName}
+ : compositionId !== null
+ ? {type: 'composition', compositionId}
+ : null;
+ if (item) {
+ entries.push({
+ item,
+ parentName,
+ node,
+ path: path as unknown as recast.types.NodePath,
+ directJsxChild:
+ (parent?.type === 'JSXElement' || parent?.type === 'JSXFragment') &&
+ parent.children.includes(node),
+ });
}
+ if (name !== null) folders.push(name);
this.traverse(path);
- if (name !== null) {
- folders.pop();
- }
-
+ if (name !== null) folders.pop();
return false;
},
});
@@ -81,11 +87,6 @@ export const requireTreeItem = (
return matches[0];
};
-const toSourceItem = (item: CompositionTreeItem): CompositionOrFolder =>
- item.type === 'composition'
- ? item
- : {type: 'folder', folderName: item.name, parentName: item.parentName};
-
export const moveTreeItem = <Project extends CodemodProject>({
project,
compositionFile,
@@ -97,48 +98,82 @@ export const moveTreeItem = <Project extends CodemodProject>({
source: CompositionTreeItem;
destination: CompositionDestination;
}) => {
- const entries = getTreeEntries({project, compositionFile});
+ const filePath = findProjectFile({project, filePath: compositionFile});
+ const input = project.files[filePath];
+ const entries = getTreeEntries({ast: parseAst(input)});
const entry = requireTreeItem(entries, source);
- let target: Extract<
- RecastCodemod,
- {type: 'move-composition-or-folder'}
- >['destination'];
- if (destination.type === 'folder') {
- requireTreeItem(entries, {type: 'folder', ...destination.folder});
- const parentPath = [destination.folder.parentName, destination.folder.name]
+ const target =
+ destination.type === 'root'
+ ? null
+ : requireTreeItem(
+ entries,
+ destination.type === 'folder'
+ ? {type: 'folder', ...destination.folder}
+ : destination.target,
+ );
+ const destinationParentName =
+ destination.type === 'folder'
+ ? [destination.folder.parentName, destination.folder.name]
+ .filter(Boolean)
+ .join('/')
+ : (target?.parentName ?? null);
+ if (source.type === 'folder') {
+ const sourcePath = [source.parentName, source.name]
.filter(Boolean)
.join('/');
- if (entry.parentName === parentPath) {
- return getCodemodResult({project, nextProject: project});
- }
-
- target = {
- type: 'folder',
- folderName: destination.folder.name,
- parentName: destination.folder.parentName,
- };
- } else if (destination.type === 'root') {
- if (entry.parentName === null) {
- return getCodemodResult({project, nextProject: project});
+ if (
+ destinationParentName === sourcePath ||
+ destinationParentName?.startsWith(`${sourcePath}/`)
+ ) {
+ throw new Error('A folder cannot be moved inside itself');
}
- target = destination;
- } else {
- const targetEntry = requireTreeItem(entries, destination.target);
- if (entry === targetEntry) {
- return getCodemodResult({project, nextProject: project});
+ if (
+ entries.some(
+ (candidate) =>
+ candidate !== entry &&
+ candidate.item.type === 'folder' &&
+ candidate.item.name === source.name &&
+ candidate.parentName === destinationParentName,
+ )
+ ) {
+ throw new Error(
+ `A folder named "${source.name}" already exists in the destination`,
+ );
}
+ }
- target = {type: destination.type, target: toSourceItem(destination.target)};
+ if (
+ entry === target ||
+ ((destination.type === 'folder' || destination.type === 'root') &&
+ entry.parentName === destinationParentName)
+ ) {
+ return getCodemodResult({project, nextProject: project});
}
- return editCompositionProject({
+ if (!entry.directJsxChild)
+ throw new Error(
+ 'Could not locate the JSX element to move as a direct JSX child',
+ );
+ if (target && !target.directJsxChild)
+ throw new Error(
+ 'Could not locate the JSX destination as a direct JSX child',
+ );
+ const nextContents = applySourceEdits({
+ input,
+ edits: getMoveTreeItemSourceEdits({
+ input,
+ source: entry,
+ target,
+ position: destination.type,
+ }),
+ });
+ parseAst(nextContents);
+ return getCodemodResult({
project,
- compositionFile,
- codemod: {
- type: 'move-composition-or-folder',
- source: toSourceItem(source),
- destination: target,
+ nextProject: {
+ ...project,
+ files: {...project.files, [filePath]: nextContents},
},
});
};
diff --git a/packages/codemods/src/folder-source-edits.ts b/packages/codemods/src/folder-source-edits.ts
index de56e21a2d..5f2ad1ca7a 100644
--- a/packages/codemods/src/folder-source-edits.ts
+++ b/packages/codemods/src/folder-source-edits.ts
@@ -1,129 +1,23 @@
import type {
ArrowFunctionExpression,
- File,
JSXElement,
JSXFragment,
ReturnStatement,
} from '@babel/types';
-import type {CompositionOrFolder, RecastCodemod} from '@remotion/studio-shared';
-import * as recast from 'recast';
+import type * as recast from 'recast';
import {getNodeSourceEdit} from './delete-jsx-nodes-internal';
+import type {TreeEntry} from './folder-editing';
import {getInsertionRootSourceEdit} from './insert-jsx-element';
-import {indentInsertedJsx, printInsertedJsx} from './print-jsx';
+import {indentInsertedJsx} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
-import {
- applyCodemod,
- type Change,
- getCompositionIdFromJSXElement,
- getFolderNameFromJSXElement,
-} from './recast-mods';
-import {ensureNamedImport} from './sequence-props/imports';
-import {parseAst} from './sequence-props/parse-ast';
import {
applySourceEdits,
- captureImportSnapshots,
getAdjacentJsxInsertionSourceEdit,
- getInsertImportSourceEdits,
getJsxElementSourceForInsertion,
- getJsxStringAttributeValueSourceEdit,
type SourceEdit,
} from './source-edits';
import {getEndOfLine, getIndentationUnit, getLineIndent} from './source-style';
-type FolderCodemod = Extract<
- RecastCodemod,
- {
- type:
- | 'delete-folder'
- | 'move-composition-or-folder'
- | 'move-composition-to-folder'
- | 'new-folder'
- | 'rename-folder';
- }
->;
-
-type LocatedItem = {
- directJsxChild: boolean;
- node: JSXElement;
- parentFolderName: string | null;
- path: recast.types.NodePath;
-};
-
-const getLocatedItems = (ast: File): LocatedItem[] => {
- const items: LocatedItem[] = [];
- const folderStack: string[] = [];
-
- const visitJsxElement = (path: recast.types.NodePath) => {
- const node = path.node as JSXElement;
- const parent = path.parentPath?.node;
- const parentFolderName = folderStack.join('/') || null;
- items.push({
- directJsxChild:
- (parent?.type === 'JSXElement' || parent?.type === 'JSXFragment') &&
- parent.children.includes(node),
- node,
- parentFolderName,
- path,
- });
-
- const folderName = getFolderNameFromJSXElement(node);
- if (folderName !== null) {
- folderStack.push(folderName);
- }
-
- for (let index = 0; index < node.children.length; index++) {
- if (node.children[index].type === 'JSXElement') {
- visitJsxElement(path.get('children', index) as recast.types.NodePath);
- }
- }
-
- if (folderName !== null) {
- folderStack.pop();
- }
- };
-
- recast.types.visit(ast, {
- visitJSXElement(path) {
- visitJsxElement(path as unknown as recast.types.NodePath);
- return false;
- },
- });
-
- return items;
-};
-
-const matchesItem = ({
- item,
- located,
-}: {
- item: CompositionOrFolder;
- located: LocatedItem;
-}) => {
- if (item.type === 'composition') {
- return getCompositionIdFromJSXElement(located.node) === item.compositionId;
- }
-
- return (
- getFolderNameFromJSXElement(located.node) === item.folderName &&
- located.parentFolderName === item.parentName
- );
-};
-
-const getFolder = ({
- folderName,
- items,
- parentName,
-}: {
- folderName: string;
- items: LocatedItem[];
- parentName: string | null;
-}) =>
- items.find(
- (item) =>
- getFolderNameFromJSXElement(item.node) === folderName &&
- item.parentFolderName === parentName,
- ) ?? null;
-
const getRegistrationRoot = (
path: recast.types.NodePath,
): JSXElement | JSXFragment => {
@@ -151,104 +45,6 @@ const getRegistrationRoot = (
throw new Error('Could not find a root JSX element');
};
-const getNewFolderSourceEdits = ({
- ast,
- input,
-}: {
- ast: File;
- input: string;
-}): SourceEdit[] => {
- const snapshots = captureImportSnapshots(ast);
- const localName = ensureNamedImport({
- ast,
- importedName: 'Folder',
- sourcePath: 'remotion',
- localName: 'Folder',
- });
- let insertionEdit: SourceEdit | null = null;
-
- recast.types.visit(ast, {
- visitNode(path) {
- const {node} = path;
- if (node.type !== 'JSXElement' && node.type !== 'JSXFragment') {
- this.traverse(path);
- return undefined;
- }
-
- const jsxNode = node as JSXElement | JSXFragment;
- const inserted = jsxNode.children.find(
- (child) =>
- child.type === 'JSXElement' &&
- !child.loc &&
- getFolderNameFromJSXElement(child) !== null,
- );
- if (!inserted || inserted.type !== 'JSXElement') {
- this.traverse(path);
- return undefined;
- }
-
- inserted.openingElement.name = recast.types.builders.jsxIdentifier(
- localName,
- ) as never;
- const root = jsxNode.loc
- ? jsxNode
- : jsxNode.children.find(
- (child) =>
- (child.type === 'JSXElement' || child.type === 'JSXFragment') &&
- child.loc,
- );
- if (
- !root ||
- (root.type !== 'JSXElement' && root.type !== 'JSXFragment')
- ) {
- throw new Error('Could not locate the folder insertion target');
- }
-
- insertionEdit = getInsertionRootSourceEdit({
- input,
- insertion: printInsertedJsx({
- element: inserted as never,
- input,
- prettierConfigOverride: null,
- }),
- root: root as never,
- nullRoot: null,
- prettierConfigOverride: null,
- insertInside: Boolean(jsxNode.loc),
- });
- return false;
- },
- });
-
- if (insertionEdit === null) {
- throw new Error('Could not locate the new folder');
- }
-
- return [
- insertionEdit,
- ...getInsertImportSourceEdits({
- ast,
- input,
- snapshots,
- prettierConfigOverride: null,
- }),
- ];
-};
-
-const getFolderNameAttribute = (folder: JSXElement) => {
- const attribute = folder.openingElement.attributes.find(
- (candidate) =>
- candidate.type === 'JSXAttribute' &&
- candidate.name.type === 'JSXIdentifier' &&
- candidate.name.name === 'name',
- );
- if (attribute?.type !== 'JSXAttribute') {
- throw new Error('Could not locate the folder name');
- }
-
- return attribute;
-};
-
const normalizeBlock = (source: string) => {
const lines = source.split(/\r?\n/);
while (lines[0]?.trim() === '') {
@@ -277,12 +73,12 @@ const normalizeBlock = (source: string) => {
const isMeaningfulChild = (child: JSXElement['children'][number]) =>
child.type !== 'JSXText' || child.value.trim() !== '';
-const getDeleteFolderSourceEdit = ({
+export const getUnwrapFolderSourceEdit = ({
input,
located,
}: {
input: string;
- located: LocatedItem;
+ located: TreeEntry;
}): SourceEdit => {
const {node, path} = located;
if (!node.loc) {
@@ -359,168 +155,90 @@ const getDeleteFolderSourceEdit = ({
};
};
-const getMoveSourceEdits = ({
- codeMod,
+export const getMoveTreeItemSourceEdits = ({
input,
- items,
+ source,
+ target,
+ position,
}: {
- codeMod: Extract<
- FolderCodemod,
- {type: 'move-composition-or-folder' | 'move-composition-to-folder'}
- >;
input: string;
- items: LocatedItem[];
+ source: TreeEntry;
+ target: TreeEntry | null;
+ position: 'root' | 'folder' | 'before' | 'after';
}): SourceEdit[] => {
- const source =
- codeMod.type === 'move-composition-to-folder'
- ? (items.find(
- (item) =>
- item.directJsxChild &&
- getCompositionIdFromJSXElement(item.node) === codeMod.idToMove,
- ) ?? null)
- : (items.find(
- (item) =>
- item.directJsxChild &&
- matchesItem({item: codeMod.source, located: item}),
- ) ?? null);
- if (source === null) {
- throw new Error('Could not locate the JSX element to move');
- }
-
+ const deletion = getNodeSourceEdit({input, jsxPath: source.path});
const insertion = getJsxElementSourceForInsertion({
element: source.node,
input,
});
- let insertionEdit: SourceEdit;
- if (codeMod.type === 'move-composition-to-folder') {
- if (codeMod.folderName === null) {
- const root = getRegistrationRoot(source.path);
- insertionEdit = getInsertionRootSourceEdit({
- input,
- insertion,
- root: root as never,
- nullRoot: null,
- prettierConfigOverride: null,
- insertInside: root.type === 'JSXFragment',
- });
- } else {
- const destination = getFolder({
- folderName: codeMod.folderName,
- items,
- parentName: codeMod.parentName,
- });
- if (destination === null) {
- throw new Error('Could not locate the destination folder');
- }
+ if (position === 'root') {
+ const root = getRegistrationRoot(source.path);
+ if (root.type === 'JSXElement') {
+ if (!root.loc) throw new Error('Could not locate the registration root');
+ const start = recastLocToOffset(input, root.loc.start);
+ const end = recastLocToOffset(input, root.loc.end);
+ const indent = getLineIndent({input, offset: start});
+ const unit = getIndentationUnit(input, null);
+ const removed = applySourceEdits({input, edits: [deletion]});
+ const rootSource = removed
+ .slice(
+ start,
+ end - (deletion.end - deletion.start) + deletion.replacement.length,
+ )
+ .split(/\r?\n/)
+ .map((line, index) =>
+ index > 0 && line.startsWith(indent)
+ ? line.slice(indent.length)
+ : line,
+ )
+ .join(getEndOfLine(input));
+ return [
+ {
+ start,
+ end,
+ replacement: [
+ '<>',
+ indentInsertedJsx({
+ indent: `${indent}${unit}`,
+ insertion: rootSource,
+ }),
+ indentInsertedJsx({indent: `${indent}${unit}`, insertion}),
+ `${indent}</>`,
+ ].join(getEndOfLine(input)),
+ },
+ ];
+ }
- insertionEdit = getInsertionRootSourceEdit({
+ return [
+ deletion,
+ getInsertionRootSourceEdit({
input,
insertion,
- root: destination.node as never,
+ root: root as never,
nullRoot: null,
prettierConfigOverride: null,
insertInside: true,
- });
- }
- } else if (codeMod.destination.type === 'root') {
- const root = getRegistrationRoot(source.path);
- insertionEdit = getInsertionRootSourceEdit({
- input,
- insertion,
- root: root as never,
- nullRoot: null,
- prettierConfigOverride: null,
- insertInside: root.type === 'JSXFragment',
- });
- } else if (codeMod.destination.type === 'folder') {
- const destination = getFolder({
- folderName: codeMod.destination.folderName,
- items,
- parentName: codeMod.destination.parentName,
- });
- if (destination === null) {
- throw new Error('Could not locate the destination folder');
- }
-
- insertionEdit = getInsertionRootSourceEdit({
- input,
- insertion,
- root: destination.node as never,
- nullRoot: null,
- prettierConfigOverride: null,
- insertInside: true,
- });
- } else {
- const {destination} = codeMod;
- const target =
- items.find(
- (item) =>
- item.directJsxChild &&
- matchesItem({item: destination.target, located: item}),
- ) ?? null;
- if (target === null) {
- throw new Error('Could not locate the JSX reorder target');
- }
-
- insertionEdit = getAdjacentJsxInsertionSourceEdit({
- input,
- insertion,
- position: destination.type,
- target: target.node,
- });
- }
-
- return [getNodeSourceEdit({input, jsxPath: source.path}), insertionEdit];
-};
-
-export const editFolderInSource = ({
- codeMod,
- input,
-}: {
- codeMod: FolderCodemod;
- input: string;
-}): {changesMade: Change[]; newContents: string} => {
- const ast = parseAst(input);
- const items = getLocatedItems(ast);
- const folder =
- codeMod.type === 'rename-folder' || codeMod.type === 'delete-folder'
- ? getFolder({
- folderName: codeMod.folderName,
- items,
- parentName: codeMod.parentName,
- })
- : null;
- const {newAst, changesMade} = applyCodemod({file: ast, codeMod});
- if (changesMade.length === 0) {
- throw new Error(
- 'Unable to calculate the changes needed for this file. Edit the file manually.',
- );
- }
-
- let edits: SourceEdit[];
- if (codeMod.type === 'new-folder') {
- edits = getNewFolderSourceEdits({ast: newAst, input});
- } else if (codeMod.type === 'rename-folder') {
- if (folder === null) {
- throw new Error('Could not locate the folder to rename');
- }
-
- edits = [
- getJsxStringAttributeValueSourceEdit({
- attribute: getFolderNameAttribute(folder.node),
- input,
- newValue: codeMod.newName,
}),
];
- } else if (codeMod.type === 'delete-folder') {
- if (folder === null) {
- throw new Error('Could not locate the folder to delete');
- }
-
- edits = [getDeleteFolderSourceEdit({input, located: folder})];
- } else {
- edits = getMoveSourceEdits({codeMod, input, items});
}
- return {changesMade, newContents: applySourceEdits({input, edits})};
+ if (target === null) throw new Error('Could not locate the JSX destination');
+ return [
+ deletion,
+ position === 'folder'
+ ? getInsertionRootSourceEdit({
+ input,
+ insertion,
+ root: target.node as never,
+ nullRoot: null,
+ prettierConfigOverride: null,
+ insertInside: true,
+ })
+ : getAdjacentJsxInsertionSourceEdit({
+ input,
+ insertion,
+ position,
+ target: target.node,
+ }),
+ ];
};
diff --git a/packages/codemods/src/generate-canvas-capture-composition.ts b/packages/codemods/src/generate-canvas-capture-composition.ts
index da70750c23..043591ad96 100644
--- a/packages/codemods/src/generate-canvas-capture-composition.ts
+++ b/packages/codemods/src/generate-canvas-capture-composition.ts
@@ -1,4 +1,4 @@
-import type {CanvasCaptureData, RecastCodemod} from '@remotion/studio-shared';
+import type {CanvasCaptureData} from '@remotion/studio-shared';
import * as recast from 'recast';
type FramedMouseMovement = CanvasCaptureData['mouseMovements'][number] & {
@@ -285,30 +285,3 @@ export const ${componentName} = () => {
};
`;
};
-
-export const makeNewCompositionComponentSource = (
- codemod: Extract<RecastCodemod, {type: 'new-composition'}>,
-) => {
- if (codemod.canvasCapture !== null) {
- return generateCanvasCaptureComposition({
- componentName: codemod.componentName,
- compositionId: codemod.newId,
- data: codemod.canvasCapture.data,
- durationInFrames: codemod.newDurationInFrames,
- fps: codemod.newFps,
- height: codemod.newHeight,
- keyframeFps: codemod.canvasCapture.keyframeFps,
- videoFileName: codemod.canvasCapture.videoFileName,
- videoHeight: codemod.canvasCapture.videoHeight,
- videoWidth: codemod.canvasCapture.videoWidth,
- width: codemod.newWidth,
- });
- }
-
- return `import React from 'react';
-
-export const ${codemod.componentName}: React.FC = () => {
- return null;
-};
-`;
-};
diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.ts
index a5c4a48cc3..6dca267b88 100644
--- a/packages/codemods/src/index.ts
+++ b/packages/codemods/src/index.ts
@@ -1,11 +1,9 @@
-import {applyVisualControl} from './apply-visual-control';
import {
basicCaptionsElementSource,
getBasicCaptionsElementFile,
} from './basic-captions-element-source';
import {enumerateEffectArrayElements, pasteEffects} from './effect-operations';
import {findSearchPosition} from './find-search-position';
-import {makeNewCompositionComponentSource} from './generate-canvas-capture-composition';
import {insertBasicCaptions} from './insert-basic-captions';
import {
insertJsxElementIntoComposition,
@@ -23,7 +21,6 @@ import {
getFolderFile,
getRootFileForProject,
} from './internals';
-import {parseAndApplyCodemod} from './parse-and-apply-codemod';
import {computeSequencePropsSubscriptionFromContent} from './sequence-props';
import {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';
import {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
@@ -164,7 +161,6 @@ export type {
export const CodemodsInternals = {
JsxElementIdentityMismatchError,
JsxElementNotFoundAtLocationError,
- applyVisualControl,
basicCaptionsElementSource,
computeCanUpdateDefaultPropsFromContent,
computeSequencePropsSubscriptionFromContent,
@@ -181,8 +177,6 @@ export const CodemodsInternals = {
insertJsxElementIntoComposition,
insertJsxElementIntoProjectWithNodePathRemappings,
insertVideoLayers,
- makeNewCompositionComponentSource,
- parseAndApplyCodemod,
pasteEffects,
resolveCompositionComponent,
resolveCompositionComponentWithFile,
@@ -190,3 +184,13 @@ export const CodemodsInternals = {
updateDefaultProps,
updateInlineCaptionPatches,
};
+
+export {
+ addCanvasCaptureComposition,
+ type AddCanvasCaptureCompositionOptions,
+} from './add-canvas-capture-composition';
+export {
+ updateVisualControls,
+ type UpdateVisualControlsOptions,
+ type UpdateVisualControlsResult,
+} from './update-visual-controls';
diff --git a/packages/codemods/src/parse-and-apply-codemod.ts b/packages/codemods/src/parse-and-apply-codemod.ts
deleted file mode 100644
index 15f702fe42..0000000000
--- a/packages/codemods/src/parse-and-apply-codemod.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import type {RecastCodemod} from '@remotion/studio-shared';
-import {applyVisualControl} from './apply-visual-control';
-import {editCompositionInSource} from './composition-source-edits';
-import {duplicateCompositionInSource} from './duplicate-composition-in-source';
-import {editFolderInSource} from './folder-source-edits';
-import type {Change} from './recast-mods';
-import {applyCodemod} from './recast-mods';
-import {parseAst, serializeAst} from './sequence-props/parse-ast';
-
-export const parseAndApplyCodemod = ({
- input,
- codeMod,
-}: {
- input: string;
- codeMod: RecastCodemod;
-}): {newContents: string; changesMade: Change[]} => {
- if (codeMod.type === 'apply-visual-control') {
- const result = applyVisualControl({input, transformation: codeMod});
- if (result.changesMade.length === 0) {
- throw new Error(
- 'Unable to calculate the changes needed for this file. Edit the file manually.',
- );
- }
-
- return result;
- }
-
- if (codeMod.type === 'duplicate-composition') {
- return duplicateCompositionInSource({input, codemod: codeMod});
- }
-
- if (
- codeMod.type === 'new-composition' ||
- codeMod.type === 'rename-composition' ||
- codeMod.type === 'delete-composition' ||
- codeMod.type === 'update-composition-metadata'
- ) {
- return editCompositionInSource({input, codeMod});
- }
-
- if (
- codeMod.type === 'move-composition-to-folder' ||
- codeMod.type === 'move-composition-or-folder' ||
- codeMod.type === 'rename-folder' ||
- codeMod.type === 'new-folder' ||
- codeMod.type === 'delete-folder'
- ) {
- return editFolderInSource({input, codeMod});
- }
-
- const ast = parseAst(input);
-
- const {newAst, changesMade} = applyCodemod({
- file: ast,
- codeMod,
- });
-
- if (changesMade.length === 0) {
- throw new Error(
- 'Unable to calculate the changes needed for this file. Edit the file manually.',
- );
- }
-
- const output = serializeAst(newAst);
-
- return {changesMade, newContents: output};
-};
diff --git a/packages/codemods/src/recast-mods.ts b/packages/codemods/src/recast-mods.ts
deleted file mode 100644
index 4b1d194a01..0000000000
--- a/packages/codemods/src/recast-mods.ts
+++ /dev/null
@@ -1,1753 +0,0 @@
-/* eslint-disable @typescript-eslint/no-use-before-define */
-import type {
- ArrowFunctionExpression,
- BlockStatement,
- ExportDefaultDeclaration,
- ExportNamedDeclaration,
- Expression,
- File,
- FunctionDeclaration,
- FunctionExpression,
- JSXAttribute,
- JSXElement,
- JSXFragment,
- JSXIdentifier,
- NullLiteral,
- ReturnStatement,
- Statement,
- VariableDeclaration,
- VariableDeclarator,
-} from '@babel/types';
-import type {CompositionOrFolder, RecastCodemod} from '@remotion/studio-shared';
-import * as recast from 'recast';
-import {applyVisualControl} from './apply-visual-control';
-import {deleteJsxElementAtPath} from './delete-jsx-nodes-internal';
-import {parseAst} from './sequence-props/parse-ast';
-import {stripParenthesizedExtra} from './strip-parenthesized-extra';
-
-export type Change = {
- description: string;
-};
-
-const b = recast.types.builders;
-
-export type ApplyCodeModReturnType = {newAst: File; changesMade: Change[]};
-
-export const applyCodemod = ({
- file,
- codeMod,
-}: {
- file: File;
- codeMod: RecastCodemod;
-}): ApplyCodeModReturnType => {
- const changesMade: Change[] = [];
-
- if (codeMod.type === 'apply-visual-control') {
- const result = applyVisualControl({
- input: recast.print(file).code,
- transformation: codeMod,
- });
- return {
- newAst: parseAst(result.newContents),
- changesMade: result.changesMade,
- };
- }
-
- if (codeMod.type === 'move-composition-to-folder') {
- return moveCompositionToFolder({
- file,
- transformation: codeMod,
- changesMade,
- });
- }
-
- if (codeMod.type === 'move-composition-or-folder') {
- return moveCompositionOrFolder({
- file,
- transformation: codeMod,
- changesMade,
- });
- }
-
- if (
- (codeMod.type === 'new-composition' && codeMod.folderName === null) ||
- (codeMod.type === 'new-folder' && codeMod.parentName === null)
- ) {
- const functions = new Map<
- object,
- {path: recast.types.NodePath; hasRegistration: boolean}
- >();
- recast.visit(file, {
- visitNode(jsxPath) {
- const jsx = jsxPath.node;
- if (
- !recast.types.namedTypes.JSXElement.check(jsx) &&
- !recast.types.namedTypes.JSXFragment.check(jsx)
- ) {
- this.traverse(jsxPath);
- return false;
- }
-
- let parent = jsxPath.parentPath;
- while (parent) {
- if (recast.types.namedTypes.Function.check(parent.node)) {
- const existing = functions.get(parent.node);
- functions.set(parent.node, {
- path: parent,
- hasRegistration:
- existing?.hasRegistration === true ||
- (jsx.type === 'JSXElement' &&
- (getCompositionIdFromJSXElement(jsx as JSXElement) !== null ||
- getFolderNameFromJSXElement(jsx as JSXElement) !== null)),
- });
- break;
- }
-
- parent = parent.parentPath;
- }
-
- this.traverse(jsxPath);
- return false;
- },
- });
- const registered = [...functions.values()].filter(
- ({hasRegistration}) => hasRegistration,
- );
- const candidates =
- registered.length > 0 ? registered : [...functions.values()];
- if (candidates.length !== 1) {
- throw new Error(
- 'Adding registrations requires a single JSX component containing registrations, or a file with a single JSX component',
- );
- }
-
- const target = candidates[0].path;
- recast.visit(
- target.node as
- | FunctionDeclaration
- | FunctionExpression
- | ArrowFunctionExpression,
- {
- visitNode(rootPath) {
- const {node} = rootPath;
- if (
- recast.types.namedTypes.Function.check(node) &&
- node !== target.node
- ) {
- return false;
- }
-
- const key =
- node.type === 'ReturnStatement'
- ? 'argument'
- : node.type === 'ArrowFunctionExpression'
- ? 'body'
- : null;
- const root = key === null ? null : rootPath.get(key).node;
- if (root?.type === 'JSXElement' || root?.type === 'JSXFragment') {
- rootPath
- .get(key)
- .replace(
- codeMod.type === 'new-composition'
- ? addNewCompositionToRootJsx(root, codeMod, changesMade)
- : addNewFolderToRootJsx(root, codeMod, changesMade),
- );
- return false;
- }
-
- this.traverse(rootPath);
- return false;
- },
- },
- );
- return {newAst: file, changesMade};
- }
-
- const body = file.program.body.map((node) => {
- return mapAll(node, codeMod, changesMade, null);
- });
-
- return {
- newAst: {
- ...file,
- program: {
- ...file.program,
- body,
- },
- },
- changesMade,
- };
-};
-
-const mapAll = <T extends Statement | Expression>(
- node: T,
- transformation: RecastCodemod,
- changesMade: Change[],
- parentFolderName: string | null,
-): T => {
- if (isRecognizedType(node)) {
- return mapRecognizedType(
- node,
- transformation,
- changesMade,
- parentFolderName,
- );
- }
-
- return node;
-};
-
-type RecognizedType =
- | ArrowFunctionExpression
- | FunctionExpression
- | JSXFragment
- | JSXElement
- | BlockStatement
- | ReturnStatement
- | VariableDeclaration
- | FunctionDeclaration
- | ExportNamedDeclaration
- | ExportDefaultDeclaration;
-
-const isRecognizedType = (t: Statement | Expression): t is RecognizedType => {
- return (
- t.type === 'ArrowFunctionExpression' ||
- t.type === 'FunctionExpression' ||
- t.type === 'JSXFragment' ||
- t.type === 'JSXElement' ||
- t.type === 'BlockStatement' ||
- t.type === 'ReturnStatement' ||
- t.type === 'VariableDeclaration' ||
- t.type === 'FunctionDeclaration' ||
- t.type === 'ExportNamedDeclaration' ||
- t.type === 'ExportDefaultDeclaration'
- );
-};
-
-const mapVariableDeclarator = (
- variableDeclarator: VariableDeclarator,
- transformation: RecastCodemod,
- changesMade: Change[],
- parentFolderName: string | null,
-): VariableDeclarator => {
- return {
- ...variableDeclarator,
- init: variableDeclarator.init
- ? mapAll(
- variableDeclarator.init,
- transformation,
- changesMade,
- parentFolderName,
- )
- : variableDeclarator.init,
- };
-};
-
-const mapBlockStatement = (
- blockStatement: BlockStatement,
- transformation: RecastCodemod,
- changesMade: Change[],
- parentFolderName: string | null,
-): BlockStatement => {
- return {
- ...blockStatement,
- body: blockStatement.body.map((a) => {
- return mapAll(a, transformation, changesMade, parentFolderName);
- }),
- };
-};
-
-const mapReturnStatement = (
- statement: ReturnStatement,
- transformation: RecastCodemod,
- changesMade: Change[],
- parentFolderName: string | null,
-): ReturnStatement => {
- if (!statement.argument) {
- return statement;
- }
-
- if (
- transformation.type === 'new-composition' &&
- transformation.folderName === null &&
- (statement.argument.type === 'JSXElement' ||
- statement.argument.type === 'JSXFragment')
- ) {
- return {
- ...statement,
- argument: addNewCompositionToRootJsx(
- statement.argument,
- transformation,
- changesMade,
- ),
- };
- }
-
- if (
- transformation.type === 'new-folder' &&
- transformation.parentName === null &&
- (statement.argument.type === 'JSXElement' ||
- statement.argument.type === 'JSXFragment')
- ) {
- return {
- ...statement,
- argument: addNewFolderToRootJsx(
- statement.argument,
- transformation,
- changesMade,
- ),
- };
- }
-
- const replacement = transformLoneJsxElement(
- statement.argument,
- transformation,
- changesMade,
- parentFolderName,
- );
- if (replacement !== null) {
- return {...statement, argument: replacement};
- }
-
- return {
- ...statement,
- argument: mapAll(
- statement.argument,
- transformation,
- changesMade,
- parentFolderName,
- ),
- };
-};
-
-const nullLiteral = (): NullLiteral => ({type: 'NullLiteral'});
-
-const wrapInJsxFragment = (children: JSXFragment['children']): JSXFragment => ({
- type: 'JSXFragment',
- openingFragment: {type: 'JSXOpeningFragment'},
- closingFragment: {type: 'JSXClosingFragment'},
- children: children.map((child) => {
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
- return stripParenthesizedExtra(child);
- }
-
- return child;
- }),
-});
-
-const isJsxExpression = (
- child: JSXFragment['children'][number],
-): child is JSXElement | JSXFragment => {
- return child.type === 'JSXElement' || child.type === 'JSXFragment';
-};
-
-const isMeaningfulJsxChild = (child: JSXFragment['children'][number]) => {
- return child.type !== 'JSXText' || child.value.trim() !== '';
-};
-
-const jsxId = (name: string): JSXIdentifier => ({type: 'JSXIdentifier', name});
-
-const jsxAttributeWithString = (name: string, value: string): JSXAttribute => ({
- type: 'JSXAttribute',
- name: jsxId(name),
- value: {type: 'StringLiteral', value},
-});
-
-const jsxAttributeWithExpression = (
- name: string,
- expression: Expression,
-): JSXAttribute => ({
- type: 'JSXAttribute',
- name: jsxId(name),
- value: {
- type: 'JSXExpressionContainer',
- expression,
- },
-});
-
-const newCompositionElement = (
- transformation: Extract<RecastCodemod, {type: 'new-composition'}>,
-): JSXElement => {
- if (transformation.canvasCapture !== null) {
- return {
- type: 'JSXElement',
- openingElement: {
- type: 'JSXOpeningElement',
- name: jsxId(transformation.componentName),
- attributes: [],
- selfClosing: true,
- },
- closingElement: null,
- children: [],
- };
- }
-
- return {
- type: 'JSXElement',
- openingElement: {
- type: 'JSXOpeningElement',
- name: jsxId('Composition'),
- attributes: [
- jsxAttributeWithString('id', transformation.newId),
- jsxAttributeWithExpression(
- 'component',
- b.identifier(transformation.componentName) as Expression,
- ),
- jsxAttributeWithExpression(
- 'durationInFrames',
- b.numericLiteral(transformation.newDurationInFrames) as Expression,
- ),
- jsxAttributeWithExpression(
- 'fps',
- b.numericLiteral(transformation.newFps) as Expression,
- ),
- jsxAttributeWithExpression(
- 'width',
- b.numericLiteral(transformation.newWidth) as Expression,
- ),
- jsxAttributeWithExpression(
- 'height',
- b.numericLiteral(transformation.newHeight) as Expression,
- ),
- ],
- selfClosing: true,
- },
- closingElement: null,
- children: [],
- };
-};
-
-const newFolderElement = (
- transformation: Extract<RecastCodemod, {type: 'new-folder'}>,
-): JSXElement => {
- return {
- type: 'JSXElement',
- openingElement: {
- type: 'JSXOpeningElement',
- name: jsxId('Folder'),
- attributes: [jsxAttributeWithString('name', transformation.folderName)],
- selfClosing: true,
- },
- closingElement: null,
- children: [],
- };
-};
-
-const addNewCompositionToRootJsx = <T extends JSXElement | JSXFragment>(
- root: T,
- transformation: Extract<RecastCodemod, {type: 'new-composition'}>,
- changesMade: Change[],
-): JSXElement | JSXFragment => {
- if (changesMade.length > 0) {
- return root;
- }
-
- changesMade.push({
- description: 'Added new composition',
- });
-
- if (root.type === 'JSXFragment') {
- return {
- ...root,
- children: [...root.children, newCompositionElement(transformation)],
- };
- }
-
- return wrapInJsxFragment([root, newCompositionElement(transformation)]);
-};
-
-const addNewFolderToRootJsx = <T extends JSXElement | JSXFragment>(
- root: T,
- transformation: Extract<RecastCodemod, {type: 'new-folder'}>,
- changesMade: Change[],
-): JSXElement | JSXFragment => {
- if (changesMade.length > 0) {
- return root;
- }
-
- changesMade.push({
- description: 'Added new folder',
- });
-
- if (root.type === 'JSXFragment') {
- return {
- ...root,
- children: [...root.children, newFolderElement(transformation)],
- };
- }
-
- return wrapInJsxFragment([root, newFolderElement(transformation)]);
-};
-
-const addNewCompositionToFolder = (
- folderElement: JSXElement,
- transformation: Extract<RecastCodemod, {type: 'new-composition'}>,
- changesMade: Change[],
-): JSXElement => {
- if (changesMade.length > 0) {
- return folderElement;
- }
-
- changesMade.push({
- description: 'Added new composition',
- });
-
- return {
- ...folderElement,
- openingElement: {
- ...folderElement.openingElement,
- selfClosing: false,
- },
- closingElement: folderElement.closingElement ?? {
- type: 'JSXClosingElement',
- name: folderElement.openingElement.name,
- },
- children: [
- ...folderElement.children,
- newCompositionElement(transformation),
- ],
- };
-};
-
-const addNewFolderToFolder = (
- folderElement: JSXElement,
- transformation: Extract<RecastCodemod, {type: 'new-folder'}>,
- changesMade: Change[],
-): JSXElement => {
- if (changesMade.length > 0) {
- return folderElement;
- }
-
- changesMade.push({
- description: 'Added new folder',
- });
-
- return {
- ...folderElement,
- openingElement: {
- ...folderElement.openingElement,
- selfClosing: false,
- },
- closingElement: folderElement.closingElement ?? {
- type: 'JSXClosingElement',
- name: folderElement.openingElement.name,
- },
- children: [...folderElement.children, newFolderElement(transformation)],
- };
-};
-
-const getChildFolderParentName = ({
- folderName,
- parentFolderName,
-}: {
- folderName: string;
- parentFolderName: string | null;
-}) => {
- return [parentFolderName, folderName].filter(Boolean).join('/');
-};
-
-const appendElementToFolder = ({
- element,
- folderElement,
-}: {
- element: JSXElement;
- folderElement: JSXElement;
-}) => {
- folderElement.openingElement.selfClosing = false;
- folderElement.closingElement = folderElement.closingElement ?? {
- type: 'JSXClosingElement',
- name: folderElement.openingElement.name,
- };
- folderElement.children.push(stripParenthesizedExtra(element));
-};
-
-const appendElementToRoot = ({
- element,
- returnStatement,
-}: {
- element: JSXElement;
- returnStatement: ReturnStatement | ArrowFunctionExpression;
-}) => {
- const argument =
- returnStatement.type === 'ArrowFunctionExpression'
- ? returnStatement.body
- : returnStatement.argument;
- if (argument?.type !== 'JSXFragment' && argument?.type !== 'JSXElement') {
- throw new Error('Could not find a root JSX element');
- }
-
- if (argument.type === 'JSXFragment') {
- (argument.children as JSXFragment['children']).push(
- stripParenthesizedExtra(element),
- );
- } else {
- const fragment = wrapInJsxFragment([
- argument as unknown as JSXElement,
- element,
- ]) as never;
- if (returnStatement.type === 'ArrowFunctionExpression') {
- returnStatement.body = fragment;
- } else {
- returnStatement.argument = fragment;
- }
- }
-};
-
-const getEnclosingJsxReturn = (path: recast.types.NodePath) => {
- let currentPath: recast.types.NodePath | null = path;
- while (currentPath !== null) {
- if (
- (currentPath.node as unknown as {type?: string} | null)?.type ===
- 'ReturnStatement'
- ) {
- return currentPath.node as unknown as ReturnStatement;
- }
-
- const node = currentPath.node as ArrowFunctionExpression;
- if (
- node?.type === 'ArrowFunctionExpression' &&
- (node.body.type === 'JSXElement' || node.body.type === 'JSXFragment')
- ) {
- return node;
- }
-
- currentPath = currentPath.parentPath ?? null;
- }
-
- throw new Error('Could not find a root JSX element');
-};
-
-const getCompositionOrFolderLabel = (item: CompositionOrFolder) => {
- return item.type === 'composition'
- ? `composition "${item.compositionId}"`
- : `folder "${[item.parentName, item.folderName].filter(Boolean).join('/')}"`;
-};
-
-const matchesCompositionOrFolder = ({
- item,
- node,
- parentFolderName,
-}: {
- item: CompositionOrFolder;
- node: JSXElement;
- parentFolderName: string | null;
-}) => {
- if (item.type === 'composition') {
- return getCompositionIdFromJSXElement(node) === item.compositionId;
- }
-
- return (
- getFolderNameFromJSXElement(node) === item.folderName &&
- parentFolderName === item.parentName
- );
-};
-
-const moveCompositionOrFolder = ({
- file,
- transformation,
- changesMade,
-}: {
- file: File;
- transformation: Extract<RecastCodemod, {type: 'move-composition-or-folder'}>;
- changesMade: Change[];
-}): ApplyCodeModReturnType => {
- type LocatedItem = {
- node: JSXElement;
- parent: JSXElement | JSXFragment;
- parentFolderName: string | null;
- path: recast.types.NodePath;
- };
-
- let source: LocatedItem | null = null;
- let target: LocatedItem | null = null;
- let destinationFolder: LocatedItem | null = null;
- const folders: {
- node: JSXElement;
- name: string;
- parentFolderName: string | null;
- }[] = [];
- const folderStack: string[] = [];
-
- const visitJsxElement = (astPath: recast.types.NodePath) => {
- const node = astPath.node as JSXElement;
- const parent = astPath.parentPath?.node;
- const parentFolderName = folderStack.join('/') || null;
- const isDirectJsxChild =
- (parent?.type === 'JSXElement' || parent?.type === 'JSXFragment') &&
- parent.children.includes(node);
-
- if (
- isDirectJsxChild &&
- matchesCompositionOrFolder({
- item: transformation.source,
- node,
- parentFolderName,
- })
- ) {
- source = {
- node,
- parent,
- parentFolderName,
- path: astPath,
- };
- }
-
- if (
- isDirectJsxChild &&
- (transformation.destination.type === 'before' ||
- transformation.destination.type === 'after') &&
- matchesCompositionOrFolder({
- item: transformation.destination.target,
- node,
- parentFolderName,
- })
- ) {
- target = {
- node,
- parent,
- parentFolderName,
- path: astPath,
- };
- }
-
- const folderName = getFolderNameFromJSXElement(node);
- if (folderName !== null) {
- folders.push({node, name: folderName, parentFolderName});
- }
-
- if (
- isDirectJsxChild &&
- transformation.destination.type === 'folder' &&
- folderName === transformation.destination.folderName &&
- parentFolderName === transformation.destination.parentName
- ) {
- destinationFolder = {
- node,
- parent,
- parentFolderName,
- path: astPath,
- };
- }
-
- if (folderName !== null) {
- folderStack.push(folderName);
- }
-
- for (let index = 0; index < node.children.length; index++) {
- if (node.children[index].type === 'JSXElement') {
- visitJsxElement(
- astPath.get('children', index) as recast.types.NodePath,
- );
- }
- }
-
- if (folderName !== null) {
- folderStack.pop();
- }
- };
-
- recast.types.visit(file, {
- visitJSXElement(astPath) {
- visitJsxElement(astPath as unknown as recast.types.NodePath);
- return false;
- },
- });
-
- if (source === null) {
- throw new Error(
- `Could not find ${getCompositionOrFolderLabel(transformation.source)} as a direct JSX child`,
- );
- }
-
- const sourceItem = source as LocatedItem;
- if (
- (transformation.destination.type === 'before' ||
- transformation.destination.type === 'after') &&
- target === null
- ) {
- throw new Error(
- `Could not find ${getCompositionOrFolderLabel(transformation.destination.target)} as a reorder target`,
- );
- }
-
- if (
- transformation.destination.type === 'folder' &&
- destinationFolder === null
- ) {
- const folderPath = [
- transformation.destination.parentName,
- transformation.destination.folderName,
- ]
- .filter(Boolean)
- .join('/');
- throw new Error(`Could not find folder "${folderPath}"`);
- }
-
- if (target !== null && (target as LocatedItem).node === sourceItem.node) {
- return {newAst: file, changesMade};
- }
-
- const sourceFolderPath =
- transformation.source.type === 'folder'
- ? [transformation.source.parentName, transformation.source.folderName]
- .filter(Boolean)
- .join('/')
- : null;
- const destinationParentFolderName =
- transformation.destination.type === 'root'
- ? null
- : transformation.destination.type === 'folder'
- ? [
- transformation.destination.parentName,
- transformation.destination.folderName,
- ]
- .filter(Boolean)
- .join('/')
- : (target as unknown as LocatedItem).parentFolderName;
- if (
- sourceFolderPath !== null &&
- destinationParentFolderName !== null &&
- (destinationParentFolderName === sourceFolderPath ||
- destinationParentFolderName.startsWith(`${sourceFolderPath}/`))
- ) {
- throw new Error('A folder cannot be moved inside itself');
- }
-
- if (transformation.source.type === 'folder') {
- const sourceFolderName = transformation.source.folderName;
- if (
- folders.some(
- (folder) =>
- folder.node !== sourceItem.node &&
- folder.name === sourceFolderName &&
- folder.parentFolderName === destinationParentFolderName,
- )
- ) {
- throw new Error(
- `A folder named "${sourceFolderName}" already exists in the destination`,
- );
- }
- }
-
- const sourceReturnStatement = getEnclosingJsxReturn(sourceItem.path);
- deleteJsxElementAtPath(sourceItem.path);
- const element = stripParenthesizedExtra(sourceItem.node);
- if (transformation.destination.type === 'root') {
- appendElementToRoot({element, returnStatement: sourceReturnStatement});
- } else if (transformation.destination.type === 'folder') {
- appendElementToFolder({
- element,
- folderElement: (destinationFolder as unknown as LocatedItem).node,
- });
- } else {
- const targetItem = target as unknown as LocatedItem;
- const targetIndex = targetItem.parent.children.indexOf(targetItem.node);
- if (targetIndex === -1) {
- throw new Error('The reorder target is no longer available');
- }
-
- targetItem.parent.children.splice(
- transformation.destination.type === 'before'
- ? targetIndex
- : targetIndex + 1,
- 0,
- element,
- );
- }
-
- changesMade.push({description: 'Moved composition or folder'});
- return {newAst: file, changesMade};
-};
-
-const moveCompositionToFolder = ({
- file,
- transformation,
- changesMade,
-}: {
- file: File;
- transformation: Extract<RecastCodemod, {type: 'move-composition-to-folder'}>;
- changesMade: Change[];
-}): ApplyCodeModReturnType => {
- let sourcePath: recast.types.NodePath | null = null;
- let sourceParentFolderName: string | null = null;
- let sourceIsDirectJsxChild = false;
- let targetFolder: JSXElement | null = null;
- const folderStack: string[] = [];
-
- const isDirectJsxChild = (astPath: recast.types.NodePath) => {
- const parent = astPath.parentPath?.node;
- return (
- (parent?.type === 'JSXElement' || parent?.type === 'JSXFragment') &&
- parent.children.includes(astPath.node as JSXElement)
- );
- };
-
- const visitJsxElementWithFolderContext = (astPath: recast.types.NodePath) => {
- const node = astPath.node as JSXElement;
- const compositionId = getCompositionIdFromJSXElement(node);
- if (compositionId === transformation.idToMove) {
- sourcePath = astPath;
- sourceParentFolderName = folderStack.join('/') || null;
- sourceIsDirectJsxChild = isDirectJsxChild(astPath);
- }
-
- const folderName = getFolderNameFromJSXElement(node);
- const parentName = folderStack.join('/') || null;
- if (
- transformation.folderName !== null &&
- folderName === transformation.folderName &&
- parentName === transformation.parentName
- ) {
- targetFolder = node;
- }
-
- if (folderName) {
- folderStack.push(folderName);
- }
-
- for (let i = 0; i < node.children.length; i++) {
- if (node.children[i].type !== 'JSXElement') {
- continue;
- }
-
- visitJsxElementWithFolderContext(
- astPath.get('children', i) as recast.types.NodePath,
- );
- }
-
- if (folderName) {
- folderStack.pop();
- }
- };
-
- recast.types.visit(file, {
- visitJSXElement(astPath) {
- visitJsxElementWithFolderContext(
- astPath as unknown as recast.types.NodePath,
- );
- return false;
- },
- });
-
- if (!sourcePath) {
- throw new Error(`Could not find composition "${transformation.idToMove}"`);
- }
-
- if (!sourceIsDirectJsxChild) {
- throw new Error(
- `Cannot move composition "${transformation.idToMove}" because it is not a direct JSX child`,
- );
- }
-
- if (transformation.folderName === null && sourceParentFolderName === null) {
- return {newAst: file, changesMade};
- }
-
- if (transformation.folderName !== null && !targetFolder) {
- const folderLabel = `${transformation.parentName ? `${transformation.parentName}/` : ''}${transformation.folderName}`;
- throw new Error(`Could not find folder "${folderLabel}"`);
- }
-
- const compositionElement = (sourcePath as recast.types.NodePath)
- .node as JSXElement;
- const sourceReturnStatement = getEnclosingJsxReturn(sourcePath);
- deleteJsxElementAtPath(sourcePath);
- if (transformation.folderName === null) {
- appendElementToRoot({
- element: compositionElement,
- returnStatement: sourceReturnStatement,
- });
- changesMade.push({description: 'Moved composition to root'});
- } else {
- if (targetFolder === null) {
- throw new Error('Could not find target folder');
- }
-
- appendElementToFolder({
- element: compositionElement,
- folderElement: targetFolder,
- });
- changesMade.push({description: 'Moved composition into folder'});
- }
-
- return {newAst: file, changesMade};
-};
-
-// When a <Composition> JSX element appears in a position where it cannot
-// simply be removed from a parent's children list (e.g. as the sole return
-// value of a wrapper component or as the concise body of an arrow function),
-// we still want delete/rename/duplicate codemods to work. This helper detects
-// that case and produces a structurally-valid replacement expression.
-const transformLoneJsxElement = (
- expression: Expression,
- transformation: RecastCodemod,
- changesMade: Change[],
- parentFolderName: string | null,
-): Expression | null => {
- if (expression.type !== 'JSXElement') {
- return null;
- }
-
- const compId = getCompositionIdFromJSXElement(expression);
- const folderName = getFolderNameFromJSXElement(expression);
- if (compId === null) {
- const isFolderMatch =
- folderName !== null &&
- ((transformation.type === 'delete-folder' &&
- folderName === transformation.folderName &&
- parentFolderName === transformation.parentName) ||
- (transformation.type === 'rename-folder' &&
- folderName === transformation.folderName &&
- parentFolderName === transformation.parentName) ||
- (transformation.type === 'new-composition' &&
- folderName === transformation.folderName &&
- parentFolderName === transformation.parentName) ||
- (transformation.type === 'new-folder' &&
- getChildFolderParentName({folderName, parentFolderName}) ===
- transformation.parentName));
-
- if (!isFolderMatch) {
- return null;
- }
- }
-
- const isMatch =
- (transformation.type === 'delete-composition' &&
- compId === transformation.idToDelete) ||
- (transformation.type === 'rename-composition' &&
- compId === transformation.idToRename) ||
- (transformation.type === 'update-composition-metadata' &&
- compId === transformation.idToUpdate) ||
- (transformation.type === 'delete-folder' &&
- folderName === transformation.folderName &&
- parentFolderName === transformation.parentName) ||
- (transformation.type === 'rename-folder' &&
- folderName === transformation.folderName &&
- parentFolderName === transformation.parentName) ||
- (transformation.type === 'new-composition' &&
- folderName === transformation.folderName &&
- parentFolderName === transformation.parentName) ||
- (transformation.type === 'new-folder' &&
- folderName !== null &&
- getChildFolderParentName({folderName, parentFolderName}) ===
- transformation.parentName);
-
- if (!isMatch) {
- return null;
- }
-
- const transformed = mapJsxChild(
- expression,
- transformation,
- changesMade,
- parentFolderName,
- );
- const meaningful = transformed.filter(isMeaningfulJsxChild);
-
- if (meaningful.length === 0) {
- return nullLiteral();
- }
-
- if (meaningful.length === 1 && isJsxExpression(meaningful[0])) {
- return meaningful[0];
- }
-
- return wrapInJsxFragment(transformed);
-};
-
-const mapJsxElementOrFragment = <T extends JSXFragment | JSXElement>(
- jsxFragment: T,
- transformation: RecastCodemod,
- changesMade: Change[],
- parentFolderName: string | null,
-): T => {
- return {
- ...jsxFragment,
- children: jsxFragment.children
- .map((c) => {
- if (c.type !== 'JSXElement') {
- return c;
- }
-
- return mapJsxChild(c, transformation, changesMade, parentFolderName);
- })
- .flat(1),
- };
-};
-
-const mapJsxChild = (
- c: JSXElement,
- transformation: RecastCodemod | null,
- changesMade: Change[],
- parentFolderName: string | null,
-): JSXFragment['children'] => {
- const compId = getCompositionIdFromJSXElement(c);
- const folderName = getFolderNameFromJSXElement(c);
-
- if (transformation === null) {
- return [c];
- }
-
- if (
- transformation.type === 'rename-composition' &&
- compId === transformation.idToRename
- ) {
- return [
- changeComposition({
- jsxElement: c,
- newCompositionId: transformation.newId,
- newCompositionFps: null,
- newCompositionDurationInFrames: null,
- newCompositionHeight: null,
- newCompositionWidth: null,
- changesMade,
- newTagToUse: null,
- }),
- ];
- }
-
- if (
- transformation.type === 'update-composition-metadata' &&
- compId === transformation.idToUpdate
- ) {
- return [
- changeComposition({
- jsxElement: c,
- newCompositionId: null,
- newCompositionFps: transformation.newFps,
- newCompositionDurationInFrames: transformation.newDurationInFrames,
- newCompositionHeight: transformation.newHeight,
- newCompositionWidth: transformation.newWidth,
- changesMade,
- newTagToUse: null,
- }),
- ];
- }
-
- if (
- transformation.type === 'delete-composition' &&
- compId === transformation.idToDelete
- ) {
- changesMade.push({
- description: 'Deleted composition',
- });
- return [];
- }
-
- if (
- transformation.type === 'rename-folder' &&
- folderName === transformation.folderName &&
- parentFolderName === transformation.parentName
- ) {
- return [
- changeFolderName({
- jsxElement: c,
- newFolderName: transformation.newName,
- changesMade,
- }),
- ];
- }
-
- if (
- transformation.type === 'delete-folder' &&
- folderName === transformation.folderName &&
- parentFolderName === transformation.parentName
- ) {
- changesMade.push({
- description: 'Deleted folder',
- });
- return c.children;
- }
-
- if (
- transformation.type === 'new-composition' &&
- folderName === transformation.folderName &&
- parentFolderName === transformation.parentName
- ) {
- return [addNewCompositionToFolder(c, transformation, changesMade)];
- }
-
- if (
- transformation.type === 'new-folder' &&
- folderName !== null &&
- getChildFolderParentName({folderName, parentFolderName}) ===
- transformation.parentName
- ) {
- return [addNewFolderToFolder(c, transformation, changesMade)];
- }
-
- const childParentFolderName = folderName
- ? getChildFolderParentName({folderName, parentFolderName})
- : parentFolderName;
-
- return [mapAll(c, transformation, changesMade, childParentFolderName)];
-};
-
-const mapRecognizedType = <T extends RecognizedType>(
- expression: T,
- transformation: RecastCodemod,
- changesMade: Change[],
- parentFolderName: string | null,
-): T => {
- if (expression.type === 'JSXFragment' || expression.type === 'JSXElement') {
- return mapJsxElementOrFragment(
- expression,
- transformation,
- changesMade,
- parentFolderName,
- ) as T;
- }
-
- if (
- expression.type === 'ArrowFunctionExpression' ||
- expression.type === 'FunctionExpression'
- ) {
- if (
- transformation.type === 'new-composition' &&
- transformation.folderName === null &&
- (expression.body.type === 'JSXElement' ||
- expression.body.type === 'JSXFragment')
- ) {
- return {
- ...expression,
- body: addNewCompositionToRootJsx(
- expression.body,
- transformation,
- changesMade,
- ),
- };
- }
-
- if (
- transformation.type === 'new-folder' &&
- transformation.parentName === null &&
- (expression.body.type === 'JSXElement' ||
- expression.body.type === 'JSXFragment')
- ) {
- return {
- ...expression,
- body: addNewFolderToRootJsx(
- expression.body,
- transformation,
- changesMade,
- ),
- };
- }
-
- if (
- expression.type === 'ArrowFunctionExpression' &&
- expression.body.type === 'JSXElement'
- ) {
- const replacement = transformLoneJsxElement(
- expression.body,
- transformation,
- changesMade,
- parentFolderName,
- );
- if (replacement !== null) {
- return {
- ...expression,
- body: replacement,
- };
- }
- }
-
- return {
- ...expression,
- body: mapAll(
- expression.body,
- transformation,
- changesMade,
- parentFolderName,
- ),
- };
- }
-
- if (expression.type === 'VariableDeclaration') {
- const declarations = expression.declarations.map((d) => {
- return mapVariableDeclarator(
- d,
- transformation,
- changesMade,
- parentFolderName,
- );
- });
- return {...expression, declarations};
- }
-
- if (expression.type === 'FunctionDeclaration') {
- return {
- ...expression,
- body: mapBlockStatement(
- expression.body,
- transformation,
- changesMade,
- parentFolderName,
- ),
- };
- }
-
- if (
- expression.type === 'ExportNamedDeclaration' ||
- expression.type === 'ExportDefaultDeclaration'
- ) {
- if (!expression.declaration) {
- return expression;
- }
-
- return {
- ...expression,
- declaration: mapAll(
- expression.declaration,
- transformation,
- changesMade,
- parentFolderName,
- ),
- };
- }
-
- if (expression.type === 'ReturnStatement') {
- return mapReturnStatement(
- expression,
- transformation,
- changesMade,
- parentFolderName,
- ) as T;
- }
-
- if (expression.type === 'BlockStatement') {
- return mapBlockStatement(
- expression,
- transformation,
- changesMade,
- parentFolderName,
- ) as T;
- }
-
- return expression;
-};
-
-export const getCompositionIdFromJSXElement = (
- jsxElement: JSXFragment['children'][number],
-) => {
- if (jsxElement.type !== 'JSXElement') {
- return null;
- }
-
- const {openingElement} = jsxElement;
- const {name} = openingElement;
- if (name.type !== 'JSXIdentifier') {
- return null;
- }
-
- if (name.name !== 'Composition' && name.name !== 'Still') {
- return null;
- }
-
- const id = openingElement.attributes
- .map((attribute) => {
- if (attribute.type === 'JSXSpreadAttribute') {
- return null;
- }
-
- if (attribute.name.type === 'JSXNamespacedName') {
- return null;
- }
-
- if (attribute.name.name !== 'id') {
- return null;
- }
-
- if (!attribute.value) {
- return null;
- }
-
- if (attribute.value.type === 'StringLiteral') {
- return attribute.value.value;
- }
-
- if (
- attribute.value.type === 'JSXExpressionContainer' &&
- attribute.value.expression.type === 'StringLiteral'
- ) {
- return attribute.value.expression.value;
- }
-
- return null;
- })
- .filter(Boolean);
-
- return id[0];
-};
-
-export const getFolderNameFromJSXElement = (
- jsxElement: JSXFragment['children'][number],
-) => {
- if (jsxElement.type !== 'JSXElement') {
- return null;
- }
-
- const {openingElement} = jsxElement;
- const {name} = openingElement;
- if (name.type !== 'JSXIdentifier') {
- return null;
- }
-
- if (name.name !== 'Folder') {
- return null;
- }
-
- const folderName = openingElement.attributes
- .map((attribute) => {
- if (attribute.type === 'JSXSpreadAttribute') {
- return null;
- }
-
- if (attribute.name.type === 'JSXNamespacedName') {
- return null;
- }
-
- if (attribute.name.name !== 'name') {
- return null;
- }
-
- if (!attribute.value) {
- return null;
- }
-
- if (attribute.value.type === 'StringLiteral') {
- return attribute.value.value;
- }
-
- if (
- attribute.value.type === 'JSXExpressionContainer' &&
- attribute.value.expression.type === 'StringLiteral'
- ) {
- return attribute.value.expression.value;
- }
-
- return null;
- })
- .filter(Boolean);
-
- return folderName[0];
-};
-
-const changeFolderName = ({
- jsxElement,
- newFolderName,
- changesMade,
-}: {
- jsxElement: JSXElement;
- newFolderName: string;
- changesMade: Change[];
-}): JSXElement => {
- const {openingElement} = jsxElement;
- const {name} = openingElement;
- if (name.type !== 'JSXIdentifier') {
- return jsxElement;
- }
-
- if (name.name !== 'Folder') {
- return jsxElement;
- }
-
- const attributes = openingElement.attributes.map((attribute) => {
- if (attribute.type === 'JSXSpreadAttribute') {
- return attribute;
- }
-
- if (attribute.name.type === 'JSXNamespacedName') {
- return attribute;
- }
-
- if (
- attribute.name.name === 'name' &&
- attribute.value &&
- attribute.value.type === 'StringLiteral'
- ) {
- changesMade.push({
- description: 'Replaced folder name',
- });
-
- return {
- ...attribute,
- value: {...attribute.value, value: newFolderName},
- };
- }
-
- if (
- attribute.name.name === 'name' &&
- attribute.value &&
- attribute.value.type === 'JSXExpressionContainer' &&
- attribute.value.expression.type === 'StringLiteral'
- ) {
- changesMade.push({
- description: 'Replaced folder name',
- });
-
- return {
- ...attribute,
- value: {
- ...attribute.value,
- expression: {
- ...attribute.value.expression,
- value: newFolderName,
- },
- },
- };
- }
-
- return attribute;
- });
-
- return {
- ...jsxElement,
- openingElement: {
- ...jsxElement.openingElement,
- attributes,
- },
- };
-};
-
-const changeComposition = ({
- jsxElement,
- newCompositionId,
- newCompositionFps,
- newCompositionDurationInFrames,
- newCompositionHeight,
- newCompositionWidth,
- changesMade,
- newTagToUse,
-}: {
- jsxElement: JSXElement;
- newCompositionId: string | null;
- newCompositionFps: number | null;
- newCompositionDurationInFrames: number | null;
- newCompositionHeight: number | null;
- newCompositionWidth: number | null;
- newTagToUse: 'Composition' | 'Still' | null;
- changesMade: Change[];
-}): JSXElement => {
- const {openingElement} = jsxElement;
- const {name} = openingElement;
- if (name.type !== 'JSXIdentifier') {
- return jsxElement;
- }
-
- if (name.name !== 'Composition' && name.name !== 'Still') {
- return jsxElement;
- }
-
- const attributes = openingElement.attributes
- .map((attribute) => {
- if (attribute.type === 'JSXSpreadAttribute') {
- return attribute;
- }
-
- if (attribute.name.type === 'JSXNamespacedName') {
- return attribute;
- }
-
- if (attribute.name.name === 'fps' && newTagToUse === 'Still') {
- changesMade.push({description: 'Removed fps attribute'});
- return null;
- }
-
- if (
- attribute.name.name === 'durationInFrames' &&
- newTagToUse === 'Still'
- ) {
- changesMade.push({description: 'Removed durationInFrames'});
- return null;
- }
-
- // id="one"
- if (
- attribute.name.name === 'id' &&
- attribute.value &&
- attribute.value.type === 'StringLiteral' &&
- newCompositionId !== null
- ) {
- changesMade.push({
- description: 'Replaced composition id',
- });
-
- return {
- ...attribute,
- value: {...attribute.value, value: newCompositionId},
- };
- }
-
- // id={"one"}
- if (
- attribute.name.name === 'id' &&
- attribute.value &&
- attribute.value.type === 'JSXExpressionContainer' &&
- attribute.value.expression.type === 'StringLiteral' &&
- newCompositionId !== null
- ) {
- changesMade.push({
- description: 'Replaced composition id',
- });
-
- return {
- ...attribute,
- value: {
- ...attribute.value,
- expression: {
- ...attribute.value.expression,
- value: newCompositionId,
- },
- },
- };
- }
-
- if (attribute.name.name === 'fps' && newCompositionFps !== null) {
- changesMade.push({
- description: 'Replaced FPS',
- });
-
- return {
- ...attribute,
- value: b.jsxExpressionContainer(b.numericLiteral(newCompositionFps)),
- };
- }
-
- if (
- attribute.name.name === 'durationInFrames' &&
- newCompositionDurationInFrames !== null
- ) {
- changesMade.push({
- description: 'Replaced durationInFrames',
- });
-
- return {
- ...attribute,
- value: b.jsxExpressionContainer(
- b.numericLiteral(newCompositionDurationInFrames),
- ),
- };
- }
-
- if (attribute.name.name === 'width' && newCompositionWidth !== null) {
- changesMade.push({
- description: 'Replaced width',
- });
-
- return {
- ...attribute,
- value: b.jsxExpressionContainer(
- b.numericLiteral(newCompositionWidth),
- ),
- };
- }
-
- if (attribute.name.name === 'height' && newCompositionHeight !== null) {
- changesMade.push({
- description: 'Replaced height',
- });
-
- return {
- ...attribute,
- value: b.jsxExpressionContainer(
- b.numericLiteral(newCompositionHeight),
- ),
- };
- }
-
- return attribute;
- })
- .filter(Boolean) as typeof openingElement.attributes;
-
- if (
- newCompositionFps !== null &&
- !attributes.some(
- (attribute) =>
- attribute.type === 'JSXAttribute' &&
- attribute.name.type === 'JSXIdentifier' &&
- attribute.name.name === 'fps',
- )
- ) {
- changesMade.push({description: 'Added FPS'});
- attributes.push(
- jsxAttributeWithExpression(
- 'fps',
- b.numericLiteral(newCompositionFps) as Expression,
- ),
- );
- }
-
- if (
- newCompositionDurationInFrames !== null &&
- !attributes.some(
- (attribute) =>
- attribute.type === 'JSXAttribute' &&
- attribute.name.type === 'JSXIdentifier' &&
- attribute.name.name === 'durationInFrames',
- )
- ) {
- changesMade.push({description: 'Added durationInFrames'});
- attributes.push(
- jsxAttributeWithExpression(
- 'durationInFrames',
- b.numericLiteral(newCompositionDurationInFrames) as Expression,
- ),
- );
- }
-
- if (
- newCompositionWidth !== null &&
- !attributes.some(
- (attribute) =>
- attribute.type === 'JSXAttribute' &&
- attribute.name.type === 'JSXIdentifier' &&
- attribute.name.name === 'width',
- )
- ) {
- changesMade.push({description: 'Added width'});
- attributes.push(
- jsxAttributeWithExpression(
- 'width',
- b.numericLiteral(newCompositionWidth) as Expression,
- ),
- );
- }
-
- if (
- newCompositionHeight !== null &&
- !attributes.some(
- (attribute) =>
- attribute.type === 'JSXAttribute' &&
- attribute.name.type === 'JSXIdentifier' &&
- attribute.name.name === 'height',
- )
- ) {
- changesMade.push({description: 'Added height'});
- attributes.push(
- jsxAttributeWithExpression(
- 'height',
- b.numericLiteral(newCompositionHeight) as Expression,
- ),
- );
- }
-
- const newName = newTagToUse ?? name.name;
- if (newName !== name.name) {
- changesMade.push({
- description: `Changed tag`,
- });
- }
-
- return {
- ...jsxElement,
- openingElement: {
- ...jsxElement.openingElement,
- name: {
- ...name,
- name: newName,
- },
- attributes,
- },
- };
-};
diff --git a/packages/codemods/src/registration-source-edits.ts b/packages/codemods/src/registration-source-edits.ts
new file mode 100644
index 0000000000..e2263c33a7
--- /dev/null
+++ b/packages/codemods/src/registration-source-edits.ts
@@ -0,0 +1,238 @@
+import type {File, JSXElement, JSXFragment, Node} from '@babel/types';
+import * as recast from 'recast';
+import type {FolderReference} from './composition-editing';
+import {getInsertionRootSourceEdit} from './insert-jsx-element';
+import {printInsertedJsx} from './print-jsx';
+import {getJsxComponentIdentity} from './sequence-props/jsx-component-identity';
+import type {SourceEdit} from './source-edits';
+
+const getRegistrationComponentType = (
+ element: JSXFragment['children'][number],
+ ast: File,
+): 'Composition' | 'Still' | 'Folder' | null => {
+ if (element.type !== 'JSXElement') return null;
+ const identity = getJsxComponentIdentity({
+ ast,
+ jsxElement: element.openingElement,
+ });
+ for (const tag of ['Composition', 'Still', 'Folder'] as const) {
+ if (identity === `dev.remotion.remotion.${tag}` || identity === tag)
+ return tag;
+ }
+
+ return null;
+};
+
+export const getCompositionIdFromJSXElement = (
+ element: JSXFragment['children'][number],
+ ast: File,
+): string | null => {
+ if (element.type !== 'JSXElement') return null;
+ const tag = getRegistrationComponentType(element, ast);
+ if (tag !== 'Composition' && tag !== 'Still') return null;
+
+ for (const attribute of element.openingElement.attributes) {
+ if (
+ attribute.type !== 'JSXAttribute' ||
+ attribute.name.type !== 'JSXIdentifier' ||
+ attribute.name.name !== 'id'
+ ) {
+ continue;
+ }
+
+ if (attribute.value?.type === 'StringLiteral') {
+ return attribute.value.value;
+ }
+
+ if (
+ attribute.value?.type === 'JSXExpressionContainer' &&
+ attribute.value.expression.type === 'StringLiteral'
+ ) {
+ return attribute.value.expression.value;
+ }
+ }
+
+ return null;
+};
+
+export const getFolderNameFromJSXElement = (
+ element: JSXFragment['children'][number],
+ ast: File,
+): string | null => {
+ if (element.type !== 'JSXElement') return null;
+ if (getRegistrationComponentType(element, ast) !== 'Folder') return null;
+
+ for (const attribute of element.openingElement.attributes) {
+ if (
+ attribute.type !== 'JSXAttribute' ||
+ attribute.name.type !== 'JSXIdentifier' ||
+ attribute.name.name !== 'name'
+ ) {
+ continue;
+ }
+
+ if (attribute.value?.type === 'StringLiteral') {
+ return attribute.value.value;
+ }
+
+ if (
+ attribute.value?.type === 'JSXExpressionContainer' &&
+ attribute.value.expression.type === 'StringLiteral'
+ ) {
+ return attribute.value.expression.value;
+ }
+ }
+
+ return null;
+};
+
+export const getRegistrationInsertionSourceEdit = ({
+ input,
+ ast,
+ insertion,
+ folder,
+}: {
+ input: string;
+ ast: File;
+ insertion: JSXElement;
+ folder: FolderReference | null;
+}): SourceEdit => {
+ let root: JSXElement | JSXFragment | null = null;
+ if (folder) {
+ const folders: string[] = [];
+ const matches: JSXElement[] = [];
+ recast.visit(ast, {
+ visitJSXElement(path) {
+ const element = path.node as JSXElement;
+ const name = getFolderNameFromJSXElement(element, ast);
+ if (name !== null) {
+ if (
+ name === folder.name &&
+ (folders.join('/') || null) === folder.parentName
+ ) {
+ matches.push(element);
+ }
+
+ folders.push(name);
+ }
+
+ this.traverse(path);
+ if (name !== null) {
+ folders.pop();
+ }
+
+ return false;
+ },
+ });
+ if (matches.length !== 1) {
+ throw new Error(
+ `Expected one folder matching ${JSON.stringify(folder)}, found ${matches.length}`,
+ );
+ }
+
+ root = matches[0];
+ } else {
+ const functions = new Map<
+ object,
+ {path: recast.types.NodePath; hasRegistration: boolean}
+ >();
+ recast.visit(ast, {
+ visitNode(path) {
+ const {node} = path as unknown as {node: Node};
+ if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
+ let parent = path.parentPath;
+ while (parent) {
+ if (recast.types.namedTypes.Function.check(parent.node)) {
+ functions.set(parent.node, {
+ path: parent,
+ hasRegistration:
+ functions.get(parent.node)?.hasRegistration === true ||
+ getRegistrationComponentType(node, ast) !== null,
+ });
+ break;
+ }
+
+ parent = parent.parentPath;
+ }
+ }
+
+ this.traverse(path);
+ return false;
+ },
+ });
+ // A JSX callback inside a registration component is part of that
+ // component's tree. Insert once in its outer return, not inside the callback.
+ const outerFunctions = [...functions.values()].filter((candidate) => {
+ let parent = candidate.path.parentPath;
+ let nested = false;
+ while (parent) {
+ const outer = functions.get(parent.node);
+ if (outer) {
+ nested = true;
+ outer.hasRegistration ||= candidate.hasRegistration;
+ }
+
+ parent = parent.parentPath;
+ }
+
+ return !nested;
+ });
+ const registered = outerFunctions.filter(
+ ({hasRegistration}) => hasRegistration,
+ );
+ const candidates = registered.length > 0 ? registered : outerFunctions;
+ if (candidates.length !== 1) {
+ throw new Error(
+ 'Adding registrations requires a single JSX component containing registrations, or a file with a single JSX component',
+ );
+ }
+
+ const target = candidates[0].path.node;
+ const roots: (JSXElement | JSXFragment)[] = [];
+ recast.visit(target as never, {
+ visitNode(path) {
+ const {node} = path as unknown as {node: Node};
+ if (recast.types.namedTypes.Function.check(node) && node !== target) {
+ return false;
+ }
+
+ const returned =
+ node.type === 'ReturnStatement'
+ ? node.argument
+ : node.type === 'ArrowFunctionExpression'
+ ? node.body
+ : null;
+ if (
+ returned?.type === 'JSXElement' ||
+ returned?.type === 'JSXFragment'
+ ) {
+ roots.push(returned as JSXElement | JSXFragment);
+ return false;
+ }
+
+ this.traverse(path);
+ return false;
+ },
+ });
+ if (roots.length !== 1) {
+ throw new Error(
+ 'Adding registrations requires a single JSX return in the registration component',
+ );
+ }
+
+ root = roots[0];
+ }
+
+ return getInsertionRootSourceEdit({
+ input,
+ insertion: printInsertedJsx({
+ element: insertion as never,
+ input,
+ prettierConfigOverride: null,
+ }),
+ root: root as never,
+ nullRoot: null,
+ prettierConfigOverride: null,
+ insertInside: folder !== null || root.type === 'JSXFragment',
+ });
+};
diff --git a/packages/codemods/src/rename-composition.ts b/packages/codemods/src/rename-composition.ts
index bc92508729..b8b98b6950 100644
--- a/packages/codemods/src/rename-composition.ts
+++ b/packages/codemods/src/rename-composition.ts
@@ -1,11 +1,17 @@
+import type {JSXElement} from '@babel/types';
import type {CodemodProject, CodemodResult} from './codemod-project';
import {getCodemodResult} from './codemod-project';
import {
type CompositionTarget,
requireComposition,
assertNewCompositionId,
- editCompositionProject,
} from './composition-editing';
+import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';
+import {parseAst} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ getJsxStringAttributeValueSourceEdit,
+} from './source-edits';
export type RenameCompositionOptions<Project extends CodemodProject> =
CompositionTarget & {project: Project; newId: string};
@@ -16,15 +22,38 @@ export const renameComposition = <Project extends CodemodProject>({
compositionId,
newId,
}: RenameCompositionOptions<Project>): CodemodResult<Project> => {
- requireComposition({project, compositionFile, compositionId});
+ const node = requireComposition({project, compositionFile, compositionId});
if (newId === compositionId) {
return getCodemodResult({project, nextProject: project});
}
assertNewCompositionId({project, compositionFile, compositionId: newId});
- return editCompositionProject({
+ const input = project.files[node.filePath];
+ const ast = parseAst(input);
+ const element = findJsxElementPathForDeletion(ast, node.nodePath)?.node as
+ | JSXElement
+ | undefined;
+ const attribute = element?.openingElement.attributes.find(
+ (attr) =>
+ attr.type === 'JSXAttribute' &&
+ attr.name.type === 'JSXIdentifier' &&
+ attr.name.name === 'id',
+ );
+ if (attribute?.type !== 'JSXAttribute') {
+ throw new Error('Could not locate the composition id');
+ }
+
+ const output = applySourceEdits({
+ input,
+ edits: [
+ getJsxStringAttributeValueSourceEdit({attribute, input, newValue: newId}),
+ ],
+ });
+ return getCodemodResult({
project,
- compositionFile,
- codemod: {type: 'rename-composition', idToRename: compositionId, newId},
+ nextProject: {
+ ...project,
+ files: {...project.files, [node.filePath]: output},
+ },
});
};
diff --git a/packages/codemods/src/rename-folder.ts b/packages/codemods/src/rename-folder.ts
index 64183e1438..5a72ab51e4 100644
--- a/packages/codemods/src/rename-folder.ts
+++ b/packages/codemods/src/rename-folder.ts
@@ -1,8 +1,13 @@
import type {AddFolderOptions} from './add-folder';
import type {CodemodProject} from './codemod-project';
import {getCodemodResult} from './codemod-project';
-import {editCompositionProject} from './composition-editing';
import {getTreeEntries, requireTreeItem} from './folder-editing';
+import {findProjectFile} from './internals';
+import {parseAst} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ getJsxStringAttributeValueSourceEdit,
+} from './source-edits';
export type RenameFolderOptions<Project extends CodemodProject> =
AddFolderOptions<Project> & {newName: string};
@@ -13,8 +18,10 @@ export const renameFolder = <Project extends CodemodProject>({
folder,
newName,
}: RenameFolderOptions<Project>) => {
- const entries = getTreeEntries({project, compositionFile});
- requireTreeItem(entries, {type: 'folder', ...folder});
+ const filePath = findProjectFile({project, filePath: compositionFile});
+ const input = project.files[filePath];
+ const entries = getTreeEntries({ast: parseAst(input)});
+ const located = requireTreeItem(entries, {type: 'folder', ...folder});
if (newName === folder.name) {
return getCodemodResult({project, nextProject: project});
}
@@ -34,14 +41,30 @@ export const renameFolder = <Project extends CodemodProject>({
throw new Error('A folder with this name already exists in the parent');
}
- return editCompositionProject({
+ const attribute = located.node.openingElement.attributes.find(
+ (candidate) =>
+ candidate.type === 'JSXAttribute' &&
+ candidate.name.type === 'JSXIdentifier' &&
+ candidate.name.name === 'name',
+ );
+ if (attribute?.type !== 'JSXAttribute')
+ throw new Error('Could not locate the folder name');
+ const nextContents = applySourceEdits({
+ input,
+ edits: [
+ getJsxStringAttributeValueSourceEdit({
+ attribute,
+ input,
+ newValue: newName,
+ }),
+ ],
+ });
+ parseAst(nextContents);
+ return getCodemodResult({
project,
- compositionFile,
- codemod: {
- type: 'rename-folder',
- folderName: folder.name,
- parentName: folder.parentName,
- newName,
+ nextProject: {
+ ...project,
+ files: {...project.files, [filePath]: nextContents},
},
});
};
diff --git a/packages/codemods/src/test/default-props.test.ts b/packages/codemods/src/test/default-props.test.ts
index eef96380c0..1ac2d0cd10 100644
--- a/packages/codemods/src/test/default-props.test.ts
+++ b/packages/codemods/src/test/default-props.test.ts
@@ -1,5 +1,7 @@
import {expect, test} from 'bun:test';
-import {computeCanUpdateDefaultPropsFromContent} from '../internals';
+import {CodemodsInternals} from '..';
+
+const {computeCanUpdateDefaultPropsFromContent} = CodemodsInternals;
test('extracts editable default props including special values', () => {
const source = `import {Composition, staticFile} from 'remotion';
diff --git a/packages/codemods/src/test/delete-jsx-nodes.test.ts b/packages/codemods/src/test/delete-jsx-nodes.test.ts
deleted file mode 100644
index 3e0b8d63ec..0000000000
--- a/packages/codemods/src/test/delete-jsx-nodes.test.ts
+++ /dev/null
@@ -1,290 +0,0 @@
-import {expect, test} from 'bun:test';
-import {deleteJsxNodes} from '../delete-jsx-nodes-internal';
-import {
- lineColumnToNodePath,
- lineContainingToNodePath,
-} from './node-path-test-utils';
-
-const sample = `import React from 'react';
-import {AbsoluteFill} from 'remotion';
-
-export const X: React.FC = () => {
- return (
- <AbsoluteFill>
- <div />
- </AbsoluteFill>
- );
-};
-`;
-
-test('deleteJsxNodes removes a JSX child from a parent element', async () => {
- const {output} = await deleteJsxNodes({
- input: sample,
- nodePaths: [lineColumnToNodePath(sample, 7)],
- });
-
- expect(output).not.toContain('<div');
- expect(output).toContain('<AbsoluteFill>');
-});
-
-const onlyReturn = `import React from 'react';
-
-export const X: React.FC = () => {
- return <div />;
-};
-`;
-
-test('deleteJsxNodes replaces sole return JSX with null', async () => {
- const {output} = await deleteJsxNodes({
- input: onlyReturn,
- nodePaths: [lineColumnToNodePath(onlyReturn, 4)],
- });
-
- expect(output).toContain('return null');
- expect(output).not.toContain('<div');
-});
-
-const conditional = `import React from 'react';
-
-export const X: React.FC<{show: boolean}> = ({show}) => {
- return <>{show && <div />}</>;
-};
-`;
-
-test('deleteJsxNodes turns conditional JSX into null', async () => {
- const {output} = await deleteJsxNodes({
- input: conditional,
- nodePaths: [lineColumnToNodePath(conditional, 4)],
- });
-
- expect(output).toContain('&& null');
- expect(output).not.toContain('<div');
-});
-
-const ternary = `import React from 'react';
-
-export const X: React.FC<{show: boolean}> = ({show}) => {
- return <>{show ? <div /> : null}</>;
-};
-`;
-
-test('deleteJsxNodes replaces JSX in ternary consequent with null', async () => {
- const {output} = await deleteJsxNodes({
- input: ternary,
- nodePaths: [lineColumnToNodePath(ternary, 4)],
- });
-
- expect(output).toMatch(/\?\s*null/);
- expect(output).not.toContain('<div');
-});
-
-const mapCase = `import React from 'react';
-
-export const X: React.FC = () => {
- return (
- <>
- {[1].map((i) => (
- <div key={i} />
- ))}
- </>
- );
-};
-`;
-
-test('deleteJsxNodes replaces JSX inside map callback', async () => {
- const {output} = await deleteJsxNodes({
- input: mapCase,
- nodePaths: [lineColumnToNodePath(mapCase, 7)],
- });
-
- expect(output).not.toContain('<div');
- expect(output).toMatch(/=>\s*\(?\s*null/);
-});
-
-const multipleSiblings = `import React from 'react';
-import {AbsoluteFill} from 'remotion';
-
-export const X: React.FC = () => {
- return (
- <AbsoluteFill>
- <div />
- <span />
- <p />
- </AbsoluteFill>
- );
-};
-`;
-
-test('deleteJsxNodes removes multiple JSX children in one transform', async () => {
- const {output, nodeLabels, logLines} = await deleteJsxNodes({
- input: multipleSiblings,
- nodePaths: [
- lineColumnToNodePath(multipleSiblings, 7),
- lineColumnToNodePath(multipleSiblings, 8),
- ],
- });
-
- expect(output).not.toContain('<div');
- expect(output).not.toContain('<span');
- expect(output).toContain('<p');
- expect(nodeLabels).toEqual(['<div>', '<span>']);
- expect(logLines).toEqual([7, 8]);
-});
-
-test('deleteJsxNodes preserves source formatting and removes standalone JSX lines', async () => {
- const cases = [
- {
- input: `export const Comp = () => {
- return (
- <div>
- <Keep />
- <RemoveOne />
- <RemoveTwo />
- <Keep />
- </div>
- );
-};
-`,
- markers: ['<RemoveOne', '<RemoveTwo'],
- expected: `export const Comp = () => {
- return (
- <div>
- <Keep />
- <Keep />
- </div>
- );
-};
-`,
- },
- {
- input: `export const Comp = () => {
- return (
- <div>
- <Remove />
- </div>
- )
-}
-`,
- markers: ['<Remove'],
- expected: `export const Comp = () => {
- return (
- <div>
- </div>
- )
-}
-`,
- },
- {
- input: `export const Comp = () => {
- return [1].map((item) => (
- <Remove key={item} />
- ));
-};
-`,
- markers: ['<Remove'],
- expected: `export const Comp = () => {
- return [1].map((item) => null);
-};
-`,
- },
- {
- input: `const AnimatedBar = () => {
- return (
- <Remove />
- );
-};
-`,
- markers: ['<Remove'],
- expected: `const AnimatedBar = () => {
- return null;
-};
-`,
- },
- {
- input: `const AnimatedBar = () => {
- return (
- // Keep this explanation.
- <Remove />
- );
-};
-`,
- markers: ['<Remove'],
- expected: `const AnimatedBar = () => {
- return (
- // Keep this explanation.
- null
- );
-};
-`,
- },
- {
- input: `export const Comp = () => <div><Keep /><Remove /><Keep /></div>;
-`,
- markers: ['<Remove'],
- expected: `export const Comp = () => <div><Keep /><Keep /></div>;
-`,
- },
- {
- input:
- 'export const Comp = () => <div><Keep />\t<Remove /><Keep /></div>;\n',
- markers: ['<Remove'],
- expected: 'export const Comp = () => <div><Keep />\t<Keep /></div>;\n',
- },
- {
- input: `export const Comp = () => (
- <div>
- <Remove /> {/* keep this comment */}
- </div>
-);
-`,
- markers: ['<Remove'],
- expected: `export const Comp = () => (
- <div>
- {/* keep this comment */}
- </div>
-);
-`,
- },
- {
- input: `export const Comp = () => {
- return (
- <div>
- <RemoveParent>
- <RemoveChild />
- </RemoveParent>
- <Keep />
- </div>
- );
-};
-`,
- markers: ['<RemoveParent', '<RemoveChild'],
- expected: `export const Comp = () => {
- return (
- <div>
- <Keep />
- </div>
- );
-};
-`,
- },
- {
- input:
- 'export const Comp = () => {\r\n\treturn (\r\n\t\t<div>\r\n\t\t\t<Remove />\r\n\t\t</div>\r\n\t);\r\n};\r\n',
- markers: ['<Remove'],
- expected:
- 'export const Comp = () => {\r\n\treturn (\r\n\t\t<div>\r\n\t\t</div>\r\n\t);\r\n};\r\n',
- },
- ] as const;
-
- for (const item of cases) {
- const {output, formatted} = await deleteJsxNodes({
- input: item.input,
- nodePaths: item.markers.map((marker) =>
- lineContainingToNodePath(item.input, marker),
- ),
- });
-
- expect(output).toBe(item.expected);
- expect(formatted).toBe(true);
- }
-});
diff --git a/packages/codemods/src/test/get-jsx-nodes.test.ts b/packages/codemods/src/test/get-jsx-elements-with-node-paths.test.ts
similarity index 56%
rename from packages/codemods/src/test/get-jsx-nodes.test.ts
rename to packages/codemods/src/test/get-jsx-elements-with-node-paths.test.ts
index 63edb1cac3..df3a5f8144 100644
--- a/packages/codemods/src/test/get-jsx-nodes.test.ts
+++ b/packages/codemods/src/test/get-jsx-elements-with-node-paths.test.ts
@@ -1,20 +1,14 @@
import {expect, test} from 'bun:test';
-import {getJsxNodes} from '../index';
+import {getJsxElementsWithNodePaths} from '../get-jsx-elements-with-node-paths';
-test('lists JSX nodes with their deletion paths in source order', () => {
- const elements = getJsxNodes({
- filePath: 'Video.tsx',
- project: {
- rootDir: '/',
- files: {
- 'Video.tsx': `export const Video = () => (
+test('lists JSX elements with their deletion paths in source order', () => {
+ const elements = getJsxElementsWithNodePaths({
+ source: `export const Video = () => (
<AbsoluteFill>
<Sequence name="Intro" />
<Series.Sequence durationInFrames={30} />
</AbsoluteFill>
);`,
- },
- },
});
expect(elements.map(({tagName}) => tagName)).toEqual([
diff --git a/packages/codemods/src/test/insert-solid.test.ts b/packages/codemods/src/test/insert-solid.test.ts
index 21dccc57ed..1b45307648 100644
--- a/packages/codemods/src/test/insert-solid.test.ts
+++ b/packages/codemods/src/test/insert-solid.test.ts
@@ -1,6 +1,10 @@
import {expect, test} from 'bun:test';
-import {insertJsxElementIntoProjectWithNodePathRemappings} from '../insert-jsx-element';
-import {insertSolidIntoSource} from '../internals';
+import {CodemodsInternals} from '..';
+
+const {
+ insertJsxElementIntoProjectWithNodePathRemappings,
+ insertSolidIntoSource,
+} = CodemodsInternals;
test('inserts a Solid into a component source file', () => {
const result = insertSolidIntoSource({
diff --git a/packages/codemods/src/test/node-path-test-utils.ts b/packages/codemods/src/test/node-path-test-utils.ts
deleted file mode 100644
index 6809ba3544..0000000000
--- a/packages/codemods/src/test/node-path-test-utils.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import type {SequenceNodePath} from 'remotion';
-import {getJsxNodes} from '../get-jsx-nodes';
-import {lineColumnToNodePath as _lineColumnToNodePath} from '../sequence-props';
-import {parseAst} from '../sequence-props/parse-ast';
-
-export const lineColumnToNodePath = (
- input: string,
- line: number,
-): SequenceNodePath => {
- const ast = parseAst(input);
- const result = _lineColumnToNodePath(ast, line);
- if (!result) {
- throw new Error(`No JSX element found at line ${line}`);
- }
-
- return result;
-};
-
-export const lineContainingToNodePath = (
- input: string,
- search: string,
-): SequenceNodePath => {
- const sourceLines = input.split('\n');
- const line = sourceLines.findIndex((sourceLine) =>
- sourceLine.includes(search),
- );
- if (line === -1) {
- throw new Error(`Could not find ${JSON.stringify(search)} in source`);
- }
-
- const column = sourceLines[line].indexOf(search);
- const result = getJsxNodes({
- project: {rootDir: '/', files: {'/test.tsx': input}},
- filePath: '/test.tsx',
- }).findLast(
- (node) =>
- node.location?.line === line + 1 && node.location.column <= column,
- )?.nodePath;
- if (!result) {
- throw new Error(`No JSX element found for ${JSON.stringify(search)}`);
- }
-
- return result;
-};
diff --git a/packages/codemods/src/test/public-editing.test.ts b/packages/codemods/src/test/public-editing.test.ts
index bb7847153b..bab99441de 100644
--- a/packages/codemods/src/test/public-editing.test.ts
+++ b/packages/codemods/src/test/public-editing.test.ts
@@ -30,7 +30,6 @@ import {
updateEffectProps,
updateJsxNodeKeyframes,
updateJsxNodeProps,
- updateMultipleJsxNodeProps,
type CodemodProject,
} from '../index';
@@ -269,13 +268,6 @@ export const VideoComposition = () => <><Video src="video.mp4" from={10} duratio
test('manage composition registrations and nested folders without changing components', () => {
const original = makeProject();
- const helper = 'const Helper = () => <div>Keep this helper unchanged</div>;';
- original.files[compositionFile] = original.files[compositionFile]
- .replace(
- 'export const Root = () => ',
- `export const Root = () => {\n${helper}\nreturn `,
- )
- .replace('/>;\n', '/>;\n};\n');
let {project} = addComposition({
project: original,
compositionFile,
@@ -283,7 +275,6 @@ test('manage composition registrations and nested folders without changing compo
component: {importName: 'Title', importPath: './Title'},
metadata: {width: 1920, height: 1080, fps: 30, durationInFrames: 60},
});
- expect(project.files[compositionFile]).toContain(helper);
project = setCompositionDefaultProps({
project,
compositionFile,
@@ -572,8 +563,7 @@ test('nested copies return root references and insertion preserves relative keys
test('reject ambiguous registration roots and unsupported splitting or audio detachment', async () => {
const project = makeProject();
- project.files[compositionFile] +=
- '\nconst AnotherRoot = () => <Composition id="Other" component={Video} />;';
+ project.files[compositionFile] += '\nconst AnotherComponent = () => <div />;';
expect(() =>
addComposition({
project,
@@ -605,78 +595,3 @@ test('node discovery and edits use original source locations with tabs and CRLF'
expect(edited.project.files[filePath].startsWith('\uFEFF')).toBe(true);
expect(edited.project.files[filePath]).toContain('\r\n');
});
-
-test('batch structured prop edits across files and preserve edit results in request order', () => {
- const project = {
- rootDir: '/',
- files: {
- 'first.tsx':
- 'export const First = () => <div style={{opacity: 0.5}} title="first" />;',
- 'second.tsx': 'export const Second = () => <div title="second" />;',
- },
- };
- const first = getJsxNodes({project, filePath: 'first.tsx'})[0];
- const second = getJsxNodes({project, filePath: 'second.tsx'})[0];
- const result = updateMultipleJsxNodeProps({
- project,
- changes: [
- {
- node: first,
- updates: [{key: 'style.opacity', value: 1, defaultValue: 1}],
- },
- {node: second, props: {title: 'updated second'}},
- {node: first, props: {title: 'updated first'}},
- ],
- });
-
- expect(result.changes).toHaveLength(2);
- expect(result.results[0].oldValueStrings).toEqual(['0.5']);
- expect(result.updatedNodes.map((node) => node.filePath)).toEqual([
- 'first.tsx',
- 'second.tsx',
- 'first.tsx',
- ]);
- expect(
- getJsxNodeProps({
- project: result.project,
- node: result.updatedNodes[0],
- keys: ['style.opacity', 'title'],
- }).props,
- ).toMatchObject({
- 'style.opacity': {codeValue: undefined},
- title: {codeValue: 'updated first'},
- });
- expect(
- getJsxNodeProps({
- project: result.project,
- node: result.updatedNodes[1],
- keys: ['title'],
- }).props.title,
- ).toMatchObject({codeValue: 'updated second'});
- expect(project.files['first.tsx']).toContain('opacity: 0.5');
-});
-
-test('set composition default props preserves serialized dates and enum assertions', () => {
- const input = `import {Composition} from 'remotion';
-const untouched = "keep this spacing";
-export const Root = () => <Composition id="Comp" defaultProps={{mode: 'old'}} />;
-`;
- const result = setCompositionDefaultProps({
- project: {rootDir: '/', files: {'Root.tsx': input}},
- compositionFile: 'Root.tsx',
- compositionId: 'Comp',
- defaultProps: {
- mode: 'fast',
- date: 'remotion-date:2026-07-29T00:00:00.000Z',
- },
- enumPaths: [['mode']],
- });
- expect(result.logLine).toBe(3);
- expect(result.project.files['Root.tsx']).toContain(
- 'const untouched = "keep this spacing";',
- );
- expect(result.project.files['Root.tsx']).toContain("mode: 'fast' as const");
- expect(result.project.files['Root.tsx']).toMatch(
- /date: new Date\(\s*'2026-07-29T00:00:00\.000Z',?\s*\)/,
- );
-});
diff --git a/packages/codemods/src/test/split-jsx-sequence.test.ts b/packages/codemods/src/test/split-jsx-sequence.test.ts
index abbd008bd6..f778ec527f 100644
--- a/packages/codemods/src/test/split-jsx-sequence.test.ts
+++ b/packages/codemods/src/test/split-jsx-sequence.test.ts
@@ -3,10 +3,6 @@ import * as recast from 'recast';
import {getNodePathForRecastPath} from '../sequence-props';
import {parseAst} from '../sequence-props/parse-ast';
import {splitJsxSequence, splitJsxSequences} from '../split-jsx-sequence';
-import {
- lineColumnToNodePath,
- lineContainingToNodePath,
-} from './node-path-test-utils';
test('splits fractional timing without persisting arithmetic noise', async () => {
const input =
@@ -79,254 +75,3 @@ test('splits multiple sibling sequences from the same source snapshot', async ()
nodePathRemappings.filter((remapping) => remapping.oldNodePath === null),
).toHaveLength(2);
});
-
-const wrap = (
- sequence: string,
-) => `import {AbsoluteFill, Img, Interactive, Sequence, Series, Solid} from 'remotion';
-import {Gif} from '@remotion/gif';
-
-export const Comp = () => {
- return (
- <>
- ${sequence}
- </>
- );
-};
-`;
-
-const sequenceLine = 7;
-const sequenceTimingKeys = ['from', 'durationInFrames', 'trimBefore'];
-
-const split = async (
- sequence: string,
- splitFrame: number,
- sequenceKeys = sequenceTimingKeys,
-) => {
- const input = wrap(sequence);
- const {output} = await splitJsxSequence({
- input,
- nodePath: lineColumnToNodePath(input, sequenceLine),
- sequenceKeys,
- splitFrame,
- });
-
- return output;
-};
-
-test('splitJsxSequence splits a sequence with no duration', async () => {
- const output = await split('<Sequence from={0} />', 30);
-
- expect(output).toContain('<Sequence from={0} durationInFrames={30} />');
- expect(output).toContain('<Sequence from={30} trimBefore={30} />');
-});
-
-test('splitJsxSequence remaps following JSX siblings', async () => {
- const input = wrap(
- '<Sequence name="split" from={0} durationInFrames={50} />\n\t\t\t<Sequence name="following" />',
- );
- const {output, nodePathRemappings} = await splitJsxSequence({
- input,
- nodePath: lineContainingToNodePath(input, 'name="split"'),
- sequenceKeys: sequenceTimingKeys,
- splitFrame: 30,
- });
-
- expect(nodePathRemappings).toEqual([
- {
- oldNodePath: lineContainingToNodePath(input, 'name="split"'),
- newNodePath: lineContainingToNodePath(output, 'name="split"'),
- },
- {
- oldNodePath: lineContainingToNodePath(input, 'name="following"'),
- newNodePath: lineContainingToNodePath(output, 'name="following"'),
- },
- {
- oldNodePath: null,
- newNodePath: lineContainingToNodePath(output, 'from={30}'),
- },
- ]);
-});
-
-test('splitJsxSequence omits right Infinity duration', async () => {
- const output = await split(
- '<Sequence from={0} durationInFrames={Infinity} />',
- 30,
- );
-
- expect(output).toContain('<Sequence from={0} durationInFrames={30} />');
- expect(output).toContain('<Sequence from={30} trimBefore={30} />');
- expect(output).not.toContain('durationInFrames={Infinity}');
-});
-
-test('splitJsxSequence keeps missing left from omitted', async () => {
- const output = await split('<Sequence durationInFrames={50} />', 30);
-
- expect(output).toContain('<Sequence durationInFrames={30} />');
- expect(output).toContain(
- '<Sequence from={30} durationInFrames={20} trimBefore={30} />',
- );
-});
-
-test('splitJsxSequence splits finite duration and trimBefore', async () => {
- const output = await split(
- '<Sequence from={10} durationInFrames={50} trimBefore={5} />',
- 30,
- );
-
- expect(output).toContain(
- '<Sequence from={10} durationInFrames={20} trimBefore={5} />',
- );
- expect(output).toContain(
- '<Sequence from={30} durationInFrames={30} trimBefore={25} />',
- );
-});
-
-test('splitJsxSequence preserves surrounding formatting without calling Prettier', async () => {
- const input = `const deliberatelyUnformatted = {value : true}
-
-export const Comp = () => {
- return (
- <>
- <Sequence
- name="clip"
- from={0}
- durationInFrames={50}
- >
- <div>Child</div>
- </Sequence>
- <Keep prop = {1}/>
- </>
- )
-}
-`;
- const {output} = await splitJsxSequence({
- input,
- nodePath: lineContainingToNodePath(input, '<Sequence'),
- sequenceKeys: sequenceTimingKeys,
- splitFrame: 30,
- });
-
- expect(output).toStartWith(
- 'const deliberatelyUnformatted = {value : true}\n',
- );
- expect(output).toContain(
- '<Sequence name="clip" from={0} durationInFrames={30}>\n',
- );
- expect(output).toContain(
- '<Sequence name="clip" from={30} durationInFrames={20} trimBefore={30}>\n',
- );
- expect(output).toContain(' <Keep prop = {1}/>');
- expect(output).toEndWith(' )\n}\n');
-});
-
-test('splitJsxSequence formats a split component root as a fragment', async () => {
- const input = `export const Comp = () => <Sequence from={0} durationInFrames={50}><span>Hi</span></Sequence>;
-
-const keep = { value : true }
-`;
- const {output} = await splitJsxSequence({
- input,
- nodePath: lineContainingToNodePath(input, '<Sequence'),
- sequenceKeys: sequenceTimingKeys,
- splitFrame: 30,
- });
-
- expect(output).toBe(`export const Comp = () => <>
- <Sequence from={0} durationInFrames={30}>
- <span>Hi</span>
- </Sequence>
- <Sequence from={30} durationInFrames={20} trimBefore={30}>
- <span>Hi</span>
- </Sequence>
-</>;
-
-const keep = { value : true }
-`);
-});
-
-test('splitJsxSequence splits a video with a negative from', async () => {
- const output = await split(
- '<Video src="video.mov" from={-2644} trimBefore={272} />',
- 100,
- );
-
- expect(output).toContain('from={-2644}');
- expect(output).toContain('durationInFrames={2744}');
- expect(output).toContain('trimBefore={272}');
- expect(output).toContain(
- '<Video src="video.mov" from={100} trimBefore={3016} />',
- );
-});
-
-test('splitJsxSequence splits from-only sequence', async () => {
- const output = await split('<Sequence from={10} />', 30);
-
- expect(output).toContain('<Sequence from={10} durationInFrames={20} />');
- expect(output).toContain('<Sequence from={30} trimBefore={20} />');
-});
-
-test('splitJsxSequence splits sequence-backed components', async () => {
- expect(
- await split('<AbsoluteFill from={0} durationInFrames={50} />', 30),
- ).toContain(
- '<AbsoluteFill from={30} durationInFrames={20} trimBefore={30} />',
- );
- expect(
- await split('<Img src="image.png" from={0} durationInFrames={50} />', 30),
- ).toContain(
- '<Img src="image.png" from={30} durationInFrames={20} trimBefore={30} />',
- );
- expect(
- await split('<Gif src="anim.gif" from={0} durationInFrames={50} />', 30),
- ).toContain(
- '<Gif src="anim.gif" from={30} durationInFrames={20} trimBefore={30} />',
- );
- const solidOutput = await split(
- '<Solid width={100} height={100} from={0} durationInFrames={50} />',
- 30,
- );
- expect(solidOutput).toContain(
- '<Solid width={100} height={100} from={0} durationInFrames={30} />',
- );
- expect(solidOutput).toContain('from={30}');
- expect(solidOutput).toContain('durationInFrames={20}');
- expect(solidOutput).toContain('trimBefore={30}');
- expect(
- await split('<Interactive.Div from={0} durationInFrames={50} />', 30),
- ).toContain(
- '<Interactive.Div from={30} durationInFrames={20} trimBefore={30} />',
- );
-});
-
-test('splitJsxSequence rejects boundary and dynamic splits', async () => {
- await expect(
- split('<Sequence from={10} durationInFrames={20} />', 10),
- ).rejects.toThrow(/sequence start/);
- await expect(
- split('<Sequence from={10} durationInFrames={20} />', 30),
- ).rejects.toThrow(/sequence end/);
- await expect(
- split('<Sequence from={10} durationInFrames={20} />', 8),
- ).rejects.toThrow(/sequence start/);
- await expect(
- split('<Sequence from={10} durationInFrames={20} />', 10.5),
- ).rejects.toThrow(/integer/);
- await expect(
- split('<Sequence from={start} durationInFrames={20} />', 15),
- ).rejects.toThrow(/dynamic from/);
-});
-
-test('splitJsxSequence rejects Series.Sequence', async () => {
- await expect(
- split('<Series.Sequence durationInFrames={50} />', 30, [
- 'durationInFrames',
- 'trimBefore',
- ]),
- ).rejects.toThrow('<Series.Sequence> cannot be split');
-});
-
-test('splitJsxSequence rejects regular DOM elements', async () => {
- await expect(
- split('<div from={0} durationInFrames={50} />', 30, []),
- ).rejects.toThrow('<div> cannot be split');
-});
diff --git a/packages/codemods/src/test/split-video-from-audio.test.ts b/packages/codemods/src/test/split-video-from-audio.test.ts
deleted file mode 100644
index b7c6369d7b..0000000000
--- a/packages/codemods/src/test/split-video-from-audio.test.ts
+++ /dev/null
@@ -1,266 +0,0 @@
-import {expect, test} from 'bun:test';
-import {splitVideoFromAudio} from '../split-video-from-audio';
-import {lineContainingToNodePath} from './node-path-test-utils';
-
-const wrap = (
- element: string,
- imports = `import {Video} from '@remotion/media';`,
-) => `${imports}
-
-export const Comp = () => {
- return (
- <>
- ${element}
- </>
- );
-};
-`;
-
-const split = async (element: string, imports?: string) => {
- const input = wrap(element, imports);
- const {output} = await splitVideoFromAudio({
- input,
- nodePath: lineContainingToNodePath(input, element),
- });
-
- return output;
-};
-
-test('splitVideoFromAudio mutes the video and adds an Audio with the same timing', async () => {
- const output = await split(
- '<Video src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} style={{opacity: 0.5}} />',
- );
-
- const singleLine = output.replace(/\s+/g, ' ');
-
- expect(output).toContain(`import {Video, Audio} from '@remotion/media';`);
- expect(singleLine).toContain(
- '<Video src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} style={{opacity: 0.5}} muted />',
- );
- expect(singleLine).toContain(
- '<Audio src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} />',
- );
-});
-
-test('splitVideoFromAudio preserves unrelated source formatting without calling the formatter', async () => {
- const input = `import{Video}from"@remotion/media"
-
-const untouched = {keep : "spacing"}
-export const Comp=()=>(
- <>
- <Video
- src = {"video.mp4"}
- from = {10}
- style = {{opacity:.5}}
- />
- <div data-value = "unchanged"/>
- </>
-)
-`;
- let formatCalls = 0;
- const {formatted, nodePathRemappings, output} = await splitVideoFromAudio({
- input,
- nodePath: lineContainingToNodePath(input, '<Video'),
- formatFile: () => {
- formatCalls++;
- throw new Error('Prettier must not be called');
- },
- });
-
- expect(formatCalls).toBe(0);
- expect(formatted).toBe(true);
- expect(output).toBe(`import{Video, Audio}from"@remotion/media"
-
-const untouched = {keep : "spacing"}
-export const Comp=()=>(
- <>
- <Video
- src = {"video.mp4"}
- from = {10}
- style = {{opacity:.5}}
- muted
- />
- <Audio src={"video.mp4"} from={10} />
- <div data-value = "unchanged"/>
- </>
-)
-`);
- expect(nodePathRemappings).toEqual([
- {
- oldNodePath: lineContainingToNodePath(input, '<Video'),
- newNodePath: lineContainingToNodePath(output, '<Video'),
- },
- {
- oldNodePath: lineContainingToNodePath(input, '<div'),
- newNodePath: lineContainingToNodePath(output, '<div'),
- },
- {
- oldNodePath: null,
- newNodePath: lineContainingToNodePath(output, '<Audio'),
- },
- ]);
-});
-
-test('splitVideoFromAudio does not copy non-audio props', async () => {
- const output = await split(
- '<Video src="video.mp4" name="my video" freeze={20} crop={{x: 0, y: 0, width: 100, height: 100}} />',
- );
-
- expect(output).toContain('<Audio src="video.mp4" />');
-});
-
-test('splitVideoFromAudio wraps a root video in a fragment', async () => {
- const input = `import {Video} from '@remotion/media';
-
-export const Comp = () => <Video src="video.mp4" />;
-`;
- const {output} = await splitVideoFromAudio({
- input,
- nodePath: lineContainingToNodePath(input, '<Video'),
- });
-
- expect(output).toBe(`import {Video, Audio} from '@remotion/media';
-
-export const Comp = () => <>
- <Video src="video.mp4" muted />
- <Audio src="video.mp4" />
-</>;
-`);
-});
-
-test('splitVideoFromAudio separates siblings with one space on a shared line', async () => {
- const input = `import {Video} from '@remotion/media';
-
-export const Comp = () => (
- <div>
- <Video src="video.mp4" /></div>
-);
-`;
- const {output} = await splitVideoFromAudio({
- input,
- nodePath: lineContainingToNodePath(input, '<Video'),
- });
-
- expect(output).toBe(`import {Video, Audio} from '@remotion/media';
-
-export const Comp = () => (
- <div>
- <Video src="video.mp4" muted /> <Audio src="video.mp4" /></div>
-);
-`);
-});
-
-test('splitVideoFromAudio preserves CRLF and tab indentation', async () => {
- const input = [
- `import {Video} from '@remotion/media';`,
- '',
- 'export const Comp = () => {',
- '\treturn (',
- '\t\t<>',
- '\t\t\t<Video',
- '\t\t\t\tsrc="video.mp4"',
- '\t\t\t\ttrimBefore={10}',
- '\t\t\t/>',
- '\t\t</>',
- '\t);',
- '};',
- '',
- ].join('\r\n');
- const {output} = await splitVideoFromAudio({
- input,
- nodePath: lineContainingToNodePath(input, '<Video'),
- });
-
- expect(output).toBe(
- [
- `import {Video, Audio} from '@remotion/media';`,
- '',
- 'export const Comp = () => {',
- '\treturn (',
- '\t\t<>',
- '\t\t\t<Video',
- '\t\t\t\tsrc="video.mp4"',
- '\t\t\t\ttrimBefore={10}',
- '\t\t\t\tmuted',
- '\t\t\t/>',
- '\t\t\t<Audio src="video.mp4" trimBefore={10} />',
- '\t\t</>',
- '\t);',
- '};',
- '',
- ].join('\r\n'),
- );
-});
-
-test('splitVideoFromAudio replaces an existing muted prop', async () => {
- const output = await split('<Video src="video.mp4" muted={false} />');
-
- expect(output).toContain('<Video src="video.mp4" muted />');
- expect(output).not.toContain('muted={false}');
-});
-
-test('splitVideoFromAudio reuses an existing Audio import', async () => {
- const output = await split(
- '<Video src="video.mp4" />',
- `import {Audio, Video} from '@remotion/media';`,
- );
-
- expect(output).toContain(`import {Audio, Video} from '@remotion/media';`);
- expect(output.match(/from '@remotion\/media'/g)?.length).toBe(1);
-});
-
-test('splitVideoFromAudio uses an aliased Audio import', async () => {
- const output = await split(
- '<Video src="video.mp4" />',
- `import {Audio as Sound, Video} from '@remotion/media';`,
- );
-
- expect(output).toContain(
- `import {Audio as Sound, Video} from '@remotion/media';`,
- );
- expect(output).toContain('<Sound src="video.mp4" />');
-});
-
-test('splitVideoFromAudio imports Audio from the same module as the tag', async () => {
- const output = await split(
- '<OffthreadVideo src="video.mp4" from={5} />',
- `import {OffthreadVideo} from 'remotion';`,
- );
-
- expect(output).toContain(`import {OffthreadVideo, Audio} from 'remotion';`);
- expect(output).toContain('<OffthreadVideo src="video.mp4" from={5} muted />');
- expect(output).toContain('<Audio src="video.mp4" from={5} />');
-});
-
-test('splitVideoFromAudio follows import aliases', async () => {
- const output = await split(
- '<V src="video.mp4" />',
- `import {Video as V} from '@remotion/media';`,
- );
-
- expect(output).toContain(
- `import {Video as V, Audio} from '@remotion/media';`,
- );
- expect(output).toContain('<Audio src="video.mp4" />');
-});
-
-test('splitVideoFromAudio rejects elements without a src attribute', async () => {
- await expect(split('<Video from={0} />')).rejects.toThrow(
- '<Video> has no src attribute',
- );
-});
-
-test('splitVideoFromAudio rejects unimported tags', async () => {
- await expect(split('<video src="video.mp4" />')).rejects.toThrow(
- 'Could not find the import of <video>',
- );
-});
-
-test('splitVideoFromAudio rejects an Audio import from another module', async () => {
- await expect(
- split(
- '<Video src="video.mp4" />',
- `import {Video} from '@remotion/media';\nimport {Audio} from 'remotion';`,
- ),
- ).rejects.toThrow('Audio is already imported from "remotion"');
-});
diff --git a/packages/codemods/src/unwrap-folder.ts b/packages/codemods/src/unwrap-folder.ts
index 4657190591..020a9aa289 100644
--- a/packages/codemods/src/unwrap-folder.ts
+++ b/packages/codemods/src/unwrap-folder.ts
@@ -1,7 +1,11 @@
import type {AddFolderOptions} from './add-folder';
import type {CodemodProject} from './codemod-project';
-import {editCompositionProject} from './composition-editing';
+import {getCodemodResult} from './codemod-project';
import {requireTreeItem, getTreeEntries} from './folder-editing';
+import {getUnwrapFolderSourceEdit} from './folder-source-edits';
+import {findProjectFile} from './internals';
+import {parseAst} from './sequence-props/parse-ast';
+import {applySourceEdits} from './source-edits';
export type UnwrapFolderOptions<Project extends CodemodProject> =
AddFolderOptions<Project>;
@@ -11,17 +15,22 @@ export const unwrapFolder = <Project extends CodemodProject>({
compositionFile,
folder,
}: UnwrapFolderOptions<Project>) => {
- requireTreeItem(getTreeEntries({project, compositionFile}), {
+ const filePath = findProjectFile({project, filePath: compositionFile});
+ const input = project.files[filePath];
+ const located = requireTreeItem(getTreeEntries({ast: parseAst(input)}), {
type: 'folder',
...folder,
});
- return editCompositionProject({
+ const nextContents = applySourceEdits({
+ input,
+ edits: [getUnwrapFolderSourceEdit({input, located})],
+ });
+ parseAst(nextContents);
+ return getCodemodResult({
project,
- compositionFile,
- codemod: {
- type: 'delete-folder',
- folderName: folder.name,
- parentName: folder.parentName,
+ nextProject: {
+ ...project,
+ files: {...project.files, [filePath]: nextContents},
},
});
};
diff --git a/packages/codemods/src/update-composition-metadata.ts b/packages/codemods/src/update-composition-metadata.ts
index 21deb61881..2629b41077 100644
--- a/packages/codemods/src/update-composition-metadata.ts
+++ b/packages/codemods/src/update-composition-metadata.ts
@@ -1,3 +1,4 @@
+import type {JSXElement} from '@babel/types';
import type {CodemodProject, CodemodResult} from './codemod-project';
import {getCodemodResult} from './codemod-project';
import {
@@ -5,8 +6,12 @@ import {
type CompositionMetadata,
requireComposition,
validateMetadata,
- editCompositionProject,
} from './composition-editing';
+import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';
+import {recastLocToOffset} from './recast-loc-to-offset';
+import {parseAst} from './sequence-props/parse-ast';
+import {applySourceEdits, type SourceEdit} from './source-edits';
+import {getEndOfLine, getIndentationUnit, getLineIndent} from './source-style';
export type UpdateCompositionMetadataOptions<Project extends CodemodProject> =
CompositionTarget & {
@@ -33,16 +38,116 @@ export const updateCompositionMetadata = <Project extends CodemodProject>({
return getCodemodResult({project, nextProject: project});
}
- return editCompositionProject({
+ const input = project.files[node.filePath];
+ const ast = parseAst(input);
+ const element = findJsxElementPathForDeletion(ast, node.nodePath)?.node as
+ | JSXElement
+ | undefined;
+ if (!element) {
+ throw new Error('Could not locate the composition metadata');
+ }
+
+ const edits: SourceEdit[] = [];
+ const updates = (['fps', 'durationInFrames', 'width', 'height'] as const).map(
+ (name) => ({name, value: metadata[name] ?? null}),
+ );
+ const existingMetadata = new Set<string>();
+
+ for (const metadataAttribute of element.openingElement.attributes) {
+ if (
+ metadataAttribute.type !== 'JSXAttribute' ||
+ metadataAttribute.name.type !== 'JSXIdentifier'
+ ) {
+ continue;
+ }
+
+ const update = updates.find(
+ (item) => item.name === metadataAttribute.name.name,
+ );
+ if (!update || update.value === null) {
+ continue;
+ }
+
+ existingMetadata.add(update.name);
+ if (metadataAttribute.value?.loc) {
+ edits.push({
+ start: recastLocToOffset(input, metadataAttribute.value.loc.start),
+ end: recastLocToOffset(input, metadataAttribute.value.loc.end),
+ replacement: `{${update.value}}`,
+ });
+ } else if (metadataAttribute.loc) {
+ const start = recastLocToOffset(input, metadataAttribute.loc.start);
+ const end = recastLocToOffset(input, metadataAttribute.loc.end);
+ edits.push({
+ start,
+ end,
+ replacement: `${input.slice(start, end)}={${update.value}}`,
+ });
+ } else {
+ throw new Error(`Could not locate the "${update.name}" attribute`);
+ }
+ }
+
+ const missingMetadata = updates.filter(
+ (item) => item.value !== null && !existingMetadata.has(item.name),
+ );
+ if (missingMetadata.length > 0) {
+ const {openingElement} = element;
+ if (!openingElement.loc || !openingElement.name.loc) {
+ throw new Error('Could not locate the composition opening element');
+ }
+
+ const openingEnd = recastLocToOffset(input, openingElement.loc.end);
+ const closingStart = openingEnd - (openingElement.selfClosing ? 2 : 1);
+ const lastAttribute = openingElement.attributes.findLast(
+ (candidate) => candidate.loc,
+ );
+ const anchor = lastAttribute?.loc?.end ?? openingElement.name.loc.end;
+ const anchorOffset = recastLocToOffset(input, anchor);
+ const rendered = missingMetadata.map(
+ (item) => `${item.name}={${item.value}}`,
+ );
+
+ if (input.slice(anchorOffset, closingStart).includes('\n')) {
+ const closingLineStart = input.lastIndexOf('\n', closingStart - 1) + 1;
+ const attributeIndent =
+ lastAttribute?.loc &&
+ lastAttribute.loc.start.line > openingElement.name.loc.end.line
+ ? getLineIndent({
+ input,
+ offset: recastLocToOffset(input, lastAttribute.loc.start),
+ })
+ : getLineIndent({
+ input,
+ offset: recastLocToOffset(input, openingElement.loc.start),
+ }) + getIndentationUnit(input, null);
+ const endOfLine = getEndOfLine(input);
+ edits.push({
+ start: closingLineStart,
+ end: closingLineStart,
+ replacement:
+ rendered
+ .map(
+ (renderedAttribute) => `${attributeIndent}${renderedAttribute}`,
+ )
+ .join(endOfLine) + endOfLine,
+ });
+ } else {
+ edits.push({
+ start: anchorOffset,
+ end: anchorOffset,
+ replacement: ` ${rendered.join(' ')}`,
+ });
+ }
+ }
+
+ const output = applySourceEdits({input, edits});
+ parseAst(output);
+ return getCodemodResult({
project,
- compositionFile,
- codemod: {
- type: 'update-composition-metadata',
- idToUpdate: compositionId,
- newWidth: metadata.width ?? null,
- newHeight: metadata.height ?? null,
- newFps: metadata.fps ?? null,
- newDurationInFrames: metadata.durationInFrames ?? null,
+ nextProject: {
+ ...project,
+ files: {...project.files, [node.filePath]: output},
},
});
};
diff --git a/packages/codemods/src/apply-visual-control.ts b/packages/codemods/src/update-visual-controls.ts
similarity index 70%
rename from packages/codemods/src/apply-visual-control.ts
rename to packages/codemods/src/update-visual-controls.ts
index 0408bb95bb..6b6e6f3394 100644
--- a/packages/codemods/src/apply-visual-control.ts
+++ b/packages/codemods/src/update-visual-controls.ts
@@ -1,10 +1,16 @@
import {
stringifyDefaultProps,
- type ApplyVisualControlCodemod,
+ type VisualControlChange,
} from '@remotion/studio-shared';
import type {ExpressionKind} from 'ast-types/lib/gen/kinds';
import * as recast from 'recast';
+import {
+ getCodemodResult,
+ type CodemodProject,
+ type CodemodResult,
+} from './codemod-project';
import {formatSerializedValue} from './format-serialized-value';
+import {findProjectFile} from './internals';
import {recastLocToOffset} from './recast-loc-to-offset';
import {parseAst} from './sequence-props/parse-ast';
import {applySourceEdits, type SourceEdit} from './source-edits';
@@ -23,7 +29,7 @@ const expectString = (
if (node.type === 'TemplateLiteral') {
if (node.expressions.length > 0) {
throw new Error(
- 'applyVisualControl() must use a static identifier, the string may not be dynamic.',
+ 'visualControl() must use a static identifier, the string may not be dynamic.',
);
}
@@ -33,18 +39,26 @@ const expectString = (
throw new Error('Expected a string literal');
};
-export const applyVisualControl = ({
- input,
- transformation,
-}: {
- input: string;
- transformation: ApplyVisualControlCodemod;
-}): {
- newContents: string;
- changesMade: {description: string}[];
-} => {
+export type UpdateVisualControlsOptions<Project extends CodemodProject> = {
+ project: Project;
+ filePath: string;
+ changes: VisualControlChange[];
+};
+
+export type UpdateVisualControlsResult<Project extends CodemodProject> =
+ CodemodResult<Project> & {
+ updatedControls: {id: string; line: number}[];
+ };
+
+export const updateVisualControls = <Project extends CodemodProject>({
+ project,
+ filePath,
+ changes,
+}: UpdateVisualControlsOptions<Project>): UpdateVisualControlsResult<Project> => {
+ const resolvedFilePath = findProjectFile({project, filePath});
+ const input = project.files[resolvedFilePath];
const file = parseAst(input);
- const changesMade: {description: string}[] = [];
+ const updatedControls: {id: string; line: number}[] = [];
const edits: SourceEdit[] = [];
recast.types.visit(file.program, {
@@ -65,7 +79,7 @@ export const applyVisualControl = ({
const firstArgument = node.arguments[0];
const str = expectString(firstArgument);
- const matchingChanges = transformation.changes.filter(
+ const matchingChanges = changes.filter(
(candidate) => candidate.id === str,
);
const change = matchingChanges.at(-1);
@@ -122,8 +136,9 @@ export const applyVisualControl = ({
}
for (const matchingChange of matchingChanges) {
- changesMade.push({
- description: `Applied visual control ${matchingChange.id}`,
+ updatedControls.push({
+ id: matchingChange.id,
+ line: node.loc?.start.line ?? 1,
});
}
@@ -131,5 +146,17 @@ export const applyVisualControl = ({
},
});
- return {newContents: applySourceEdits({input, edits}), changesMade};
+ return {
+ ...getCodemodResult({
+ project,
+ nextProject: {
+ ...project,
+ files: {
+ ...project.files,
+ [resolvedFilePath]: applySourceEdits({input, edits}),
+ },
+ },
+ }),
+ updatedControls,
+ };
};
diff --git a/packages/studio-server/src/codemods/apply-codemod-to-file.ts b/packages/studio-server/src/codemods/apply-codemod-to-file.ts
index 8ce0110db0..90335f462f 100644
--- a/packages/studio-server/src/codemods/apply-codemod-to-file.ts
+++ b/packages/studio-server/src/codemods/apply-codemod-to-file.ts
@@ -2,7 +2,9 @@ import {existsSync} from 'node:fs';
import {readFile} from 'node:fs/promises';
import path from 'node:path';
import {
- CodemodsInternals,
+ addCanvasCaptureComposition,
+ updateVisualControls,
+ type CodemodProject,
addComposition,
addFolder,
deleteComposition,
@@ -19,11 +21,10 @@ import type {
RecastCodemod,
SymbolicatedStackFrame,
} from '@remotion/studio-shared';
+import {emptyCompositionComponent} from '@remotion/studio-shared';
import {resolveFileInsideProject} from '../helpers/resolve-file-inside-project';
import {checkIfTypeScriptFile} from '../preview-server/routes/can-update-default-props';
-const {parseAndApplyCodemod} = CodemodsInternals;
-
export const resolveFilePathFromSymbolicatedStack = (
remotionRoot: string,
stack: SymbolicatedStackFrame,
@@ -53,7 +54,7 @@ export const applyCodemodToFile = async ({
}: {
filePath: string;
codeMod: RecastCodemod;
-}): Promise<string> => {
+}): Promise<CodemodProject> => {
checkIfTypeScriptFile(filePath);
const input = await readFile(filePath, 'utf-8');
@@ -61,18 +62,30 @@ export const applyCodemodToFile = async ({
project: {files: {[filePath]: input}, rootDir: path.dirname(filePath)},
compositionFile: filePath,
};
- if (
- codeMod.type === 'apply-visual-control' ||
- (codeMod.type === 'new-composition' && codeMod.canvasCapture !== null)
- ) {
- return parseAndApplyCodemod({input, codeMod}).newContents;
+ if (codeMod.type === 'apply-visual-control') {
+ return updateVisualControls({
+ ...options,
+ filePath,
+ changes: codeMod.changes,
+ }).project;
}
if (codeMod.type === 'new-composition') {
- return addComposition({
+ const componentFilePath = path.join(
+ path.dirname(filePath),
+ `${codeMod.componentName}.tsx`,
+ );
+ if (existsSync(componentFilePath)) {
+ throw new Error(
+ `Cannot create ${componentFilePath} because it already exists`,
+ );
+ }
+
+ const composition = {
...options,
compositionId: codeMod.newId,
component: {
+ filePath: componentFilePath,
importName: codeMod.componentName,
importPath: codeMod.componentImportPath,
},
@@ -86,7 +99,22 @@ export const applyCodemodToFile = async ({
codeMod.folderName === null
? undefined
: {name: codeMod.folderName, parentName: codeMod.parentName},
- }).project.files[filePath];
+ };
+ if (codeMod.canvasCapture !== null) {
+ return addCanvasCaptureComposition({
+ ...composition,
+ capture: codeMod.canvasCapture,
+ }).project;
+ }
+
+ const result = addComposition(composition).project;
+ return {
+ ...result,
+ files: {
+ ...result.files,
+ [componentFilePath]: emptyCompositionComponent(codeMod.componentName),
+ },
+ };
}
if (codeMod.type === 'rename-composition') {
@@ -94,12 +122,12 @@ export const applyCodemodToFile = async ({
...options,
compositionId: codeMod.idToRename,
newId: codeMod.newId,
- }).project.files[filePath];
+ }).project;
}
if (codeMod.type === 'delete-composition') {
return deleteComposition({...options, compositionId: codeMod.idToDelete})
- .project.files[filePath];
+ .project;
}
if (
@@ -132,7 +160,7 @@ export const applyCodemodToFile = async ({
compositionId: codeMod.idToUpdate,
metadata,
});
- return result.project.files[filePath];
+ return result.project;
}
if (codeMod.type === 'move-composition-to-folder') {
@@ -149,7 +177,7 @@ export const applyCodemodToFile = async ({
parentName: codeMod.parentName,
},
},
- }).project.files[filePath];
+ }).project;
}
if (codeMod.type === 'move-composition-or-folder') {
@@ -188,7 +216,7 @@ export const applyCodemodToFile = async ({
},
destination,
});
- return result.project.files[filePath];
+ return result.project;
}
const folder = {name: codeMod.folderName, parentName: codeMod.parentName};
@@ -198,5 +226,5 @@ export const applyCodemodToFile = async ({
: codeMod.type === 'rename-folder'
? renameFolder({...options, folder, newName: codeMod.newName})
: unwrapFolder({...options, folder});
- return folderResult.project.files[filePath];
+ return folderResult.project;
};
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index d4fdf0328e..b266b7aa58 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -1,4 +1,4 @@
-import {formatBytes, type RecastCodemod} from '@remotion/studio-shared';
+import {formatBytes} from '@remotion/studio-shared';
export {
ApiRoutes,
CopyStillToClipboardRequest,
@@ -66,15 +66,6 @@ import {startStudio} from './start-studio';
const {updateDefaultProps} = CodemodsInternals;
-const parseAndApplyCodemod = ({
- input,
- codeMod,
-}: {
- input: string;
- codeMod: RecastCodemod;
-}): {newContents: string; changesMade: {description: string}[]} =>
- CodemodsInternals.parseAndApplyCodemod({input, codeMod});
-
export type {
RemotionSkillsScope,
RemotionSkillsStatus,
@@ -103,7 +94,6 @@ export const StudioServerInternals = {
setFileWatcherRegistry,
AnsiDiff,
formatBytes,
- parseAndApplyCodemod,
applyCodemodToFile,
updateDefaultProps,
getInstalledDependencies,
diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
index 1f468b54ab..a87830bb69 100644
--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts
+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
@@ -25,11 +25,7 @@ import {
withSourceFileWriteQueue,
} from './source-file-write-queue';
-const {makeNewCompositionComponentSource, simpleDiff} = CodemodsInternals;
-
-export const formatNewCompositionFile = (
- codemod: Extract<ApplyCodemodRequest['codemod'], {type: 'new-composition'}>,
-) => makeNewCompositionComponentSource(codemod);
+const {simpleDiff} = CodemodsInternals;
const getFolderPath = (parentName: string | null, folderName: string) => {
return parentName ? `${parentName}/${folderName}` : folderName;
@@ -246,11 +242,13 @@ export const applyCodemodHandler: ApiHandler<
}
const input = readFileSync(filePath, 'utf-8');
- const formatted = await applyCodemodToFile({
+ const nextProject = await applyCodemodToFile({
filePath,
codeMod: codemod,
});
+ const formatted = nextProject.files[filePath];
+
const diff = simpleDiff({
oldLines: input.split('\n'),
newLines: formatted.split('\n'),
@@ -279,7 +277,7 @@ export const applyCodemodHandler: ApiHandler<
throw new Error('Could not determine the new component file path');
}
- componentFileContents = await formatNewCompositionFile(codemod);
+ componentFileContents = nextProject.files[componentFilePath];
snapshots.push({
filePath: componentFilePath,
oldContents: null,
diff --git a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts
index fbcc8a6b11..e980c265e4 100644
--- a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts
+++ b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts
@@ -1,13 +1,10 @@
import {readFileSync} from 'node:fs';
-import type {File} from '@babel/types';
-import {CodemodsInternals} from '@remotion/codemods';
+import {updateVisualControls} from '@remotion/codemods';
import {RenderInternals} from '@remotion/renderer';
import type {
ApplyVisualControlRequest,
ApplyVisualControlResponse,
} from '@remotion/studio-shared';
-import * as recast from 'recast';
-import {parseAst} from '../../codemods/parse-ast';
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
@@ -24,31 +21,6 @@ import {
withSourceFileWriteQueue,
} from './source-file-write-queue';
-const {applyVisualControl} = CodemodsInternals;
-
-const getVisualControlChangeLine = (file: File, changeId: string): number => {
- let line = 1;
- recast.types.visit(file.program, {
- visitCallExpression(callPath) {
- const {node} = callPath;
- if (
- node.callee.type === 'Identifier' &&
- node.callee.name === 'visualControl'
- ) {
- const firstArg = node.arguments[0];
- if (firstArg?.type === 'StringLiteral' && firstArg.value === changeId) {
- line = node.loc?.start.line ?? 1;
- return false;
- }
- }
-
- this.traverse(callPath);
- },
- });
-
- return line;
-};
-
export const applyVisualControlHandler: ApiHandler<
ApplyVisualControlRequest,
ApplyVisualControlResponse
@@ -65,19 +37,18 @@ export const applyVisualControlHandler: ApiHandler<
});
const fileContents = readFileSync(absolutePath, 'utf-8');
- const ast = parseAst(fileContents);
- const logLine =
- changes.length > 0 ? getVisualControlChangeLine(ast, changes[0].id) : 1;
-
- const {newContents: output, changesMade} = applyVisualControl({
- input: fileContents,
- transformation: {
- type: 'apply-visual-control',
- changes,
- },
+ const result = updateVisualControls({
+ project: {rootDir: remotionRoot, files: {[absolutePath]: fileContents}},
+ filePath: absolutePath,
+ changes,
});
+ const output = result.project.files[absolutePath];
+ const logLine =
+ result.updatedControls.findLast(
+ (control) => control.id === changes[0]?.id,
+ )?.line ?? 1;
- if (changesMade.length === 0) {
+ if (result.updatedControls.length === 0) {
throw new Error('No changes were made to the file');
}
diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.ts
index 77a6c0dda9..096b3f53fc 100644
--- a/packages/studio-server/src/preview-server/routes/insert-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts
@@ -21,7 +21,6 @@ import {
pushTransactionToUndoStack,
suppressUndoStackInvalidation,
} from '../undo-stack';
-import {formatNewCompositionFile} from './apply-codemod';
import {checkIfTypeScriptFile} from './can-update-default-props';
import {
getElementInstallPlan,
@@ -171,13 +170,13 @@ export const insertElementHandler: ApiHandler<
registrationFilePath,
'utf-8',
);
- const registrationFileNewContents = await applyCodemodToFile({
+ const nextProject = await applyCodemodToFile({
filePath: registrationFilePath,
codeMod: newComposition.codemod,
});
- const componentFileContents = await formatNewCompositionFile(
- newComposition.codemod,
- );
+ const registrationFileNewContents =
+ nextProject.files[registrationFilePath];
+ const componentFileContents = nextProject.files[componentFilePath];
compositionCreation = {
componentFileContents,
componentFilePath,
diff --git a/packages/codemods/src/test/add-effect.test.ts b/packages/studio-server/src/test/add-effect.test.ts
similarity index 96%
rename from packages/codemods/src/test/add-effect.test.ts
rename to packages/studio-server/src/test/add-effect.test.ts
index f9462f79bc..634c1e734a 100644
--- a/packages/codemods/src/test/add-effect.test.ts
+++ b/packages/studio-server/src/test/add-effect.test.ts
@@ -1,6 +1,8 @@
import {expect, test} from 'bun:test';
-import {addEffect} from '../effect-operations';
-import {lineColumnToNodePath} from './node-path-test-utils';
+import {CodemodsInternals} from '@remotion/codemods';
+import {lineColumnToNodePath} from './test-utils';
+
+const {addEffect} = CodemodsInternals;
const buildInput = (jsx: string) => `import {Solid} from 'remotion';
diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/apply-codemod.test.ts
index 62835f45a7..6eb74cff9e 100644
--- a/packages/studio-server/src/test/apply-codemod.test.ts
+++ b/packages/studio-server/src/test/apply-codemod.test.ts
@@ -219,8 +219,7 @@ export const Root = () => <Folder name="Before" />;
test('metadata codemods do not run Prettier after applying source edits', async () => {
const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
const filePath = path.join(remotionRoot, 'Root.tsx');
- const input = `import {Composition} from 'remotion';
-const untouched = { value : "keep" };
+ const input = `const untouched = { value : "keep" };
export const Root=()=> <Composition id='Comp' width = { WIDTH }/>;
`;
@@ -238,8 +237,7 @@ export const Root=()=> <Composition id='Comp' width = { WIDTH }/>;
},
});
- expect(output).toBe(`import {Composition} from 'remotion';
-const untouched = { value : "keep" };
+ expect(output).toBe(`const untouched = { value : "keep" };
export const Root=()=> <Composition id='Comp' width = {1920} durationInFrames={90} height={1080}/>;
`);
} finally {
@@ -633,34 +631,26 @@ test('applyCodemodHandler logs composition renames and pushes them to the undo a
});
});
-test('applyCodemodHandler pushes composition and still duplications to undo and redo stacks', async () => {
- for (const tag of ['Composition', 'Still'] as const) {
- await runCompositionCodemodUndoRedoTest({
- codemod: {
- type: 'duplicate-composition',
- idToDuplicate: 'DeleteMe',
- newId: 'Duplicated',
- newDurationInFrames: 120,
- newFps: 30,
- newHeight: null,
- newWidth: null,
- tag,
- },
- assertApplied: (contents) => {
- expect(contents).toContain('id="DeleteMe"');
- expect(contents).toContain('id="Duplicated"');
- expect(contents).toContain('id="KeepMe"');
- if (tag === 'Still') {
- const still = contents.match(/<Still[\s\S]*?\/>/)?.[0];
- expect(still).toContain('id="Duplicated"');
- expect(still).not.toContain('fps=');
- expect(still).not.toContain('durationInFrames=');
- }
- },
- expectedUndoMessage:
- '↩️ Duplication of composition "DeleteMe" to "Duplicated"',
- });
- }
+test('applyCodemodHandler pushes composition duplications to undo and redo stacks', async () => {
+ await runCompositionCodemodUndoRedoTest({
+ codemod: {
+ type: 'duplicate-composition',
+ idToDuplicate: 'DeleteMe',
+ newId: 'Duplicated',
+ newDurationInFrames: null,
+ newFps: null,
+ newHeight: null,
+ newWidth: null,
+ tag: 'Composition',
+ },
+ assertApplied: (contents) => {
+ expect(contents).toContain('id="DeleteMe"');
+ expect(contents).toContain('id="Duplicated"');
+ expect(contents).toContain('id="KeepMe"');
+ },
+ expectedUndoMessage:
+ '↩️ Duplication of composition "DeleteMe" to "Duplicated"',
+ });
});
test('applyCodemodHandler pushes folder creations to undo and redo stacks', async () => {
diff --git a/packages/codemods/src/test/delete-effect.test.ts b/packages/studio-server/src/test/delete-effect.test.ts
similarity index 95%
rename from packages/codemods/src/test/delete-effect.test.ts
rename to packages/studio-server/src/test/delete-effect.test.ts
index a83c86491c..c5e0e04bb4 100644
--- a/packages/codemods/src/test/delete-effect.test.ts
+++ b/packages/studio-server/src/test/delete-effect.test.ts
@@ -1,6 +1,8 @@
import {expect, test} from 'bun:test';
-import {deleteEffect, deleteEffects} from '../effect-operations';
-import {lineColumnToNodePath} from './node-path-test-utils';
+import {CodemodsInternals} from '@remotion/codemods';
+import {lineColumnToNodePath} from './test-utils';
+
+const {deleteEffect, deleteEffects} = CodemodsInternals;
const buildInput = (
effects: string,
diff --git a/packages/studio-server/src/test/delete-jsx-nodes.test.ts b/packages/studio-server/src/test/delete-jsx-nodes.test.ts
index 23b8f5bd3c..5f2261a354 100644
--- a/packages/studio-server/src/test/delete-jsx-nodes.test.ts
+++ b/packages/studio-server/src/test/delete-jsx-nodes.test.ts
@@ -6,6 +6,7 @@ import type {
EventSourceEvent,
SubscribeToSequencePropsRequest,
} from '@remotion/studio-shared';
+import {deleteJsxNodes} from '../codemods/delete-jsx-nodes';
import {
createFileWatcherRegistry,
setFileWatcherRegistry,
@@ -19,7 +20,291 @@ import {
popRedo,
popUndo,
} from '../preview-server/undo-stack';
-import {lineColumnToNodePath} from './test-utils';
+import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
+
+const sample = `import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+export const X: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <div />
+ </AbsoluteFill>
+ );
+};
+`;
+
+test('deleteJsxNodes removes a JSX child from a parent element', async () => {
+ const {output} = await deleteJsxNodes({
+ input: sample,
+ nodePaths: [lineColumnToNodePath(sample, 7)],
+ });
+
+ expect(output).not.toContain('<div');
+ expect(output).toContain('<AbsoluteFill>');
+});
+
+const onlyReturn = `import React from 'react';
+
+export const X: React.FC = () => {
+ return <div />;
+};
+`;
+
+test('deleteJsxNodes replaces sole return JSX with null', async () => {
+ const {output} = await deleteJsxNodes({
+ input: onlyReturn,
+ nodePaths: [lineColumnToNodePath(onlyReturn, 4)],
+ });
+
+ expect(output).toContain('return null');
+ expect(output).not.toContain('<div');
+});
+
+const conditional = `import React from 'react';
+
+export const X: React.FC<{show: boolean}> = ({show}) => {
+ return <>{show && <div />}</>;
+};
+`;
+
+test('deleteJsxNodes turns conditional JSX into null', async () => {
+ const {output} = await deleteJsxNodes({
+ input: conditional,
+ nodePaths: [lineColumnToNodePath(conditional, 4)],
+ });
+
+ expect(output).toContain('&& null');
+ expect(output).not.toContain('<div');
+});
+
+const ternary = `import React from 'react';
+
+export const X: React.FC<{show: boolean}> = ({show}) => {
+ return <>{show ? <div /> : null}</>;
+};
+`;
+
+test('deleteJsxNodes replaces JSX in ternary consequent with null', async () => {
+ const {output} = await deleteJsxNodes({
+ input: ternary,
+ nodePaths: [lineColumnToNodePath(ternary, 4)],
+ });
+
+ expect(output).toMatch(/\?\s*null/);
+ expect(output).not.toContain('<div');
+});
+
+const mapCase = `import React from 'react';
+
+export const X: React.FC = () => {
+ return (
+ <>
+ {[1].map((i) => (
+ <div key={i} />
+ ))}
+ </>
+ );
+};
+`;
+
+test('deleteJsxNodes replaces JSX inside map callback', async () => {
+ const {output} = await deleteJsxNodes({
+ input: mapCase,
+ nodePaths: [lineColumnToNodePath(mapCase, 7)],
+ });
+
+ expect(output).not.toContain('<div');
+ expect(output).toMatch(/=>\s*\(?\s*null/);
+});
+
+const multipleSiblings = `import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+export const X: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <div />
+ <span />
+ <p />
+ </AbsoluteFill>
+ );
+};
+`;
+
+test('deleteJsxNodes removes multiple JSX children in one transform', async () => {
+ const {output, nodeLabels, logLines} = await deleteJsxNodes({
+ input: multipleSiblings,
+ nodePaths: [
+ lineColumnToNodePath(multipleSiblings, 7),
+ lineColumnToNodePath(multipleSiblings, 8),
+ ],
+ });
+
+ expect(output).not.toContain('<div');
+ expect(output).not.toContain('<span');
+ expect(output).toContain('<p');
+ expect(nodeLabels).toEqual(['<div>', '<span>']);
+ expect(logLines).toEqual([7, 8]);
+});
+
+test('deleteJsxNodes preserves source formatting and removes standalone JSX lines', async () => {
+ const cases = [
+ {
+ input: `export const Comp = () => {
+ return (
+ <div>
+ <Keep />
+ <RemoveOne />
+ <RemoveTwo />
+ <Keep />
+ </div>
+ );
+};
+`,
+ markers: ['<RemoveOne', '<RemoveTwo'],
+ expected: `export const Comp = () => {
+ return (
+ <div>
+ <Keep />
+ <Keep />
+ </div>
+ );
+};
+`,
+ },
+ {
+ input: `export const Comp = () => {
+ return (
+ <div>
+ <Remove />
+ </div>
+ )
+}
+`,
+ markers: ['<Remove'],
+ expected: `export const Comp = () => {
+ return (
+ <div>
+ </div>
+ )
+}
+`,
+ },
+ {
+ input: `export const Comp = () => {
+ return [1].map((item) => (
+ <Remove key={item} />
+ ));
+};
+`,
+ markers: ['<Remove'],
+ expected: `export const Comp = () => {
+ return [1].map((item) => null);
+};
+`,
+ },
+ {
+ input: `const AnimatedBar = () => {
+ return (
+ <Remove />
+ );
+};
+`,
+ markers: ['<Remove'],
+ expected: `const AnimatedBar = () => {
+ return null;
+};
+`,
+ },
+ {
+ input: `const AnimatedBar = () => {
+ return (
+ // Keep this explanation.
+ <Remove />
+ );
+};
+`,
+ markers: ['<Remove'],
+ expected: `const AnimatedBar = () => {
+ return (
+ // Keep this explanation.
+ null
+ );
+};
+`,
+ },
+ {
+ input: `export const Comp = () => <div><Keep /><Remove /><Keep /></div>;
+`,
+ markers: ['<Remove'],
+ expected: `export const Comp = () => <div><Keep /><Keep /></div>;
+`,
+ },
+ {
+ input:
+ 'export const Comp = () => <div><Keep />\t<Remove /><Keep /></div>;\n',
+ markers: ['<Remove'],
+ expected: 'export const Comp = () => <div><Keep />\t<Keep /></div>;\n',
+ },
+ {
+ input: `export const Comp = () => (
+ <div>
+ <Remove /> {/* keep this comment */}
+ </div>
+);
+`,
+ markers: ['<Remove'],
+ expected: `export const Comp = () => (
+ <div>
+ {/* keep this comment */}
+ </div>
+);
+`,
+ },
+ {
+ input: `export const Comp = () => {
+ return (
+ <div>
+ <RemoveParent>
+ <RemoveChild />
+ </RemoveParent>
+ <Keep />
+ </div>
+ );
+};
+`,
+ markers: ['<RemoveParent', '<RemoveChild'],
+ expected: `export const Comp = () => {
+ return (
+ <div>
+ <Keep />
+ </div>
+ );
+};
+`,
+ },
+ {
+ input:
+ 'export const Comp = () => {\r\n\treturn (\r\n\t\t<div>\r\n\t\t\t<Remove />\r\n\t\t</div>\r\n\t);\r\n};\r\n',
+ markers: ['<Remove'],
+ expected:
+ 'export const Comp = () => {\r\n\treturn (\r\n\t\t<div>\r\n\t\t</div>\r\n\t);\r\n};\r\n',
+ },
+ ] as const;
+
+ for (const item of cases) {
+ const {output, formatted} = await deleteJsxNodes({
+ input: item.input,
+ nodePaths: item.markers.map((marker) =>
+ lineContainingToNodePath(item.input, marker),
+ ),
+ });
+
+ expect(output).toBe(item.expected);
+ expect(formatted).toBe(true);
+ }
+});
const interactiveSiblings = `import {Interactive} from 'remotion';
diff --git a/packages/studio-server/src/test/discriminated-union-update.test.ts b/packages/studio-server/src/test/discriminated-union-update.test.ts
index a2060fd0f0..ce025b2b68 100644
--- a/packages/studio-server/src/test/discriminated-union-update.test.ts
+++ b/packages/studio-server/src/test/discriminated-union-update.test.ts
@@ -5,7 +5,7 @@ import path from 'node:path';
import {getFieldsToShow} from '@remotion/studio-shared';
import {NoReactInternals} from 'remotion/no-react';
import {parseAst} from '../codemods/parse-ast';
-import {updateSequenceProps} from '../codemods/update-sequence-props/update-sequence-props';
+import {updateSequencePropsAst} from '../codemods/update-sequence-props/update-sequence-props';
import {lineColumnToNodePath} from '../preview-server/routes/can-update-sequence-props';
import {prettify} from './test-utils';
@@ -75,9 +75,8 @@ test('Should be able to update a discriminated union', async () => {
const nodePath = lineColumnToNodePath(ast, 3);
assert(nodePath, 'No node path found');
- const update = await updateSequenceProps({
+ const update = updateSequencePropsAst({
videoConfigValues: null,
- prettierConfigOverride: null,
input: file,
nodePath,
updates: [
@@ -95,7 +94,7 @@ test('Should be able to update a discriminated union', async () => {
'utf-8',
);
- expect(await prettify(update.output)).toBe(await prettify(expected));
+ expect(await prettify(update.serialized)).toBe(await prettify(expected));
});
test('Should remove variant-specific props when switching enum value', async () => {
@@ -109,9 +108,8 @@ test('Should remove variant-specific props when switching enum value', async ()
const nodePath = lineColumnToNodePath(ast, 3);
assert(nodePath, 'No node path found');
- const update = await updateSequenceProps({
+ const update = updateSequencePropsAst({
videoConfigValues: null,
- prettierConfigOverride: null,
input: file,
nodePath,
updates: [
@@ -133,7 +131,7 @@ test('Should remove variant-specific props when switching enum value', async ()
'utf-8',
);
- expect(await prettify(update.output)).toBe(await prettify(expected));
+ expect(await prettify(update.serialized)).toBe(await prettify(expected));
});
test('Should remove premountFor and preserve styleWhile* when switching to layout="none"', async () => {
@@ -147,9 +145,8 @@ test('Should remove premountFor and preserve styleWhile* when switching to layou
const nodePath = lineColumnToNodePath(ast, 3);
assert(nodePath, 'No node path found');
- const update = await updateSequenceProps({
+ const update = updateSequencePropsAst({
videoConfigValues: null,
- prettierConfigOverride: null,
input: file,
nodePath,
updates: [
@@ -171,5 +168,5 @@ test('Should remove premountFor and preserve styleWhile* when switching to layou
'utf-8',
);
- expect(await prettify(update.output)).toBe(await prettify(expected));
+ expect(await prettify(update.serialized)).toBe(await prettify(expected));
});
diff --git a/packages/codemods/src/test/duplicate-effect.test.ts b/packages/studio-server/src/test/duplicate-effect.test.ts
similarity index 94%
rename from packages/codemods/src/test/duplicate-effect.test.ts
rename to packages/studio-server/src/test/duplicate-effect.test.ts
index 08dc5076dd..096c30681e 100644
--- a/packages/codemods/src/test/duplicate-effect.test.ts
+++ b/packages/studio-server/src/test/duplicate-effect.test.ts
@@ -1,6 +1,8 @@
import {expect, test} from 'bun:test';
-import {duplicateEffect, duplicateEffects} from '../effect-operations';
-import {lineColumnToNodePath} from './node-path-test-utils';
+import {CodemodsInternals} from '@remotion/codemods';
+import {lineColumnToNodePath} from './test-utils';
+
+const {duplicateEffect, duplicateEffects} = CodemodsInternals;
const buildInput = (
effects: string,
diff --git a/packages/codemods/src/test/duplicate-jsx-node.test.ts b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
similarity index 96%
rename from packages/codemods/src/test/duplicate-jsx-node.test.ts
rename to packages/studio-server/src/test/duplicate-jsx-node.test.ts
index 5457d96fb6..33c817d5da 100644
--- a/packages/codemods/src/test/duplicate-jsx-node.test.ts
+++ b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
@@ -1,9 +1,8 @@
import {expect, test} from 'bun:test';
-import {duplicateJsxNodes} from '../duplicate-jsx-node';
-import {
- lineColumnToNodePath,
- lineContainingToNodePath,
-} from './node-path-test-utils';
+import {CodemodsInternals} from '@remotion/codemods';
+import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
+
+const {duplicateJsxNodes} = CodemodsInternals;
const sample = `import React from 'react';
import {AbsoluteFill} from 'remotion';
diff --git a/packages/studio-server/src/test/effect-editing-routes.test.ts b/packages/studio-server/src/test/effect-editing-routes.test.ts
deleted file mode 100644
index 55be86273a..0000000000
--- a/packages/studio-server/src/test/effect-editing-routes.test.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import {expect, test} from 'bun:test';
-import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
-import {tmpdir} from 'node:os';
-import {join} from 'node:path';
-import {
- createFileWatcherRegistry,
- setFileWatcherRegistry,
-} from '../file-watcher';
-import {setLiveEventsListener} from '../preview-server/live-events';
-import {addEffectHandler} from '../preview-server/routes/add-effect';
-import {deleteEffectHandler} from '../preview-server/routes/delete-effect';
-import {duplicateEffectHandler} from '../preview-server/routes/duplicate-effect';
-import {reorderEffectHandler} from '../preview-server/routes/reorder-effect';
-import {clearUndoStackForTests, popUndo} from '../preview-server/undo-stack';
-import {lineContainingToNodePath} from './test-utils';
-
-test('effect routes persist additions, duplication, reordering, deletion, and undo', async () => {
- const remotionRoot = mkdtempSync(join(tmpdir(), 'remotion-effect-routes-'));
- const filePath = join(remotionRoot, 'Comp.tsx');
- const cleanupFileWatcher = setFileWatcherRegistry(
- createFileWatcherRegistry(),
- );
- const cleanupLiveEvents = setLiveEventsListener({
- sendEventToClient: () => undefined,
- sendEventToClientId: () => true,
- router: () => Promise.resolve(),
- closeConnections: () => Promise.resolve(),
- addNewClientListener: () => () => undefined,
- });
- const context = {
- entryPoint: filePath,
- remotionRoot,
- request: {} as never,
- response: {} as never,
- logLevel: 'error' as const,
- methods: {
- removeJob: () => undefined,
- cancelJob: () => undefined,
- addJob: () => undefined,
- },
- publicDir: remotionRoot,
- binariesDirectory: null,
- configFile: null,
- getDefaultCodingAgent: () => null,
- getDefaultEditor: () => null,
- };
- const input = `import {Solid} from 'remotion';
-const untouched = { value : 'keep' };
-const dimensions = {width: 100, height: 100};
-const presets = [];
-export const Comp = () => <>
- <Solid {...dimensions} />
- <Solid name="preset" effects={[...presets]} />
- <Solid name="overridden" effects={[...presets]} {...dimensions} />
-</>;
-`;
-
- try {
- clearUndoStackForTests();
- writeFileSync(filePath, input);
- const sequenceNodePath = {
- absolutePath: filePath,
- nodePath: lineContainingToNodePath(input, '<Solid'),
- sequenceKeys: [],
- effectKeys: [],
- videoConfigValues: null,
- };
- for (const effectName of ['brightness', 'contrast']) {
- const result = await addEffectHandler({
- ...context,
- input: {
- fileName: filePath,
- sequenceNodePath,
- effectName,
- effectImportPath: `@remotion/effects/${effectName}`,
- effectConfig: {amount: 1.2},
- clientId: 'effect-routes-test',
- },
- });
- expect(result.success).toBe(true);
- }
-
- const duplicate = await duplicateEffectHandler({
- ...context,
- input: [{fileName: filePath, sequenceNodePath, effectIndex: 0}],
- });
- expect(duplicate.success).toBe(true);
- expect(
- readFileSync(filePath, 'utf-8').match(/brightness\(\{/g),
- ).toHaveLength(2);
-
- const reorder = await reorderEffectHandler({
- ...context,
- input: {
- fileName: filePath,
- sequenceNodePath,
- fromIndex: 1,
- toIndex: 2,
- clientId: 'effect-routes-test',
- },
- });
- expect(reorder.success).toBe(true);
- const reordered = readFileSync(filePath, 'utf-8');
- expect(reordered.indexOf('brightness({')).toBeLessThan(
- reordered.indexOf('contrast({'),
- );
- expect(reordered.lastIndexOf('brightness({')).toBeGreaterThan(
- reordered.indexOf('contrast({'),
- );
- expect(reordered).toContain("const untouched = { value : 'keep' };");
-
- const overridden = await addEffectHandler({
- ...context,
- input: {
- fileName: filePath,
- sequenceNodePath: {
- ...sequenceNodePath,
- nodePath: lineContainingToNodePath(
- reordered,
- '<Solid name="overridden"',
- ),
- },
- effectName: 'brightness',
- effectImportPath: '@remotion/effects/brightness',
- effectConfig: {amount: 2},
- clientId: 'effect-routes-test',
- },
- });
- expect(overridden.success).toBe(false);
- expect(readFileSync(filePath, 'utf-8')).toBe(reordered);
-
- const deleted = await deleteEffectHandler({
- ...context,
- input: [
- {type: 'all-effects', fileName: filePath, sequenceNodePath},
- {
- type: 'all-effects',
- fileName: filePath,
- sequenceNodePath: {
- ...sequenceNodePath,
- nodePath: lineContainingToNodePath(
- reordered,
- '<Solid name="preset"',
- ),
- },
- },
- ],
- });
- expect(deleted.success).toBe(true);
- expect(readFileSync(filePath, 'utf-8')).toContain(
- '<Solid {...dimensions} />',
- );
- expect(readFileSync(filePath, 'utf-8')).toContain(
- '<Solid name="preset" />',
- );
- expect(popUndo().success).toBe(true);
- expect(readFileSync(filePath, 'utf-8')).toBe(reordered);
- } finally {
- clearUndoStackForTests();
- cleanupFileWatcher();
- cleanupLiveEvents();
- rmSync(remotionRoot, {recursive: true, force: true});
- }
-});
diff --git a/packages/codemods/src/test/fixtures/canvas-capture-composition.txt b/packages/studio-server/src/test/fixtures/canvas-capture-composition.txt
similarity index 100%
rename from packages/codemods/src/test/fixtures/canvas-capture-composition.txt
rename to packages/studio-server/src/test/fixtures/canvas-capture-composition.txt
diff --git a/packages/codemods/src/test/fixtures/canvas-capture-metadata.json b/packages/studio-server/src/test/fixtures/canvas-capture-metadata.json
similarity index 100%
rename from packages/codemods/src/test/fixtures/canvas-capture-metadata.json
rename to packages/studio-server/src/test/fixtures/canvas-capture-metadata.json
diff --git a/packages/codemods/src/test/generate-canvas-capture-composition.test.ts b/packages/studio-server/src/test/generate-canvas-capture-composition.test.ts
similarity index 91%
rename from packages/codemods/src/test/generate-canvas-capture-composition.test.ts
rename to packages/studio-server/src/test/generate-canvas-capture-composition.test.ts
index fa000cc6b0..95c74e6f16 100644
--- a/packages/codemods/src/test/generate-canvas-capture-composition.test.ts
+++ b/packages/studio-server/src/test/generate-canvas-capture-composition.test.ts
@@ -1,11 +1,13 @@
import {expect, test} from 'bun:test';
import {readFileSync} from 'node:fs';
import path from 'node:path';
+import {CodemodsInternals} from '@remotion/codemods';
import {
CANVAS_CAPTURE_METADATA_TAG,
parseCanvasCaptureData,
} from '@remotion/studio-shared';
-import {generateCanvasCaptureComposition} from '../generate-canvas-capture-composition';
+
+const {generateCanvasCaptureComposition} = CodemodsInternals;
test('generates the ideal interactive Canvas Capture composition markup', async () => {
const fixtureDirectory = path.join(__dirname, 'fixtures');
diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.ts
index ece1cd26e9..9f5f6c04a5 100644
--- a/packages/studio-server/src/test/insert-element.test.ts
+++ b/packages/studio-server/src/test/insert-element.test.ts
@@ -326,10 +326,6 @@ test('invalidates a new-composition install after an external component edit', a
);
}
- const registration = readFileSync(fixture.compositionFile, 'utf-8');
- expect(registration).toContain('const Target = () => <div>Hello</div>;');
- expect(registration.match(/id="ElementScene"/g)).toHaveLength(1);
-
const componentFile = path.join(
path.dirname(fixture.compositionFile),
'ElementScene.tsx',
diff --git a/packages/codemods/src/test/reorder-effect.test.ts b/packages/studio-server/src/test/reorder-effect.test.ts
similarity index 93%
rename from packages/codemods/src/test/reorder-effect.test.ts
rename to packages/studio-server/src/test/reorder-effect.test.ts
index 9d3ffb3cf0..582569acde 100644
--- a/packages/codemods/src/test/reorder-effect.test.ts
+++ b/packages/studio-server/src/test/reorder-effect.test.ts
@@ -1,6 +1,8 @@
import {expect, test} from 'bun:test';
-import {reorderEffect} from '../effect-operations';
-import {lineColumnToNodePath} from './node-path-test-utils';
+import {CodemodsInternals} from '@remotion/codemods';
+import {lineColumnToNodePath} from './test-utils';
+
+const {reorderEffect} = CodemodsInternals;
const buildInput = (
effects: string,
diff --git a/packages/codemods/src/test/reorder-sequence.test.ts b/packages/studio-server/src/test/reorder-sequence.test.ts
similarity index 91%
rename from packages/codemods/src/test/reorder-sequence.test.ts
rename to packages/studio-server/src/test/reorder-sequence.test.ts
index ec163cc939..14a1c31c6a 100644
--- a/packages/codemods/src/test/reorder-sequence.test.ts
+++ b/packages/studio-server/src/test/reorder-sequence.test.ts
@@ -1,7 +1,10 @@
import {expect, test} from 'bun:test';
-import {getJsxNodes} from '../get-jsx-nodes';
-import {reorderSequence} from '../reorder-sequence';
-import {lineColumnToNodePath} from './node-path-test-utils';
+import {CodemodsInternals} from '@remotion/codemods';
+import {parseAst} from '../codemods/parse-ast';
+import {lineColumnToNodePath as getNodePathAtPosition} from '../preview-server/routes/can-update-sequence-props';
+import {lineColumnToNodePath} from './test-utils';
+
+const {reorderSequence} = CodemodsInternals;
const sequenceContaining = (input: string, search: string) => {
const searchOffset = input.indexOf(search);
@@ -17,14 +20,12 @@ const sequenceContaining = (input: string, search: string) => {
}
const sourceBeforeOpening = input.slice(0, openingOffset).split('\n');
- const nodePath = getJsxNodes({
- project: {rootDir: '/', files: {'/test.tsx': input}},
- filePath: '/test.tsx',
- }).find(
- (node) =>
- node.location?.line === sourceBeforeOpening.length &&
- node.location.column === (sourceBeforeOpening.at(-1)?.length ?? 0),
- )?.nodePath;
+ const nodePath = getNodePathAtPosition(
+ parseAst(input),
+ sourceBeforeOpening.length,
+ sourceBeforeOpening.at(-1)?.length ?? 0,
+ input,
+ );
if (!nodePath) {
throw new Error(
`Could not resolve a Sequence containing ${JSON.stringify(search)}`,
diff --git a/packages/codemods/src/test/fixtures/fixed.tsx.txt b/packages/studio-server/src/test/snapshots/fixed.tsx
similarity index 100%
rename from packages/codemods/src/test/fixtures/fixed.tsx.txt
rename to packages/studio-server/src/test/snapshots/fixed.tsx
diff --git a/packages/codemods/src/test/fixtures/problematic.tsx.txt b/packages/studio-server/src/test/snapshots/problematic.tsx
similarity index 100%
rename from packages/codemods/src/test/fixtures/problematic.tsx.txt
rename to packages/studio-server/src/test/snapshots/problematic.tsx
diff --git a/packages/codemods/src/test/fixtures/root-after.tsx.txt b/packages/studio-server/src/test/snapshots/root-after.tsx
similarity index 100%
rename from packages/codemods/src/test/fixtures/root-after.tsx.txt
rename to packages/studio-server/src/test/snapshots/root-after.tsx
diff --git a/packages/codemods/src/test/fixtures/root-before.tsx.txt b/packages/studio-server/src/test/snapshots/root-before.tsx
similarity index 100%
rename from packages/codemods/src/test/fixtures/root-before.tsx.txt
rename to packages/studio-server/src/test/snapshots/root-before.tsx
diff --git a/packages/studio-server/src/test/split-jsx-sequence.test.ts b/packages/studio-server/src/test/split-jsx-sequence.test.ts
index ab4fd96f5a..cb7adff0da 100644
--- a/packages/studio-server/src/test/split-jsx-sequence.test.ts
+++ b/packages/studio-server/src/test/split-jsx-sequence.test.ts
@@ -2,6 +2,8 @@ import {expect, test} from 'bun:test';
import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';
+import {CodemodsInternals} from '@remotion/codemods';
+import {splitJsxSequence} from '../codemods/split-jsx-sequence';
import {
createFileWatcherRegistry,
setFileWatcherRegistry,
@@ -9,7 +11,9 @@ import {
import {setLiveEventsListener} from '../preview-server/live-events';
import {splitJsxSequenceHandler} from '../preview-server/routes/split-jsx-sequence';
import {getUndoStack} from '../preview-server/undo-stack';
-import {lineContainingToNodePath} from './test-utils';
+import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
+
+const {splitJsxSequence: splitJsxSequenceCodemod} = CodemodsInternals;
const wrap = (
sequence: string,
@@ -25,8 +29,243 @@ export const Comp = () => {
};
`;
+const sequenceLine = 7;
const sequenceTimingKeys = ['from', 'durationInFrames', 'trimBefore'];
+const split = async (
+ sequence: string,
+ splitFrame: number,
+ sequenceKeys = sequenceTimingKeys,
+) => {
+ const input = wrap(sequence);
+ const {output} = await splitJsxSequence({
+ input,
+ nodePath: lineColumnToNodePath(input, sequenceLine),
+ sequenceKeys,
+ splitFrame,
+ });
+
+ return output;
+};
+
+test('splitJsxSequence splits a sequence with no duration', async () => {
+ const output = await split('<Sequence from={0} />', 30);
+
+ expect(output).toContain('<Sequence from={0} durationInFrames={30} />');
+ expect(output).toContain('<Sequence from={30} trimBefore={30} />');
+});
+
+test('splitJsxSequence remaps following JSX siblings', async () => {
+ const input = wrap(
+ '<Sequence name="split" from={0} durationInFrames={50} />\n\t\t\t<Sequence name="following" />',
+ );
+ const {output, nodePathRemappings} = await splitJsxSequence({
+ input,
+ nodePath: lineContainingToNodePath(input, 'name="split"'),
+ sequenceKeys: sequenceTimingKeys,
+ splitFrame: 30,
+ });
+
+ expect(nodePathRemappings).toEqual([
+ {
+ oldNodePath: lineContainingToNodePath(input, 'name="split"'),
+ newNodePath: lineContainingToNodePath(output, 'name="split"'),
+ },
+ {
+ oldNodePath: lineContainingToNodePath(input, 'name="following"'),
+ newNodePath: lineContainingToNodePath(output, 'name="following"'),
+ },
+ {
+ oldNodePath: null,
+ newNodePath: lineContainingToNodePath(output, 'from={30}'),
+ },
+ ]);
+});
+
+test('splitJsxSequence omits right Infinity duration', async () => {
+ const output = await split(
+ '<Sequence from={0} durationInFrames={Infinity} />',
+ 30,
+ );
+
+ expect(output).toContain('<Sequence from={0} durationInFrames={30} />');
+ expect(output).toContain('<Sequence from={30} trimBefore={30} />');
+ expect(output).not.toContain('durationInFrames={Infinity}');
+});
+
+test('splitJsxSequence keeps missing left from omitted', async () => {
+ const output = await split('<Sequence durationInFrames={50} />', 30);
+
+ expect(output).toContain('<Sequence durationInFrames={30} />');
+ expect(output).toContain(
+ '<Sequence from={30} durationInFrames={20} trimBefore={30} />',
+ );
+});
+
+test('splitJsxSequence splits finite duration and trimBefore', async () => {
+ const output = await split(
+ '<Sequence from={10} durationInFrames={50} trimBefore={5} />',
+ 30,
+ );
+
+ expect(output).toContain(
+ '<Sequence from={10} durationInFrames={20} trimBefore={5} />',
+ );
+ expect(output).toContain(
+ '<Sequence from={30} durationInFrames={30} trimBefore={25} />',
+ );
+});
+
+test('splitJsxSequence preserves surrounding formatting without calling Prettier', async () => {
+ const input = `const deliberatelyUnformatted = {value : true}
+
+export const Comp = () => {
+ return (
+ <>
+ <Sequence
+ name="clip"
+ from={0}
+ durationInFrames={50}
+ >
+ <div>Child</div>
+ </Sequence>
+ <Keep prop = {1}/>
+ </>
+ )
+}
+`;
+ const {output} = await splitJsxSequenceCodemod({
+ input,
+ nodePath: lineContainingToNodePath(input, '<Sequence'),
+ sequenceKeys: sequenceTimingKeys,
+ splitFrame: 30,
+ });
+
+ expect(output).toStartWith(
+ 'const deliberatelyUnformatted = {value : true}\n',
+ );
+ expect(output).toContain(
+ '<Sequence name="clip" from={0} durationInFrames={30}>\n',
+ );
+ expect(output).toContain(
+ '<Sequence name="clip" from={30} durationInFrames={20} trimBefore={30}>\n',
+ );
+ expect(output).toContain(' <Keep prop = {1}/>');
+ expect(output).toEndWith(' )\n}\n');
+});
+
+test('splitJsxSequence formats a split component root as a fragment', async () => {
+ const input = `export const Comp = () => <Sequence from={0} durationInFrames={50}><span>Hi</span></Sequence>;
+
+const keep = { value : true }
+`;
+ const {output} = await splitJsxSequenceCodemod({
+ input,
+ nodePath: lineContainingToNodePath(input, '<Sequence'),
+ sequenceKeys: sequenceTimingKeys,
+ splitFrame: 30,
+ });
+
+ expect(output).toBe(`export const Comp = () => <>
+ <Sequence from={0} durationInFrames={30}>
+ <span>Hi</span>
+ </Sequence>
+ <Sequence from={30} durationInFrames={20} trimBefore={30}>
+ <span>Hi</span>
+ </Sequence>
+</>;
+
+const keep = { value : true }
+`);
+});
+
+test('splitJsxSequence splits a video with a negative from', async () => {
+ const output = await split(
+ '<Video src="video.mov" from={-2644} trimBefore={272} />',
+ 100,
+ );
+
+ expect(output).toContain('from={-2644}');
+ expect(output).toContain('durationInFrames={2744}');
+ expect(output).toContain('trimBefore={272}');
+ expect(output).toContain(
+ '<Video src="video.mov" from={100} trimBefore={3016} />',
+ );
+});
+
+test('splitJsxSequence splits from-only sequence', async () => {
+ const output = await split('<Sequence from={10} />', 30);
+
+ expect(output).toContain('<Sequence from={10} durationInFrames={20} />');
+ expect(output).toContain('<Sequence from={30} trimBefore={20} />');
+});
+
+test('splitJsxSequence splits sequence-backed components', async () => {
+ expect(
+ await split('<AbsoluteFill from={0} durationInFrames={50} />', 30),
+ ).toContain(
+ '<AbsoluteFill from={30} durationInFrames={20} trimBefore={30} />',
+ );
+ expect(
+ await split('<Img src="image.png" from={0} durationInFrames={50} />', 30),
+ ).toContain(
+ '<Img src="image.png" from={30} durationInFrames={20} trimBefore={30} />',
+ );
+ expect(
+ await split('<Gif src="anim.gif" from={0} durationInFrames={50} />', 30),
+ ).toContain(
+ '<Gif src="anim.gif" from={30} durationInFrames={20} trimBefore={30} />',
+ );
+ const solidOutput = await split(
+ '<Solid width={100} height={100} from={0} durationInFrames={50} />',
+ 30,
+ );
+ expect(solidOutput).toContain(
+ '<Solid width={100} height={100} from={0} durationInFrames={30} />',
+ );
+ expect(solidOutput).toContain('from={30}');
+ expect(solidOutput).toContain('durationInFrames={20}');
+ expect(solidOutput).toContain('trimBefore={30}');
+ expect(
+ await split('<Interactive.Div from={0} durationInFrames={50} />', 30),
+ ).toContain(
+ '<Interactive.Div from={30} durationInFrames={20} trimBefore={30} />',
+ );
+});
+
+test('splitJsxSequence rejects boundary and dynamic splits', async () => {
+ await expect(
+ split('<Sequence from={10} durationInFrames={20} />', 10),
+ ).rejects.toThrow(/sequence start/);
+ await expect(
+ split('<Sequence from={10} durationInFrames={20} />', 30),
+ ).rejects.toThrow(/sequence end/);
+ await expect(
+ split('<Sequence from={10} durationInFrames={20} />', 8),
+ ).rejects.toThrow(/sequence start/);
+ await expect(
+ split('<Sequence from={10} durationInFrames={20} />', 10.5),
+ ).rejects.toThrow(/integer/);
+ await expect(
+ split('<Sequence from={start} durationInFrames={20} />', 15),
+ ).rejects.toThrow(/dynamic from/);
+});
+
+test('splitJsxSequence rejects Series.Sequence', async () => {
+ await expect(
+ split('<Series.Sequence durationInFrames={50} />', 30, [
+ 'durationInFrames',
+ 'trimBefore',
+ ]),
+ ).rejects.toThrow('<Series.Sequence> cannot be split');
+});
+
+test('splitJsxSequence rejects regular DOM elements', async () => {
+ await expect(
+ split('<div from={0} durationInFrames={50} />', 30, []),
+ ).rejects.toThrow('<div> cannot be split');
+});
+
const clearUndoStack = () => {
(getUndoStack() as unknown as unknown[]).length = 0;
};
diff --git a/packages/studio-server/src/test/split-video-from-audio.test.ts b/packages/studio-server/src/test/split-video-from-audio.test.ts
index 0aaa2a34e0..97e206d193 100644
--- a/packages/studio-server/src/test/split-video-from-audio.test.ts
+++ b/packages/studio-server/src/test/split-video-from-audio.test.ts
@@ -2,6 +2,7 @@ import {expect, test} from 'bun:test';
import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';
+import {CodemodsInternals} from '@remotion/codemods';
import {
createFileWatcherRegistry,
setFileWatcherRegistry,
@@ -11,6 +12,8 @@ import {splitVideoFromAudioHandler} from '../preview-server/routes/split-video-f
import {getUndoStack} from '../preview-server/undo-stack';
import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
+const {splitVideoFromAudio} = CodemodsInternals;
+
const wrap = (
element: string,
imports = `import {Video} from '@remotion/media';`,
@@ -27,6 +30,255 @@ export const Comp = () => {
const elementLine = 6;
+const split = async (element: string, imports?: string) => {
+ const input = wrap(element, imports);
+ const {output} = await splitVideoFromAudio({
+ input,
+ nodePath: lineContainingToNodePath(input, element),
+ });
+
+ return output;
+};
+
+test('splitVideoFromAudio mutes the video and adds an Audio with the same timing', async () => {
+ const output = await split(
+ '<Video src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} style={{opacity: 0.5}} />',
+ );
+
+ const singleLine = output.replace(/\s+/g, ' ');
+
+ expect(output).toContain(`import {Video, Audio} from '@remotion/media';`);
+ expect(singleLine).toContain(
+ '<Video src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} style={{opacity: 0.5}} muted />',
+ );
+ expect(singleLine).toContain(
+ '<Audio src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} />',
+ );
+});
+
+test('splitVideoFromAudio preserves unrelated source formatting without calling the formatter', async () => {
+ const input = `import{Video}from"@remotion/media"
+
+const untouched = {keep : "spacing"}
+export const Comp=()=>(
+ <>
+ <Video
+ src = {"video.mp4"}
+ from = {10}
+ style = {{opacity:.5}}
+ />
+ <div data-value = "unchanged"/>
+ </>
+)
+`;
+ let formatCalls = 0;
+ const {formatted, nodePathRemappings, output} = await splitVideoFromAudio({
+ input,
+ nodePath: lineContainingToNodePath(input, '<Video'),
+ formatFile: () => {
+ formatCalls++;
+ throw new Error('Prettier must not be called');
+ },
+ });
+
+ expect(formatCalls).toBe(0);
+ expect(formatted).toBe(true);
+ expect(output).toBe(`import{Video, Audio}from"@remotion/media"
+
+const untouched = {keep : "spacing"}
+export const Comp=()=>(
+ <>
+ <Video
+ src = {"video.mp4"}
+ from = {10}
+ style = {{opacity:.5}}
+ muted
+ />
+ <Audio src={"video.mp4"} from={10} />
+ <div data-value = "unchanged"/>
+ </>
+)
+`);
+ expect(nodePathRemappings).toEqual([
+ {
+ oldNodePath: lineContainingToNodePath(input, '<Video'),
+ newNodePath: lineContainingToNodePath(output, '<Video'),
+ },
+ {
+ oldNodePath: lineContainingToNodePath(input, '<div'),
+ newNodePath: lineContainingToNodePath(output, '<div'),
+ },
+ {
+ oldNodePath: null,
+ newNodePath: lineContainingToNodePath(output, '<Audio'),
+ },
+ ]);
+});
+
+test('splitVideoFromAudio does not copy non-audio props', async () => {
+ const output = await split(
+ '<Video src="video.mp4" name="my video" freeze={20} crop={{x: 0, y: 0, width: 100, height: 100}} />',
+ );
+
+ expect(output).toContain('<Audio src="video.mp4" />');
+});
+
+test('splitVideoFromAudio wraps a root video in a fragment', async () => {
+ const input = `import {Video} from '@remotion/media';
+
+export const Comp = () => <Video src="video.mp4" />;
+`;
+ const {output} = await splitVideoFromAudio({
+ input,
+ nodePath: lineContainingToNodePath(input, '<Video'),
+ });
+
+ expect(output).toBe(`import {Video, Audio} from '@remotion/media';
+
+export const Comp = () => <>
+ <Video src="video.mp4" muted />
+ <Audio src="video.mp4" />
+</>;
+`);
+});
+
+test('splitVideoFromAudio separates siblings with one space on a shared line', async () => {
+ const input = `import {Video} from '@remotion/media';
+
+export const Comp = () => (
+ <div>
+ <Video src="video.mp4" /></div>
+);
+`;
+ const {output} = await splitVideoFromAudio({
+ input,
+ nodePath: lineContainingToNodePath(input, '<Video'),
+ });
+
+ expect(output).toBe(`import {Video, Audio} from '@remotion/media';
+
+export const Comp = () => (
+ <div>
+ <Video src="video.mp4" muted /> <Audio src="video.mp4" /></div>
+);
+`);
+});
+
+test('splitVideoFromAudio preserves CRLF and tab indentation', async () => {
+ const input = [
+ `import {Video} from '@remotion/media';`,
+ '',
+ 'export const Comp = () => {',
+ '\treturn (',
+ '\t\t<>',
+ '\t\t\t<Video',
+ '\t\t\t\tsrc="video.mp4"',
+ '\t\t\t\ttrimBefore={10}',
+ '\t\t\t/>',
+ '\t\t</>',
+ '\t);',
+ '};',
+ '',
+ ].join('\r\n');
+ const {output} = await splitVideoFromAudio({
+ input,
+ nodePath: lineContainingToNodePath(input, '<Video'),
+ });
+
+ expect(output).toBe(
+ [
+ `import {Video, Audio} from '@remotion/media';`,
+ '',
+ 'export const Comp = () => {',
+ '\treturn (',
+ '\t\t<>',
+ '\t\t\t<Video',
+ '\t\t\t\tsrc="video.mp4"',
+ '\t\t\t\ttrimBefore={10}',
+ '\t\t\t\tmuted',
+ '\t\t\t/>',
+ '\t\t\t<Audio src="video.mp4" trimBefore={10} />',
+ '\t\t</>',
+ '\t);',
+ '};',
+ '',
+ ].join('\r\n'),
+ );
+});
+
+test('splitVideoFromAudio replaces an existing muted prop', async () => {
+ const output = await split('<Video src="video.mp4" muted={false} />');
+
+ expect(output).toContain('<Video src="video.mp4" muted />');
+ expect(output).not.toContain('muted={false}');
+});
+
+test('splitVideoFromAudio reuses an existing Audio import', async () => {
+ const output = await split(
+ '<Video src="video.mp4" />',
+ `import {Audio, Video} from '@remotion/media';`,
+ );
+
+ expect(output).toContain(`import {Audio, Video} from '@remotion/media';`);
+ expect(output.match(/from '@remotion\/media'/g)?.length).toBe(1);
+});
+
+test('splitVideoFromAudio uses an aliased Audio import', async () => {
+ const output = await split(
+ '<Video src="video.mp4" />',
+ `import {Audio as Sound, Video} from '@remotion/media';`,
+ );
+
+ expect(output).toContain(
+ `import {Audio as Sound, Video} from '@remotion/media';`,
+ );
+ expect(output).toContain('<Sound src="video.mp4" />');
+});
+
+test('splitVideoFromAudio imports Audio from the same module as the tag', async () => {
+ const output = await split(
+ '<OffthreadVideo src="video.mp4" from={5} />',
+ `import {OffthreadVideo} from 'remotion';`,
+ );
+
+ expect(output).toContain(`import {OffthreadVideo, Audio} from 'remotion';`);
+ expect(output).toContain('<OffthreadVideo src="video.mp4" from={5} muted />');
+ expect(output).toContain('<Audio src="video.mp4" from={5} />');
+});
+
+test('splitVideoFromAudio follows import aliases', async () => {
+ const output = await split(
+ '<V src="video.mp4" />',
+ `import {Video as V} from '@remotion/media';`,
+ );
+
+ expect(output).toContain(
+ `import {Video as V, Audio} from '@remotion/media';`,
+ );
+ expect(output).toContain('<Audio src="video.mp4" />');
+});
+
+test('splitVideoFromAudio rejects elements without a src attribute', async () => {
+ await expect(split('<Video from={0} />')).rejects.toThrow(
+ '<Video> has no src attribute',
+ );
+});
+
+test('splitVideoFromAudio rejects unimported tags', async () => {
+ await expect(split('<video src="video.mp4" />')).rejects.toThrow(
+ 'Could not find the import of <video>',
+ );
+});
+
+test('splitVideoFromAudio rejects an Audio import from another module', async () => {
+ await expect(
+ split(
+ '<Video src="video.mp4" />',
+ `import {Video} from '@remotion/media';\nimport {Audio} from 'remotion';`,
+ ),
+ ).rejects.toThrow('Audio is already imported from "remotion"');
+});
+
const clearUndoStack = () => {
(getUndoStack() as unknown as unknown[]).length = 0;
};
diff --git a/packages/codemods/src/test/update-default-props.test.ts b/packages/studio-server/src/test/update-default-props.test.ts
similarity index 88%
rename from packages/codemods/src/test/update-default-props.test.ts
rename to packages/studio-server/src/test/update-default-props.test.ts
index 10613b9dbf..0028042141 100644
--- a/packages/codemods/src/test/update-default-props.test.ts
+++ b/packages/studio-server/src/test/update-default-props.test.ts
@@ -1,19 +1,18 @@
import {expect, test} from 'bun:test';
import {readFileSync} from 'node:fs';
import path from 'node:path';
-import {parseAst} from '../sequence-props/parse-ast';
-import {
- getCompositionDefaultPropsLine,
- updateDefaultProps,
-} from '../update-default-props';
+import {CodemodsInternals} from '@remotion/codemods';
+import {parseAst} from '../codemods/parse-ast';
+
+const {getCompositionDefaultPropsLine, updateDefaultProps} = CodemodsInternals;
test('updates default props without changing surrounding source', () => {
const file = readFileSync(
- path.join(__dirname, 'fixtures', 'root-before.tsx.txt'),
+ path.join(__dirname, 'snapshots', 'root-before.tsx'),
'utf-8',
);
const expected = readFileSync(
- path.join(__dirname, 'fixtures', 'root-after.tsx.txt'),
+ path.join(__dirname, 'snapshots', 'root-after.tsx'),
'utf-8',
);
@@ -29,7 +28,7 @@ test('updates default props without changing surrounding source', () => {
test('getCompositionDefaultPropsLine returns the opening tag line (ast-types visitor must traverse)', () => {
const file = readFileSync(
- path.join(__dirname, 'fixtures', 'root-before.tsx.txt'),
+ path.join(__dirname, 'snapshots', 'root-before.tsx'),
'utf-8',
);
@@ -43,11 +42,11 @@ test('getCompositionDefaultPropsLine returns the opening tag line (ast-types vis
test('replaces multiline default props with a compact value', () => {
const file = readFileSync(
- path.join(__dirname, 'fixtures', 'problematic.tsx.txt'),
+ path.join(__dirname, 'snapshots', 'problematic.tsx'),
'utf-8',
);
const expected = readFileSync(
- path.join(__dirname, 'fixtures', 'fixed.tsx.txt'),
+ path.join(__dirname, 'snapshots', 'fixed.tsx'),
'utf-8',
);
diff --git a/packages/codemods/src/test/update-effect-props.test.ts b/packages/studio-server/src/test/update-effect-props.test.ts
similarity index 98%
rename from packages/codemods/src/test/update-effect-props.test.ts
rename to packages/studio-server/src/test/update-effect-props.test.ts
index 5d93ccd50c..958e2deb0c 100644
--- a/packages/codemods/src/test/update-effect-props.test.ts
+++ b/packages/studio-server/src/test/update-effect-props.test.ts
@@ -1,6 +1,6 @@
import {expect, test} from 'bun:test';
-import {updateEffectPropsAst} from '../effect-operations';
-import {lineColumnToNodePath} from './node-path-test-utils';
+import {updateEffectPropsAst} from '../codemods/update-effect-props/update-effect-props';
+import {lineColumnToNodePath} from './test-utils';
const tintSchema = {
color: {
diff --git a/packages/codemods/src/test/update-keyframes-imports.test.ts b/packages/studio-server/src/test/update-keyframes-imports.test.ts
similarity index 99%
rename from packages/codemods/src/test/update-keyframes-imports.test.ts
rename to packages/studio-server/src/test/update-keyframes-imports.test.ts
index 65b3b41d74..1f3eabd1b7 100644
--- a/packages/codemods/src/test/update-keyframes-imports.test.ts
+++ b/packages/studio-server/src/test/update-keyframes-imports.test.ts
@@ -3,8 +3,8 @@ import type {InteractivitySchema} from 'remotion';
import {
updateEffectKeyframesAst,
updateSequenceKeyframesAst,
-} from '../update-keyframes';
-import {lineColumnToNodePath} from './node-path-test-utils';
+} from '../codemods/update-keyframes/update-keyframes';
+import {lineColumnToNodePath} from './test-utils';
const getLine = (input: string, needle: string): number => {
const lineIndex = input
diff --git a/packages/studio-server/src/test/update-keyframes.test.ts b/packages/studio-server/src/test/update-keyframes.test.ts
index 87a19099e3..45e6cf1736 100644
--- a/packages/studio-server/src/test/update-keyframes.test.ts
+++ b/packages/studio-server/src/test/update-keyframes.test.ts
@@ -2,7 +2,7 @@ import {expect, test} from 'bun:test';
import type {InteractivitySchema} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
import {
- updateEffectKeyframes,
+ updateEffectKeyframesAst,
updateSequenceKeyframes,
} from '../codemods/update-keyframes/update-keyframes';
import {computeSequencePropsStatusFromContent} from '../preview-server/routes/can-update-sequence-props';
@@ -1849,12 +1849,12 @@ test('updateSequenceKeyframes keeps a color interpolation when one keyframe rema
expect(output).toContain("color={interpolateColors(frame, [100], ['blue'])}");
});
-test('updateEffectKeyframes converts a static value to a clamped interpolation', async () => {
+test('updateEffectKeyframes converts a static value to a clamped interpolation', () => {
const input = effectInput.replace(
'interpolate(frame, [0, 50, 100], [0.2, 0.5, 0.8])',
'0.2',
);
- const {output: serialized, oldValueStrings} = await updateEffectKeyframes({
+ const {serialized, oldValueStrings} = updateEffectKeyframesAst({
videoConfigValues: null,
input,
sequenceNodePath: lineColumnToNodePath(
@@ -1877,8 +1877,8 @@ test('updateEffectKeyframes converts a static value to a clamped interpolation',
expect(serialized).not.toContain('perceptual-scale');
});
-test('updateEffectKeyframes uses the schema keyframe output default', async () => {
- const {output: serialized} = await updateEffectKeyframes({
+test('updateEffectKeyframes uses the schema keyframe output default', () => {
+ const {serialized} = updateEffectKeyframesAst({
videoConfigValues: null,
input: scaleEffectInput,
sequenceNodePath: lineColumnToNodePath(
@@ -1899,8 +1899,8 @@ test('updateEffectKeyframes uses the schema keyframe output default', async () =
expect(serialized).toContain("output: 'perceptual-scale'");
});
-test('updateEffectKeyframes adds a missing prop before keyframing it', async () => {
- const {output: serialized, oldValueStrings} = await updateEffectKeyframes({
+test('updateEffectKeyframes adds a missing prop before keyframing it', () => {
+ const {serialized, oldValueStrings} = updateEffectKeyframesAst({
videoConfigValues: null,
input: waveEffectInput,
sequenceNodePath: lineColumnToNodePath(
@@ -1925,9 +1925,9 @@ test('updateEffectKeyframes adds a missing prop before keyframing it', async ()
expect(serialized).toContain("extrapolateRight: 'clamp'");
});
-test('updateEffectKeyframes adds props to a zero-argument effect', async () => {
+test('updateEffectKeyframes adds props to a zero-argument effect', () => {
const input = waveEffectInput.replace('wave({})', 'wave()');
- const {output: serialized, oldValueStrings} = await updateEffectKeyframes({
+ const {serialized, oldValueStrings} = updateEffectKeyframesAst({
videoConfigValues: null,
input,
sequenceNodePath: lineColumnToNodePath(input, getLine(input, '<Solid')),
@@ -1946,8 +1946,8 @@ test('updateEffectKeyframes adds props to a zero-argument effect', async () => {
expect(serialized).toContain('phase: interpolate(frame, [15], [45], {');
});
-test('updateEffectKeyframes sets one easing segment and fills linear segments', async () => {
- const {output: serialized} = await updateEffectKeyframes({
+test('updateEffectKeyframes sets one easing segment and fills linear segments', () => {
+ const {serialized} = updateEffectKeyframesAst({
videoConfigValues: null,
input: effectInput,
sequenceNodePath: lineColumnToNodePath(
@@ -2013,12 +2013,8 @@ test('updateSequenceKeyframes converts the last color keyframe to a static value
});
});
-test('updateEffectKeyframes removes a keyframe from an effect prop interpolation', async () => {
- const {
- output: serialized,
- oldValueStrings,
- effectCallee,
- } = await updateEffectKeyframes({
+test('updateEffectKeyframes removes a keyframe from an effect prop interpolation', () => {
+ const {serialized, oldValueStrings, effectCallee} = updateEffectKeyframesAst({
videoConfigValues: null,
input: effectInput,
sequenceNodePath: lineColumnToNodePath(
@@ -2047,8 +2043,8 @@ test('updateEffectKeyframes removes a keyframe from an effect prop interpolation
);
});
-test('updateEffectKeyframes allows moving keyframes outside the sequence range', async () => {
- const {output: serialized, newValueStrings} = await updateEffectKeyframes({
+test('updateEffectKeyframes allows moving keyframes outside the sequence range', () => {
+ const {serialized, newValueStrings} = updateEffectKeyframesAst({
videoConfigValues: null,
input: effectInput,
sequenceNodePath: lineColumnToNodePath(
@@ -2078,8 +2074,8 @@ test('updateEffectKeyframes allows moving keyframes outside the sequence range',
);
});
-test('updateEffectKeyframes replaces an existing keyframe when moving onto it', async () => {
- const {output: serialized, newValueStrings} = await updateEffectKeyframes({
+test('updateEffectKeyframes replaces an existing keyframe when moving onto it', () => {
+ const {serialized, newValueStrings} = updateEffectKeyframesAst({
videoConfigValues: null,
input: effectInput,
sequenceNodePath: lineColumnToNodePath(
@@ -2106,12 +2102,12 @@ test('updateEffectKeyframes replaces an existing keyframe when moving onto it',
);
});
-test('updateEffectKeyframes keeps an effect prop interpolation with one keyframe', async () => {
+test('updateEffectKeyframes keeps an effect prop interpolation with one keyframe', () => {
const input = effectInput.replace(
'interpolate(frame, [0, 50, 100], [0.2, 0.5, 0.8])',
'interpolate(frame, [0, 100], [0.2, 0.8])',
);
- const {output: serialized} = await updateEffectKeyframes({
+ const {serialized} = updateEffectKeyframesAst({
videoConfigValues: null,
input,
sequenceNodePath: lineColumnToNodePath(
@@ -2134,35 +2130,31 @@ test('updateEffectKeyframes keeps an effect prop interpolation with one keyframe
expect(serialized).toContain('amount: interpolate(frame, [0], [0.2])');
});
-test('updateEffectKeyframes converts the last effect keyframe to a static value', async () => {
+test('updateEffectKeyframes converts the last effect keyframe to a static value', () => {
const input = effectInput.replace(
'interpolate(frame, [0, 50, 100], [0.2, 0.5, 0.8])',
'interpolate(frame, [40], [0.6])',
);
- const {
- output: serialized,
- oldValueStrings,
- newValueStrings,
- effectCallee,
- } = await updateEffectKeyframes({
- videoConfigValues: null,
- input,
- sequenceNodePath: lineColumnToNodePath(
+ const {serialized, oldValueStrings, newValueStrings, effectCallee} =
+ updateEffectKeyframesAst({
+ videoConfigValues: null,
input,
- getLine(input, '<HtmlInCanvas'),
- ),
- effectIndex: 0,
- updates: [
- {
- key: 'amount',
- operation: {
- type: 'remove',
- frame: 40,
- valueWhenLastKeyframeDeleted: null,
+ sequenceNodePath: lineColumnToNodePath(
+ input,
+ getLine(input, '<HtmlInCanvas'),
+ ),
+ effectIndex: 0,
+ updates: [
+ {
+ key: 'amount',
+ operation: {
+ type: 'remove',
+ frame: 40,
+ valueWhenLastKeyframeDeleted: null,
+ },
},
- },
- ],
- });
+ ],
+ });
expect(effectCallee).toBe('tint');
expect(oldValueStrings).toEqual(['interpolate(frame, [40], [0.6])']);
diff --git a/packages/studio-server/src/test/update-sequence-props.test.ts b/packages/studio-server/src/test/update-sequence-props.test.ts
index c437553e89..689621064d 100644
--- a/packages/studio-server/src/test/update-sequence-props.test.ts
+++ b/packages/studio-server/src/test/update-sequence-props.test.ts
@@ -1,9 +1,14 @@
import {expect, test} from 'bun:test';
+import * as recast from 'recast';
import {NoReactInternals} from 'remotion/no-react';
import {
updateMultipleSequenceProps,
updateSequenceProps,
} from '../codemods/update-sequence-props/update-sequence-props';
+import {
+ computeSequencePropsStatusFromContent,
+ takeCachedSequencePropsStatusAst,
+} from '../preview-server/routes/can-update-sequence-props';
import {lineColumnToNodePath} from './test-utils';
const lightLeakInput = `import {LightLeak} from '@remotion/light-leaks';
@@ -721,6 +726,41 @@ test('updateMultipleSequenceProps formats a multiline non-self-closing opening e
expect(formatted).toBe(true);
});
+test('updateMultipleSequenceProps reuses the status AST across the shared Recast runtime', async () => {
+ const nodePath = lineColumnToNodePath(lightLeakInput, 8);
+ computeSequencePropsStatusFromContent({
+ fileContents: lightLeakInput,
+ nodePath,
+ componentIdentity: null,
+ keys: ['hueShift'],
+ effects: [],
+ videoConfigValues: null,
+ });
+ expect(takeCachedSequencePropsStatusAst(`${lightLeakInput}\n`)).toBeNull();
+ const cachedAst = takeCachedSequencePropsStatusAst(lightLeakInput);
+ if (!cachedAst) {
+ throw new Error('Expected the status AST to be reusable');
+ }
+
+ const {ast} = await updateMultipleSequenceProps({
+ input: lightLeakInput,
+ changes: [
+ {
+ nodePath,
+ updates: [{key: 'hueShift', value: 90, defaultValue: null}],
+ schema: NoReactInternals.sequenceSchema,
+ videoConfigValues: null,
+ },
+ ],
+ prettierConfigOverride: null,
+ ast: cachedAst,
+ });
+
+ expect(ast).toBe(cachedAst);
+ expect(() => recast.print(ast).code).not.toThrow();
+ expect(takeCachedSequencePropsStatusAst(lightLeakInput)).toBeNull();
+});
+
test('updateSequenceProps should update JSX text children', async () => {
const input = `import React from 'react';
import {Interactive} from 'remotion';
diff --git a/packages/studio-shared/src/empty-composition-component.ts b/packages/studio-shared/src/empty-composition-component.ts
new file mode 100644
index 0000000000..e9f13bec91
--- /dev/null
+++ b/packages/studio-shared/src/empty-composition-component.ts
@@ -0,0 +1,8 @@
+export const emptyCompositionComponent = (componentName: string) => {
+ return `import React from 'react';
+
+export const ${componentName}: React.FC = () => {
+ return null;
+};
+`;
+};
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index d8b60f1fcf..d55adce154 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -429,3 +429,5 @@ export {
stringifySequenceSubscriptionKey,
} from './stringify-sequence-subscription-key';
export {isUrl} from './url';
+
+export {emptyCompositionComponent} from './empty-composition-component';
diff --git a/packages/template-recorder/scripts/server/register-composition.ts b/packages/template-recorder/scripts/server/register-composition.ts
index 5ed45f0a37..ba1b319e86 100644
--- a/packages/template-recorder/scripts/server/register-composition.ts
+++ b/packages/template-recorder/scripts/server/register-composition.ts
@@ -69,7 +69,7 @@ export const registerComposition = async ({
const {output: withDefaultScene} =
await StudioServerInternals.updateDefaultProps({
- input: duplicated,
+ input: duplicated.files[rootPath],
compositionId: projectName,
newDefaultProps: getDefaultPropsForNewProject(),
enumPaths: [],