Skip to content

🎥 Make videos programmatically with React

@remotion/studio: Add multi-clip splitting

JonnyBurger9e13f199c234
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index e3d732fa91..cccb54d14f 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -27,7 +27,7 @@ import {
reorderSequence as reorderSequenceCodemod,
resolveCompositionComponentWithFile,
simpleDiff,
- splitJsxSequence as splitJsxSequenceCodemod,
+ splitJsxSequences as splitJsxSequencesCodemod,
splitVideoFromAudio as splitVideoFromAudioCodemod,
updateDefaultProps as updateDefaultPropsCodemod,
updateEffectProps as updateEffectPropsCodemod,
@@ -1368,37 +1368,63 @@ export const createBrowserStudioOperations = ({
};
const splitJsxSequence: BrowserStudioOperations['splitJsxSequence'] = async ({
- fileName,
- nodePath,
- sequenceKeys,
- splitFrame,
+ sequences,
}) => {
try {
+ if (sequences.length === 0) {
+ throw new Error('No JSX sequences were specified for splitting');
+ }
+
const project = getProject();
- const absolutePath = findProjectFile({
- filePath: fileName,
- project,
- });
- const result = await splitJsxSequenceCodemod({
- input: project.files[absolutePath],
- nodePath,
- sequenceKeys,
- splitFrame,
- });
+ const sequencesByFile = new Map<
+ string,
+ Array<{
+ nodePath: (typeof sequences)[number]['nodePath'];
+ sequenceKeys: string[];
+ splitFrame: number;
+ }>
+ >();
+ for (const sequence of sequences) {
+ const fileName = findProjectFile({
+ filePath: sequence.fileName,
+ project,
+ });
+ const fileSequences = sequencesByFile.get(fileName) ?? [];
+ fileSequences.push({
+ nodePath: sequence.nodePath,
+ sequenceKeys: sequence.sequenceKeys,
+ splitFrame: sequence.splitFrame,
+ });
+ sequencesByFile.set(fileName, fileSequences);
+ }
+
+ const updates = await Promise.all(
+ [...sequencesByFile].map(async ([fileName, splits]) => ({
+ fileName,
+ result: await splitJsxSequencesCodemod({
+ input: project.files[fileName],
+ splits,
+ }),
+ })),
+ );
+ const nextProject = {
+ ...project,
+ files: {
+ ...project.files,
+ ...Object.fromEntries(
+ updates.map(({fileName, result}) => [fileName, result.output]),
+ ),
+ },
+ };
const nodePathMutation = controller.applyMutation({
undoRedoNavigation: null,
timelineSelection: null,
- fileName: absolutePath,
- mutate: () => ({
- ...project,
- files: {...project.files, [absolutePath]: result.output},
- }),
- nodePathMutationFiles: [
- {
- absolutePath,
- remappings: result.nodePathRemappings,
- },
- ],
+ fileName: updates.map(({fileName}) => fileName).join(', '),
+ mutate: () => nextProject,
+ nodePathMutationFiles: updates.map(({fileName, result}) => ({
+ absolutePath: fileName,
+ remappings: result.nodePathRemappings,
+ })),
});
if (nodePathMutation === null) {
throw new Error('Could not split JSX sequence');
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 62de85b0d0..20dda6bf17 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -874,10 +874,14 @@ registerRoot(Root);`,
}
const failure = await operations.splitJsxSequence({
- fileName: 'src/Composition.tsx',
- nodePath: subscription.nodePath.nodePath,
- sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
- splitFrame: 10,
+ sequences: [
+ {
+ fileName: 'src/Composition.tsx',
+ nodePath: subscription.nodePath.nodePath,
+ sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
+ splitFrame: 10,
+ },
+ ],
});
expect(failure).toMatchObject({
success: false,
@@ -887,10 +891,14 @@ registerRoot(Root);`,
expect(currentProject.files[fileName]).toBe(initialContents);
const splitResult = await operations.splitJsxSequence({
- fileName: 'src/Composition.tsx',
- nodePath: subscription.nodePath.nodePath,
- sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
- splitFrame: 15,
+ sequences: [
+ {
+ fileName: 'src/Composition.tsx',
+ nodePath: subscription.nodePath.nodePath,
+ sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
+ splitFrame: 15,
+ },
+ ],
});
if (!splitResult.success) {
throw new Error(splitResult.reason);
diff --git a/packages/docs/docs/studio/shortcuts.mdx b/packages/docs/docs/studio/shortcuts.mdx
index 9eaa9748ac..16f347b243 100644
--- a/packages/docs/docs/studio/shortcuts.mdx
+++ b/packages/docs/docs/studio/shortcuts.mdx
@@ -10,50 +10,51 @@ You can also press <kbd>?</kbd> to open this tab.
## Available actions
-| Action ID | Default | Action |
-| ------------------------------- | ------------------------------------------ | -------------------------------------------------------------- |
-| `playPause` | `Space` | Play or pause |
-| `toggleMute` | `M` | Mute or unmute preview audio |
-| `toggleLoop` | `Shift+L` | Enable or disable looping |
-| `jumpToBeginning` | `A` | Jump to the beginning |
-| `jumpToEnd` | `E` | Jump to the end |
-| `reversePlayback` | `J` | Play in reverse |
-| `pausePlayback` | `K` | Pause playback |
-| `playForward` | `L` | Play forward; press repeatedly to increase speed |
-| `goToFrame` | `G` | Open the frame input |
-| `pauseAndReturnToPlaybackStart` | `Enter` | Pause and return to where playback started |
-| `toggleLeftSidebar` | `Cmd/Ctrl+B` | Toggle the left sidebar |
-| `toggleRightSidebar` | `Cmd/Ctrl+J` | Toggle the right sidebar |
-| `toggleBothSidebars` | `Cmd/Ctrl+G` | Toggle both sidebars |
-| `enterFullscreen` | `F` | Enter fullscreen |
-| `toggleOutlines` | `Shift+O` | Show or hide outlines |
-| `toggleRulersAndGuides` | `Shift+R` | Show or hide rulers and guides |
-| `toggleSnapping` | `Shift+M` | Enable or disable snapping |
-| `previousComposition` | `PageUp` | Select the previous composition |
-| `nextComposition` | `PageDown` | Select the next composition |
-| `showKeyboardShortcuts` | `?` | Open the Shortcuts settings |
-| `quickSwitcher` | `Cmd/Ctrl+K` | Open the Quick Switcher |
-| `render` | `R` | Open the Render dialog unless a sequence property is selected |
-| `toggleCheckerboard` | `T` | Toggle the checkerboard unless a sequence property is selected |
-| `setInPoint` | `I` | Set the playback In Point |
-| `setOutPoint` | `O` | Set the playback Out Point |
-| `clearInOutPoints` | `X` | Clear the playback In and Out Points |
-| `zoomIn` | `+` | Zoom into the preview |
-| `zoomOut` | `-` | Zoom out of the preview |
-| `resetZoom` | `0` | Reset the preview zoom |
-| `undo` | `Cmd/Ctrl+Z` | Undo the last props edit |
-| `redo` | `Cmd/Ctrl+Shift+Z`; `Ctrl+Y` outside macOS | Redo the last props edit |
-| `selectAllSequenceRows` | `Cmd/Ctrl+A` | Select all sequence rows |
-| `selectTranslateProp` | `P` | Select the `style.translate` property |
-| `selectOpacityProp` | `T` | Select the `style.opacity` property |
-| `selectRotateProp` | `R` | Select the `style.rotate` property |
-| `selectScaleProp` | `S` | Select the `style.scale` property |
-| `duplicateSequences` | `Cmd/Ctrl+D` | Duplicate selected sequences |
-| `copyEffectsAndValues` | `Cmd/Ctrl+C` | Copy selected effects or property values |
-| `cutEffects` | `Cmd/Ctrl+X` | Cut selected effects |
-| `deleteSelection` | `Backspace` or `Delete` | Delete or reset the selection |
-| `askAI` | `Cmd/Ctrl+I` | Open Ask AI when it is enabled |
-| `pickColor` | `Shift+C` | Open the color picker <AvailableFrom v="4.0.525" inline /> |
+| Action ID | Default | Action |
+| ------------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------- |
+| `playPause` | `Space` | Play or pause |
+| `toggleMute` | `M` | Mute or unmute preview audio |
+| `toggleLoop` | `Shift+L` | Enable or disable looping |
+| `jumpToBeginning` | `A` | Jump to the beginning |
+| `jumpToEnd` | `E` | Jump to the end |
+| `reversePlayback` | `J` | Play in reverse |
+| `pausePlayback` | `K` | Pause playback |
+| `playForward` | `L` | Play forward; press repeatedly to increase speed |
+| `goToFrame` | `G` | Open the frame input |
+| `pauseAndReturnToPlaybackStart` | `Enter` | Pause and return to where playback started |
+| `toggleLeftSidebar` | `Cmd/Ctrl+B` | Toggle the left sidebar |
+| `toggleRightSidebar` | `Cmd/Ctrl+J` | Toggle the right sidebar |
+| `toggleBothSidebars` | `Cmd/Ctrl+G` | Toggle both sidebars |
+| `enterFullscreen` | `F` | Enter fullscreen |
+| `toggleOutlines` | `Shift+O` | Show or hide outlines |
+| `toggleRulersAndGuides` | `Shift+R` | Show or hide rulers and guides |
+| `toggleSnapping` | `Shift+M` | Enable or disable snapping |
+| `previousComposition` | `PageUp` | Select the previous composition |
+| `nextComposition` | `PageDown` | Select the next composition |
+| `showKeyboardShortcuts` | `?` | Open the Shortcuts settings |
+| `quickSwitcher` | `Cmd/Ctrl+K` | Open the Quick Switcher |
+| `render` | `R` | Open the Render dialog unless a sequence property is selected |
+| `toggleCheckerboard` | `T` | Toggle the checkerboard unless a sequence property is selected |
+| `setInPoint` | `I` | Set the playback In Point |
+| `setOutPoint` | `O` | Set the playback Out Point |
+| `clearInOutPoints` | `X` | Clear the playback In and Out Points |
+| `zoomIn` | `+` | Zoom into the preview |
+| `zoomOut` | `-` | Zoom out of the preview |
+| `resetZoom` | `0` | Reset the preview zoom |
+| `undo` | `Cmd/Ctrl+Z` | Undo the last props edit |
+| `redo` | `Cmd/Ctrl+Shift+Z`; `Ctrl+Y` outside macOS | Redo the last props edit |
+| `selectAllSequenceRows` | `Cmd/Ctrl+A` | Select all sequence rows |
+| `selectTranslateProp` | `P` | Select the `style.translate` property |
+| `selectOpacityProp` | `T` | Select the `style.opacity` property |
+| `selectRotateProp` | `R` | Select the `style.rotate` property |
+| `selectScaleProp` | `S` | Select the `style.scale` property |
+| `duplicateSequences` | `Cmd/Ctrl+D` | Duplicate selected sequences |
+| `splitSequences` | `Cmd/Ctrl+Shift+D` | Split eligible selected sequences at the playhead <AvailableFrom v="4.0.527" inline /> |
+| `copyEffectsAndValues` | `Cmd/Ctrl+C` | Copy selected effects or property values |
+| `cutEffects` | `Cmd/Ctrl+X` | Cut selected effects |
+| `deleteSelection` | `Backspace` or `Delete` | Delete or reset the selection |
+| `askAI` | `Cmd/Ctrl+I` | Open Ask AI when it is enabled |
+| `pickColor` | `Shift+C` | Open the color picker <AvailableFrom v="4.0.525" inline /> |
## Fixed shortcuts
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index c64e6376a7..7b6602d3f1 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -83,7 +83,7 @@ export {
export {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';
export {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
export {simpleDiff} from './simple-diff';
-export {splitJsxSequence} from './split-jsx-sequence';
+export {splitJsxSequence, splitJsxSequences} from './split-jsx-sequence';
export {splitVideoFromAudio} from './split-video-from-audio';
export {insertBasicCaptions} from './insert-basic-captions';
export {
diff --git a/packages/studio-codemods/src/split-jsx-sequence.ts b/packages/studio-codemods/src/split-jsx-sequence.ts
index e213dc0f54..8a4fa15fc8 100644
--- a/packages/studio-codemods/src/split-jsx-sequence.ts
+++ b/packages/studio-codemods/src/split-jsx-sequence.ts
@@ -29,6 +29,7 @@ import {
import {printInsertedJsx} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
import {parseAst, parseAstForReadOnly} from './sequence-props/parse-ast';
+import {applySourceEdits} from './source-edits';
import {
getEndOfLine,
getLineIndent,
@@ -383,118 +384,136 @@ const getSplitSourceEdit = ({
return {end, replacement, start};
};
-export const splitJsxSequence = ({
+export type SplitJsxSequenceItem = {
+ nodePath: SequenceNodePath;
+ sequenceKeys: string[];
+ splitFrame: number;
+};
+
+export const splitJsxSequences = ({
input,
- nodePath,
- sequenceKeys,
- splitFrame,
+ splits,
prettierConfigOverride,
}: {
input: string;
- nodePath: SequenceNodePath;
- sequenceKeys: string[];
- splitFrame: number;
+ splits: SplitJsxSequenceItem[];
prettierConfigOverride?: Record<string, unknown> | null;
}): Promise<{
output: string;
- nodeLabel: string;
- logLine: number;
+ nodeLabels: string[];
+ logLines: number[];
nodePathRemappings: SequenceNodePathRemapping[];
}> => {
- if (!Number.isInteger(splitFrame)) {
- throw new Error('Split frame must be an integer');
+ if (splits.length === 0) {
+ throw new Error('No JSX sequences were specified for splitting');
}
const ast = parseAst(input);
const capturedNodePaths = captureJsxNodePaths(ast);
- const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
- if (!jsxPath) {
- throw new Error(
- 'Could not find a JSX sequence at the specified location to split',
- );
- }
-
- const jsxElement = jsxPath.node as JSXElement;
- const tagName = getSplittableSequenceTagName(jsxElement);
- if (!hasSequenceTimingTraits(sequenceKeys)) {
- throw new Error(`<${tagName}> cannot be split`);
- }
-
- const timing = readSequenceTiming(jsxElement);
- const finiteEnd =
- timing.durationInFrames === Infinity
- ? Infinity
- : timing.from + timing.durationInFrames;
-
- if (splitFrame <= timing.from) {
- throw new Error('Cannot split at or before the sequence start');
- }
+ const targets = splits.map(({nodePath, sequenceKeys, splitFrame}) => {
+ if (!Number.isInteger(splitFrame)) {
+ throw new Error('Split frame must be an integer');
+ }
- if (splitFrame >= finiteEnd) {
- throw new Error('Cannot split at or after the sequence end');
- }
+ const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
+ if (!jsxPath) {
+ throw new Error(
+ 'Could not find a JSX sequence at the specified location to split',
+ );
+ }
- const right = cloneJsxElement(jsxElement);
- // Match Studio's numeric dragger precision while retaining fractional frames.
- const leftDuration = normalizeComputedTiming(splitFrame - timing.from);
- const rightDuration =
- timing.durationInFrames === Infinity
- ? Infinity
- : normalizeComputedTiming(finiteEnd - splitFrame);
- const rightTrimBefore = normalizeComputedTiming(
- timing.trimBefore + leftDuration,
- );
+ const jsxElement = jsxPath.node as JSXElement;
+ const tagName = getSplittableSequenceTagName(jsxElement);
+ if (!hasSequenceTimingTraits(sequenceKeys)) {
+ throw new Error(`<${tagName}> cannot be split`);
+ }
- setNumericAttribute({
- element: jsxElement,
- name: 'durationInFrames',
- value: leftDuration,
- omitIfMissing: false,
- });
- setNumericAttribute({
- element: right,
- name: 'from',
- value: splitFrame,
- omitIfMissing: false,
- });
- setNumericAttribute({
- element: right,
- name: 'durationInFrames',
- value: rightDuration === Infinity ? null : rightDuration,
- omitIfMissing: !timing.hasDurationInFrames,
- });
- setNumericAttribute({
- element: right,
- name: 'trimBefore',
- value: rightTrimBefore === 0 ? null : rightTrimBefore,
- omitIfMissing: !timing.hasTrimBefore && rightTrimBefore === 0,
- });
- orderTimingAttributes(jsxElement);
- orderTimingAttributes(right);
+ const timing = readSequenceTiming(jsxElement);
+ const finiteEnd =
+ timing.durationInFrames === Infinity
+ ? Infinity
+ : timing.from + timing.durationInFrames;
- const {parentPath} = jsxPath;
- if (!parentPath) {
- throw new Error('Cannot split JSX sequence with no parent');
- }
+ if (splitFrame <= timing.from) {
+ throw new Error('Cannot split at or before the sequence start');
+ }
- const isJsxChild =
- namedTypes.JSXElement.check(parentPath.node) ||
- namedTypes.JSXFragment.check(parentPath.node);
- if (!insertAfter(parentPath.node, jsxElement, right)) {
- jsxPath.replace(makeFragment(jsxElement, right));
- }
+ if (splitFrame >= finiteEnd) {
+ throw new Error('Cannot split at or after the sequence end');
+ }
- const sourceEdit = getSplitSourceEdit({
- input,
- left: jsxElement,
- prettierConfigOverride: prettierConfigOverride ?? null,
- right,
- wrapInFragment: !isJsxChild,
+ return {finiteEnd, jsxElement, jsxPath, splitFrame, timing};
});
- const output =
- input.slice(0, sourceEdit.start) +
- sourceEdit.replacement +
- input.slice(sourceEdit.end);
+ const nodeLabels: string[] = [];
+ const logLines: number[] = [];
+ const sourceEdits = targets.map(
+ ({finiteEnd, jsxElement, jsxPath, splitFrame, timing}) => {
+ const right = cloneJsxElement(jsxElement);
+ // Match Studio's numeric dragger precision while retaining fractional frames.
+ const leftDuration = normalizeComputedTiming(splitFrame - timing.from);
+ const rightDuration =
+ timing.durationInFrames === Infinity
+ ? Infinity
+ : normalizeComputedTiming(finiteEnd - splitFrame);
+ const rightTrimBefore = normalizeComputedTiming(
+ timing.trimBefore + leftDuration,
+ );
+
+ setNumericAttribute({
+ element: jsxElement,
+ name: 'durationInFrames',
+ value: leftDuration,
+ omitIfMissing: false,
+ });
+ setNumericAttribute({
+ element: right,
+ name: 'from',
+ value: splitFrame,
+ omitIfMissing: false,
+ });
+ setNumericAttribute({
+ element: right,
+ name: 'durationInFrames',
+ value: rightDuration === Infinity ? null : rightDuration,
+ omitIfMissing: !timing.hasDurationInFrames,
+ });
+ setNumericAttribute({
+ element: right,
+ name: 'trimBefore',
+ value: rightTrimBefore === 0 ? null : rightTrimBefore,
+ omitIfMissing: !timing.hasTrimBefore && rightTrimBefore === 0,
+ });
+ orderTimingAttributes(jsxElement);
+ orderTimingAttributes(right);
+
+ const {parentPath} = jsxPath;
+ if (!parentPath) {
+ throw new Error('Cannot split JSX sequence with no parent');
+ }
+
+ const isJsxChild =
+ namedTypes.JSXElement.check(parentPath.node) ||
+ namedTypes.JSXFragment.check(parentPath.node);
+ if (!insertAfter(parentPath.node, jsxElement, right)) {
+ jsxPath.replace(makeFragment(jsxElement, right));
+ }
+
+ nodeLabels.push(getJsxElementTagLabel(jsxElement));
+ logLines.push(
+ jsxElement.openingElement.loc?.start.line ??
+ jsxElement.loc?.start.line ??
+ 1,
+ );
+ return getSplitSourceEdit({
+ input,
+ left: jsxElement,
+ prettierConfigOverride: prettierConfigOverride ?? null,
+ right,
+ wrapInFragment: !isJsxChild,
+ });
+ },
+ );
+ const output = applySourceEdits({edits: sourceEdits, input});
const {nodePathRemappings} = getNodePathRemappings({
ast,
captured: capturedNodePaths,
@@ -503,11 +522,41 @@ export const splitJsxSequence = ({
return Promise.resolve({
output,
- nodeLabel: getJsxElementTagLabel(jsxElement),
- logLine:
- jsxElement.openingElement.loc?.start.line ??
- jsxElement.loc?.start.line ??
- 1,
+ nodeLabels,
+ logLines,
nodePathRemappings,
});
};
+
+export const splitJsxSequence = async ({
+ input,
+ nodePath,
+ sequenceKeys,
+ splitFrame,
+ prettierConfigOverride,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+ sequenceKeys: string[];
+ splitFrame: number;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}): Promise<{
+ output: string;
+ nodeLabel: string;
+ logLine: number;
+ nodePathRemappings: SequenceNodePathRemapping[];
+}> => {
+ const {output, nodeLabels, logLines, nodePathRemappings} =
+ await splitJsxSequences({
+ input,
+ prettierConfigOverride,
+ splits: [{nodePath, sequenceKeys, splitFrame}],
+ });
+
+ return {
+ output,
+ nodeLabel: nodeLabels[0],
+ logLine: logLines[0],
+ nodePathRemappings,
+ };
+};
diff --git a/packages/studio-codemods/src/test/split-jsx-sequence.test.ts b/packages/studio-codemods/src/test/split-jsx-sequence.test.ts
index 54ed9c0a9e..f778ec527f 100644
--- a/packages/studio-codemods/src/test/split-jsx-sequence.test.ts
+++ b/packages/studio-codemods/src/test/split-jsx-sequence.test.ts
@@ -2,7 +2,7 @@ import {expect, test} from 'bun:test';
import * as recast from 'recast';
import {getNodePathForRecastPath} from '../sequence-props';
import {parseAst} from '../sequence-props/parse-ast';
-import {splitJsxSequence} from '../split-jsx-sequence';
+import {splitJsxSequence, splitJsxSequences} from '../split-jsx-sequence';
test('splits fractional timing without persisting arithmetic noise', async () => {
const input =
@@ -26,3 +26,52 @@ test('splits fractional timing without persisting arithmetic noise', async () =>
expect(output).toContain('durationInFrames={0.3}');
expect(output).toContain('trimBefore={1.1}');
});
+
+test('splits multiple sibling sequences from the same source snapshot', async () => {
+ const input = `export const Comp = () => (
+ <>
+ <Sequence name="video" from={0} durationInFrames={50} />
+ <Audio name="audio" from={10} durationInFrames={50} trimBefore={5} />
+ </>
+);`;
+ const ast = parseAst(input);
+ const nodePaths: Parameters<
+ typeof splitJsxSequences
+ >[0]['splits'][number]['nodePath'][] = [];
+ recast.types.visit(ast, {
+ visitJSXOpeningElement(path) {
+ if (
+ path.node.name.type === 'JSXIdentifier' &&
+ (path.node.name.name === 'Sequence' || path.node.name.name === 'Audio')
+ ) {
+ nodePaths.push(getNodePathForRecastPath(path, ast));
+ }
+
+ return this.traverse(path);
+ },
+ });
+ const {output, nodePathRemappings} = await splitJsxSequences({
+ input,
+ splits: nodePaths.map((nodePath) => ({
+ nodePath,
+ sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
+ splitFrame: 30,
+ })),
+ });
+
+ expect(output).toContain(
+ '<Sequence name="video" from={0} durationInFrames={30} />',
+ );
+ expect(output).toContain(
+ '<Sequence name="video" from={30} durationInFrames={20} trimBefore={30} />',
+ );
+ expect(output).toContain(
+ '<Audio name="audio" from={10} durationInFrames={20} trimBefore={5} />',
+ );
+ expect(output).toContain(
+ '<Audio name="audio" from={30} durationInFrames={30} trimBefore={25} />',
+ );
+ expect(
+ nodePathRemappings.filter((remapping) => remapping.oldNodePath === null),
+ ).toHaveLength(2);
+});
diff --git a/packages/studio-server/src/codemods/split-jsx-sequence.ts b/packages/studio-server/src/codemods/split-jsx-sequence.ts
index e283f904a6..6f6425a845 100644
--- a/packages/studio-server/src/codemods/split-jsx-sequence.ts
+++ b/packages/studio-server/src/codemods/split-jsx-sequence.ts
@@ -1,4 +1,7 @@
-import {splitJsxSequence as splitJsxSequenceCodemod} from '@remotion/studio-codemods';
+import {
+ splitJsxSequence as splitJsxSequenceCodemod,
+ splitJsxSequences as splitJsxSequencesCodemod,
+} from '@remotion/studio-codemods';
import type {SequenceNodePath} from 'remotion';
export const splitJsxSequence = ({
@@ -21,3 +24,22 @@ export const splitJsxSequence = ({
splitFrame,
prettierConfigOverride,
});
+
+export const splitJsxSequences = ({
+ input,
+ splits,
+ prettierConfigOverride,
+}: {
+ input: string;
+ splits: Array<{
+ nodePath: SequenceNodePath;
+ sequenceKeys: string[];
+ splitFrame: number;
+ }>;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}) =>
+ splitJsxSequencesCodemod({
+ input,
+ splits,
+ prettierConfigOverride,
+ });
diff --git a/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts b/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts
index 1bf1667dcf..3561471aaf 100644
--- a/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts
+++ b/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts
@@ -4,7 +4,7 @@ import type {
SplitJsxSequenceRequest,
SplitJsxSequenceResponse,
} from '@remotion/studio-shared';
-import {splitJsxSequence} from '../../codemods/split-jsx-sequence';
+import {splitJsxSequences} from '../../codemods/split-jsx-sequence';
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
@@ -12,7 +12,7 @@ import {formatLogFileLocation} from '../format-log-file-location';
import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
printUndoHint,
- pushToUndoStack,
+ pushTransactionToUndoStack,
suppressUndoStackInvalidation,
} from '../undo-stack';
import {
@@ -23,80 +23,115 @@ import {
export const splitJsxSequenceHandler: ApiHandler<
SplitJsxSequenceRequest,
SplitJsxSequenceResponse
-> = ({
- input: {fileName, nodePath, sequenceKeys, splitFrame},
- remotionRoot,
- logLevel,
-}) =>
+> = ({input: {sequences}, remotionRoot, logLevel}) =>
withSourceFileWriteQueue(async () => {
try {
+ if (sequences.length === 0) {
+ throw new Error('No JSX sequences were specified for splitting');
+ }
+
RenderInternals.Log.trace(
{indent: false, logLevel},
- `[split-jsx-sequence] Received request for fileName="${fileName}" at frame ${splitFrame}`,
+ `[split-jsx-sequence] Received request to split ${sequences.length} JSX sequence${sequences.length === 1 ? '' : 's'}`,
);
- const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({
- remotionRoot,
- fileName,
- action: 'modify',
- });
+ const sequencesByFileName = new Map<string, typeof sequences>();
+ for (const sequence of sequences) {
+ const fileSequences = sequencesByFileName.get(sequence.fileName) ?? [];
+ fileSequences.push(sequence);
+ sequencesByFileName.set(sequence.fileName, fileSequences);
+ }
- const fileContents = readFileSync(absolutePath, 'utf-8');
+ const updates = await Promise.all(
+ [...sequencesByFileName].map(async ([fileName, fileSequences]) => {
+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({
+ remotionRoot,
+ fileName,
+ action: 'modify',
+ });
+ const fileContents = readFileSync(absolutePath, 'utf-8');
+ const {output, nodeLabels, logLines, nodePathRemappings} =
+ await splitJsxSequences({
+ input: fileContents,
+ splits: fileSequences.map(
+ ({nodePath, sequenceKeys, splitFrame}) => ({
+ nodePath,
+ sequenceKeys,
+ splitFrame,
+ }),
+ ),
+ });
- const {output, nodeLabel, logLine, nodePathRemappings} =
- await splitJsxSequence({
- input: fileContents,
- nodePath,
- sequenceKeys,
- splitFrame,
- });
- const nodePathMutation = broadcastSequenceNodePathMutation(
- [
- {
+ return {
absolutePath,
- remappings: nodePathRemappings,
- },
- ],
+ fileContents,
+ fileRelativeToRoot,
+ logLine: Math.min(...logLines),
+ nodeLabels,
+ nodePathRemappings,
+ output,
+ };
+ }),
+ );
+ const nodePathMutation = broadcastSequenceNodePathMutation(
+ updates.map((update) => ({
+ absolutePath: update.absolutePath,
+ remappings: update.nodePathRemappings,
+ })),
null,
);
+ const splitDescription =
+ sequences.length === 1
+ ? updates[0].nodeLabels[0]
+ : `${sequences.length} JSX sequences`;
- pushToUndoStack({
- filePath: absolutePath,
- oldContents: fileContents,
- newContents: null,
+ pushTransactionToUndoStack({
+ snapshots: updates.map((update) => ({
+ filePath: update.absolutePath,
+ oldContents: update.fileContents,
+ newContents: null,
+ logLine: update.logLine,
+ nodePathRemappings: update.nodePathRemappings,
+ })),
logLevel,
remotionRoot,
- logLine,
description: {
- undoMessage: `↩️ Split of ${nodeLabel}`,
- redoMessage: `↪️ Split of ${nodeLabel}`,
+ undoMessage: `↩️ Split of ${splitDescription}`,
+ redoMessage: `↪️ Split of ${splitDescription}`,
},
entryType: 'split-jsx-sequence',
suppressHmrOnFileRestore: false,
- nodePathRemappings,
- });
- suppressUndoStackInvalidation(absolutePath);
- writeFileAndNotifyFileWatchers({
- file: absolutePath,
- content: output,
- originatorClientId: undefined,
- metadata: {skipSequencePropsUpdate: true},
+ undoRedoNavigation: null,
});
- const locationLabel = formatLogFileLocation({
- remotionRoot,
- absolutePath,
- line: logLine,
- });
- RenderInternals.Log.info(
- {indent: false, logLevel},
- `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(
- `${locationLabel}`,
- )} Split ${nodeLabel}`,
- );
- RenderInternals.Log.verbose(
- {indent: false, logLevel},
- `[split-jsx-sequence] Wrote ${fileRelativeToRoot}`,
- );
+ for (const update of updates) {
+ suppressUndoStackInvalidation(update.absolutePath);
+ writeFileAndNotifyFileWatchers({
+ file: update.absolutePath,
+ content: update.output,
+ originatorClientId: undefined,
+ metadata: {skipSequencePropsUpdate: true},
+ });
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: update.absolutePath,
+ line: update.logLine,
+ });
+ const fileDescription =
+ update.nodeLabels.length === 1
+ ? update.nodeLabels[0]
+ : `${update.nodeLabels.length} JSX sequences`;
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(
+ `${locationLabel}`,
+ )} Split ${fileDescription}`,
+ );
+ RenderInternals.Log.verbose(
+ {indent: false, logLevel},
+ `[split-jsx-sequence] Wrote ${update.fileRelativeToRoot}`,
+ );
+ }
printUndoHint(logLevel);
diff --git a/packages/studio-server/src/test/jsx-node-path-mutation-routes.test.ts b/packages/studio-server/src/test/jsx-node-path-mutation-routes.test.ts
index 7e33f76299..0b2d81ae17 100644
--- a/packages/studio-server/src/test/jsx-node-path-mutation-routes.test.ts
+++ b/packages/studio-server/src/test/jsx-node-path-mutation-routes.test.ts
@@ -190,10 +190,14 @@ test('JSX structure routes broadcast and return node path mutations before writi
const splitResponse = await splitJsxSequenceHandler({
...handlerContext,
input: {
- fileName,
- nodePath: lineContainingToNodePath(before, 'name="c"'),
- sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
- splitFrame: 30,
+ sequences: [
+ {
+ fileName,
+ nodePath: lineContainingToNodePath(before, 'name="c"'),
+ sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
+ splitFrame: 30,
+ },
+ ],
},
});
if (!splitResponse.success) {
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 9b3428719c..308bfb8a24 100644
--- a/packages/studio-server/src/test/split-jsx-sequence.test.ts
+++ b/packages/studio-server/src/test/split-jsx-sequence.test.ts
@@ -311,16 +311,28 @@ test('splitJsxSequenceHandler writes success and failure responses', async () =>
try {
clearUndoStack();
const entryPoint = path.join(remotionRoot, 'Root.tsx');
- const input = wrap('<AbsoluteFill from={0} durationInFrames={50} />');
+ const input = wrap(
+ '<AbsoluteFill name="one" from={0} durationInFrames={50} />\n\t\t\t<AbsoluteFill name="two" from={10} durationInFrames={50} />',
+ );
writeFileSync(entryPoint, input);
const success = await splitJsxSequenceHandler(
getHandlerOptions({
input: {
- fileName: entryPoint,
- nodePath: lineColumnToNodePath(input, sequenceLine),
- sequenceKeys: sequenceTimingKeys,
- splitFrame: 30,
+ sequences: [
+ {
+ fileName: entryPoint,
+ nodePath: lineContainingToNodePath(input, 'name="one"'),
+ sequenceKeys: sequenceTimingKeys,
+ splitFrame: 30,
+ },
+ {
+ fileName: entryPoint,
+ nodePath: lineContainingToNodePath(input, 'name="two"'),
+ sequenceKeys: sequenceTimingKeys,
+ splitFrame: 30,
+ },
+ ],
},
entryPoint,
remotionRoot,
@@ -329,17 +341,24 @@ test('splitJsxSequenceHandler writes success and failure responses', async () =>
expect(success.success).toBe(true);
expect(readFileSync(entryPoint, 'utf-8')).toContain(
- '<AbsoluteFill from={30} durationInFrames={20} trimBefore={30} />',
+ '<AbsoluteFill name="one" from={30} durationInFrames={20} trimBefore={30} />',
+ );
+ expect(readFileSync(entryPoint, 'utf-8')).toContain(
+ '<AbsoluteFill name="two" from={30} durationInFrames={30} trimBefore={20} />',
);
expect(getUndoStack().length).toBe(1);
const failure = await splitJsxSequenceHandler(
getHandlerOptions({
input: {
- fileName: entryPoint,
- nodePath: lineColumnToNodePath(input, sequenceLine),
- sequenceKeys: sequenceTimingKeys,
- splitFrame: 0,
+ sequences: [
+ {
+ fileName: entryPoint,
+ nodePath: lineContainingToNodePath(input, 'name="one"'),
+ sequenceKeys: sequenceTimingKeys,
+ splitFrame: 0,
+ },
+ ],
},
entryPoint,
remotionRoot,
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 9bc8322a30..356362ec26 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -884,13 +884,17 @@ export type DuplicateJsxNodeResponse =
stack: string;
};
-export type SplitJsxSequenceRequest = {
+export type SplitJsxSequenceRequestItem = {
fileName: string;
nodePath: SequenceNodePath;
sequenceKeys: string[];
splitFrame: number;
};
+export type SplitJsxSequenceRequest = {
+ sequences: SplitJsxSequenceRequestItem[];
+};
+
export type SplitJsxSequenceResponse =
| {
success: true;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 291bfae342..2fbdbd0659 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -133,6 +133,7 @@ export {
SaveSequencePropsResult,
SimpleDiff,
SplitJsxSequenceRequest,
+ SplitJsxSequenceRequestItem,
SplitJsxSequenceResponse,
SplitVideoFromAudioRequest,
SplitVideoFromAudioResponse,
diff --git a/packages/studio-shared/src/keyboard-shortcuts.ts b/packages/studio-shared/src/keyboard-shortcuts.ts
index 14ded616c7..9c66166139 100644
--- a/packages/studio-shared/src/keyboard-shortcuts.ts
+++ b/packages/studio-shared/src/keyboard-shortcuts.ts
@@ -36,6 +36,7 @@ export const studioKeyboardShortcutActions = [
'selectRotateProp',
'selectScaleProp',
'duplicateSequences',
+ 'splitSequences',
'copyEffectsAndValues',
'cutEffects',
'deleteSelection',
diff --git a/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx b/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx
index aa473932d4..8c930962bc 100644
--- a/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx
@@ -1,23 +1,35 @@
import {stringifySequenceExpandedRowKey} from '@remotion/studio-shared';
-import React, {useContext, useMemo, useSyncExternalStore} from 'react';
+import React, {
+ useCallback,
+ useContext,
+ useMemo,
+ useSyncExternalStore,
+} from 'react';
import {Internals} from 'remotion';
import {calculateTimeline} from '../../helpers/calculate-timeline';
import {LIGHT_TEXT} from '../../helpers/colors';
+import {isStudioInteractivityEnabled} from '../../helpers/interactivity-enabled';
import {
getFieldsToShow,
SCHEMA_FIELD_GROUPS,
} from '../../helpers/timeline-layout';
+import {ScissorsIcon} from '../../icons/scissors';
import {InspectorInfoHeader} from '../InspectorInfoHeader';
import {INSPECTOR_PANEL_HORIZONTAL_PADDING} from '../InspectorPanelLayout';
import {COMPACT_CONTROL_ROW_HEIGHT} from '../layout';
import {VERTICAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';
+import {splitSelectedTimelineItems} from '../Timeline/split-selected-timeline-item';
import {
INSPECTOR_TIMELINE_ROW_LAYOUT,
TimelineRowLayoutContext,
} from '../Timeline/TimelineRowLayoutContext';
import type {TimelineSelection} from '../Timeline/TimelineSelection';
import {CollapsibleInspectorSection} from './CollapsibleInspectorSection';
-import {InspectorMessage} from './common';
+import {
+ InspectorMessage,
+ InspectorQuickAction,
+ InspectorQuickActionsSection,
+} from './common';
import {
MultiSequenceField,
type MultiSequenceTarget,
@@ -36,6 +48,12 @@ const selectionCountStyle: React.CSSProperties = {
whiteSpace: 'nowrap',
};
+const actionIconStyle: React.CSSProperties = {
+ display: 'block',
+ height: 16,
+ width: 16,
+};
+
export const MultiSequenceInspector: React.FC<{
readonly selections: readonly Extract<
TimelineSelection,
@@ -44,6 +62,7 @@ export const MultiSequenceInspector: React.FC<{
readonly readOnlyStudio: boolean;
}> = ({selections, readOnlyStudio}) => {
const {sequences} = useContext(Internals.SequenceManager);
+ const timelinePosition = Internals.Timeline.useTimelinePosition();
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
);
@@ -134,6 +153,27 @@ export const MultiSequenceInspector: React.FC<{
),
);
}, [getDragOverrides, propStatuses, runtimeValues, targets]);
+ const canSplit = !readOnlyStudio && isStudioInteractivityEnabled();
+ const onSplit = useCallback(() => {
+ if (!canSplit) {
+ return;
+ }
+
+ splitSelectedTimelineItems({
+ selections,
+ sequences,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ propStatuses,
+ splitFrame: timelinePosition,
+ })?.catch(() => undefined);
+ }, [
+ canSplit,
+ overrideIdToNodePathMappings,
+ propStatuses,
+ selections,
+ sequences,
+ timelinePosition,
+ ]);
return (
<div style={scrollableContainer} className={VERTICAL_SCROLLBAR_CLASSNAME}>
@@ -143,6 +183,24 @@ export const MultiSequenceInspector: React.FC<{
</div>
</InspectorInfoHeader>
<div role="separator" style={sequenceHeaderDivider} />
+ <CollapsibleInspectorSection
+ collapsible
+ label="Actions"
+ sectionId="multi-sequence-actions"
+ >
+ <InspectorQuickActionsSection>
+ <InspectorQuickAction
+ disabled={!canSplit}
+ onClick={onSplit}
+ title={canSplit ? undefined : 'Studio is read-only'}
+ renderIcon={(color) => (
+ <ScissorsIcon style={actionIconStyle} color={color} />
+ )}
+ >
+ Split selected
+ </InspectorQuickAction>
+ </InspectorQuickActionsSection>
+ </CollapsibleInspectorSection>
{targets === null ? (
<InspectorMessage>Sequence controls unavailable</InspectorMessage>
) : fields.length === 0 ? (
diff --git a/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx
index d3f41f8397..bf11198393 100644
--- a/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx
+++ b/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx
@@ -6,10 +6,7 @@ import {useKeybinding} from '../../helpers/use-keybinding';
import {useConfirmationDialog} from '../ConfirmationDialog';
import {duplicateSelectedTimelineItems} from './duplicate-selected-timeline-item';
import {getCurrentFrame} from './imperative-state';
-import {
- shouldHandleTimelineSplitShortcut,
- splitSelectedTimelineItems,
-} from './split-selected-timeline-item';
+import {splitSelectedTimelineItems} from './split-selected-timeline-item';
import {
useCurrentTimelineSelectionStateAsRef,
useTimelineSelection,
@@ -69,12 +66,8 @@ export const TimelineDeleteKeybindings: React.FC = () => {
});
const split = keybindings.registerKeybinding({
event: 'keydown',
- key: 'd',
- callback: (event) => {
- if (!shouldHandleTimelineSplitShortcut(event)) {
- return;
- }
-
+ action: 'splitSequences',
+ callback: () => {
const {selectedItems} = currentSelection.current;
if (selectedItems.length === 0) {
return;
@@ -94,7 +87,6 @@ export const TimelineDeleteKeybindings: React.FC = () => {
splitPromise.catch(() => undefined);
},
- commandCtrlKey: true,
preventDefault: true,
triggerIfInputFieldFocused: false,
keepRegisteredWhenNotHighestContext: false,
diff --git a/packages/studio/src/components/Timeline/TimelineSequence.tsx b/packages/studio/src/components/Timeline/TimelineSequence.tsx
index bc6abcc7c0..271752f9b1 100644
--- a/packages/studio/src/components/Timeline/TimelineSequence.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequence.tsx
@@ -59,6 +59,7 @@ import {getTimelineMediaStartFrame} from './get-timeline-media-start-frame';
import {getTimelineSequenceVisibleLayout} from './get-timeline-sequence-visible-layout';
import {getCurrentFrame} from './imperative-state';
import {LoopedTimelineIndicator} from './LoopedTimelineIndicators';
+import {splitSelectedTimelineItems} from './split-selected-timeline-item';
import {getTimelineAssetLinkInfo} from './timeline-asset-link';
import {TimelineImageInfo} from './TimelineImageInfo';
import {
@@ -437,6 +438,9 @@ const TimelineSequenceInner: React.FC<{
const video = Internals.useVideo();
const {sequences} = useContext(Internals.SequenceManager);
+ const {overrideIdToNodePathMappings} = useContext(
+ Internals.OverrideIdsToNodePathsGettersContext,
+ );
const renderWindow = useContext(TimelineViewportContext);
const mediaDurationDragLimitsRegistry = useContext(
TimelineSequenceMediaDurationDragLimitsContext,
@@ -639,6 +643,26 @@ const TimelineSequenceInner: React.FC<{
() => undefined,
);
}, [confirm, previewInteractive, selectedSequenceNodePathInfos]);
+ const onSplitSelectedSequences = useCallback(() => {
+ if (!previewInteractive || selectedSequenceNodePathInfos === null) {
+ return;
+ }
+
+ splitSelectedTimelineItems({
+ selections: selectedItems,
+ sequences,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ propStatuses,
+ splitFrame: getCurrentFrame(),
+ })?.catch(() => undefined);
+ }, [
+ overrideIdToNodePathMappings,
+ previewInteractive,
+ propStatuses,
+ selectedItems,
+ selectedSequenceNodePathInfos,
+ sequences,
+ ]);
const onDeleteSequenceFromSource = useCallback(() => {
if (
!validatedLocation?.source ||
@@ -705,8 +729,10 @@ const TimelineSequenceInner: React.FC<{
return getMultiSequenceContextMenuItems({
deleteDisabled: !previewInteractive,
duplicateDisabled: !previewInteractive,
+ splitDisabled: !previewInteractive,
onDeleteSelectedSequences,
onDuplicateSelectedSequences,
+ onSplitSelectedSequences,
});
}
@@ -788,6 +814,7 @@ const TimelineSequenceInner: React.FC<{
onDisableSequenceInteractivity,
onDuplicateSequenceFromSource,
onDuplicateSelectedSequences,
+ onSplitSelectedSequences,
openInCodingAgent,
openInEditor,
originalLocation,
diff --git a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
index 42e771bcb8..d753bd8418 100644
--- a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
@@ -82,6 +82,7 @@ import {
import {getSequenceSplitMenuItem} from './get-sequence-split-menu-item';
import {getCurrentFrame} from './imperative-state';
import {saveSequenceProps} from './save-sequence-prop';
+import {splitSelectedTimelineItems} from './split-selected-timeline-item';
import {getTimelineAssetLinkInfo} from './timeline-asset-link';
import {timelineVerticalScroll} from './timeline-refs';
import {
@@ -314,6 +315,11 @@ const TimelineSequenceItemInner: React.FC<{
showProvisionalVisibilityToggle,
}) => {
const nodePath = nodePathInfo?.sequenceSubscriptionKey ?? null;
+ const {sequences} = useContext(Internals.SequenceManager);
+ const {overrideIdToNodePathMappings} = useContext(
+ Internals.OverrideIdsToNodePathsGettersContext,
+ );
+ const {propStatuses} = useContext(Internals.VisualModePropStatusesContext);
const {hovered, onPointerEnter, onPointerLeave} =
useTimelineSequenceHover(nodePathInfo);
const {previewServerState} = useContext(StudioServerConnectionCtx);
@@ -446,6 +452,26 @@ const TimelineSequenceItemInner: React.FC<{
() => undefined,
);
}, [confirm, previewInteractive, selectedSequenceNodePathInfos]);
+ const onSplitSelectedSequences = useCallback(() => {
+ if (!previewInteractive || selectedSequenceNodePathInfos === null) {
+ return;
+ }
+
+ splitSelectedTimelineItems({
+ selections: selectedItems,
+ sequences,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ propStatuses,
+ splitFrame: getCurrentFrame(),
+ })?.catch(() => undefined);
+ }, [
+ overrideIdToNodePathMappings,
+ previewInteractive,
+ propStatuses,
+ selectedItems,
+ selectedSequenceNodePathInfos,
+ sequences,
+ ]);
const onDeleteSequenceFromSource = useCallback(() => {
if (
@@ -1152,8 +1178,10 @@ const TimelineSequenceItemInner: React.FC<{
return getMultiSequenceContextMenuItems({
deleteDisabled: !previewInteractive,
duplicateDisabled: !previewInteractive,
+ splitDisabled: !previewInteractive,
onDeleteSelectedSequences,
onDuplicateSelectedSequences,
+ onSplitSelectedSequences,
});
}
@@ -1313,6 +1341,7 @@ const TimelineSequenceItemInner: React.FC<{
onDisableSequenceInteractivity,
onDuplicateSequenceFromSource,
onDuplicateSelectedSequences,
+ onSplitSelectedSequences,
onRenameSequence,
onSelect,
openInCodingAgent,
diff --git a/packages/studio/src/components/Timeline/get-sequence-context-menu-items.ts b/packages/studio/src/components/Timeline/get-sequence-context-menu-items.ts
index 5c3680aa2b..5fc96567b8 100644
--- a/packages/studio/src/components/Timeline/get-sequence-context-menu-items.ts
+++ b/packages/studio/src/components/Timeline/get-sequence-context-menu-items.ts
@@ -122,13 +122,17 @@ const copyImageToClipboard = async (element: Element): Promise<void> => {
export const getMultiSequenceContextMenuItems = ({
deleteDisabled,
duplicateDisabled,
+ splitDisabled,
onDeleteSelectedSequences,
onDuplicateSelectedSequences,
+ onSplitSelectedSequences,
}: {
readonly deleteDisabled: boolean;
readonly duplicateDisabled: boolean;
+ readonly splitDisabled: boolean;
readonly onDeleteSelectedSequences: () => void;
readonly onDuplicateSelectedSequences: () => void;
+ readonly onSplitSelectedSequences: () => void;
}): ComboboxValue[] => {
return [
{
@@ -143,6 +147,18 @@ export const getMultiSequenceContextMenuItems = ({
subMenu: null,
value: 'duplicate-selected-sequences',
},
+ {
+ type: 'item',
+ id: 'split-selected-sequences',
+ keyHint: null,
+ label: 'Split selected at playhead',
+ leftItem: null,
+ disabled: splitDisabled,
+ onClick: onSplitSelectedSequences,
+ quickSwitcherLabel: null,
+ subMenu: null,
+ value: 'split-selected-sequences',
+ },
{
type: 'divider',
id: 'duplicate-delete-selected-sequences-divider',
diff --git a/packages/studio/src/components/Timeline/split-selected-timeline-item.ts b/packages/studio/src/components/Timeline/split-selected-timeline-item.ts
index 8c3c15ffb6..c476bb6d44 100644
--- a/packages/studio/src/components/Timeline/split-selected-timeline-item.ts
+++ b/packages/studio/src/components/Timeline/split-selected-timeline-item.ts
@@ -151,13 +151,29 @@ export const splitTimelineSequenceFromSource = ({
nodePathInfo: SequenceNodePathInfo;
splitFrame: number;
}): Promise<boolean> => {
- const nodePath = nodePathInfo.sequenceSubscriptionKey;
+ return splitTimelineSequencesFromSource({
+ sequences: [{nodePathInfo, splitFrame}],
+ });
+};
+export const splitTimelineSequencesFromSource = ({
+ sequences,
+}: {
+ sequences: Array<{
+ nodePathInfo: SequenceNodePathInfo;
+ splitFrame: number;
+ }>;
+}): Promise<boolean> => {
return splitJsxSequence({
- fileName: nodePath.absolutePath,
- nodePath: nodePath.nodePath,
- sequenceKeys: nodePath.sequenceKeys,
- splitFrame,
+ sequences: sequences.map(({nodePathInfo, splitFrame}) => {
+ const nodePath = nodePathInfo.sequenceSubscriptionKey;
+ return {
+ fileName: nodePath.absolutePath,
+ nodePath: nodePath.nodePath,
+ sequenceKeys: nodePath.sequenceKeys,
+ splitFrame,
+ };
+ }),
})
.then((result) => {
if (result.success) {
@@ -173,70 +189,90 @@ export const splitTimelineSequenceFromSource = ({
});
};
-export const shouldHandleTimelineDuplicateShortcut = ({
- shiftKey,
-}: {
- readonly shiftKey: boolean;
-}) => !shiftKey;
-
-export const shouldHandleTimelineSplitShortcut = ({
- shiftKey,
-}: {
- readonly shiftKey: boolean;
-}) => shiftKey;
-
export const splitSelectedTimelineItems = ({
selections,
sequences,
overrideIdsToNodePaths,
propStatuses,
splitFrame,
- splitSequence = splitTimelineSequenceFromSource,
+ splitSequences = splitTimelineSequencesFromSource,
+ notify = showNotification,
}: {
selections: readonly TimelineSelection[];
sequences: TSequence[];
overrideIdsToNodePaths: OverrideIdToNodePaths;
propStatuses: PropStatuses | undefined;
splitFrame: number;
- splitSequence?: (options: {
- nodePathInfo: SequenceNodePathInfo;
- splitFrame: number;
+ splitSequences?: (options: {
+ sequences: Array<{
+ nodePathInfo: SequenceNodePathInfo;
+ splitFrame: number;
+ }>;
}) => Promise<boolean>;
+ notify?: (message: string, durationInMs: number) => void;
}): Promise<boolean> | null => {
- if (selections.length !== 1) {
+ if (
+ selections.length === 0 ||
+ selections.some((selection) => selection.type !== 'sequence')
+ ) {
return null;
}
- const [selection] = selections;
- if (selection.type !== 'sequence') {
- return null;
- }
+ const eligible: Array<{
+ nodePathInfo: SequenceNodePathInfo;
+ splitFrame: number;
+ }> = [];
+ const skippedReasons: string[] = [];
+ for (const selection of selections) {
+ if (selection.type !== 'sequence') {
+ continue;
+ }
- const track = findTrackForNodePathInfo({
- sequences,
- overrideIdsToNodePaths,
- nodePathInfo: selection.nodePathInfo,
- });
- const sequencePropStatuses = propStatuses
- ? Internals.getPropStatusesCtx(
- propStatuses,
- selection.nodePathInfo.sequenceSubscriptionKey,
- )
- : undefined;
- const eligibility = getTimelineSequenceSplitEligibility({
- selection,
- sequence: track?.sequence ?? null,
- splitFrame,
- propStatuses: sequencePropStatuses,
- });
+ const track = findTrackForNodePathInfo({
+ sequences,
+ overrideIdsToNodePaths,
+ nodePathInfo: selection.nodePathInfo,
+ });
+ const sequencePropStatuses = propStatuses
+ ? Internals.getPropStatusesCtx(
+ propStatuses,
+ selection.nodePathInfo.sequenceSubscriptionKey,
+ )
+ : undefined;
+ const eligibility = getTimelineSequenceSplitEligibility({
+ selection,
+ sequence: track?.sequence ?? null,
+ splitFrame,
+ propStatuses: sequencePropStatuses,
+ });
+ if (eligibility.canSplit) {
+ eligible.push({
+ nodePathInfo: eligibility.nodePathInfo,
+ splitFrame,
+ });
+ } else {
+ skippedReasons.push(eligibility.reason);
+ }
+ }
- if (!eligibility.canSplit) {
- showNotification(eligibility.reason, 4000);
+ if (eligible.length === 0) {
+ notify(
+ selections.length === 1
+ ? skippedReasons[0]
+ : `None of the ${selections.length} selected clips can be split at the playhead`,
+ 4000,
+ );
return Promise.resolve(false);
}
- return splitSequence({
- nodePathInfo: eligibility.nodePathInfo,
- splitFrame,
+ return splitSequences({sequences: eligible}).then((success) => {
+ if (success && skippedReasons.length > 0) {
+ notify(
+ `Split ${eligible.length} ${eligible.length === 1 ? 'clip' : 'clips'}. Skipped ${skippedReasons.length} ${skippedReasons.length === 1 ? 'clip' : 'clips'} that could not be split.`,
+ 4000,
+ );
+ }
+
+ return success;
});
};
diff --git a/packages/studio/src/components/keyboard-shortcuts.ts b/packages/studio/src/components/keyboard-shortcuts.ts
index 952e8e6c16..e02b6d43a4 100644
--- a/packages/studio/src/components/keyboard-shortcuts.ts
+++ b/packages/studio/src/components/keyboard-shortcuts.ts
@@ -73,7 +73,8 @@ export const defaultKeyboardShortcuts: Record<
selectOpacityProp: [{key: 't'}],
selectRotateProp: [{key: 'r', shift: false}],
selectScaleProp: [{key: 's'}],
- duplicateSequences: [{key: 'd', commandOrControl: true}],
+ duplicateSequences: [{key: 'd', commandOrControl: true, shift: false}],
+ splitSequences: [{key: 'd', commandOrControl: true, shift: true}],
copyEffectsAndValues: [{key: 'c', commandOrControl: true}],
cutEffects: [{key: 'x', commandOrControl: true}],
deleteSelection: [{key: 'Backspace'}, {key: 'Delete'}],
@@ -195,6 +196,7 @@ export const keyboardShortcutGroups: readonly KeyboardShortcutGroup[] = [
shortcut('Select rotate prop', 'selectRotateProp'),
shortcut('Select scale prop', 'selectScaleProp'),
shortcut('Duplicate sequences', 'duplicateSequences'),
+ shortcut('Split sequences at playhead', 'splitSequences'),
shortcut('Copy effects / values', 'copyEffectsAndValues'),
shortcut('Cut effects', 'cutEffects'),
fixedShortcut(
diff --git a/packages/studio/src/test/keyboard-shortcuts.test.ts b/packages/studio/src/test/keyboard-shortcuts.test.ts
index 4b44a715de..4acaf5cd3f 100644
--- a/packages/studio/src/test/keyboard-shortcuts.test.ts
+++ b/packages/studio/src/test/keyboard-shortcuts.test.ts
@@ -99,11 +99,17 @@ test('keeps shifted shortcuts distinct from their plain-key actions', () => {
['o', 'setOutPoint', 'toggleOutlines'],
['r', 'render', 'toggleRulersAndGuides'],
['r', 'selectRotateProp', 'toggleRulersAndGuides'],
+ ['d', 'duplicateSequences', 'splitSequences'],
] as const) {
const plainShortcut = defaultKeyboardShortcuts[plainAction][0];
const shiftedShortcut = defaultKeyboardShortcuts[shiftedAction][0];
for (const shiftKey of [false, true]) {
const keyEvent = event({
+ ...(plainShortcut.commandOrControl
+ ? isMac
+ ? {metaKey: true}
+ : {ctrlKey: true}
+ : {}),
key: shiftKey ? key.toUpperCase() : key,
shiftKey,
});
diff --git a/packages/studio/src/test/split-selected-timeline-item.test.ts b/packages/studio/src/test/split-selected-timeline-item.test.ts
index 7706a7f9a4..49e4ed5407 100644
--- a/packages/studio/src/test/split-selected-timeline-item.test.ts
+++ b/packages/studio/src/test/split-selected-timeline-item.test.ts
@@ -9,8 +9,6 @@ import type {
import {Internals} from 'remotion';
import {
getTimelineSequenceSplitEligibility,
- shouldHandleTimelineDuplicateShortcut,
- shouldHandleTimelineSplitShortcut,
splitSelectedTimelineItems,
} from '../components/Timeline/split-selected-timeline-item';
import type {SequenceNodePathInfo} from '../helpers/get-timeline-sequence-sort-key';
@@ -35,7 +33,10 @@ const makeNodePathInfo = (
supportsEffects: true,
});
-const makeSequence = (overrides: Partial<TSequence> = {}): TSequence =>
+const makeSequence = (
+ overrides: Partial<TSequence> = {},
+ overrideId = 'override',
+): TSequence =>
({
from: 10,
trimBefore: null,
@@ -52,7 +53,7 @@ const makeSequence = (overrides: Partial<TSequence> = {}): TSequence =>
controls: {
schema: {},
runtimeValues: makeRuntimeValueStore({}),
- overrideId: 'override',
+ overrideId,
supportsEffects: true,
componentIdentity: null,
componentName: 'Sequence',
@@ -209,13 +210,6 @@ test('getTimelineSequenceSplitEligibility rejects dynamic timing props', () => {
).toBe(false);
});
-test('Cmd+D and Cmd+Shift+D shortcut gates are mutually exclusive', () => {
- expect(shouldHandleTimelineDuplicateShortcut({shiftKey: false})).toBe(true);
- expect(shouldHandleTimelineDuplicateShortcut({shiftKey: true})).toBe(false);
- expect(shouldHandleTimelineSplitShortcut({shiftKey: false})).toBe(false);
- expect(shouldHandleTimelineSplitShortcut({shiftKey: true})).toBe(true);
-});
-
test('splitSelectedTimelineItems splits the selected sequence at the playhead', async () => {
const nodePathInfo = makeNodePathInfo(['body', 0]);
const propStatuses = {
@@ -242,8 +236,8 @@ test('splitSelectedTimelineItems splits the selected sequence at the playhead',
},
propStatuses,
splitFrame: 30,
- splitSequence: (options) => {
- splitCalls.push(options);
+ splitSequences: ({sequences: splitSequences}) => {
+ splitCalls.push(...splitSequences);
return Promise.resolve(true);
},
});
@@ -251,3 +245,76 @@ test('splitSelectedTimelineItems splits the selected sequence at the playhead',
expect(result).toBe(true);
expect(splitCalls).toEqual([{nodePathInfo, splitFrame: 30}]);
});
+
+test('splitSelectedTimelineItems batches multiple selected clips', async () => {
+ const first = makeNodePathInfo(['body', 0]);
+ const second = makeNodePathInfo(['body', 1]);
+ const firstSequence = makeSequence();
+ const secondSequence = makeSequence(
+ {id: 'second-sequence'},
+ 'second-override',
+ );
+ const splitCalls: {nodePathInfo: SequenceNodePathInfo; splitFrame: number}[] =
+ [];
+
+ const result = await splitSelectedTimelineItems({
+ selections: [
+ {type: 'sequence', nodePathInfo: first},
+ {type: 'sequence', nodePathInfo: second},
+ ],
+ sequences: [firstSequence, secondSequence],
+ overrideIdsToNodePaths: {
+ override: first.sequenceSubscriptionKey,
+ 'second-override': second.sequenceSubscriptionKey,
+ },
+ propStatuses: undefined,
+ splitFrame: 30,
+ splitSequences: ({sequences}) => {
+ splitCalls.push(...sequences);
+ return Promise.resolve(true);
+ },
+ });
+
+ expect(result).toBe(true);
+ expect(splitCalls).toEqual([
+ {nodePathInfo: first, splitFrame: 30},
+ {nodePathInfo: second, splitFrame: 30},
+ ]);
+});
+
+test('splitSelectedTimelineItems skips ineligible clips and reports the partial split', async () => {
+ const eligible = makeNodePathInfo(['body', 0]);
+ const ineligible = makeNodePathInfo(['body', 1]);
+ const ineligibleSequence = makeSequence(
+ {from: 40, id: 'ineligible-sequence'},
+ 'ineligible-override',
+ );
+ const splitCalls: {nodePathInfo: SequenceNodePathInfo; splitFrame: number}[] =
+ [];
+ const notifications: string[] = [];
+
+ const result = await splitSelectedTimelineItems({
+ selections: [
+ {type: 'sequence', nodePathInfo: eligible},
+ {type: 'sequence', nodePathInfo: ineligible},
+ ],
+ sequences: [makeSequence(), ineligibleSequence],
+ overrideIdsToNodePaths: {
+ override: eligible.sequenceSubscriptionKey,
+ 'ineligible-override': ineligible.sequenceSubscriptionKey,
+ },
+ propStatuses: undefined,
+ splitFrame: 30,
+ splitSequences: ({sequences}) => {
+ splitCalls.push(...sequences);
+ return Promise.resolve(true);
+ },
+ notify: (message) => notifications.push(message),
+ });
+
+ expect(result).toBe(true);
+ expect(splitCalls).toEqual([{nodePathInfo: eligible, splitFrame: 30}]);
+ expect(notifications).toEqual([
+ 'Split 1 clip. Skipped 1 clip that could not be split.',
+ ]);
+});