🎥 Make videos programmatically with React
`@remotion/codemods`: Group split clips in a named `Track`
JonnyBurger879c3e9e17bc
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 56c50ed0f0..5aca60a8e2 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -894,6 +894,7 @@ registerRoot(Root);`,throw new Error(splitResult.reason);}+ expect(currentProject.files[fileName]).toContain('<Track name="Sequence">');expect(currentProject.files[fileName]).toContain('<Sequence from={10} durationInFrames={5} />',);diff --git a/packages/codemods/src/split-jsx-sequence.ts b/packages/codemods/src/split-jsx-sequence.tsindex f2e6934b6c..11f34f3c41 100644--- a/packages/codemods/src/split-jsx-sequence.ts+++ b/packages/codemods/src/split-jsx-sequence.ts@@ -33,6 +33,8 @@ import {} from './get-node-path-remappings';import {printInsertedJsx} from './print-jsx';import {recastLocToOffset} from './recast-loc-to-offset';+import {ensureOfficialNamedImport} from './sequence-props/imports';+import {getJsxComponentIdentity} from './sequence-props/jsx-component-identity';import {parseAst, parseAstForReadOnly} from './sequence-props/parse-ast';import {parseVideoConfigNumericExpression,@@ -42,12 +44,17 @@ import {getVideoConfigIdentifierValues,type VideoConfigIdentifierValues,} from './sequence-props/video-config-values';-import {applySourceEdits} from './source-edits';+import {+ applySourceEdits,+ captureImportSnapshots,+ getInsertImportSourceEdits,+} from './source-edits';import {getEndOfLine,getLineIndent,indentContinuationLines,} from './source-style';+import {stripParenthesizedExtra} from './strip-parenthesized-extra';const {builders: b, namedTypes} = recast.types;@@ -383,12 +390,14 @@ const getSplitSourceEdit = ({left,prettierConfigOverride,right,+ track,wrapInFragment,}: {input: string;left: JSXElement;prettierConfigOverride: Record<string, unknown> | null;right: JSXElement;+ track: JSXElement | null;wrapInFragment: boolean;}) => {if (!left.loc) {@@ -416,9 +425,11 @@ const getSplitSourceEdit = ({prettierConfigOverride: formattingConfig,}),});- const replacement = wrapInFragment- ? print(makeFragment(left, right))- : `${print(left)}${isOnlyElementOnLine ? `${endOfLine}${lineIndent}` : ' '}${print(right)}`;+ const replacement = track+ ? print(track)+ : wrapInFragment+ ? print(makeFragment(left, right))+ : `${print(left)}${isOnlyElementOnLine ? `${endOfLine}${lineIndent}` : ' '}${print(right)}`;return {end, replacement, start};};@@ -442,6 +453,7 @@ export const splitJsxSequences = ({output: string;nodeLabels: string[];logLines: number[];+ insertedNodePaths: SequenceNodePath[];nodePathRemappings: SequenceNodePathRemapping[];}> => {if (splits.length === 0) {@@ -450,6 +462,7 @@ export const splitJsxSequences = ({const ast = parseAst(input);const capturedNodePaths = captureJsxNodePaths(ast);+ const importSnapshots = captureImportSnapshots(ast);const targets = splits.map(({nodePath, sequenceKeys, splitFrame, videoConfigValues}) => {if (!Number.isFinite(splitFrame)) {@@ -499,7 +512,25 @@ export const splitJsxSequences = ({throw new Error('Cannot split at or after the sequence end');}+ let isInsideTrack = false;+ let ancestor = jsxPath.parentPath;+ while (ancestor) {+ if (+ ancestor.node.type === 'JSXElement' &&+ getJsxComponentIdentity({+ ast,+ jsxElement: (ancestor.node as JSXElement).openingElement,+ }) === 'dev.remotion.remotion.Track'+ ) {+ isInsideTrack = true;+ break;+ }++ ancestor = ancestor.parentPath;+ }+return {+ isInsideTrack,contentDuration,from,jsxElement,@@ -511,9 +542,19 @@ export const splitJsxSequences = ({);const nodeLabels: string[] = [];const logLines: number[] = [];+ const insertedElements: JSXElement[] = [];const sourceEdits = targets.map(- ({contentDuration, from, jsxElement, jsxPath, splitFrame, timing}) => {+ ({+ contentDuration,+ from,+ isInsideTrack,+ jsxElement,+ jsxPath,+ splitFrame,+ timing,+ }) => {const right = cloneJsxElement(jsxElement);+ insertedElements.push(right);// Match Studio's numeric dragger precision while retaining fractional frames.const leftTimelineDuration = normalizeComputedTiming(splitFrame - from);const leftDuration = normalizeComputedTiming(@@ -571,8 +612,88 @@ export const splitJsxSequences = ({const isJsxChild =namedTypes.JSXElement.check(parentPath.node) ||namedTypes.JSXFragment.check(parentPath.node);- if (!insertAfter(parentPath.node, jsxElement, right)) {- jsxPath.replace(makeFragment(jsxElement, right));+ let track: JSXElement | null = null;+ if (isInsideTrack) {+ if (!insertAfter(parentPath.node, jsxElement, right)) {+ jsxPath.replace(makeFragment(jsxElement, right));+ }+ } else {+ const trackLocalName = ensureOfficialNamedImport({+ ast,+ importedName: 'Track',+ sourcePath: 'remotion',+ preferredLocalName: 'Track',+ });+ const {attributes} = jsxElement.openingElement;+ const nameAttribute = attributes.find(+ (attribute) => getAttributeName(attribute) === 'name',+ );+ const sourceAttribute = attributes.find(+ (attribute) => getAttributeName(attribute) === 'src',+ );+ let name: JSXAttribute['value'] =+ nameAttribute?.type === 'JSXAttribute' ? nameAttribute.value : null;+ if (!name && sourceAttribute?.type === 'JSXAttribute') {+ const source = sourceAttribute.value;+ const expression =+ source?.type === 'JSXExpressionContainer'+ ? source.expression+ : source;+ const sourceValue =+ expression?.type === 'StringLiteral'+ ? expression.value+ : expression?.type === 'CallExpression' &&+ expression.arguments[0]?.type === 'StringLiteral' &&+ expression.callee.type === 'Identifier' &&+ expression.callee.name === 'staticFile'+ ? expression.arguments[0].value+ : null;+ if (sourceValue) {+ let assetName = sourceValue.startsWith('data:')+ ? 'Data URL'+ : sourceValue.startsWith('blob:')+ ? 'Blob URL'+ : sourceValue.split(/[?#]/)[0].split(/[\\/]/).at(-1) ||+ sourceValue;+ try {+ assetName = decodeURIComponent(assetName);+ } catch {+ // Keep filenames that contain malformed URI escapes readable.+ }++ name = {type: 'StringLiteral', value: assetName};+ } else {+ name = source;+ }+ }++ track = {+ type: 'JSXElement',+ openingElement: {+ type: 'JSXOpeningElement',+ name: jsxId(trackLocalName),+ attributes: [+ {+ type: 'JSXAttribute',+ name: jsxId('name'),+ value: name ?? {+ type: 'StringLiteral',+ value: getSplittableSequenceTagName(jsxElement),+ },+ },+ ],+ selfClosing: false,+ },+ closingElement: {+ type: 'JSXClosingElement',+ name: jsxId(trackLocalName),+ },+ children: [+ stripParenthesizedExtra(jsxElement),+ stripParenthesizedExtra(right),+ ],+ };+ jsxPath.replace(track);}nodeLabels.push(getJsxElementTagLabel(jsxElement));@@ -586,12 +707,24 @@ export const splitJsxSequences = ({left: jsxElement,prettierConfigOverride: prettierConfigOverride ?? null,right,+ track,wrapInFragment: !isJsxChild,});},);- const output = applySourceEdits({edits: sourceEdits, input});- const {nodePathRemappings} = getNodePathRemappings({+ const output = applySourceEdits({+ edits: [+ ...sourceEdits,+ ...getInsertImportSourceEdits({+ ast,+ input,+ prettierConfigOverride: prettierConfigOverride ?? null,+ snapshots: importSnapshots,+ }),+ ],+ input,+ });+ const {nodePathRemappings, finalNodePathByNode} = getNodePathRemappings({ast,captured: capturedNodePaths,output,@@ -601,6 +734,14 @@ export const splitJsxSequences = ({output,nodeLabels,logLines,+ insertedNodePaths: insertedElements.map((element) => {+ const nodePath = finalNodePathByNode.get(element.openingElement);+ if (!nodePath) {+ throw new Error('Could not locate the split clip after editing');+ }++ return nodePath;+ }),nodePathRemappings,});};diff --git a/packages/codemods/src/split-sequences.ts b/packages/codemods/src/split-sequences.tsindex e5abdb23c6..b3e53c5e99 100644--- a/packages/codemods/src/split-sequences.ts+++ b/packages/codemods/src/split-sequences.ts@@ -4,11 +4,7 @@ import type {DuplicateNodesResult} from './duplicate-nodes';import {getNodeProps} from './get-node-props';import {getNodes, type CodemodNode} from './get-nodes';import {findProjectFile} from './internals';-import {- getNodeEditResult,- getInsertedNodeReferences,- type NodeReference,-} from './node-references';+import {getNodeEditResult, type NodeReference} from './node-references';import {splitJsxSequences} from './split-jsx-sequence';export type SplitSequencesOptions<Project extends CodemodProject> = {@@ -110,6 +106,8 @@ export const splitSequences = async <Project extends CodemodProject>({nodeLabels,logLines,})),- insertedNodes: getInsertedNodeReferences(result.nodePathRemappings),+ insertedNodes: edits.flatMap(({filePath, insertedNodePaths}) =>+ insertedNodePaths.map((nodePath) => ({filePath, nodePath})),+ ),};};diff --git a/packages/codemods/src/test/split-jsx-sequence.test.ts b/packages/codemods/src/test/split-jsx-sequence.test.tsindex f1f47fc80c..b41a0b8331 100644--- a/packages/codemods/src/test/split-jsx-sequence.test.ts+++ b/packages/codemods/src/test/split-jsx-sequence.test.ts@@ -79,7 +79,7 @@ test('splits multiple sibling sequences from the same source snapshot', async ());expect(nodePathRemappings.filter((remapping) => remapping.oldNodePath === null),- ).toHaveLength(2);+ ).toHaveLength(4);});test('splitting a sped-up sequence preserves its child clock across a fractional parent frame', async () => {@@ -150,7 +150,7 @@ test('splitJsxSequence splits a sequence with no duration', async () => {expect(output).toContain('<Sequence from={30} trimBefore={30} />');});-test('splitJsxSequence remaps following JSX siblings', async () => {+test('splitJsxSequence remaps wrapped clips and preserves following JSX siblings', async () => {const input = wrap('<Sequence name="split" from={0} durationInFrames={50} />\n\t\t\t<Sequence name="following" />',);@@ -162,18 +162,21 @@ test('splitJsxSequence remaps following JSX siblings', async () => {videoConfigValues: null,});+ expect(lineContainingToNodePath(output, 'name="following"')).toEqual(+ lineContainingToNodePath(input, 'name="following"'),+ );expect(nodePathRemappings).toEqual([{oldNodePath: lineContainingToNodePath(input, 'name="split"'),- newNodePath: lineContainingToNodePath(output, 'name="split"'),+ newNodePath: lineContainingToNodePath(output, '<Sequence name="split"'),oldJsxName: 'Sequence',newJsxName: 'Sequence',},{- oldNodePath: lineContainingToNodePath(input, 'name="following"'),- newNodePath: lineContainingToNodePath(output, 'name="following"'),- oldJsxName: 'Sequence',- newJsxName: 'Sequence',+ oldNodePath: null,+ newNodePath: lineContainingToNodePath(output, '<Track'),+ oldJsxName: null,+ newJsxName: 'Track',},{oldNodePath: null,@@ -205,10 +208,17 @@ test('splitJsxSequence keeps missing left from omitted', async () => {});test('splitJsxSequence splits finite duration and trimBefore', async () => {- const output = await split(- '<Sequence from={10} durationInFrames={50} trimBefore={5} />',- 30,- );+ const input = `import {Sequence, Track as TimelineTrack} from 'remotion';+export const Comp = () => <TimelineTrack name="Existing"><Sequence from={10} durationInFrames={50} trimBefore={5} /></TimelineTrack>;`;+ const {output} = await splitJsxSequence({+ input,+ nodePath: lineContainingToNodePath(input, '<Sequence'),+ sequenceKeys: sequenceTimingKeys,+ splitFrame: 30,+ videoConfigValues: null,+ });+ expect(output.match(/<TimelineTrack /g)).toHaveLength(1);+ expect(output).not.toContain('<Track');expect(output).toContain('<Sequence from={10} durationInFrames={20} trimBefore={5} />',@@ -244,9 +254,7 @@ export const Comp = () => {videoConfigValues: null,});- expect(output).toStartWith(- 'const deliberatelyUnformatted = {value : true}\n',- );+ expect(output).toContain('const deliberatelyUnformatted = {value : true}\n');expect(output).toContain('<Sequence name="clip" from={0} durationInFrames={30}>\n',);@@ -257,7 +265,7 @@ export const Comp = () => {expect(output).toEndWith(' )\n}\n');});-test('splitJsxSequence formats a split component root as a fragment', async () => {+test('splitJsxSequence formats a split component root as a named track', async () => {const input = `export const Comp = () => <Sequence from={0} durationInFrames={50}><span>Hi</span></Sequence>;const keep = { value : true }@@ -270,14 +278,15 @@ const keep = { value : true }videoConfigValues: null,});- expect(output).toBe(`export const Comp = () => <>+ expect(output).toBe(`import { Track } from "remotion"+export const Comp = () => <Track name="Sequence"><Sequence from={0} durationInFrames={30}><span>Hi</span></Sequence><Sequence from={30} durationInFrames={20} trimBefore={30}><span>Hi</span></Sequence>-</>;+</Track>;const keep = { value : true }`);@@ -289,6 +298,7 @@ test('splitJsxSequence splits a video with a negative from', async () => {100,);+ expect(output).toContain('<Track name="video.mov">');expect(output).toContain('from={-2644}');expect(output).toContain('durationInFrames={2744}');expect(output).toContain('trimBefore={272}');diff --git a/packages/studio-server/src/test/split-sequences.test.ts b/packages/studio-server/src/test/split-sequences.test.tsindex 673d112cb7..cf0565f529 100644--- a/packages/studio-server/src/test/split-sequences.test.ts+++ b/packages/studio-server/src/test/split-sequences.test.ts@@ -105,6 +105,8 @@ test('splitSequencesHandler writes success and failure responses', async () => {);expect(success.success).toBe(true);+ expect(readFileSync(entryPoint, 'utf-8')).toContain('<Track name="one">');+ expect(readFileSync(entryPoint, 'utf-8')).toContain('<Track name="two">');expect(readFileSync(entryPoint, 'utf-8')).toContain('<AbsoluteFill name="one" from={30} durationInFrames={20} trimBefore={30} />',);@@ -131,7 +133,7 @@ test('splitSequencesHandler writes success and failure responses', async () => {JSON.stringify(remapping.newNodePath) ===JSON.stringify(originalSolidPath),),- ).toMatchObject({oldJsxName: null, newJsxName: 'AbsoluteFill'});+ ).toMatchObject({oldJsxName: null, newJsxName: 'Track'});expect(getUndoStack().length).toBe(1);const undo = popUndo();@@ -147,7 +149,7 @@ test('splitSequencesHandler writes success and failure responses', async () => {JSON.stringify(remapping.oldNodePath) ===JSON.stringify(originalSolidPath) && remapping.newNodePath === null,),- ).toMatchObject({oldJsxName: 'AbsoluteFill', newJsxName: null});+ ).toMatchObject({oldJsxName: 'Track', newJsxName: null});const failure = await splitSequencesHandler(getHandlerOptions({