Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Batch delete effects (#7872)

Jonny Burger233797f494d1
diff --git a/packages/studio-server/src/codemods/delete-effect.ts b/packages/studio-server/src/codemods/delete-effect.ts
index ca8f04eb51..beca88d8bb 100644
--- a/packages/studio-server/src/codemods/delete-effect.ts
+++ b/packages/studio-server/src/codemods/delete-effect.ts
@@ -1,9 +1,15 @@
-import type {ArrayExpression, Expression, JSXAttribute} from '@babel/types';
+import type {
+ ArrayExpression,
+ Expression,
+ JSXAttribute,
+ JSXSpreadAttribute,
+} 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 {
+ enumerateEffectArrayElements,
findEffectCallExpression,
findEffectsAttr,
} from './update-effect-props/update-effect-props';
@@ -21,47 +27,147 @@ const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
return expr;
};
-export const deleteEffect = async ({
+export type EffectDeletionTarget = {
+ sequenceNodePath: SequenceNodePath;
+} & (
+ | {
+ type: 'single-effect';
+ effectIndex: number;
+ }
+ | {
+ type: 'all-effects';
+ }
+);
+
+type EffectsArrayDeletion = {
+ jsxAttributes: Array<JSXAttribute | JSXSpreadAttribute>;
+ attr: JSXAttribute;
+ effectsArray: ArrayExpression;
+ allEffects: boolean;
+ effectIndices: Set<number>;
+ effectLabels: string[];
+ logLines: number[];
+};
+
+const getAllEffectLabels = (
+ effectsArray: ArrayExpression,
+ attr: JSXAttribute,
+): {effectLabels: string[]; logLines: number[]} => {
+ if (effectsArray.elements.length === 0) {
+ throw new Error('Cannot delete effect: no effects found');
+ }
+
+ const elements = enumerateEffectArrayElements(effectsArray);
+ return {
+ effectLabels: elements.map((effect) =>
+ effect.kind === 'call' ? `${effect.callee}()` : 'effect',
+ ),
+ logLines: elements.map((effect) =>
+ effect.kind === 'call'
+ ? (effect.node.loc?.start.line ?? attr.loc?.start.line ?? 1)
+ : (attr.loc?.start.line ?? 1),
+ ),
+ };
+};
+
+export const deleteEffects = async ({
input,
- sequenceNodePath,
- effectIndex,
+ effects,
prettierConfigOverride,
}: {
input: string;
- sequenceNodePath: SequenceNodePath;
- effectIndex: number;
+ effects: EffectDeletionTarget[];
prettierConfigOverride?: Record<string, unknown> | null;
}): Promise<{
output: string;
formatted: boolean;
- effectLabel: string;
- logLine: number;
+ effectLabels: string[];
+ logLines: number[];
}> => {
+ if (effects.length === 0) {
+ throw new Error('No effects were specified for deletion');
+ }
+
const ast = parseAst(input);
- const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
- if (!jsx) {
- throw new Error(
- 'Could not find a JSX element at the specified location to delete effect',
+ const deletionsByAttr = new Map<JSXAttribute, EffectsArrayDeletion>();
+
+ for (const effect of effects) {
+ const {sequenceNodePath} = effect;
+ const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
+ if (!jsx) {
+ throw new Error(
+ 'Could not find a JSX element at the specified location to delete 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 existingDeletion = deletionsByAttr.get(attr);
+ const deletion =
+ existingDeletion ??
+ ({
+ jsxAttributes: jsx.attributes,
+ attr,
+ effectsArray,
+ allEffects: false,
+ effectIndices: new Set<number>(),
+ effectLabels: [],
+ logLines: [],
+ } satisfies EffectsArrayDeletion);
+
+ deletionsByAttr.set(attr, deletion);
+
+ if (effect.type === 'all-effects') {
+ const {effectLabels, logLines} = getAllEffectLabels(effectsArray, attr);
+ deletion.allEffects = true;
+ deletion.effectIndices.clear();
+ deletion.effectLabels = effectLabels;
+ deletion.logLines = logLines;
+ continue;
+ }
+
+ const {effectIndex} = effect;
+ if (deletion.allEffects || deletion.effectIndices.has(effectIndex)) {
+ continue;
+ }
+
+ const found = findEffectCallExpression({attr, effectIndex});
+ if (found.kind === 'error') {
+ throw new Error(`Cannot delete effect: ${found.reason}`);
+ }
+
+ deletion.effectIndices.add(effectIndex);
+ deletion.effectLabels.push(`${found.callee}()`);
+ deletion.logLines.push(
+ found.call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
);
}
- const attr = findEffectsAttr(jsx.attributes ?? []);
- if (!attr) {
- throw new Error('Could not find effects on the target JSX element');
- }
+ for (const deletion of deletionsByAttr.values()) {
+ if (deletion.allEffects) {
+ const attrIndex = deletion.jsxAttributes.indexOf(deletion.attr);
+ if (attrIndex !== -1) {
+ deletion.jsxAttributes.splice(attrIndex, 1);
+ }
- const effectsArray = getEffectsArray(attr);
- const found = findEffectCallExpression({attr, effectIndex});
- if (found.kind === 'error') {
- throw new Error(`Cannot delete effect: ${found.reason}`);
- }
+ continue;
+ }
- effectsArray.elements.splice(effectIndex, 1);
+ for (const effectIndex of [...deletion.effectIndices].sort(
+ (a, b) => b - a,
+ )) {
+ deletion.effectsArray.elements.splice(effectIndex, 1);
+ }
- if (effectsArray.elements.length === 0) {
- const attrIndex = jsx.attributes.indexOf(attr);
- if (attrIndex !== -1) {
- jsx.attributes.splice(attrIndex, 1);
+ if (deletion.effectsArray.elements.length === 0) {
+ const attrIndex = deletion.jsxAttributes.indexOf(deletion.attr);
+ if (attrIndex !== -1) {
+ deletion.jsxAttributes.splice(attrIndex, 1);
+ }
}
}
@@ -74,7 +180,41 @@ export const deleteEffect = async ({
return {
output,
formatted,
- effectLabel: `${found.callee}()`,
- logLine: found.call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
+ effectLabels: [...deletionsByAttr.values()].flatMap(
+ (deletion) => deletion.effectLabels,
+ ),
+ logLines: [...deletionsByAttr.values()].flatMap(
+ (deletion) => deletion.logLines,
+ ),
+ };
+};
+
+export const deleteEffect = 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 deleteEffects({
+ input,
+ effects: [{type: 'single-effect', sequenceNodePath, effectIndex}],
+ prettierConfigOverride,
+ });
+
+ return {
+ output,
+ formatted,
+ effectLabel: effectLabels[0],
+ logLine: logLines[0],
};
};
diff --git a/packages/studio-server/src/preview-server/routes/delete-effect.ts b/packages/studio-server/src/preview-server/routes/delete-effect.ts
index ef4b766ed3..8b1bc829ba 100644
--- a/packages/studio-server/src/preview-server/routes/delete-effect.ts
+++ b/packages/studio-server/src/preview-server/routes/delete-effect.ts
@@ -4,7 +4,7 @@ import type {
DeleteEffectRequest,
DeleteEffectResponse,
} from '@remotion/studio-shared';
-import {deleteEffect} from '../../codemods/delete-effect';
+import {deleteEffects} from '../../codemods/delete-effect';
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
@@ -17,66 +17,118 @@ import {
import {strikeThroughOrRemovedPrefix} from './log-updates/formatting';
import {warnAboutPrettierOnce} from './log-updates/log-update';
+const getDeletedEffectDescription = (effectLabels: string[]): string => {
+ if (effectLabels.length === 1) {
+ return effectLabels[0];
+ }
+
+ return `${effectLabels.length} effects`;
+};
+
export const deleteEffectHandler: ApiHandler<
DeleteEffectRequest,
DeleteEffectResponse
-> = async ({
- input: {fileName, sequenceNodePath, effectIndex},
- remotionRoot,
- logLevel,
-}) => {
+> = async ({input: effects, remotionRoot, logLevel}) => {
try {
+ if (effects.length === 0) {
+ throw new Error('No effects were specified for deletion');
+ }
+
RenderInternals.Log.trace(
{indent: false, logLevel},
- `[delete-effect] Received request for fileName="${fileName}" effectIndex=${effectIndex}`,
+ `[delete-effect] Received request to delete ${effects.length} effect target${effects.length === 1 ? '' : 's'}`,
);
- const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({
- remotionRoot,
- fileName,
- action: 'modify',
- });
- const fileContents = readFileSync(absolutePath, 'utf-8');
- const {output, formatted, effectLabel, logLine} = await deleteEffect({
- input: fileContents,
- sequenceNodePath: sequenceNodePath.nodePath,
- effectIndex,
- });
+ 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);
+ }
- pushToUndoStack({
- filePath: absolutePath,
- oldContents: fileContents,
- logLevel,
- remotionRoot,
- logLine,
- description: {
- undoMessage: `↩️ Deletion of ${effectLabel}`,
- redoMessage: `↪️ Deletion of ${effectLabel}`,
- },
- entryType: 'delete-effect',
- suppressHmrOnFileRestore: false,
- });
- suppressUndoStackInvalidation(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, undefined);
+ const updates = await Promise.all(
+ [...itemsByFileName.entries()].map(async ([fileName, fileItems]) => {
+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({
+ remotionRoot,
+ fileName,
+ action: 'modify',
+ });
- const locationLabel = formatLogFileLocation({
- remotionRoot,
- absolutePath,
- line: logLine,
- });
- RenderInternals.Log.info(
- {indent: false, logLevel},
- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} ${strikeThroughOrRemovedPrefix(effectLabel)}`,
- );
- if (!formatted) {
- warnAboutPrettierOnce(logLevel);
- }
+ const fileContents = readFileSync(absolutePath, 'utf-8');
+ const {output, formatted, effectLabels, logLines} = await deleteEffects(
+ {
+ input: fileContents,
+ effects: fileItems.map((item) =>
+ item.type === 'single-effect'
+ ? {
+ type: 'single-effect',
+ sequenceNodePath: item.sequenceNodePath.nodePath,
+ effectIndex: item.effectIndex,
+ }
+ : {
+ type: 'all-effects',
+ sequenceNodePath: item.sequenceNodePath.nodePath,
+ },
+ ),
+ },
+ );
- RenderInternals.Log.verbose(
- {indent: false, logLevel},
- `[delete-effect] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,
+ return {
+ absolutePath,
+ fileRelativeToRoot,
+ fileContents,
+ output,
+ formatted,
+ effectLabels,
+ logLine: Math.min(...logLines),
+ };
+ }),
);
+ for (const update of updates) {
+ const deletedEffectDescription = getDeletedEffectDescription(
+ update.effectLabels,
+ );
+
+ pushToUndoStack({
+ filePath: update.absolutePath,
+ oldContents: update.fileContents,
+ logLevel,
+ remotionRoot,
+ logLine: update.logLine,
+ description: {
+ undoMessage: `↩️ Deletion of ${deletedEffectDescription}`,
+ redoMessage: `↪️ Deletion of ${deletedEffectDescription}`,
+ },
+ entryType: 'delete-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}`)} ${strikeThroughOrRemovedPrefix(deletedEffectDescription)}`,
+ );
+ if (!update.formatted) {
+ warnAboutPrettierOnce(logLevel);
+ }
+
+ RenderInternals.Log.verbose(
+ {indent: false, logLevel},
+ `[delete-effect] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,
+ );
+ }
+
printUndoHint(logLevel);
return {
diff --git a/packages/studio-server/src/test/delete-effect.test.ts b/packages/studio-server/src/test/delete-effect.test.ts
index 8caa92e184..7569ebc2f7 100644
--- a/packages/studio-server/src/test/delete-effect.test.ts
+++ b/packages/studio-server/src/test/delete-effect.test.ts
@@ -1,5 +1,5 @@
import {expect, test} from 'bun:test';
-import {deleteEffect} from '../codemods/delete-effect';
+import {deleteEffect, deleteEffects} from '../codemods/delete-effect';
import {lineColumnToNodePath} from './test-utils';
const buildInput = (
@@ -46,6 +46,53 @@ test('deleteEffect removes the targeted effect by index', async () => {
expect(output).toContain('effects={[');
});
+test('deleteEffects removes multiple targeted effects in one pass', async () => {
+ const input = buildInput(
+ '[tint({color: "red"}), tint({color: "green"}), tint({color: "blue"})]',
+ );
+ const {output, effectLabels} = await deleteEffects({
+ input,
+ effects: [
+ {
+ type: 'single-effect',
+ sequenceNodePath: lineColumnToNodePath(input, 6),
+ effectIndex: 0,
+ },
+ {
+ type: 'single-effect',
+ sequenceNodePath: lineColumnToNodePath(input, 6),
+ effectIndex: 2,
+ },
+ ],
+ });
+
+ expect(effectLabels).toEqual(['tint()', 'tint()']);
+ expect(output).not.toMatch(/color: ['"]red['"]/);
+ expect(output).toMatch(/color: ['"]green['"]/);
+ expect(output).not.toMatch(/color: ['"]blue['"]/);
+ expect(output).toContain('effects={[');
+});
+
+test('deleteEffects removes all effects from the target sequence', async () => {
+ const input = buildInput(
+ '[tint({color: "red"}), tint({color: "green"}), tint({color: "blue"})]',
+ );
+ const {output, effectLabels} = await deleteEffects({
+ input,
+ effects: [
+ {
+ type: 'all-effects',
+ sequenceNodePath: lineColumnToNodePath(input, 6),
+ },
+ ],
+ });
+
+ expect(effectLabels).toEqual(['tint()', 'tint()', 'tint()']);
+ expect(output).not.toContain('effects=');
+ expect(output).not.toContain('tint(');
+ expect(output).toContain('<HtmlInCanvas>');
+});
+
test('deleteEffect keeps the effects prop when other effects remain', async () => {
const input = buildInput('[tint({color: "red"}), tint({color: "green"})]');
const {output} = await deleteEffect({
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 034fa0ec51..99b1d55381 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -329,12 +329,22 @@ export type AddEffectKeyframeRequest = {
export type AddEffectKeyframeResponse = SaveEffectPropsResponse;
-export type DeleteEffectRequest = {
+type BaseDeleteEffectRequestItem = {
fileName: string;
sequenceNodePath: SequencePropsSubscriptionKey;
- effectIndex: number;
};
+export type DeleteEffectRequestItem =
+ | (BaseDeleteEffectRequestItem & {
+ type: 'single-effect';
+ effectIndex: number;
+ })
+ | (BaseDeleteEffectRequestItem & {
+ type: 'all-effects';
+ });
+
+export type DeleteEffectRequest = DeleteEffectRequestItem[];
+
export type DeleteEffectResponse =
| {
success: true;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index aa2771947e..f7a87ec681 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -18,6 +18,7 @@ export {
DeleteEffectKeyframeRequest,
DeleteEffectKeyframeResponse,
DeleteEffectRequest,
+ DeleteEffectRequestItem,
DeleteEffectResponse,
DeleteJsxNodeRequest,
DeleteJsxNodeRequestItem,
diff --git a/packages/studio/src/components/Timeline/TimelineEffectItem.tsx b/packages/studio/src/components/Timeline/TimelineEffectItem.tsx
index 62ec8e94aa..283b38b28e 100644
--- a/packages/studio/src/components/Timeline/TimelineEffectItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineEffectItem.tsx
@@ -95,11 +95,14 @@ export const TimelineEffectItem: React.FC<{
}
try {
- const result = await callApi('/api/delete-effect', {
- fileName: validatedLocation.source,
- sequenceNodePath: nodePath,
- effectIndex,
- });
+ const result = await callApi('/api/delete-effect', [
+ {
+ type: 'single-effect',
+ fileName: validatedLocation.source,
+ sequenceNodePath: nodePath,
+ effectIndex,
+ },
+ ]);
if (result.success) {
showNotification('Removed effect from source file', 2000);
} else {
diff --git a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts b/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts
index 0d02d50374..056b29c164 100644
--- a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts
+++ b/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts
@@ -67,20 +67,52 @@ const deleteSequences = (
});
};
-const deleteEffect = (
- nodePathInfo: SequenceNodePathInfo,
- effectIndex: number,
+const deleteEffects = (
+ effects: ({
+ nodePathInfo: SequenceNodePathInfo;
+ } & (
+ | {
+ type: 'single-effect';
+ effectIndex: number;
+ }
+ | {
+ type: 'all-effects';
+ }
+ ))[],
): Promise<void> => {
- const nodePath = nodePathInfo.sequenceSubscriptionKey;
+ if (effects.length === 0) {
+ return Promise.resolve();
+ }
- return callApi('/api/delete-effect', {
- fileName: nodePath.absolutePath,
- sequenceNodePath: nodePath,
- effectIndex,
- })
+ return callApi(
+ '/api/delete-effect',
+ effects.map((effect) => {
+ const nodePath = effect.nodePathInfo.sequenceSubscriptionKey;
+ return effect.type === 'single-effect'
+ ? {
+ type: 'single-effect',
+ fileName: nodePath.absolutePath,
+ sequenceNodePath: nodePath,
+ effectIndex: effect.effectIndex,
+ }
+ : {
+ type: 'all-effects',
+ fileName: nodePath.absolutePath,
+ sequenceNodePath: nodePath,
+ };
+ }),
+ )
.then((result) => {
if (result.success) {
- showNotification('Removed effect from source file', 2000);
+ const singleEffect = effects[0];
+ showNotification(
+ effects.length === 1 && singleEffect?.type === 'single-effect'
+ ? 'Removed effect from source file'
+ : effects.length === 1
+ ? 'Removed effects from source file'
+ : 'Removed effects from source files',
+ 2000,
+ );
} else {
showNotification(result.reason, 4000);
}
@@ -118,11 +150,20 @@ export const deleteSelectedTimelineItem = ({
case 'sequence':
return deleteSequences([selection.nodePathInfo]);
case 'sequence-effect':
- return deleteEffect(selection.nodePathInfo, selection.i);
+ return deleteEffects([
+ {
+ type: 'single-effect',
+ nodePathInfo: selection.nodePathInfo,
+ effectIndex: selection.i,
+ },
+ ]);
case 'sequence-prop':
- case 'sequence-all-effects':
case 'sequence-effect-prop':
return null;
+ case 'sequence-all-effects':
+ return deleteEffects([
+ {type: 'all-effects', nodePathInfo: selection.nodePathInfo},
+ ]);
default:
throw new Error(
`Unexpected timeline selection type: ${selection satisfies never}`,
@@ -142,6 +183,12 @@ const isSequenceEffectSelection = (
type: 'sequence-effect';
} => selection.type === 'sequence-effect';
+const isSequenceAllEffectsSelection = (
+ selection: TimelineSelection,
+): selection is TimelineSelection & {
+ type: 'sequence-all-effects';
+} => selection.type === 'sequence-all-effects';
+
const isKeyframeSelection = (
selection: TimelineSelection,
): selection is TimelineSelection & {
@@ -193,13 +240,13 @@ export const deleteSelectedTimelineItems = ({
.map((selection) => selection.nodePathInfo),
);
case 'sequence-effect':
- return Promise.all(
- selections
- .filter(isSequenceEffectSelection)
- .map((selection) =>
- deleteEffect(selection.nodePathInfo, selection.i),
- ),
- ).then(() => undefined);
+ return deleteEffects(
+ selections.filter(isSequenceEffectSelection).map((selection) => ({
+ type: 'single-effect',
+ nodePathInfo: selection.nodePathInfo,
+ effectIndex: selection.i,
+ })),
+ );
case 'keyframe': {
const deletePromises = selections
.filter(isKeyframeSelection)
@@ -223,9 +270,15 @@ export const deleteSelectedTimelineItems = ({
}
case 'sequence-prop':
- case 'sequence-all-effects':
case 'sequence-effect-prop':
return null;
+ case 'sequence-all-effects':
+ return deleteEffects(
+ selections.filter(isSequenceAllEffectsSelection).map((selection) => ({
+ type: 'all-effects',
+ nodePathInfo: selection.nodePathInfo,
+ })),
+ );
default:
throw new Error(
`Unexpected timeline selection type: ${firstSelection satisfies never}`,