🎥 Make videos programmatically with React
`@remotion/studio`: Save folder operations without Prettier
Jonny Burger01117deae2da
diff --git a/packages/studio-codemods/src/composition-source-edits.ts b/packages/studio-codemods/src/composition-source-edits.tsindex f6b42b8093..2c79c2d927 100644--- a/packages/studio-codemods/src/composition-source-edits.ts+++ b/packages/studio-codemods/src/composition-source-edits.ts@@ -6,7 +6,6 @@ import {getNodeSourceEdit} from './delete-jsx-node';import {getCompositionId} from './duplicate-composition';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';@@ -14,6 +13,7 @@ import {applySourceEdits,captureImportSnapshots,getInsertImportSourceEdits,+ getJsxStringAttributeValueSourceEdit,type SourceEdit,} from './source-edits';@@ -150,31 +150,17 @@ export const editCompositionInSource = ({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') {+ if (attribute?.type !== 'JSXAttribute') {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});+ edits.push(+ getJsxStringAttributeValueSourceEdit({+ attribute,+ input,+ newValue: codeMod.newId,+ }),+ );changesMade.push({description: 'Replaced composition id'});return false;},diff --git a/packages/studio-codemods/src/folder-source-edits.ts b/packages/studio-codemods/src/folder-source-edits.tsnew file mode 100644index 0000000000..5ed6c9915d--- /dev/null+++ b/packages/studio-codemods/src/folder-source-edits.ts@@ -0,0 +1,518 @@+import type {+ File,+ JSXElement,+ JSXFragment,+ ReturnStatement,+} from '@babel/types';+import type {CompositionOrFolder, RecastCodemod} from '@remotion/studio-shared';+import * as recast from 'recast';+import {getNodeSourceEdit} from './delete-jsx-node';+import {getInsertionRootSourceEdit} from './insert-jsx-element';+import {indentInsertedJsx, printInsertedJsx} 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 => {+ let currentPath: recast.types.NodePath | null = path;+ while (currentPath !== null) {+ const node = currentPath.node as ReturnStatement;+ if (+ node.type === 'ReturnStatement' &&+ (node.argument?.type === 'JSXElement' ||+ node.argument?.type === 'JSXFragment')+ ) {+ return node.argument;+ }++ currentPath = currentPath.parentPath ?? null;+ }++ 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() === '') {+ lines.shift();+ }++ while (lines.at(-1)?.trim() === '') {+ lines.pop();+ }++ const indents = lines+ .filter((line) => line.trim() !== '')+ .map((line) => line.match(/^[\t ]*/)?.[0] ?? '');+ let commonIndent = indents[0] ?? '';+ for (const indent of indents.slice(1)) {+ while (!indent.startsWith(commonIndent)) {+ commonIndent = commonIndent.slice(0, -1);+ }+ }++ return lines+ .map((line) => (line.trim() === '' ? '' : line.slice(commonIndent.length)))+ .join(getEndOfLine(source));+};++const isMeaningfulChild = (child: JSXElement['children'][number]) =>+ child.type !== 'JSXText' || child.value.trim() !== '';++const getDeleteFolderSourceEdit = ({+ input,+ located,+}: {+ input: string;+ located: LocatedItem;+}): SourceEdit => {+ const {node, path} = located;+ if (!node.loc) {+ throw new Error('Could not locate the folder to delete');+ }++ const openingEnd = node.openingElement.loc+ ? recastLocToOffset(input, node.openingElement.loc.end)+ : null;+ const closingStart = node.closingElement?.loc+ ? recastLocToOffset(input, node.closingElement.loc.start)+ : null;+ const inner =+ openingEnd === null || closingStart === null+ ? ''+ : normalizeBlock(input.slice(openingEnd, closingStart));++ if (!located.directJsxChild) {+ const meaningfulChildren = node.children.filter(isMeaningfulChild);+ if (meaningfulChildren.length === 0) {+ return {+ start: recastLocToOffset(input, node.loc.start),+ end: recastLocToOffset(input, node.loc.end),+ replacement: 'null',+ };+ }++ if (+ meaningfulChildren.length === 1 &&+ (meaningfulChildren[0].type === 'JSXElement' ||+ meaningfulChildren[0].type === 'JSXFragment')+ ) {+ return {+ start: recastLocToOffset(input, node.loc.start),+ end: recastLocToOffset(input, node.loc.end),+ replacement: inner,+ };+ }++ const rootIndent = getLineIndent({+ input,+ offset: recastLocToOffset(input, node.loc.start),+ });+ const endOfLine = getEndOfLine(input);+ const unit = getIndentationUnit(input, null);+ return {+ start: recastLocToOffset(input, node.loc.start),+ end: recastLocToOffset(input, node.loc.end),+ replacement: [+ '<>',+ indentInsertedJsx({+ indent: `${rootIndent}${unit}`,+ insertion: inner,+ }),+ `${rootIndent}</>`,+ ].join(endOfLine),+ };+ }++ const deletion = getNodeSourceEdit({input, jsxPath: path});+ if (inner === '') {+ return deletion;+ }++ const nodeStart = recastLocToOffset(input, node.loc.start);+ const indent = getLineIndent({input, offset: nodeStart});+ return {+ ...deletion,+ replacement: `${indentInsertedJsx({indent, insertion: inner})}${+ deletion.end > recastLocToOffset(input, node.loc.end)+ ? getEndOfLine(input)+ : ''+ }`,+ };+};++const getMoveSourceEdits = ({+ codeMod,+ input,+ items,+}: {+ codeMod: Extract<+ FolderCodemod,+ {type: 'move-composition-or-folder' | 'move-composition-to-folder'}+ >;+ input: string;+ items: LocatedItem[];+}): 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 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');+ }++ insertionEdit = getInsertionRootSourceEdit({+ input,+ insertion,+ root: destination.node 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})};+};diff --git a/packages/studio-codemods/src/parse-and-apply-codemod.ts b/packages/studio-codemods/src/parse-and-apply-codemod.tsindex 15555890af..d44ef5d8f2 100644--- a/packages/studio-codemods/src/parse-and-apply-codemod.ts+++ b/packages/studio-codemods/src/parse-and-apply-codemod.ts@@ -1,9 +1,9 @@import type {RecastCodemod} from '@remotion/studio-shared';import {editCompositionInSource} from './composition-source-edits';import {duplicateCompositionInSource} from './duplicate-composition';+import {editFolderInSource} from './folder-source-edits';import type {Change} from './recast-mods';import {applyCodemod} from './recast-mods';-import {ensureNamedImport} from './sequence-props/imports';import {parseAst, serializeAst} from './sequence-props/parse-ast';export const parseAndApplyCodemod = ({@@ -25,6 +25,16 @@ export const parseAndApplyCodemod = ({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({@@ -38,15 +48,6 @@ export const parseAndApplyCodemod = ({);}- if (codeMod.type === 'new-folder') {- ensureNamedImport({- ast: newAst,- importedName: 'Folder',- sourcePath: 'remotion',- localName: 'Folder',- });- }-const output = serializeAst(newAst);return {changesMade, newContents: output};diff --git a/packages/studio-codemods/src/recast-mods.ts b/packages/studio-codemods/src/recast-mods.tsindex 8d0a9b8121..ffeb0a6da9 100644--- a/packages/studio-codemods/src/recast-mods.ts+++ b/packages/studio-codemods/src/recast-mods.ts@@ -1209,7 +1209,7 @@ const mapRecognizedType = <T extends RecognizedType>(return expression;};-const getCompositionIdFromJSXElement = (+export const getCompositionIdFromJSXElement = (jsxElement: JSXFragment['children'][number],) => {if (jsxElement.type !== 'JSXElement') {@@ -1262,7 +1262,7 @@ const getCompositionIdFromJSXElement = (return id[0];};-const getFolderNameFromJSXElement = (+export const getFolderNameFromJSXElement = (jsxElement: JSXFragment['children'][number],) => {if (jsxElement.type !== 'JSXElement') {diff --git a/packages/studio-codemods/src/source-edits.ts b/packages/studio-codemods/src/source-edits.tsindex f9d760c1a5..969a22f64e 100644--- a/packages/studio-codemods/src/source-edits.ts+++ b/packages/studio-codemods/src/source-edits.ts@@ -1,7 +1,15 @@-import type {File, ImportDeclaration, Node} from '@babel/types';+import type {+ File,+ ImportDeclaration,+ JSXAttribute,+ JSXElement,+ Node,+} from '@babel/types';+import * as recast from 'recast';+import {indentInsertedJsx} from './print-jsx';import {recastLocToOffset} from './recast-loc-to-offset';import {getImportedName} from './sequence-props/imports';-import {getEndOfLine, getPreferredQuote} from './source-style';+import {getEndOfLine, getLineIndent, getPreferredQuote} from './source-style';export type SourceEdit = {end: number;@@ -14,6 +22,110 @@ export type ImportSnapshot = {specifiers: NonNullable<ImportDeclaration['specifiers']>;};+export const getJsxStringAttributeValueSourceEdit = ({+ attribute,+ input,+ newValue,+}: {+ attribute: JSXAttribute;+ input: string;+ newValue: string;+}): SourceEdit => {+ const {value} = attribute;+ const literal =+ value?.type === 'JSXExpressionContainer' ? value.expression : value;+ if (!literal?.loc || literal.type !== 'StringLiteral') {+ throw new Error(`Could not locate the "${attribute.name.name}" attribute`);+ }++ const start = recastLocToOffset(input, literal.loc.start);+ const end = recastLocToOffset(input, literal.loc.end);+ const quote = input[start] === "'" ? "'" : '"';+ const replacement =+ value?.type === 'StringLiteral'+ ? quote ++ newValue+ .replaceAll('&', '&')+ .replaceAll('"', '"')+ .replaceAll("'", ''')+ .replaceAll('<', '<') ++ quote+ : recast.prettyPrint(recast.types.builders.stringLiteral(newValue), {+ quote: quote === "'" ? 'single' : 'double',+ }).code;++ return {start, end, replacement};+};++export const getJsxElementSourceForInsertion = ({+ element,+ input,+}: {+ element: JSXElement;+ input: string;+}): string => {+ if (!element.loc) {+ throw new Error('Could not locate the JSX element to move');+ }++ const start = recastLocToOffset(input, element.loc.start);+ const end = recastLocToOffset(input, element.loc.end);+ const originalIndent = getLineIndent({input, offset: start});++ return input+ .slice(start, end)+ .split(/\r?\n/)+ .map((line, index) => {+ if (index === 0) {+ return line;+ }++ return line.startsWith(originalIndent)+ ? line.slice(originalIndent.length)+ : line.trimStart();+ })+ .join(getEndOfLine(input));+};++export const getAdjacentJsxInsertionSourceEdit = ({+ input,+ insertion,+ position,+ target,+}: {+ input: string;+ insertion: string;+ position: 'after' | 'before';+ target: JSXElement;+}): SourceEdit => {+ if (!target.loc) {+ throw new Error('Could not locate the JSX reorder target');+ }++ const targetStart = recastLocToOffset(input, target.loc.start);+ const targetEnd = recastLocToOffset(input, target.loc.end);+ const indent = getLineIndent({input, offset: targetStart});+ const endOfLine = getEndOfLine(input);++ if (position === 'after') {+ return {+ start: targetEnd,+ end: targetEnd,+ replacement: `${endOfLine}${indentInsertedJsx({indent, insertion})}`,+ };+ }++ const continuation = insertion+ .split(/\r?\n/)+ .map((line, index) => (index === 0 ? line : `${indent}${line}`))+ .join(endOfLine);+ return {+ start: targetStart,+ end: targetStart,+ replacement: `${continuation}${endOfLine}${indent}`,+ };+};+export const getNodeEndIncludingSameLineComments = ({input,node,diff --git a/packages/studio-codemods/src/test/folder-source-edits.test.ts b/packages/studio-codemods/src/test/folder-source-edits.test.tsnew file mode 100644index 0000000000..2fa3bed134--- /dev/null+++ b/packages/studio-codemods/src/test/folder-source-edits.test.ts@@ -0,0 +1,225 @@+import {expect, test} from 'bun:test';+import {parseAndApplyCodemod} from '../parse-and-apply-codemod';+import {parseAst} from '../sequence-props/parse-ast';++const untouched = 'const untouched = { value : "keep" }; // preserve';++test('renames a folder without formatting the file', () => {+ const input = `import {Folder} from 'remotion';++${untouched}+export const Root = () => (+ <Folder name={'Old name'}>+ <div />+ </Folder>+);+`;+ const output = parseAndApplyCodemod({+ input,+ codeMod: {+ type: 'rename-folder',+ folderName: 'Old name',+ parentName: null,+ newName: 'New name',+ },+ }).newContents;++ expect(output).toBe(input.replace("'Old name'", "'New name'"));+ parseAst(output);+});++test('creates top-level and nested folders without formatting the file', () => {+ const input = [+ 'import {Composition} from "remotion"',+ '',+ untouched,+ 'export const Root=()=>(',+ ' <>',+ ' <Folder name="Existing" />',+ ' <Composition id="Keep" />',+ ' </>',+ ')',+ '',+ ].join('\r\n');+ const topLevel = parseAndApplyCodemod({+ input,+ codeMod: {+ type: 'new-folder',+ folderName: 'Top level',+ parentName: null,+ },+ }).newContents;+ expect(topLevel).toBe(+ input+ .replace(+ 'import {Composition} from "remotion"',+ 'import {Composition, Folder} from "remotion"',+ )+ .replace(+ ' <Composition id="Keep" />\r\n </>',+ ' <Composition id="Keep" />\r\n <Folder name="Top level" />\r\n </>',+ ),+ );++ const nested = parseAndApplyCodemod({+ input: topLevel,+ codeMod: {+ type: 'new-folder',+ folderName: 'Nested',+ parentName: 'Existing',+ },+ }).newContents;+ expect(nested).toBe(+ topLevel.replace(+ ' <Folder name="Existing" />',+ [+ ' <Folder name="Existing">',+ ' <Folder name="Nested" />',+ ' </Folder>',+ ].join('\r\n'),+ ),+ );+ parseAst(nested);+});++test('deletes a folder by unwrapping its source without formatting it', () => {+ const input = `import {Folder} from 'remotion';++${untouched}+export const Root = () => (+ <>+ <Folder name="Remove">+ {/* preserve this comment */}+ <Folder name="Nested">+ <div data-spacing = "keep" />+ </Folder>+ </Folder>+ <div />+ </>+);+`;+ const output = parseAndApplyCodemod({+ input,+ codeMod: {+ type: 'delete-folder',+ folderName: 'Remove',+ parentName: null,+ },+ }).newContents;++ expect(output).toBe(+ input.replace(+ ` <Folder name="Remove">+ {/* preserve this comment */}+ <Folder name="Nested">+ <div data-spacing = "keep" />+ </Folder>+ </Folder>+`,+ ` {/* preserve this comment */}+ <Folder name="Nested">+ <div data-spacing = "keep" />+ </Folder>+`,+ ),+ );+ parseAst(output);+});++test('moves a composition into a folder without formatting either node', () => {+ const input = `import {Composition, Folder} from 'remotion';++${untouched}+export const Root = () => {+ return (+ <>+ <Folder name="Target">+ {/* keep target */}+ </Folder>+ <Composition+ id="Move"+ component = {Video}+ />+ </>+ );+};+`;+ const output = parseAndApplyCodemod({+ input,+ codeMod: {+ type: 'move-composition-to-folder',+ idToMove: 'Move',+ folderName: 'Target',+ parentName: null,+ },+ }).newContents;++ expect(output).toBe(+ input+ .replace(+ ` <Composition+ id="Move"+ component = {Video}+ />+`,+ '',+ )+ .replace(+ ' </Folder>',+ ` <Composition+ id="Move"+ component = {Video}+ />+ </Folder>`,+ ),+ );+ parseAst(output);+});++test('moves a folder next to another item without formatting it', () => {+ const input = `import {Composition, Folder} from 'remotion';++${untouched}+export const Root = () => {+ return (+ <>+ <Folder name="Move">+ <Composition id="Nested" />+ </Folder>+ <Composition id="Middle" />+ <Folder name="Target" />+ </>+ );+};+`;+ const output = parseAndApplyCodemod({+ input,+ codeMod: {+ type: 'move-composition-or-folder',+ source: {type: 'folder', folderName: 'Move', parentName: null},+ destination: {+ type: 'after',+ target: {type: 'folder', folderName: 'Target', parentName: null},+ },+ },+ }).newContents;++ expect(output).toBe(+ input+ .replace(+ ` <Folder name="Move">+ <Composition id="Nested" />+ </Folder>+`,+ '',+ )+ .replace(+ ' <Folder name="Target" />',+ ` <Folder name="Target" />+ <Folder name="Move">+ <Composition id="Nested" />+ </Folder>`,+ ),+ );+ parseAst(output);+});diff --git a/packages/studio-server/src/codemods/apply-codemod-to-file.ts b/packages/studio-server/src/codemods/apply-codemod-to-file.tsindex 306031bf37..6d3339d92e 100644--- a/packages/studio-server/src/codemods/apply-codemod-to-file.ts+++ b/packages/studio-server/src/codemods/apply-codemod-to-file.ts@@ -49,7 +49,12 @@ export const applyCodemodToFile = async ({codeMod.type === 'new-composition' ||codeMod.type === 'duplicate-composition' ||codeMod.type === 'rename-composition' ||- codeMod.type === 'delete-composition'+ codeMod.type === 'delete-composition' ||+ 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 newContents;}diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/apply-codemod.test.tsindex 6284c977c2..66d89ac1ae 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 {applyCodemodToFile} from '../codemods/apply-codemod-to-file';import {parseAndApplyCodemod} from '../codemods/duplicate-composition';import {createFileWatcherRegistry,@@ -185,6 +186,33 @@ const clearUndoRedoStacks = () => {(getRedoStack() as unknown as unknown[]).length = 0;};+test('folder 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 {Folder} from 'remotion';++const untouched = { value : "keep" };+export const Root = () => <Folder name="Before" />;+`;++ try {+ writeFileSync(filePath, input);+ const output = await applyCodemodToFile({+ filePath,+ codeMod: {+ type: 'rename-folder',+ folderName: 'Before',+ parentName: null,+ newName: 'After',+ },+ });++ expect(output).toBe(input.replace('"Before"', '"After"'));+ } finally {+ rmSync(remotionRoot, {recursive: true, force: true});+ }+});+test('formats precise log messages for all codemods', () => {const testCases: {codemod: RecastCodemod; expected: string}[] = [{