Skip to content

🎥 Make videos programmatically with React

Refactor Studio composition codemods

JonnyBurgerca92a2b06b80
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index d435ebe8e8..f06a94404b 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -1,13 +1,13 @@
import {
CodemodsInternals,
applyCodemodChanges,
- addComposition,
+ addComposition as addCompositionCodemod,
addCanvasCaptureComposition,
addEffect as addEffectCodemod,
addElement,
- addFolder,
+ addFolder as addFolderCodemod,
createElement,
- deleteComposition,
+ deleteComposition as deleteCompositionCodemod,
deleteEffects as deleteEffectsCodemod,
deleteNodes as deleteNodesCodemod,
detachAudio,
@@ -19,17 +19,17 @@ import {
getNodeProps,
canPrecomposeJsxNodes,
precomposeJsxNodes as precomposeJsxNodesCodemod,
- moveComposition,
- moveFolder,
- renameComposition,
- renameFolder,
+ moveComposition as moveCompositionCodemod,
+ moveFolder as moveFolderCodemod,
+ renameComposition as renameCompositionCodemod,
+ renameFolder as renameFolderCodemod,
reorderEffect as reorderEffectCodemod,
reorderNode,
resolveCompositionComponent,
setCompositionDefaultProps,
splitSequences as splitSequencesCodemod,
- unwrapFolder,
- updateCompositionMetadata,
+ unwrapFolder as unwrapFolderCodemod,
+ updateCompositionMetadata as updateCompositionMetadataCodemod,
updateEffectKeyframes,
updateEffectProps as updateEffectPropsCodemod,
updateNodeKeyframes,
@@ -56,20 +56,20 @@ import {
type BrowserStudioKeyframeOperations,
type BrowserStudioOperations,
type BrowserStudioPackageInstallationOperations,
+ type CompositionEditResponse,
+ type CompositionDestination as StudioCompositionDestination,
type ElementInstallExpectedFileState,
type EventSourceEvent,
type InsertElementResponse,
type InsertCompositionElementRequest,
- type RecastCodemod,
+ type NewCompositionOptions,
type SequenceNodePathRemapping,
type SubscribeToSequencePropsRequest,
type SubscribeToSequencePropsResponse,
type SymbolicatedStackFrame,
type UnsubscribeFromSequencePropsRequest,
+ type UndoRedoNavigation,
} from '@remotion/studio-shared';
-import * as prettierPluginEstree from 'prettier/plugins/estree';
-import * as prettierPluginTypescript from 'prettier/plugins/typescript';
-import {format} from 'prettier/standalone';
import type {
InteractivitySchema,
SequenceNodePath,
@@ -105,7 +105,6 @@ const {
JsxElementIdentityMismatchError,
JsxElementNotFoundAtLocationError,
pasteEffects: pasteEffectsCodemod,
- simpleDiff,
} = CodemodsInternals;
/*
@@ -180,17 +179,6 @@ const insertIntoProject = async ({
};
};
-const formatCodemodFile = async ({contents}: {contents: string}) => ({
- formatted: true,
- output: await format(contents, {
- bracketSpacing: false,
- parser: 'typescript',
- plugins: [prettierPluginTypescript, prettierPluginEstree],
- singleQuote: true,
- useTabs: true,
- }),
-});
-
const getNodePathMutationFiles = (result: CodemodNodeResult) =>
[
...new Set([
@@ -210,6 +198,16 @@ const getStructuredError = (error: unknown) => ({
stack: error instanceof Error && error.stack ? error.stack : '',
});
+const runBrowserCompositionEdit = (
+ edit: () => CompositionEditResponse,
+): Promise<CompositionEditResponse> => {
+ try {
+ return Promise.resolve(edit());
+ } catch (error) {
+ return Promise.resolve(getStructuredError(error));
+ }
+};
+
export type BrowserStudioOperationsController = BrowserStudioOperations & {
emitEvent: (event: EventSourceEvent) => void;
resetHistory: () => void;
@@ -300,41 +298,14 @@ const relativeToRoot = (filePath: string, rootDir: string) => {
: filePath.replace(/^\//, '');
};
-const getCodemodTargetCompositionId = (
- codemod: RecastCodemod,
-): string | null => {
- if (codemod.type === 'duplicate-composition') {
- return codemod.idToDuplicate;
- }
-
- if (codemod.type === 'rename-composition') {
- return codemod.idToRename;
- }
-
- if (codemod.type === 'update-composition-metadata') {
- return codemod.idToUpdate;
- }
-
- if (codemod.type === 'delete-composition') {
- return codemod.idToDelete;
- }
-
- if (
- codemod.type === 'move-composition-or-folder' &&
- codemod.source.type === 'composition'
- ) {
- return codemod.source.compositionId;
- }
-
- return null;
-};
-
-const resolveCodemodTargetFile = ({
- codemod,
+const resolveCompositionEditFile = ({
+ compositionId,
+ folderName,
project,
symbolicatedStack,
}: {
- codemod: RecastCodemod;
+ compositionId: string | null;
+ folderName: string | null;
project: VirtualProject;
symbolicatedStack: SymbolicatedStackFrame | null;
}): string => {
@@ -345,7 +316,6 @@ const resolveCodemodTargetFile = ({
});
}
- const compositionId = getCodemodTargetCompositionId(codemod);
if (compositionId !== null) {
const compositionFile = getCompositionFile({compositionId, project});
if (compositionFile === null) {
@@ -355,28 +325,13 @@ const resolveCodemodTargetFile = ({
return findProjectFile({filePath: compositionFile, project});
}
- if (codemod.type === 'rename-folder' || codemod.type === 'delete-folder') {
+ if (folderName !== null) {
const folderFile = getFolderFile({
- folderName: codemod.folderName,
+ folderName,
project,
});
if (folderFile === null) {
- throw new Error(`Could not find folder "${codemod.folderName}"`);
- }
-
- return findProjectFile({filePath: folderFile, project});
- }
-
- if (
- codemod.type === 'move-composition-or-folder' &&
- codemod.source.type === 'folder'
- ) {
- const folderFile = getFolderFile({
- folderName: codemod.source.folderName,
- project,
- });
- if (folderFile === null) {
- throw new Error(`Could not find folder "${codemod.source.folderName}"`);
+ throw new Error(`Could not find folder "${folderName}"`);
}
return findProjectFile({filePath: folderFile, project});
@@ -393,188 +348,91 @@ const resolveCodemodTargetFile = ({
return findProjectFile({filePath: rootFile, project});
};
-const applyCompositionCodemod = ({
+const toCodemodCompositionDestination = (
+ destination: StudioCompositionDestination,
+): CompositionDestination =>
+ 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,
+ },
+ };
+
+const getAddCompositionResult = ({
project,
compositionFile,
- codemod,
+ options,
}: {
project: VirtualProject;
compositionFile: string;
- codemod: RecastCodemod;
-}): VirtualProject => {
- const target = {project, compositionFile};
- const apply = (result: CodemodResult) =>
- applyCodemodChanges(project, result.changes);
- switch (codemod.type) {
- case 'new-composition': {
- const componentFilePath = `${dirname(compositionFile)}/${codemod.componentName}.tsx`;
- if (project.files[componentFilePath] !== undefined) {
- throw new Error(
- `Cannot create ${relativeToRoot(componentFilePath, project.rootDir)} because it already exists`,
- );
- }
-
- const composition = {
- ...target,
- compositionId: codemod.newId,
- component: {
- filePath: componentFilePath,
- importName: codemod.componentName,
- importPath: codemod.componentImportPath,
- },
- metadata: {
- width: codemod.newWidth,
- height: codemod.newHeight,
- fps: codemod.newFps,
- durationInFrames: codemod.newDurationInFrames,
- },
- folder:
- codemod.folderName === null
- ? undefined
- : {name: codemod.folderName, parentName: codemod.parentName},
- };
- if (codemod.canvasCapture !== null) {
- return apply(
- addCanvasCaptureComposition({
- ...composition,
- capture: codemod.canvasCapture,
- }),
- );
- }
-
- const result = addComposition(composition);
- return applyCodemodChanges(project, [
- ...result.changes,
- {
- filePath: componentFilePath,
- previousContents: null,
- nextContents:
- codemod.asset === null
- ? emptyCompositionComponent(codemod.componentName)
- : assetCompositionComponent({
- asset: codemod.asset,
- componentName: codemod.componentName,
- }),
- },
- ]);
- }
-
- case 'duplicate-composition':
- return apply(
- duplicateCompositionCodemod({
- ...target,
- compositionId: codemod.idToDuplicate,
- newId: codemod.newId,
- tag: codemod.tag,
- metadata: {
- width: codemod.newWidth ?? undefined,
- height: codemod.newHeight ?? undefined,
- fps:
- codemod.tag === 'Still'
- ? undefined
- : (codemod.newFps ?? undefined),
- durationInFrames:
- codemod.tag === 'Still'
- ? undefined
- : (codemod.newDurationInFrames ?? undefined),
- },
- }),
- );
- case 'rename-composition':
- return apply(
- renameComposition({
- ...target,
- compositionId: codemod.idToRename,
- newId: codemod.newId,
- }),
- );
- case 'delete-composition':
- return apply(
- deleteComposition({...target, compositionId: codemod.idToDelete}),
- );
- case 'update-composition-metadata':
- return apply(
- updateCompositionMetadata({
- ...target,
- compositionId: codemod.idToUpdate,
- metadata: {
- width: codemod.newWidth ?? undefined,
- height: codemod.newHeight ?? undefined,
- fps: codemod.newFps ?? undefined,
- durationInFrames: codemod.newDurationInFrames ?? undefined,
- },
- }),
- );
- case 'new-folder':
- return apply(
- addFolder({
- ...target,
- folder: {name: codemod.folderName, parentName: codemod.parentName},
- }),
- );
- case 'rename-folder':
- return apply(
- renameFolder({
- ...target,
- folder: {name: codemod.folderName, parentName: codemod.parentName},
- newName: codemod.newName,
- }),
- );
- case 'delete-folder':
- return apply(
- unwrapFolder({
- ...target,
- folder: {name: codemod.folderName, parentName: codemod.parentName},
- }),
- );
- case 'move-composition-or-folder': {
- const destination: CompositionDestination =
- codemod.destination.type === 'folder'
- ? {
- type: 'folder',
- folder: {
- name: codemod.destination.folderName,
- parentName: codemod.destination.parentName,
- },
- }
- : codemod.destination.type === 'root'
- ? codemod.destination
- : {
- type: codemod.destination.type,
- target:
- codemod.destination.target.type === 'composition'
- ? codemod.destination.target
- : {
- type: 'folder',
- name: codemod.destination.target.folderName,
- parentName: codemod.destination.target.parentName,
- },
- };
- return apply(
- codemod.source.type === 'composition'
- ? moveComposition({
- ...target,
- compositionId: codemod.source.compositionId,
- destination,
- })
- : moveFolder({
- ...target,
- folder: {
- name: codemod.source.folderName,
- parentName: codemod.source.parentName,
- },
- destination,
- }),
- );
- }
+ options: NewCompositionOptions;
+}): CodemodResult => {
+ const componentFilePath = `${dirname(compositionFile)}/${options.componentName}.tsx`;
+ if (project.files[componentFilePath] !== undefined) {
+ throw new Error(
+ `Cannot create ${relativeToRoot(componentFilePath, project.rootDir)} because it already exists`,
+ );
+ }
- case 'apply-visual-control':
- throw new Error(
- 'Applying visual controls is not supported in Browser Studio',
- );
- default:
- throw new Error('Unsupported codemod');
+ const composition = {
+ project,
+ compositionFile,
+ compositionId: options.newId,
+ component: {
+ filePath: componentFilePath,
+ importName: options.componentName,
+ importPath: options.componentImportPath,
+ },
+ metadata: {
+ width: options.newWidth,
+ height: options.newHeight,
+ fps: options.newFps,
+ durationInFrames: options.newDurationInFrames,
+ },
+ folder:
+ options.folderName === null
+ ? undefined
+ : {name: options.folderName, parentName: options.parentName},
+ };
+ if (options.canvasCapture !== null) {
+ return addCanvasCaptureComposition({
+ ...composition,
+ capture: options.canvasCapture,
+ });
}
+
+ const result = addCompositionCodemod(composition);
+ return {
+ changes: [
+ ...result.changes,
+ {
+ filePath: componentFilePath,
+ previousContents: null,
+ nextContents:
+ options.asset === null
+ ? emptyCompositionComponent(options.componentName)
+ : assetCompositionComponent({
+ asset: options.asset,
+ componentName: options.componentName,
+ }),
+ },
+ ],
+ };
};
const getElementInstallPlanForProject = async ({
@@ -759,6 +617,27 @@ export const createBrowserStudioOperations = ({
}
},
});
+ const commitCompositionEdit = ({
+ fileName,
+ project: _project,
+ result,
+ undoRedoNavigation,
+ }: {
+ fileName: string;
+ project: VirtualProject;
+ result: CodemodResult | CodemodNodeResult;
+ undoRedoNavigation: UndoRedoNavigation | null;
+ }) => {
+ const nodePathMutationFiles =
+ 'nodePathRemappings' in result ? getNodePathMutationFiles(result) : null;
+ return controller.applyMutation({
+ undoRedoNavigation,
+ timelineSelection: null,
+ fileName,
+ nodePathMutationFiles,
+ mutate: (current) => applyCodemodChanges(current, result.changes),
+ });
+ };
const mutateKeyframesInProject = async ({
project,
@@ -1724,66 +1603,261 @@ export const createBrowserStudioOperations = ({
}
};
- const applyCodemod: BrowserStudioOperations['applyCodemod'] = async ({
- codemod,
- dryRun,
- symbolicatedStack,
- undoRedoNavigation,
- }) => {
- try {
- if (codemod.type === 'apply-visual-control') {
- throw new Error(
- 'Applying visual controls is not supported in Browser Studio',
- );
- }
+ const addComposition: BrowserStudioOperations['addComposition'] = (
+ request,
+ ) => {
+ return runBrowserCompositionEdit(() => {
+ const project = getProject();
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: null,
+ folderName: null,
+ project,
+ symbolicatedStack: request.symbolicatedStack,
+ });
+ const result = getAddCompositionResult({
+ project,
+ compositionFile: absolutePath,
+ options: request.options,
+ });
+ const nodePathMutation = commitCompositionEdit({
+ fileName: absolutePath,
+ project,
+ result,
+ undoRedoNavigation: request.undoRedoNavigation,
+ });
+ return {success: true, nodePathMutation};
+ });
+ };
+ const renameCompositionOperation: BrowserStudioOperations['renameComposition'] =
+ (request) => {
+ return runBrowserCompositionEdit(() => {
+ const project = getProject();
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: request.idToRename,
+ folderName: null,
+ project,
+ symbolicatedStack: request.symbolicatedStack,
+ });
+ const result = renameCompositionCodemod({
+ project,
+ compositionFile: absolutePath,
+ compositionId: request.idToRename,
+ newId: request.newId,
+ });
+ return {
+ success: true as const,
+ nodePathMutation: commitCompositionEdit({
+ fileName: absolutePath,
+ project,
+ result,
+ undoRedoNavigation: request.undoRedoNavigation,
+ }),
+ };
+ });
+ };
+
+ const deleteCompositionOperation: BrowserStudioOperations['deleteComposition'] =
+ (request) => {
+ return runBrowserCompositionEdit(() => {
+ const project = getProject();
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: request.idToDelete,
+ folderName: null,
+ project,
+ symbolicatedStack: request.symbolicatedStack,
+ });
+ const result = deleteCompositionCodemod({
+ project,
+ compositionFile: absolutePath,
+ compositionId: request.idToDelete,
+ });
+ return {
+ success: true as const,
+ nodePathMutation: commitCompositionEdit({
+ fileName: absolutePath,
+ project,
+ result,
+ undoRedoNavigation: request.undoRedoNavigation,
+ }),
+ };
+ });
+ };
+
+ const updateCompositionMetadataOperation: BrowserStudioOperations['updateCompositionMetadata'] =
+ (request) => {
+ return runBrowserCompositionEdit(() => {
+ const project = getProject();
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: request.idToUpdate,
+ folderName: null,
+ project,
+ symbolicatedStack: request.symbolicatedStack,
+ });
+ const result = updateCompositionMetadataCodemod({
+ project,
+ compositionFile: absolutePath,
+ compositionId: request.idToUpdate,
+ metadata: {
+ width: request.newWidth ?? undefined,
+ height: request.newHeight ?? undefined,
+ fps: request.newFps ?? undefined,
+ durationInFrames: request.newDurationInFrames ?? undefined,
+ },
+ });
+ return {
+ success: true as const,
+ nodePathMutation: commitCompositionEdit({
+ fileName: absolutePath,
+ project,
+ result,
+ undoRedoNavigation: request.undoRedoNavigation,
+ }),
+ };
+ });
+ };
+
+ const moveCompositionOperation: BrowserStudioOperations['moveComposition'] = (
+ request,
+ ) => {
+ return runBrowserCompositionEdit(() => {
const project = getProject();
- const absolutePath = resolveCodemodTargetFile({
- codemod,
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: request.compositionId,
+ folderName: null,
project,
- symbolicatedStack,
+ symbolicatedStack: request.symbolicatedStack,
});
- const input = project.files[absolutePath];
- const nextProject = applyCompositionCodemod({
+ const result = moveCompositionCodemod({
project,
compositionFile: absolutePath,
- codemod,
- });
- const newContents = nextProject.files[absolutePath];
- const output =
- codemod.type === 'new-composition' ||
- codemod.type === 'duplicate-composition' ||
- codemod.type === 'rename-composition' ||
- codemod.type === 'delete-composition'
- ? newContents
- : (await formatCodemodFile({contents: newContents})).output;
- const files: Record<string, string> = {
- ...nextProject.files,
- [absolutePath]: output,
+ compositionId: request.compositionId,
+ destination: toCodemodCompositionDestination(request.destination),
+ });
+ return {
+ success: true as const,
+ nodePathMutation: commitCompositionEdit({
+ fileName: absolutePath,
+ project,
+ result,
+ undoRedoNavigation: request.undoRedoNavigation,
+ }),
};
+ });
+ };
- const diff = simpleDiff({
- oldLines: input.split('\n'),
- newLines: output.split('\n'),
+ const addFolderOperation: BrowserStudioOperations['addFolder'] = (
+ request,
+ ) => {
+ return runBrowserCompositionEdit(() => {
+ const project = getProject();
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: null,
+ folderName: null,
+ project,
+ symbolicatedStack: request.symbolicatedStack,
});
+ const result = addFolderCodemod({
+ project,
+ compositionFile: absolutePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ });
+ return {
+ success: true as const,
+ nodePathMutation: commitCompositionEdit({
+ fileName: absolutePath,
+ project,
+ result,
+ undoRedoNavigation: request.undoRedoNavigation,
+ }),
+ };
+ });
+ };
- if (!dryRun) {
- controller.applyMutation({
- undoRedoNavigation,
- timelineSelection: null,
+ const renameFolderOperation: BrowserStudioOperations['renameFolder'] = (
+ request,
+ ) => {
+ return runBrowserCompositionEdit(() => {
+ const project = getProject();
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: null,
+ folderName: request.folderName,
+ project,
+ symbolicatedStack: request.symbolicatedStack,
+ });
+ const result = renameFolderCodemod({
+ project,
+ compositionFile: absolutePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ newName: request.newName,
+ });
+ return {
+ success: true as const,
+ nodePathMutation: commitCompositionEdit({
fileName: absolutePath,
- nodePathMutationFiles: null,
- mutate: () => ({...project, files}),
- });
- }
+ project,
+ result,
+ undoRedoNavigation: request.undoRedoNavigation,
+ }),
+ };
+ });
+ };
- return {success: true, diff};
- } catch (error) {
+ const unwrapFolderOperation: BrowserStudioOperations['unwrapFolder'] = (
+ request,
+ ) => {
+ return runBrowserCompositionEdit(() => {
+ const project = getProject();
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: null,
+ folderName: request.folderName,
+ project,
+ symbolicatedStack: request.symbolicatedStack,
+ });
+ const result = unwrapFolderCodemod({
+ project,
+ compositionFile: absolutePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ });
return {
- success: false,
- reason: error instanceof Error ? error.message : String(error),
+ success: true as const,
+ nodePathMutation: commitCompositionEdit({
+ fileName: absolutePath,
+ project,
+ result,
+ undoRedoNavigation: request.undoRedoNavigation,
+ }),
};
- }
+ });
+ };
+
+ const moveFolderOperation: BrowserStudioOperations['moveFolder'] = (
+ request,
+ ) => {
+ return runBrowserCompositionEdit(() => {
+ const project = getProject();
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: null,
+ folderName: request.folderName,
+ project,
+ symbolicatedStack: request.symbolicatedStack,
+ });
+ const result = moveFolderCodemod({
+ project,
+ compositionFile: absolutePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ destination: toCodemodCompositionDestination(request.destination),
+ });
+ return {
+ success: true as const,
+ nodePathMutation: commitCompositionEdit({
+ fileName: absolutePath,
+ project,
+ result,
+ undoRedoNavigation: request.undoRedoNavigation,
+ }),
+ };
+ });
};
const reorderSequence: BrowserStudioOperations['reorderSequence'] = async ({
@@ -2072,57 +2146,44 @@ export const createBrowserStudioOperations = ({
};
const duplicateComposition: BrowserStudioOperations['duplicateComposition'] =
- async ({codemod, dryRun, undoRedoNavigation}) => {
- try {
+ (request) => {
+ return runBrowserCompositionEdit(() => {
const project = getProject();
- const compositionFile = getCompositionFile({
- compositionId: codemod.idToDuplicate,
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: request.idToDuplicate,
+ folderName: null,
project,
+ symbolicatedStack: request.symbolicatedStack,
});
- if (compositionFile === null) {
- throw new Error(
- `Could not find composition "${codemod.idToDuplicate}" to duplicate`,
- );
- }
-
- const absolutePath = findProjectFile({
- filePath: compositionFile,
- project,
- });
- const input = project.files[absolutePath];
- const nextProject = applyCompositionCodemod({
+ const result = duplicateCompositionCodemod({
project,
compositionFile: absolutePath,
- codemod,
- });
- const newContents = nextProject.files[absolutePath];
- const {output} = await formatCodemodFile({contents: newContents});
- const diff = simpleDiff({
- oldLines: input.split('\n'),
- newLines: output.split('\n'),
+ compositionId: request.idToDuplicate,
+ newId: request.newId,
+ tag: request.tag,
+ metadata: {
+ width: request.newWidth ?? undefined,
+ height: request.newHeight ?? undefined,
+ fps:
+ request.tag === 'Still'
+ ? undefined
+ : (request.newFps ?? undefined),
+ durationInFrames:
+ request.tag === 'Still'
+ ? undefined
+ : (request.newDurationInFrames ?? undefined),
+ },
});
-
- if (!dryRun) {
- controller.applyMutation({
- undoRedoNavigation,
- timelineSelection: null,
- fileName: absolutePath,
- nodePathMutationFiles: null,
- mutate: () => ({
- ...project,
- files: {...project.files, [absolutePath]: output},
- }),
- });
- }
-
- return {success: true, diff};
- } catch (error) {
return {
- success: false,
- reason: error instanceof Error ? error.message : String(error),
- stack: error instanceof Error && error.stack ? error.stack : '',
+ success: true,
+ nodePathMutation: commitCompositionEdit({
+ fileName: absolutePath,
+ project,
+ result,
+ undoRedoNavigation: request.undoRedoNavigation,
+ }),
};
- }
+ });
};
const updateDefaultProps: BrowserStudioOperations['updateDefaultProps'] =
@@ -2363,7 +2424,8 @@ export const createBrowserStudioOperations = ({
};
return {
- applyCodemod,
+ addComposition,
+ addFolder: addFolderOperation,
consumeInitialElement: () => {
const value = pendingInitialElement;
pendingInitialElement = null;
@@ -2392,6 +2454,7 @@ export const createBrowserStudioOperations = ({
project: getProject(),
}),
duplicateComposition,
+ deleteComposition: deleteCompositionOperation,
precomposeJsxNodes,
duplicateNodes,
wrapNode,
@@ -2440,14 +2503,15 @@ export const createBrowserStudioOperations = ({
const originalProject = getProject();
let project = originalProject;
if (request.newComposition !== null) {
- if (request.newComposition.codemod.newId !== request.compositionId) {
+ if (request.newComposition.options.newId !== request.compositionId) {
throw new Error(
'New composition ID does not match installation target',
);
}
- const absolutePath = resolveCodemodTargetFile({
- codemod: request.newComposition.codemod,
+ const absolutePath = resolveCompositionEditFile({
+ compositionId: null,
+ folderName: null,
project,
symbolicatedStack: request.newComposition.symbolicatedStack,
});
@@ -2457,11 +2521,14 @@ export const createBrowserStudioOperations = ({
);
}
- project = applyCompositionCodemod({
+ project = applyCodemodChanges(
project,
- compositionFile: absolutePath,
- codemod: request.newComposition.codemod,
- });
+ getAddCompositionResult({
+ project,
+ compositionFile: absolutePath,
+ options: request.newComposition.options,
+ }).changes,
+ );
}
const plan = await getElementInstallPlanForProject({
@@ -2672,6 +2739,8 @@ export const createBrowserStudioOperations = ({
}
},
insertCompositionElement,
+ moveComposition: moveCompositionOperation,
+ moveFolder: moveFolderOperation,
keyframes,
packageInstallation,
prepareElementInstall: async (request) => {
@@ -2698,6 +2767,8 @@ export const createBrowserStudioOperations = ({
};
}
},
+ renameComposition: renameCompositionOperation,
+ renameFolder: renameFolderOperation,
redo: controller.redo,
renameStaticFile: controller.renameStaticFile,
reorderSequence,
@@ -2876,6 +2947,8 @@ export const createBrowserStudioOperations = ({
return Promise.resolve(undefined);
},
updateDefaultProps,
+ updateCompositionMetadata: updateCompositionMetadataOperation,
+ unwrapFolder: unwrapFolderOperation,
writeStaticFile: controller.writeStaticFile,
};
};
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index 2071305803..10f92c7027 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -1309,13 +1309,9 @@ test('renames a composition by resolving the file from the composition id', asyn
createBlankTemplateProject(),
);
- const result = await operations.applyCodemod({
- codemod: {
- type: 'rename-composition',
- idToRename: 'MyComp',
- newId: 'RenamedComp',
- },
- dryRun: false,
+ const result = await operations.renameComposition({
+ idToRename: 'MyComp',
+ newId: 'RenamedComp',
undoRedoNavigation: null,
symbolicatedStack: null,
});
@@ -1339,16 +1335,12 @@ test('updates composition metadata in Browser Studio', async () => {
createBlankTemplateProject(),
);
- const result = await operations.applyCodemod({
- codemod: {
- type: 'update-composition-metadata',
- idToUpdate: 'MyComp',
- newDurationInFrames: 120,
- newFps: 60,
- newHeight: 1080,
- newWidth: 1920,
- },
- dryRun: false,
+ const result = await operations.updateCompositionMetadata({
+ idToUpdate: 'MyComp',
+ newDurationInFrames: 120,
+ newFps: 60,
+ newHeight: 1080,
+ newWidth: 1920,
undoRedoNavigation: null,
symbolicatedStack: null,
});
@@ -1363,30 +1355,12 @@ test('updates composition metadata in Browser Studio', async () => {
expect(composition).toContain('height={1080}');
});
-test('deletes a composition and supports a dry run', async () => {
+test('deletes a composition', async () => {
const {operations, getProject} = makeOperationsForProject(
createBlankTemplateProject(),
);
- const initialContents = getProject().files['/project/src/Composition.tsx'];
-
- const dryRunResult = await operations.applyCodemod({
- codemod: {type: 'delete-composition', idToDelete: 'MyComp'},
- dryRun: true,
- undoRedoNavigation: null,
- symbolicatedStack: null,
- });
- if (!dryRunResult.success) {
- throw new Error(dryRunResult.reason);
- }
-
- expect(dryRunResult.diff.deletions).toBeGreaterThan(0);
- expect(getProject().files['/project/src/Composition.tsx']).toBe(
- initialContents,
- );
-
- const result = await operations.applyCodemod({
- codemod: {type: 'delete-composition', idToDelete: 'MyComp'},
- dryRun: false,
+ const result = await operations.deleteComposition({
+ idToDelete: 'MyComp',
undoRedoNavigation: null,
symbolicatedStack: null,
});
@@ -1404,8 +1378,7 @@ test('creates a composition with a component file in the root file', async () =>
createBlankTemplateProject(),
);
- const codemod = {
- type: 'new-composition' as const,
+ const options = {
asset: null,
newId: 'FreshComp',
componentName: 'FreshComp',
@@ -1418,9 +1391,8 @@ test('creates a composition with a component file in the root file', async () =>
newDurationInFrames: 90,
canvasCapture: null,
};
- const result = await operations.applyCodemod({
- codemod,
- dryRun: false,
+ const result = await operations.addComposition({
+ options,
undoRedoNavigation: null,
symbolicatedStack: null,
});
@@ -1436,13 +1408,12 @@ test('creates a composition with a component file in the root file', async () =>
'export const FreshComp: React.FC',
);
- const conflict = await operations.applyCodemod({
- codemod: {...codemod, newId: 'FreshComp2'},
- dryRun: false,
+ const conflict = await operations.addComposition({
+ options: {...options, newId: 'FreshComp2'},
undoRedoNavigation: null,
symbolicatedStack: null,
});
- expect(conflict).toEqual({
+ expect(conflict).toMatchObject({
success: false,
reason: 'Cannot create src/FreshComp.tsx because it already exists',
});
@@ -1460,9 +1431,8 @@ test('imports a Canvas Capture as an interactive composition', async () => {
createBlankTemplateProject(),
);
- const result = await operations.applyCodemod({
- codemod: {
- type: 'new-composition',
+ const result = await operations.addComposition({
+ options: {
asset: null,
newId: 'CanvasComp',
componentName: 'CanvasComp',
@@ -1501,7 +1471,6 @@ test('imports a Canvas Capture as an interactive composition', async () => {
},
},
},
- dryRun: false,
undoRedoNavigation: null,
symbolicatedStack: null,
});
@@ -1533,9 +1502,9 @@ test('creates, renames and deletes a folder in Browser Studio', async () => {
createBlankTemplateProject(),
);
- const createResult = await operations.applyCodemod({
- codemod: {type: 'new-folder', folderName: 'my-folder', parentName: null},
- dryRun: false,
+ const createResult = await operations.addFolder({
+ folderName: 'my-folder',
+ parentName: null,
undoRedoNavigation: null,
symbolicatedStack: null,
});
@@ -1545,16 +1514,12 @@ test('creates, renames and deletes a folder in Browser Studio', async () => {
const rootFile = getProject().files['/project/src/Root.tsx'];
expect(rootFile).toContain('<Folder name="my-folder" />');
- expect(rootFile).toContain("import {Folder} from 'remotion'");
+ expect(rootFile).toContain('import { Folder } from "remotion"');
- const renameResult = await operations.applyCodemod({
- codemod: {
- type: 'rename-folder',
- folderName: 'my-folder',
- parentName: null,
- newName: 'renamed-folder',
- },
- dryRun: false,
+ const renameResult = await operations.renameFolder({
+ folderName: 'my-folder',
+ parentName: null,
+ newName: 'renamed-folder',
undoRedoNavigation: null,
symbolicatedStack: null,
});
@@ -1566,13 +1531,9 @@ test('creates, renames and deletes a folder in Browser Studio', async () => {
'<Folder name="renamed-folder" />',
);
- const deleteResult = await operations.applyCodemod({
- codemod: {
- type: 'delete-folder',
- folderName: 'renamed-folder',
- parentName: null,
- },
- dryRun: false,
+ const deleteResult = await operations.unwrapFolder({
+ folderName: 'renamed-folder',
+ parentName: null,
undoRedoNavigation: null,
symbolicatedStack: null,
});
@@ -1609,17 +1570,13 @@ export const Root = () => {
},
});
- const result = await operations.applyCodemod({
- codemod: {
- type: 'move-composition-or-folder',
- source: {type: 'composition', compositionId: 'MyComp'},
- destination: {
- type: 'folder',
- folderName: 'target-folder',
- parentName: null,
- },
+ const result = await operations.moveComposition({
+ compositionId: 'MyComp',
+ destination: {
+ type: 'folder',
+ folderName: 'target-folder',
+ parentName: null,
},
- dryRun: false,
undoRedoNavigation: null,
symbolicatedStack: {
originalFileName: 'src/Root.tsx',
@@ -1633,6 +1590,7 @@ export const Root = () => {
throw new Error(result.reason);
}
+ expect(result.nodePathMutation).not.toBeNull();
const rootFile = getProject().files[fileName];
expect(rootFile).toContain('<Folder name="target-folder">');
expect(rootFile.indexOf('<Composition')).toBeGreaterThan(
@@ -1889,32 +1847,19 @@ test('adds missing composition defaultProps and restores them through undo and r
expect(getProject().files).toEqual(updatedFiles);
});
-test('reports structured failures for unsupported codemods', async () => {
+test('reports structured failures for composition edits', async () => {
const {operations, getProject} = makeOperationsForProject(
createBlankTemplateProject(),
);
const initialFiles = {...getProject().files};
expect(
- await operations.applyCodemod({
- codemod: {type: 'apply-visual-control', changes: []},
- dryRun: false,
- undoRedoNavigation: null,
- symbolicatedStack: null,
- }),
- ).toEqual({
- success: false,
- reason: 'Applying visual controls is not supported in Browser Studio',
- });
-
- expect(
- await operations.applyCodemod({
- codemod: {type: 'delete-composition', idToDelete: 'MissingComp'},
- dryRun: false,
+ await operations.deleteComposition({
+ idToDelete: 'MissingComp',
undoRedoNavigation: null,
symbolicatedStack: null,
}),
- ).toEqual({
+ ).toMatchObject({
success: false,
reason: 'Could not find composition "MissingComp"',
});
diff --git a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
index 6b8fe1d3a7..7312a85700 100644
--- a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
@@ -9,7 +9,7 @@ import {
import {createBlankTemplateProject} from '../templates/blank';
import type {VirtualProject} from '../types';
-test('previews and creates a Canvas Capture with both files in undo history', async () => {
+test('creates a Canvas Capture with both files in undo history', async () => {
const initialProject = createBlankTemplateProject();
let project = initialProject;
const operations = createBrowserStudioOperations({
@@ -22,9 +22,8 @@ test('previews and creates a Canvas Capture with both files in undo history', as
},
resolveDependencies: null,
});
- const request: Parameters<typeof operations.applyCodemod>[0] = {
- codemod: {
- type: 'new-composition',
+ const request: Parameters<typeof operations.addComposition>[0] = {
+ options: {
asset: null,
newId: 'Capture',
componentName: 'Capture',
@@ -49,20 +48,14 @@ test('previews and creates a Canvas Capture with both files in undo history', as
},
},
},
- dryRun: true,
undoRedoNavigation: null,
symbolicatedStack: null,
};
- const preview = await operations.applyCodemod(request);
- if (!preview.success) {
- throw new Error(preview.reason);
+ const result = await operations.addComposition(request);
+ if (!result.success) {
+ throw new Error(result.reason);
}
- expect(preview.diff.additions).toBeGreaterThan(0);
- expect(project).toBe(initialProject);
- expect(await operations.applyCodemod({...request, dryRun: false})).toEqual(
- preview,
- );
expect(project.files['/project/src/Root.tsx']).toContain('<Capture />');
expect(project.files['/project/src/Root.tsx']).toMatch(
/from ["']\.\/Capture["']/,
@@ -76,9 +69,7 @@ test('previews and creates a Canvas Capture with both files in undo history', as
expect(project.files).toEqual(initialProject.files);
expect((await operations.redo()).success).toBe(true);
expect(project.files).toEqual(createdProject.files);
- expect(
- await operations.applyCodemod({...request, dryRun: false}),
- ).toMatchObject({
+ expect(await operations.addComposition(request)).toMatchObject({
success: false,
reason: expect.stringContaining('already exists'),
});
@@ -383,7 +374,7 @@ test('downloads CORS-enabled remote assets and rejects failed cross-origin fetch
}
});
-test('previews and duplicates compositions as an undoable project mutation', async () => {
+test('duplicates compositions as an undoable project mutation', async () => {
const initialProject = createBlankTemplateProject();
let project = initialProject;
const operations = createBrowserStudioOperations({
@@ -396,41 +387,23 @@ test('previews and duplicates compositions as an undoable project mutation', asy
},
resolveDependencies: null,
});
- const request = {
+ const request: Parameters<typeof operations.duplicateComposition>[0] = {
undoRedoNavigation: {
undoRoute: '/MyComp',
redoRoute: '/MyCompCopy',
},
- codemod: {
- type: 'duplicate-composition' as const,
- idToDuplicate: 'MyComp',
- newDurationInFrames: 120,
- newFps: 24,
- newHeight: 1080,
- newId: 'MyCompCopy',
- newWidth: 1920,
- tag: 'Composition' as const,
- },
+ symbolicatedStack: null,
+ idToDuplicate: 'MyComp',
+ newDurationInFrames: 120,
+ newFps: 24,
+ newHeight: 1080,
+ newId: 'MyCompCopy',
+ newWidth: 1920,
+ tag: 'Composition',
};
- const preview = await operations.duplicateComposition({
- ...request,
- dryRun: true,
- undoRedoNavigation: null,
- });
- expect(preview.success).toBe(true);
- if (!preview.success) {
- throw new Error(preview.reason);
- }
-
- expect(preview.diff.additions).toBeGreaterThan(0);
- expect(project).toBe(initialProject);
-
- const result = await operations.duplicateComposition({
- ...request,
- dryRun: false,
- });
- expect(result).toEqual(preview);
+ const result = await operations.duplicateComposition(request);
+ expect(result).toEqual({success: true, nodePathMutation: null});
expect(project.files['/project/src/Composition.tsx']).toContain(
'id="MyCompCopy"',
);
@@ -459,12 +432,11 @@ test('previews and duplicates compositions as an undoable project mutation', asy
const failure = await operations.duplicateComposition({
...request,
- codemod: {...request.codemod, idToDuplicate: 'Missing'},
- dryRun: false,
+ idToDuplicate: 'Missing',
});
expect(failure).toMatchObject({
success: false,
- reason: 'Could not find composition "Missing" to duplicate',
+ reason: 'Could not find composition "Missing"',
stack: expect.any(String),
});
expect(project.files['/project/src/Composition.tsx']).toBe(
@@ -473,8 +445,8 @@ test('previews and duplicates compositions as an undoable project mutation', asy
const stillResult = await operations.duplicateComposition({
...request,
- codemod: {...request.codemod, newId: 'MyStill', tag: 'Still'},
- dryRun: false,
+ newId: 'MyStill',
+ tag: 'Still',
});
expect(stillResult.success).toBe(true);
const stillSource =
@@ -883,8 +855,7 @@ test('installs an Element into a new composition as one undoable mutation', asyn
redoRoute: '/ElementScene',
},
newComposition: {
- codemod: {
- type: 'new-composition',
+ options: {
asset: null,
newId: 'ElementScene',
componentName: 'ElementScene',
diff --git a/packages/bundler/src/fast-refresh/notify-on-refresh.ts b/packages/bundler/src/fast-refresh/notify-on-refresh.ts
index 352bd5104a..02af53143e 100644
--- a/packages/bundler/src/fast-refresh/notify-on-refresh.ts
+++ b/packages/bundler/src/fast-refresh/notify-on-refresh.ts
@@ -1,4 +1,7 @@
-import {REACT_REFRESH_FINISHED_EVENT} from '@remotion/studio-shared';
+import {
+ REACT_REFRESH_FINISHED_EVENT,
+ REACT_REFRESH_STARTED_EVENT,
+} from '@remotion/studio-shared';
type ReactRefreshRuntime = {
performReactRefresh: () => unknown;
@@ -12,6 +15,7 @@ if (RefreshRuntime.__remotionReactRefreshWrapped === null) {
const originalPerformReactRefresh = RefreshRuntime.performReactRefresh;
RefreshRuntime.__remotionReactRefreshWrapped = true;
RefreshRuntime.performReactRefresh = () => {
+ window.dispatchEvent(new Event(REACT_REFRESH_STARTED_EVENT));
// The refresh integration calls this after applying the update. Emitting
// here gives Studio a boundary after React refreshed its roots.
const result = originalPerformReactRefresh();
diff --git a/packages/codemods/src/folder-editing.ts b/packages/codemods/src/folder-editing.ts
index 54abf4675b..15f799d7c7 100644
--- a/packages/codemods/src/folder-editing.ts
+++ b/packages/codemods/src/folder-editing.ts
@@ -1,10 +1,11 @@
import type {File, JSXElement} from '@babel/types';
import * as recast from 'recast';
import type {CodemodProject} from './codemod-project';
-import {getCodemodResult} from './codemod-project';
import type {FolderReference} from './composition-editing';
import {getMoveTreeItemSourceEdits} from './folder-source-edits';
+import {captureJsxNodePaths} from './get-node-path-remappings';
import {findProjectFile} from './internals';
+import {getNodeEditResult} from './node-references';
import {
getCompositionIdFromJSXElement,
getFolderNameFromJSXElement,
@@ -100,7 +101,8 @@ export const moveTreeItem = <Project extends CodemodProject>({
}) => {
const filePath = findProjectFile({project, filePath: compositionFile});
const input = project.files[filePath];
- const entries = getTreeEntries({ast: parseAst(input)});
+ const ast = parseAst(input);
+ const entries = getTreeEntries({ast});
const entry = requireTreeItem(entries, source);
const target =
destination.type === 'root'
@@ -148,7 +150,7 @@ export const moveTreeItem = <Project extends CodemodProject>({
((destination.type === 'folder' || destination.type === 'root') &&
entry.parentName === destinationParentName)
) {
- return {changes: []};
+ return {changes: [], nodePathRemappings: []};
}
if (!entry.directJsxChild)
@@ -168,9 +170,63 @@ export const moveTreeItem = <Project extends CodemodProject>({
position: destination.type,
}),
});
- parseAst(nextContents);
- return getCodemodResult({
+ const nextAst = parseAst(nextContents);
+ const nextEntries = getTreeEntries({ast: nextAst});
+ const movedEntry = requireTreeItem(
+ nextEntries,
+ source.type === 'composition'
+ ? source
+ : {
+ type: 'folder',
+ name: source.name,
+ parentName: destinationParentName,
+ },
+ );
+ const before = captureJsxNodePaths(ast);
+ const after = captureJsxNodePaths(nextAst);
+ const beforeMovedNodes = new Set<object>([entry.node.openingElement]);
+ const afterMovedNodes = new Set<object>([movedEntry.node.openingElement]);
+ for (const captured of before) {
+ if (
+ captured.parentNode !== null &&
+ beforeMovedNodes.has(captured.parentNode)
+ ) {
+ beforeMovedNodes.add(captured.node);
+ }
+ }
+
+ for (const captured of after) {
+ if (
+ captured.parentNode !== null &&
+ afterMovedNodes.has(captured.parentNode)
+ ) {
+ afterMovedNodes.add(captured.node);
+ }
+ }
+
+ const beforeMoved = before.filter(({node}) => beforeMovedNodes.has(node));
+ const afterMoved = after.filter(({node}) => afterMovedNodes.has(node));
+ const beforeUnmoved = before.filter(({node}) => !beforeMovedNodes.has(node));
+ const afterUnmoved = after.filter(({node}) => !afterMovedNodes.has(node));
+ if (
+ beforeMoved.length !== afterMoved.length ||
+ beforeUnmoved.length !== afterUnmoved.length
+ ) {
+ throw new Error('Could not remap JSX nodes after moving a tree item');
+ }
+
+ const nodePathRemappings = [
+ ...beforeMoved.map((node, index) => ({node, next: afterMoved[index]})),
+ ...beforeUnmoved.map((node, index) => ({node, next: afterUnmoved[index]})),
+ ].flatMap(({node, next}) =>
+ JSON.stringify(node.nodePath) === JSON.stringify(next.nodePath) &&
+ node.signature === next.signature
+ ? []
+ : [{oldNodePath: node.nodePath, newNodePath: next.nodePath}],
+ );
+
+ return getNodeEditResult({
project,
- edits: [{filePath, nextContents}],
+ edits: [{filePath, output: nextContents, nodePathRemappings}],
});
};
diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.ts
index 1fbcc96377..e30f116817 100644
--- a/packages/codemods/src/index.ts
+++ b/packages/codemods/src/index.ts
@@ -25,7 +25,6 @@ import {computeSequencePropsSubscriptionFromContent} from './sequence-props';
import {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';
import {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
import {getKeyframeInterpolationFunctionForCallee} from './sequence-props/keyframe-interpolation-function';
-import {simpleDiff} from './simple-diff';
import {updateInlineCaptionPatches} from './update-inline-caption-patches';
export {
@@ -193,7 +192,6 @@ export const CodemodsInternals = {
pasteEffects,
resolveCompositionComponent,
resolveCompositionComponentWithFile,
- simpleDiff,
updateInlineCaptionPatches,
};
diff --git a/packages/codemods/src/simple-diff.ts b/packages/codemods/src/simple-diff.ts
deleted file mode 100644
index bf6e9283d8..0000000000
--- a/packages/codemods/src/simple-diff.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import type {SimpleDiff} from '@remotion/studio-shared';
-
-const countUniqueLineChanges = ({from, to}: {from: string[]; to: string[]}) => {
- const linesChecked = new Set<string>();
- let total = 0;
- for (const line of from) {
- if (linesChecked.has(line)) {
- continue;
- }
-
- total += Math.max(
- 0,
- from.filter((candidate) => candidate === line).length -
- to.filter((candidate) => candidate === line).length,
- );
- linesChecked.add(line);
- }
-
- return total;
-};
-
-export const simpleDiff = ({
- oldLines,
- newLines,
-}: {
- oldLines: string[];
- newLines: string[];
-}): SimpleDiff => ({
- additions: countUniqueLineChanges({from: newLines, to: oldLines}),
- deletions: countUniqueLineChanges({from: oldLines, to: newLines}),
-});
diff --git a/packages/studio-server/src/codemods/add-composition-to-file.ts b/packages/studio-server/src/codemods/add-composition-to-file.ts
new file mode 100644
index 0000000000..8dfc326a6c
--- /dev/null
+++ b/packages/studio-server/src/codemods/add-composition-to-file.ts
@@ -0,0 +1,80 @@
+import {existsSync} from 'node:fs';
+import {readFile} from 'node:fs/promises';
+import path from 'node:path';
+import {
+ addCanvasCaptureComposition,
+ addComposition,
+ type CodemodResult,
+} from '@remotion/codemods';
+import type {NewCompositionOptions} from '@remotion/studio-shared';
+import {
+ assetCompositionComponent,
+ emptyCompositionComponent,
+} from '@remotion/studio-shared';
+import {checkIfTypeScriptFile} from '../preview-server/routes/can-update-default-props';
+
+export const addCompositionToFile = async ({
+ filePath,
+ options,
+}: {
+ filePath: string;
+ options: NewCompositionOptions;
+}): Promise<CodemodResult> => {
+ checkIfTypeScriptFile(filePath);
+ const input = await readFile(filePath, 'utf-8');
+ const componentFilePath = path.join(
+ path.dirname(filePath),
+ `${options.componentName}.tsx`,
+ );
+ if (existsSync(componentFilePath)) {
+ throw new Error(
+ `Cannot create ${componentFilePath} because it already exists`,
+ );
+ }
+
+ const composition = {
+ project: {files: {[filePath]: input}, rootDir: path.dirname(filePath)},
+ compositionFile: filePath,
+ compositionId: options.newId,
+ component: {
+ filePath: componentFilePath,
+ importName: options.componentName,
+ importPath: options.componentImportPath,
+ },
+ metadata: {
+ width: options.newWidth,
+ height: options.newHeight,
+ fps: options.newFps,
+ durationInFrames: options.newDurationInFrames,
+ },
+ folder:
+ options.folderName === null
+ ? undefined
+ : {name: options.folderName, parentName: options.parentName},
+ };
+ if (options.canvasCapture !== null) {
+ return addCanvasCaptureComposition({
+ ...composition,
+ capture: options.canvasCapture,
+ });
+ }
+
+ const result = addComposition(composition);
+ return {
+ ...result,
+ changes: [
+ ...result.changes,
+ {
+ filePath: componentFilePath,
+ previousContents: null,
+ nextContents:
+ options.asset === null
+ ? emptyCompositionComponent(options.componentName)
+ : assetCompositionComponent({
+ asset: options.asset,
+ componentName: options.componentName,
+ }),
+ },
+ ],
+ };
+};
diff --git a/packages/studio-server/src/codemods/apply-codemod-to-file.ts b/packages/studio-server/src/codemods/apply-codemod-to-file.ts
deleted file mode 100644
index 9c821bc780..0000000000
--- a/packages/studio-server/src/codemods/apply-codemod-to-file.ts
+++ /dev/null
@@ -1,225 +0,0 @@
-import {existsSync} from 'node:fs';
-import {readFile} from 'node:fs/promises';
-import path from 'node:path';
-import {
- addCanvasCaptureComposition,
- updateVisualControls,
- type CodemodResult,
- addComposition,
- addFolder,
- deleteComposition,
- duplicateComposition,
- moveComposition,
- moveFolder,
- renameComposition,
- renameFolder,
- unwrapFolder,
- updateCompositionMetadata,
- type CompositionDestination,
-} from '@remotion/codemods';
-import type {
- RecastCodemod,
- SymbolicatedStackFrame,
-} from '@remotion/studio-shared';
-import {
- assetCompositionComponent,
- emptyCompositionComponent,
-} from '@remotion/studio-shared';
-import {resolveFileInsideProject} from '../helpers/resolve-file-inside-project';
-import {checkIfTypeScriptFile} from '../preview-server/routes/can-update-default-props';
-
-export const resolveFilePathFromSymbolicatedStack = (
- remotionRoot: string,
- stack: SymbolicatedStackFrame,
-): string => {
- if (!stack.originalFileName) {
- throw new Error(
- 'Could not determine the file where this composition is defined',
- );
- }
-
- const {absolutePath} = resolveFileInsideProject({
- remotionRoot,
- fileName: stack.originalFileName,
- action: 'apply codemod to',
- });
-
- if (!existsSync(absolutePath)) {
- throw new Error(`File not found: ${stack.originalFileName}`);
- }
-
- return absolutePath;
-};
-
-export const applyCodemodToFile = async ({
- filePath,
- codeMod,
-}: {
- filePath: string;
- codeMod: RecastCodemod;
-}): Promise<CodemodResult> => {
- checkIfTypeScriptFile(filePath);
-
- const input = await readFile(filePath, 'utf-8');
- const options = {
- project: {files: {[filePath]: input}, rootDir: path.dirname(filePath)},
- compositionFile: filePath,
- };
- if (codeMod.type === 'apply-visual-control') {
- return updateVisualControls({
- ...options,
- filePath,
- changes: codeMod.changes,
- });
- }
-
- if (codeMod.type === 'new-composition') {
- const componentFilePath = path.join(
- path.dirname(filePath),
- `${codeMod.componentName}.tsx`,
- );
- if (existsSync(componentFilePath)) {
- throw new Error(
- `Cannot create ${componentFilePath} because it already exists`,
- );
- }
-
- const composition = {
- ...options,
- compositionId: codeMod.newId,
- component: {
- filePath: componentFilePath,
- importName: codeMod.componentName,
- importPath: codeMod.componentImportPath,
- },
- metadata: {
- width: codeMod.newWidth,
- height: codeMod.newHeight,
- fps: codeMod.newFps,
- durationInFrames: codeMod.newDurationInFrames,
- },
- folder:
- codeMod.folderName === null
- ? undefined
- : {name: codeMod.folderName, parentName: codeMod.parentName},
- };
- if (codeMod.canvasCapture !== null) {
- return addCanvasCaptureComposition({
- ...composition,
- capture: codeMod.canvasCapture,
- });
- }
-
- const result = addComposition(composition);
- return {
- ...result,
- changes: [
- ...result.changes,
- {
- filePath: componentFilePath,
- previousContents: null,
- nextContents:
- codeMod.asset === null
- ? emptyCompositionComponent(codeMod.componentName)
- : assetCompositionComponent({
- asset: codeMod.asset,
- componentName: codeMod.componentName,
- }),
- },
- ],
- };
- }
-
- if (codeMod.type === 'rename-composition') {
- return renameComposition({
- ...options,
- compositionId: codeMod.idToRename,
- newId: codeMod.newId,
- });
- }
-
- if (codeMod.type === 'delete-composition') {
- return deleteComposition({...options, compositionId: codeMod.idToDelete});
- }
-
- if (
- codeMod.type === 'duplicate-composition' ||
- codeMod.type === 'update-composition-metadata'
- ) {
- const metadata = {
- width: codeMod.newWidth ?? undefined,
- height: codeMod.newHeight ?? undefined,
- fps:
- codeMod.type === 'duplicate-composition' && codeMod.tag === 'Still'
- ? undefined
- : (codeMod.newFps ?? undefined),
- durationInFrames:
- codeMod.type === 'duplicate-composition' && codeMod.tag === 'Still'
- ? undefined
- : (codeMod.newDurationInFrames ?? undefined),
- };
- const result =
- codeMod.type === 'duplicate-composition'
- ? duplicateComposition({
- ...options,
- compositionId: codeMod.idToDuplicate,
- newId: codeMod.newId,
- tag: codeMod.tag,
- metadata,
- })
- : updateCompositionMetadata({
- ...options,
- compositionId: codeMod.idToUpdate,
- metadata,
- });
- return result;
- }
-
- if (codeMod.type === 'move-composition-or-folder') {
- const target = codeMod.destination;
- const destination: CompositionDestination =
- target.type === 'root'
- ? target
- : target.type === 'folder'
- ? {
- type: 'folder',
- folder: {name: target.folderName, parentName: target.parentName},
- }
- : {
- type: target.type,
- target:
- target.target.type === 'composition'
- ? target.target
- : {
- type: 'folder',
- name: target.target.folderName,
- parentName: target.target.parentName,
- },
- };
- const result =
- codeMod.source.type === 'composition'
- ? moveComposition({
- ...options,
- compositionId: codeMod.source.compositionId,
- destination,
- })
- : moveFolder({
- ...options,
- folder: {
- name: codeMod.source.folderName,
- parentName: codeMod.source.parentName,
- },
- destination,
- });
- return result;
- }
-
- const folder = {name: codeMod.folderName, parentName: codeMod.parentName};
- const folderResult =
- codeMod.type === 'new-folder'
- ? addFolder({...options, folder})
- : codeMod.type === 'rename-folder'
- ? renameFolder({...options, folder, newName: codeMod.newName})
- : unwrapFolder({...options, folder});
- return folderResult;
-};
diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.ts
index 71ceb83895..177ddbae32 100644
--- a/packages/studio-server/src/preview-server/api-routes.ts
+++ b/packages/studio-server/src/preview-server/api-routes.ts
@@ -5,11 +5,22 @@ import {addEffectKeyframeHandler} from './routes/add-effect-keyframe';
import {addKeyframesHandler} from './routes/add-keyframes';
import {handleAddRender} from './routes/add-render';
import {addSequenceKeyframeHandler} from './routes/add-sequence-keyframe';
-import {applyCodemodHandler} from './routes/apply-codemod';
import {applyVisualControlHandler} from './routes/apply-visual-control-change';
import {batchUpdateKeyframeSettingsHandler} from './routes/batch-update-keyframe-settings';
import {handleCancelRender} from './routes/cancel-render';
import {compositionComponentInfoHandler} from './routes/composition-component-info';
+import {
+ addCompositionHandler,
+ addFolderHandler,
+ deleteCompositionHandler,
+ duplicateCompositionHandler,
+ moveCompositionHandler,
+ moveFolderHandler,
+ renameCompositionHandler,
+ renameFolderHandler,
+ unwrapFolderHandler,
+ updateCompositionMetadataHandler,
+} from './routes/composition-edits';
import {convertFigmaClipboardToSvgHandler} from './routes/convert-figma-clipboard-to-svg';
import {copyRenderOutputToAssetHandler} from './routes/copy-render-output-to-asset';
import {
@@ -105,7 +116,16 @@ export const allApiRoutes: {
'/api/unregister-client-render': unregisterClientRenderHandler,
'/api/update-default-props': updateDefaultPropsHandler,
'/api/apply-visual-control-change': applyVisualControlHandler,
- '/api/apply-codemod': applyCodemodHandler,
+ '/api/add-composition': addCompositionHandler,
+ '/api/duplicate-composition': duplicateCompositionHandler,
+ '/api/rename-composition': renameCompositionHandler,
+ '/api/update-composition-metadata': updateCompositionMetadataHandler,
+ '/api/delete-composition': deleteCompositionHandler,
+ '/api/move-composition': moveCompositionHandler,
+ '/api/add-folder': addFolderHandler,
+ '/api/rename-folder': renameFolderHandler,
+ '/api/unwrap-folder': unwrapFolderHandler,
+ '/api/move-folder': moveFolderHandler,
'/api/subscribe-to-default-props': subscribeToDefaultProps,
'/api/unsubscribe-from-default-props': unsubscribeFromDefaultProps,
'/api/subscribe-to-sequence-props': subscribeToSequenceProps,
diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
deleted file mode 100644
index 05501aab5e..0000000000
--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts
+++ /dev/null
@@ -1,353 +0,0 @@
-import {existsSync, readFileSync} from 'node:fs';
-import path from 'node:path';
-import {CodemodsInternals} from '@remotion/codemods';
-import {RenderInternals} from '@remotion/renderer';
-import type {
- ApplyCodemodRequest,
- ApplyCodemodResponse,
-} from '@remotion/studio-shared';
-import {
- applyCodemodToFile,
- resolveFilePathFromSymbolicatedStack,
-} from '../../codemods/apply-codemod-to-file';
-import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
-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';
-
-const {simpleDiff} = CodemodsInternals;
-
-const getFolderPath = (parentName: string | null, folderName: string) => {
- return parentName ? `${parentName}/${folderName}` : folderName;
-};
-
-export const getCodemodLogMessage = (
- codemod: ApplyCodemodRequest['codemod'],
-) => {
- if (codemod.type === 'new-composition') {
- const destination = codemod.folderName
- ? ` in folder "${getFolderPath(codemod.parentName, codemod.folderName)}"`
- : '';
- return `Created composition "${codemod.newId}"${destination}`;
- }
-
- if (codemod.type === 'duplicate-composition') {
- return `Duplicated composition "${codemod.idToDuplicate}" to "${codemod.newId}"`;
- }
-
- if (codemod.type === 'rename-composition') {
- return `Renamed composition "${codemod.idToRename}" to "${codemod.newId}"`;
- }
-
- if (codemod.type === 'update-composition-metadata') {
- return `Updated metadata of composition "${codemod.idToUpdate}"`;
- }
-
- if (codemod.type === 'delete-composition') {
- return `Deleted composition "${codemod.idToDelete}"`;
- }
-
- if (codemod.type === 'move-composition-or-folder') {
- const source =
- codemod.source.type === 'composition'
- ? `composition "${codemod.source.compositionId}"`
- : `folder "${getFolderPath(codemod.source.parentName, codemod.source.folderName)}"`;
- return `Moved ${source}`;
- }
-
- if (codemod.type === 'rename-folder') {
- const oldName = getFolderPath(codemod.parentName, codemod.folderName);
- const newName = getFolderPath(codemod.parentName, codemod.newName);
- return `Renamed folder "${oldName}" to "${newName}"`;
- }
-
- if (codemod.type === 'new-folder') {
- return `Created folder "${getFolderPath(codemod.parentName, codemod.folderName)}"`;
- }
-
- if (codemod.type === 'delete-folder') {
- return `Deleted folder "${getFolderPath(codemod.parentName, codemod.folderName)}"`;
- }
-
- if (codemod.changes.length === 1) {
- return `Updated visual control "${codemod.changes[0].id}"`;
- }
-
- return `Updated visual controls ${codemod.changes
- .map((change) => `"${change.id}"`)
- .join(', ')}`;
-};
-
-const getCodemodUndoDescription = (codemod: ApplyCodemodRequest['codemod']) => {
- if (codemod.type === 'delete-composition') {
- return {
- undoMessage: `↩️ Deletion of composition "${codemod.idToDelete}"`,
- redoMessage: `↪️ Deletion of composition "${codemod.idToDelete}"`,
- entryType: codemod.type,
- };
- }
-
- if (codemod.type === 'rename-composition') {
- const label = `composition "${codemod.idToRename}" to "${codemod.newId}"`;
- return {
- undoMessage: `↩️ Rename of ${label}`,
- redoMessage: `↪️ Rename of ${label}`,
- entryType: codemod.type,
- };
- }
-
- if (codemod.type === 'update-composition-metadata') {
- const label = `metadata of composition "${codemod.idToUpdate}"`;
- return {
- undoMessage: `↩️ Update of ${label}`,
- redoMessage: `↪️ Update of ${label}`,
- entryType: codemod.type,
- };
- }
-
- if (codemod.type === 'duplicate-composition') {
- const label = `composition "${codemod.idToDuplicate}" to "${codemod.newId}"`;
- return {
- undoMessage: `↩️ Duplication of ${label}`,
- redoMessage: `↪️ Duplication of ${label}`,
- entryType: codemod.type,
- };
- }
-
- if (codemod.type === 'move-composition-or-folder') {
- const label =
- codemod.source.type === 'composition'
- ? `composition "${codemod.source.compositionId}"`
- : `folder "${getFolderPath(codemod.source.parentName, codemod.source.folderName)}"`;
- return {
- undoMessage: `↩️ Move of ${label}`,
- redoMessage: `↪️ Move of ${label}`,
- entryType: codemod.type,
- };
- }
-
- if (codemod.type === 'new-composition') {
- return {
- undoMessage: `↩️ Creation of composition "${codemod.newId}"`,
- redoMessage: `↪️ Creation of composition "${codemod.newId}"`,
- entryType: codemod.type,
- };
- }
-
- if (codemod.type === 'delete-folder') {
- const label = `folder "${getFolderPath(codemod.parentName, codemod.folderName)}"`;
- return {
- undoMessage: `↩️ Deletion of ${label}`,
- redoMessage: `↪️ Deletion of ${label}`,
- entryType: codemod.type,
- };
- }
-
- if (codemod.type === 'new-folder') {
- const label = `folder "${getFolderPath(codemod.parentName, codemod.folderName)}"`;
- return {
- undoMessage: `↩️ Creation of ${label}`,
- redoMessage: `↪️ Creation of ${label}`,
- entryType: codemod.type,
- };
- }
-
- if (codemod.type === 'rename-folder') {
- const oldName = getFolderPath(codemod.parentName, codemod.folderName);
- const newName = getFolderPath(codemod.parentName, codemod.newName);
- const label = `folder "${oldName}" to "${newName}"`;
- return {
- undoMessage: `↩️ Rename of ${label}`,
- redoMessage: `↪️ Rename of ${label}`,
- entryType: codemod.type,
- };
- }
-
- return {
- undoMessage: '↩️ Visual control change',
- redoMessage: '↪️ Visual control change',
- entryType: 'visual-control' as const,
- };
-};
-
-export const applyCodemodHandler: ApiHandler<
- ApplyCodemodRequest,
- ApplyCodemodResponse
-> = ({
- input: {codemod, dryRun, symbolicatedStack, undoRedoNavigation},
- logLevel,
- remotionRoot,
- entryPoint,
-}) => {
- return withSourceFileWriteQueue(async () => {
- try {
- const logLine = symbolicatedStack?.originalLineNumber ?? 1;
-
- const filePath = symbolicatedStack
- ? resolveFilePathFromSymbolicatedStack(remotionRoot, symbolicatedStack)
- : (await getProjectInfo(remotionRoot, entryPoint)).rootFile;
-
- if (!filePath) {
- throw new Error('Cannot find file for composition in project');
- }
-
- checkIfTypeScriptFile(filePath);
-
- const newCompositionComponentFilePath =
- codemod.type === 'new-composition'
- ? path.join(path.dirname(filePath), `${codemod.componentName}.tsx`)
- : null;
-
- if (
- codemod.type === 'new-composition' &&
- newCompositionComponentFilePath &&
- existsSync(newCompositionComponentFilePath)
- ) {
- throw new Error(
- `Cannot create ${path.relative(
- remotionRoot,
- newCompositionComponentFilePath,
- )} because it already exists`,
- );
- }
-
- const input = readFileSync(filePath, 'utf-8');
- const result = await applyCodemodToFile({
- filePath,
- codeMod: codemod,
- });
-
- const formatted =
- result.changes.find((change) => change.filePath === filePath)
- ?.nextContents ?? input;
-
- const diff = simpleDiff({
- oldLines: input.split('\n'),
- newLines: formatted.split('\n'),
- });
-
- if (!dryRun) {
- if (readFileSync(filePath, 'utf-8') !== input) {
- throw new Error(
- `Source changed before applying codemod: ${filePath}`,
- );
- }
-
- 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 {entryType, undoMessage, redoMessage} =
- getCodemodUndoDescription(codemod);
- const snapshots: Parameters<
- typeof pushTransactionToUndoStack
- >[0]['snapshots'] = [
- {
- filePath,
- oldContents: input,
- newContents: null,
- logLine,
- nodePathRemappings: null,
- },
- ];
- let componentFilePath: string | null = null;
- let componentFileContents: string | null = null;
-
- if (codemod.type === 'new-composition') {
- componentFilePath = newCompositionComponentFilePath;
- if (componentFilePath === null) {
- throw new Error('Could not determine the new component file path');
- }
-
- componentFileContents =
- result.changes.find(
- (change) => change.filePath === componentFilePath,
- )?.nextContents ?? null;
- if (componentFileContents === null) {
- throw new Error('Could not create the composition component');
- }
-
- snapshots.push({
- filePath: componentFilePath,
- oldContents: null,
- newContents: componentFileContents,
- logLine: 1,
- nodePathRemappings: null,
- });
- }
-
- pushTransactionToUndoStack({
- snapshots,
- logLevel,
- remotionRoot,
- description: {
- undoMessage,
- redoMessage,
- },
- entryType,
- suppressHmrOnFileRestore: false,
- undoRedoNavigation,
- });
-
- suppressUndoStackInvalidation(filePath);
- if (componentFilePath) {
- suppressUndoStackInvalidation(componentFilePath);
- }
-
- writeFileAndNotifyFileWatchers({
- file: filePath,
- content: formatted,
- originatorClientId: undefined,
- metadata: null,
- });
- if (componentFilePath && componentFileContents !== null) {
- writeFileAndNotifyFileWatchers({
- file: componentFilePath,
- content: componentFileContents,
- originatorClientId: undefined,
- metadata: null,
- });
- }
-
- const logMessage = getCodemodLogMessage(codemod);
- const editMessage = `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(
- formatLogFileLocation({
- remotionRoot,
- absolutePath: filePath,
- line: logLine,
- }),
- )} ${logMessage}`;
- RenderInternals.Log.info({indent: false, logLevel}, editMessage);
- printUndoHint(logLevel);
- }
-
- return {
- success: true,
- diff,
- };
- } catch (err) {
- return {
- success: false,
- reason: (err as Error).message,
- stack: (err as Error).stack as string,
- };
- }
- });
-};
diff --git a/packages/studio-server/src/preview-server/routes/composition-edits.ts b/packages/studio-server/src/preview-server/routes/composition-edits.ts
new file mode 100644
index 0000000000..cfa832cae5
--- /dev/null
+++ b/packages/studio-server/src/preview-server/routes/composition-edits.ts
@@ -0,0 +1,426 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
+import {
+ addFolder,
+ deleteComposition,
+ duplicateComposition,
+ moveComposition,
+ moveFolder,
+ renameComposition,
+ renameFolder,
+ unwrapFolder,
+ updateCompositionMetadata,
+ type CodemodNodeResult,
+ type CodemodResult,
+ type CompositionDestination as CodemodCompositionDestination,
+} from '@remotion/codemods';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ AddCompositionRequest,
+ AddFolderRequest,
+ CompositionDestination,
+ CompositionEditResponse,
+ DeleteCompositionRequest,
+ DuplicateCompositionRequest,
+ MoveCompositionRequest,
+ MoveFolderRequest,
+ RenameCompositionRequest,
+ RenameFolderRequest,
+ SymbolicatedStackFrame,
+ UnwrapFolderRequest,
+ UpdateCompositionMetadataRequest,
+} from '@remotion/studio-shared';
+import {addCompositionToFile} from '../../codemods/add-composition-to-file';
+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;
+};
+
+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'];
+
+const runCompositionEdit = <
+ Request extends {
+ symbolicatedStack: SymbolicatedStackFrame | null;
+ undoRedoNavigation: AddCompositionRequest['undoRedoNavigation'];
+ },
+>({
+ 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 ?? '') : '',
+ };
+ }
+ });
+};
+
+const getProject = (filePath: string) => ({
+ files: {[filePath]: readFileSync(filePath, 'utf-8')},
+ rootDir: path.dirname(filePath),
+});
+
+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}),
+});
+
+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: getProject(filePath),
+ compositionFile: filePath,
+ compositionId: request.idToDuplicate,
+ newId: request.newId,
+ tag: request.tag,
+ metadata: {
+ width: request.newWidth ?? undefined,
+ height: request.newHeight ?? undefined,
+ fps:
+ request.tag === 'Still' ? undefined : (request.newFps ?? undefined),
+ durationInFrames:
+ request.tag === 'Still'
+ ? undefined
+ : (request.newDurationInFrames ?? undefined),
+ },
+ }),
+ });
+
+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: getProject(filePath),
+ compositionFile: filePath,
+ compositionId: request.idToRename,
+ newId: request.newId,
+ }),
+ });
+
+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: getProject(filePath),
+ compositionFile: filePath,
+ compositionId: request.idToUpdate,
+ metadata: {
+ width: request.newWidth ?? undefined,
+ height: request.newHeight ?? undefined,
+ fps: request.newFps ?? undefined,
+ durationInFrames: request.newDurationInFrames ?? undefined,
+ },
+ }),
+ });
+
+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: getProject(filePath),
+ compositionFile: filePath,
+ compositionId: request.idToDelete,
+ }),
+ });
+
+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: getProject(filePath),
+ compositionFile: filePath,
+ compositionId: request.compositionId,
+ destination: toCodemodDestination(request.destination),
+ }),
+ });
+
+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: getProject(filePath),
+ compositionFile: filePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ }),
+});
+
+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: getProject(filePath),
+ compositionFile: filePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ newName: request.newName,
+ }),
+});
+
+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: getProject(filePath),
+ compositionFile: filePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ }),
+});
+
+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: getProject(filePath),
+ compositionFile: filePath,
+ folder: {name: request.folderName, parentName: request.parentName},
+ destination: toCodemodDestination(request.destination),
+ }),
+});
diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.ts
index 1f8ba0b096..2c4911facf 100644
--- a/packages/studio-server/src/preview-server/routes/insert-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts
@@ -14,16 +14,14 @@ import type {
InsertElementRequest,
InsertElementResponse,
} from '@remotion/studio-shared';
-import {
- applyCodemodToFile,
- resolveFilePathFromSymbolicatedStack,
-} from '../../codemods/apply-codemod-to-file';
+import {addCompositionToFile} from '../../codemods/add-composition-to-file';
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {
assertNoSymlinks,
openFileForWritingWithoutSymlinks,
} from '../../helpers/open-file-for-writing-without-symlinks';
import {insertJsxElementIntoComposition} from '../../helpers/resolve-composition-component';
+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';
@@ -170,17 +168,19 @@ export const insertElementHandler: ApiHandler<
let sourceFileOverrides: ReadonlyMap<string, string> | null = null;
if (newComposition !== null) {
- if (newComposition.codemod.newId !== compositionId) {
+ if (newComposition.options.newId !== compositionId) {
throw new Error(
'New composition ID does not match installation target',
);
}
const registrationFilePath = newComposition.symbolicatedStack
- ? resolveFilePathFromSymbolicatedStack(
+ ?.originalFileName
+ ? resolveFileInsideProject({
remotionRoot,
- newComposition.symbolicatedStack,
- )
+ fileName: newComposition.symbolicatedStack.originalFileName,
+ action: 'add a composition to',
+ }).absolutePath
: (await getProjectInfo(remotionRoot, entryPoint)).rootFile;
if (registrationFilePath === null) {
throw new Error('Cannot find file for composition in project');
@@ -197,7 +197,7 @@ export const insertElementHandler: ApiHandler<
const componentFilePath = path.join(
path.dirname(registrationFilePath),
- `${newComposition.codemod.componentName}.tsx`,
+ `${newComposition.options.componentName}.tsx`,
);
if (existsSync(componentFilePath)) {
throw new Error(
@@ -212,9 +212,9 @@ export const insertElementHandler: ApiHandler<
registrationFilePath,
'utf-8',
);
- const codemodResult = await applyCodemodToFile({
+ const codemodResult = await addCompositionToFile({
filePath: registrationFilePath,
- codeMod: newComposition.codemod,
+ options: newComposition.options,
});
const registrationFileNewContents =
codemodResult.changes.find(
diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/composition-edits.test.ts
similarity index 72%
rename from packages/studio-server/src/test/apply-codemod.test.ts
rename to packages/studio-server/src/test/composition-edits.test.ts
index 9ac216a545..d7e1a73d64 100644
--- a/packages/studio-server/src/test/apply-codemod.test.ts
+++ b/packages/studio-server/src/test/composition-edits.test.ts
@@ -8,18 +8,27 @@ import {
} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';
-import type {RecastCodemod} from '@remotion/studio-shared';
-import {applyCodemodToFile} from '../codemods/apply-codemod-to-file';
+import {renameFolder, updateCompositionMetadata} from '@remotion/codemods';
+import type {
+ CompositionEditResponse,
+ SymbolicatedStackFrame,
+ UndoRedoNavigation,
+} from '@remotion/studio-shared';
import {
createFileWatcherRegistry,
setFileWatcherRegistry,
} from '../file-watcher';
+import type {ApiHandler} from '../preview-server/api-types';
import {setLiveEventsListener} from '../preview-server/live-events';
-import {
- applyCodemodHandler,
- getCodemodLogMessage,
-} from '../preview-server/routes/apply-codemod';
import {applyVisualControlHandler} from '../preview-server/routes/apply-visual-control-change';
+import {
+ addCompositionHandler,
+ addFolderHandler,
+ deleteCompositionHandler,
+ duplicateCompositionHandler,
+ moveCompositionHandler,
+ renameCompositionHandler,
+} from '../preview-server/routes/composition-edits';
import {redoHandler} from '../preview-server/routes/redo';
import {undoHandler} from '../preview-server/routes/undo';
import {getRedoStack, getUndoStack} from '../preview-server/undo-stack';
@@ -95,7 +104,7 @@ const clearUndoRedoStacks = () => {
(getRedoStack() as unknown as unknown[]).length = 0;
};
-test('folder codemods do not run Prettier after applying source edits', async () => {
+test('folder edits do not run Prettier after applying source edits', () => {
const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
const filePath = path.join(remotionRoot, 'Root.tsx');
const input = `import {Folder} from 'remotion';
@@ -106,14 +115,11 @@ export const Root = () => <Folder name="Before" />;
try {
writeFileSync(filePath, input);
- const output = await applyCodemodToFile({
- filePath,
- codeMod: {
- type: 'rename-folder',
- folderName: 'Before',
- parentName: null,
- newName: 'After',
- },
+ const output = renameFolder({
+ project: {rootDir: remotionRoot, files: {[filePath]: input}},
+ compositionFile: filePath,
+ folder: {name: 'Before', parentName: null},
+ newName: 'After',
});
expect(output.changes[0].nextContents).toBe(
@@ -124,7 +130,7 @@ export const Root = () => <Folder name="Before" />;
}
});
-test('metadata codemods do not run Prettier after applying source edits', async () => {
+test('metadata edits do not run Prettier after applying source edits', () => {
const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
const filePath = path.join(remotionRoot, 'Root.tsx');
const input = `import {Composition} from 'remotion';
@@ -134,15 +140,14 @@ export const Root=()=> <Composition id='Comp' width = { WIDTH }/>;
try {
writeFileSync(filePath, input);
- const output = await applyCodemodToFile({
- filePath,
- codeMod: {
- type: 'update-composition-metadata',
- idToUpdate: 'Comp',
- newDurationInFrames: 90,
- newFps: null,
- newHeight: 1080,
- newWidth: 1920,
+ const output = updateCompositionMetadata({
+ project: {rootDir: remotionRoot, files: {[filePath]: input}},
+ compositionFile: filePath,
+ compositionId: 'Comp',
+ metadata: {
+ durationInFrames: 90,
+ height: 1080,
+ width: 1920,
},
});
@@ -156,38 +161,6 @@ export const Root=()=> <Composition id='Comp' width = {1920} durationInFrames={9
}
});
-test('visual-control codemods do not run Prettier after applying source edits', async () => {
- const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
- const filePath = path.join(remotionRoot, 'Root.tsx');
- const input = `const untouched = { value : "keep" };
-export const Root=()=> visualControl('opacity', OPACITY);
-`;
-
- try {
- writeFileSync(filePath, input);
- const output = await applyCodemodToFile({
- filePath,
- codeMod: {
- type: 'apply-visual-control',
- changes: [
- {
- id: 'opacity',
- newValueSerialized: '0.5',
- newValueIsUndefined: false,
- enumPaths: [],
- },
- ],
- },
- });
-
- expect(output.changes[0].nextContents).toBe(
- input.replace('OPACITY', '0.5'),
- );
- } finally {
- rmSync(remotionRoot, {recursive: true, force: true});
- }
-});
-
test('visual-control handler preserves source formatting', async () => {
const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
const cleanupFileWatcher = setFileWatcherRegistry(
@@ -239,150 +212,6 @@ export const Root=()=> visualControl('opacity', OPACITY);
}
});
-test('formats precise log messages for all codemods', () => {
- const testCases: {codemod: RecastCodemod; expected: string}[] = [
- {
- codemod: {
- type: 'new-composition',
- asset: null,
- canvasCapture: null,
- newId: 'FreshVideo',
- componentName: 'FreshVideo',
- componentImportPath: './FreshVideo',
- folderName: 'Shared',
- parentName: 'Parent',
- newDurationInFrames: 150,
- newFps: 30,
- newHeight: 1080,
- newWidth: 1920,
- },
- expected: 'Created composition "FreshVideo" in folder "Parent/Shared"',
- },
- {
- codemod: {
- type: 'duplicate-composition',
- idToDuplicate: 'Original',
- newId: 'Copy',
- newDurationInFrames: null,
- newFps: null,
- newHeight: null,
- newWidth: null,
- tag: 'Composition',
- },
- expected: 'Duplicated composition "Original" to "Copy"',
- },
- {
- codemod: {
- type: 'rename-composition',
- idToRename: 'Original',
- newId: 'Renamed',
- },
- expected: 'Renamed composition "Original" to "Renamed"',
- },
- {
- codemod: {
- type: 'update-composition-metadata',
- idToUpdate: 'Original',
- newDurationInFrames: null,
- newFps: null,
- newHeight: null,
- newWidth: 1920,
- },
- expected: 'Updated metadata of composition "Original"',
- },
- {
- codemod: {type: 'delete-composition', idToDelete: 'DeleteMe'},
- expected: 'Deleted composition "DeleteMe"',
- },
- {
- codemod: {
- type: 'move-composition-or-folder',
- source: {type: 'composition', compositionId: 'MoveMe'},
- destination: {
- type: 'before',
- target: {type: 'folder', folderName: 'Shared', parentName: null},
- },
- },
- expected: 'Moved composition "MoveMe"',
- },
- {
- codemod: {
- type: 'move-composition-or-folder',
- source: {
- type: 'folder',
- folderName: 'Shared',
- parentName: 'Parent',
- },
- destination: {type: 'root'},
- },
- expected: 'Moved folder "Parent/Shared"',
- },
- {
- codemod: {
- type: 'rename-folder',
- folderName: 'Old',
- parentName: 'Parent',
- newName: 'New',
- },
- expected: 'Renamed folder "Parent/Old" to "Parent/New"',
- },
- {
- codemod: {
- type: 'new-folder',
- folderName: 'New',
- parentName: 'Parent',
- },
- expected: 'Created folder "Parent/New"',
- },
- {
- codemod: {
- type: 'delete-folder',
- folderName: 'DeleteMe',
- parentName: 'Parent',
- },
- expected: 'Deleted folder "Parent/DeleteMe"',
- },
- {
- codemod: {
- type: 'apply-visual-control',
- changes: [
- {
- id: 'opacity',
- newValueSerialized: '0.5',
- newValueIsUndefined: false,
- enumPaths: [],
- },
- ],
- },
- expected: 'Updated visual control "opacity"',
- },
- {
- codemod: {
- type: 'apply-visual-control',
- changes: [
- {
- id: 'opacity',
- newValueSerialized: '0.5',
- newValueIsUndefined: false,
- enumPaths: [],
- },
- {
- id: 'scale',
- newValueSerialized: '2',
- newValueIsUndefined: false,
- enumPaths: [],
- },
- ],
- },
- expected: 'Updated visual controls "opacity", "scale"',
- },
- ];
-
- for (const {codemod, expected} of testCases) {
- expect(getCodemodLogMessage(codemod)).toBe(expected);
- }
-});
-
const getHandlerOptions = <T>({
input,
entryPoint,
@@ -412,16 +241,25 @@ const getHandlerOptions = <T>({
getDefaultEditor: () => null,
});
-const runCompositionCodemodUndoRedoTest = async ({
- codemod,
+type CompositionEditRequest = {
+ symbolicatedStack: SymbolicatedStackFrame | null;
+ undoRedoNavigation: UndoRedoNavigation | null;
+};
+
+const runCompositionEditUndoRedoTest = async <
+ Request extends CompositionEditRequest,
+>({
+ handler,
+ request,
assertApplied,
expectedUndoMessage,
expectedLogMessage,
}: {
- codemod: RecastCodemod;
+ handler: ApiHandler<Request, CompositionEditResponse>;
+ request: Request;
assertApplied: (contents: string) => void;
expectedUndoMessage: string;
- expectedLogMessage?: string;
+ expectedLogMessage: string | null;
}) => {
const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
const cleanupFileWatcher = setFileWatcherRegistry(
@@ -443,12 +281,10 @@ const runCompositionCodemodUndoRedoTest = async ({
const entryPoint = path.join(remotionRoot, 'Root.tsx');
writeFileSync(entryPoint, rootContents);
- const applyResponse = await applyCodemodHandler(
+ const applyResponse = await handler(
getHandlerOptions({
input: {
- codemod,
- dryRun: false,
- undoRedoNavigation: null,
+ ...request,
symbolicatedStack: {
originalFunctionName: null,
originalFileName: 'Root.tsx',
@@ -499,23 +335,31 @@ const runCompositionCodemodUndoRedoTest = async ({
}
};
-test('applyCodemodHandler pushes composition deletions to undo and redo stacks', async () => {
- await runCompositionCodemodUndoRedoTest({
- codemod: {type: 'delete-composition', idToDelete: 'DeleteMe'},
+test('deleteCompositionHandler pushes composition deletions to undo and redo stacks', async () => {
+ await runCompositionEditUndoRedoTest({
+ handler: deleteCompositionHandler,
+ request: {
+ idToDelete: 'DeleteMe',
+ undoRedoNavigation: null,
+ symbolicatedStack: null,
+ },
assertApplied: (contents) => {
expect(contents).not.toContain('id="DeleteMe"');
expect(contents).toContain('id="KeepMe"');
},
expectedUndoMessage: '↩️ Deletion of composition "DeleteMe"',
+ expectedLogMessage: null,
});
});
-test('applyCodemodHandler logs composition renames and pushes them to the undo and redo stacks', async () => {
- await runCompositionCodemodUndoRedoTest({
- codemod: {
- type: 'rename-composition',
+test('renameCompositionHandler logs composition renames and pushes them to the undo and redo stacks', async () => {
+ await runCompositionEditUndoRedoTest({
+ handler: renameCompositionHandler,
+ request: {
idToRename: 'DeleteMe',
newId: 'Renamed',
+ undoRedoNavigation: null,
+ symbolicatedStack: null,
},
assertApplied: (contents) => {
expect(contents).not.toContain('id="DeleteMe"');
@@ -527,11 +371,11 @@ test('applyCodemodHandler logs composition renames and pushes them to the undo a
});
});
-test('applyCodemodHandler pushes composition and still duplications to undo and redo stacks', async () => {
+test('duplicateCompositionHandler pushes composition and still duplications to undo and redo stacks', async () => {
for (const tag of ['Composition', 'Still'] as const) {
- await runCompositionCodemodUndoRedoTest({
- codemod: {
- type: 'duplicate-composition',
+ await runCompositionEditUndoRedoTest({
+ handler: duplicateCompositionHandler,
+ request: {
idToDuplicate: 'DeleteMe',
newId: 'Duplicated',
newDurationInFrames: 120,
@@ -539,6 +383,8 @@ test('applyCodemodHandler pushes composition and still duplications to undo and
newHeight: null,
newWidth: null,
tag,
+ undoRedoNavigation: null,
+ symbolicatedStack: null,
},
assertApplied: (contents) => {
expect(contents).toContain('id="DeleteMe"');
@@ -553,26 +399,30 @@ test('applyCodemodHandler pushes composition and still duplications to undo and
},
expectedUndoMessage:
'↩️ Duplication of composition "DeleteMe" to "Duplicated"',
+ expectedLogMessage: null,
});
}
});
-test('applyCodemodHandler pushes folder creations to undo and redo stacks', async () => {
- await runCompositionCodemodUndoRedoTest({
- codemod: {
- type: 'new-folder',
+test('addFolderHandler pushes folder creations to undo and redo stacks', async () => {
+ await runCompositionEditUndoRedoTest({
+ handler: addFolderHandler,
+ request: {
folderName: 'FreshFolder',
parentName: null,
+ undoRedoNavigation: null,
+ symbolicatedStack: null,
},
assertApplied: (contents) => {
expect(contents).toContain('<Folder name="FreshFolder" />');
expect(contents).toContain('id="KeepMe"');
},
expectedUndoMessage: '↩️ Creation of folder "FreshFolder"',
+ expectedLogMessage: null,
});
});
-test('applyCodemodHandler pushes composition moves to undo and redo stacks', async () => {
+test('moveCompositionHandler pushes composition moves to undo and redo stacks', async () => {
const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
const cleanupFileWatcher = setFileWatcherRegistry(
createFileWatcherRegistry(),
@@ -590,19 +440,15 @@ test('applyCodemodHandler pushes composition moves to undo and redo stacks', asy
const entryPoint = path.join(remotionRoot, 'Root.tsx');
writeFileSync(entryPoint, folderRootContents);
- const applyResponse = await applyCodemodHandler(
+ const applyResponse = await moveCompositionHandler(
getHandlerOptions({
input: {
- codemod: {
- type: 'move-composition-or-folder',
- source: {type: 'composition', compositionId: 'NestedA'},
- destination: {
- type: 'folder',
- folderName: 'Shared',
- parentName: 'Other',
- },
- } satisfies RecastCodemod,
- dryRun: false,
+ compositionId: 'NestedA',
+ destination: {
+ type: 'folder',
+ folderName: 'Shared',
+ parentName: 'Other',
+ },
undoRedoNavigation: null,
symbolicatedStack: {
originalFunctionName: null,
@@ -618,6 +464,11 @@ test('applyCodemodHandler pushes composition moves to undo and redo stacks', asy
);
expect(applyResponse.success).toBe(true);
+ if (!applyResponse.success) {
+ throw new Error(applyResponse.reason);
+ }
+
+ expect(applyResponse.nodePathMutation).not.toBeNull();
const contents = readFileSync(entryPoint, 'utf-8');
expect(contents.indexOf('id="NestedB"')).toBeLessThan(
contents.indexOf('id="NestedA"'),
@@ -639,7 +490,7 @@ test('applyCodemodHandler pushes composition moves to undo and redo stacks', asy
}
});
-test('applyCodemodHandler pushes composition moves to root to undo and redo stacks', async () => {
+test('moveCompositionHandler pushes composition moves to root to undo and redo stacks', async () => {
const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
const cleanupFileWatcher = setFileWatcherRegistry(
createFileWatcherRegistry(),
@@ -657,15 +508,11 @@ test('applyCodemodHandler pushes composition moves to root to undo and redo stac
const entryPoint = path.join(remotionRoot, 'Root.tsx');
writeFileSync(entryPoint, folderRootContents);
- const applyResponse = await applyCodemodHandler(
+ const applyResponse = await moveCompositionHandler(
getHandlerOptions({
input: {
- codemod: {
- type: 'move-composition-or-folder',
- source: {type: 'composition', compositionId: 'NestedA'},
- destination: {type: 'root'},
- } satisfies RecastCodemod,
- dryRun: false,
+ compositionId: 'NestedA',
+ destination: {type: 'root'},
undoRedoNavigation: null,
symbolicatedStack: {
originalFunctionName: null,
@@ -681,6 +528,11 @@ test('applyCodemodHandler pushes composition moves to root to undo and redo stac
);
expect(applyResponse.success).toBe(true);
+ if (!applyResponse.success) {
+ throw new Error(applyResponse.reason);
+ }
+
+ expect(applyResponse.nodePathMutation).not.toBeNull();
const contents = readFileSync(entryPoint, 'utf-8');
expect(contents.indexOf('id="NestedB"')).toBeLessThan(
contents.indexOf('id="NestedA"'),
@@ -702,7 +554,7 @@ test('applyCodemodHandler pushes composition moves to root to undo and redo stac
}
});
-test('applyCodemodHandler creates new composition files with undo and redo', async () => {
+test('addCompositionHandler creates new composition files with undo and redo', async () => {
const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
const cleanupFileWatcher = setFileWatcherRegistry(
createFileWatcherRegistry(),
@@ -721,11 +573,10 @@ test('applyCodemodHandler creates new composition files with undo and redo', asy
const componentFile = path.join(remotionRoot, 'FreshVideo.tsx');
writeFileSync(entryPoint, rootContents);
- const applyResponse = await applyCodemodHandler(
+ const applyResponse = await addCompositionHandler(
getHandlerOptions({
input: {
- codemod: {
- type: 'new-composition',
+ options: {
asset: null,
canvasCapture: null,
newId: 'FreshVideo',
@@ -737,8 +588,7 @@ test('applyCodemodHandler creates new composition files with undo and redo', asy
newFps: 30,
newHeight: 1080,
newWidth: 1920,
- } satisfies RecastCodemod,
- dryRun: false,
+ },
undoRedoNavigation: null,
symbolicatedStack: {
originalFunctionName: null,
@@ -801,7 +651,7 @@ test('applyCodemodHandler creates new composition files with undo and redo', asy
}
});
-test('applyCodemodHandler creates an interactive Canvas Capture composition', async () => {
+test('addCompositionHandler creates an interactive Canvas Capture composition', async () => {
const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
const cleanupFileWatcher = setFileWatcherRegistry(
createFileWatcherRegistry(),
@@ -820,11 +670,10 @@ test('applyCodemodHandler creates an interactive Canvas Capture composition', as
const componentFile = path.join(remotionRoot, 'FreshCapture.tsx');
writeFileSync(entryPoint, rootContents);
- const applyResponse = await applyCodemodHandler(
+ const applyResponse = await addCompositionHandler(
getHandlerOptions({
input: {
- codemod: {
- type: 'new-composition',
+ options: {
asset: null,
canvasCapture: {
videoFileName: 'capture.mp4',
@@ -863,8 +712,7 @@ test('applyCodemodHandler creates an interactive Canvas Capture composition', as
newFps: 30,
newHeight: 720,
newWidth: 1280,
- } satisfies RecastCodemod,
- dryRun: false,
+ },
undoRedoNavigation: null,
symbolicatedStack: {
originalFunctionName: null,
diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.ts
index fd7bb30f53..58d59a4c10 100644
--- a/packages/studio-server/src/test/insert-element.test.ts
+++ b/packages/studio-server/src/test/insert-element.test.ts
@@ -476,8 +476,7 @@ test('invalidates a new-composition install after an external component edit', a
position: null,
undoRedoNavigation: null,
newComposition: {
- codemod: {
- type: 'new-composition',
+ options: {
asset: null,
newId: 'ElementScene',
componentName: 'ElementScene',
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 7dd090e7dc..033510901a 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -27,7 +27,11 @@ import type {
SequencePropsSubscriptionKey,
VideoConfigValues,
} from 'remotion';
-import type {RecastCodemod, VisualControlChange} from './codemods';
+import type {
+ CompositionDestination,
+ NewCompositionOptions,
+ VisualControlChange,
+} from './codemods';
import type {
EffectClipboardParam,
EffectClipboardPasteType,
@@ -313,26 +317,78 @@ export type UndoRedoNavigation = {
redoRoute: string;
};
-export type ApplyCodemodRequest = {
- codemod: RecastCodemod;
- dryRun: boolean;
+type CompositionEditRequest = {
symbolicatedStack: SymbolicatedStackFrame | null;
undoRedoNavigation: UndoRedoNavigation | null;
};
-export type SimpleDiff = {
- additions: number;
- deletions: number;
+export type AddCompositionRequest = CompositionEditRequest & {
+ options: NewCompositionOptions;
+};
+
+export type DuplicateCompositionRequest = CompositionEditRequest & {
+ idToDuplicate: string;
+ newId: string;
+ newHeight: number | null;
+ newWidth: number | null;
+ newFps: number | null;
+ newDurationInFrames: number | null;
+ tag: 'Still' | 'Composition';
+};
+
+export type RenameCompositionRequest = CompositionEditRequest & {
+ idToRename: string;
+ newId: string;
+};
+
+export type UpdateCompositionMetadataRequest = CompositionEditRequest & {
+ idToUpdate: string;
+ newDurationInFrames: number | null;
+ newFps: number | null;
+ newHeight: number | null;
+ newWidth: number | null;
+};
+
+export type DeleteCompositionRequest = CompositionEditRequest & {
+ idToDelete: string;
+};
+
+export type MoveCompositionRequest = CompositionEditRequest & {
+ compositionId: string;
+ destination: CompositionDestination;
+};
+
+export type AddFolderRequest = CompositionEditRequest & {
+ folderName: string;
+ parentName: string | null;
};
-export type ApplyCodemodResponse =
+export type RenameFolderRequest = CompositionEditRequest & {
+ folderName: string;
+ parentName: string | null;
+ newName: string;
+};
+
+export type UnwrapFolderRequest = CompositionEditRequest & {
+ folderName: string;
+ parentName: string | null;
+};
+
+export type MoveFolderRequest = CompositionEditRequest & {
+ folderName: string;
+ parentName: string | null;
+ destination: CompositionDestination;
+};
+
+export type CompositionEditResponse =
| {
success: true;
- diff: SimpleDiff;
+ nodePathMutation: SequenceNodePathMutation | null;
}
| {
success: false;
reason: string;
+ stack: string;
};
export type DeleteStaticFileRequest = {
@@ -1153,7 +1209,7 @@ export type InsertElementRequest = {
overwriteExisting: boolean;
undoRedoNavigation: UndoRedoNavigation | null;
newComposition: {
- codemod: Extract<RecastCodemod, {type: 'new-composition'}>;
+ options: NewCompositionOptions;
symbolicatedStack: SymbolicatedStackFrame | null;
} | null;
};
@@ -1563,7 +1619,34 @@ export type ApiRoutes = {
RemoveRemotionSkillRequest,
GetRemotionSkillsInfoResponse
>;
- '/api/apply-codemod': ReqAndRes<ApplyCodemodRequest, ApplyCodemodResponse>;
+ '/api/add-composition': ReqAndRes<
+ AddCompositionRequest,
+ CompositionEditResponse
+ >;
+ '/api/duplicate-composition': ReqAndRes<
+ DuplicateCompositionRequest,
+ CompositionEditResponse
+ >;
+ '/api/rename-composition': ReqAndRes<
+ RenameCompositionRequest,
+ CompositionEditResponse
+ >;
+ '/api/update-composition-metadata': ReqAndRes<
+ UpdateCompositionMetadataRequest,
+ CompositionEditResponse
+ >;
+ '/api/delete-composition': ReqAndRes<
+ DeleteCompositionRequest,
+ CompositionEditResponse
+ >;
+ '/api/move-composition': ReqAndRes<
+ MoveCompositionRequest,
+ CompositionEditResponse
+ >;
+ '/api/add-folder': ReqAndRes<AddFolderRequest, CompositionEditResponse>;
+ '/api/rename-folder': ReqAndRes<RenameFolderRequest, CompositionEditResponse>;
+ '/api/unwrap-folder': ReqAndRes<UnwrapFolderRequest, CompositionEditResponse>;
+ '/api/move-folder': ReqAndRes<MoveFolderRequest, CompositionEditResponse>;
'/api/project-info': ReqAndRes<ProjectInfoRequest, ProjectInfoResponse>;
'/api/delete-static-file': ReqAndRes<
DeleteStaticFileRequest,
diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.ts
index 4a30bdaf16..b493d91094 100644
--- a/packages/studio-shared/src/browser-studio-operations.ts
+++ b/packages/studio-shared/src/browser-studio-operations.ts
@@ -3,16 +3,18 @@ import type {
AddEffectKeyframeResponse,
AddEffectRequest,
AddEffectResponse,
+ AddCompositionRequest,
+ AddFolderRequest,
AddKeyframesRequest,
AddKeyframesResponse,
AddSequenceKeyframeRequest,
AddSequenceKeyframeResponse,
- ApplyCodemodRequest,
- ApplyCodemodResponse,
BatchUpdateKeyframeSettingsRequest,
BatchUpdateKeyframeSettingsResponse,
CompositionComponentInfoRequest,
CompositionComponentInfoResponse,
+ CompositionEditResponse,
+ DeleteCompositionRequest,
DeleteNodesRequest,
DeleteNodesResponse,
DeleteKeyframesRequest,
@@ -27,6 +29,7 @@ import type {
FindInFileResponse,
DuplicateEffectRequest,
DuplicateEffectResponse,
+ DuplicateCompositionRequest,
PrecomposeJsxNodesRequest,
PrecomposeJsxNodesResponse,
DuplicateNodesRequest,
@@ -38,15 +41,18 @@ import type {
InsertElementRequest,
InsertElementResponse,
InstallPackageRequest,
- UndoRedoNavigation,
InstallableElement,
MoveKeyframesRequest,
MoveKeyframesResponse,
+ MoveCompositionRequest,
+ MoveFolderRequest,
PasteEffectsRequest,
PasteEffectsResponse,
PrepareElementInstallRequest,
PrepareElementInstallResponse,
RedoResponse,
+ RenameCompositionRequest,
+ RenameFolderRequest,
RenameStaticFileRequest,
RenameStaticFileResponse,
ReorderEffectRequest,
@@ -59,7 +65,6 @@ import type {
SaveEffectPropsResponse,
SaveMultipleEffectPropsRequest,
SaveMultipleEffectPropsResponse,
- SimpleDiff,
SplitSequencesRequest,
SplitSequencesResponse,
SplitVideoFromAudioRequest,
@@ -77,12 +82,13 @@ import type {
UnsubscribeFromSequencePropsRequest,
UpdateDefaultPropsRequest,
UpdateDefaultPropsResponse,
+ UpdateCompositionMetadataRequest,
UpdateEffectKeyframeSettingsRequest,
UpdateEffectKeyframeSettingsResponse,
UpdateSequenceKeyframeSettingsRequest,
UpdateSequenceKeyframeSettingsResponse,
+ UnwrapFolderRequest,
} from './api-requests';
-import type {RecastCodemod} from './codemods';
import type {EventSourceEvent} from './event-source-event';
export type WriteStaticFileRequest = {
@@ -90,23 +96,6 @@ export type WriteStaticFileRequest = {
filePath: string;
};
-export type DuplicateCompositionRequest = {
- codemod: Extract<RecastCodemod, {type: 'duplicate-composition'}>;
- dryRun: boolean;
- undoRedoNavigation: UndoRedoNavigation | null;
-};
-
-export type DuplicateCompositionResponse =
- | {
- success: true;
- diff: SimpleDiff;
- }
- | {
- success: false;
- reason: string;
- stack: string;
- };
-
export type BrowserStudioKeyframeOperations = {
addEffectKeyframe: (
request: AddEffectKeyframeRequest,
@@ -173,7 +162,13 @@ export type BrowserStudioOperations = {
element: InstallableElement;
sourceOrigin: string | null;
} | null;
- applyCodemod: (request: ApplyCodemodRequest) => Promise<ApplyCodemodResponse>;
+ addComposition: (
+ request: AddCompositionRequest,
+ ) => Promise<CompositionEditResponse>;
+ addFolder: (request: AddFolderRequest) => Promise<CompositionEditResponse>;
+ deleteComposition: (
+ request: DeleteCompositionRequest,
+ ) => Promise<CompositionEditResponse>;
deleteNodes: (request: DeleteNodesRequest) => Promise<DeleteNodesResponse>;
deleteStaticFile: (
request: DeleteStaticFileRequest,
@@ -187,7 +182,7 @@ export type BrowserStudioOperations = {
) => Promise<DownloadRemoteAssetResponse>;
duplicateComposition: (
request: DuplicateCompositionRequest,
- ) => Promise<DuplicateCompositionResponse>;
+ ) => Promise<CompositionEditResponse>;
precomposeJsxNodes: (
request: PrecomposeJsxNodesRequest,
) => Promise<PrecomposeJsxNodesResponse>;
@@ -208,11 +203,27 @@ export type BrowserStudioOperations = {
insertCompositionElement: (
request: InsertCompositionElementRequest,
) => Promise<InsertCompositionElementResponse>;
+ moveComposition: (
+ request: MoveCompositionRequest,
+ ) => Promise<CompositionEditResponse>;
+ moveFolder: (request: MoveFolderRequest) => Promise<CompositionEditResponse>;
keyframes: BrowserStudioKeyframeOperations;
packageInstallation: BrowserStudioPackageInstallationOperations;
prepareElementInstall: (
request: PrepareElementInstallRequest,
) => Promise<PrepareElementInstallResponse>;
+ renameComposition: (
+ request: RenameCompositionRequest,
+ ) => Promise<CompositionEditResponse>;
+ renameFolder: (
+ request: RenameFolderRequest,
+ ) => Promise<CompositionEditResponse>;
+ unwrapFolder: (
+ request: UnwrapFolderRequest,
+ ) => Promise<CompositionEditResponse>;
+ updateCompositionMetadata: (
+ request: UpdateCompositionMetadataRequest,
+ ) => Promise<CompositionEditResponse>;
redo: () => Promise<RedoResponse>;
renameStaticFile: (
request: RenameStaticFileRequest,
diff --git a/packages/studio-shared/src/codemods.ts b/packages/studio-shared/src/codemods.ts
index bed70ef991..a799296166 100644
--- a/packages/studio-shared/src/codemods.ts
+++ b/packages/studio-shared/src/codemods.ts
@@ -8,11 +8,6 @@ export type VisualControlChange = {
enumPaths: EnumPath[];
};
-export type ApplyVisualControlCodemod = {
- type: 'apply-visual-control';
- changes: VisualControlChange[];
-};
-
export type NewCompositionAsset = {
type: 'audio' | 'image' | 'video';
src: string;
@@ -30,83 +25,34 @@ export type CompositionOrFolder =
parentName: string | null;
};
-export type RecastCodemod =
- | {
- type: 'new-composition';
- asset: NewCompositionAsset | null;
- newId: string;
- componentName: string;
- componentImportPath: string;
- folderName: string | null;
- parentName: string | null;
- newHeight: number;
- newWidth: number;
- newFps: number;
- newDurationInFrames: number;
- canvasCapture: {
- readonly videoFileName: string;
- readonly videoHeight: number;
- readonly videoWidth: number;
- readonly keyframeFps: number;
- readonly data: CanvasCaptureData;
- } | null;
- }
- | {
- type: 'duplicate-composition';
- idToDuplicate: string;
- newId: string;
- newHeight: number | null;
- newWidth: number | null;
- newFps: number | null;
- newDurationInFrames: number | null;
- tag: 'Still' | 'Composition';
- }
- | {
- type: 'rename-composition';
- idToRename: string;
- newId: string;
- }
- | {
- type: 'update-composition-metadata';
- idToUpdate: string;
- newDurationInFrames: number | null;
- newFps: number | null;
- newHeight: number | null;
- newWidth: number | null;
- }
- | {
- type: 'delete-composition';
- idToDelete: string;
- }
+export type CompositionDestination =
+ | {type: 'root'}
| {
- type: 'move-composition-or-folder';
- source: CompositionOrFolder;
- destination:
- | {type: 'root'}
- | {
- type: 'folder';
- folderName: string;
- parentName: string | null;
- }
- | {
- type: 'before' | 'after';
- target: CompositionOrFolder;
- };
- }
- | {
- type: 'rename-folder';
- folderName: string;
- parentName: string | null;
- newName: string;
- }
- | {
- type: 'new-folder';
+ type: 'folder';
folderName: string;
parentName: string | null;
}
| {
- type: 'delete-folder';
- folderName: string;
- parentName: string | null;
- }
- | ApplyVisualControlCodemod;
+ type: 'before' | 'after';
+ target: CompositionOrFolder;
+ };
+
+export type NewCompositionOptions = {
+ asset: NewCompositionAsset | null;
+ newId: string;
+ componentName: string;
+ componentImportPath: string;
+ folderName: string | null;
+ parentName: string | null;
+ newHeight: number;
+ newWidth: number;
+ newFps: number;
+ newDurationInFrames: number;
+ canvasCapture: {
+ readonly videoFileName: string;
+ readonly videoHeight: number;
+ readonly videoWidth: number;
+ readonly keyframeFps: number;
+ readonly data: CanvasCaptureData;
+ } | null;
+};
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index ba6793f4b4..75650d949f 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -6,14 +6,14 @@ export {
AddEffectKeyframeResponse,
AddEffectRequest,
AddEffectResponse,
+ AddCompositionRequest,
+ AddFolderRequest,
AddKeyframesRequest,
AddKeyframesResponse,
AddRenderRequest,
AddSequenceKeyframeRequest,
AddSequenceKeyframeResponse,
ApiRoutes,
- ApplyCodemodRequest,
- ApplyCodemodResponse,
ApplyVisualControlRequest,
ApplyVisualControlResponse,
BatchUpdateEffectKeyframeSettings,
@@ -27,6 +27,7 @@ export {
CaptionPatch,
CompositionComponentInfoRequest,
CompositionComponentInfoResponse,
+ CompositionEditResponse,
ComponentProp,
ConvertFigmaClipboardToSvgRequest,
ConvertFigmaClipboardToSvgResponse,
@@ -37,6 +38,7 @@ export {
DeleteEffectRequest,
DeleteEffectRequestItem,
DeleteEffectResponse,
+ DeleteCompositionRequest,
DeleteNodesRequest,
DeleteNodesRequestItem,
DeleteNodesResponse,
@@ -50,6 +52,7 @@ export {
DuplicateEffectRequest,
DuplicateEffectRequestItem,
DuplicateEffectResponse,
+ DuplicateCompositionRequest,
PrecomposeJsxNodesRequest,
PrecomposeJsxNodesRequestItem,
PrecomposeJsxNodesResponse,
@@ -95,6 +98,8 @@ export {
LogStudioErrorRequest,
LogStudioErrorResponse,
MoveEffectKeyframe,
+ MoveCompositionRequest,
+ MoveFolderRequest,
MoveKeyframesRequest,
MoveKeyframesResponse,
MoveSequenceKeyframe,
@@ -116,6 +121,8 @@ export {
ProjectInfoResponse,
RedoRequest,
RedoResponse,
+ RenameCompositionRequest,
+ RenameFolderRequest,
RemoveRenderRequest,
RenameStaticFileRequest,
RenameStaticFileResponse,
@@ -139,7 +146,6 @@ export {
SaveSequencePropsRequest,
SaveSequencePropsResponse,
SaveSequencePropsResult,
- SimpleDiff,
SplitSequencesRequest,
SplitSequencesRequestItem,
SplitSequencesResponse,
@@ -161,6 +167,7 @@ export {
UnsubscribeFromSequencePropsRequest,
UpdateAvailableRequest,
UpdateAvailableResponse,
+ UpdateCompositionMetadataRequest,
UpdateConfigRequest,
UpdateConfigResponse,
UpdateDefaultPropsRequest,
@@ -171,6 +178,7 @@ export {
UpdateElementInstallTargetResponse,
UpdateSequenceKeyframeSettingsRequest,
UpdateSequenceKeyframeSettingsResponse,
+ UnwrapFolderRequest,
type AddEffectKeyframe,
type AddSequenceKeyframe,
type ConfigUpdate,
@@ -183,8 +191,6 @@ export type {
BrowserStudioInstallPackagesResponse,
BrowserStudioOperations,
BrowserStudioPackageInstallationOperations,
- DuplicateCompositionRequest,
- DuplicateCompositionResponse,
} from './browser-studio-operations';
export type {
CanvasCaptureData,
@@ -200,12 +206,15 @@ export type {
SequenceNodePathRemapping,
} from './sequence-node-path-mutation';
export type {
- ApplyVisualControlCodemod,
+ CompositionDestination,
CompositionOrFolder,
NewCompositionAsset,
- RecastCodemod,
+ NewCompositionOptions,
} from './codemods';
-export {REACT_REFRESH_FINISHED_EVENT} from './react-refresh-event';
+export {
+ REACT_REFRESH_FINISHED_EVENT,
+ REACT_REFRESH_STARTED_EVENT,
+} from './react-refresh-event';
export {hasSequenceTimingTraits} from './has-sequence-timing-traits';
export {
getConfigFileChangeMessage,
diff --git a/packages/studio-shared/src/react-refresh-event.ts b/packages/studio-shared/src/react-refresh-event.ts
index 304a405af2..5d11c7a202 100644
--- a/packages/studio-shared/src/react-refresh-event.ts
+++ b/packages/studio-shared/src/react-refresh-event.ts
@@ -1 +1,2 @@
+export const REACT_REFRESH_STARTED_EVENT = 'remotion-react-refresh-started';
export const REACT_REFRESH_FINISHED_EVENT = 'remotion-react-refresh-finished';
diff --git a/packages/studio/src/components/CompositionSelector.tsx b/packages/studio/src/components/CompositionSelector.tsx
index f9e9712fa5..ae14716145 100644
--- a/packages/studio/src/components/CompositionSelector.tsx
+++ b/packages/studio/src/components/CompositionSelector.tsx
@@ -26,9 +26,8 @@ import {
import {CompositionSelectorItem} from './CompositionSelectorItem';
import {ContextMenuForTarget} from './ContextMenu';
import {useSelectComposition} from './InitialCompositionLoader';
-import {showNotification} from './Notifications/NotificationCenter';
import {ExplorerQuickSwitcherTrigger} from './QuickSwitcher/ExplorerQuickSwitcherTrigger';
-import {applyCodemod} from './RenderQueue/actions';
+import {moveComposition, moveFolder} from './RenderQueue/actions';
import {getRootCompositionMenuItems} from './root-composition-menu-items';
export const useCompositionNavigation = () => {
@@ -334,37 +333,30 @@ export const CompositionSelector: React.FC = () => {
event.stopPropagation();
stopCompositionListAutoScroll();
setRootDragHovered(false);
- const notification = showNotification(
- `Moving ${dragData.item.type === 'composition' ? dragData.item.compositionId : dragData.item.folderName}...`,
- null,
- );
const controller = new AbortController();
try {
- const result = await applyCodemod({
- codemod: {
- type: 'move-composition-or-folder',
- source: dragData.item,
- destination: {type: 'root'},
- },
- dryRun: false,
- signal: controller.signal,
+ const source = dragData.item;
+ const common = {
+ destination: {type: 'root'} as const,
symbolicatedStack:
compositionSelectorDragDataToSymbolicatedStack(dragData),
undoRedoNavigation: null,
- });
-
- if (result.success) {
- notification.dismiss();
- } else {
- notification.replaceContent(result.reason, 4000);
- }
- } catch (err) {
- notification.replaceContent(
- err instanceof Error ? err.message : String(err),
- 4000,
- );
- }
+ };
+ await (source.type === 'composition'
+ ? moveComposition(
+ {...common, compositionId: source.compositionId},
+ controller.signal,
+ )
+ : moveFolder(
+ {
+ ...common,
+ folderName: source.folderName,
+ parentName: source.parentName,
+ },
+ controller.signal,
+ ));
+ } catch {}
},
[stopCompositionListAutoScroll],
);
diff --git a/packages/studio/src/components/CompositionSelectorItem.tsx b/packages/studio/src/components/CompositionSelectorItem.tsx
index 339329eca4..85c9ebe69f 100644
--- a/packages/studio/src/components/CompositionSelectorItem.tsx
+++ b/packages/studio/src/components/CompositionSelectorItem.tsx
@@ -1,4 +1,7 @@
-import type {CompositionOrFolder, RecastCodemod} from '@remotion/studio-shared';
+import type {
+ CompositionDestination,
+ CompositionOrFolder,
+} from '@remotion/studio-shared';
import type {
DragEvent,
KeyboardEvent,
@@ -53,8 +56,7 @@ import {ContextMenu} from './ContextMenu';
import {getFolderMenuItems} from './folder-menu-items';
import {COMPACT_CONTROL_ROW_HEIGHT, Row, Spacing} from './layout';
import type {ComboboxValue} from './NewComposition/ComboBox';
-import {showNotification} from './Notifications/NotificationCenter';
-import {applyCodemod} from './RenderQueue/actions';
+import {moveComposition, moveFolder} from './RenderQueue/actions';
import {SidebarRenderButton} from './SidebarRenderButton';
import {useResolvedStack} from './Timeline/use-resolved-stack';
import {useOpenInMenuApps} from './use-open-in-menu-apps';
@@ -592,51 +594,44 @@ export const CompositionSelectorItem: React.FC<{
destination,
dragData,
}: {
- destination: Extract<
- RecastCodemod,
- {type: 'move-composition-or-folder'}
- >['destination'];
+ destination: CompositionDestination;
dragData: CompositionSelectorDragData;
}) => {
- const label =
- dragData.item.type === 'composition'
- ? dragData.item.compositionId
- : dragData.item.folderName;
- const notification = showNotification(`Moving ${label}...`, null);
try {
- const result = await applyCodemod({
- codemod: {
- type: 'move-composition-or-folder',
- source: dragData.item,
- destination,
- },
- dryRun: false,
- signal: new AbortController().signal,
+ const {item: source} = dragData;
+ const {signal} = new AbortController();
+ const common = {
+ destination,
symbolicatedStack:
compositionSelectorDragDataToSymbolicatedStack(dragData),
undoRedoNavigation: null,
- });
+ };
+ const result = await (source.type === 'composition'
+ ? moveComposition(
+ {...common, compositionId: source.compositionId},
+ signal,
+ )
+ : moveFolder(
+ {
+ ...common,
+ folderName: source.folderName,
+ parentName: source.parentName,
+ },
+ signal,
+ ));
- if (result.success) {
- notification.dismiss();
- } else {
- notification.replaceContent(result.reason, 4000);
+ if (!result.success) {
+ return;
}
if (
- result.success &&
destination.type === 'folder' &&
item.type === 'folder' &&
!item.expanded
) {
toggleFolder(item.folderName, item.parentName);
}
- } catch (err) {
- notification.replaceContent(
- err instanceof Error ? err.message : String(err),
- 4000,
- );
- }
+ } catch {}
},
[item, toggleFolder],
);
diff --git a/packages/studio/src/components/ElementInstallConfirmation.tsx b/packages/studio/src/components/ElementInstallConfirmation.tsx
index 27d892f468..4bc8106f3e 100644
--- a/packages/studio/src/components/ElementInstallConfirmation.tsx
+++ b/packages/studio/src/components/ElementInstallConfirmation.tsx
@@ -532,7 +532,7 @@ export const ElementInstallConfirmation: React.FC<{
}, [folderCompositionFile, newPlan, request.element, selectedFolderStack]);
const {
- codemod: newCompositionCodemod,
+ options: newCompositionOptions,
compositionId: newCompositionId,
heightValidationMessage,
nameValidationMessage,
@@ -840,7 +840,7 @@ export const ElementInstallConfirmation: React.FC<{
newComposition:
mode === 'new-composition'
? {
- codemod: newCompositionCodemod,
+ options: newCompositionOptions,
symbolicatedStack:
selectedFolderStack === null ? null : folderSymbolicatedStack,
}
@@ -872,7 +872,7 @@ export const ElementInstallConfirmation: React.FC<{
currentDestination,
folderSymbolicatedStack,
mode,
- newCompositionCodemod,
+ newCompositionOptions,
newCompositionId,
onClose,
request,
diff --git a/packages/studio/src/components/InspectorPanel/CompositionMetadata.tsx b/packages/studio/src/components/InspectorPanel/CompositionMetadata.tsx
index d935dce938..00e574eff2 100644
--- a/packages/studio/src/components/InspectorPanel/CompositionMetadata.tsx
+++ b/packages/studio/src/components/InspectorPanel/CompositionMetadata.tsx
@@ -1,4 +1,3 @@
-import type {RecastCodemod} from '@remotion/studio-shared';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {Internals} from 'remotion';
import {WHITE_ALPHA_40} from '../../helpers/colors';
@@ -12,7 +11,7 @@ import {
inputDraggerContainerStyle,
} from '../NewComposition/InputDragger';
import {showNotification} from '../Notifications/NotificationCenter';
-import {applyCodemod} from '../RenderQueue/actions';
+import {updateCompositionMetadata} from '../RenderQueue/actions';
import {useResolvedStack} from '../Timeline/use-resolved-stack';
import {InspectorDetailRow} from './common';
import {
@@ -362,22 +361,19 @@ export const CompositionMetadata: React.FC<{
};
return values;
}, {} as PendingCompositionMetadata);
- const codemod: RecastCodemod = {
- type: 'update-composition-metadata',
- idToUpdate: compositionId,
- newDurationInFrames: newValues.durationInFrames ?? null,
- newFps: newValues.fps ?? null,
- newHeight: newValues.height ?? null,
- newWidth: newValues.width ?? null,
- };
setPendingValues((pending) => ({...pending, ...optimisticValues}));
- applyCodemod({
- codemod,
- dryRun: false,
- signal: new AbortController().signal,
- symbolicatedStack,
- undoRedoNavigation: null,
- })
+ updateCompositionMetadata(
+ {
+ idToUpdate: compositionId,
+ newDurationInFrames: newValues.durationInFrames ?? null,
+ newFps: newValues.fps ?? null,
+ newHeight: newValues.height ?? null,
+ newWidth: newValues.width ?? null,
+ symbolicatedStack,
+ undoRedoNavigation: null,
+ },
+ new AbortController().signal,
+ )
.then((result) => {
if (!result.success) {
for (const field of changedFields) {
diff --git a/packages/studio/src/components/NewComposition/CodemodFooter.tsx b/packages/studio/src/components/NewComposition/CompositionEditFooter.tsx
similarity index 59%
rename from packages/studio/src/components/NewComposition/CodemodFooter.tsx
rename to packages/studio/src/components/NewComposition/CompositionEditFooter.tsx
index 3626dd7557..4f40508548 100644
--- a/packages/studio/src/components/NewComposition/CodemodFooter.tsx
+++ b/packages/studio/src/components/NewComposition/CompositionEditFooter.tsx
@@ -1,6 +1,5 @@
import type {
- ApplyCodemodResponse,
- RecastCodemod,
+ CompositionEditResponse,
SymbolicatedStackFrame,
} from '@remotion/studio-shared';
import React, {
@@ -11,34 +10,30 @@ import React, {
useState,
} from 'react';
import {ShortcutHint} from '../../error-overlay/remotion-overlay/ShortcutHint';
+import {LIGHT_TEXT} from '../../helpers/colors';
import {resolvedStackToSymbolicated} from '../../helpers/resolved-stack-to-symbolicated';
import {useKeybinding} from '../../helpers/use-keybinding';
import {SetSelectedModalContext} from '../../state/modals';
import {Flex, Row, Spacing} from '../layout';
import {ModalButton} from '../ModalButton';
import {showNotification} from '../Notifications/NotificationCenter';
-import {applyCodemod as applyCodemodApi} from '../RenderQueue/actions';
import {
hasResolvedStack,
useResolvedStack,
} from '../Timeline/use-resolved-stack';
-import type {CodemodStatus} from './DiffPreview';
-import {CodemodDiffPreview} from './DiffPreview';
-type ApplyCodemodAction = (options: {
+type ApplyCompositionEditAction = (options: {
signal: AbortSignal;
symbolicatedStack: SymbolicatedStackFrame | null;
-}) => Promise<ApplyCodemodResponse>;
+}) => Promise<CompositionEditResponse>;
-const CodemodFooterPresentation: React.FC<{
- readonly codemodStatus: CodemodStatus;
+const CompositionEditFooterPresentation: React.FC<{
readonly disabled: boolean;
readonly genericSubmitLabel: string;
readonly relativeFilePath: string | null;
readonly submitLabel: (options: {relativeRootPath: string}) => string;
readonly trigger: () => void;
}> = ({
- codemodStatus,
disabled,
genericSubmitLabel,
relativeFilePath,
@@ -47,7 +42,9 @@ const CodemodFooterPresentation: React.FC<{
}) => {
return (
<Row align="center">
- <CodemodDiffPreview status={codemodStatus} />
+ <span style={{color: LIGHT_TEXT, fontSize: 13, lineHeight: 1.2}}>
+ This will edit your codebase.
+ </span>
<Flex />
<Spacing block x={2} />
<ModalButton onClick={trigger} disabled={disabled}>
@@ -60,9 +57,8 @@ const CodemodFooterPresentation: React.FC<{
);
};
-export const CodemodFooter: React.FC<{
+export const CompositionEditFooter: React.FC<{
readonly valid: boolean;
- readonly codemod: RecastCodemod;
readonly stack: string | null;
readonly loadingNotification: React.ReactNode | null;
readonly errorNotification: string;
@@ -70,10 +66,8 @@ export const CodemodFooter: React.FC<{
readonly submitLabel: (options: {relativeRootPath: string}) => string;
readonly onSuccess: (() => void) | null;
readonly fallbackToRootFile?: boolean;
- readonly applyCodemod: ApplyCodemodAction;
- readonly applyCodemodForPreview: ApplyCodemodAction | null;
+ readonly applyEdit: ApplyCompositionEditAction;
}> = ({
- codemod,
stack,
valid,
loadingNotification,
@@ -82,14 +76,10 @@ export const CodemodFooter: React.FC<{
submitLabel,
onSuccess,
fallbackToRootFile = false,
- applyCodemod,
- applyCodemodForPreview,
+ applyEdit,
}) => {
const [submitting, setSubmitting] = useState(false);
const {setSelectedModal} = useContext(SetSelectedModalContext);
- const [codemodStatus, setCanApplyCodemod] = useState<CodemodStatus>({
- type: 'loading',
- });
const resolvedLocation = useResolvedStack(stack);
const symbolicatedStack = useMemo(
@@ -107,7 +97,7 @@ export const CodemodFooter: React.FC<{
? null
: showNotification(loadingNotification, null);
- applyCodemod({
+ applyEdit({
symbolicatedStack,
signal: new AbortController().signal,
})
@@ -136,7 +126,7 @@ export const CodemodFooter: React.FC<{
}
});
}, [
- applyCodemod,
+ applyEdit,
errorNotification,
loadingNotification,
onSuccess,
@@ -144,58 +134,8 @@ export const CodemodFooter: React.FC<{
symbolicatedStack,
]);
- const getCanApplyCodemod = useCallback(
- async (signal: AbortSignal) => {
- const res = applyCodemodForPreview
- ? await applyCodemodForPreview({signal, symbolicatedStack})
- : await applyCodemodApi({
- codemod,
- dryRun: true,
- symbolicatedStack,
- signal,
- undoRedoNavigation: null,
- });
-
- if (res.success) {
- setCanApplyCodemod({type: 'success', diff: res.diff});
- } else {
- setCanApplyCodemod({
- type: 'fail',
- error: res.reason,
- });
- }
- },
- [applyCodemodForPreview, codemod, symbolicatedStack],
- );
-
useEffect(() => {
if (!stack) {
- if (fallbackToRootFile) {
- const rootFileAbortController = new AbortController();
- let rootFileAborted = false;
- getCanApplyCodemod(rootFileAbortController.signal)
- .then(() => undefined)
- .catch((err) => {
- if (rootFileAborted) {
- return;
- }
-
- showNotification(
- `${errorNotification}: ${(err as Error).message}`,
- 3000,
- );
- });
-
- return () => {
- rootFileAborted = true;
- rootFileAbortController.abort();
- };
- }
-
- setCanApplyCodemod({
- type: 'fail',
- error: 'Could not determine where this item is defined',
- });
return;
}
@@ -204,45 +144,15 @@ export const CodemodFooter: React.FC<{
}
if (!symbolicatedStack) {
- setCanApplyCodemod({
- type: 'fail',
- error: 'Could not resolve the source location of this item',
- });
- return;
+ showNotification(
+ `${errorNotification}: Could not resolve the source location of this item`,
+ 3000,
+ );
}
-
- const abortController = new AbortController();
- let aborted = false;
- getCanApplyCodemod(abortController.signal)
- .then(() => undefined)
- .catch((err) => {
- if (aborted) {
- return;
- }
-
- showNotification(
- `${errorNotification}: ${(err as Error).message}`,
- 3000,
- );
- });
-
- return () => {
- aborted = true;
- abortController.abort();
- };
- }, [
- errorNotification,
- fallbackToRootFile,
- getCanApplyCodemod,
- stack,
- symbolicatedStack,
- ]);
+ }, [errorNotification, fallbackToRootFile, stack, symbolicatedStack]);
const disabled =
- !valid ||
- submitting ||
- (symbolicatedStack === null && !fallbackToRootFile) ||
- codemodStatus.type !== 'success';
+ !valid || submitting || (symbolicatedStack === null && !fallbackToRootFile);
const {registerKeybinding} = useKeybinding();
@@ -268,8 +178,7 @@ export const CodemodFooter: React.FC<{
}, [disabled, registerKeybinding, trigger, valid]);
return (
- <CodemodFooterPresentation
- codemodStatus={codemodStatus}
+ <CompositionEditFooterPresentation
disabled={disabled}
genericSubmitLabel={genericSubmitLabel}
relativeFilePath={relativeFilePath}
diff --git a/packages/studio/src/components/NewComposition/DeleteComposition.tsx b/packages/studio/src/components/NewComposition/DeleteComposition.tsx
index 6172d79453..a5171996cd 100644
--- a/packages/studio/src/components/NewComposition/DeleteComposition.tsx
+++ b/packages/studio/src/components/NewComposition/DeleteComposition.tsx
@@ -1,5 +1,4 @@
-import type {RecastCodemod} from '@remotion/studio-shared';
-import React, {useCallback, useContext, useMemo, useRef} from 'react';
+import React, {useCallback, useContext, useRef} from 'react';
import type {_InternalTypes} from 'remotion';
import {Internals} from 'remotion';
import {getRoute, pushUrl} from '../../helpers/url-state';
@@ -12,8 +11,8 @@ import {
ResolveCompositionBeforeModal,
ResolvedCompositionContext,
} from '../RenderModal/ResolveCompositionBeforeModal';
-import {applyCodemod} from '../RenderQueue/actions';
-import {CodemodFooter} from './CodemodFooter';
+import {deleteComposition} from '../RenderQueue/actions';
+import {CompositionEditFooter} from './CompositionEditFooter';
import {DismissableModal} from './DismissableModal';
const content: React.CSSProperties = {
@@ -40,13 +39,6 @@ const DeleteCompositionLoaded: React.FC<{
_InternalTypes['AnyComposition'] | null | undefined
>(undefined);
- const codemod: RecastCodemod = useMemo(() => {
- return {
- type: 'delete-composition',
- idToDelete: compositionId,
- };
- }, [compositionId]);
-
const onSubmit: React.FormEventHandler<HTMLFormElement> = useCallback((e) => {
e.preventDefault();
}, []);
@@ -82,18 +74,17 @@ const DeleteCompositionLoaded: React.FC<{
remain in your code.
</div>
<ModalFooterContainer>
- <CodemodFooter
+ <CompositionEditFooter
errorNotification={`Could not delete composition`}
loadingNotification={'Deleting'}
genericSubmitLabel={`Delete`}
submitLabel={({relativeRootPath}) =>
`Delete from ${relativeRootPath}`
}
- codemod={codemod}
stack={compositionStack}
valid
onSuccess={onSuccess}
- applyCodemod={({signal, symbolicatedStack}) => {
+ applyEdit={({signal, symbolicatedStack}) => {
const currentRoute = getRoute();
const currentCanvasContent = deriveCanvasContentFromUrl();
const isSelected =
@@ -104,21 +95,22 @@ const DeleteCompositionLoaded: React.FC<{
: undefined;
navigationAfterDelete.current = fallback;
- return applyCodemod({
- codemod,
- dryRun: false,
+ return deleteComposition(
+ {
+ idToDelete: compositionId,
+ symbolicatedStack,
+ undoRedoNavigation:
+ fallback === undefined
+ ? null
+ : {
+ undoRoute: currentRoute,
+ redoRoute:
+ fallback === null ? '/' : `/${fallback.id}`,
+ },
+ },
signal,
- symbolicatedStack,
- undoRedoNavigation:
- fallback === undefined
- ? null
- : {
- undoRoute: currentRoute,
- redoRoute: fallback === null ? '/' : `/${fallback.id}`,
- },
- });
+ );
}}
- applyCodemodForPreview={null}
/>
</ModalFooterContainer>
</form>
diff --git a/packages/studio/src/components/NewComposition/DeleteFolder.tsx b/packages/studio/src/components/NewComposition/DeleteFolder.tsx
index b63633673a..5f51affd5e 100644
--- a/packages/studio/src/components/NewComposition/DeleteFolder.tsx
+++ b/packages/studio/src/components/NewComposition/DeleteFolder.tsx
@@ -1,11 +1,10 @@
-import type {RecastCodemod} from '@remotion/studio-shared';
-import React, {useCallback, useMemo} from 'react';
+import React, {useCallback} from 'react';
import {getFolderId} from '../../helpers/get-folder-id';
import {inlineCodeSnippet} from '../Menu/styles';
import {ModalFooterContainer} from '../ModalFooter';
import {ModalHeader} from '../ModalHeader';
-import {applyCodemod} from '../RenderQueue/actions';
-import {CodemodFooter} from './CodemodFooter';
+import {unwrapFolder} from '../RenderQueue/actions';
+import {CompositionEditFooter} from './CompositionEditFooter';
import {DismissableModal} from './DismissableModal';
const content: React.CSSProperties = {
@@ -20,14 +19,6 @@ export const DeleteFolder: React.FC<{
readonly parentName: string | null;
readonly stack: string | null;
}> = ({folderName, parentName, stack}) => {
- const codemod: RecastCodemod = useMemo(() => {
- return {
- type: 'delete-folder',
- folderName,
- parentName,
- };
- }, [folderName, parentName]);
-
const onSubmit: React.FormEventHandler<HTMLFormElement> = useCallback((e) => {
e.preventDefault();
}, []);
@@ -47,27 +38,27 @@ export const DeleteFolder: React.FC<{
The compositions and nested folders inside it will stay in your code.
</div>
<ModalFooterContainer>
- <CodemodFooter
+ <CompositionEditFooter
errorNotification={`Could not delete folder`}
loadingNotification={'Deleting folder'}
genericSubmitLabel={`Delete`}
submitLabel={({relativeRootPath}) =>
`Delete from ${relativeRootPath}`
}
- codemod={codemod}
stack={stack}
valid
onSuccess={null}
- applyCodemod={({signal, symbolicatedStack}) =>
- applyCodemod({
- codemod,
- dryRun: false,
+ applyEdit={({signal, symbolicatedStack}) =>
+ unwrapFolder(
+ {
+ folderName,
+ parentName,
+ symbolicatedStack,
+ undoRedoNavigation: null,
+ },
signal,
- symbolicatedStack,
- undoRedoNavigation: null,
- })
+ )
}
- applyCodemodForPreview={null}
/>
</ModalFooterContainer>
</form>
diff --git a/packages/studio/src/components/NewComposition/DiffPreview.tsx b/packages/studio/src/components/NewComposition/DiffPreview.tsx
deleted file mode 100644
index ce71d4de58..0000000000
--- a/packages/studio/src/components/NewComposition/DiffPreview.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import type {SimpleDiff} from '@remotion/studio-shared';
-import React from 'react';
-import {
- BLUE,
- FAIL_COLOR,
- LIGHT_TEXT,
- SELECTED_GUIDE,
-} from '../../helpers/colors';
-
-export type CodemodStatus =
- | {
- type: 'loading';
- }
- | {
- type: 'success';
- diff: SimpleDiff;
- }
- | {
- type: 'fail';
- error: string;
- };
-
-export const CodemodDiffPreview: React.FC<{
- readonly status: CodemodStatus;
-}> = ({status}) => {
- if (status.type === 'loading') {
- return null;
- }
-
- if (status.type === 'fail') {
- return (
- <span style={{color: FAIL_COLOR, fontSize: 13, lineHeight: 1.2}}>
- {status.error}
- </span>
- );
- }
-
- return (
- <div style={{lineHeight: 1.2}}>
- <span style={{color: LIGHT_TEXT, fontSize: 13, lineHeight: 1.2}}>
- This will edit your codebase.
- </span>
- <br />
- <span style={{color: BLUE, fontSize: 13, lineHeight: 1.2}}>
- {status.diff.additions} addition
- {status.diff.additions === 1 ? '' : 's'},
- </span>{' '}
- <span
- style={{
- color: SELECTED_GUIDE,
- fontSize: 13,
- lineHeight: 1.2,
- }}
- >
- {status.diff.deletions} deletion
- {status.diff.deletions === 1 ? '' : 's'}
- </span>
- </div>
- );
-};
diff --git a/packages/studio/src/components/NewComposition/DuplicateComposition.tsx b/packages/studio/src/components/NewComposition/DuplicateComposition.tsx
index d01b7c4747..a2d50c7456 100644
--- a/packages/studio/src/components/NewComposition/DuplicateComposition.tsx
+++ b/packages/studio/src/components/NewComposition/DuplicateComposition.tsx
@@ -1,4 +1,3 @@
-import type {RecastCodemod} from '@remotion/studio-shared';
import type {ChangeEventHandler} from 'react';
import React, {useCallback, useContext, useMemo, useState} from 'react';
import {Internals} from 'remotion';
@@ -15,11 +14,11 @@ import {
ResolveCompositionBeforeModal,
ResolvedCompositionContext,
} from '../RenderModal/ResolveCompositionBeforeModal';
-import {CodemodFooter} from './CodemodFooter';
+import {duplicateComposition} from '../RenderQueue/actions';
import type {ComboboxValue} from './ComboBox';
import {Combobox} from './ComboBox';
+import {CompositionEditFooter} from './CompositionEditFooter';
import {DismissableModal} from './DismissableModal';
-import {duplicateComposition} from './duplicate-composition-api';
import {InputAndValidationContainer} from './InputAndValidationContainer';
import {InputDragger} from './InputDragger';
import {NewCompDuration} from './NewCompDuration';
@@ -190,16 +189,15 @@ const DuplicateCompositionLoaded: React.FC<{
compWidthErrMessage === null &&
compHeightErrMessage === null;
- const codemod: RecastCodemod = useMemo(() => {
+ const duplicateRequest = useMemo(() => {
return {
- type: 'duplicate-composition',
idToDuplicate: resolved.result.id,
newDurationInFrames: hadDurationDefined ? Number(durationInFrames) : null,
newFps: hadFpsDefined ? Number(selectedFrameRate) : null,
newHeight: hadDimensionsDefined ? Number(size.height) : null,
newWidth: hadDimensionsDefined ? Number(size.width) : null,
newId,
- tag: type === 'still' ? 'Still' : 'Composition',
+ tag: type === 'still' ? ('Still' as const) : ('Composition' as const),
};
}, [
durationInFrames,
@@ -367,35 +365,26 @@ const DuplicateCompositionLoaded: React.FC<{
) : null}
</div>
<ModalFooterContainer>
- <CodemodFooter
+ <CompositionEditFooter
loadingNotification={'Duplicating...'}
errorNotification={'Could not duplicate composition'}
genericSubmitLabel={'Duplicate'}
submitLabel={({relativeRootPath}) => `Add to ${relativeRootPath}`}
- codemod={codemod}
stack={compositionStack}
valid={valid}
onSuccess={onDuplicateSuccess}
- applyCodemod={({signal, symbolicatedStack}) =>
- duplicateComposition({
- codemod,
- dryRun: false,
- signal,
- symbolicatedStack,
- undoRedoNavigation: {
- undoRoute: getRoute(),
- redoRoute: `/${newId}`,
+ applyEdit={({signal, symbolicatedStack}) =>
+ duplicateComposition(
+ {
+ ...duplicateRequest,
+ symbolicatedStack,
+ undoRedoNavigation: {
+ undoRoute: getRoute(),
+ redoRoute: `/${newId}`,
+ },
},
- })
- }
- applyCodemodForPreview={({signal, symbolicatedStack}) =>
- duplicateComposition({
- codemod,
- dryRun: true,
signal,
- symbolicatedStack,
- undoRedoNavigation: null,
- })
+ )
}
/>
</ModalFooterContainer>
diff --git a/packages/studio/src/components/NewComposition/NewComposition.tsx b/packages/studio/src/components/NewComposition/NewComposition.tsx
index 5641857096..97434f0313 100644
--- a/packages/studio/src/components/NewComposition/NewComposition.tsx
+++ b/packages/studio/src/components/NewComposition/NewComposition.tsx
@@ -31,9 +31,9 @@ import {Spacing} from '../layout';
import {ModalFooterContainer} from '../ModalFooter';
import {ModalHeader} from '../ModalHeader';
import {label, optionRow, rightRow} from '../RenderModal/layout';
-import {CodemodFooter} from './CodemodFooter';
import type {ComboboxValue} from './ComboBox';
import {Combobox} from './ComboBox';
+import {CompositionEditFooter} from './CompositionEditFooter';
import {DismissableModal} from './DismissableModal';
import {getNewCompositionDefaults} from './get-new-composition-defaults';
import {InputAndValidationContainer} from './InputAndValidationContainer';
@@ -483,7 +483,6 @@ const NewCompositionLoaded: React.FC<{
}, []);
const {
- codemod,
compositionId,
createComposition,
heightValidationMessage,
@@ -569,22 +568,20 @@ const NewCompositionLoaded: React.FC<{
/>
</div>
<ModalFooterContainer>
- <CodemodFooter
+ <CompositionEditFooter
loadingNotification={null}
errorNotification="Could not create composition"
genericSubmitLabel="Add to root file"
submitLabel={({relativeRootPath}) => `Add to ${relativeRootPath}`}
- codemod={codemod}
stack={values.folder.stack}
valid={valid}
onSuccess={null}
- applyCodemod={({signal, symbolicatedStack}) =>
+ applyEdit={({signal, symbolicatedStack}) =>
createCanvasCaptureComposition({
signal,
symbolicatedStack,
})
}
- applyCodemodForPreview={null}
fallbackToRootFile
/>
</ModalFooterContainer>
diff --git a/packages/studio/src/components/NewComposition/NewFolder.tsx b/packages/studio/src/components/NewComposition/NewFolder.tsx
index fc3dc085a5..16f692af88 100644
--- a/packages/studio/src/components/NewComposition/NewFolder.tsx
+++ b/packages/studio/src/components/NewComposition/NewFolder.tsx
@@ -1,10 +1,8 @@
-import type {RecastCodemod} from '@remotion/studio-shared';
import type {ChangeEventHandler} from 'react';
import React, {
useCallback,
useContext,
useEffect,
- useMemo,
useRef,
useState,
} from 'react';
@@ -21,8 +19,8 @@ import {Spacing} from '../layout';
import {ModalFooterContainer} from '../ModalFooter';
import {ModalHeader} from '../ModalHeader';
import {label, optionRow, rightRow} from '../RenderModal/layout';
-import {applyCodemod} from '../RenderQueue/actions';
-import {CodemodFooter} from './CodemodFooter';
+import {addFolder} from '../RenderQueue/actions';
+import {CompositionEditFooter} from './CompositionEditFooter';
import {DismissableModal} from './DismissableModal';
import {InputAndValidationContainer} from './InputAndValidationContainer';
import {RemotionInput} from './RemInput';
@@ -92,14 +90,6 @@ export const NewFolder: React.FC<{
: 'Enter a name containing letters or numbers.';
const valid = folderNameErrMessage === null;
- const codemod: RecastCodemod = useMemo(() => {
- return {
- type: 'new-folder',
- folderName,
- parentName,
- };
- }, [folderName, parentName]);
-
const onSubmit: React.FormEventHandler<HTMLFormElement> = useCallback((e) => {
e.preventDefault();
}, []);
@@ -174,26 +164,26 @@ export const NewFolder: React.FC<{
</div>
</div>
<ModalFooterContainer>
- <CodemodFooter
+ <CompositionEditFooter
loadingNotification={'Creating folder...'}
errorNotification={'Could not create folder'}
genericSubmitLabel={'Add to root file'}
submitLabel={({relativeRootPath}) => `Add to ${relativeRootPath}`}
- codemod={codemod}
stack={stack}
valid={valid}
onSuccess={onSuccess}
fallbackToRootFile
- applyCodemod={({signal, symbolicatedStack}) =>
- applyCodemod({
- codemod,
- dryRun: false,
+ applyEdit={({signal, symbolicatedStack}) =>
+ addFolder(
+ {
+ folderName,
+ parentName,
+ symbolicatedStack,
+ undoRedoNavigation: null,
+ },
signal,
- symbolicatedStack,
- undoRedoNavigation: null,
- })
+ )
}
- applyCodemodForPreview={null}
/>
</ModalFooterContainer>
</form>
diff --git a/packages/studio/src/components/NewComposition/RenameComposition.tsx b/packages/studio/src/components/NewComposition/RenameComposition.tsx
index e3914158d7..3d66e6c210 100644
--- a/packages/studio/src/components/NewComposition/RenameComposition.tsx
+++ b/packages/studio/src/components/NewComposition/RenameComposition.tsx
@@ -16,7 +16,7 @@ import {
ResolveCompositionBeforeModal,
ResolvedCompositionContext,
} from '../RenderModal/ResolveCompositionBeforeModal';
-import {CodemodFooter} from './CodemodFooter';
+import {CompositionEditFooter} from './CompositionEditFooter';
import {DismissableModal} from './DismissableModal';
import {InputAndValidationContainer} from './InputAndValidationContainer';
import {RemotionInput} from './RemInput';
@@ -60,7 +60,6 @@ const RenameCompositionLoaded: React.FC<{}> = () => {
);
const {
- codemod,
compositionId,
renameComposition,
valid,
@@ -115,23 +114,21 @@ const RenameCompositionLoaded: React.FC<{}> = () => {
</div>
</div>
<ModalFooterContainer>
- <CodemodFooter
+ <CompositionEditFooter
loadingNotification={'Renaming...'}
errorNotification={'Could not rename composition'}
genericSubmitLabel={'Rename'}
submitLabel={({relativeRootPath}) => `Modify ${relativeRootPath}`}
- codemod={codemod}
stack={compositionStack}
valid={valid}
onSuccess={null}
- applyCodemod={({signal, symbolicatedStack}) =>
+ applyEdit={({signal, symbolicatedStack}) =>
renameComposition({
newCompositionId: newId,
signal,
symbolicatedStack,
})
}
- applyCodemodForPreview={null}
/>
</ModalFooterContainer>
</form>
diff --git a/packages/studio/src/components/NewComposition/RenameFolder.tsx b/packages/studio/src/components/NewComposition/RenameFolder.tsx
index cb80376a84..92e94c44eb 100644
--- a/packages/studio/src/components/NewComposition/RenameFolder.tsx
+++ b/packages/studio/src/components/NewComposition/RenameFolder.tsx
@@ -1,10 +1,8 @@
-import type {RecastCodemod} from '@remotion/studio-shared';
import type {ChangeEventHandler} from 'react';
import React, {
useCallback,
useContext,
useEffect,
- useMemo,
useRef,
useState,
} from 'react';
@@ -16,8 +14,8 @@ import {Spacing} from '../layout';
import {ModalFooterContainer} from '../ModalFooter';
import {ModalHeader} from '../ModalHeader';
import {label, optionRow, rightRow} from '../RenderModal/layout';
-import {applyCodemod} from '../RenderQueue/actions';
-import {CodemodFooter} from './CodemodFooter';
+import {renameFolder} from '../RenderQueue/actions';
+import {CompositionEditFooter} from './CompositionEditFooter';
import {DismissableModal} from './DismissableModal';
import {InputAndValidationContainer} from './InputAndValidationContainer';
import {RemotionInput} from './RemInput';
@@ -66,15 +64,6 @@ export const RenameFolder: React.FC<{
const valid = folderNameErrMessage === null && folderName !== slug;
- const codemod: RecastCodemod = useMemo(() => {
- return {
- type: 'rename-folder',
- folderName,
- parentName,
- newName: slug,
- };
- }, [folderName, slug, parentName]);
-
const onSubmit: React.FormEventHandler<HTMLFormElement> = useCallback((e) => {
e.preventDefault();
}, []);
@@ -121,25 +110,26 @@ export const RenameFolder: React.FC<{
</div>
</div>
<ModalFooterContainer>
- <CodemodFooter
+ <CompositionEditFooter
loadingNotification={'Renaming folder...'}
errorNotification={'Could not rename folder'}
genericSubmitLabel={'Rename'}
submitLabel={({relativeRootPath}) => `Modify ${relativeRootPath}`}
- codemod={codemod}
stack={stack}
valid={valid}
onSuccess={null}
- applyCodemod={({signal, symbolicatedStack}) =>
- applyCodemod({
- codemod,
- dryRun: false,
+ applyEdit={({signal, symbolicatedStack}) =>
+ renameFolder(
+ {
+ folderName,
+ parentName,
+ newName: slug,
+ symbolicatedStack,
+ undoRedoNavigation: null,
+ },
signal,
- symbolicatedStack,
- undoRedoNavigation: null,
- })
+ )
}
- applyCodemodForPreview={null}
/>
</ModalFooterContainer>
</form>
diff --git a/packages/studio/src/components/NewComposition/duplicate-composition-api.ts b/packages/studio/src/components/NewComposition/duplicate-composition-api.ts
deleted file mode 100644
index 9b431d61f5..0000000000
--- a/packages/studio/src/components/NewComposition/duplicate-composition-api.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import type {
- DuplicateCompositionResponse,
- RecastCodemod,
- SymbolicatedStackFrame,
- UndoRedoNavigation,
-} from '@remotion/studio-shared';
-import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';
-import {applyCodemod} from '../RenderQueue/actions';
-
-export const duplicateComposition = ({
- codemod,
- dryRun,
- signal,
- symbolicatedStack,
- undoRedoNavigation,
-}: {
- codemod: Extract<RecastCodemod, {type: 'duplicate-composition'}>;
- dryRun: boolean;
- signal: AbortSignal;
- symbolicatedStack: SymbolicatedStackFrame | null;
- undoRedoNavigation: UndoRedoNavigation | null;
-}): Promise<DuplicateCompositionResponse> => {
- const browserStudioOperations = getBrowserStudioOperations();
- if (browserStudioOperations === null) {
- return applyCodemod({
- codemod,
- dryRun,
- signal,
- symbolicatedStack,
- undoRedoNavigation,
- }).then((result) => (result.success ? result : {...result, stack: ''}));
- }
-
- return browserStudioOperations.duplicateComposition({
- codemod,
- dryRun,
- undoRedoNavigation,
- });
-};
diff --git a/packages/studio/src/components/RenderQueue/actions.ts b/packages/studio/src/components/RenderQueue/actions.ts
index cfee777e3b..ad4057d992 100644
--- a/packages/studio/src/components/RenderQueue/actions.ts
+++ b/packages/studio/src/components/RenderQueue/actions.ts
@@ -11,12 +11,20 @@ import type {
} from '@remotion/renderer';
import type {HardwareAccelerationOption} from '@remotion/renderer/client';
import type {
- ApplyCodemodRequest,
+ AddCompositionRequest,
+ AddFolderRequest,
+ DeleteCompositionRequest,
+ DuplicateCompositionRequest,
EnumPath,
+ MoveCompositionRequest,
+ MoveFolderRequest,
OpenInFileExplorerRequest,
- RecastCodemod,
+ RenameCompositionRequest,
+ RenameFolderRequest,
RenderJob,
RequiredChromiumOptions,
+ UnwrapFolderRequest,
+ UpdateCompositionMetadataRequest,
VisualControlChange,
} from '@remotion/studio-shared';
import type {_InternalTypes} from 'remotion';
@@ -346,31 +354,98 @@ export const openInFileExplorer = ({directory}: {directory: string}) => {
return callApi('/api/open-in-file-explorer', body);
};
-export const applyCodemod = ({
- codemod,
- dryRun,
- symbolicatedStack,
- signal,
- undoRedoNavigation,
-}: {
- codemod: RecastCodemod;
- dryRun: boolean;
- symbolicatedStack: ApplyCodemodRequest['symbolicatedStack'];
- signal: AbortController['signal'];
- undoRedoNavigation: ApplyCodemodRequest['undoRedoNavigation'];
-}) => {
- const body: ApplyCodemodRequest = {
- codemod,
- dryRun,
- symbolicatedStack,
- undoRedoNavigation,
- };
- const browserStudioOperations = getBrowserStudioOperations();
- if (browserStudioOperations !== null) {
- return browserStudioOperations.applyCodemod(body);
- }
+export const addComposition = (
+ request: AddCompositionRequest,
+ signal: AbortSignal,
+) => {
+ const operations = getBrowserStudioOperations();
+ return operations === null
+ ? callApi('/api/add-composition', request, signal)
+ : operations.addComposition(request);
+};
+
+export const duplicateComposition = (
+ request: DuplicateCompositionRequest,
+ signal: AbortSignal,
+) => {
+ const operations = getBrowserStudioOperations();
+ return operations === null
+ ? callApi('/api/duplicate-composition', request, signal)
+ : operations.duplicateComposition(request);
+};
+
+export const renameComposition = (
+ request: RenameCompositionRequest,
+ signal: AbortSignal,
+) => {
+ const operations = getBrowserStudioOperations();
+ return operations === null
+ ? callApi('/api/rename-composition', request, signal)
+ : operations.renameComposition(request);
+};
+
+export const updateCompositionMetadata = (
+ request: UpdateCompositionMetadataRequest,
+ signal: AbortSignal,
+) => {
+ const operations = getBrowserStudioOperations();
+ return operations === null
+ ? callApi('/api/update-composition-metadata', request, signal)
+ : operations.updateCompositionMetadata(request);
+};
+
+export const deleteComposition = (
+ request: DeleteCompositionRequest,
+ signal: AbortSignal,
+) => {
+ const operations = getBrowserStudioOperations();
+ return operations === null
+ ? callApi('/api/delete-composition', request, signal)
+ : operations.deleteComposition(request);
+};
+
+export const moveComposition = (
+ request: MoveCompositionRequest,
+ signal: AbortSignal,
+) => {
+ const operations = getBrowserStudioOperations();
+ return operations === null
+ ? callApi('/api/move-composition', request, signal)
+ : operations.moveComposition(request);
+};
+
+export const addFolder = (request: AddFolderRequest, signal: AbortSignal) => {
+ const operations = getBrowserStudioOperations();
+ return operations === null
+ ? callApi('/api/add-folder', request, signal)
+ : operations.addFolder(request);
+};
+
+export const renameFolder = (
+ request: RenameFolderRequest,
+ signal: AbortSignal,
+) => {
+ const operations = getBrowserStudioOperations();
+ return operations === null
+ ? callApi('/api/rename-folder', request, signal)
+ : operations.renameFolder(request);
+};
+
+export const unwrapFolder = (
+ request: UnwrapFolderRequest,
+ signal: AbortSignal,
+) => {
+ const operations = getBrowserStudioOperations();
+ return operations === null
+ ? callApi('/api/unwrap-folder', request, signal)
+ : operations.unwrapFolder(request);
+};
- return callApi('/api/apply-codemod', body, signal);
+export const moveFolder = (request: MoveFolderRequest, signal: AbortSignal) => {
+ const operations = getBrowserStudioOperations();
+ return operations === null
+ ? callApi('/api/move-folder', request, signal)
+ : operations.moveFolder(request);
};
export const removeRenderJob = (job: RenderJob) => {
diff --git a/packages/studio/src/components/Timeline/SequencePropsObserver.tsx b/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
index bb0140f756..50cddb0f44 100644
--- a/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
+++ b/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
@@ -1,5 +1,9 @@
-import {type EventSourceEvent} from '@remotion/studio-shared';
+import {
+ REACT_REFRESH_STARTED_EVENT,
+ type EventSourceEvent,
+} from '@remotion/studio-shared';
import {useContext, useEffect, useLayoutEffect, useRef, useState} from 'react';
+import {flushSync} from 'react-dom';
import type {
SequencePropsStatusRemapping,
SequencePropsSubscriptionKey,
@@ -7,10 +11,7 @@ import type {
import {Internals} from 'remotion';
import {FastRefreshContext} from '../../fast-refresh-context';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
-import {
- subscribeToSequenceNodePathMutations,
- takePendingSequenceNodePathMutations,
-} from '../../helpers/sequence-node-path-mutations';
+import {takePendingSequenceNodePathMutations} from '../../helpers/sequence-node-path-mutations';
import {ExpandedTracksSetterContext} from '../ExpandedTracksProvider';
import {refreshSequencePropsSubscription} from './sequence-props-subscription-store';
import {useTimelineSelection} from './TimelineSelection';
@@ -32,14 +33,28 @@ export const SequencePropsObserver = () => {
Internals.OverrideIdsToNodePathsSettersContext,
);
const {fastRefreshes} = useContext(FastRefreshContext);
- const [mutationVersion, setMutationVersion] = useState(0);
- useEffect(
- () =>
- subscribeToSequenceNodePathMutations(() =>
- setMutationVersion((version) => version + 1),
- ),
- [],
- );
+ const [fastRefreshStarts, setFastRefreshStarts] = useState(0);
+ useEffect(() => {
+ const handleReactRefreshStarted = () => {
+ // Apply source-node remappings immediately before React commits the
+ // refreshed tree. This keeps the old tree paired with the old statuses
+ // and the new tree paired with the remapped statuses in the same task.
+ flushSync(() => {
+ setFastRefreshStarts((starts) => starts + 1);
+ });
+ };
+
+ window.addEventListener(
+ REACT_REFRESH_STARTED_EVENT,
+ handleReactRefreshStarted,
+ );
+ return () => {
+ window.removeEventListener(
+ REACT_REFRESH_STARTED_EVENT,
+ handleReactRefreshStarted,
+ );
+ };
+ }, []);
const {migrateExpandedTracksForSubscriptionKey} = useContext(
ExpandedTracksSetterContext,
);
@@ -198,7 +213,7 @@ export const SequencePropsObserver = () => {
}
}, [
fastRefreshes,
- mutationVersion,
+ fastRefreshStarts,
migrateExpandedTracksForSubscriptionKey,
propStatusesRef,
remapSelectionNodePaths,
diff --git a/packages/studio/src/helpers/sequence-node-path-mutations.ts b/packages/studio/src/helpers/sequence-node-path-mutations.ts
index 074db1cd2e..64ecc7a516 100644
--- a/packages/studio/src/helpers/sequence-node-path-mutations.ts
+++ b/packages/studio/src/helpers/sequence-node-path-mutations.ts
@@ -3,14 +3,6 @@ import {requestInsertedElementSelection} from './inserted-element-selection';
const pendingMutations: SequenceNodePathMutation[] = [];
const seenMutationIds = new Set<string>();
-const mutationListeners = new Set<() => void>();
-
-export const subscribeToSequenceNodePathMutations = (listener: () => void) => {
- mutationListeners.add(listener);
- return () => {
- mutationListeners.delete(listener);
- };
-};
export const queueSequenceNodePathMutation = (
mutation: SequenceNodePathMutation,
@@ -21,9 +13,6 @@ export const queueSequenceNodePathMutation = (
seenMutationIds.add(mutation.mutationId);
pendingMutations.push(mutation);
- for (const listener of mutationListeners) {
- listener();
- }
if (mutation.timelineSelection !== null) {
requestInsertedElementSelection({
diff --git a/packages/studio/src/helpers/use-create-composition.ts b/packages/studio/src/helpers/use-create-composition.ts
index 75cc438b56..dc011f63bc 100644
--- a/packages/studio/src/helpers/use-create-composition.ts
+++ b/packages/studio/src/helpers/use-create-composition.ts
@@ -1,13 +1,13 @@
import type {
CanvasCaptureData,
NewCompositionAsset,
- RecastCodemod,
+ NewCompositionOptions,
SymbolicatedStackFrame,
} from '@remotion/studio-shared';
import {useCallback, useMemo} from 'react';
import type {_InternalTypes} from 'remotion';
import {useSelectComposition} from '../components/InitialCompositionLoader';
-import {applyCodemod} from '../components/RenderQueue/actions';
+import {addComposition} from '../components/RenderQueue/actions';
import {slugifyName} from './slugify-name';
import {getRoute} from './url-state';
import {
@@ -101,9 +101,8 @@ export const useCreateComposition = ({
return validateCompositionDimension('Height', size.height);
}, [size.height]);
- const codemod: RecastCodemod = useMemo(() => {
+ const options: NewCompositionOptions = useMemo(() => {
return {
- type: 'new-composition',
asset,
newDurationInFrames: Number(durationInFrames),
newFps: Number(selectedFrameRate),
@@ -151,16 +150,17 @@ export const useCreateComposition = ({
signal: AbortSignal;
symbolicatedStack: SymbolicatedStackFrame | null;
}) => {
- const result = await applyCodemod({
- codemod,
- dryRun: false,
- signal,
- symbolicatedStack,
- undoRedoNavigation: {
- undoRoute: getRoute(),
- redoRoute: `/${compositionId}`,
+ const result = await addComposition(
+ {
+ options,
+ symbolicatedStack,
+ undoRedoNavigation: {
+ undoRoute: getRoute(),
+ redoRoute: `/${compositionId}`,
+ },
},
- });
+ signal,
+ );
if (result.success) {
selectComposition(
@@ -175,11 +175,11 @@ export const useCreateComposition = ({
return result;
},
- [codemod, compositionId, folderName, parentName, selectComposition],
+ [compositionId, folderName, options, parentName, selectComposition],
);
return {
- codemod,
+ options,
compositionId,
createComposition,
heightValidationMessage,
diff --git a/packages/studio/src/helpers/use-rename-composition.ts b/packages/studio/src/helpers/use-rename-composition.ts
index 8047fd49d7..8c651956f6 100644
--- a/packages/studio/src/helpers/use-rename-composition.ts
+++ b/packages/studio/src/helpers/use-rename-composition.ts
@@ -1,10 +1,7 @@
-import type {
- RecastCodemod,
- SymbolicatedStackFrame,
-} from '@remotion/studio-shared';
+import type {SymbolicatedStackFrame} from '@remotion/studio-shared';
import {useCallback, useMemo} from 'react';
import type {_InternalTypes} from 'remotion';
-import {applyCodemod} from '../components/RenderQueue/actions';
+import {renameComposition as renameCompositionApi} from '../components/RenderQueue/actions';
import {slugifyName} from './slugify-name';
import {getRoute, pushUrl} from './url-state';
import {validateCompositionName} from './validate-new-comp-data';
@@ -32,26 +29,11 @@ export const useRenameComposition = ({
[compositions, currentId],
);
- const getCodemod = useCallback(
- (value: string): RecastCodemod => {
- return {
- type: 'rename-composition',
- idToRename: currentId,
- newId: slugifyName(value),
- };
- },
- [currentId],
- );
-
const compositionId = slugifyName(newId);
const validationMessage = useMemo(() => {
return getValidationMessage(newId);
}, [getValidationMessage, newId]);
- const codemod = useMemo(() => {
- return getCodemod(newId);
- }, [getCodemod, newId]);
-
const valid = validationMessage === null && currentId !== compositionId;
const renameComposition = useCallback(
@@ -65,16 +47,18 @@ export const useRenameComposition = ({
symbolicatedStack: SymbolicatedStackFrame | null;
}) => {
const nextCompositionId = slugifyName(newCompositionId);
- const result = await applyCodemod({
- codemod: getCodemod(newCompositionId),
- dryRun: false,
- signal,
- symbolicatedStack,
- undoRedoNavigation: {
- undoRoute: getRoute(),
- redoRoute: `/${nextCompositionId}`,
+ const result = await renameCompositionApi(
+ {
+ idToRename: currentId,
+ newId: nextCompositionId,
+ symbolicatedStack,
+ undoRedoNavigation: {
+ undoRoute: getRoute(),
+ redoRoute: `/${nextCompositionId}`,
+ },
},
- });
+ signal,
+ );
if (result.success) {
pushUrl(`/${nextCompositionId}`);
@@ -82,11 +66,10 @@ export const useRenameComposition = ({
return result;
},
- [getCodemod],
+ [currentId],
);
return {
- codemod,
compositionId,
getValidationMessage,
renameComposition,
diff --git a/packages/studio/src/test/make-browser-studio-operations.ts b/packages/studio/src/test/make-browser-studio-operations.ts
index 23224af8a2..2fe196abbd 100644
--- a/packages/studio/src/test/make-browser-studio-operations.ts
+++ b/packages/studio/src/test/make-browser-studio-operations.ts
@@ -8,9 +8,11 @@ export const makeBrowserStudioOperations = (
overrides: Partial<BrowserStudioOperations>,
): BrowserStudioOperations => {
return {
- applyCodemod: () => unusedOperation('applyCodemod'),
+ addComposition: () => unusedOperation('addComposition'),
+ addFolder: () => unusedOperation('addFolder'),
consumeInitialElement: () => null,
deleteNodes: () => unusedOperation('deleteNodes'),
+ deleteComposition: () => unusedOperation('deleteComposition'),
deleteStaticFile: () => unusedOperation('deleteStaticFile'),
downloadRemoteAsset: () => unusedOperation('downloadRemoteAsset'),
downloadProject: () => unusedOperation('downloadProject'),
@@ -34,6 +36,8 @@ export const makeBrowserStudioOperations = (
getFileSource: () => unusedOperation('getFileSource'),
insertElement: () => unusedOperation('insertElement'),
insertCompositionElement: () => unusedOperation('insertCompositionElement'),
+ moveComposition: () => unusedOperation('moveComposition'),
+ moveFolder: () => unusedOperation('moveFolder'),
keyframes: {
addEffectKeyframe: () => unusedOperation('keyframes'),
addKeyframes: () => unusedOperation('keyframes'),
@@ -48,6 +52,8 @@ export const makeBrowserStudioOperations = (
installPackages: () => unusedOperation('packageInstallation'),
},
prepareElementInstall: () => unusedOperation('prepareElementInstall'),
+ renameComposition: () => unusedOperation('renameComposition'),
+ renameFolder: () => unusedOperation('renameFolder'),
redo: () => unusedOperation('redo'),
renameStaticFile: () => unusedOperation('renameStaticFile'),
reorderSequence: () => unusedOperation('reorderSequence'),
@@ -64,6 +70,9 @@ export const makeBrowserStudioOperations = (
unsubscribeFromSequenceProps: () =>
unusedOperation('unsubscribeFromSequenceProps'),
updateDefaultProps: () => unusedOperation('updateDefaultProps'),
+ updateCompositionMetadata: () =>
+ unusedOperation('updateCompositionMetadata'),
+ unwrapFolder: () => unusedOperation('unwrapFolder'),
writeStaticFile: () => unusedOperation('writeStaticFile'),
...overrides,
};