🎥 Make videos programmatically with React
@remotion/studio-codemods: Reorder sequences without Prettier
Jonny Burger5116288deab5
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex 3e892006b6..3b8499de77 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -1517,7 +1517,6 @@ export const createBrowserStudioOperations = ({sourceNodePath: sourceNodePath.nodePath,targetNodePath: targetNodePath.nodePath,position,- formatFile: formatCodemodFile,});const nodePathMutation = controller.applyMutation({undoRedoNavigation: null,diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 8298a648e3..d4014836c5 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -1476,18 +1476,18 @@ export const Root = () => {test('reorders JSX sequences as an undoable project mutation', async () => {const fileName = '/project/src/Composition.tsx';- const initialContents = `import {Composition, Sequence} from 'remotion';+ const initialContents = `import {Composition,Sequence} from "remotion"-export const Component = () => {+export const Component=()=>{return (<><Sequence name="first" from={0} durationInFrames={20} /><Sequence name="second" from={20} durationInFrames={20} /></>- );-};+ )+}-export const Root = () => <Composition id="MyComp" component={Component} durationInFrames={60} fps={30} width={1280} height={720} />;+export const Root=()=> <Composition id="MyComp" component={Component} durationInFrames={60} fps={30} width={1280} height={720} />`;const {operations, getProject} = makeOperationsForProject({rootDir: '/project',@@ -1556,9 +1556,19 @@ registerRoot(Root);`,}const reordered = getProject().files[fileName];- expect(reordered.indexOf('name="second"')).toBeLessThan(- reordered.indexOf('name="first"'),- );+ expect(reordered).toBe(`import {Composition,Sequence} from "remotion"++export const Component=()=>{+ return (+ <>+ <Sequence name="second" from={20} durationInFrames={20} />+ <Sequence name="first" from={0} durationInFrames={20} />+ </>+ )+}++export const Root=()=> <Composition id="MyComp" component={Component} durationInFrames={60} fps={30} width={1280} height={720} />+`);expect(result.nodePathMutation.files).toEqual([{absolutePath: fileName,diff --git a/packages/studio-codemods/src/reorder-sequence.ts b/packages/studio-codemods/src/reorder-sequence.tsindex 8a92138764..8d96d1cc7a 100644--- a/packages/studio-codemods/src/reorder-sequence.ts+++ b/packages/studio-codemods/src/reorder-sequence.ts@@ -8,12 +8,18 @@ import type {SequenceNodePath} from 'remotion';import {findJsxElementPathForDeletion,getJsxElementTagLabel,+ getNodeSourceEdit,} from './delete-jsx-node';import {captureJsxNodePaths,getNodePathRemappings,} from './get-node-path-remappings';-import {parseAst, serializeAst} from './sequence-props/parse-ast';+import {parseAst} from './sequence-props/parse-ast';+import {+ applySourceEdits,+ getAdjacentJsxInsertionSourceEdit,+ getJsxElementSourceForInsertion,+} from './source-edits';const {namedTypes} = recast.types;@@ -36,19 +42,20 @@ const getJsxChildrenParent = (return null;};+/* eslint-disable require-await -- Keep the formatter-era Promise API. */export const reorderSequence = async ({input,sourceNodePath,targetNodePath,position,- formatFile,- prettierConfigOverride,}: {input: string;sourceNodePath: SequenceNodePath;targetNodePath: SequenceNodePath;position: ReorderSequencePosition;- formatFile: (input: {+ // Kept optional for compatibility with callers from before source edits+ // replaced the full-file formatting pass.+ formatFile?: (input: {contents: string;prettierConfigOverride: Record<string, unknown> | null;}) => Promise<{output: string; formatted: boolean}>;@@ -102,6 +109,18 @@ export const reorderSequence = async ({sourceElement.openingElement.loc?.start.line ??sourceElement.loc?.start.line ??1;+ const sourceEdits = [+ getNodeSourceEdit({input, jsxPath: sourcePath}),+ getAdjacentJsxInsertionSourceEdit({+ input,+ insertion: getJsxElementSourceForInsertion({+ element: sourceElement,+ input,+ }),+ position,+ target: targetElement,+ }),+ ];const [moved] = children.splice(sourceIndex, 1);if (!moved) {@@ -121,11 +140,7 @@ export const reorderSequence = async ({moved,);- const finalFile = serializeAst(ast);- const {output, formatted} = await formatFile({- contents: finalFile,- prettierConfigOverride: prettierConfigOverride ?? null,- });+ const output = applySourceEdits({edits: sourceEdits, input});const {nodePathRemappings} = getNodePathRemappings({ast,captured: capturedNodePaths,@@ -134,9 +149,10 @@ export const reorderSequence = async ({return {output,- formatted,+ formatted: true,sequenceLabel,logLine,nodePathRemappings,};};+/* eslint-enable require-await */diff --git a/packages/studio-server/src/codemods/reorder-sequence.ts b/packages/studio-server/src/codemods/reorder-sequence.tsindex 615ea61592..1a19b60220 100644--- a/packages/studio-server/src/codemods/reorder-sequence.ts+++ b/packages/studio-server/src/codemods/reorder-sequence.ts@@ -1,30 +1 @@-import {reorderSequence as reorderSequenceCodemod} from '@remotion/studio-codemods';-import type {ReorderSequencePosition} from '@remotion/studio-shared';-import type {SequenceNodePath} from 'remotion';-import {formatFileContent} from './format-file-content';--export const reorderSequence = ({- input,- sourceNodePath,- targetNodePath,- position,- prettierConfigOverride,-}: {- input: string;- sourceNodePath: SequenceNodePath;- targetNodePath: SequenceNodePath;- position: ReorderSequencePosition;- prettierConfigOverride?: Record<string, unknown> | null;-}) =>- reorderSequenceCodemod({- input,- sourceNodePath,- targetNodePath,- position,- formatFile: ({contents, prettierConfigOverride: override}) =>- formatFileContent({- input: contents,- prettierConfigOverride: override,- }),- prettierConfigOverride,- });+export {reorderSequence} from '@remotion/studio-codemods';diff --git a/packages/studio-server/src/preview-server/routes/reorder-sequence.ts b/packages/studio-server/src/preview-server/routes/reorder-sequence.tsindex c1019d2468..3297be06f5 100644--- a/packages/studio-server/src/preview-server/routes/reorder-sequence.ts+++ b/packages/studio-server/src/preview-server/routes/reorder-sequence.ts@@ -16,7 +16,6 @@ import {suppressUndoStackInvalidation,} from '../undo-stack';import {attrName} from './log-updates/formatting';-import {warnAboutPrettierOnce} from './log-updates/log-update';import {getCodemodTimingPrefix,withSourceFileWriteQueue,@@ -44,7 +43,7 @@ export const reorderSequenceHandler: ApiHandler<});const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, formatted, sequenceLabel, logLine, nodePathRemappings} =+ const {output, sequenceLabel, logLine, nodePathRemappings} =await reorderSequence({input: fileContents,sourceNodePath: sourceNodePath.nodePath,@@ -93,13 +92,9 @@ export const reorderSequenceHandler: ApiHandler<{indent: false, logLevel},`${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(`${locationLabel}`)} Reordered ${attrName(sequenceLabel)}`,);- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }-RenderInternals.Log.verbose({indent: false, logLevel},- `[reorder-sequence] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,+ `[reorder-sequence] Wrote ${fileRelativeToRoot}`,);printUndoHint(logLevel);diff --git a/packages/studio-server/src/test/reorder-sequence.test.ts b/packages/studio-server/src/test/reorder-sequence.test.tsindex 8ed4d0ac1f..f44bd79c26 100644--- a/packages/studio-server/src/test/reorder-sequence.test.ts+++ b/packages/studio-server/src/test/reorder-sequence.test.ts@@ -1,44 +1,103 @@import {expect, test} from 'bun:test';+import {parseAst} from '../codemods/parse-ast';import {reorderSequence} from '../codemods/reorder-sequence';-import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';+import {lineColumnToNodePath as getNodePathAtPosition} from '../preview-server/routes/can-update-sequence-props';+import {lineColumnToNodePath} from './test-utils';-const buildInput = () => `import {Sequence} from 'remotion';+const sequenceContaining = (input: string, search: string) => {+ const searchOffset = input.indexOf(search);+ if (searchOffset === -1) {+ throw new Error(`Could not find ${JSON.stringify(search)} in source`);+ }-export const Comp = () => {+ const openingOffset = input.lastIndexOf('<Sequence', searchOffset);+ if (openingOffset === -1) {+ throw new Error(+ `Could not find a Sequence containing ${JSON.stringify(search)}`,+ );+ }++ const sourceBeforeOpening = input.slice(0, openingOffset).split('\n');+ 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)}`,+ );+ }++ return nodePath;+};++const buildInput = () => `import {Sequence} from 'remotion'++const untouched = {keep:"this spacing"}++export const Comp=()=>{return (<>- <Sequence name="a" from={0} />- <Sequence name="b" from={10} />- <Sequence name="c" from={20} />+ <Sequence name='a' from = {0}/>+ {/* keep this comment before b */}+ <Sequence+ name='b'+ from = {10}+ />+ <Sequence name='c' from={20}/></>- );-};+ )+}`;-test('reorderSequence moves a sequence forward', async () => {+test('reorderSequence moves a sequence forward without formatting the file', async () => {const input = buildInput();+ let formatCalls = 0;const {output, sequenceLabel, nodePathRemappings} = await reorderSequence({input,- sourceNodePath: lineColumnToNodePath(input, 6),- targetNodePath: lineColumnToNodePath(input, 8),+ sourceNodePath: sequenceContaining(input, "name='a'"),+ targetNodePath: sequenceContaining(input, "name='c'"),position: 'after',+ formatFile: () => {+ formatCalls++;+ throw new Error('Prettier must not be called');+ },});expect(sequenceLabel).toBe('<Sequence>');- expect(output.indexOf('name="b"')).toBeLessThan(output.indexOf('name="c"'));- expect(output.indexOf('name="c"')).toBeLessThan(output.indexOf('name="a"'));+ expect(formatCalls).toBe(0);+ expect(output).toBe(`import {Sequence} from 'remotion'++const untouched = {keep:"this spacing"}++export const Comp=()=>{+ return (+ <>+ {/* keep this comment before b */}+ <Sequence+ name='b'+ from = {10}+ />+ <Sequence name='c' from={20}/>+ <Sequence name='a' from = {0}/>+ </>+ )+}+`);expect(nodePathRemappings).toEqual([{- oldNodePath: lineContainingToNodePath(input, 'name="a"'),- newNodePath: lineContainingToNodePath(output, 'name="a"'),+ oldNodePath: sequenceContaining(input, "name='a'"),+ newNodePath: sequenceContaining(output, "name='a'"),},{- oldNodePath: lineContainingToNodePath(input, 'name="b"'),- newNodePath: lineContainingToNodePath(output, 'name="b"'),+ oldNodePath: sequenceContaining(input, "name='b'"),+ newNodePath: sequenceContaining(output, "name='b'"),},{- oldNodePath: lineContainingToNodePath(input, 'name="c"'),- newNodePath: lineContainingToNodePath(output, 'name="c"'),+ oldNodePath: sequenceContaining(input, "name='c'"),+ newNodePath: sequenceContaining(output, "name='c'"),},]);});@@ -47,14 +106,85 @@ test('reorderSequence moves a sequence backward', async () => {const input = buildInput();const {output, sequenceLabel} = await reorderSequence({input,- sourceNodePath: lineColumnToNodePath(input, 8),- targetNodePath: lineColumnToNodePath(input, 6),+ sourceNodePath: sequenceContaining(input, "name='c'"),+ targetNodePath: sequenceContaining(input, "name='a'"),position: 'before',});expect(sequenceLabel).toBe('<Sequence>');- expect(output.indexOf('name="c"')).toBeLessThan(output.indexOf('name="a"'));- expect(output.indexOf('name="a"')).toBeLessThan(output.indexOf('name="b"'));+ expect(output).toBe(`import {Sequence} from 'remotion'++const untouched = {keep:"this spacing"}++export const Comp=()=>{+ return (+ <>+ <Sequence name='c' from={20}/>+ <Sequence name='a' from = {0}/>+ {/* keep this comment before b */}+ <Sequence+ name='b'+ from = {10}+ />+ </>+ )+}+`);+});++test('reorderSequence preserves CRLF and multiline JSX', async () => {+ const input = [+ 'export const Comp = () => (',+ ' <>',+ ' <Sequence name="a" />',+ ' <Sequence',+ ' name="b"',+ ' style = {{opacity:1}}',+ ' />',+ ' <Sequence name="c" />',+ ' </>',+ ')',+ '',+ ].join('\r\n');++ const {output} = await reorderSequence({+ input,+ sourceNodePath: sequenceContaining(input, 'name="b"'),+ targetNodePath: sequenceContaining(input, 'name="c"'),+ position: 'after',+ });++ expect(output).toBe(+ [+ 'export const Comp = () => (',+ ' <>',+ ' <Sequence name="a" />',+ ' <Sequence name="c" />',+ ' <Sequence',+ ' name="b"',+ ' style = {{opacity:1}}',+ ' />',+ ' </>',+ ')',+ '',+ ].join('\r\n'),+ );+});++test('reorderSequence keeps inline siblings parseable', async () => {+ const input =+ 'export const Comp=()=> <><Sequence name="a"/><Sequence name="b"/></>;\n';++ const {output} = await reorderSequence({+ input,+ sourceNodePath: sequenceContaining(input, 'name="a"'),+ targetNodePath: sequenceContaining(input, 'name="b"'),+ position: 'after',+ });++ expect(output).toBe(+ 'export const Comp=()=> <><Sequence name="b"/>\n<Sequence name="a"/></>;\n',+ );});test('reorderSequence rejects sequences with different JSX parents', async () => {@@ -81,3 +211,17 @@ export const Comp = () => {}),).rejects.toThrow(/not JSX siblings/);});++test('reorderSequence rejects identical source and target sequences', async () => {+ const input = buildInput();+ const nodePath = sequenceContaining(input, "name='a'");++ await expect(+ reorderSequence({+ input,+ sourceNodePath: nodePath,+ targetNodePath: nodePath,+ position: 'after',+ }),+ ).rejects.toThrow(/source and target are identical/);+});