Skip to content

🎥 Make videos programmatically with React

Untangle composition edit handlers

JonnyBurgerc20cc5d5be68
diff --git a/packages/studio-server/src/preview-server/routes/add-composition.ts b/packages/studio-server/src/preview-server/routes/add-composition.ts
index cb221ecef6..09b1237770 100644
--- a/packages/studio-server/src/preview-server/routes/add-composition.ts
+++ b/packages/studio-server/src/preview-server/routes/add-composition.ts
@@ -1,14 +1,117 @@
-import type {AddCompositionRequest} from '@remotion/studio-shared';
+import {existsSync, readFileSync} from 'node:fs';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ AddCompositionRequest,
+ CompositionEditResponse,
+} from '@remotion/studio-shared';
import {addCompositionToFile} from '../../codemods/add-composition-to-file';
-import {runCompositionEdit} from './run-composition-edit';
-
-export const addCompositionHandler = runCompositionEdit<AddCompositionRequest>({
- entryType: 'new-composition',
- getDescription: ({options}) => ({
- undoMessage: `↩️ Creation of composition "${options.newId}"`,
- redoMessage: `↪️ Creation of composition "${options.newId}"`,
- }),
- getLogMessage: ({options}) => `Created composition "${options.newId}"`,
- getResult: ({filePath, request}) =>
- addCompositionToFile({filePath, options: request.options}),
-});
+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 {getProjectInfo} from '../project-info';
+import {
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const addCompositionHandler: ApiHandler<
+ AddCompositionRequest,
+ CompositionEditResponse
+> = ({input: request, logLevel, remotionRoot, entryPoint}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ let filePath: string;
+ if (request.symbolicatedStack?.originalFileName) {
+ filePath = resolveFileInsideProject({
+ remotionRoot,
+ fileName: request.symbolicatedStack.originalFileName,
+ action: 'add a composition to',
+ }).absolutePath;
+ } else {
+ const {rootFile} = await getProjectInfo(remotionRoot, entryPoint);
+ if (rootFile === null) {
+ throw new Error('Cannot find the Remotion root file');
+ }
+
+ filePath = rootFile;
+ }
+
+ checkIfTypeScriptFile(filePath);
+ const result = await addCompositionToFile({
+ filePath,
+ options: request.options,
+ });
+ for (const change of result.changes) {
+ const currentContents = existsSync(change.filePath)
+ ? readFileSync(change.filePath, 'utf-8')
+ : null;
+ if (currentContents !== change.previousContents) {
+ throw new Error(
+ `Source changed before adding composition: ${change.filePath}`,
+ );
+ }
+ }
+
+ if (result.changes.length > 0) {
+ const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
+ pushTransactionToUndoStack({
+ snapshots: result.changes.map((change) => ({
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === filePath ? logLine : 1,
+ nodePathRemappings: null,
+ })),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Creation of composition "${request.options.newId}"`,
+ redoMessage: `↪️ Creation of composition "${request.options.newId}"`,
+ },
+ entryType: 'new-composition',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+
+ for (const change of result.changes) {
+ if (change.nextContents === null) {
+ throw new Error('Adding a composition cannot remove source files');
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: change.nextContents,
+ originatorClientId: undefined,
+ metadata: null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: filePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Created composition "${request.options.newId}"`,
+ );
+ printUndoHint(logLevel);
+ }
+
+ return {success: true, nodePathMutation: null};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ };
+ }
+ });
diff --git a/packages/studio-server/src/preview-server/routes/add-folder.ts b/packages/studio-server/src/preview-server/routes/add-folder.ts
index c2c67659fb..ed287f8a09 100644
--- a/packages/studio-server/src/preview-server/routes/add-folder.ts
+++ b/packages/studio-server/src/preview-server/routes/add-folder.ts
@@ -1,25 +1,125 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
import {addFolder} from '@remotion/codemods';
-import type {AddFolderRequest} from '@remotion/studio-shared';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ AddFolderRequest,
+ CompositionEditResponse,
+} from '@remotion/studio-shared';
+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 {getProjectInfo} from '../project-info';
import {
- getCompositionEditProject,
- runCompositionEdit,
-} from './run-composition-edit';
-
-export const addFolderHandler = runCompositionEdit<AddFolderRequest>({
- entryType: 'new-folder',
- getDescription: ({folderName, parentName}) => {
- const folderPath = parentName ? `${parentName}/${folderName}` : folderName;
- return {
- undoMessage: `↩️ Creation of folder "${folderPath}"`,
- redoMessage: `↪️ Creation of folder "${folderPath}"`,
- };
- },
- getLogMessage: ({folderName, parentName}) =>
- `Created folder "${parentName ? `${parentName}/${folderName}` : folderName}"`,
- getResult: ({filePath, request}) =>
- addFolder({
- project: getCompositionEditProject(filePath),
- compositionFile: filePath,
- folder: {name: request.folderName, parentName: request.parentName},
- }),
-});
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const addFolderHandler: ApiHandler<
+ AddFolderRequest,
+ CompositionEditResponse
+> = ({input: request, logLevel, remotionRoot, entryPoint}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ let filePath: string;
+ if (request.symbolicatedStack?.originalFileName) {
+ filePath = resolveFileInsideProject({
+ remotionRoot,
+ fileName: request.symbolicatedStack.originalFileName,
+ action: 'add a folder to',
+ }).absolutePath;
+ } else {
+ const {rootFile} = await getProjectInfo(remotionRoot, entryPoint);
+ if (rootFile === null) {
+ throw new Error('Cannot find the Remotion root file');
+ }
+
+ filePath = rootFile;
+ }
+
+ checkIfTypeScriptFile(filePath);
+ const result = addFolder({
+ project: {
+ files: {[filePath]: readFileSync(filePath, 'utf-8')},
+ rootDir: path.dirname(filePath),
+ },
+ compositionFile: filePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ });
+ for (const change of result.changes) {
+ const currentContents = existsSync(change.filePath)
+ ? readFileSync(change.filePath, 'utf-8')
+ : null;
+ if (currentContents !== change.previousContents) {
+ throw new Error(
+ `Source changed before adding folder: ${change.filePath}`,
+ );
+ }
+ }
+
+ if (result.changes.length > 0) {
+ const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
+ const folderPath = request.parentName
+ ? `${request.parentName}/${request.folderName}`
+ : request.folderName;
+ pushTransactionToUndoStack({
+ snapshots: result.changes.map((change) => ({
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === filePath ? logLine : 1,
+ nodePathRemappings: null,
+ })),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Creation of folder "${folderPath}"`,
+ redoMessage: `↪️ Creation of folder "${folderPath}"`,
+ },
+ entryType: 'new-folder',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+
+ for (const change of result.changes) {
+ if (change.nextContents === null) {
+ throw new Error('Adding a folder cannot remove source files');
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: change.nextContents,
+ originatorClientId: undefined,
+ metadata: null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: filePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Created folder "${folderPath}"`,
+ );
+ printUndoHint(logLevel);
+ }
+
+ return {success: true, nodePathMutation: null};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ };
+ }
+ });
diff --git a/packages/studio-server/src/preview-server/routes/delete-composition.ts b/packages/studio-server/src/preview-server/routes/delete-composition.ts
index 1addef6ace..2aed93c8eb 100644
--- a/packages/studio-server/src/preview-server/routes/delete-composition.ts
+++ b/packages/studio-server/src/preview-server/routes/delete-composition.ts
@@ -1,22 +1,124 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
import {deleteComposition} from '@remotion/codemods';
-import type {DeleteCompositionRequest} from '@remotion/studio-shared';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ CompositionEditResponse,
+ DeleteCompositionRequest,
+} from '@remotion/studio-shared';
+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 {getProjectInfo} from '../project-info';
import {
- getCompositionEditProject,
- runCompositionEdit,
-} from './run-composition-edit';
-
-export const deleteCompositionHandler =
- runCompositionEdit<DeleteCompositionRequest>({
- entryType: 'delete-composition',
- getDescription: ({idToDelete}) => ({
- undoMessage: `↩️ Deletion of composition "${idToDelete}"`,
- redoMessage: `↪️ Deletion of composition "${idToDelete}"`,
- }),
- getLogMessage: ({idToDelete}) => `Deleted composition "${idToDelete}"`,
- getResult: ({filePath, request}) =>
- deleteComposition({
- project: getCompositionEditProject(filePath),
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const deleteCompositionHandler: ApiHandler<
+ DeleteCompositionRequest,
+ CompositionEditResponse
+> = ({input: request, logLevel, remotionRoot, entryPoint}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ let filePath: string;
+ if (request.symbolicatedStack?.originalFileName) {
+ filePath = resolveFileInsideProject({
+ remotionRoot,
+ fileName: request.symbolicatedStack.originalFileName,
+ action: 'delete a composition from',
+ }).absolutePath;
+ } else {
+ const {rootFile} = await getProjectInfo(remotionRoot, entryPoint);
+ if (rootFile === null) {
+ throw new Error('Cannot find the Remotion root file');
+ }
+
+ filePath = rootFile;
+ }
+
+ checkIfTypeScriptFile(filePath);
+ const result = deleteComposition({
+ project: {
+ files: {[filePath]: readFileSync(filePath, 'utf-8')},
+ rootDir: path.dirname(filePath),
+ },
compositionFile: filePath,
compositionId: request.idToDelete,
- }),
+ });
+ for (const change of result.changes) {
+ const currentContents = existsSync(change.filePath)
+ ? readFileSync(change.filePath, 'utf-8')
+ : null;
+ if (currentContents !== change.previousContents) {
+ throw new Error(
+ `Source changed before deleting composition: ${change.filePath}`,
+ );
+ }
+ }
+
+ if (result.changes.length > 0) {
+ const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
+ pushTransactionToUndoStack({
+ snapshots: result.changes.map((change) => ({
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === filePath ? logLine : 1,
+ nodePathRemappings: null,
+ })),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Deletion of composition "${request.idToDelete}"`,
+ redoMessage: `↪️ Deletion of composition "${request.idToDelete}"`,
+ },
+ entryType: 'delete-composition',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+
+ for (const change of result.changes) {
+ if (change.nextContents === null) {
+ throw new Error(
+ 'Deleting a composition cannot remove source files',
+ );
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: change.nextContents,
+ originatorClientId: undefined,
+ metadata: null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: filePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Deleted composition "${request.idToDelete}"`,
+ );
+ printUndoHint(logLevel);
+ }
+
+ return {success: true, nodePathMutation: null};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ };
+ }
});
diff --git a/packages/studio-server/src/preview-server/routes/duplicate-composition.ts b/packages/studio-server/src/preview-server/routes/duplicate-composition.ts
index 84d6b8952f..6fba72c643 100644
--- a/packages/studio-server/src/preview-server/routes/duplicate-composition.ts
+++ b/packages/studio-server/src/preview-server/routes/duplicate-composition.ts
@@ -1,22 +1,55 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
import {duplicateComposition} from '@remotion/codemods';
-import type {DuplicateCompositionRequest} from '@remotion/studio-shared';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ CompositionEditResponse,
+ DuplicateCompositionRequest,
+} from '@remotion/studio-shared';
+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 {getProjectInfo} from '../project-info';
import {
- getCompositionEditProject,
- runCompositionEdit,
-} from './run-composition-edit';
-
-export const duplicateCompositionHandler =
- runCompositionEdit<DuplicateCompositionRequest>({
- entryType: 'duplicate-composition',
- getDescription: ({idToDuplicate, newId}) => ({
- undoMessage: `↩️ Duplication of composition "${idToDuplicate}" to "${newId}"`,
- redoMessage: `↪️ Duplication of composition "${idToDuplicate}" to "${newId}"`,
- }),
- getLogMessage: ({idToDuplicate, newId}) =>
- `Duplicated composition "${idToDuplicate}" to "${newId}"`,
- getResult: ({filePath, request}) =>
- duplicateComposition({
- project: getCompositionEditProject(filePath),
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const duplicateCompositionHandler: ApiHandler<
+ DuplicateCompositionRequest,
+ CompositionEditResponse
+> = ({input: request, logLevel, remotionRoot, entryPoint}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ let filePath: string;
+ if (request.symbolicatedStack?.originalFileName) {
+ filePath = resolveFileInsideProject({
+ remotionRoot,
+ fileName: request.symbolicatedStack.originalFileName,
+ action: 'duplicate a composition in',
+ }).absolutePath;
+ } else {
+ const {rootFile} = await getProjectInfo(remotionRoot, entryPoint);
+ if (rootFile === null) {
+ throw new Error('Cannot find the Remotion root file');
+ }
+
+ filePath = rootFile;
+ }
+
+ checkIfTypeScriptFile(filePath);
+ const result = duplicateComposition({
+ project: {
+ files: {[filePath]: readFileSync(filePath, 'utf-8')},
+ rootDir: path.dirname(filePath),
+ },
compositionFile: filePath,
compositionId: request.idToDuplicate,
newId: request.newId,
@@ -31,5 +64,73 @@ export const duplicateCompositionHandler =
? undefined
: (request.newDurationInFrames ?? undefined),
},
- }),
+ });
+ for (const change of result.changes) {
+ const currentContents = existsSync(change.filePath)
+ ? readFileSync(change.filePath, 'utf-8')
+ : null;
+ if (currentContents !== change.previousContents) {
+ throw new Error(
+ `Source changed before duplicating composition: ${change.filePath}`,
+ );
+ }
+ }
+
+ if (result.changes.length > 0) {
+ const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
+ pushTransactionToUndoStack({
+ snapshots: result.changes.map((change) => ({
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === filePath ? logLine : 1,
+ nodePathRemappings: null,
+ })),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Duplication of composition "${request.idToDuplicate}" to "${request.newId}"`,
+ redoMessage: `↪️ Duplication of composition "${request.idToDuplicate}" to "${request.newId}"`,
+ },
+ entryType: 'duplicate-composition',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+
+ for (const change of result.changes) {
+ if (change.nextContents === null) {
+ throw new Error(
+ 'Duplicating a composition cannot remove source files',
+ );
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: change.nextContents,
+ originatorClientId: undefined,
+ metadata: null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: filePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Duplicated composition "${request.idToDuplicate}" to "${request.newId}"`,
+ );
+ printUndoHint(logLevel);
+ }
+
+ return {success: true, nodePathMutation: null};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ };
+ }
});
diff --git a/packages/studio-server/src/preview-server/routes/move-composition.ts b/packages/studio-server/src/preview-server/routes/move-composition.ts
index 5b346dd641..b7ec602ad3 100644
--- a/packages/studio-server/src/preview-server/routes/move-composition.ts
+++ b/packages/studio-server/src/preview-server/routes/move-composition.ts
@@ -1,24 +1,168 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
import {moveComposition} from '@remotion/codemods';
-import type {MoveCompositionRequest} from '@remotion/studio-shared';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ CompositionEditResponse,
+ MoveCompositionRequest,
+} from '@remotion/studio-shared';
+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 {getProjectInfo} from '../project-info';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
- getCompositionEditProject,
- runCompositionEdit,
- toCodemodDestination,
-} from './run-composition-edit';
-
-export const moveCompositionHandler =
- runCompositionEdit<MoveCompositionRequest>({
- entryType: 'move-composition-or-folder',
- getDescription: ({compositionId}) => ({
- undoMessage: `↩️ Move of composition "${compositionId}"`,
- redoMessage: `↪️ Move of composition "${compositionId}"`,
- }),
- getLogMessage: ({compositionId}) => `Moved composition "${compositionId}"`,
- getResult: ({filePath, request}) =>
- moveComposition({
- project: getCompositionEditProject(filePath),
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const moveCompositionHandler: ApiHandler<
+ MoveCompositionRequest,
+ CompositionEditResponse
+> = ({input: request, logLevel, remotionRoot, entryPoint}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ let filePath: string;
+ if (request.symbolicatedStack?.originalFileName) {
+ filePath = resolveFileInsideProject({
+ remotionRoot,
+ fileName: request.symbolicatedStack.originalFileName,
+ action: 'move a composition in',
+ }).absolutePath;
+ } else {
+ const {rootFile} = await getProjectInfo(remotionRoot, entryPoint);
+ if (rootFile === null) {
+ throw new Error('Cannot find the Remotion root file');
+ }
+
+ filePath = rootFile;
+ }
+
+ checkIfTypeScriptFile(filePath);
+ const destination =
+ request.destination.type === 'folder'
+ ? {
+ type: 'folder' as const,
+ folder: {
+ name: request.destination.folderName,
+ parentName: request.destination.parentName,
+ },
+ }
+ : request.destination.type === 'root'
+ ? request.destination
+ : {
+ type: request.destination.type,
+ target:
+ request.destination.target.type === 'composition'
+ ? request.destination.target
+ : {
+ type: 'folder' as const,
+ name: request.destination.target.folderName,
+ parentName: request.destination.target.parentName,
+ },
+ };
+ const result = moveComposition({
+ project: {
+ files: {[filePath]: readFileSync(filePath, 'utf-8')},
+ rootDir: path.dirname(filePath),
+ },
compositionFile: filePath,
compositionId: request.compositionId,
- destination: toCodemodDestination(request.destination),
- }),
+ destination,
+ });
+ for (const change of result.changes) {
+ const currentContents = existsSync(change.filePath)
+ ? readFileSync(change.filePath, 'utf-8')
+ : null;
+ if (currentContents !== change.previousContents) {
+ throw new Error(
+ `Source changed before moving composition: ${change.filePath}`,
+ );
+ }
+ }
+
+ const mutationFiles = [
+ ...new Set(
+ result.nodePathRemappings.map((remapping) => remapping.filePath),
+ ),
+ ].map((absolutePath) => ({
+ absolutePath,
+ remappings: result.nodePathRemappings
+ .filter((remapping) => remapping.filePath === absolutePath)
+ .map(({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath})),
+ }));
+ const nodePathMutation =
+ mutationFiles.length === 0
+ ? null
+ : broadcastSequenceNodePathMutation(mutationFiles, null);
+
+ if (result.changes.length > 0) {
+ const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
+ pushTransactionToUndoStack({
+ snapshots: result.changes.map((change) => ({
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === filePath ? logLine : 1,
+ nodePathRemappings:
+ mutationFiles.find(
+ (mutation) => mutation.absolutePath === change.filePath,
+ )?.remappings ?? null,
+ })),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Move of composition "${request.compositionId}"`,
+ redoMessage: `↪️ Move of composition "${request.compositionId}"`,
+ },
+ entryType: 'move-composition-or-folder',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+
+ for (const change of result.changes) {
+ if (change.nextContents === null) {
+ throw new Error('Moving a composition cannot remove source files');
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: change.nextContents,
+ originatorClientId: undefined,
+ metadata: mutationFiles.some(
+ (mutation) => mutation.absolutePath === change.filePath,
+ )
+ ? {skipSequencePropsUpdate: true}
+ : null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: filePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Moved composition "${request.compositionId}"`,
+ );
+ printUndoHint(logLevel);
+ }
+
+ return {success: true, nodePathMutation};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ };
+ }
});
diff --git a/packages/studio-server/src/preview-server/routes/move-folder.ts b/packages/studio-server/src/preview-server/routes/move-folder.ts
index c3648365d2..c9b9f90c37 100644
--- a/packages/studio-server/src/preview-server/routes/move-folder.ts
+++ b/packages/studio-server/src/preview-server/routes/move-folder.ts
@@ -1,27 +1,171 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
import {moveFolder} from '@remotion/codemods';
-import type {MoveFolderRequest} from '@remotion/studio-shared';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ CompositionEditResponse,
+ MoveFolderRequest,
+} from '@remotion/studio-shared';
+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 {getProjectInfo} from '../project-info';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
- getCompositionEditProject,
- runCompositionEdit,
- toCodemodDestination,
-} from './run-composition-edit';
-
-export const moveFolderHandler = runCompositionEdit<MoveFolderRequest>({
- entryType: 'move-composition-or-folder',
- getDescription: ({folderName, parentName}) => {
- const folderPath = parentName ? `${parentName}/${folderName}` : folderName;
- return {
- undoMessage: `↩️ Move of folder "${folderPath}"`,
- redoMessage: `↪️ Move of folder "${folderPath}"`,
- };
- },
- getLogMessage: ({folderName, parentName}) =>
- `Moved folder "${parentName ? `${parentName}/${folderName}` : folderName}"`,
- getResult: ({filePath, request}) =>
- moveFolder({
- project: getCompositionEditProject(filePath),
- compositionFile: filePath,
- folder: {name: request.folderName, parentName: request.parentName},
- destination: toCodemodDestination(request.destination),
- }),
-});
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const moveFolderHandler: ApiHandler<
+ MoveFolderRequest,
+ CompositionEditResponse
+> = ({input: request, logLevel, remotionRoot, entryPoint}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ let filePath: string;
+ if (request.symbolicatedStack?.originalFileName) {
+ filePath = resolveFileInsideProject({
+ remotionRoot,
+ fileName: request.symbolicatedStack.originalFileName,
+ action: 'move a folder in',
+ }).absolutePath;
+ } else {
+ const {rootFile} = await getProjectInfo(remotionRoot, entryPoint);
+ if (rootFile === null) {
+ throw new Error('Cannot find the Remotion root file');
+ }
+
+ filePath = rootFile;
+ }
+
+ checkIfTypeScriptFile(filePath);
+ const destination =
+ request.destination.type === 'folder'
+ ? {
+ type: 'folder' as const,
+ folder: {
+ name: request.destination.folderName,
+ parentName: request.destination.parentName,
+ },
+ }
+ : request.destination.type === 'root'
+ ? request.destination
+ : {
+ type: request.destination.type,
+ target:
+ request.destination.target.type === 'composition'
+ ? request.destination.target
+ : {
+ type: 'folder' as const,
+ name: request.destination.target.folderName,
+ parentName: request.destination.target.parentName,
+ },
+ };
+ const result = moveFolder({
+ project: {
+ files: {[filePath]: readFileSync(filePath, 'utf-8')},
+ rootDir: path.dirname(filePath),
+ },
+ compositionFile: filePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ destination,
+ });
+ for (const change of result.changes) {
+ const currentContents = existsSync(change.filePath)
+ ? readFileSync(change.filePath, 'utf-8')
+ : null;
+ if (currentContents !== change.previousContents) {
+ throw new Error(
+ `Source changed before moving folder: ${change.filePath}`,
+ );
+ }
+ }
+
+ const mutationFiles = [
+ ...new Set(
+ result.nodePathRemappings.map((remapping) => remapping.filePath),
+ ),
+ ].map((absolutePath) => ({
+ absolutePath,
+ remappings: result.nodePathRemappings
+ .filter((remapping) => remapping.filePath === absolutePath)
+ .map(({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath})),
+ }));
+ const nodePathMutation =
+ mutationFiles.length === 0
+ ? null
+ : broadcastSequenceNodePathMutation(mutationFiles, null);
+
+ if (result.changes.length > 0) {
+ const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
+ const folderPath = request.parentName
+ ? `${request.parentName}/${request.folderName}`
+ : request.folderName;
+ pushTransactionToUndoStack({
+ snapshots: result.changes.map((change) => ({
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === filePath ? logLine : 1,
+ nodePathRemappings:
+ mutationFiles.find(
+ (mutation) => mutation.absolutePath === change.filePath,
+ )?.remappings ?? null,
+ })),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Move of folder "${folderPath}"`,
+ redoMessage: `↪️ Move of folder "${folderPath}"`,
+ },
+ entryType: 'move-composition-or-folder',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+
+ for (const change of result.changes) {
+ if (change.nextContents === null) {
+ throw new Error('Moving a folder cannot remove source files');
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: change.nextContents,
+ originatorClientId: undefined,
+ metadata: mutationFiles.some(
+ (mutation) => mutation.absolutePath === change.filePath,
+ )
+ ? {skipSequencePropsUpdate: true}
+ : null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: filePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Moved folder "${folderPath}"`,
+ );
+ printUndoHint(logLevel);
+ }
+
+ return {success: true, nodePathMutation};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ };
+ }
+ });
diff --git a/packages/studio-server/src/preview-server/routes/rename-composition.ts b/packages/studio-server/src/preview-server/routes/rename-composition.ts
index 73896ec03e..bb903c906f 100644
--- a/packages/studio-server/src/preview-server/routes/rename-composition.ts
+++ b/packages/studio-server/src/preview-server/routes/rename-composition.ts
@@ -1,24 +1,125 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
import {renameComposition} from '@remotion/codemods';
-import type {RenameCompositionRequest} from '@remotion/studio-shared';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ CompositionEditResponse,
+ RenameCompositionRequest,
+} from '@remotion/studio-shared';
+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 {getProjectInfo} from '../project-info';
import {
- getCompositionEditProject,
- runCompositionEdit,
-} from './run-composition-edit';
-
-export const renameCompositionHandler =
- runCompositionEdit<RenameCompositionRequest>({
- entryType: 'rename-composition',
- getDescription: ({idToRename, newId}) => ({
- undoMessage: `↩️ Rename of composition "${idToRename}" to "${newId}"`,
- redoMessage: `↪️ Rename of composition "${idToRename}" to "${newId}"`,
- }),
- getLogMessage: ({idToRename, newId}) =>
- `Renamed composition "${idToRename}" to "${newId}"`,
- getResult: ({filePath, request}) =>
- renameComposition({
- project: getCompositionEditProject(filePath),
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const renameCompositionHandler: ApiHandler<
+ RenameCompositionRequest,
+ CompositionEditResponse
+> = ({input: request, logLevel, remotionRoot, entryPoint}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ let filePath: string;
+ if (request.symbolicatedStack?.originalFileName) {
+ filePath = resolveFileInsideProject({
+ remotionRoot,
+ fileName: request.symbolicatedStack.originalFileName,
+ action: 'rename a composition in',
+ }).absolutePath;
+ } else {
+ const {rootFile} = await getProjectInfo(remotionRoot, entryPoint);
+ if (rootFile === null) {
+ throw new Error('Cannot find the Remotion root file');
+ }
+
+ filePath = rootFile;
+ }
+
+ checkIfTypeScriptFile(filePath);
+ const result = renameComposition({
+ project: {
+ files: {[filePath]: readFileSync(filePath, 'utf-8')},
+ rootDir: path.dirname(filePath),
+ },
compositionFile: filePath,
compositionId: request.idToRename,
newId: request.newId,
- }),
+ });
+ for (const change of result.changes) {
+ const currentContents = existsSync(change.filePath)
+ ? readFileSync(change.filePath, 'utf-8')
+ : null;
+ if (currentContents !== change.previousContents) {
+ throw new Error(
+ `Source changed before renaming composition: ${change.filePath}`,
+ );
+ }
+ }
+
+ if (result.changes.length > 0) {
+ const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
+ pushTransactionToUndoStack({
+ snapshots: result.changes.map((change) => ({
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === filePath ? logLine : 1,
+ nodePathRemappings: null,
+ })),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Rename of composition "${request.idToRename}" to "${request.newId}"`,
+ redoMessage: `↪️ Rename of composition "${request.idToRename}" to "${request.newId}"`,
+ },
+ entryType: 'rename-composition',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+
+ for (const change of result.changes) {
+ if (change.nextContents === null) {
+ throw new Error(
+ 'Renaming a composition cannot remove source files',
+ );
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: change.nextContents,
+ originatorClientId: undefined,
+ metadata: null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: filePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Renamed composition "${request.idToRename}" to "${request.newId}"`,
+ );
+ printUndoHint(logLevel);
+ }
+
+ return {success: true, nodePathMutation: null};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ };
+ }
});
diff --git a/packages/studio-server/src/preview-server/routes/rename-folder.ts b/packages/studio-server/src/preview-server/routes/rename-folder.ts
index fb51bf35d6..4f2a53185f 100644
--- a/packages/studio-server/src/preview-server/routes/rename-folder.ts
+++ b/packages/studio-server/src/preview-server/routes/rename-folder.ts
@@ -1,27 +1,129 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
import {renameFolder} from '@remotion/codemods';
-import type {RenameFolderRequest} from '@remotion/studio-shared';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ CompositionEditResponse,
+ RenameFolderRequest,
+} from '@remotion/studio-shared';
+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 {getProjectInfo} from '../project-info';
import {
- getCompositionEditProject,
- runCompositionEdit,
-} from './run-composition-edit';
-
-export const renameFolderHandler = runCompositionEdit<RenameFolderRequest>({
- entryType: 'rename-folder',
- getDescription: ({folderName, parentName, newName}) => {
- const oldPath = parentName ? `${parentName}/${folderName}` : folderName;
- const newPath = parentName ? `${parentName}/${newName}` : newName;
- return {
- undoMessage: `↩️ Rename of folder "${oldPath}" to "${newPath}"`,
- redoMessage: `↪️ Rename of folder "${oldPath}" to "${newPath}"`,
- };
- },
- getLogMessage: ({folderName, parentName}) =>
- `Renamed folder "${parentName ? `${parentName}/${folderName}` : folderName}"`,
- getResult: ({filePath, request}) =>
- renameFolder({
- project: getCompositionEditProject(filePath),
- compositionFile: filePath,
- folder: {name: request.folderName, parentName: request.parentName},
- newName: request.newName,
- }),
-});
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const renameFolderHandler: ApiHandler<
+ RenameFolderRequest,
+ CompositionEditResponse
+> = ({input: request, logLevel, remotionRoot, entryPoint}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ let filePath: string;
+ if (request.symbolicatedStack?.originalFileName) {
+ filePath = resolveFileInsideProject({
+ remotionRoot,
+ fileName: request.symbolicatedStack.originalFileName,
+ action: 'rename a folder in',
+ }).absolutePath;
+ } else {
+ const {rootFile} = await getProjectInfo(remotionRoot, entryPoint);
+ if (rootFile === null) {
+ throw new Error('Cannot find the Remotion root file');
+ }
+
+ filePath = rootFile;
+ }
+
+ checkIfTypeScriptFile(filePath);
+ const result = renameFolder({
+ project: {
+ files: {[filePath]: readFileSync(filePath, 'utf-8')},
+ rootDir: path.dirname(filePath),
+ },
+ compositionFile: filePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ newName: request.newName,
+ });
+ for (const change of result.changes) {
+ const currentContents = existsSync(change.filePath)
+ ? readFileSync(change.filePath, 'utf-8')
+ : null;
+ if (currentContents !== change.previousContents) {
+ throw new Error(
+ `Source changed before renaming folder: ${change.filePath}`,
+ );
+ }
+ }
+
+ if (result.changes.length > 0) {
+ const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
+ const oldPath = request.parentName
+ ? `${request.parentName}/${request.folderName}`
+ : request.folderName;
+ const newPath = request.parentName
+ ? `${request.parentName}/${request.newName}`
+ : request.newName;
+ pushTransactionToUndoStack({
+ snapshots: result.changes.map((change) => ({
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === filePath ? logLine : 1,
+ nodePathRemappings: null,
+ })),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Rename of folder "${oldPath}" to "${newPath}"`,
+ redoMessage: `↪️ Rename of folder "${oldPath}" to "${newPath}"`,
+ },
+ entryType: 'rename-folder',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+
+ for (const change of result.changes) {
+ if (change.nextContents === null) {
+ throw new Error('Renaming a folder cannot remove source files');
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: change.nextContents,
+ originatorClientId: undefined,
+ metadata: null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: filePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Renamed folder "${oldPath}"`,
+ );
+ printUndoHint(logLevel);
+ }
+
+ return {success: true, nodePathMutation: null};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ };
+ }
+ });
diff --git a/packages/studio-server/src/preview-server/routes/run-composition-edit.ts b/packages/studio-server/src/preview-server/routes/run-composition-edit.ts
deleted file mode 100644
index 306fe20a08..0000000000
--- a/packages/studio-server/src/preview-server/routes/run-composition-edit.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-import {existsSync, readFileSync} from 'node:fs';
-import path from 'node:path';
-import type {
- CodemodNodeResult,
- CodemodResult,
- CompositionDestination as CodemodCompositionDestination,
-} from '@remotion/codemods';
-import {RenderInternals} from '@remotion/renderer';
-import type {
- CompositionDestination,
- CompositionEditResponse,
- SymbolicatedStackFrame,
- UndoRedoNavigation,
-} from '@remotion/studio-shared';
-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 {getProjectInfo} from '../project-info';
-import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
-import {
- printUndoHint,
- pushTransactionToUndoStack,
- suppressUndoStackInvalidation,
-} from '../undo-stack';
-import {checkIfTypeScriptFile} from './can-update-default-props';
-import {
- getCodemodTimingPrefix,
- withSourceFileWriteQueue,
-} from './source-file-write-queue';
-
-const resolveCompositionFile = async ({
- entryPoint,
- remotionRoot,
- symbolicatedStack,
-}: {
- entryPoint: string;
- remotionRoot: string;
- symbolicatedStack: SymbolicatedStackFrame | null;
-}) => {
- if (symbolicatedStack?.originalFileName) {
- return resolveFileInsideProject({
- remotionRoot,
- fileName: symbolicatedStack.originalFileName,
- action: 'apply composition edit to',
- }).absolutePath;
- }
-
- const filePath = (await getProjectInfo(remotionRoot, entryPoint)).rootFile;
- if (filePath === null) {
- throw new Error('Cannot find the Remotion root file');
- }
-
- return filePath;
-};
-
-export const toCodemodDestination = (
- destination: CompositionDestination,
-): CodemodCompositionDestination =>
- destination.type === 'folder'
- ? {
- type: 'folder',
- folder: {
- name: destination.folderName,
- parentName: destination.parentName,
- },
- }
- : destination.type === 'root'
- ? destination
- : {
- type: destination.type,
- target:
- destination.target.type === 'composition'
- ? destination.target
- : {
- type: 'folder',
- name: destination.target.folderName,
- parentName: destination.target.parentName,
- },
- };
-
-type EditResult = CodemodResult | CodemodNodeResult;
-type UndoEntryType = Parameters<
- typeof pushTransactionToUndoStack
->[0]['entryType'];
-
-export const runCompositionEdit = <
- Request extends {
- symbolicatedStack: SymbolicatedStackFrame | null;
- undoRedoNavigation: UndoRedoNavigation | null;
- },
->({
- entryType,
- getDescription,
- getLogMessage,
- getResult,
-}: {
- entryType: UndoEntryType;
- getDescription: (request: Request) => {
- undoMessage: string;
- redoMessage: string;
- };
- getLogMessage: (request: Request) => string;
- getResult: (options: {
- filePath: string;
- request: Request;
- }) => EditResult | Promise<EditResult>;
-}): ApiHandler<Request, CompositionEditResponse> => {
- return ({input: request, logLevel, remotionRoot, entryPoint}) =>
- withSourceFileWriteQueue(async () => {
- try {
- const filePath = await resolveCompositionFile({
- entryPoint,
- remotionRoot,
- symbolicatedStack: request.symbolicatedStack,
- });
- checkIfTypeScriptFile(filePath);
- const result = await getResult({filePath, request});
- for (const change of result.changes) {
- const currentContents = existsSync(change.filePath)
- ? readFileSync(change.filePath, 'utf-8')
- : null;
- if (currentContents !== change.previousContents) {
- throw new Error(
- `Source changed before applying codemod: ${change.filePath}`,
- );
- }
- }
-
- const remappings =
- 'nodePathRemappings' in result ? result.nodePathRemappings : [];
- const mutationFiles = [
- ...new Set(remappings.map((remapping) => remapping.filePath)),
- ].map((absolutePath) => ({
- absolutePath,
- remappings: remappings
- .filter((remapping) => remapping.filePath === absolutePath)
- .map(({oldNodePath, newNodePath}) => ({
- oldNodePath,
- newNodePath,
- })),
- }));
- const nodePathMutation =
- mutationFiles.length === 0
- ? null
- : broadcastSequenceNodePathMutation(mutationFiles, null);
-
- if (result.changes.length > 0) {
- const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
- pushTransactionToUndoStack({
- snapshots: result.changes.map((change) => {
- const fileRemappings = mutationFiles.find(
- (file) => file.absolutePath === change.filePath,
- )?.remappings;
- return {
- filePath: change.filePath,
- oldContents: change.previousContents,
- newContents: change.nextContents,
- logLine: change.filePath === filePath ? logLine : 1,
- nodePathRemappings: fileRemappings ?? null,
- };
- }),
- logLevel,
- remotionRoot,
- description: getDescription(request),
- entryType,
- suppressHmrOnFileRestore: false,
- undoRedoNavigation: request.undoRedoNavigation,
- });
-
- for (const change of result.changes) {
- if (change.nextContents === null) {
- throw new Error('Composition edits cannot remove source files');
- }
-
- suppressUndoStackInvalidation(change.filePath);
- writeFileAndNotifyFileWatchers({
- file: change.filePath,
- content: change.nextContents,
- originatorClientId: undefined,
- metadata: mutationFiles.some(
- (mutation) => mutation.absolutePath === change.filePath,
- )
- ? {skipSequencePropsUpdate: true}
- : null,
- });
- }
-
- const editMessage = `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(
- formatLogFileLocation({
- remotionRoot,
- absolutePath: filePath,
- line: logLine,
- }),
- )} ${getLogMessage(request)}`;
- RenderInternals.Log.info({indent: false, logLevel}, editMessage);
- printUndoHint(logLevel);
- }
-
- return {success: true, nodePathMutation};
- } catch (error) {
- return {
- success: false,
- reason: error instanceof Error ? error.message : String(error),
- stack: error instanceof Error ? (error.stack ?? '') : '',
- };
- }
- });
-};
-
-export const getCompositionEditProject = (filePath: string) => ({
- files: {[filePath]: readFileSync(filePath, 'utf-8')},
- rootDir: path.dirname(filePath),
-});
diff --git a/packages/studio-server/src/preview-server/routes/unwrap-folder.ts b/packages/studio-server/src/preview-server/routes/unwrap-folder.ts
index 9c6ea2759a..3a4b7e5f84 100644
--- a/packages/studio-server/src/preview-server/routes/unwrap-folder.ts
+++ b/packages/studio-server/src/preview-server/routes/unwrap-folder.ts
@@ -1,25 +1,125 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
import {unwrapFolder} from '@remotion/codemods';
-import type {UnwrapFolderRequest} from '@remotion/studio-shared';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ CompositionEditResponse,
+ UnwrapFolderRequest,
+} from '@remotion/studio-shared';
+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 {getProjectInfo} from '../project-info';
import {
- getCompositionEditProject,
- runCompositionEdit,
-} from './run-composition-edit';
-
-export const unwrapFolderHandler = runCompositionEdit<UnwrapFolderRequest>({
- entryType: 'delete-folder',
- getDescription: ({folderName, parentName}) => {
- const folderPath = parentName ? `${parentName}/${folderName}` : folderName;
- return {
- undoMessage: `↩️ Deletion of folder "${folderPath}"`,
- redoMessage: `↪️ Deletion of folder "${folderPath}"`,
- };
- },
- getLogMessage: ({folderName, parentName}) =>
- `Deleted folder "${parentName ? `${parentName}/${folderName}` : folderName}"`,
- getResult: ({filePath, request}) =>
- unwrapFolder({
- project: getCompositionEditProject(filePath),
- compositionFile: filePath,
- folder: {name: request.folderName, parentName: request.parentName},
- }),
-});
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const unwrapFolderHandler: ApiHandler<
+ UnwrapFolderRequest,
+ CompositionEditResponse
+> = ({input: request, logLevel, remotionRoot, entryPoint}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ let filePath: string;
+ if (request.symbolicatedStack?.originalFileName) {
+ filePath = resolveFileInsideProject({
+ remotionRoot,
+ fileName: request.symbolicatedStack.originalFileName,
+ action: 'delete a folder from',
+ }).absolutePath;
+ } else {
+ const {rootFile} = await getProjectInfo(remotionRoot, entryPoint);
+ if (rootFile === null) {
+ throw new Error('Cannot find the Remotion root file');
+ }
+
+ filePath = rootFile;
+ }
+
+ checkIfTypeScriptFile(filePath);
+ const result = unwrapFolder({
+ project: {
+ files: {[filePath]: readFileSync(filePath, 'utf-8')},
+ rootDir: path.dirname(filePath),
+ },
+ compositionFile: filePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ });
+ for (const change of result.changes) {
+ const currentContents = existsSync(change.filePath)
+ ? readFileSync(change.filePath, 'utf-8')
+ : null;
+ if (currentContents !== change.previousContents) {
+ throw new Error(
+ `Source changed before deleting folder: ${change.filePath}`,
+ );
+ }
+ }
+
+ if (result.changes.length > 0) {
+ const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
+ const folderPath = request.parentName
+ ? `${request.parentName}/${request.folderName}`
+ : request.folderName;
+ pushTransactionToUndoStack({
+ snapshots: result.changes.map((change) => ({
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === filePath ? logLine : 1,
+ nodePathRemappings: null,
+ })),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Deletion of folder "${folderPath}"`,
+ redoMessage: `↪️ Deletion of folder "${folderPath}"`,
+ },
+ entryType: 'delete-folder',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+
+ for (const change of result.changes) {
+ if (change.nextContents === null) {
+ throw new Error('Deleting a folder cannot remove source files');
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: change.nextContents,
+ originatorClientId: undefined,
+ metadata: null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: filePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Deleted folder "${folderPath}"`,
+ );
+ printUndoHint(logLevel);
+ }
+
+ return {success: true, nodePathMutation: null};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ };
+ }
+ });
diff --git a/packages/studio-server/src/preview-server/routes/update-composition-metadata.ts b/packages/studio-server/src/preview-server/routes/update-composition-metadata.ts
index bc5725cad9..c84c49f8cd 100644
--- a/packages/studio-server/src/preview-server/routes/update-composition-metadata.ts
+++ b/packages/studio-server/src/preview-server/routes/update-composition-metadata.ts
@@ -1,22 +1,55 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
import {updateCompositionMetadata} from '@remotion/codemods';
-import type {UpdateCompositionMetadataRequest} from '@remotion/studio-shared';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ CompositionEditResponse,
+ UpdateCompositionMetadataRequest,
+} from '@remotion/studio-shared';
+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 {getProjectInfo} from '../project-info';
import {
- getCompositionEditProject,
- runCompositionEdit,
-} from './run-composition-edit';
-
-export const updateCompositionMetadataHandler =
- runCompositionEdit<UpdateCompositionMetadataRequest>({
- entryType: 'update-composition-metadata',
- getDescription: ({idToUpdate}) => ({
- undoMessage: `↩️ Update of metadata of composition "${idToUpdate}"`,
- redoMessage: `↪️ Update of metadata of composition "${idToUpdate}"`,
- }),
- getLogMessage: ({idToUpdate}) =>
- `Updated metadata of composition "${idToUpdate}"`,
- getResult: ({filePath, request}) =>
- updateCompositionMetadata({
- project: getCompositionEditProject(filePath),
+ printUndoHint,
+ pushTransactionToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {checkIfTypeScriptFile} from './can-update-default-props';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const updateCompositionMetadataHandler: ApiHandler<
+ UpdateCompositionMetadataRequest,
+ CompositionEditResponse
+> = ({input: request, logLevel, remotionRoot, entryPoint}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ let filePath: string;
+ if (request.symbolicatedStack?.originalFileName) {
+ filePath = resolveFileInsideProject({
+ remotionRoot,
+ fileName: request.symbolicatedStack.originalFileName,
+ action: 'update composition metadata in',
+ }).absolutePath;
+ } else {
+ const {rootFile} = await getProjectInfo(remotionRoot, entryPoint);
+ if (rootFile === null) {
+ throw new Error('Cannot find the Remotion root file');
+ }
+
+ filePath = rootFile;
+ }
+
+ checkIfTypeScriptFile(filePath);
+ const result = updateCompositionMetadata({
+ project: {
+ files: {[filePath]: readFileSync(filePath, 'utf-8')},
+ rootDir: path.dirname(filePath),
+ },
compositionFile: filePath,
compositionId: request.idToUpdate,
metadata: {
@@ -25,5 +58,73 @@ export const updateCompositionMetadataHandler =
fps: request.newFps ?? undefined,
durationInFrames: request.newDurationInFrames ?? undefined,
},
- }),
+ });
+ for (const change of result.changes) {
+ const currentContents = existsSync(change.filePath)
+ ? readFileSync(change.filePath, 'utf-8')
+ : null;
+ if (currentContents !== change.previousContents) {
+ throw new Error(
+ `Source changed before updating composition metadata: ${change.filePath}`,
+ );
+ }
+ }
+
+ if (result.changes.length > 0) {
+ const logLine = request.symbolicatedStack?.originalLineNumber ?? 1;
+ pushTransactionToUndoStack({
+ snapshots: result.changes.map((change) => ({
+ filePath: change.filePath,
+ oldContents: change.previousContents,
+ newContents: change.nextContents,
+ logLine: change.filePath === filePath ? logLine : 1,
+ nodePathRemappings: null,
+ })),
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Update of metadata of composition "${request.idToUpdate}"`,
+ redoMessage: `↪️ Update of metadata of composition "${request.idToUpdate}"`,
+ },
+ entryType: 'update-composition-metadata',
+ suppressHmrOnFileRestore: false,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+
+ for (const change of result.changes) {
+ if (change.nextContents === null) {
+ throw new Error(
+ 'Updating composition metadata cannot remove source files',
+ );
+ }
+
+ suppressUndoStackInvalidation(change.filePath);
+ writeFileAndNotifyFileWatchers({
+ file: change.filePath,
+ content: change.nextContents,
+ originatorClientId: undefined,
+ metadata: null,
+ });
+ }
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath: filePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Updated metadata of composition "${request.idToUpdate}"`,
+ );
+ printUndoHint(logLevel);
+ }
+
+ return {success: true, nodePathMutation: null};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ };
+ }
});
diff --git a/packages/studio-server/src/test/composition-edits.test.ts b/packages/studio-server/src/test/composition-edits.test.ts
index 046f017d0d..05a24fbce0 100644
--- a/packages/studio-server/src/test/composition-edits.test.ts
+++ b/packages/studio-server/src/test/composition-edits.test.ts
@@ -244,7 +244,7 @@ type CompositionEditRequest = {
undoRedoNavigation: UndoRedoNavigation | null;
};
-const runCompositionEditUndoRedoTest = async <
+const expectCompositionEditUndoRedo = async <
Request extends CompositionEditRequest,
>({
handler,
@@ -334,7 +334,7 @@ const runCompositionEditUndoRedoTest = async <
};
test('deleteCompositionHandler pushes composition deletions to undo and redo stacks', async () => {
- await runCompositionEditUndoRedoTest({
+ await expectCompositionEditUndoRedo({
handler: deleteCompositionHandler,
request: {
idToDelete: 'DeleteMe',
@@ -351,7 +351,7 @@ test('deleteCompositionHandler pushes composition deletions to undo and redo sta
});
test('renameCompositionHandler logs composition renames and pushes them to the undo and redo stacks', async () => {
- await runCompositionEditUndoRedoTest({
+ await expectCompositionEditUndoRedo({
handler: renameCompositionHandler,
request: {
idToRename: 'DeleteMe',
@@ -371,7 +371,7 @@ test('renameCompositionHandler logs composition renames and pushes them to the u
test('duplicateCompositionHandler pushes composition and still duplications to undo and redo stacks', async () => {
for (const tag of ['Composition', 'Still'] as const) {
- await runCompositionEditUndoRedoTest({
+ await expectCompositionEditUndoRedo({
handler: duplicateCompositionHandler,
request: {
idToDuplicate: 'DeleteMe',
@@ -403,7 +403,7 @@ test('duplicateCompositionHandler pushes composition and still duplications to u
});
test('addFolderHandler pushes folder creations to undo and redo stacks', async () => {
- await runCompositionEditUndoRedoTest({
+ await expectCompositionEditUndoRedo({
handler: addFolderHandler,
request: {
folderName: 'FreshFolder',
diff --git a/packages/studio/src/components/NewComposition/CompositionEditFooter.tsx b/packages/studio/src/components/NewComposition/CompositionEditFooter.tsx
index 4f40508548..24816b500c 100644
--- a/packages/studio/src/components/NewComposition/CompositionEditFooter.tsx
+++ b/packages/studio/src/components/NewComposition/CompositionEditFooter.tsx
@@ -17,10 +17,7 @@ import {SetSelectedModalContext} from '../../state/modals';
import {Flex, Row, Spacing} from '../layout';
import {ModalButton} from '../ModalButton';
import {showNotification} from '../Notifications/NotificationCenter';
-import {
- hasResolvedStack,
- useResolvedStack,
-} from '../Timeline/use-resolved-stack';
+import {useResolvedStack} from '../Timeline/use-resolved-stack';
type ApplyCompositionEditAction = (options: {
signal: AbortSignal;
@@ -134,23 +131,6 @@ export const CompositionEditFooter: React.FC<{
symbolicatedStack,
]);
- useEffect(() => {
- if (!stack) {
- return;
- }
-
- if (!hasResolvedStack(stack)) {
- return;
- }
-
- if (!symbolicatedStack) {
- showNotification(
- `${errorNotification}: Could not resolve the source location of this item`,
- 3000,
- );
- }
- }, [errorNotification, fallbackToRootFile, stack, symbolicatedStack]);
-
const disabled =
!valid || submitting || (symbolicatedStack === null && !fallbackToRootFile);