🎥 Make videos programmatically with React
Fix context actions for selected sequences
Jonny Burgerc34fa055e172
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex ae1944199c..336595cc01 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -6,7 +6,7 @@ import {deleteEffects as deleteEffectsCodemod,duplicateEffects as duplicateEffectsCodemod,duplicateCompositionInSource,- duplicateJsxNode as duplicateJsxNodeCodemod,+ duplicateJsxNodes as duplicateJsxNodesCodemod,findProjectFile,getCanUpdateDefaultPropsForProject,getCompositionComponentInfo,@@ -1293,33 +1293,55 @@ export const createBrowserStudioOperations = ({};const duplicateJsxNode: BrowserStudioOperations['duplicateJsxNode'] = async ({- fileName,- nodePath,+ nodes,}) => {try {+ if (nodes.length === 0) {+ throw new Error('No JSX nodes were specified for duplication');+ }+const project = getProject();- const absolutePath = findProjectFile({- filePath: fileName,- project,- });- const result = await duplicateJsxNodeCodemod({- input: project.files[absolutePath],- nodePath,- formatFile: formatCodemodFile,- });+ const nodesByFile = new Map<+ string,+ (typeof nodes)[number]['nodePath'][]+ >();+ for (const node of nodes) {+ const fileName = findProjectFile({+ filePath: node.fileName,+ project,+ });+ const fileNodes = nodesByFile.get(fileName) ?? [];+ fileNodes.push(node.nodePath);+ nodesByFile.set(fileName, fileNodes);+ }++ const updates = await Promise.all(+ [...nodesByFile].map(async ([fileName, nodePaths]) => ({+ fileName,+ result: await duplicateJsxNodesCodemod({+ input: project.files[fileName],+ nodePaths,+ formatFile: formatCodemodFile,+ }),+ })),+ );+ const nextProject = {+ ...project,+ files: {+ ...project.files,+ ...Object.fromEntries(+ updates.map(({fileName, result}) => [fileName, result.output]),+ ),+ },+ };const nodePathMutation = controller.applyMutation({- fileName: absolutePath,- mutate: () => ({- ...project,- files: {...project.files, [absolutePath]: result.output},- }),- nodePathMutationFiles: [- {- absolutePath,- remappings: result.nodePathRemappings,- restoredNodePaths: [],- },- ],+ fileName: updates.map(({fileName}) => fileName).join(', '),+ mutate: () => nextProject,+ nodePathMutationFiles: updates.map(({fileName, result}) => ({+ absolutePath: fileName,+ remappings: result.nodePathRemappings,+ restoredNodePaths: [],+ })),});if (nodePathMutation === null) {throw new Error('Could not duplicate JSX node');diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 11b31acbeb..9143325532 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -870,8 +870,12 @@ registerRoot(Root);`,}const failure = await operations.duplicateJsxNode({- fileName: 'src/Composition.tsx',- nodePath: [...subscription.nodePath.nodePath, 'missing'],+ nodes: [+ {+ fileName: 'src/Composition.tsx',+ nodePath: [...subscription.nodePath.nodePath, 'missing'],+ },+ ],});expect(failure).toMatchObject({success: false,@@ -882,8 +886,12 @@ registerRoot(Root);`,expect(getProject().files[fileName]).toBe(initialContents);const result = await operations.duplicateJsxNode({- fileName: 'src/Composition.tsx',- nodePath: subscription.nodePath.nodePath,+ nodes: [+ {+ fileName: 'src/Composition.tsx',+ nodePath: subscription.nodePath.nodePath,+ },+ ],});if (!result.success) {throw new Error(result.reason);diff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mtsindex 32ddaa20a8..e9ec2f4fa2 100644--- a/packages/example/e2e/studio.test.mts+++ b/packages/example/e2e/studio.test.mts@@ -16,6 +16,12 @@ import {import {startStudio, stopStudio} from './studio-server.mts';const macCursorsFile = path.join(exampleDir, 'src', 'MacCursors', 'index.tsx');+const sequenceShiftFile = path.join(+ exampleDir,+ 'src',+ 'VisualModeTests',+ 'SequenceShiftRepro.tsx',+);const outlineSelectionCasesFile = path.join(exampleDir,'src',@@ -1614,6 +1620,130 @@ test.describe('visual mode', () => {).toBeVisible();});+ test('should apply a timeline context menu action to multiple selected sequences', async ({+ page,+ }) => {+ const sourceBefore = fs.readFileSync(sequenceShiftFile, 'utf-8');++ try {+ await page.goto(`${STUDIO_URL}/sequence-shift-repro`);+ await page.waitForFunction(+ () => !document.body.innerText.includes('Loading...'),+ {timeout: 30_000},+ );+ await page.keyboard.press('g');+ const currentFrameInput = page.locator('input:focus');+ await currentFrameInput.fill('22');+ await currentFrameInput.press('Enter');+ const outer = page.getByText('Outer frame descendant', {exact: true});+ const local = page.getByText('Local frame descendant', {exact: true});+ const localBar = page.locator(+ '[data-timeline-marquee-item][title="Local frame descendant"]',+ );+ await expect(outer).toBeVisible({timeout: 15_000});+ await expect(local).toBeVisible();++ await outer.click();+ await local.click({modifiers: ['Meta']});+ await localBar.click({button: 'right'});+ await expect(outer.locator('../../..')).toHaveCSS(+ 'background-color',+ 'rgb(59, 63, 66)',+ );+ await expect(+ page+ .locator('[data-remotion-menu-tree-id]')+ .last()+ .getByRole('button', {+ name: 'Duplicate selected',+ exact: true,+ }),+ ).toBeVisible();+ await page.keyboard.press('Escape');+ await local.click({button: 'right'});+ await expect(outer.locator('../../..')).toHaveCSS(+ 'background-color',+ 'rgb(59, 63, 66)',+ );++ const contextMenu = page.locator('[data-remotion-menu-tree-id]').last();+ await expect(+ contextMenu.getByRole('button', {+ name: 'Duplicate selected',+ exact: true,+ }),+ ).toBeVisible();+ await contextMenu+ .getByRole('button', {name: 'Delete selected', exact: true})+ .click();++ await expect+ .poll(() => {+ const source = fs.readFileSync(sequenceShiftFile, 'utf-8');+ return [+ source.includes('name="Outer frame descendant"'),+ source.includes('name="Local frame descendant"'),+ ];+ })+ .toEqual([false, false]);+ } finally {+ fs.writeFileSync(sequenceShiftFile, sourceBefore);+ }+ });++ test('should duplicate each selected timeline sequence once', async ({+ page,+ }) => {+ const sourceBefore = fs.readFileSync(sequenceShiftFile, 'utf-8');++ try {+ await page.goto(`${STUDIO_URL}/sequence-shift-repro`);+ await page.waitForFunction(+ () => !document.body.innerText.includes('Loading...'),+ {timeout: 30_000},+ );+ await page.keyboard.press('g');+ const currentFrameInput = page.locator('input:focus');+ await currentFrameInput.fill('22');+ await currentFrameInput.press('Enter');+ const outer = page.getByText('Outer frame descendant', {exact: true});+ const nestedParent = page.getByText('Nested timing parent', {+ exact: true,+ });+ await expect(outer).toBeVisible({timeout: 15_000});+ await expect(nestedParent).toBeVisible();++ await outer.click();+ await nestedParent.click({modifiers: ['Meta']});+ await nestedParent.click({button: 'right'});+ await page+ .locator('[data-remotion-menu-tree-id]')+ .last()+ .getByRole('button', {name: 'Duplicate selected', exact: true})+ .click();++ await expect+ .poll(() => {+ const source = fs.readFileSync(sequenceShiftFile, 'utf-8');+ return [+ source.match(/name="Outer frame descendant-copy"/g)?.length ?? 0,+ source.match(/name="Nested timing parent-copy"/g)?.length ?? 0,+ source.match(/name="Outer frame descendant-copy-copy"/g)?.length ??+ 0,+ source.match(/<LocalFrameDescendant \/>/g)?.length ?? 0,+ ];+ })+ .toEqual([1, 1, 0, 1]);++ await page.keyboard.press('ControlOrMeta+z');+ await expect+ .poll(() => fs.readFileSync(sequenceShiftFile, 'utf-8'))+ .toBe(sourceBefore);+ } finally {+ fs.writeFileSync(sequenceShiftFile, sourceBefore);+ }+ });+test('should keep selected canvas outlines visible outside the canvas', async ({page,}) => {diff --git a/packages/studio-codemods/src/duplicate-jsx-node.ts b/packages/studio-codemods/src/duplicate-jsx-node.tsindex c09126f8cc..2f3c2fd458 100644--- a/packages/studio-codemods/src/duplicate-jsx-node.ts+++ b/packages/studio-codemods/src/duplicate-jsx-node.ts@@ -161,14 +161,14 @@ export const duplicateJsxElementAtPath = (jsxPath.replace(makeFragment(jsxNode, clone));};-export const duplicateJsxNode = async ({+export const duplicateJsxNodes = async ({input,- nodePath,+ nodePaths,formatFile,prettierConfigOverride,}: {input: string;- nodePath: SequenceNodePath;+ nodePaths: SequenceNodePath[];formatFile: (input: {contents: string;prettierConfigOverride: Record<string, unknown> | null;@@ -177,27 +177,34 @@ export const duplicateJsxNode = async ({}): Promise<{output: string;formatted: boolean;- nodeLabel: string;- logLine: number;+ nodeLabels: string[];+ logLines: number[];nodePathRemappings: SequenceNodePathRemapping[];}> => {const ast = parseAst(input);const capturedNodePaths = captureJsxNodePaths(ast);- const jsxPath = findJsxElementPathForDeletion(ast, nodePath);- if (!jsxPath) {- throw new Error(- 'Could not find a JSX element at the specified location to duplicate',- );- }+ const targets = nodePaths.map((nodePath) => {+ const jsxPath = findJsxElementPathForDeletion(ast, nodePath);+ if (!jsxPath) {+ throw new Error(+ 'Could not find a JSX element at the specified location to duplicate',+ );+ }- const jsxElement = jsxPath.node as JSXElement;- const nodeLabel = getJsxElementTagLabel(jsxElement);- const logLine =- jsxElement.openingElement.loc?.start.line ??- jsxElement.loc?.start.line ??- 1;+ const jsxElement = jsxPath.node as JSXElement;+ return {+ jsxPath,+ nodeLabel: getJsxElementTagLabel(jsxElement),+ logLine:+ jsxElement.openingElement.loc?.start.line ??+ jsxElement.loc?.start.line ??+ 1,+ };+ });- duplicateJsxElementAtPath(jsxPath);+ for (const target of targets) {+ duplicateJsxElementAtPath(target.jsxPath);+ }const finalFile = serializeAst(ast);const {output, formatted} = await formatFile({@@ -213,8 +220,42 @@ export const duplicateJsxNode = async ({return {output,formatted,- nodeLabel,- logLine,+ nodeLabels: targets.map((target) => target.nodeLabel),+ logLines: targets.map((target) => target.logLine),nodePathRemappings,};};++export const duplicateJsxNode = async ({+ input,+ nodePath,+ formatFile,+ prettierConfigOverride,+}: {+ input: string;+ nodePath: SequenceNodePath;+ formatFile: (input: {+ contents: string;+ prettierConfigOverride: Record<string, unknown> | null;+ }) => Promise<{output: string; formatted: boolean}>;+ prettierConfigOverride?: Record<string, unknown> | null;+}): Promise<{+ output: string;+ formatted: boolean;+ nodeLabel: string;+ logLine: number;+ nodePathRemappings: SequenceNodePathRemapping[];+}> => {+ const {nodeLabels, logLines, ...result} = await duplicateJsxNodes({+ input,+ nodePaths: [nodePath],+ formatFile,+ prettierConfigOverride,+ });++ return {+ ...result,+ nodeLabel: nodeLabels[0],+ logLine: logLines[0],+ };+};diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.tsindex 8bbd7dd2e5..cb9cc28f7b 100644--- a/packages/studio-codemods/src/index.ts+++ b/packages/studio-codemods/src/index.ts@@ -24,6 +24,7 @@ export {duplicateCompositionInSource} from './duplicate-composition';export {duplicateJsxElementAtPath,duplicateJsxNode,+ duplicateJsxNodes,} from './duplicate-jsx-node';export {addEffect,diff --git a/packages/studio-server/src/codemods/duplicate-jsx-node.ts b/packages/studio-server/src/codemods/duplicate-jsx-node.tsindex b0c884b95a..825a370207 100644--- a/packages/studio-server/src/codemods/duplicate-jsx-node.ts+++ b/packages/studio-server/src/codemods/duplicate-jsx-node.ts@@ -1,6 +1,7 @@import {duplicateJsxElementAtPath,duplicateJsxNode as duplicateJsxNodeCodemod,+ duplicateJsxNodes as duplicateJsxNodesCodemod,} from '@remotion/studio-codemods';import type {SequenceNodePath} from 'remotion';import {formatFileContent} from './format-file-content';@@ -26,3 +27,23 @@ export const duplicateJsxNode = ({}),prettierConfigOverride,});++export const duplicateJsxNodes = ({+ input,+ nodePaths,+ prettierConfigOverride,+}: {+ input: string;+ nodePaths: SequenceNodePath[];+ prettierConfigOverride?: Record<string, unknown> | null;+}) =>+ duplicateJsxNodesCodemod({+ input,+ nodePaths,+ formatFile: ({contents, prettierConfigOverride: override}) =>+ formatFileContent({+ input: contents,+ prettierConfigOverride: override,+ }),+ prettierConfigOverride,+ });diff --git a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.tsindex ea0acba7f7..af1be9c4b4 100644--- a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts+++ b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts@@ -4,7 +4,7 @@ import type {DuplicateJsxNodeRequest,DuplicateJsxNodeResponse,} from '@remotion/studio-shared';-import {duplicateJsxNode} from '../../codemods/duplicate-jsx-node';+import {duplicateJsxNodes} from '../../codemods/duplicate-jsx-node';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 {warnAboutPrettierOnce} from './log-updates/log-update';@@ -24,71 +24,112 @@ import {export const duplicateJsxNodeHandler: ApiHandler<DuplicateJsxNodeRequest,DuplicateJsxNodeResponse-> = ({input: {fileName, nodePath}, remotionRoot, logLevel}) => {+> = ({input: {nodes}, remotionRoot, logLevel}) => {return withSourceFileWriteQueue(async () => {try {+ if (nodes.length === 0) {+ throw new Error('No JSX nodes were specified for duplication');+ }+RenderInternals.Log.trace({indent: false, logLevel},- `[duplicate-jsx-node] Received request for fileName="${fileName}"`,+ `[duplicate-jsx-node] Received request to duplicate ${nodes.length} JSX node${nodes.length === 1 ? '' : 's'}`,);- const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({- remotionRoot,- fileName,- action: 'modify',- });- const fileContents = readFileSync(absolutePath, 'utf-8');+ const itemsByFileName = new Map<string, typeof nodes>();+ for (const item of nodes) {+ const fileItems = itemsByFileName.get(item.fileName) ?? [];+ fileItems.push(item);+ itemsByFileName.set(item.fileName, fileItems);+ }++ const updates = await Promise.all(+ [...itemsByFileName.entries()].map(async ([fileName, fileItems]) => {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });+ const fileContents = readFileSync(absolutePath, 'utf-8');+ const {output, formatted, nodeLabels, logLines, nodePathRemappings} =+ await duplicateJsxNodes({+ input: fileContents,+ nodePaths: fileItems.map((item) => item.nodePath),+ });- const {output, formatted, nodeLabel, logLine, nodePathRemappings} =- await duplicateJsxNode({input: fileContents, nodePath});- const nodePathMutation = broadcastSequenceNodePathMutation([- {- absolutePath,- remappings: nodePathRemappings,+ return {+ absolutePath,+ fileRelativeToRoot,+ fileContents,+ formatted,+ logLine: Math.min(...logLines),+ nodeLabels,+ nodePathRemappings,+ output,+ };+ }),+ );+ const nodePathMutation = broadcastSequenceNodePathMutation(+ updates.map((update) => ({+ absolutePath: update.absolutePath,+ remappings: update.nodePathRemappings,restoredNodePaths: [],- },- ]);+ })),+ );+ const duplicatedNodeDescription =+ nodes.length === 1+ ? updates[0].nodeLabels[0]+ : `${nodes.length} JSX nodes`;- 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: `↩️ Duplication of ${nodeLabel}`,- redoMessage: `↪️ Duplication of ${nodeLabel}`,+ undoMessage: `↩️ Duplication of ${duplicatedNodeDescription}`,+ redoMessage: `↪️ Duplication of ${duplicatedNodeDescription}`,},entryType: 'duplicate-jsx-node',suppressHmrOnFileRestore: false,- nodePathRemappings,- });- suppressUndoStackInvalidation(absolutePath);- writeFileAndNotifyFileWatchers({- file: absolutePath,- content: output,- originatorClientId: undefined,- metadata: {skipSequencePropsUpdate: true},});- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath,- line: logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(`${locationLabel}`)} Duplicated ${nodeLabel}`,- );- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }+ for (const update of updates) {+ suppressUndoStackInvalidation(update.absolutePath);+ writeFileAndNotifyFileWatchers({+ file: update.absolutePath,+ content: update.output,+ originatorClientId: undefined,+ metadata: {skipSequencePropsUpdate: true},+ });- RenderInternals.Log.verbose(- {indent: false, logLevel},- `[duplicate-jsx-node] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,- );+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath: update.absolutePath,+ line: update.logLine,+ });+ const fileDescription =+ update.nodeLabels.length === 1+ ? update.nodeLabels[0]+ : `${update.nodeLabels.length} JSX nodes`;+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(`${locationLabel}`)} Duplicated ${fileDescription}`,+ );+ if (!update.formatted) {+ warnAboutPrettierOnce(logLevel);+ }++ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[duplicate-jsx-node] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,+ );+ }printUndoHint(logLevel);diff --git a/packages/studio-server/src/test/duplicate-jsx-node.test.ts b/packages/studio-server/src/test/duplicate-jsx-node.test.tsindex ca517600fc..08ca2dcec8 100644--- a/packages/studio-server/src/test/duplicate-jsx-node.test.ts+++ b/packages/studio-server/src/test/duplicate-jsx-node.test.ts@@ -1,5 +1,8 @@import {expect, test} from 'bun:test';-import {duplicateJsxNode} from '../codemods/duplicate-jsx-node';+import {+ duplicateJsxNode,+ duplicateJsxNodes,+} from '../codemods/duplicate-jsx-node';import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';const sample = `import React from 'react';@@ -46,6 +49,29 @@ test('duplicateJsxNode remaps following JSX siblings', async () => {]);});+test('duplicateJsxNodes duplicates each requested JSX element once', async () => {+ const input = `export const X = () => (+ <div>+ <span name="first" />+ <span name="second" />+ <span name="untouched" />+ </div>+);+`;+ const {output} = await duplicateJsxNodes({+ input,+ nodePaths: [+ lineContainingToNodePath(input, 'name="first"'),+ lineContainingToNodePath(input, 'name="second"'),+ ],+ });++ expect(output.match(/name="first-copy"/g)).toHaveLength(1);+ expect(output.match(/name="second-copy"/g)).toHaveLength(1);+ expect(output).not.toContain('name="first-copy-copy"');+ expect(output.match(/name="untouched"/g)).toHaveLength(1);+});+const onlyReturn = `import React from 'react';export const X: React.FC = () => {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.tsindex c91948ca4d..e4e74d58f9 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@@ -140,8 +140,16 @@ test('JSX structure routes broadcast and return node path mutations before writiconst duplicateResponse = await duplicateJsxNodeHandler({...handlerContext,input: {- fileName,- nodePath: lineContainingToNodePath(before, 'name="b"'),+ nodes: [+ {+ fileName,+ nodePath: lineContainingToNodePath(before, 'name="b"'),+ },+ {+ fileName,+ nodePath: lineContainingToNodePath(before, 'name="c"'),+ },+ ],},});if (!duplicateResponse.success) {@@ -149,6 +157,8 @@ test('JSX structure routes broadcast and return node path mutations before writi}assertMutation({before, mutation: duplicateResponse.nodePathMutation});+ expect(readFileSync(filePath, 'utf-8')).toContain('name="b-copy"');+ expect(readFileSync(filePath, 'utf-8')).toContain('name="c-copy"');before = readFileSync(filePath, 'utf-8');const splitResponse = await splitJsxSequenceHandler({diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 06a85c9254..cbe6584f25 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -802,11 +802,15 @@ export type DeleteJsxNodeResponse =stack: string;};-export type DuplicateJsxNodeRequest = {+export type DuplicateJsxNodeRequestItem = {fileName: string;nodePath: SequenceNodePath;};+export type DuplicateJsxNodeRequest = {+ nodes: DuplicateJsxNodeRequestItem[];+};+export type DuplicateJsxNodeResponse =| {success: true;diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex a58865a777..c98f0effe9 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -50,6 +50,7 @@ export {DuplicateEffectRequestItem,DuplicateEffectResponse,DuplicateJsxNodeRequest,+ DuplicateJsxNodeRequestItem,DuplicateJsxNodeResponse,EditorPickerId,ElementInstallDestination,diff --git a/packages/studio/src/components/Timeline/TimelineRowChrome.tsx b/packages/studio/src/components/Timeline/TimelineRowChrome.tsxindex d3218e0f58..248f890498 100644--- a/packages/studio/src/components/Timeline/TimelineRowChrome.tsx+++ b/packages/studio/src/components/Timeline/TimelineRowChrome.tsx@@ -136,9 +136,11 @@ export const TimelineRowChrome: React.FC<{const onContextMenu = useCallback((e: React.MouseEvent<HTMLDivElement>) => {e.stopPropagation();- onSelect();+ if (!selected) {+ onSelect();+ }},- [onSelect],+ [onSelect, selected],);const onDoubleClickIfNotInteractive = useCallback(diff --git a/packages/studio/src/components/Timeline/TimelineSequence.tsx b/packages/studio/src/components/Timeline/TimelineSequence.tsxindex a36e565607..600730a959 100644--- a/packages/studio/src/components/Timeline/TimelineSequence.tsx+++ b/packages/studio/src/components/Timeline/TimelineSequence.tsx@@ -40,9 +40,13 @@ import {deleteJsxNode} from '../delete-jsx-node-api';import {useSelectComposition} from '../InitialCompositionLoader';import {showNotification} from '../Notifications/NotificationCenter';import {useSelectAsset} from '../use-select-asset';+import {deleteSequencesFromSource} from './delete-selected-timeline-item';import {disableSequenceInteractivity} from './disable-sequence-interactivity';import {duplicateSequencesFromSource} from './duplicate-selected-timeline-item';-import {getSequenceContextMenuItems} from './get-sequence-context-menu-items';+import {+ getMultiSequenceContextMenuItems,+ getSequenceContextMenuItems,+} from './get-sequence-context-menu-items';import {getTimelineSequenceVisibleLayout} from './get-timeline-sequence-visible-layout';import {getCurrentFrame} from './imperative-state';import {LoopedTimelineIndicator} from './LoopedTimelineIndicators';@@ -482,7 +486,22 @@ const TimelineSequenceInner: React.FC<{const selectAsset = useSelectAsset();const selectComposition = useSelectComposition();const confirm = useConfirmationDialog();- const {onSelect, selectable} = useTimelineRowSelection(nodePathInfo);+ const {onSelect, selectable, selected} =+ useTimelineRowSelection(nodePathInfo);+ const {selectedItems} = useTimelineSelection();+ const selectedSequenceNodePathInfos = useMemo(() => {+ if (+ !selected ||+ selectedItems.length < 2 ||+ selectedItems.some((item) => item.type !== 'sequence')+ ) {+ return null;+ }++ return selectedItems.flatMap((item) =>+ item.type === 'sequence' ? [item.nodePathInfo] : [],+ );+ }, [selected, selectedItems]);const onSequenceDoubleClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {if (isTimelineSelectionModifierEvent(e)) {@@ -554,6 +573,15 @@ const TimelineSequenceInner: React.FC<{() => undefined,);}, [confirm, duplicateDisabled, nodePathInfo, validatedLocation?.source]);+ const onDuplicateSelectedSequences = useCallback(() => {+ if (!previewInteractive || selectedSequenceNodePathInfos === null) {+ return;+ }++ duplicateSequencesFromSource(selectedSequenceNodePathInfos, confirm).catch(+ () => undefined,+ );+ }, [confirm, previewInteractive, selectedSequenceNodePathInfos]);const onDeleteSequenceFromSource = useCallback(async () => {if (!validatedLocation?.source || !nodePath || deleteDisabled) {return;@@ -595,6 +623,15 @@ const TimelineSequenceInner: React.FC<{nodePathInfo,validatedLocation?.source,]);+ const onDeleteSelectedSequences = useCallback(() => {+ if (!previewInteractive || selectedSequenceNodePathInfos === null) {+ return;+ }++ deleteSequencesFromSource(selectedSequenceNodePathInfos, confirm).catch(+ () => undefined,+ );+ }, [confirm, previewInteractive, selectedSequenceNodePathInfos]);const onDisableSequenceInteractivity = useCallback(() => {if (disableInteractivityDisabled ||@@ -619,10 +656,19 @@ const TimelineSequenceInner: React.FC<{validatedLocation?.source,]);const getContextMenuItems = useCallback(() => {- if (selectable) {+ if (selectable && !selected) {onSelect({shiftKey: false, toggleKey: false});}+ if (selectedSequenceNodePathInfos !== null) {+ return getMultiSequenceContextMenuItems({+ deleteDisabled: !previewInteractive,+ duplicateDisabled: !previewInteractive,+ onDeleteSelectedSequences,+ onDuplicateSelectedSequences,+ });+ }+const freezeFrameMenuItem = getSequenceFreezeFrameMenuItem({clientId:previewInteractive && previewServerState.type === 'connected'@@ -683,8 +729,10 @@ const TimelineSequenceInner: React.FC<{nodePath,onSelect,onDeleteSequenceFromSource,+ onDeleteSelectedSequences,onDisableSequenceInteractivity,onDuplicateSequenceFromSource,+ onDuplicateSelectedSequences,openInCodingAgent,openInEditor,originalLocation,@@ -694,6 +742,8 @@ const TimelineSequenceInner: React.FC<{s,selectAsset,selectable,+ selected,+ selectedSequenceNodePathInfos,sequenceFrameOffset,setPropStatuses,setSelectedModal,diff --git a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsxindex 9956bab254..b18fa33d99 100644--- a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx+++ b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx@@ -62,9 +62,13 @@ import {rotateFieldKey,} from '../selected-outline-types';import {useSelectAsset} from '../use-select-asset';+import {deleteSequencesFromSource} from './delete-selected-timeline-item';import {disableSequenceInteractivity} from './disable-sequence-interactivity';import {duplicateSequencesFromSource} from './duplicate-selected-timeline-item';-import {getSequenceContextMenuItems} from './get-sequence-context-menu-items';+import {+ getMultiSequenceContextMenuItems,+ getSequenceContextMenuItems,+} from './get-sequence-context-menu-items';import {getCurrentFrame} from './imperative-state';import {saveSequenceProps} from './save-sequence-prop';import {getTimelineAssetLinkInfo} from './timeline-asset-link';@@ -303,6 +307,19 @@ const TimelineSequenceItemInner: React.FC<{const {onSelect, selectable, selected} =useTimelineRowSelection(nodePathInfo);const {selectItem, selectedItems} = useTimelineSelection();+ const selectedSequenceNodePathInfos = useMemo(() => {+ if (+ !selected ||+ selectedItems.length < 2 ||+ selectedItems.some((item) => item.type !== 'sequence')+ ) {+ return null;+ }++ return selectedItems.flatMap((item) =>+ item.type === 'sequence' ? [item.nodePathInfo] : [],+ );+ }, [selected, selectedItems]);const containsSelection = useTimelineRowContainsSelection(nodePathInfo);const [effectDropHovered, setEffectDropHovered] = useState(false);const [isRenaming, setIsRenaming] = useState(false);@@ -395,6 +412,15 @@ const TimelineSequenceItemInner: React.FC<{() => undefined,);}, [confirm, duplicateDisabled, nodePathInfo, validatedLocation?.source]);+ const onDuplicateSelectedSequences = useCallback(() => {+ if (!previewInteractive || selectedSequenceNodePathInfos === null) {+ return;+ }++ duplicateSequencesFromSource(selectedSequenceNodePathInfos, confirm).catch(+ () => undefined,+ );+ }, [confirm, previewInteractive, selectedSequenceNodePathInfos]);const onDeleteSequenceFromSource = useCallback(async () => {if (deleteDisabled || !validatedLocation?.source || !nodePath) {@@ -437,6 +463,15 @@ const TimelineSequenceItemInner: React.FC<{validatedLocation?.source,nodePathInfo,]);+ const onDeleteSelectedSequences = useCallback(() => {+ if (!previewInteractive || selectedSequenceNodePathInfos === null) {+ return;+ }++ deleteSequencesFromSource(selectedSequenceNodePathInfos, confirm).catch(+ () => undefined,+ );+ }, [confirm, previewInteractive, selectedSequenceNodePathInfos]);const onDisableSequenceInteractivity = useCallback(() => {if (@@ -978,10 +1013,19 @@ const TimelineSequenceItemInner: React.FC<{}, [canRotate, nodePathInfo, selectItem, setManuallyEnabled]);const getContextMenuItems = useCallback(() => {- if (selectable) {+ if (selectable && !selected) {onSelect({shiftKey: false, toggleKey: false});}+ if (selectedSequenceNodePathInfos !== null) {+ return getMultiSequenceContextMenuItems({+ deleteDisabled: !previewInteractive,+ duplicateDisabled: !previewInteractive,+ onDeleteSelectedSequences,+ onDuplicateSelectedSequences,+ });+ }+const freezeFrameMenuItem = getSequenceFreezeFrameMenuItem({clientId:previewInteractive && previewServerState.type === 'connected'@@ -1122,8 +1166,10 @@ const TimelineSequenceItemInner: React.FC<{onCrop,onRotate,onDeleteSequenceFromSource,+ onDeleteSelectedSequences,onDisableSequenceInteractivity,onDuplicateSequenceFromSource,+ onDuplicateSelectedSequences,onRenameSequence,onSelect,openInCodingAgent,@@ -1134,6 +1180,8 @@ const TimelineSequenceItemInner: React.FC<{propStatusesForOverride,selectAsset,selectable,+ selected,+ selectedSequenceNodePathInfos,sequence,sequenceFrameOffset,setSelectedModal,diff --git a/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.ts b/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.tsindex a2fafaa7ff..cd1575dbd1 100644--- a/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.ts+++ b/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.ts@@ -35,15 +35,7 @@ const confirmDuplicatingProgrammaticallyDuplicatedSequences = (});};-const duplicateSequence = (nodePathInfo: SequenceNodePathInfo) => {- const nodePath = nodePathInfo.sequenceSubscriptionKey;- return duplicateJsxNode({- fileName: nodePath.absolutePath,- nodePath: nodePath.nodePath,- });-};--export const duplicateSequencesFromSource = (+export const duplicateSequencesFromSource = async (nodePathInfos: readonly SequenceNodePathInfo[],confirm: ConfirmationDialogFunction,): Promise<void> => {@@ -54,30 +46,36 @@ export const duplicateSequencesFromSource = ((nodePathInfo) => nodePathInfo.numberOfSequencesWithThisNodePath <= 1,);- return confirmDuplicatingProgrammaticallyDuplicatedSequences(- programmaticallyDuplicated,- confirm,- ).then((shouldDuplicateProgrammaticSequences) => {- const toDuplicate = [...regular];- if (shouldDuplicateProgrammaticSequences) {- toDuplicate.push(...programmaticallyDuplicated);- }+ const shouldDuplicateProgrammaticSequences =+ await confirmDuplicatingProgrammaticallyDuplicatedSequences(+ programmaticallyDuplicated,+ confirm,+ );+ const toDuplicate = [...regular];+ if (shouldDuplicateProgrammaticSequences) {+ toDuplicate.push(...programmaticallyDuplicated);+ }++ const nodes = toDuplicate.map((nodePathInfo) => {+ const nodePath = nodePathInfo.sequenceSubscriptionKey;+ return {+ fileName: nodePath.absolutePath,+ nodePath: nodePath.nodePath,+ };+ });- if (toDuplicate.length === 0) {- return Promise.resolve();+ try {+ if (nodes.length === 0) {+ return;}- return Promise.all(toDuplicate.map(duplicateSequence))- .then((results) => {- const failedResult = results.find((result) => !result.success);- if (failedResult && !failedResult.success) {- showNotification(failedResult.reason, 4000);- }- })- .catch((err) => {- showNotification((err as Error).message, 4000);- });- });+ const result = await duplicateJsxNode({nodes});+ if (!result.success) {+ showNotification(result.reason, 4000);+ }+ } catch (err) {+ showNotification((err as Error).message, 4000);+ }};export const isDuplicatableSequenceRowSelection = (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.tsindex fa66a33ba6..b2dd49095d 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@@ -39,6 +39,49 @@ const normalizeMenuDividers = (items: ComboboxValue[]): ComboboxValue[] => {const interactiveSvgComponentIdentity = 'dev.remotion.remotion.Interactive.Svg';+export const getMultiSequenceContextMenuItems = ({+ deleteDisabled,+ duplicateDisabled,+ onDeleteSelectedSequences,+ onDuplicateSelectedSequences,+}: {+ readonly deleteDisabled: boolean;+ readonly duplicateDisabled: boolean;+ readonly onDeleteSelectedSequences: () => void;+ readonly onDuplicateSelectedSequences: () => void;+}): ComboboxValue[] => {+ return [+ {+ type: 'item',+ id: 'duplicate-selected-sequences',+ keyHint: null,+ label: 'Duplicate selected',+ leftItem: null,+ disabled: duplicateDisabled,+ onClick: onDuplicateSelectedSequences,+ quickSwitcherLabel: null,+ subMenu: null,+ value: 'duplicate-selected-sequences',+ },+ {+ type: 'divider',+ id: 'duplicate-delete-selected-sequences-divider',+ },+ {+ type: 'item',+ id: 'delete-selected-sequences',+ keyHint: null,+ label: 'Delete selected',+ leftItem: null,+ disabled: deleteDisabled,+ onClick: onDeleteSelectedSequences,+ quickSwitcherLabel: null,+ subMenu: null,+ value: 'delete-selected-sequences',+ },+ ];+};+export const getSequenceContextMenuItems = ({assetLinkInfo,canOpenInEditor,diff --git a/packages/studio/src/test/browser-studio-duplicate-jsx-node.test.ts b/packages/studio/src/test/browser-studio-duplicate-jsx-node.test.tsindex 95c4fcc77e..697201efb3 100644--- a/packages/studio/src/test/browser-studio-duplicate-jsx-node.test.ts+++ b/packages/studio/src/test/browser-studio-duplicate-jsx-node.test.ts@@ -36,15 +36,23 @@ test('routes JSX duplication through Browser Studio', async () => {});const result = await duplicateJsxNode({- fileName: '/project/src/Composition.tsx',- nodePath,+ nodes: [+ {+ fileName: '/project/src/Composition.tsx',+ nodePath,+ },+ ],});expect(result.success).toBe(true);expect(receivedRequests).toEqual([{- fileName: '/project/src/Composition.tsx',- nodePath,+ nodes: [+ {+ fileName: '/project/src/Composition.tsx',+ nodePath,+ },+ ],},]);});