🎥 Make videos programmatically with React
@remotion/studio: Support batch sequence deletion (#7822)
Jonny Burgerc151e0b17ab6
diff --git a/packages/studio-server/src/codemods/delete-jsx-node.ts b/packages/studio-server/src/codemods/delete-jsx-node.tsindex 022aedcea9..0e9f54637e 100644--- a/packages/studio-server/src/codemods/delete-jsx-node.ts+++ b/packages/studio-server/src/codemods/delete-jsx-node.ts@@ -408,36 +408,48 @@ export const deleteJsxElementAtPath = (jsxPath.replace(b.nullLiteral());};-export const deleteJsxNode = async ({+export const deleteJsxNodes = async ({input,- nodePath,+ nodePaths,prettierConfigOverride,}: {input: string;- nodePath: SequenceNodePath;+ nodePaths: SequenceNodePath[];prettierConfigOverride?: Record<string, unknown> | null;}): Promise<{output: string;formatted: boolean;- nodeLabel: string;- logLine: number;+ nodeLabels: string[];+ logLines: number[];}> => {- const ast = parseAst(input);- const jsxPath = findJsxElementPathForDeletion(ast, nodePath);- if (!jsxPath) {- throw new Error(- 'Could not find a JSX element at the specified location to delete',- );+ if (nodePaths.length === 0) {+ throw new Error('No JSX nodes were specified for deletion');}- const jsxElement = jsxPath.node as JSXElement;- const nodeLabel = getJsxElementTagLabel(jsxElement);- const logLine =- jsxElement.openingElement.loc?.start.line ??- jsxElement.loc?.start.line ??- 1;+ const ast = parseAst(input);+ const pathsToDelete = nodePaths.map((nodePath) => {+ const jsxPath = findJsxElementPathForDeletion(ast, nodePath);+ if (!jsxPath) {+ throw new Error(+ 'Could not find a JSX element at the specified location to delete',+ );+ }++ const jsxElement = jsxPath.node as JSXElement;- deleteJsxElementAtPath(jsxPath);+ return {+ jsxPath,+ nodeLabel: getJsxElementTagLabel(jsxElement),+ logLine:+ jsxElement.openingElement.loc?.start.line ??+ jsxElement.loc?.start.line ??+ 1,+ };+ });++ for (const {jsxPath} of pathsToDelete) {+ deleteJsxElementAtPath(jsxPath);+ }const finalFile = serializeAst(ast);const {output, formatted} = await formatFileContent({@@ -448,7 +460,35 @@ export const deleteJsxNode = async ({return {output,formatted,- nodeLabel,- logLine,+ nodeLabels: pathsToDelete.map(({nodeLabel}) => nodeLabel),+ logLines: pathsToDelete.map(({logLine}) => logLine),+ };+};++export const deleteJsxNode = async ({+ input,+ nodePath,+ prettierConfigOverride,+}: {+ input: string;+ nodePath: SequenceNodePath;+ prettierConfigOverride?: Record<string, unknown> | null;+}): Promise<{+ output: string;+ formatted: boolean;+ nodeLabel: string;+ logLine: number;+}> => {+ const {output, formatted, nodeLabels, logLines} = await deleteJsxNodes({+ input,+ nodePaths: [nodePath],+ prettierConfigOverride,+ });++ return {+ output,+ formatted,+ nodeLabel: nodeLabels[0],+ logLine: logLines[0],};};diff --git a/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts b/packages/studio-server/src/preview-server/routes/delete-jsx-node.tsindex 5a5645630b..b4f6f7d88a 100644--- a/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts+++ b/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts@@ -4,7 +4,7 @@ import type {DeleteJsxNodeRequest,DeleteJsxNodeResponse,} from '@remotion/studio-shared';-import {deleteJsxNode} from '../../codemods/delete-jsx-node';+import {deleteJsxNodes} from '../../codemods/delete-jsx-node';import {writeFileAndNotifyFileWatchers} from '../../file-watcher';import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';import type {ApiHandler} from '../api-types';@@ -16,62 +16,106 @@ import {} from '../undo-stack';import {warnAboutPrettierOnce} from './log-updates/log-update';+const getDeletedNodeDescription = (nodeLabels: string[]): string => {+ if (nodeLabels.length === 1) {+ return nodeLabels[0];+ }++ return `${nodeLabels.length} JSX nodes`;+};+export const deleteJsxNodeHandler: ApiHandler<DeleteJsxNodeRequest,DeleteJsxNodeResponse-> = async ({input: {fileName, nodePath}, remotionRoot, logLevel}) => {+> = async ({input: {nodes}, remotionRoot, logLevel}) => {try {+ if (nodes.length === 0) {+ throw new Error('No JSX nodes were specified for deletion');+ }+RenderInternals.Log.trace({indent: false, logLevel},- `[delete-jsx-node] Received request for fileName="${fileName}"`,+ `[delete-jsx-node] Received request to delete ${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 {output, formatted, nodeLabel, logLine} = await deleteJsxNode({- input: fileContents,- nodePath,- });+ const updates = await Promise.all(+ [...itemsByFileName.entries()].map(async ([fileName, fileItems]) => {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });- pushToUndoStack({- filePath: absolutePath,- oldContents: fileContents,- logLevel,- remotionRoot,- logLine,- description: {- undoMessage: `↩️ Deletion of ${nodeLabel}`,- redoMessage: `↪️ Deletion of ${nodeLabel}`,- },- entryType: 'delete-jsx-node',- suppressHmrOnFileRestore: false,- });- suppressUndoStackInvalidation(absolutePath);- writeFileAndNotifyFileWatchers(absolutePath, output, undefined);+ const fileContents = readFileSync(absolutePath, 'utf-8');- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath,- line: logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Deleted ${nodeLabel}`,- );- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }+ const {output, formatted, nodeLabels, logLines} = await deleteJsxNodes({+ input: fileContents,+ nodePaths: fileItems.map((item) => item.nodePath),+ });- RenderInternals.Log.verbose(- {indent: false, logLevel},- `[delete-jsx-node] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,+ return {+ absolutePath,+ fileRelativeToRoot,+ fileContents,+ output,+ formatted,+ nodeLabels,+ logLine: Math.min(...logLines),+ };+ }),);+ for (const update of updates) {+ const deletedNodeDescription = getDeletedNodeDescription(+ update.nodeLabels,+ );++ pushToUndoStack({+ filePath: update.absolutePath,+ oldContents: update.fileContents,+ logLevel,+ remotionRoot,+ logLine: update.logLine,+ description: {+ undoMessage: `↩️ Deletion of ${deletedNodeDescription}`,+ redoMessage: `↪️ Deletion of ${deletedNodeDescription}`,+ },+ entryType: 'delete-jsx-node',+ 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}`)} Deleted ${deletedNodeDescription}`,+ );+ if (!update.formatted) {+ warnAboutPrettierOnce(logLevel);+ }++ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[delete-jsx-node] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,+ );+ }+printUndoHint(logLevel);return {diff --git a/packages/studio-server/src/test/delete-jsx-node.test.ts b/packages/studio-server/src/test/delete-jsx-node.test.tsindex 378e2aae96..dcc7007eb3 100644--- a/packages/studio-server/src/test/delete-jsx-node.test.ts+++ b/packages/studio-server/src/test/delete-jsx-node.test.ts@@ -1,5 +1,5 @@import {expect, test} from 'bun:test';-import {deleteJsxNode} from '../codemods/delete-jsx-node';+import {deleteJsxNode, deleteJsxNodes} from '../codemods/delete-jsx-node';import {lineColumnToNodePath} from './test-utils';const sample = `import React from 'react';@@ -97,3 +97,33 @@ test('deleteJsxNode replaces JSX inside map callback', async () => {expect(output).not.toContain('<div');expect(output).toMatch(/=>\s*\(?\s*null/);});++const multipleSiblings = `import React from 'react';+import {AbsoluteFill} from 'remotion';++export const X: React.FC = () => {+ return (+ <AbsoluteFill>+ <div />+ <span />+ <p />+ </AbsoluteFill>+ );+};+`;++test('deleteJsxNodes removes multiple JSX children in one transform', async () => {+ const {output, nodeLabels, logLines} = await deleteJsxNodes({+ input: multipleSiblings,+ nodePaths: [+ lineColumnToNodePath(multipleSiblings, 7),+ lineColumnToNodePath(multipleSiblings, 8),+ ],+ });++ expect(output).not.toContain('<div');+ expect(output).not.toContain('<span');+ expect(output).toContain('<p');+ expect(nodeLabels).toEqual(['<div>', '<span>']);+ expect(logLines).toEqual([7, 8]);+});diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex faa252d9d6..42afe554a2 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -10,16 +10,16 @@ import type {X264Preset,} from '@remotion/renderer';import type {HardwareAccelerationOption} from '@remotion/renderer/client';-import type {CannotUpdateSequenceReason} from 'remotion';import type {_InternalTypes,+ CannotUpdateSequenceReason,CanUpdateEffectPropsResponse,CanUpdateSequencePropsResponseFalse,CanUpdateSequencePropsResponseTrue,CanUpdateSequencePropStatus,- SequenceSchema,SequenceNodePath,SequencePropsSubscriptionKey,+ SequenceSchema,} from 'remotion';import type {RecastCodemod, VisualControlChange} from './codemods';import type {PackageManager} from './package-manager';@@ -320,11 +320,15 @@ export type DeleteEffectResponse =stack: string;};-export type DeleteJsxNodeRequest = {+export type DeleteJsxNodeRequestItem = {fileName: string;nodePath: SequenceNodePath;};+export type DeleteJsxNodeRequest = {+ nodes: DeleteJsxNodeRequestItem[];+};+export type DeleteJsxNodeResponse =| {success: true;diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 1c5471e8eb..85549d1e11 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -9,23 +9,21 @@ export {CanUpdateDefaultPropsResponse,CanUpdateSequencePropsRequest,CancelRenderRequest,- SubscribeToSequencePropsRequest,- SubscribeToSequencePropsResponse,- UnsubscribeFromSequencePropsRequest,CancelRenderResponse,CopyStillToClipboardRequest,- DeleteEffectRequest,- DeleteEffectResponse,DeleteEffectKeyframeRequest,DeleteEffectKeyframeResponse,- DeleteSequenceKeyframeRequest,- DeleteSequenceKeyframeResponse,+ DeleteEffectRequest,+ DeleteEffectResponse,DeleteJsxNodeRequest,+ DeleteJsxNodeRequestItem,DeleteJsxNodeResponse,- DuplicateJsxNodeRequest,- DuplicateJsxNodeResponse,+ DeleteSequenceKeyframeRequest,+ DeleteSequenceKeyframeResponse,DeleteStaticFileRequest,DeleteStaticFileResponse,+ DuplicateJsxNodeRequest,+ DuplicateJsxNodeResponse,InstallPackageRequest,InstallPackageResponse,OpenInFileExplorerRequest,@@ -45,10 +43,13 @@ export {SubscribeToDefaultPropsResponse,SubscribeToFileExistenceRequest,SubscribeToFileExistenceResponse,+ SubscribeToSequencePropsRequest,+ SubscribeToSequencePropsResponse,UndoRequest,UndoResponse,UnsubscribeFromDefaultPropsRequest,UnsubscribeFromFileExistenceRequest,+ UnsubscribeFromSequencePropsRequest,UpdateAvailableRequest,UpdateAvailableResponse,UpdateDefaultPropsRequest,@@ -58,8 +59,8 @@ export type {ApplyVisualControlCodemod, RecastCodemod} from './codemods';export {DEFAULT_BUFFER_STATE_DELAY_IN_MILLISECONDS} from './default-buffer-state-delay-in-milliseconds';export {EventSourceEvent} from './event-source-event';export {formatBytes} from './format-bytes';-export {getDefaultOutLocation} from './get-default-out-name';export {getAllSchemaKeys} from './get-all-keys';+export {getDefaultOutLocation} from './get-default-out-name';export {ErrorLocation,getLocationFromBuildError,@@ -131,5 +132,7 @@ export {} from './optimistic-delete-keyframe';export {optimisticUpdateForCodeValues} from './optimistic-update-for-code-values';export {optimisticUpdateForEffectCodeValues} from './optimistic-update-for-effect-code-values';-export {stringifySequenceSubscriptionKey} from './stringify-sequence-subscription-key';-export {stringifySequenceExpandedRowKey} from './stringify-sequence-subscription-key';+export {+ stringifySequenceExpandedRowKey,+ stringifySequenceSubscriptionKey,+} from './stringify-sequence-subscription-key';diff --git a/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsxindex 9c21579b1f..ac49ca747a 100644--- a/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx+++ b/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx@@ -3,7 +3,7 @@ import {useContext, useEffect} from 'react';import {Internals} from 'remotion';import {StudioServerConnectionCtx} from '../../helpers/client-id';import {useKeybinding} from '../../helpers/use-keybinding';-import {deleteSelectedTimelineItem} from './delete-selected-timeline-item';+import {deleteSelectedTimelineItems} from './delete-selected-timeline-item';import {useTimelineSelection} from './TimelineSelection';export const TimelineDeleteKeybindings: React.FC = () => {@@ -31,24 +31,20 @@ export const TimelineDeleteKeybindings: React.FC = () => {event: 'keydown',key: 'Backspace',callback: () => {- const deletePromises = currentSelection- .map((selection) =>- deleteSelectedTimelineItem({- selection,- sequences,- overrideIdsToNodePaths: overrideIdToNodePathMappings,- setCodeValues,- clientId,- }),- )- .filter((promise): promise is Promise<void> => promise !== null);+ const deletePromise = deleteSelectedTimelineItems({+ selections: currentSelection,+ sequences,+ overrideIdsToNodePaths: overrideIdToNodePathMappings,+ setCodeValues,+ clientId,+ });- if (deletePromises.length === 0) {+ if (deletePromise === null) {return;}clearSelection();- Promise.all(deletePromises).catch(() => undefined);+ deletePromise.catch(() => undefined);},commandCtrlKey: false,preventDefault: true,diff --git a/packages/studio/src/components/Timeline/TimelineListItem.tsx b/packages/studio/src/components/Timeline/TimelineListItem.tsxindex 8480e2bb5e..5ef04746ef 100644--- a/packages/studio/src/components/Timeline/TimelineListItem.tsx+++ b/packages/studio/src/components/Timeline/TimelineListItem.tsx@@ -143,8 +143,12 @@ export const TimelineListItem: React.FC<{try {const result = await callApi('/api/delete-jsx-node', {- fileName: validatedLocation.source,- nodePath: nodePath.nodePath,+ nodes: [+ {+ fileName: validatedLocation.source,+ nodePath: nodePath.nodePath,+ },+ ],});if (result.success) {showNotification('Removed sequence from source file', 2000);diff --git a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts b/packages/studio/src/components/Timeline/delete-selected-timeline-item.tsindex 24bcee5aa6..aaa7cbd485 100644--- a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts+++ b/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts@@ -6,27 +6,58 @@ import {deleteSelectedKeyframe} from './delete-selected-keyframe';import type {SetCodeValues} from './save-sequence-prop';import type {TimelineSelection} from './TimelineSelection';-const deleteSequence = (nodePathInfo: SequenceNodePathInfo): Promise<void> => {- const nodePath = nodePathInfo.sequenceSubscriptionKey;+const confirmDeletingDuplicatedSequences = (+ nodePathInfos: SequenceNodePathInfo[],+): boolean => {+ const duplicatedNodePathInfos = nodePathInfos.filter(+ (nodePathInfo) => nodePathInfo.numberOfSequencesWithThisNodePath > 1,+ );+ if (duplicatedNodePathInfos.length === 0) {+ return true;+ }- if (nodePathInfo.numberOfSequencesWithThisNodePath > 1) {- const message =+ if (duplicatedNodePathInfos.length === 1) {+ const [nodePathInfo] = duplicatedNodePathInfos;+ const singleDuplicatedSequenceMessage ='This sequence is programmatically duplicated ' +nodePathInfo.numberOfSequencesWithThisNodePath +' times in the code. Deleting removes all instances. Continue?';// eslint-disable-next-line no-alert -- native confirm before deleting all instances of a duplicated sequence- if (!window.confirm(message)) {- return Promise.resolve();- }+ return window.confirm(singleDuplicatedSequenceMessage);+ }++ const multipleDuplicatedSequencesMessage =+ duplicatedNodePathInfos.length ++ ' selected sequences are programmatically duplicated in the code. Deleting removes all instances. Continue?';+ // eslint-disable-next-line no-alert -- native confirm before deleting all instances of duplicated sequences+ return window.confirm(multipleDuplicatedSequencesMessage);+};++const deleteSequences = (+ nodePathInfos: SequenceNodePathInfo[],+): Promise<void> => {+ if (!confirmDeletingDuplicatedSequences(nodePathInfos)) {+ return Promise.resolve();}return callApi('/api/delete-jsx-node', {- fileName: nodePath.absolutePath,- nodePath: nodePath.nodePath,+ nodes: nodePathInfos.map((nodePathInfo) => {+ const nodePath = nodePathInfo.sequenceSubscriptionKey;++ return {+ fileName: nodePath.absolutePath,+ nodePath: nodePath.nodePath,+ };+ }),}).then((result) => {if (result.success) {- showNotification('Removed sequence from source file', 2000);+ showNotification(+ nodePathInfos.length === 1+ ? 'Removed sequence from source file'+ : 'Removed sequences from source files',+ 2000,+ );} else {showNotification(result.reason, 4000);}@@ -88,7 +119,7 @@ export const deleteSelectedTimelineItem = ({// The sequence track row itself has no auxiliary keys.if (auxiliaryKeys.length === 0) {- return deleteSequence(nodePathInfo);+ return deleteSequences([nodePathInfo]);}// An effect group row is ['effects', effectIndex].@@ -104,3 +135,52 @@ export const deleteSelectedTimelineItem = ({// Field rows and other intermediate rows are not deletable on their own.return null;};++const isSequenceRowSelection = (+ selection: TimelineSelection,+): selection is TimelineSelection & {+ type: 'row';+} =>+ selection.type === 'row' && selection.nodePathInfo.auxiliaryKeys.length === 0;++export const deleteSelectedTimelineItems = ({+ selections,+ sequences,+ overrideIdsToNodePaths,+ setCodeValues,+ clientId,+}: {+ selections: readonly TimelineSelection[];+ sequences: TSequence[];+ overrideIdsToNodePaths: OverrideIdToNodePaths;+ setCodeValues: SetCodeValues;+ clientId: string;+}): Promise<void> | null => {+ const sequenceSelections = selections.filter(isSequenceRowSelection);+ const deletePromises = selections+ .filter((selection) => !isSequenceRowSelection(selection))+ .map((selection) =>+ deleteSelectedTimelineItem({+ selection,+ sequences,+ overrideIdsToNodePaths,+ setCodeValues,+ clientId,+ }),+ )+ .filter((promise): promise is Promise<void> => promise !== null);++ if (sequenceSelections.length > 0) {+ deletePromises.push(+ deleteSequences(+ sequenceSelections.map((selection) => selection.nodePathInfo),+ ),+ );+ }++ if (deletePromises.length === 0) {+ return null;+ }++ return Promise.all(deletePromises).then(() => undefined);+};