🎥 Make videos programmatically with React
`@remotion/studio`: Create, duplicate, rename and delete compositions without Prettier
JonnyBurgereb0837b2fe78
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex b952404b98..5a7206e7e9 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -1466,7 +1466,13 @@ export const createBrowserStudioOperations = ({});const input = project.files[absolutePath];const {newContents} = parseAndApplyCodemod({input, codeMod: codemod});- const {output} = await formatCodemodFile({contents: newContents});+ const output =+ codemod.type === 'new-composition' ||+ codemod.type === 'duplicate-composition' ||+ codemod.type === 'rename-composition' ||+ codemod.type === 'delete-composition'+ ? newContents+ : (await formatCodemodFile({contents: newContents})).output;const files: Record<string, string> = {...project.files,[absolutePath]: output,@@ -1480,10 +1486,9 @@ export const createBrowserStudioOperations = ({);}- const componentFile = await formatCodemodFile({- contents: makeNewCompositionComponentSource(codemod.componentName),- });- files[componentFilePath] = componentFile.output;+ files[componentFilePath] = makeNewCompositionComponentSource(+ codemod.componentName,+ );}const diff = simpleDiff({diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 562b3c159e..ab63f7f651 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -1,6 +1,7 @@-import {expect, test} from 'bun:test';+import {expect, spyOn, test} from 'bun:test';import {createElementPayload} from '@remotion/studio-protocol';import type {EventSourceEvent} from '@remotion/studio-shared';+import * as prettier from 'prettier/standalone';import type {InteractivitySchema} from 'remotion';import {NoReactInternals} from 'remotion/no-react';import {@@ -1249,39 +1250,46 @@ test('creates a composition with a component file in the root file', async () =>newDurationInFrames: 90,canvasCapture: null,};- const result = await operations.applyCodemod({- codemod,- dryRun: false,- symbolicatedStack: null,+ const formatter = spyOn(prettier, 'format').mockImplementation(() => {+ throw new Error('Prettier must not be called');});- if (!result.success) {- throw new Error(result.reason);- }+ try {+ const result = await operations.applyCodemod({+ codemod,+ dryRun: false,+ symbolicatedStack: null,+ });+ if (!result.success) {+ throw new Error(result.reason);+ }- const rootFile = getProject().files['/project/src/Root.tsx'];- expect(rootFile).toContain('id="FreshComp"');- expect(rootFile).toContain("import {Composition} from 'remotion'");- expect(rootFile).toContain("import {FreshComp} from './FreshComp'");- expect(getProject().files['/project/src/FreshComp.tsx']).toContain(- 'export const FreshComp: React.FC',- );+ const rootFile = getProject().files['/project/src/Root.tsx'];+ expect(rootFile).toContain('id="FreshComp"');+ expect(rootFile).toContain('import { Composition } from "remotion"');+ expect(rootFile).toContain('import { FreshComp } from "./FreshComp"');+ expect(getProject().files['/project/src/FreshComp.tsx']).toContain(+ 'export const FreshComp: React.FC',+ );- const conflict = await operations.applyCodemod({- codemod: {...codemod, newId: 'FreshComp2'},- dryRun: false,- symbolicatedStack: null,- });- expect(conflict).toEqual({- success: false,- reason: 'Cannot create src/FreshComp.tsx because it already exists',- });+ const conflict = await operations.applyCodemod({+ codemod: {...codemod, newId: 'FreshComp2'},+ dryRun: false,+ symbolicatedStack: null,+ });+ expect(conflict).toEqual({+ success: false,+ reason: 'Cannot create src/FreshComp.tsx because it already exists',+ });- const undoResult = await operations.undo();- expect(undoResult.success).toBe(true);- expect(getProject().files['/project/src/FreshComp.tsx']).toBeUndefined();- expect(getProject().files['/project/src/Root.tsx']).not.toContain(- 'id="FreshComp"',- );+ const undoResult = await operations.undo();+ expect(undoResult.success).toBe(true);+ expect(getProject().files['/project/src/FreshComp.tsx']).toBeUndefined();+ expect(getProject().files['/project/src/Root.tsx']).not.toContain(+ 'id="FreshComp"',+ );+ } finally {+ formatter.mockRestore();+ }});test('creates, renames and deletes a folder in Browser Studio', async () => {diff --git a/packages/it-tests/src/codemods/codemods.test.ts b/packages/it-tests/src/codemods/codemods.test.tsindex 18b6071dd5..289c083cc5 100644--- a/packages/it-tests/src/codemods/codemods.test.ts+++ b/packages/it-tests/src/codemods/codemods.test.ts@@ -154,5 +154,5 @@ test("curly braces id={'seven'}", () => {expect(changesMade.length).toBe(1);expect(getCompositionCount(newContents)).toBe(compCount);expect(newContents).not.toContain('"seven"');- expect(newContents).toContain('"mno"');+ expect(newContents).toBe(contents.replace("id={'seven'}", "id={'mno'}"));});diff --git a/packages/studio-codemods/src/composition-source-edits.ts b/packages/studio-codemods/src/composition-source-edits.tsnew file mode 100644index 0000000000..e61740e03b--- /dev/null+++ b/packages/studio-codemods/src/composition-source-edits.ts@@ -0,0 +1,194 @@+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-node';+import {getCompositionId} from './duplicate-composition';+import {+ applySourceEdits,+ getInsertImportSourceEdits,+ getInsertionRootSourceEdit,+ type SourceEdit,+} 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';++export const editCompositionInSource = ({+ input,+ codeMod,+}: {+ input: string;+ codeMod: Extract<+ RecastCodemod,+ {type: 'new-composition' | 'rename-composition' | 'delete-composition'}+ >;+}): {newContents: string; changesMade: Change[]} => {+ const ast = parseAst(input);+ const edits: SourceEdit[] = [];+ let changesMade: Change[] = [];+ if (codeMod.type === 'new-composition') {+ const snapshots = ast.program.body.flatMap((statement) =>+ statement.type === 'ImportDeclaration'+ ? [{declaration: statement, specifiers: [...statement.specifiers]}]+ : [],+ );+ 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;+ if (+ getCompositionId(element) !==+ (codeMod.type === 'rename-composition'+ ? codeMod.idToRename+ : codeMod.idToDelete)+ ) {+ 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;+ }++ const attribute = element.openingElement.attributes.find(+ (attr) =>+ attr.type === 'JSXAttribute' &&+ attr.name.type === 'JSXIdentifier' &&+ attr.name.name === 'id',+ );+ const value =+ attribute?.type === 'JSXAttribute' ? attribute.value : null;+ const literal =+ value?.type === 'JSXExpressionContainer' ? value.expression : value;+ if (!literal?.loc || literal.type !== 'StringLiteral') {+ throw new Error('Could not locate the composition id');+ }++ const start = recastLocToOffset(input, literal.loc.start);+ const end = recastLocToOffset(input, literal.loc.end);+ const quote = input[start] === "'" ? "'" : '"';+ const replacement =+ value?.type === 'StringLiteral'+ ? quote ++ codeMod.newId+ .replaceAll('&', '&')+ .replaceAll('"', '"')+ .replaceAll("'", ''')+ .replaceAll('<', '<') ++ quote+ : recast.prettyPrint(+ recast.types.builders.stringLiteral(codeMod.newId),+ {quote: quote === "'" ? 'single' : 'double'},+ ).code;+ edits.push({start, end, replacement});+ 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/studio-codemods/src/delete-jsx-node.ts b/packages/studio-codemods/src/delete-jsx-node.tsindex 9e8d7fbbfa..498ddec60d 100644--- a/packages/studio-codemods/src/delete-jsx-node.ts+++ b/packages/studio-codemods/src/delete-jsx-node.ts@@ -419,7 +419,7 @@ type SourceEdit = {start: number;};-const getNodeSourceEdit = ({+export const getNodeSourceEdit = ({input,jsxPath,}: {diff --git a/packages/studio-codemods/src/duplicate-composition.ts b/packages/studio-codemods/src/duplicate-composition.tsindex 375d700a6d..95225359e9 100644--- a/packages/studio-codemods/src/duplicate-composition.ts+++ b/packages/studio-codemods/src/duplicate-composition.ts@@ -2,14 +2,21 @@ import type {Expression,JSXAttribute,JSXElement,- JSXFragment,JSXIdentifier,JSXOpeningElement,} from '@babel/types';import type {RecastCodemod} from '@remotion/studio-shared';import * as recast from 'recast';+import {+ applySourceEdits,+ getInsertImportSourceEdits,+ getInsertionRootSourceEdit,+ type SourceEdit,+} from './insert-jsx-element';+import {indentInsertedJsx, printInsertedJsx} from './print-jsx';+import {recastLocToOffset} from './recast-loc-to-offset';import {ensureNamedImport} from './sequence-props/imports';-import {parseAst, serializeAst} from './sequence-props/parse-ast';+import {parseAst} from './sequence-props/parse-ast';const b = recast.types.builders;@@ -18,7 +25,7 @@ type DuplicateCompositionCodemod = Extract<{type: 'duplicate-composition'}>;-const getCompositionId = (jsxElement: JSXElement) => {+export const getCompositionId = (jsxElement: JSXElement) => {const {openingElement} = jsxElement;if (openingElement.name.type !== 'JSXIdentifier' ||@@ -191,6 +198,9 @@ const changeComposition = ({return {...jsxElement,+ closingElement: jsxElement.closingElement+ ? {...jsxElement.closingElement, name: {...name, name: codemod.tag}}+ : null,openingElement: {...openingElement,name: {...name, name: codemod.tag},@@ -199,34 +209,6 @@ const changeComposition = ({};};-const makeFragment = (- original: JSXElement,- duplicate: JSXElement,-): JSXFragment => ({- type: 'JSXFragment',- openingFragment: {type: 'JSXOpeningFragment'},- closingFragment: {type: 'JSXClosingFragment'},- children: [original, duplicate],-});--const insertAfterInJsxParent = ({- duplicate,- original,- parent,-}: {- duplicate: JSXElement;- original: JSXElement;- parent: JSXElement | JSXFragment;-}) => {- const index = parent.children.indexOf(original);- if (index === -1) {- return false;- }-- parent.children.splice(index + 1, 0, duplicate);- return true;-};-export const duplicateCompositionInSource = ({input,codemod,@@ -236,15 +218,17 @@ export const duplicateCompositionInSource = ({}): {newContents: string; changesMade: {description: string}[]} => {const ast = parseAst(input);const changesMade: {description: string}[] = [];- const generatedNodes = new WeakSet<JSXElement>();+ const edits: SourceEdit[] = [];+ const snapshots = ast.program.body.flatMap((statement) =>+ statement.type === 'ImportDeclaration'+ ? [{declaration: statement, specifiers: [...statement.specifiers]}]+ : [],+ );recast.types.visit(ast, {visitJSXElement(astPath) {const original = astPath.node as unknown as JSXElement;- if (- generatedNodes.has(original) ||- getCompositionId(original) !== codemod.idToDuplicate- ) {+ if (getCompositionId(original) !== codemod.idToDuplicate) {this.traverse(astPath);return undefined;}@@ -254,20 +238,44 @@ export const duplicateCompositionInSource = ({codemod,changesMade,});- generatedNodes.add(duplicate);- const parent = astPath.parentPath?.node as- | JSXElement- | JSXFragment- | undefined;+ 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') &&- insertAfterInJsxParent({duplicate, original, parent})+ (parent.type === 'JSXElement' || parent.type === 'JSXFragment')) {- return false;+ 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,+ }),+ );}- astPath.replace(makeFragment(original, duplicate));return false;},});@@ -285,5 +293,19 @@ export const duplicateCompositionInSource = ({localName: codemod.tag,});- return {newContents: serializeAst(ast), changesMade};+ return {+ newContents: applySourceEdits({+ input,+ edits: [+ ...edits,+ ...getInsertImportSourceEdits({+ ast,+ input,+ snapshots,+ prettierConfigOverride: null,+ }),+ ],+ }),+ changesMade,+ };};diff --git a/packages/studio-codemods/src/insert-jsx-element.ts b/packages/studio-codemods/src/insert-jsx-element.tsindex 833c791ef0..cd7fac8492 100644--- a/packages/studio-codemods/src/insert-jsx-element.ts+++ b/packages/studio-codemods/src/insert-jsx-element.ts@@ -173,7 +173,7 @@ type SourceLocation = {column: number;};-type SourceEdit = {+export type SourceEdit = {end: number;replacement: string;start: number;@@ -2166,7 +2166,7 @@ const getImportBracketSpacing = ({return prettierConfigOverride?.bracketSpacing !== false;};-const getInsertImportSourceEdits = ({+export const getInsertImportSourceEdits = ({ast,input,prettierConfigOverride,@@ -2509,13 +2509,15 @@ const getInsertionSource = ({});};-const getInsertionRootSourceEdit = ({+export const getInsertionRootSourceEdit = ({+ insertInside,input,insertion,nullRoot,prettierConfigOverride,root,}: {+ insertInside: boolean;input: string;insertion: string;nullRoot: NullLiteral | null;@@ -2553,15 +2555,32 @@ const getInsertionRootSourceEdit = ({throw new Error('Could not locate the composition component root');}- if (root.type === 'JSXFragment') {- if (!root.closingFragment.loc) {- throw new Error('Could not locate the composition fragment closing tag');+ if (insertInside) {+ const closing =+ root.type === 'JSXFragment' ? root.closingFragment : root.closingElement;+ if (!closing?.loc) {+ if (root.type !== 'JSXElement' || !root.openingElement.loc) {+ throw new Error('Could not locate the composition closing tag');+ }++ const openingStart = recastLocToOffset(+ input,+ root.openingElement.loc.start,+ );+ const openingEnd = recastLocToOffset(input, root.openingElement.loc.end);+ const openingIndent = getLineIndent(input, openingStart);+ return {+ start: openingStart,+ end: openingEnd,+ replacement: [+ input.slice(openingStart, openingEnd).replace(/\s*\/>$/, '>'),+ indentInsertedJsx({indent: `${openingIndent}${unit}`, insertion}),+ `${openingIndent}</${recast.print(root.openingElement.name).code}>`,+ ].join(endOfLine),+ };}- const closingStart = recastLocToOffset(- input,- root.closingFragment.loc.start,- );+ const closingStart = recastLocToOffset(input, closing.loc.start);const lineStart = input.lastIndexOf('\n', closingStart - 1) + 1;const beforeClosing = input.slice(lineStart, closingStart);const closingIndent = /^\s*$/.test(beforeClosing)@@ -2610,7 +2629,7 @@ const getInsertionRootSourceEdit = ({};};-const applySourceEdits = ({+export const applySourceEdits = ({edits,input,}: {@@ -3218,6 +3237,7 @@ export const insertJsxElementIntoComposition = async ({snapshots: importSnapshots,}),getInsertionRootSourceEdit({+ insertInside: rootBeforeInsertion?.type === 'JSXFragment',input,insertion: getInsertionSource({element,diff --git a/packages/studio-codemods/src/parse-and-apply-codemod.ts b/packages/studio-codemods/src/parse-and-apply-codemod.tsindex 5b10bcc47a..15555890af 100644--- a/packages/studio-codemods/src/parse-and-apply-codemod.ts+++ b/packages/studio-codemods/src/parse-and-apply-codemod.ts@@ -1,4 +1,5 @@import type {RecastCodemod} from '@remotion/studio-shared';+import {editCompositionInSource} from './composition-source-edits';import {duplicateCompositionInSource} from './duplicate-composition';import type {Change} from './recast-mods';import {applyCodemod} from './recast-mods';@@ -16,6 +17,14 @@ export const parseAndApplyCodemod = ({return duplicateCompositionInSource({input, codemod: codeMod});}+ if (+ codeMod.type === 'new-composition' ||+ codeMod.type === 'rename-composition' ||+ codeMod.type === 'delete-composition'+ ) {+ return editCompositionInSource({input, codeMod});+ }+const ast = parseAst(input);const {newAst, changesMade} = applyCodemod({@@ -29,24 +38,6 @@ export const parseAndApplyCodemod = ({);}- if (codeMod.type === 'new-composition') {- if (codeMod.canvasCapture === null) {- ensureNamedImport({- ast: newAst,- importedName: 'Composition',- sourcePath: 'remotion',- localName: 'Composition',- });- }-- ensureNamedImport({- ast: newAst,- importedName: codeMod.componentName,- sourcePath: codeMod.componentImportPath,- localName: codeMod.componentName,- });- }-if (codeMod.type === 'new-folder') {ensureNamedImport({ast: newAst,diff --git a/packages/studio-codemods/src/print-jsx.ts b/packages/studio-codemods/src/print-jsx.tsindex 6f9a4fe7a0..39679a4402 100644--- a/packages/studio-codemods/src/print-jsx.ts+++ b/packages/studio-codemods/src/print-jsx.ts@@ -76,6 +76,15 @@ export const printInsertedJsx = ({},});const printNode = (node: namedTypes.Node) => {+ // The generic printer drops comments inside empty JSX expressions.+ if (+ node.type === 'JSXExpressionContainer' &&+ (node as namedTypes.JSXExpressionContainer).expression.type ===+ 'JSXEmptyExpression'+ ) {+ return recast.print(node).code;+ }+return recast.prettyPrint(node, {objectCurlySpacing: prettierConfigOverride?.bracketSpacing !== false,quote: prettierConfigOverride?.singleQuote === true ? 'single' : 'double',diff --git a/packages/studio-codemods/src/test/composition-source-edits.test.ts b/packages/studio-codemods/src/test/composition-source-edits.test.tsnew file mode 100644index 0000000000..3fb938d2c5--- /dev/null+++ b/packages/studio-codemods/src/test/composition-source-edits.test.ts@@ -0,0 +1,179 @@+import {expect, test} from 'bun:test';+import {parseAndApplyCodemod} from '../parse-and-apply-codemod';+import {parseAst} from '../sequence-props/parse-ast';++for (const [indent, eol] of [+ ['\t', '\n'],+ [' ', '\n'],+ [' ', '\r\n'],+]) {+ test(`composition edits preserve ${JSON.stringify({indent, eol})}`, () => {+ const composition = [+ `${indent}<Composition`,+ `${indent}${indent}id="Original"`,+ `${indent}${indent}component={Video}`,+ `${indent}${indent}durationInFrames={120}`,+ `${indent}${indent}fps={30}`,+ `${indent}${indent}width={1280}`,+ `${indent}${indent}height={720}`,+ `${indent}/>`,+ ].join(eol);+ const input = [+ "import {Composition} from 'remotion';",+ '',+ 'const preserve = { custom : "spacing" }; // keep this',+ 'export const Root = () => <>',+ composition,+ `${indent}{/* keep this comment */}`,+ '</>;',+ '',+ ].join(eol);+ const renamed = parseAndApplyCodemod({+ input,+ codeMod: {+ type: 'rename-composition',+ idToRename: 'Original',+ newId: 'Renamed',+ },+ }).newContents;+ expect(renamed).toBe(input.replace('id="Original"', 'id="Renamed"'));+ const duplicated = parseAndApplyCodemod({+ input: renamed,+ codeMod: {+ type: 'duplicate-composition',+ idToDuplicate: 'Renamed',+ newId: 'Copy',+ tag: 'Composition',+ newFps: null,+ newHeight: null,+ newWidth: null,+ newDurationInFrames: null,+ },+ }).newContents;+ expect(duplicated).toBe(+ renamed.replace(+ composition.replace('Original', 'Renamed'),+ composition.replace('Original', 'Renamed') ++ eol ++ composition.replace('Original', 'Copy'),+ ),+ );+ const deleted = parseAndApplyCodemod({+ input: duplicated,+ codeMod: {type: 'delete-composition', idToDelete: 'Copy'},+ }).newContents;+ expect(deleted).toBe(renamed);+ parseAst(duplicated);+ });+}++test('new compositions append to fragments and folders and wrap standalone roots', () => {+ for (const [root, folderName, expected] of [+ ['<>\n {/* keep */}\n</>', null, '<>\n {/* keep */}\n INSERT\n</>'],+ [+ '<Folder name="Target" />',+ 'Target',+ '<Folder name="Target">\n INSERT\n</Folder>',+ ],+ [+ '<Folder name="Target"><Composition id="Old" /></Folder>',+ 'Target',+ '<Folder name="Target"><Composition id="Old" />\n INSERT\n</Folder>',+ ],+ [+ '<Composition id="Old" />',+ null,+ '<>\n <Composition id="Old" />\n INSERT\n</>',+ ],+ ] as const) {+ const input = `import {Composition, Folder} from 'remotion';\nexport const Root = () => (${root});\n`;+ const output = parseAndApplyCodemod({+ input,+ codeMod: {+ type: 'new-composition',+ componentName: 'Fresh',+ componentImportPath: './Fresh',+ newId: 'Fresh',+ newWidth: 1920,+ newHeight: 1080,+ newDurationInFrames: 90,+ newFps: 30,+ folderName,+ parentName: null,+ canvasCapture: null,+ },+ }).newContents;+ const inserted =+ '<Composition\n id="Fresh"\n component={Fresh}\n durationInFrames={90}\n fps={30}\n width={1920}\n height={1080}\n />';+ expect(output).toBe(+ "import {Fresh} from './Fresh';\n" ++ input.replace(root, expected.replace('INSERT', inserted)),+ );+ parseAst(output);+ }+});++test('duplicating a standalone composition into a Still updates both tags and removes timing props', () => {+ const input = `import {Composition} from 'remotion';+export const Root = () => (+ <Composition id="Original" fps={30} durationInFrames={90}>+ {/* keep the child */}+ <Child />+ </Composition>+);+`;+ const output = parseAndApplyCodemod({+ input,+ codeMod: {+ type: 'duplicate-composition',+ idToDuplicate: 'Original',+ newId: 'Poster',+ tag: 'Still',+ newFps: null,+ newDurationInFrames: null,+ newWidth: 500,+ newHeight: 400,+ },+ }).newContents;+ expect(output).toContain("import {Composition, Still} from 'remotion';");+ expect(output).toContain(+ ' <Still id="Poster" width={500} height={400}>\n {/* keep the child */}\n <Child />\n </Still>',+ );+ expect(output).toContain(+ ' <Composition id="Original" fps={30} durationInFrames={90}>',+ );+ parseAst(output);+});++test('rename preserves expression quotes and delete replaces standalone and conditional JSX with null', () => {+ for (const original of [+ '<Composition id={"Original"} />',+ "<Still id={'Original'} />",+ ]) {+ for (const expression of [+ original,+ `(${original})`,+ `enabled ? ${original} : null`,+ ]) {+ const input = `export const Root = () => ${expression};\n`;+ const renamed = parseAndApplyCodemod({+ input,+ codeMod: {+ type: 'rename-composition',+ idToRename: 'Original',+ newId: 'Renamed',+ },+ }).newContents;+ expect(renamed).toBe(input.replace('Original', 'Renamed'));+ const deleted = parseAndApplyCodemod({+ input: renamed,+ codeMod: {type: 'delete-composition', idToDelete: 'Renamed'},+ }).newContents;+ expect(deleted).toBe(+ expression.startsWith('enabled')+ ? 'export const Root = () => enabled ? null : null;\n'+ : 'export const Root = () => null;\n',+ );+ }+ }+});diff --git a/packages/studio-server/src/canvas-capture/generate-canvas-capture-composition.ts b/packages/studio-server/src/canvas-capture/generate-canvas-capture-composition.tsindex 390f1710c8..7d18f4879c 100644--- a/packages/studio-server/src/canvas-capture/generate-canvas-capture-composition.ts+++ b/packages/studio-server/src/canvas-capture/generate-canvas-capture-composition.ts@@ -1,5 +1,5 @@import type {CanvasCaptureData} from '@remotion/studio-shared';-import {formatOutput} from '../codemods/duplicate-composition';+import * as recast from 'recast';type FramedMouseMovement = CanvasCaptureData['mouseMovements'][number] & {readonly frame: number;@@ -44,7 +44,19 @@ const getCursorName = (cursor: string) => {return cursor.split(',').at(-1)?.trim().toLowerCase() || 'default';};-const serialize = (value: unknown) => JSON.stringify(value);+const serialize = (value: unknown): string => {+ if (typeof value === 'string') {+ return recast.prettyPrint(recast.types.builders.stringLiteral(value), {+ quote: 'single',+ }).code;+ }++ if (Array.isArray(value)) {+ return `[${value.map(serialize).join(', ')}]`;+ }++ return JSON.stringify(value);+};export const generateCanvasCaptureComposition = ({componentName,@@ -133,7 +145,7 @@ export const generateCanvasCaptureComposition = ({)?.cursor;const cursorProp =cursorKeyframes.length === 1- ? `cursor=${serialize(cursorKeyframes[0].value)}`+ ? `cursor={${serialize(cursorKeyframes[0].value)}}`: `cursor={interpolate(frame,${serialize(cursorKeyframes.map((keyframe) => keyframe.frame))},@@ -174,7 +186,7 @@ export const generateCanvasCaptureComposition = ({? `${componentName.slice(0, -'Composition'.length)}Preview`: `${componentName}Preview`;- return formatOutput(`import {MacOSCursor} from '@remotion/mac-cursors';+ return `import {MacOSCursor} from '@remotion/mac-cursors';import {Video} from '@remotion/media';import {AbsoluteFill,@@ -218,7 +230,7 @@ ${customCursor === undefined ? '' : `\t\t\t\tcustomCursor={${serialize(customCurexport const ${componentName} = () => {return (<Composition- id=${serialize(compositionId)}+ id={${serialize(compositionId)}}component={${previewComponentName}}width={${width}}height={${height}}@@ -227,5 +239,5 @@ export const ${componentName} = () => {/>);};-`);+`;};diff --git a/packages/studio-server/src/codemods/apply-codemod-to-file.ts b/packages/studio-server/src/codemods/apply-codemod-to-file.tsindex 8f3d4a74ff..306031bf37 100644--- a/packages/studio-server/src/codemods/apply-codemod-to-file.ts+++ b/packages/studio-server/src/codemods/apply-codemod-to-file.ts@@ -45,5 +45,15 @@ export const applyCodemodToFile = async ({input,});- return formatOutput(newContents);+ if (+ codeMod.type === 'new-composition' ||+ codeMod.type === 'duplicate-composition' ||+ codeMod.type === 'rename-composition' ||+ codeMod.type === 'delete-composition'+ ) {+ return newContents;+ }++ const formatted = await formatOutput(newContents);+ return formatted;};diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.tsindex 39f384e962..345268ac9c 100644--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts@@ -11,7 +11,6 @@ import {applyCodemodToFile,resolveFilePathFromSymbolicatedStack,} from '../../codemods/apply-codemod-to-file';-import {formatOutput} from '../../codemods/duplicate-composition';import {writeFileAndNotifyFileWatchers} from '../../file-watcher';import type {ApiHandler} from '../api-types';import {formatLogFileLocation} from '../format-log-file-location';@@ -47,12 +46,12 @@ const formatNewCompositionFile = (});}- return formatOutput(`import React from 'react';+ return `import React from 'react';export const ${codemod.componentName}: React.FC = () => {return null;};-`);+`;};const getFolderPath = (parentName: string | null, folderName: string) => {diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/apply-codemod.test.tsindex 4706e0db55..ea000a7cad 100644--- a/packages/studio-server/src/test/apply-codemod.test.ts+++ b/packages/studio-server/src/test/apply-codemod.test.ts@@ -9,6 +9,7 @@ import {import {tmpdir} from 'node:os';import path from 'node:path';import type {RecastCodemod} from '@remotion/studio-shared';+import * as prettier from 'prettier';import {parseAndApplyCodemod} from '../codemods/duplicate-composition';import {createFileWatcherRegistry,@@ -401,6 +402,16 @@ const runCompositionCodemodUndoRedoTest = async ({? spyOn(console, 'log').mockImplementation(() => undefined): null;+ const formatter = [+ 'duplicate-composition',+ 'rename-composition',+ 'delete-composition',+ ].includes(codemod.type)+ ? spyOn(prettier, 'format').mockImplementation(() => {+ throw new Error('Prettier must not be called');+ })+ : null;+try {clearUndoRedoStacks();const entryPoint = path.join(remotionRoot, 'Root.tsx');@@ -453,6 +464,7 @@ const runCompositionCodemodUndoRedoTest = async ({expect(getUndoStack().length).toBe(1);expect(getRedoStack().length).toBe(0);} finally {+ formatter?.mockRestore();clearUndoRedoStacks();cleanupLiveEvents();cleanupFileWatcher();@@ -665,6 +677,10 @@ test('applyCodemodHandler creates new composition files with undo and redo', asyaddNewClientListener: () => () => undefined,});+ const formatter = spyOn(prettier, 'format').mockImplementation(() => {+ throw new Error('Prettier must not be called');+ });+try {clearUndoRedoStacks();const entryPoint = path.join(remotionRoot, 'Root.tsx');@@ -702,7 +718,23 @@ test('applyCodemodHandler creates new composition files with undo and redo', asy);expect(applyResponse.success).toBe(true);- expect(readFileSync(entryPoint, 'utf-8')).toContain('id="FreshVideo"');+ expect(readFileSync(entryPoint, 'utf-8')).toBe(+ "import {FreshVideo} from './FreshVideo';\n" ++ rootContents.replace(+ '\t\t</>',+ [+ '\t\t\t<Composition',+ '\t\t\t\tid="FreshVideo"',+ '\t\t\t\tcomponent={FreshVideo}',+ '\t\t\t\tdurationInFrames={150}',+ '\t\t\t\tfps={30}',+ '\t\t\t\twidth={1920}',+ '\t\t\t\theight={1080}',+ '\t\t\t/>',+ '\t\t</>',+ ].join('\n'),+ ),+ );expect(readFileSync(entryPoint, 'utf-8')).toContain("import {FreshVideo} from './FreshVideo'",);@@ -726,6 +758,7 @@ test('applyCodemodHandler creates new composition files with undo and redo', asy'export const FreshVideo',);} finally {+ formatter.mockRestore();clearUndoRedoStacks();cleanupLiveEvents();cleanupFileWatcher();@@ -746,6 +779,10 @@ test('applyCodemodHandler creates an interactive Canvas Capture composition', asaddNewClientListener: () => () => undefined,});+ const formatter = spyOn(prettier, 'format').mockImplementation(() => {+ throw new Error('Prettier must not be called');+ });+try {clearUndoRedoStacks();const entryPoint = path.join(remotionRoot, 'Root.tsx');@@ -825,7 +862,7 @@ test('applyCodemodHandler creates an interactive Canvas Capture composition', asexpect(componentContents).toContain("src={staticFile('capture.mp4')}");expect(componentContents).toContain('width: 1920');expect(componentContents).toContain('height: 1080');- expect(componentContents).toContain('id="FreshCapture"');+ expect(componentContents).toContain("id={'FreshCapture'}");expect(componentContents).toContain('width={1280}');expect(componentContents).toContain('height={720}');@@ -836,6 +873,7 @@ test('applyCodemodHandler creates an interactive Canvas Capture composition', asexpect(readFileSync(entryPoint, 'utf-8')).toBe(rootContents);expect(existsSync(componentFile)).toBe(false);} finally {+ formatter.mockRestore();clearUndoRedoStacks();cleanupLiveEvents();cleanupFileWatcher();