Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Duplicate selected effects with Cmd+D (#8452)

Jonny Burger2e896ef5f539
diff --git a/packages/studio-server/src/codemods/duplicate-effect.ts b/packages/studio-server/src/codemods/duplicate-effect.ts
new file mode 100644
index 0000000000..91dd22d8c3
--- /dev/null
+++ b/packages/studio-server/src/codemods/duplicate-effect.ts
@@ -0,0 +1,164 @@
+import type {ArrayExpression, Expression, JSXAttribute} from '@babel/types';
+import {cloneNode} from '@babel/types';
+import type {SequenceNodePath} from 'remotion';
+import {findJsxElementAtNodePath} from '../preview-server/routes/can-update-sequence-props';
+import {formatFileContent} from './format-file-content';
+import {parseAst, serializeAst} from './parse-ast';
+import {
+ findEffectCallExpression,
+ findEffectsAttr,
+} from './update-effect-props/update-effect-props';
+
+const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
+ if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
+ throw new Error('Cannot duplicate effect: effects prop is not an array');
+ }
+
+ const expr = attr.value.expression as Expression;
+ if (expr.type !== 'ArrayExpression') {
+ throw new Error('Cannot duplicate effect: effects prop is not an array');
+ }
+
+ return expr;
+};
+
+export type EffectDuplicationTarget = {
+ sequenceNodePath: SequenceNodePath;
+ effectIndex: number;
+};
+
+type EffectsArrayDuplication = {
+ effectsArray: ArrayExpression;
+ effectIndices: Set<number>;
+ effectLabels: string[];
+ logLines: number[];
+};
+
+export const duplicateEffects = async ({
+ input,
+ effects,
+ prettierConfigOverride,
+}: {
+ input: string;
+ effects: EffectDuplicationTarget[];
+ prettierConfigOverride?: Record<string, unknown> | null;
+}): Promise<{
+ output: string;
+ formatted: boolean;
+ effectLabels: string[];
+ logLines: number[];
+}> => {
+ if (effects.length === 0) {
+ throw new Error('No effects were specified for duplication');
+ }
+
+ const ast = parseAst(input);
+ const duplicationsByAttr = new Map<JSXAttribute, EffectsArrayDuplication>();
+
+ for (const effect of effects) {
+ const {sequenceNodePath, effectIndex} = effect;
+ const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
+ if (!jsx) {
+ throw new Error(
+ 'Could not find a JSX element at the specified location to duplicate effect',
+ );
+ }
+
+ const attr = findEffectsAttr(jsx.attributes ?? []);
+ if (!attr) {
+ throw new Error('Could not find effects on the target JSX element');
+ }
+
+ const effectsArray = getEffectsArray(attr);
+ const existingDuplication = duplicationsByAttr.get(attr);
+ const duplication =
+ existingDuplication ??
+ ({
+ effectsArray,
+ effectIndices: new Set<number>(),
+ effectLabels: [],
+ logLines: [],
+ } satisfies EffectsArrayDuplication);
+
+ duplicationsByAttr.set(attr, duplication);
+
+ if (duplication.effectIndices.has(effectIndex)) {
+ continue;
+ }
+
+ const found = findEffectCallExpression({attr, effectIndex});
+ if (found.kind === 'error') {
+ throw new Error(`Cannot duplicate effect: ${found.reason}`);
+ }
+
+ duplication.effectIndices.add(effectIndex);
+ duplication.effectLabels.push(`${found.callee}()`);
+ duplication.logLines.push(
+ found.call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
+ );
+ }
+
+ for (const duplication of duplicationsByAttr.values()) {
+ for (const effectIndex of [...duplication.effectIndices].sort(
+ (a, b) => b - a,
+ )) {
+ const effect = duplication.effectsArray.elements[effectIndex];
+ if (!effect || effect.type !== 'CallExpression') {
+ throw new Error('Cannot duplicate effect: not-call-expression');
+ }
+
+ duplication.effectsArray.elements.splice(
+ effectIndex + 1,
+ 0,
+ cloneNode(effect, true) as never,
+ );
+ }
+ }
+
+ const finalFile = serializeAst(ast);
+ const {output, formatted} = await formatFileContent({
+ input: finalFile,
+ prettierConfigOverride,
+ });
+
+ return {
+ output,
+ formatted,
+ effectLabels: [...duplicationsByAttr.values()].flatMap(
+ (duplication) => duplication.effectLabels,
+ ),
+ logLines: [...duplicationsByAttr.values()].flatMap(
+ (duplication) => duplication.logLines,
+ ),
+ };
+};
+
+export const duplicateEffect = async ({
+ input,
+ sequenceNodePath,
+ effectIndex,
+ prettierConfigOverride,
+}: {
+ input: string;
+ sequenceNodePath: SequenceNodePath;
+ effectIndex: number;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}): Promise<{
+ output: string;
+ formatted: boolean;
+ effectLabel: string;
+ logLine: number;
+}> => {
+ const {output, formatted, effectLabels, logLines} = await duplicateEffects({
+ input,
+ effects: [{sequenceNodePath, effectIndex}],
+ prettierConfigOverride,
+ });
+
+ return {
+ output,
+ formatted,
+ effectLabel: effectLabels[0],
+ logLine: logLines[0],
+ };
+};
diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.ts
index 6908d498f7..8c391ceac7 100644
--- a/packages/studio-server/src/preview-server/api-routes.ts
+++ b/packages/studio-server/src/preview-server/api-routes.ts
@@ -14,6 +14,7 @@ import {deleteJsxNodeHandler} from './routes/delete-jsx-node';
import {deleteKeyframesHandler} from './routes/delete-keyframes';
import {deleteStaticFileHandler} from './routes/delete-static-file';
import {downloadRemoteAssetHandler} from './routes/download-remote-asset';
+import {duplicateEffectHandler} from './routes/duplicate-effect';
import {duplicateJsxNodeHandler} from './routes/duplicate-jsx-node';
import {insertJsxElementHandler} from './routes/insert-jsx-element';
import {handleInstallPackage} from './routes/install-dependency';
@@ -72,6 +73,7 @@ export const allApiRoutes: {
'/api/save-effect-props': saveEffectPropsHandler,
'/api/add-effect': addEffectHandler,
'/api/reorder-effect': reorderEffectHandler,
+ '/api/duplicate-effect': duplicateEffectHandler,
'/api/reorder-sequence': reorderSequenceHandler,
'/api/delete-keyframes': deleteKeyframesHandler,
'/api/move-keyframes': moveKeyframesHandler,
diff --git a/packages/studio-server/src/preview-server/routes/duplicate-effect.ts b/packages/studio-server/src/preview-server/routes/duplicate-effect.ts
new file mode 100644
index 0000000000..6d0d4357a2
--- /dev/null
+++ b/packages/studio-server/src/preview-server/routes/duplicate-effect.ts
@@ -0,0 +1,136 @@
+import {readFileSync} from 'node:fs';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ DuplicateEffectRequest,
+ DuplicateEffectResponse,
+} from '@remotion/studio-shared';
+import {duplicateEffects} from '../../codemods/duplicate-effect';
+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
+import type {ApiHandler} from '../api-types';
+import {formatLogFileLocation} from '../format-log-file-location';
+import {
+ printUndoHint,
+ pushToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {attrName} from './log-updates/formatting';
+import {warnAboutPrettierOnce} from './log-updates/log-update';
+
+const getDuplicatedEffectDescription = (effectLabels: string[]): string => {
+ if (effectLabels.length === 1) {
+ return effectLabels[0];
+ }
+
+ return `${effectLabels.length} effects`;
+};
+
+export const duplicateEffectHandler: ApiHandler<
+ DuplicateEffectRequest,
+ DuplicateEffectResponse
+> = async ({input: effects, remotionRoot, logLevel}) => {
+ try {
+ if (effects.length === 0) {
+ throw new Error('No effects were specified for duplication');
+ }
+
+ RenderInternals.Log.trace(
+ {indent: false, logLevel},
+ `[duplicate-effect] Received request to duplicate ${effects.length} effect target${effects.length === 1 ? '' : 's'}`,
+ );
+
+ const itemsByFileName = new Map<string, typeof effects>();
+ for (const item of effects) {
+ 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, effectLabels, logLines} =
+ await duplicateEffects({
+ input: fileContents,
+ effects: fileItems.map((item) => ({
+ sequenceNodePath: item.sequenceNodePath.nodePath,
+ effectIndex: item.effectIndex,
+ })),
+ });
+
+ return {
+ absolutePath,
+ fileRelativeToRoot,
+ fileContents,
+ output,
+ formatted,
+ effectLabels,
+ logLine: Math.min(...logLines),
+ };
+ }),
+ );
+
+ for (const update of updates) {
+ const duplicatedEffectDescription = getDuplicatedEffectDescription(
+ update.effectLabels,
+ );
+
+ pushToUndoStack({
+ filePath: update.absolutePath,
+ oldContents: update.fileContents,
+ newContents: null,
+ logLevel,
+ remotionRoot,
+ logLine: update.logLine,
+ description: {
+ undoMessage: `↩️ Duplication of ${duplicatedEffectDescription}`,
+ redoMessage: `↪️ Duplication of ${duplicatedEffectDescription}`,
+ },
+ entryType: 'duplicate-effect',
+ suppressHmrOnFileRestore: false,
+ });
+ suppressUndoStackInvalidation(update.absolutePath);
+ writeFileAndNotifyFileWatchers(
+ update.absolutePath,
+ update.output,
+ undefined,
+ );
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: update.absolutePath,
+ line: update.logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Duplicated ${attrName(duplicatedEffectDescription)}`,
+ );
+ if (!update.formatted) {
+ warnAboutPrettierOnce(logLevel);
+ }
+
+ RenderInternals.Log.verbose(
+ {indent: false, logLevel},
+ `[duplicate-effect] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,
+ );
+ }
+
+ printUndoHint(logLevel);
+
+ return {
+ success: true,
+ };
+ } catch (err) {
+ return {
+ success: false,
+ reason: (err as Error).message,
+ stack: (err as Error).stack as string,
+ };
+ }
+};
diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.ts
index 0702239575..ed9a21e9b3 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -27,6 +27,7 @@ type UndoEntryType =
| 'keyframe-delete'
| 'add-effect'
| 'delete-effect'
+ | 'duplicate-effect'
| 'paste-effects'
| 'reorder-effect'
| 'reorder-sequence'
@@ -64,6 +65,7 @@ type UndoEntry = {
| {entryType: 'keyframe-delete'}
| {entryType: 'add-effect'}
| {entryType: 'delete-effect'}
+ | {entryType: 'duplicate-effect'}
| {entryType: 'paste-effects'}
| {entryType: 'reorder-effect'}
| {entryType: 'reorder-sequence'}
diff --git a/packages/studio-server/src/test/duplicate-effect.test.ts b/packages/studio-server/src/test/duplicate-effect.test.ts
new file mode 100644
index 0000000000..cc5b650ee8
--- /dev/null
+++ b/packages/studio-server/src/test/duplicate-effect.test.ts
@@ -0,0 +1,97 @@
+import {expect, test} from 'bun:test';
+import {duplicateEffect, duplicateEffects} from '../codemods/duplicate-effect';
+import {lineColumnToNodePath} from './test-utils';
+
+const buildInput = (
+ effects: string,
+) => `import {HtmlInCanvas} from '@remotion/html-in-canvas';
+import {blur} from '@remotion/effects/blur';
+import {brightness} from '@remotion/effects/brightness';
+import {tint} from '@remotion/effects/tint';
+
+export const Comp = () => {
+ return (
+ <HtmlInCanvas effects={${effects}}>
+ hi
+ </HtmlInCanvas>
+ );
+};
+`;
+
+test('duplicateEffect clones the targeted effect after itself', async () => {
+ const input = buildInput(
+ '[blur({radius: 5}), tint({color: "red"}), brightness({amount: 2})]',
+ );
+ const {output, effectLabel} = await duplicateEffect({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 8),
+ effectIndex: 1,
+ });
+
+ expect(effectLabel).toBe('tint()');
+ expect(output.indexOf('blur({')).toBeLessThan(output.indexOf('tint({'));
+ expect(output.match(/tint\(\{\s*color: ['"]red['"],?\s*\}\)/g)).toHaveLength(
+ 2,
+ );
+ expect(output.lastIndexOf('tint({')).toBeLessThan(
+ output.indexOf('brightness({'),
+ );
+});
+
+test('duplicateEffects clones multiple targeted effects in one pass', async () => {
+ const input = buildInput(
+ '[blur({radius: 5}), tint({color: "red"}), brightness({amount: 2})]',
+ );
+ const {output, effectLabels} = await duplicateEffects({
+ input,
+ effects: [
+ {
+ sequenceNodePath: lineColumnToNodePath(input, 8),
+ effectIndex: 0,
+ },
+ {
+ sequenceNodePath: lineColumnToNodePath(input, 8),
+ effectIndex: 2,
+ },
+ ],
+ });
+
+ expect(effectLabels).toEqual(['blur()', 'brightness()']);
+ expect(output.match(/blur\(\{\s*radius: 5,?\s*\}\)/g)).toHaveLength(2);
+ expect(output.match(/brightness\(\{\s*amount: 2,?\s*\}\)/g)).toHaveLength(2);
+ expect(output.indexOf('blur({')).toBeLessThan(output.indexOf('tint({'));
+ expect(output.indexOf('tint({')).toBeLessThan(output.indexOf('brightness({'));
+});
+
+test('duplicateEffect throws when effect index is out of range', async () => {
+ const input = buildInput('[tint({color: "red"})]');
+ await expect(
+ duplicateEffect({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 8),
+ effectIndex: 5,
+ }),
+ ).rejects.toThrow(/not-found/);
+});
+
+test('duplicateEffect throws when effects are not an inline array', async () => {
+ const input = buildInput('effects');
+ await expect(
+ duplicateEffect({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 8),
+ effectIndex: 0,
+ }),
+ ).rejects.toThrow(/not an array/);
+});
+
+test('duplicateEffect throws when the target effect is unsupported', async () => {
+ const input = buildInput('[tint({color: "red"}), ...effects]');
+ await expect(
+ duplicateEffect({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 8),
+ effectIndex: 1,
+ }),
+ ).rejects.toThrow(/not-call-expression/);
+});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index f21283a46d..9e780ae88e 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -389,6 +389,24 @@ export type ReorderEffectResponse =
stack: string;
};
+export type DuplicateEffectRequestItem = {
+ fileName: string;
+ sequenceNodePath: SequencePropsSubscriptionKey;
+ effectIndex: number;
+};
+
+export type DuplicateEffectRequest = DuplicateEffectRequestItem[];
+
+export type DuplicateEffectResponse =
+ | {
+ success: true;
+ }
+ | {
+ success: false;
+ reason: string;
+ stack: string;
+ };
+
export type ReorderSequencePosition = 'before' | 'after';
export type ReorderSequenceRequest = {
@@ -785,6 +803,10 @@ export type ApiRoutes = {
>;
'/api/add-effect': ReqAndRes<AddEffectRequest, AddEffectResponse>;
'/api/reorder-effect': ReqAndRes<ReorderEffectRequest, ReorderEffectResponse>;
+ '/api/duplicate-effect': ReqAndRes<
+ DuplicateEffectRequest,
+ DuplicateEffectResponse
+ >;
'/api/reorder-sequence': ReqAndRes<
ReorderSequenceRequest,
ReorderSequenceResponse
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 8b16762ba4..f12906ea38 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -35,6 +35,9 @@ export {
DeleteStaticFileResponse,
DownloadRemoteAssetRequest,
DownloadRemoteAssetResponse,
+ DuplicateEffectRequest,
+ DuplicateEffectRequestItem,
+ DuplicateEffectResponse,
DuplicateJsxNodeRequest,
DuplicateJsxNodeResponse,
InsertJsxElementRequest,
diff --git a/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.ts b/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.ts
index 496d2ce03e..6a17be4590 100644
--- a/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.ts
+++ b/packages/studio/src/components/Timeline/duplicate-selected-timeline-item.ts
@@ -92,6 +92,44 @@ export const isDuplicatableSequenceRowSelection = (
type: 'sequence';
} => selection.type === 'sequence';
+export const isDuplicatableEffectSelection = (
+ selection: TimelineSelection,
+): selection is TimelineSelection & {
+ type: 'sequence-effect';
+} => selection.type === 'sequence-effect';
+
+const duplicateEffectsFromSource = (
+ effects: readonly (TimelineSelection & {type: 'sequence-effect'})[],
+): Promise<void> => {
+ return callApi(
+ '/api/duplicate-effect',
+ effects.map((effect) => {
+ const nodePath = effect.nodePathInfo.sequenceSubscriptionKey;
+
+ return {
+ fileName: nodePath.absolutePath,
+ sequenceNodePath: nodePath,
+ effectIndex: effect.i,
+ };
+ }),
+ )
+ .then((result) => {
+ if (result.success) {
+ showNotification(
+ effects.length === 1
+ ? 'Duplicated effect in source file'
+ : 'Duplicated effects in source files',
+ 2000,
+ );
+ } else {
+ showNotification(result.reason, 4000);
+ }
+ })
+ .catch((err) => {
+ showNotification((err as Error).message, 4000);
+ });
+};
+
export const duplicateSelectedTimelineItems = ({
selections,
confirm,
@@ -102,12 +140,17 @@ export const duplicateSelectedTimelineItems = ({
const sequenceSelections = selections.filter(
isDuplicatableSequenceRowSelection,
);
- if (sequenceSelections.length === 0) {
+ if (sequenceSelections.length > 0) {
+ return duplicateSequencesFromSource(
+ sequenceSelections.map((selection) => selection.nodePathInfo),
+ confirm,
+ );
+ }
+
+ const effectSelections = selections.filter(isDuplicatableEffectSelection);
+ if (effectSelections.length === 0) {
return null;
}
- return duplicateSequencesFromSource(
- sequenceSelections.map((selection) => selection.nodePathInfo),
- confirm,
- );
+ return duplicateEffectsFromSource(effectSelections);
};
diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.ts
index 4276c78a6e..ed3cfcc5c3 100644
--- a/packages/studio/src/test/timeline-selection.test.ts
+++ b/packages/studio/src/test/timeline-selection.test.ts
@@ -48,7 +48,10 @@ import {
type SelectedOutlineScaleDragState,
} from '../components/SelectedOutlineOverlay';
import {deleteSelectedTimelineItems} from '../components/Timeline/delete-selected-timeline-item';
-import {isDuplicatableSequenceRowSelection} from '../components/Timeline/duplicate-selected-timeline-item';
+import {
+ isDuplicatableEffectSelection,
+ isDuplicatableSequenceRowSelection,
+} from '../components/Timeline/duplicate-selected-timeline-item';
import {getTimelinePropResetTargets} from '../components/Timeline/reset-selected-timeline-props';
import {
getEffectPropClipboardDataFromSelection,
@@ -1831,7 +1834,7 @@ test('Cmd+A selection only targets selectable timeline sequences', () => {
]);
});
-test('Cmd+D only duplicates selected timeline sequence rows', () => {
+test('Cmd+D duplicates selected timeline sequence and effect rows', () => {
const sequenceNodePathInfo = makeNodePathInfo(['body', 0], []);
const effectNodePathInfo = makeNodePathInfo(['body', 1], ['effects', '0']);
@@ -1855,6 +1858,28 @@ test('Cmd+D only duplicates selected timeline sequence rows', () => {
nodePathInfo: sequenceNodePathInfo,
},
]);
+
+ expect(
+ [
+ {type: 'sequence' as const, nodePathInfo: sequenceNodePathInfo},
+ {
+ type: 'sequence-effect' as const,
+ nodePathInfo: effectNodePathInfo,
+ i: 0,
+ },
+ {
+ type: 'keyframe' as const,
+ nodePathInfo: sequenceNodePathInfo,
+ frame: 12,
+ },
+ ].filter(isDuplicatableEffectSelection),
+ ).toEqual([
+ {
+ type: 'sequence-effect',
+ nodePathInfo: effectNodePathInfo,
+ i: 0,
+ },
+ ]);
});
test('Backspace reset targets multiple selected sequence props', () => {