Skip to content

🎥 Make videos programmatically with React

`@remotion/canvas`: Add `queueSequenceNodePathRemappings()` to apply codemod remappings with the next Fast Refresh

JonnyBurger3237c8dd817f
diff --git a/bun.lock b/bun.lock
index b9cd369e7e..e4756e5961 100644
--- a/bun.lock
+++ b/bun.lock
@@ -154,6 +154,7 @@
"name": "@remotion/browser-bundler",
"version": "4.0.529",
"dependencies": {
+ "@remotion/studio-shared": "workspace:*",
"@rspack/browser": "2.1.1",
"react-refresh": "0.18.0",
"remotion": "workspace:*",
diff --git a/packages/browser-bundler/bundle.ts b/packages/browser-bundler/bundle.ts
index d742748dc6..1981f25000 100644
--- a/packages/browser-bundler/bundle.ts
+++ b/packages/browser-bundler/bundle.ts
@@ -40,6 +40,7 @@ const output = await build({
target: 'browser',
define,
external: [
+ '@remotion/studio-shared',
'@rspack/browser',
'react',
'react-dom',
diff --git a/packages/browser-bundler/package.json b/packages/browser-bundler/package.json
index 3186c74c46..114f462774 100644
--- a/packages/browser-bundler/package.json
+++ b/packages/browser-bundler/package.json
@@ -24,6 +24,7 @@
"url": "https://github.com/remotion-dev/remotion/issues"
},
"dependencies": {
+ "@remotion/studio-shared": "workspace:*",
"@rspack/browser": "2.1.1",
"react-refresh": "0.18.0",
"remotion": "workspace:*"
diff --git a/packages/browser-bundler/src/create-browser-bundle-runtime.ts b/packages/browser-bundler/src/create-browser-bundle-runtime.ts
index c6ac8ee11c..b09d300346 100644
--- a/packages/browser-bundler/src/create-browser-bundle-runtime.ts
+++ b/packages/browser-bundler/src/create-browser-bundle-runtime.ts
@@ -1,3 +1,7 @@
+import {
+ REACT_REFRESH_FINISHED_EVENT,
+ REACT_REFRESH_STARTED_EVENT,
+} from '@remotion/studio-shared';
import type {FC} from 'react';
import {Internals} from 'remotion';
import {createBrowserModuleScope} from './browser-module-scope';
@@ -185,7 +189,12 @@ export const createBrowserBundleRuntime = (): BrowserBundleRuntime => {
throw new Error('The browser bundle runtime was disposed.');
}
- refresh.performReactRefresh();
+ // Authoring UIs such as <Canvas> commit queued source-node remappings
+ // on the started event, in the same task as the refreshed tree.
+ window.dispatchEvent(new Event(REACT_REFRESH_STARTED_EVENT));
+ if (refresh.performReactRefresh() !== null) {
+ window.dispatchEvent(new Event(REACT_REFRESH_FINISHED_EVENT));
+ }
}
if (disposed) {
diff --git a/packages/browser-bundler/tsconfig.json b/packages/browser-bundler/tsconfig.json
index 00f904424c..49b4e5c2c5 100644
--- a/packages/browser-bundler/tsconfig.json
+++ b/packages/browser-bundler/tsconfig.json
@@ -12,5 +12,9 @@
"emitDeclarationOnly": true
},
"include": ["src"],
- "references": [{"path": "../core"}, {"path": "../player"}]
+ "references": [
+ {"path": "../core"},
+ {"path": "../player"},
+ {"path": "../studio-shared"}
+ ]
}
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index f06a94404b..76515bc622 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -36,7 +36,6 @@ import {
updateNodeProps,
type CodemodFileChange,
type CodemodNodeResult,
- type CodemodResult,
type CompositionDestination,
type EffectKeyframeUpdate,
type InsertableSequenceWrapper,
@@ -381,7 +380,7 @@ const getAddCompositionResult = ({
project: VirtualProject;
compositionFile: string;
options: NewCompositionOptions;
-}): CodemodResult => {
+}): CodemodNodeResult => {
const componentFilePath = `${dirname(compositionFile)}/${options.componentName}.tsx`;
if (project.files[componentFilePath] !== undefined) {
throw new Error(
@@ -418,6 +417,7 @@ const getAddCompositionResult = ({
const result = addCompositionCodemod(composition);
return {
+ ...result,
changes: [
...result.changes,
{
@@ -625,16 +625,14 @@ export const createBrowserStudioOperations = ({
}: {
fileName: string;
project: VirtualProject;
- result: CodemodResult | CodemodNodeResult;
+ result: CodemodNodeResult;
undoRedoNavigation: UndoRedoNavigation | null;
}) => {
- const nodePathMutationFiles =
- 'nodePathRemappings' in result ? getNodePathMutationFiles(result) : null;
return controller.applyMutation({
undoRedoNavigation,
timelineSelection: null,
fileName,
- nodePathMutationFiles,
+ nodePathMutationFiles: getNodePathMutationFiles(result),
mutate: (current) => applyCodemodChanges(current, result.changes),
});
};
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 7312a85700..e7028a256e 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
@@ -403,7 +403,19 @@ test('duplicates compositions as an undoable project mutation', async () => {
};
const result = await operations.duplicateComposition(request);
- expect(result).toEqual({success: true, nodePathMutation: null});
+ if (!result.success || result.nodePathMutation === null) {
+ throw new Error('Expected the duplicate to remap node paths');
+ }
+
+ // The copy is inserted after the original; the copied registration is new.
+ expect(result.nodePathMutation.files).toEqual([
+ {
+ absolutePath: '/project/src/Composition.tsx',
+ remappings: expect.arrayContaining([
+ {oldNodePath: null, newNodePath: expect.any(Array)},
+ ]),
+ },
+ ]);
expect(project.files['/project/src/Composition.tsx']).toContain(
'id="MyCompCopy"',
);
@@ -412,9 +424,18 @@ test('duplicates compositions as an undoable project mutation', async () => {
'width={1920}',
);
- expect(await operations.undo()).toEqual({
+ const undoResult = await operations.undo();
+ expect(undoResult).toEqual({
success: true,
- nodePathMutation: null,
+ nodePathMutation: expect.objectContaining({
+ files: result.nodePathMutation.files.map((file) => ({
+ absolutePath: file.absolutePath,
+ remappings: file.remappings.map((remapping) => ({
+ oldNodePath: remapping.newNodePath,
+ newNodePath: remapping.oldNodePath,
+ })),
+ })),
+ }),
route: '/MyComp',
});
expect(project.files['/project/src/Composition.tsx']).toBe(
@@ -422,7 +443,9 @@ test('duplicates compositions as an undoable project mutation', async () => {
);
expect(await operations.redo()).toEqual({
success: true,
- nodePathMutation: null,
+ nodePathMutation: expect.objectContaining({
+ files: result.nodePathMutation.files,
+ }),
route: '/MyCompCopy',
});
expect(project.files['/project/src/Composition.tsx']).toContain(
diff --git a/packages/canvas/src/canvas-controller.ts b/packages/canvas/src/canvas-controller.ts
index e0830d1b9d..fddebd49e9 100644
--- a/packages/canvas/src/canvas-controller.ts
+++ b/packages/canvas/src/canvas-controller.ts
@@ -17,6 +17,11 @@ import {
createCanvasSelectionController,
type CanvasSelectionController,
} from './selection';
+import {
+ remapCanvasSelection,
+ remapOverrideIdToNodePaths,
+ type CanvasSequenceNodePathRemapping,
+} from './sequence-node-path-remapping';
type VisualModeSetters = React.ContextType<
typeof Internals.VisualModeSettersContext
@@ -48,6 +53,22 @@ export type CanvasController = {
readonly setSequenceNodePaths: (
nodePaths: Record<string, SequencePropsSubscriptionKey>,
) => void;
+ /**
+ * Queue the `nodePathRemappings` of a source edit. They are applied when
+ * the next Fast Refresh update starts, immediately before React commits the
+ * refreshed tree, so registered node paths and the selection never pair the
+ * new elements with the old paths.
+ */
+ readonly queueSequenceNodePathRemappings: (
+ remappings: readonly CanvasSequenceNodePathRemapping[],
+ ) => void;
+ /**
+ * Apply the remappings of one source edit to the registered node paths and
+ * the selection right away, for hosts that swap the mounted tree themselves.
+ */
+ readonly remapSequenceNodePaths: (
+ remappings: readonly CanvasSequenceNodePathRemapping[],
+ ) => void;
};
type CanvasControllerInternals = {
@@ -58,6 +79,7 @@ type CanvasControllerInternals = {
readonly subscribe: (listener: () => void) => () => void;
};
readonly setVisualModeSetters: (setters: VisualModeSetters | null) => void;
+ readonly commitQueuedSequenceNodePathRemappings: () => void;
};
const controllerInternals = new WeakMap<
@@ -92,6 +114,9 @@ export const createCanvasController = (): CanvasController => {
let sequences: TSequence[] = [];
let nodePaths: OverrideIdToNodePaths = {};
let visualModeSetters: VisualModeSetters | null = null;
+ // One entry per source edit: the remappings of an edit must not be chained
+ // with each other, only with those of earlier edits.
+ let queuedRemappings: (readonly CanvasSequenceNodePathRemapping[])[] = [];
const timelineListeners = new Set<() => void>();
const nodePathListeners = new Set<() => void>();
@@ -113,6 +138,41 @@ export const createCanvasController = (): CanvasController => {
);
};
+ const setNodePaths = (nextNodePaths: OverrideIdToNodePaths) => {
+ nodePaths = nextNodePaths;
+ for (const listener of nodePathListeners) {
+ listener();
+ }
+
+ recalculateTimeline();
+ };
+
+ const selection = createCanvasSelectionController();
+ const hover = createCanvasHoverController();
+ const remapSequenceNodePaths = (
+ remappings: readonly CanvasSequenceNodePathRemapping[],
+ ) => {
+ if (remappings.length === 0) {
+ return;
+ }
+
+ const nextNodePaths = remapOverrideIdToNodePaths(nodePaths, remappings);
+ if (nextNodePaths !== null) {
+ setNodePaths(nextNodePaths);
+ }
+
+ const nextSelection = remapCanvasSelection(
+ selection.getSnapshot(),
+ remappings,
+ );
+ if (nextSelection !== null) {
+ selection.setSnapshot(nextSelection);
+ }
+
+ // Hover keys embed node paths; the pointer restores it on the next move.
+ hover.clear(null);
+ };
+
const controller: CanvasController = {
timeline: {
getSnapshot: () => timelineSnapshot,
@@ -121,8 +181,8 @@ export const createCanvasController = (): CanvasController => {
return () => timelineListeners.delete(listener);
},
},
- selection: createCanvasSelectionController(),
- hover: createCanvasHoverController(),
+ selection,
+ hover,
overrides: {
set: (nodePathInfo, key, value) => {
visualModeSetters?.setDragOverrides(
@@ -142,13 +202,14 @@ export const createCanvasController = (): CanvasController => {
return;
}
- nodePaths = {...nextNodePaths};
- for (const listener of nodePathListeners) {
- listener();
+ setNodePaths({...nextNodePaths});
+ },
+ queueSequenceNodePathRemappings: (remappings) => {
+ if (remappings.length > 0) {
+ queuedRemappings.push(remappings);
}
-
- recalculateTimeline();
},
+ remapSequenceNodePaths,
};
controllerInternals.set(controller, {
@@ -171,6 +232,13 @@ export const createCanvasController = (): CanvasController => {
setVisualModeSetters: (setters) => {
visualModeSetters = setters;
},
+ commitQueuedSequenceNodePathRemappings: () => {
+ const pending = queuedRemappings;
+ queuedRemappings = [];
+ for (const remappings of pending) {
+ remapSequenceNodePaths(remappings);
+ }
+ },
});
return controller;
diff --git a/packages/canvas/src/canvas.tsx b/packages/canvas/src/canvas.tsx
index 9f7febdf38..ad9a056e0f 100644
--- a/packages/canvas/src/canvas.tsx
+++ b/packages/canvas/src/canvas.tsx
@@ -1,5 +1,6 @@
import type {PlayerProps, PlayerRef} from '@remotion/player';
import {Player, PlayerInternals} from '@remotion/player';
+import {REACT_REFRESH_STARTED_EVENT} from '@remotion/studio-shared';
import type {RefObject} from 'react';
import React, {
forwardRef,
@@ -94,6 +95,19 @@ const CanvasFn = <
useEffect(() => {
return () => internals.clear();
}, [internals]);
+ // Studio's bundler, Browser Studio and the browser bundler runtime dispatch
+ // this event before React Refresh schedules the refreshed tree. Committing
+ // the queued remappings here renders the new elements with their new paths.
+ useEffect(() => {
+ if (typeof window === 'undefined') {
+ return;
+ }
+
+ const commit = () => internals.commitQueuedSequenceNodePathRemappings();
+ window.addEventListener(REACT_REFRESH_STARTED_EVENT, commit);
+ return () =>
+ window.removeEventListener(REACT_REFRESH_STARTED_EVENT, commit);
+ }, [internals]);
// React Refresh (used by Browser Studio) or React DevTools must have
// registered the renderer before this commit. Install before the commit hook
// fires so the initial outline nodes are discovered as well.
diff --git a/packages/canvas/src/index.ts b/packages/canvas/src/index.ts
index d1d72a3892..2a0b7cad38 100644
--- a/packages/canvas/src/index.ts
+++ b/packages/canvas/src/index.ts
@@ -8,6 +8,7 @@ export type {
CanvasController,
CanvasOverridesController,
} from './canvas-controller';
+export type {CanvasSequenceNodePathRemapping} from './sequence-node-path-remapping';
export {
createCanvasHoverController,
useCanvasHover,
diff --git a/packages/canvas/src/sequence-node-path-remapping.ts b/packages/canvas/src/sequence-node-path-remapping.ts
new file mode 100644
index 0000000000..45367ccb41
--- /dev/null
+++ b/packages/canvas/src/sequence-node-path-remapping.ts
@@ -0,0 +1,143 @@
+import type {
+ OverrideIdToNodePaths,
+ SequenceNodePath,
+ SequencePropsSubscriptionKey,
+} from 'remotion';
+import type {SequenceNodePathInfo} from './get-timeline-sequence-sort-key';
+import type {CanvasSelectionItem, CanvasSelectionSnapshot} from './selection';
+
+/**
+ * How a source edit moved a JSX node, as returned by the mutations of
+ * `@remotion/codemods` in `nodePathRemappings`. A `null` old path is an
+ * insertion, a `null` new path a removal.
+ */
+export type CanvasSequenceNodePathRemapping = {
+ /** The edited file, matching `absolutePath` of the registered node paths. */
+ readonly filePath: string;
+ readonly oldNodePath: SequenceNodePath | null;
+ readonly newNodePath: SequenceNodePath | null;
+};
+
+const findRemapping = (
+ key: SequencePropsSubscriptionKey,
+ remappings: readonly CanvasSequenceNodePathRemapping[],
+) => {
+ const nodePath = JSON.stringify(key.nodePath);
+ return (
+ remappings.find(
+ (remapping) =>
+ remapping.filePath === key.absolutePath &&
+ remapping.oldNodePath !== null &&
+ JSON.stringify(remapping.oldNodePath) === nodePath,
+ ) ?? null
+ );
+};
+
+/**
+ * The source node a selection follows after the edit. `null` when the node
+ * was removed, the same object when the node was not remapped.
+ */
+export const remapSequenceNodePathInfo = (
+ nodePathInfo: SequenceNodePathInfo,
+ remappings: readonly CanvasSequenceNodePathRemapping[],
+): SequenceNodePathInfo | null => {
+ const remapping = findRemapping(
+ nodePathInfo.sequenceSubscriptionKey,
+ remappings,
+ );
+ if (
+ remapping === null ||
+ JSON.stringify(remapping.newNodePath) ===
+ JSON.stringify(nodePathInfo.sequenceSubscriptionKey.nodePath)
+ ) {
+ return nodePathInfo;
+ }
+
+ if (remapping.newNodePath === null) {
+ return null;
+ }
+
+ return {
+ ...nodePathInfo,
+ sequenceSubscriptionKey: {
+ ...nodePathInfo.sequenceSubscriptionKey,
+ nodePath: remapping.newNodePath,
+ },
+ };
+};
+
+/**
+ * Override IDs belong to mounted React instances. Fast Refresh reuses an
+ * instance at a path that still exists after the edit, so its ID then refers
+ * to whichever node is at that path. Only IDs whose path disappeared follow
+ * their node to its new path, or are dropped when the node was removed.
+ */
+export const remapOverrideIdToNodePaths = (
+ nodePaths: OverrideIdToNodePaths,
+ remappings: readonly CanvasSequenceNodePathRemapping[],
+): OverrideIdToNodePaths | null => {
+ let changed = false;
+ const next: OverrideIdToNodePaths = {};
+ for (const [overrideId, key] of Object.entries(nodePaths)) {
+ const remapping = findRemapping(key, remappings);
+ const nodePath = JSON.stringify(key.nodePath);
+ const pathStillExists = remappings.some(
+ (candidate) =>
+ candidate.filePath === key.absolutePath &&
+ candidate.newNodePath !== null &&
+ JSON.stringify(candidate.newNodePath) === nodePath,
+ );
+ if (remapping === null || pathStillExists) {
+ next[overrideId] = key;
+ continue;
+ }
+
+ changed = true;
+ if (remapping.newNodePath !== null) {
+ next[overrideId] = {...key, nodePath: remapping.newNodePath};
+ }
+ }
+
+ return changed ? next : null;
+};
+
+const remapSelectionItem = (
+ item: CanvasSelectionItem,
+ remappings: readonly CanvasSequenceNodePathRemapping[],
+): CanvasSelectionItem | null => {
+ if (item.type === 'guide') {
+ return item;
+ }
+
+ const nodePathInfo = remapSequenceNodePathInfo(item.nodePathInfo, remappings);
+ if (nodePathInfo === item.nodePathInfo) {
+ return item;
+ }
+
+ return nodePathInfo === null ? null : {...item, nodePathInfo};
+};
+
+/** The selection after the edit, or `null` when no item was affected. */
+export const remapCanvasSelection = (
+ snapshot: CanvasSelectionSnapshot,
+ remappings: readonly CanvasSequenceNodePathRemapping[],
+): CanvasSelectionSnapshot | null => {
+ const selectedItems = snapshot.selectedItems
+ .map((item) => remapSelectionItem(item, remappings))
+ .filter((item): item is CanvasSelectionItem => item !== null);
+ const anchor =
+ snapshot.anchor === null
+ ? null
+ : remapSelectionItem(snapshot.anchor, remappings);
+ if (
+ selectedItems.length === snapshot.selectedItems.length &&
+ selectedItems.every(
+ (item, index) => item === snapshot.selectedItems[index],
+ ) &&
+ anchor === snapshot.anchor
+ ) {
+ return null;
+ }
+
+ return {selectedItems, anchor};
+};
diff --git a/packages/codemods/src/add-canvas-capture-composition.ts b/packages/codemods/src/add-canvas-capture-composition.ts
index 1f84843692..56acc83e59 100644
--- a/packages/codemods/src/add-canvas-capture-composition.ts
+++ b/packages/codemods/src/add-canvas-capture-composition.ts
@@ -1,11 +1,7 @@
import type {JSXElement} from '@babel/types';
import type {CanvasCaptureData} from '@remotion/studio-shared';
import * as recast from 'recast';
-import {
- getCodemodResult,
- type CodemodProject,
- type CodemodResult,
-} from './codemod-project';
+import type {CodemodProject} from './codemod-project';
import {
assertNewCompositionId,
validateMetadata,
@@ -13,8 +9,10 @@ import {
type CompositionMetadata,
type FolderReference,
} from './composition-editing';
+import {getRegistrationInsertionResult} from './folder-editing';
import {generateCanvasCaptureComposition} from './generate-canvas-capture-composition';
import {findProjectFile} from './internals';
+import type {CodemodInsertionResult} from './node-references';
import {getRegistrationInsertionSourceEdit} from './registration-source-edits';
import {ensureNamedImport} from './sequence-props/imports';
import {parseAst} from './sequence-props/parse-ast';
@@ -47,7 +45,7 @@ export const addCanvasCaptureComposition = <Project extends CodemodProject>({
metadata,
folder,
capture,
-}: AddCanvasCaptureCompositionOptions<Project>): CodemodResult => {
+}: AddCanvasCaptureCompositionOptions<Project>): CodemodInsertionResult => {
assertNewCompositionId({project, compositionFile, compositionId});
validateMetadata(metadata);
if (!/^[A-Z_$][\w$]*$/.test(component.importName)) {
@@ -111,13 +109,23 @@ export const addCanvasCaptureComposition = <Project extends CodemodProject>({
...metadata,
...capture,
});
- parseAst(output);
parseAst(componentSource);
- return getCodemodResult({
+ const result = getRegistrationInsertionResult({
project,
- edits: [
- {filePath, nextContents: output},
- {filePath: component.filePath, nextContents: componentSource},
- ],
+ filePath,
+ input,
+ output,
+ inserted: {type: 'last-child', folder: folder ?? null},
});
+ return {
+ ...result,
+ changes: [
+ ...result.changes,
+ {
+ filePath: component.filePath,
+ previousContents: null,
+ nextContents: componentSource,
+ },
+ ],
+ };
};
diff --git a/packages/codemods/src/add-composition.ts b/packages/codemods/src/add-composition.ts
index 582bd287e4..2a9c25351c 100644
--- a/packages/codemods/src/add-composition.ts
+++ b/packages/codemods/src/add-composition.ts
@@ -1,7 +1,6 @@
import type {JSXElement} from '@babel/types';
import * as recast from 'recast';
-import type {CodemodProject, CodemodResult} from './codemod-project';
-import {getCodemodResult} from './codemod-project';
+import type {CodemodProject} from './codemod-project';
import {
type CompositionTarget,
type CompositionMetadata,
@@ -9,7 +8,9 @@ import {
assertNewCompositionId,
validateMetadata,
} from './composition-editing';
+import {getRegistrationInsertionResult} from './folder-editing';
import {findProjectFile} from './internals';
+import type {CodemodInsertionResult} from './node-references';
import {getRegistrationInsertionSourceEdit} from './registration-source-edits';
import {ensureNamedImport} from './sequence-props/imports';
import {parseAst} from './sequence-props/parse-ast';
@@ -34,7 +35,7 @@ export const addComposition = <Project extends CodemodProject>({
component,
metadata,
folder,
-}: AddCompositionOptions<Project>): CodemodResult => {
+}: AddCompositionOptions<Project>): CodemodInsertionResult => {
assertNewCompositionId({project, compositionFile, compositionId});
validateMetadata(metadata);
if (!/^[A-Z_$][\w$]*$/.test(component.importName)) {
@@ -133,9 +134,11 @@ export const addComposition = <Project extends CodemodProject>({
}),
],
});
- parseAst(output);
- return getCodemodResult({
+ return getRegistrationInsertionResult({
project,
- edits: [{filePath, nextContents: output}],
+ filePath,
+ input,
+ output,
+ inserted: {type: 'composition', compositionId},
});
};
diff --git a/packages/codemods/src/add-folder.ts b/packages/codemods/src/add-folder.ts
index 0b2a330d14..191ac229af 100644
--- a/packages/codemods/src/add-folder.ts
+++ b/packages/codemods/src/add-folder.ts
@@ -1,9 +1,13 @@
import * as recast from 'recast';
import type {CodemodProject} from './codemod-project';
-import {getCodemodResult} from './codemod-project';
import type {FolderReference} from './composition-editing';
-import {getTreeEntries, requireTreeItem} from './folder-editing';
+import {
+ getRegistrationInsertionResult,
+ getTreeEntries,
+ requireTreeItem,
+} from './folder-editing';
import {findProjectFile} from './internals';
+import type {CodemodInsertionResult} from './node-references';
import {getRegistrationInsertionSourceEdit} from './registration-source-edits';
import {ensureNamedImport} from './sequence-props/imports';
import {parseAst} from './sequence-props/parse-ast';
@@ -23,7 +27,7 @@ export const addFolder = <Project extends CodemodProject>({
project,
compositionFile,
folder,
-}: AddFolderOptions<Project>) => {
+}: AddFolderOptions<Project>): CodemodInsertionResult => {
if (!folder.name || folder.name.includes('/')) {
throw new Error('Folder names must be non-empty and cannot contain /');
}
@@ -92,9 +96,11 @@ export const addFolder = <Project extends CodemodProject>({
}),
],
});
- parseAst(nextContents);
- return getCodemodResult({
+ return getRegistrationInsertionResult({
project,
- edits: [{filePath, nextContents}],
+ filePath,
+ input,
+ output: nextContents,
+ inserted: {type: 'folder', ...folder},
});
};
diff --git a/packages/codemods/src/delete-composition.ts b/packages/codemods/src/delete-composition.ts
index 86c2edcaf2..65e68f5c08 100644
--- a/packages/codemods/src/delete-composition.ts
+++ b/packages/codemods/src/delete-composition.ts
@@ -1,5 +1,5 @@
-import type {CodemodProject, CodemodResult} from './codemod-project';
-import {getCodemodResult} from './codemod-project';
+import type {JSXElement} from '@babel/types';
+import type {CodemodProject} from './codemod-project';
import {
type CompositionTarget,
requireComposition,
@@ -8,6 +8,15 @@ import {
findJsxElementPathForDeletion,
getNodeSourceEdit,
} from './delete-jsx-nodes-internal';
+import {
+ captureJsxNodePaths,
+ collectJsxSubtree,
+} from './get-node-path-remappings';
+import {
+ getNodeEditResult,
+ getSubtreeEditRemappings,
+ type CodemodNodeResult,
+} from './node-references';
import {parseAst} from './sequence-props/parse-ast';
import {applySourceEdits} from './source-edits';
@@ -18,7 +27,7 @@ export const deleteComposition = <Project extends CodemodProject>({
project,
compositionFile,
compositionId,
-}: DeleteCompositionOptions<Project>): CodemodResult => {
+}: DeleteCompositionOptions<Project>): CodemodNodeResult => {
const node = requireComposition({project, compositionFile, compositionId});
const input = project.files[node.filePath];
const ast = parseAst(input);
@@ -27,12 +36,26 @@ export const deleteComposition = <Project extends CodemodProject>({
throw new Error('Could not locate the composition to delete');
}
+ const before = captureJsxNodePaths(ast);
const output = applySourceEdits({
input,
edits: [getNodeSourceEdit({input, jsxPath})],
});
- return getCodemodResult({
+ const nodePathRemappings = getSubtreeEditRemappings({
+ before,
+ after: captureJsxNodePaths(parseAst(output)),
+ subtrees: [
+ {
+ before: collectJsxSubtree(
+ before,
+ (jsxPath.node as JSXElement).openingElement,
+ ),
+ after: new Set(),
+ },
+ ],
+ });
+ return getNodeEditResult({
project,
- edits: [{filePath: node.filePath, nextContents: output}],
+ edits: [{filePath: node.filePath, output, nodePathRemappings}],
});
};
diff --git a/packages/codemods/src/duplicate-composition.ts b/packages/codemods/src/duplicate-composition.ts
index 7de484b7dd..f4f493c4fb 100644
--- a/packages/codemods/src/duplicate-composition.ts
+++ b/packages/codemods/src/duplicate-composition.ts
@@ -1,5 +1,4 @@
-import type {CodemodProject, CodemodResult} from './codemod-project';
-import {getCodemodResult} from './codemod-project';
+import type {CodemodProject} from './codemod-project';
import {
type CompositionTarget,
type CompositionMetadata,
@@ -8,7 +7,8 @@ import {
validateMetadata,
} from './composition-editing';
import {duplicateCompositionInSource} from './duplicate-composition-in-source';
-import {parseAst} from './sequence-props/parse-ast';
+import {getRegistrationInsertionResult} from './folder-editing';
+import type {CodemodInsertionResult} from './node-references';
export type DuplicateCompositionOptions<Project extends CodemodProject> =
CompositionTarget & {
@@ -25,7 +25,7 @@ export const duplicateComposition = <Project extends CodemodProject>({
newId,
tag,
metadata = {},
-}: DuplicateCompositionOptions<Project>): CodemodResult => {
+}: DuplicateCompositionOptions<Project>): CodemodInsertionResult => {
const node = requireComposition({project, compositionFile, compositionId});
assertNewCompositionId({project, compositionFile, compositionId: newId});
validateMetadata(metadata);
@@ -37,16 +37,19 @@ export const duplicateComposition = <Project extends CodemodProject>({
throw new Error('Still registrations do not have fps or durationInFrames');
}
+ const input = project.files[node.filePath];
const output = duplicateCompositionInSource({
- input: project.files[node.filePath],
+ input,
nodePath: node.nodePath,
newId,
tag: newTag,
metadata,
});
- parseAst(output);
- return getCodemodResult({
+ return getRegistrationInsertionResult({
project,
- edits: [{filePath: node.filePath, nextContents: output}],
+ filePath: node.filePath,
+ input,
+ output,
+ inserted: {type: 'composition', compositionId: newId},
});
};
diff --git a/packages/codemods/src/folder-editing.ts b/packages/codemods/src/folder-editing.ts
index 15f799d7c7..b780e54659 100644
--- a/packages/codemods/src/folder-editing.ts
+++ b/packages/codemods/src/folder-editing.ts
@@ -3,10 +3,21 @@ import * as recast from 'recast';
import type {CodemodProject} from './codemod-project';
import type {FolderReference} from './composition-editing';
import {getMoveTreeItemSourceEdits} from './folder-source-edits';
-import {captureJsxNodePaths} from './get-node-path-remappings';
+import {
+ captureJsxNodePaths,
+ collectJsxSubtree,
+ requireCapturedNodePath,
+} from './get-node-path-remappings';
import {findProjectFile} from './internals';
-import {getNodeEditResult} from './node-references';
import {
+ getNodeEditResult,
+ getSubtreeEditRemappings,
+ type CodemodInsertionResult,
+ type CodemodNodeResult,
+ type NodeReference,
+} from './node-references';
+import {
+ findRegistrationRoot,
getCompositionIdFromJSXElement,
getFolderNameFromJSXElement,
} from './registration-source-edits';
@@ -88,6 +99,64 @@ export const requireTreeItem = (
return matches[0];
};
+// The result of inserting one registration element. The element is located in
+// the output by its ID or folder reference, or as the last element appended to
+// the folder or the registration root.
+export const getRegistrationInsertionResult = ({
+ project,
+ filePath,
+ input,
+ output,
+ inserted,
+}: {
+ project: CodemodProject;
+ filePath: string;
+ input: string;
+ output: string;
+ inserted:
+ | CompositionTreeItem
+ | {type: 'last-child'; folder: FolderReference | null};
+}): CodemodInsertionResult => {
+ const before = captureJsxNodePaths(parseAst(input));
+ const nextAst = parseAst(output);
+ const after = captureJsxNodePaths(nextAst);
+ let element: JSXElement;
+ if (inserted.type === 'last-child') {
+ const root = findRegistrationRoot({ast: nextAst, folder: inserted.folder});
+ const last = root.children.findLast(
+ (child): child is JSXElement => child.type === 'JSXElement',
+ );
+ if (!last) {
+ throw new Error('Could not locate the inserted registration');
+ }
+
+ element = last;
+ } else {
+ element = requireTreeItem(getTreeEntries({ast: nextAst}), inserted).node;
+ }
+
+ const nodePathRemappings = getSubtreeEditRemappings({
+ before,
+ after,
+ subtrees: [
+ {
+ before: new Set(),
+ after: collectJsxSubtree(after, element.openingElement),
+ },
+ ],
+ });
+ return {
+ ...getNodeEditResult({
+ project,
+ edits: [{filePath, output, nodePathRemappings}],
+ }),
+ insertedNode: {
+ filePath,
+ nodePath: requireCapturedNodePath(after, element.openingElement),
+ },
+ };
+};
+
export const moveTreeItem = <Project extends CodemodProject>({
project,
compositionFile,
@@ -98,12 +167,13 @@ export const moveTreeItem = <Project extends CodemodProject>({
compositionFile: string;
source: CompositionTreeItem;
destination: CompositionDestination;
-}) => {
+}): CodemodNodeResult & {updatedNode: NodeReference} => {
const filePath = findProjectFile({project, filePath: compositionFile});
const input = project.files[filePath];
const ast = parseAst(input);
const entries = getTreeEntries({ast});
const entry = requireTreeItem(entries, source);
+ const before = captureJsxNodePaths(ast);
const target =
destination.type === 'root'
? null
@@ -150,7 +220,14 @@ export const moveTreeItem = <Project extends CodemodProject>({
((destination.type === 'folder' || destination.type === 'root') &&
entry.parentName === destinationParentName)
) {
- return {changes: [], nodePathRemappings: []};
+ return {
+ changes: [],
+ nodePathRemappings: [],
+ updatedNode: {
+ filePath,
+ nodePath: requireCapturedNodePath(before, entry.node.openingElement),
+ },
+ };
}
if (!entry.directJsxChild)
@@ -182,51 +259,26 @@ export const moveTreeItem = <Project extends CodemodProject>({
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, output: nextContents, nodePathRemappings}],
+ const nodePathRemappings = getSubtreeEditRemappings({
+ before,
+ after,
+ subtrees: [
+ {
+ before: collectJsxSubtree(before, entry.node.openingElement),
+ after: collectJsxSubtree(after, movedEntry.node.openingElement),
+ },
+ ],
});
+
+ return {
+ ...getNodeEditResult({
+ project,
+ edits: [{filePath, output: nextContents, nodePathRemappings}],
+ }),
+ updatedNode: {
+ filePath,
+ nodePath: requireCapturedNodePath(after, movedEntry.node.openingElement),
+ },
+ };
};
diff --git a/packages/codemods/src/get-node-path-remappings.ts b/packages/codemods/src/get-node-path-remappings.ts
index a486c61b08..b212e8c01b 100644
--- a/packages/codemods/src/get-node-path-remappings.ts
+++ b/packages/codemods/src/get-node-path-remappings.ts
@@ -42,6 +42,34 @@ export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {
return captured;
};
+// The opening elements of a JSX element and its descendants. Relies on the
+// captured nodes being in document order, so parents precede their children.
+export const collectJsxSubtree = (
+ captured: CapturedJsxNodePath[],
+ root: JSXOpeningElement,
+): Set<JSXOpeningElement> => {
+ const nodes = new Set<JSXOpeningElement>([root]);
+ for (const {node, parentNode} of captured) {
+ if (parentNode !== null && nodes.has(parentNode)) {
+ nodes.add(node);
+ }
+ }
+
+ return nodes;
+};
+
+export const requireCapturedNodePath = (
+ captured: CapturedJsxNodePath[],
+ node: JSXOpeningElement,
+): SequenceNodePath => {
+ const match = captured.find((entry) => entry.node === node);
+ if (!match) {
+ throw new Error('Could not locate the JSX node after editing the source');
+ }
+
+ return match.nodePath;
+};
+
export const getNodePathRemappings = ({
ast,
captured,
diff --git a/packages/codemods/src/node-references.ts b/packages/codemods/src/node-references.ts
index 81415804e6..33a8d766a3 100644
--- a/packages/codemods/src/node-references.ts
+++ b/packages/codemods/src/node-references.ts
@@ -1,7 +1,10 @@
import type {SequenceNodePath} from 'remotion';
import type {CodemodProject, CodemodResult} from './codemod-project';
import {getCodemodResult} from './codemod-project';
-import {captureJsxNodePaths} from './get-node-path-remappings';
+import {
+ captureJsxNodePaths,
+ type CapturedJsxNodePath,
+} from './get-node-path-remappings';
import {findProjectFile} from './internals';
import {parseAst} from './sequence-props/parse-ast';
@@ -75,6 +78,13 @@ export const getNodeEditResult = ({
};
};
+const isUnchangedNode = (
+ node: CapturedJsxNodePath,
+ next: CapturedJsxNodePath,
+): boolean =>
+ JSON.stringify(node.nodePath) === JSON.stringify(next.nodePath) &&
+ node.signature === next.signature;
+
// Props, effects, and keyframe edits preserve JSX traversal order. Hooks and
// statements they insert can still change the paths of every node in a function.
export const getUnchangedStructureRemappings = ({
@@ -92,15 +102,72 @@ export const getUnchangedStructureRemappings = ({
return before.flatMap((node, index) => {
const next = after[index];
+ return isUnchangedNode(node, next)
+ ? []
+ : [{oldNodePath: node.nodePath, newNodePath: next.nodePath}];
+ });
+};
+
+// Registration edits insert, remove, or move whole JSX subtrees while the
+// remaining nodes keep their document order.
+export const getSubtreeEditRemappings = ({
+ before,
+ after,
+ subtrees,
+}: {
+ before: CapturedJsxNodePath[];
+ after: CapturedJsxNodePath[];
+ // Matched separately from the remaining nodes. A subtree without `before`
+ // nodes was inserted, a subtree without `after` nodes was removed.
+ subtrees: {before: ReadonlySet<object>; after: ReadonlySet<object>}[];
+}): NodeSourceEdit['nodePathRemappings'] => {
+ const remainingBefore = before.filter(
+ ({node}) => !subtrees.some((subtree) => subtree.before.has(node)),
+ );
+ const remainingAfter = after.filter(
+ ({node}) => !subtrees.some((subtree) => subtree.after.has(node)),
+ );
+ if (remainingBefore.length !== remainingAfter.length) {
+ throw new Error(
+ 'Could not remap JSX nodes after editing the registrations',
+ );
+ }
+
+ const pairs: {
+ node: CapturedJsxNodePath | null;
+ next: CapturedJsxNodePath | null;
+ }[] = remainingBefore.map((node, index) => ({
+ node,
+ next: remainingAfter[index],
+ }));
+ for (const subtree of subtrees) {
+ const nodes = before.filter(({node}) => subtree.before.has(node));
+ const nextNodes = after.filter(({node}) => subtree.after.has(node));
if (
- JSON.stringify(node.nodePath) === JSON.stringify(next.nodePath) &&
- node.signature === next.signature
+ nodes.length > 0 &&
+ nextNodes.length > 0 &&
+ nodes.length !== nextNodes.length
) {
- return [];
+ throw new Error(
+ 'Could not remap JSX nodes after editing the registrations',
+ );
}
- return [{oldNodePath: node.nodePath, newNodePath: next.nodePath}];
- });
+ for (let i = 0; i < Math.max(nodes.length, nextNodes.length); i++) {
+ pairs.push({node: nodes[i] ?? null, next: nextNodes[i] ?? null});
+ }
+ }
+
+ return pairs.flatMap(({node, next}) =>
+ node !== null && next !== null && isUnchangedNode(node, next)
+ ? []
+ : [
+ {
+ oldNodePath: node?.nodePath ?? null,
+ newNodePath: next?.nodePath ?? null,
+ },
+ ],
+ );
};
export const getUpdatedNodeReference = ({
diff --git a/packages/codemods/src/registration-source-edits.ts b/packages/codemods/src/registration-source-edits.ts
index e63357be23..aea2106c3c 100644
--- a/packages/codemods/src/registration-source-edits.ts
+++ b/packages/codemods/src/registration-source-edits.ts
@@ -86,17 +86,15 @@ export const getFolderNameFromJSXElement = (
return null;
};
-export const getRegistrationInsertionSourceEdit = ({
- input,
+// The element registrations are appended to: the folder, or the JSX returned
+// by the component that registers compositions.
+export const findRegistrationRoot = ({
ast,
- insertion,
folder,
}: {
- input: string;
ast: File;
- insertion: JSXElement;
folder: FolderReference | null;
-}): SourceEdit => {
+}): JSXElement | JSXFragment => {
let root: JSXElement | JSXFragment | null = null;
if (folder) {
const folders: string[] = [];
@@ -223,6 +221,21 @@ export const getRegistrationInsertionSourceEdit = ({
root = roots[0];
}
+ return root;
+};
+
+export const getRegistrationInsertionSourceEdit = ({
+ input,
+ ast,
+ insertion,
+ folder,
+}: {
+ input: string;
+ ast: File;
+ insertion: JSXElement;
+ folder: FolderReference | null;
+}): SourceEdit => {
+ const root = findRegistrationRoot({ast, folder});
return getInsertionRootSourceEdit({
input,
insertion: printInsertedJsx({
diff --git a/packages/codemods/src/rename-composition.ts b/packages/codemods/src/rename-composition.ts
index 2bbd33dc95..05856f0790 100644
--- a/packages/codemods/src/rename-composition.ts
+++ b/packages/codemods/src/rename-composition.ts
@@ -1,12 +1,18 @@
import type {JSXElement} from '@babel/types';
-import type {CodemodProject, CodemodResult} from './codemod-project';
-import {getCodemodResult} from './codemod-project';
+import type {CodemodProject} from './codemod-project';
import {
type CompositionTarget,
requireComposition,
assertNewCompositionId,
} from './composition-editing';
import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';
+import {
+ getNodeEditResult,
+ getUnchangedStructureRemappings,
+ getUpdatedNodeReference,
+ type CodemodNodeResult,
+ type NodeReference,
+} from './node-references';
import {parseAst} from './sequence-props/parse-ast';
import {
applySourceEdits,
@@ -21,10 +27,13 @@ export const renameComposition = <Project extends CodemodProject>({
compositionFile,
compositionId,
newId,
-}: RenameCompositionOptions<Project>): CodemodResult => {
+}: RenameCompositionOptions<Project>): CodemodNodeResult & {
+ updatedNode: NodeReference;
+} => {
const node = requireComposition({project, compositionFile, compositionId});
+ const reference = {filePath: node.filePath, nodePath: node.nodePath};
if (newId === compositionId) {
- return {changes: []};
+ return {changes: [], nodePathRemappings: [], updatedNode: reference};
}
assertNewCompositionId({project, compositionFile, compositionId: newId});
@@ -49,8 +58,22 @@ export const renameComposition = <Project extends CodemodProject>({
getJsxStringAttributeValueSourceEdit({attribute, input, newValue: newId}),
],
});
- return getCodemodResult({
+ const result = getNodeEditResult({
project,
- edits: [{filePath: node.filePath, nextContents: output}],
+ edits: [
+ {
+ filePath: node.filePath,
+ output,
+ nodePathRemappings: getUnchangedStructureRemappings({input, output}),
+ },
+ ],
});
+ return {
+ ...result,
+ updatedNode: getUpdatedNodeReference({
+ project,
+ node: reference,
+ nodePathRemappings: result.nodePathRemappings,
+ }),
+ };
};
diff --git a/packages/codemods/src/rename-folder.ts b/packages/codemods/src/rename-folder.ts
index 7fd67ce7d9..ac58fca861 100644
--- a/packages/codemods/src/rename-folder.ts
+++ b/packages/codemods/src/rename-folder.ts
@@ -1,8 +1,18 @@
import type {AddFolderOptions} from './add-folder';
import type {CodemodProject} from './codemod-project';
-import {getCodemodResult} from './codemod-project';
import {getTreeEntries, requireTreeItem} from './folder-editing';
+import {
+ captureJsxNodePaths,
+ requireCapturedNodePath,
+} from './get-node-path-remappings';
import {findProjectFile} from './internals';
+import {
+ getNodeEditResult,
+ getUnchangedStructureRemappings,
+ getUpdatedNodeReference,
+ type CodemodNodeResult,
+ type NodeReference,
+} from './node-references';
import {parseAst} from './sequence-props/parse-ast';
import {
applySourceEdits,
@@ -17,13 +27,23 @@ export const renameFolder = <Project extends CodemodProject>({
compositionFile,
folder,
newName,
-}: RenameFolderOptions<Project>) => {
+}: RenameFolderOptions<Project>): CodemodNodeResult & {
+ updatedNode: NodeReference;
+} => {
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 located = requireTreeItem(entries, {type: 'folder', ...folder});
+ const reference = {
+ filePath,
+ nodePath: requireCapturedNodePath(
+ captureJsxNodePaths(ast),
+ located.node.openingElement,
+ ),
+ };
if (newName === folder.name) {
- return {changes: []};
+ return {changes: [], nodePathRemappings: [], updatedNode: reference};
}
if (!newName || newName.includes('/')) {
@@ -59,9 +79,25 @@ export const renameFolder = <Project extends CodemodProject>({
}),
],
});
- parseAst(nextContents);
- return getCodemodResult({
+ const result = getNodeEditResult({
project,
- edits: [{filePath, nextContents}],
+ edits: [
+ {
+ filePath,
+ output: nextContents,
+ nodePathRemappings: getUnchangedStructureRemappings({
+ input,
+ output: nextContents,
+ }),
+ },
+ ],
});
+ return {
+ ...result,
+ updatedNode: getUpdatedNodeReference({
+ project,
+ node: reference,
+ nodePathRemappings: result.nodePathRemappings,
+ }),
+ };
};
diff --git a/packages/codemods/src/unwrap-folder.ts b/packages/codemods/src/unwrap-folder.ts
index 77ab180478..3ae11d300c 100644
--- a/packages/codemods/src/unwrap-folder.ts
+++ b/packages/codemods/src/unwrap-folder.ts
@@ -1,9 +1,14 @@
import type {AddFolderOptions} from './add-folder';
import type {CodemodProject} from './codemod-project';
-import {getCodemodResult} from './codemod-project';
import {requireTreeItem, getTreeEntries} from './folder-editing';
import {getUnwrapFolderSourceEdit} from './folder-source-edits';
+import {captureJsxNodePaths} from './get-node-path-remappings';
import {findProjectFile} from './internals';
+import {
+ getNodeEditResult,
+ getSubtreeEditRemappings,
+ type CodemodNodeResult,
+} from './node-references';
import {parseAst} from './sequence-props/parse-ast';
import {applySourceEdits} from './source-edits';
@@ -14,10 +19,11 @@ export const unwrapFolder = <Project extends CodemodProject>({
project,
compositionFile,
folder,
-}: UnwrapFolderOptions<Project>) => {
+}: UnwrapFolderOptions<Project>): CodemodNodeResult => {
const filePath = findProjectFile({project, filePath: compositionFile});
const input = project.files[filePath];
- const located = requireTreeItem(getTreeEntries({ast: parseAst(input)}), {
+ const ast = parseAst(input);
+ const located = requireTreeItem(getTreeEntries({ast}), {
type: 'folder',
...folder,
});
@@ -25,9 +31,16 @@ export const unwrapFolder = <Project extends CodemodProject>({
input,
edits: [getUnwrapFolderSourceEdit({input, located})],
});
- parseAst(nextContents);
- return getCodemodResult({
+ // The folder's children stay in place, only its own element is removed.
+ const nodePathRemappings = getSubtreeEditRemappings({
+ before: captureJsxNodePaths(ast),
+ after: captureJsxNodePaths(parseAst(nextContents)),
+ subtrees: [
+ {before: new Set([located.node.openingElement]), after: new Set()},
+ ],
+ });
+ return getNodeEditResult({
project,
- edits: [{filePath, nextContents}],
+ edits: [{filePath, output: nextContents, nodePathRemappings}],
});
};
diff --git a/packages/codemods/src/update-composition-metadata.ts b/packages/codemods/src/update-composition-metadata.ts
index 57036e3d0c..f4a879d341 100644
--- a/packages/codemods/src/update-composition-metadata.ts
+++ b/packages/codemods/src/update-composition-metadata.ts
@@ -1,6 +1,5 @@
import type {JSXElement} from '@babel/types';
-import type {CodemodProject, CodemodResult} from './codemod-project';
-import {getCodemodResult} from './codemod-project';
+import type {CodemodProject} from './codemod-project';
import {
type CompositionTarget,
type CompositionMetadata,
@@ -8,6 +7,13 @@ import {
validateMetadata,
} from './composition-editing';
import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';
+import {
+ getNodeEditResult,
+ getUnchangedStructureRemappings,
+ getUpdatedNodeReference,
+ type CodemodNodeResult,
+ type NodeReference,
+} from './node-references';
import {recastLocToOffset} from './recast-loc-to-offset';
import {parseAst} from './sequence-props/parse-ast';
import {applySourceEdits, type SourceEdit} from './source-edits';
@@ -24,7 +30,9 @@ export const updateCompositionMetadata = <Project extends CodemodProject>({
compositionFile,
compositionId,
metadata,
-}: UpdateCompositionMetadataOptions<Project>): CodemodResult => {
+}: UpdateCompositionMetadataOptions<Project>): CodemodNodeResult & {
+ updatedNode: NodeReference;
+} => {
const node = requireComposition({project, compositionFile, compositionId});
validateMetadata(metadata);
if (
@@ -34,8 +42,9 @@ export const updateCompositionMetadata = <Project extends CodemodProject>({
throw new Error('Still registrations do not have fps or durationInFrames');
}
+ const reference = {filePath: node.filePath, nodePath: node.nodePath};
if (Object.values(metadata).every((value) => value === undefined)) {
- return {changes: []};
+ return {changes: [], nodePathRemappings: [], updatedNode: reference};
}
const input = project.files[node.filePath];
@@ -142,9 +151,22 @@ export const updateCompositionMetadata = <Project extends CodemodProject>({
}
const output = applySourceEdits({input, edits});
- parseAst(output);
- return getCodemodResult({
+ const result = getNodeEditResult({
project,
- edits: [{filePath: node.filePath, nextContents: output}],
+ edits: [
+ {
+ filePath: node.filePath,
+ output,
+ nodePathRemappings: getUnchangedStructureRemappings({input, output}),
+ },
+ ],
});
+ return {
+ ...result,
+ updatedNode: getUpdatedNodeReference({
+ project,
+ node: reference,
+ nodePathRemappings: result.nodePathRemappings,
+ }),
+ };
};
diff --git a/packages/docs/docs/browser-bundler/create-browser-bundle-runtime.mdx b/packages/docs/docs/browser-bundler/create-browser-bundle-runtime.mdx
index 87e85b6cab..3ddf1758e7 100644
--- a/packages/docs/docs/browser-bundler/create-browser-bundle-runtime.mdx
+++ b/packages/docs/docs/browser-bundler/create-browser-bundle-runtime.mdx
@@ -10,7 +10,7 @@ Load a virtual Remotion project once and apply later edits through Rspack hot up
:::warning
-*Draft API*: This API is not yet stable. We are in the experimental phase of this package and reserve to change it at any time.
+_Draft API_: This API is not yet stable. We are in the experimental phase of this package and reserve to change it at any time.
:::
@@ -87,6 +87,8 @@ Accepts a complete [`BrowserBundle`](/docs/browser-bundler/create-browser-bundle
The first call evaluates the full bundle. Later calls apply Rspack's hot-update assets to the existing module graph and run React Fast Refresh. Compatible component edits preserve React state; changing hook signatures or component types can reset the affected component.
+Immediately before a Fast Refresh update is applied, the runtime dispatches a `remotion-react-refresh-started` event on `window`, and a `remotion-react-refresh-finished` event once React refreshed its roots<AvailableFrom v="4.0.530" inline />. A [`<Canvas>`](/docs/canvas/canvas) in the preview document uses the started event to commit [queued node-path remappings](/docs/canvas/create-canvas-controller#queuesequencenodepathremappings) in the same task as the refreshed tree.
+
Calls are serialized. Apply every successfully compiled bundle in order, even when newer edits are pending. Skipping compiled updates breaks the hot-update chain and rejects the promise.
Compilation errors do not produce a bundle to apply. Keep the previous preview visible while showing diagnostics, then apply the next successful build.
diff --git a/packages/docs/docs/canvas/create-canvas-controller.mdx b/packages/docs/docs/canvas/create-canvas-controller.mdx
index 8d89069ae8..0d542f5f5d 100644
--- a/packages/docs/docs/canvas/create-canvas-controller.mdx
+++ b/packages/docs/docs/canvas/create-canvas-controller.mdx
@@ -68,6 +68,39 @@ Afterwards, the affected tracks carry a `nodePathInfo` with that `sequenceSubscr
Passing an unchanged mapping is a no-op, so the function may be called from a `timeline` subscription. Call it again after the source changed. [`getCanvasSequenceSourceLocation()`](/docs/canvas/get-canvas-sequence-source-location) shows how to derive the mapping from the compiled source locations.
+### queueSequenceNodePathRemappings()<AvailableFrom v="4.0.530" />
+
+`queueSequenceNodePathRemappings(remappings)` hands the Canvas the `nodePathRemappings` that a mutation of [`@remotion/codemods`](/docs/codemods#node-references) returned. `remappings` is an array of `{filePath, oldNodePath, newNodePath}` entries, where `filePath` matches the `absolutePath` of the registered node paths. A `null` old path is an insertion, a `null` new path a removal.
+
+Queue the remappings when you apply the edit to your project. The Canvas commits them when the next Fast Refresh update starts, immediately before React commits the refreshed tree, so the registered node paths and the [selection](#selection) never pair the new elements with the old paths. Studio's bundler, Browser Studio and [`createBrowserBundleRuntime()`](/docs/browser-bundler/create-browser-bundle-runtime#applybundle) dispatch that event. Call `queueSequenceNodePathRemappings()` once per edit; the remappings of one edit are not chained with each other, only with those of earlier edits.
+
+```tsx twoslash title="Applying an edit"
+// @moduleResolution: bundler
+import type {CanvasController} from '@remotion/canvas';
+import {
+ applyCodemodChanges,
+ deleteNodes,
+ type CodemodProject,
+ type NodeReference,
+} from '@remotion/codemods';
+declare const controller: CanvasController;
+declare const project: CodemodProject;
+declare const nodes: NodeReference[];
+declare const compile: (project: CodemodProject) => void;
+// ---cut---
+export const removeNodes = async () => {
+ const result = await deleteNodes({project, nodes});
+ controller.queueSequenceNodePathRemappings(result.nodePathRemappings);
+ compile(applyCodemodChanges(project, result.changes));
+};
+```
+
+Selected items whose node was removed leave the selection, other selected items follow their node to its new path. Override IDs belong to mounted instances, which Fast Refresh keeps at paths that still exist after the edit; a registered node path therefore only follows its node when its old path disappeared. Hover is cleared. Registering the resolved mapping again with [`setSequenceNodePaths()`](#setsequencenodepaths) after the compilation confirms the result and covers edits that produced no remappings.
+
+### remapSequenceNodePaths()<AvailableFrom v="4.0.530" />
+
+`remapSequenceNodePaths(remappings)` applies the remappings of one edit right away instead of queueing them. Use it when you swap the mounted tree yourself, in the same task as the swap.
+
### overrides<AvailableFrom v="4.0.529" />
Preview prop values on mounted sequences without changing the source. Overrides are applied to sequences that have a `nodePathInfo`, so register node paths first. They are kept while the composition stays mounted and are not persisted; write the final value to the source, for example with [`updateNodeProps()`](/docs/codemods/update-node-props), and clear the override once the update has been applied.
diff --git a/packages/docs/docs/codemods/add-canvas-capture-composition.mdx b/packages/docs/docs/codemods/add-canvas-capture-composition.mdx
index 45a8c29c40..689a1def2e 100644
--- a/packages/docs/docs/codemods/add-canvas-capture-composition.mdx
+++ b/packages/docs/docs/codemods/add-canvas-capture-composition.mdx
@@ -115,6 +115,14 @@ The generated component uses `@remotion/media` and `@remotion/mac-cursors`. Thes
Two `{filePath, previousContents, nextContents}` entries: the modified registration file and the created component file. The new component's `previousContents` is `null`. Save both changes to persist the operation; the video asset is not created or copied.
+### nodePathRemappings<AvailableFrom v="4.0.530" />
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
+### insertedNode<AvailableFrom v="4.0.530" />
+
+The reference of the inserted registration in the new project.
+
## Errors
Throws if the component file already exists, the registration target cannot be resolved, the capture has no usable cursor movements, or an option is invalid. Failed operations leave the input project unchanged.
diff --git a/packages/docs/docs/codemods/add-composition.mdx b/packages/docs/docs/codemods/add-composition.mdx
index 1dab5b0b20..58febc380d 100644
--- a/packages/docs/docs/codemods/add-composition.mdx
+++ b/packages/docs/docs/codemods/add-composition.mdx
@@ -92,6 +92,14 @@ Returns an object with the following properties.
An array containing the registration file's `{filePath, previousContents, nextContents}` change. No component-file change is returned.
+### nodePathRemappings<AvailableFrom v="4.0.530" />
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
+### insertedNode<AvailableFrom v="4.0.530" />
+
+The reference of the inserted registration in the new project.
+
## Errors
Throws when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.
diff --git a/packages/docs/docs/codemods/add-folder.mdx b/packages/docs/docs/codemods/add-folder.mdx
index 9d7ea9e768..98160ba94d 100644
--- a/packages/docs/docs/codemods/add-folder.mdx
+++ b/packages/docs/docs/codemods/add-folder.mdx
@@ -60,6 +60,14 @@ Returns an object with the following properties.
An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+### nodePathRemappings<AvailableFrom v="4.0.530" />
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
+### insertedNode<AvailableFrom v="4.0.530" />
+
+The reference of the inserted `<Folder>` element in the new project.
+
## Errors
Throws when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.
diff --git a/packages/docs/docs/codemods/delete-composition.mdx b/packages/docs/docs/codemods/delete-composition.mdx
index f898f93d7a..9a01f2d6c0 100644
--- a/packages/docs/docs/codemods/delete-composition.mdx
+++ b/packages/docs/docs/codemods/delete-composition.mdx
@@ -52,6 +52,10 @@ Returns an object with the following properties.
An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+### nodePathRemappings<AvailableFrom v="4.0.530" />
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
## Errors
Throws when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.
diff --git a/packages/docs/docs/codemods/duplicate-composition.mdx b/packages/docs/docs/codemods/duplicate-composition.mdx
index be56257fba..2b437453e4 100644
--- a/packages/docs/docs/codemods/duplicate-composition.mdx
+++ b/packages/docs/docs/codemods/duplicate-composition.mdx
@@ -68,6 +68,14 @@ Returns an object with the following properties.
An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+### nodePathRemappings<AvailableFrom v="4.0.530" />
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
+### insertedNode<AvailableFrom v="4.0.530" />
+
+The reference of the inserted copy in the new project.
+
## Errors
Throws when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.
diff --git a/packages/docs/docs/codemods/index.mdx b/packages/docs/docs/codemods/index.mdx
index bba52c63db..48a5f6c04b 100644
--- a/packages/docs/docs/codemods/index.mdx
+++ b/packages/docs/docs/codemods/index.mdx
@@ -123,9 +123,11 @@ A reference identifies source, not a particular rendered instance. Editing a com
### Keeping references after edits
-Node mutations return `nodePathRemappings`. Each entry contains `filePath`, `oldNodePath`, and `newNodePath`. Apply a mapping once to references from the input project, matching both the file and old path. A `null` old path means insertion; a `null` new path means removal. An omitted reference keeps its path.
+Node and registration mutations return `nodePathRemappings`. Each entry contains `filePath`, `oldNodePath`, and `newNodePath`. Apply a mapping once to references from the input project, matching both the file and old path. A `null` old path means insertion; a `null` new path means removal. An omitted reference keeps its path.
-Use `insertedNode`, `insertedNodes`, or `updatedNode` when returned instead of trying to reconstruct a path. Adding hooks, duplicating elements, or changing wrappers can move other nodes as well. After manual source changes or composition-tree edits, discover nodes again.
+Use `insertedNode`, `insertedNodes`, or `updatedNode` when returned instead of trying to reconstruct a path. Adding hooks, duplicating elements, changing wrappers, or moving registrations can move other nodes as well. After manual source changes, discover nodes again.
+
+Editors that keep mounted sequences attached to their source nodes, such as [`<Canvas>`](/docs/canvas/canvas), accept these mappings through [`queueSequenceNodePathRemappings()`](/docs/canvas/create-canvas-controller#queuesequencenodepathremappings).
## Effect references<AvailableFrom v="4.0.528" />
@@ -155,7 +157,7 @@ The next source, or `null` if the file was deleted.
### nodePathRemappings<AvailableFrom v="4.0.528" />
-Node, effect, and keyframe mutations return these mappings in addition to the shared result. See [node references](#node-references).
+Node, effect, keyframe, and registration mutations return these mappings in addition to the shared result. Registration mutations return them since <AvailableFrom v="4.0.530" inline />. See [node references](#node-references).
## Applying changes
diff --git a/packages/docs/docs/codemods/move-composition.mdx b/packages/docs/docs/codemods/move-composition.mdx
index 2f863031c6..c8fa684ec4 100644
--- a/packages/docs/docs/codemods/move-composition.mdx
+++ b/packages/docs/docs/codemods/move-composition.mdx
@@ -57,6 +57,14 @@ Returns an object with the following properties.
An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+### nodePathRemappings
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
+### updatedNode<AvailableFrom v="4.0.530" />
+
+The moved registration's node reference in the new project.
+
## Errors
Throws when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.
diff --git a/packages/docs/docs/codemods/move-folder.mdx b/packages/docs/docs/codemods/move-folder.mdx
index 14ac0d5488..b4427f5c0c 100644
--- a/packages/docs/docs/codemods/move-folder.mdx
+++ b/packages/docs/docs/codemods/move-folder.mdx
@@ -65,6 +65,14 @@ Returns an object with the following properties.
An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+### nodePathRemappings
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
+### updatedNode<AvailableFrom v="4.0.530" />
+
+The moved `<Folder>` element's node reference in the new project.
+
## Errors
Throws when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.
diff --git a/packages/docs/docs/codemods/rename-composition.mdx b/packages/docs/docs/codemods/rename-composition.mdx
index dddee2556d..26c9cd920f 100644
--- a/packages/docs/docs/codemods/rename-composition.mdx
+++ b/packages/docs/docs/codemods/rename-composition.mdx
@@ -57,6 +57,14 @@ Returns an object with the following properties.
An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+### nodePathRemappings<AvailableFrom v="4.0.530" />
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
+### updatedNode<AvailableFrom v="4.0.530" />
+
+The renamed registration's node reference in the new project.
+
## Errors
Throws when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.
diff --git a/packages/docs/docs/codemods/rename-folder.mdx b/packages/docs/docs/codemods/rename-folder.mdx
index 3f400d682e..90974e9d2e 100644
--- a/packages/docs/docs/codemods/rename-folder.mdx
+++ b/packages/docs/docs/codemods/rename-folder.mdx
@@ -65,6 +65,14 @@ Returns an object with the following properties.
An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+### nodePathRemappings<AvailableFrom v="4.0.530" />
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
+### updatedNode<AvailableFrom v="4.0.530" />
+
+The renamed `<Folder>` element's node reference in the new project.
+
## Errors
Throws when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.
diff --git a/packages/docs/docs/codemods/unwrap-folder.mdx b/packages/docs/docs/codemods/unwrap-folder.mdx
index c9cb8a4492..97582d36ed 100644
--- a/packages/docs/docs/codemods/unwrap-folder.mdx
+++ b/packages/docs/docs/codemods/unwrap-folder.mdx
@@ -60,6 +60,10 @@ Returns an object with the following properties.
An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+### nodePathRemappings<AvailableFrom v="4.0.530" />
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
## Example transformation
```tsx title="Before"
diff --git a/packages/docs/docs/codemods/update-composition-metadata.mdx b/packages/docs/docs/codemods/update-composition-metadata.mdx
index a577c05da6..fc1fddb2a4 100644
--- a/packages/docs/docs/codemods/update-composition-metadata.mdx
+++ b/packages/docs/docs/codemods/update-composition-metadata.mdx
@@ -75,6 +75,14 @@ Returns an object with the following properties.
An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+### nodePathRemappings<AvailableFrom v="4.0.530" />
+
+An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).
+
+### updatedNode<AvailableFrom v="4.0.530" />
+
+The composition registration's node reference in the new project.
+
## Errors
Throws when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.
diff --git a/packages/template-vibe-code/src/editor/Editor.tsx b/packages/template-vibe-code/src/editor/Editor.tsx
index e62fee4349..7dac0c9528 100644
--- a/packages/template-vibe-code/src/editor/Editor.tsx
+++ b/packages/template-vibe-code/src/editor/Editor.tsx
@@ -25,7 +25,7 @@ import { useEditorShortcuts } from "./hooks/use-editor-shortcuts";
import { useLayers } from "./hooks/use-layers";
import { usePlaybackStore } from "./hooks/use-playback";
import { usePreviewHost } from "./hooks/use-preview-host";
-import { findCompositionFile, getCompositions } from "./model/compositions";
+import { findCompositionFile, getRegistrations } from "./model/compositions";
import { getKeyframedProps } from "./model/keyframes";
import { getSequencePropStatuses } from "./model/layers";
import { toCodemodProject, type ProjectFiles } from "./model/project";
@@ -46,8 +46,7 @@ export const Editor: React.FC<{
const [state, dispatch] = useReducer(editorReducer, initialFiles, (files) => {
const project = toCodemodProject(files);
const compositionFile = findCompositionFile(project);
- const compositions = getCompositions(project, compositionFile);
- const first = compositions[0];
+ const first = getRegistrations(project, compositionFile).compositions[0];
let activeFile = compositionFile;
if (first && compositionFile) {
try {
@@ -77,10 +76,11 @@ export const Editor: React.FC<{
() => findCompositionFile(project),
[project],
);
- const compositions = useMemo(
- () => getCompositions(project, compositionFile),
+ const registrations = useMemo(
+ () => getRegistrations(project, compositionFile),
[compositionFile, project],
);
+ const { compositions } = registrations;
const activeComposition = useMemo(
() =>
compositions.find(
@@ -348,6 +348,7 @@ export const Editor: React.FC<{
layers,
keyframedProps,
project,
+ registrations,
compositions,
compositionFile,
mainFile,
diff --git a/packages/template-vibe-code/src/editor/components/SidebarPanel.tsx b/packages/template-vibe-code/src/editor/components/SidebarPanel.tsx
index f5c40872e2..62818464ad 100644
--- a/packages/template-vibe-code/src/editor/components/SidebarPanel.tsx
+++ b/packages/template-vibe-code/src/editor/components/SidebarPanel.tsx
@@ -1,9 +1,17 @@
"use client";
+import type {
+ CompositionDestination,
+ CompositionTreeItem,
+} from "@remotion/codemods";
import {
+ ChevronDownIcon,
+ ChevronRightIcon,
FileCode2Icon,
FileIcon,
FilmIcon,
+ FolderIcon,
+ FolderPlusIcon,
ImageIcon,
PlusIcon,
} from "lucide-react";
@@ -13,13 +21,22 @@ import {
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
ContextMenuTrigger,
} from "@/components/ui/context-menu";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { PROJECT_DIR } from "@/lib/project-paths";
import { cn } from "@/lib/utils";
-import type { CompositionInfo } from "../model/compositions";
+import {
+ getFolderPath,
+ toCompositionTreeItem,
+ toFolderReference,
+ type FolderInfo,
+ type RegistrationTreeItem,
+} from "../model/compositions";
import { getFileName, sortFilePaths } from "../model/project";
import { useEditor } from "../state/editor-context";
import { ToolbarButton } from "./TopBar";
@@ -27,14 +44,16 @@ import { ToolbarButton } from "./TopBar";
const InlineInput: React.FC<{
readonly placeholder: string;
readonly initialValue?: string;
+ readonly indent?: number;
readonly onSubmit: (value: string) => void;
readonly onCancel: () => void;
-}> = ({ placeholder, initialValue = "", onSubmit, onCancel }) => {
+}> = ({ placeholder, initialValue = "", indent = 0, onSubmit, onCancel }) => {
const [value, setValue] = useState(initialValue);
return (
<form
- className="px-2 py-1"
+ className="py-1 pr-2"
+ style={{ paddingLeft: 8 + indent }}
onSubmit={(event) => {
event.preventDefault();
if (value.trim()) {
@@ -61,18 +80,235 @@ const InlineInput: React.FC<{
);
};
+/** A registration being created, inside the folder `parentName` or at the root. */
+type CreatingRegistration = {
+ type: "composition" | "folder";
+ parentName: string | null;
+};
+
+type Creating = CreatingRegistration | { type: "file" };
+
+type DropPosition = "before" | "after" | "inside";
+
+type DropTarget = { key: string; position: DropPosition };
+
+const getItemKey = (item: RegistrationTreeItem) =>
+ item.type === "composition"
+ ? `composition:${item.composition.id}`
+ : `folder:${getFolderPath(item.folder)}`;
+
+const getItemParentName = (item: RegistrationTreeItem) =>
+ item.type === "composition"
+ ? item.composition.folderPath
+ : item.folder.parentName;
+
+/** Whether `folderPath` is the folder `candidate` or one of its descendants. */
+const isInsideFolder = (
+ folderPath: string | null,
+ candidate: RegistrationTreeItem,
+) =>
+ candidate.type === "folder" &&
+ folderPath !== null &&
+ (folderPath === getFolderPath(candidate.folder) ||
+ folderPath.startsWith(`${getFolderPath(candidate.folder)}/`));
+
+const getDropDestination = (
+ target: RegistrationTreeItem,
+ position: DropPosition,
+): CompositionDestination => {
+ if (position === "inside" && target.type === "folder") {
+ return {
+ type: "folder",
+ folder: {
+ name: target.folder.name,
+ parentName: target.folder.parentName,
+ },
+ };
+ }
+
+ return {
+ type: position === "before" ? "before" : "after",
+ target: toCompositionTreeItem(target),
+ };
+};
+
+type TreeContext = {
+ readonly dragging: RegistrationTreeItem | null;
+ readonly dropTarget: DropTarget | null;
+ readonly collapsed: ReadonlySet<string>;
+ readonly creating: CreatingRegistration | null;
+ readonly setDragging: (item: RegistrationTreeItem | null) => void;
+ readonly setDropTarget: (target: DropTarget | null) => void;
+ readonly toggleCollapsed: (folderPath: string) => void;
+ readonly setCreating: (creating: CreatingRegistration | null) => void;
+ readonly move: (
+ item: CompositionTreeItem,
+ destination: CompositionDestination,
+ ) => void;
+};
+
+const MoveToMenu: React.FC<{
+ readonly item: RegistrationTreeItem;
+ readonly folders: FolderInfo[];
+ readonly onMove: (destination: CompositionDestination) => void;
+}> = ({ item, folders, onMove }) => {
+ const parentName = getItemParentName(item);
+ const destinations = folders.filter(
+ (folder) =>
+ getFolderPath(folder) !== parentName &&
+ !isInsideFolder(getFolderPath(folder), item),
+ );
+
+ return (
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>Move to</ContextMenuSubTrigger>
+ <ContextMenuSubContent>
+ <ContextMenuItem
+ disabled={parentName === null}
+ onSelect={() => onMove({ type: "root" })}
+ >
+ Root
+ </ContextMenuItem>
+ {destinations.length > 0 ? <ContextMenuSeparator /> : null}
+ {destinations.map((folder) => (
+ <ContextMenuItem
+ key={getFolderPath(folder)}
+ onSelect={() =>
+ onMove({
+ type: "folder",
+ folder: { name: folder.name, parentName: folder.parentName },
+ })
+ }
+ >
+ <FolderIcon className="opacity-70" />
+ {getFolderPath(folder)}
+ </ContextMenuItem>
+ ))}
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+ );
+};
+
+/**
+ * Drag handlers of a tree row. Dropping on the upper or lower edge inserts
+ * beside the row, dropping on the middle of a folder moves into it. Rows stop
+ * the events so the root drop zone only reacts to the space below them.
+ */
+const getRowDragProps = (item: RegistrationTreeItem, tree: TreeContext) => {
+ const key = getItemKey(item);
+ const dropPosition =
+ tree.dropTarget?.key === key ? tree.dropTarget.position : null;
+
+ const getPosition = (event: React.DragEvent): DropPosition => {
+ const rect = event.currentTarget.getBoundingClientRect();
+ const ratio = (event.clientY - rect.top) / rect.height;
+ if (item.type === "folder") {
+ return ratio < 0.25 ? "before" : ratio > 0.75 ? "after" : "inside";
+ }
+
+ return ratio < 0.5 ? "before" : "after";
+ };
+
+ // An item cannot be dropped on itself or inside its own folder subtree.
+ const canDrop = () =>
+ tree.dragging !== null &&
+ getItemKey(tree.dragging) !== key &&
+ !isInsideFolder(
+ item.type === "folder"
+ ? getFolderPath(item.folder)
+ : item.composition.folderPath,
+ tree.dragging,
+ );
+
+ return {
+ dropPosition,
+ props: {
+ draggable: true,
+ onDragStart: (event: React.DragEvent) => {
+ event.stopPropagation();
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData(
+ "text/plain",
+ item.type === "composition" ? item.composition.id : item.folder.name,
+ );
+ tree.setDragging(item);
+ },
+ onDragEnd: () => {
+ tree.setDragging(null);
+ tree.setDropTarget(null);
+ },
+ onDragOver: (event: React.DragEvent) => {
+ event.stopPropagation();
+ if (!canDrop()) {
+ return;
+ }
+
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ const position = getPosition(event);
+ if (dropPosition !== position) {
+ tree.setDropTarget({ key, position });
+ }
+ },
+ onDragLeave: (event: React.DragEvent) => {
+ if (
+ dropPosition !== null &&
+ !event.currentTarget.contains(event.relatedTarget as Node | null)
+ ) {
+ tree.setDropTarget(null);
+ }
+ },
+ onDrop: (event: React.DragEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ const { dragging } = tree;
+ tree.setDragging(null);
+ tree.setDropTarget(null);
+ if (dragging && canDrop()) {
+ tree.move(
+ toCompositionTreeItem(dragging),
+ getDropDestination(item, getPosition(event)),
+ );
+ }
+ },
+ },
+ };
+};
+
+const rowClassName =
+ "relative flex w-full items-center gap-2 py-1.5 pr-3 text-left text-xs outline-none";
+
+const DropIndicator: React.FC<{ readonly position: DropPosition | null }> = ({
+ position,
+}) =>
+ position === "before" || position === "after" ? (
+ <span
+ aria-hidden
+ className={cn(
+ "bg-primary pointer-events-none absolute inset-x-2 h-px",
+ position === "before" ? "top-0" : "bottom-0",
+ )}
+ />
+ ) : null;
+
const CompositionRow: React.FC<{
- readonly composition: CompositionInfo;
- readonly active: boolean;
-}> = ({ composition, active }) => {
- const { actions, compositions } = useEditor();
+ readonly item: Extract<RegistrationTreeItem, { type: "composition" }>;
+ readonly level: number;
+ readonly tree: TreeContext;
+}> = ({ item, level, tree }) => {
+ const { actions, compositions, registrations, activeComposition } =
+ useEditor();
const [renaming, setRenaming] = useState(false);
+ const { composition } = item;
+ const { dropPosition, props: dragProps } = getRowDragProps(item, tree);
+ const active = activeComposition?.id === composition.id;
if (renaming) {
return (
<InlineInput
placeholder="Composition ID"
initialValue={composition.id}
+ indent={level * 14}
onSubmit={(newId) => {
setRenaming(false);
void actions.renameComposition(composition.id, newId);
@@ -97,13 +333,16 @@ const CompositionRow: React.FC<{
aria-pressed={active}
onClick={() => actions.selectComposition(composition.id)}
onDoubleClick={() => setRenaming(true)}
+ style={{ paddingLeft: 12 + level * 14 }}
className={cn(
- "flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs outline-none",
+ rowClassName,
active
? "bg-selection-dim/60 text-foreground"
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
)}
+ {...dragProps}
>
+ <DropIndicator position={dropPosition} />
{composition.tagName === "Still" ? (
<ImageIcon className="size-3.5 shrink-0 opacity-70" />
) : (
@@ -126,6 +365,13 @@ const CompositionRow: React.FC<{
>
Duplicate
</ContextMenuItem>
+ <MoveToMenu
+ item={item}
+ folders={registrations.folders}
+ onMove={(destination) =>
+ tree.move(toCompositionTreeItem(item), destination)
+ }
+ />
<ContextMenuItem
onSelect={() =>
actions.reveal(composition.filePath, composition.line, null)
@@ -146,6 +392,262 @@ const CompositionRow: React.FC<{
);
};
+const FolderRow: React.FC<{
+ readonly item: Extract<RegistrationTreeItem, { type: "folder" }>;
+ readonly level: number;
+ readonly tree: TreeContext;
+}> = ({ item, level, tree }) => {
+ const { actions, registrations } = useEditor();
+ const [renaming, setRenaming] = useState(false);
+ const { folder } = item;
+ const folderPath = getFolderPath(folder);
+ const expanded = !tree.collapsed.has(folderPath);
+ const { dropPosition, props: dragProps } = getRowDragProps(item, tree);
+
+ const row = renaming ? (
+ <InlineInput
+ placeholder="Folder name"
+ initialValue={folder.name}
+ indent={level * 14}
+ onSubmit={(newName) => {
+ setRenaming(false);
+ void actions.renameFolder(
+ { name: folder.name, parentName: folder.parentName },
+ newName,
+ );
+ }}
+ onCancel={() => setRenaming(false)}
+ />
+ ) : (
+ <ContextMenu>
+ <ContextMenuTrigger asChild>
+ <button
+ type="button"
+ aria-expanded={expanded}
+ onClick={() => tree.toggleCollapsed(folderPath)}
+ onDoubleClick={() => setRenaming(true)}
+ style={{ paddingLeft: 12 + level * 14 }}
+ className={cn(
+ rowClassName,
+ "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
+ dropPosition === "inside" && "bg-selection-dim/40 text-foreground",
+ )}
+ {...dragProps}
+ >
+ <DropIndicator position={dropPosition} />
+ {expanded ? (
+ <ChevronDownIcon className="-ml-1 size-3 shrink-0 opacity-60" />
+ ) : (
+ <ChevronRightIcon className="-ml-1 size-3 shrink-0 opacity-60" />
+ )}
+ <FolderIcon className="size-3.5 shrink-0 opacity-70" />
+ <span className="min-w-0 flex-1 truncate font-medium">
+ {folder.name}
+ </span>
+ </button>
+ </ContextMenuTrigger>
+ <ContextMenuContent>
+ <ContextMenuItem
+ onSelect={() =>
+ tree.setCreating({ type: "composition", parentName: folderPath })
+ }
+ >
+ New composition
+ </ContextMenuItem>
+ <ContextMenuItem
+ onSelect={() =>
+ tree.setCreating({ type: "folder", parentName: folderPath })
+ }
+ >
+ New folder
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem onSelect={() => setRenaming(true)}>
+ Rename
+ </ContextMenuItem>
+ <MoveToMenu
+ item={item}
+ folders={registrations.folders}
+ onMove={(destination) =>
+ tree.move(toCompositionTreeItem(item), destination)
+ }
+ />
+ <ContextMenuItem
+ onSelect={() => actions.reveal(folder.filePath, folder.line, null)}
+ >
+ Reveal in code
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ variant="destructive"
+ onSelect={() =>
+ void actions.deleteFolder({
+ name: folder.name,
+ parentName: folder.parentName,
+ })
+ }
+ >
+ Delete folder, keep contents
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
+ );
+
+ return (
+ <>
+ {row}
+ {expanded ? (
+ <TreeItems
+ items={item.children}
+ parentName={folderPath}
+ level={level + 1}
+ tree={tree}
+ />
+ ) : null}
+ </>
+ );
+};
+
+const TreeItems: React.FC<{
+ readonly items: RegistrationTreeItem[];
+ /** The folder the items are in, `null` at the root. */
+ readonly parentName: string | null;
+ readonly level: number;
+ readonly tree: TreeContext;
+}> = ({ items, parentName, level, tree }) => {
+ const { actions } = useEditor();
+ const { creating } = tree;
+
+ return (
+ <>
+ {items.map((item) =>
+ item.type === "composition" ? (
+ <CompositionRow
+ key={getItemKey(item)}
+ item={item}
+ level={level}
+ tree={tree}
+ />
+ ) : (
+ <FolderRow
+ key={getItemKey(item)}
+ item={item}
+ level={level}
+ tree={tree}
+ />
+ ),
+ )}
+ {creating !== null && creating.parentName === parentName ? (
+ <InlineInput
+ placeholder={
+ creating.type === "composition"
+ ? "New composition ID"
+ : "New folder name"
+ }
+ indent={level * 14}
+ onSubmit={(value) => {
+ tree.setCreating(null);
+ if (creating.type === "composition") {
+ void actions.addComposition(
+ value,
+ parentName === null ? null : toFolderReference(parentName),
+ );
+ } else {
+ void actions.addFolder(value, parentName);
+ }
+ }}
+ onCancel={() => tree.setCreating(null)}
+ />
+ ) : null}
+ </>
+ );
+};
+
+const RegistrationTree: React.FC<{
+ readonly creating: CreatingRegistration | null;
+ readonly setCreating: (creating: CreatingRegistration | null) => void;
+}> = ({ creating, setCreating }) => {
+ const { actions, registrations } = useEditor();
+ const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
+ const [dragging, setDragging] = useState<RegistrationTreeItem | null>(null);
+ const [dropTarget, setDropTarget] = useState<DropTarget | null>(null);
+ const tree: TreeContext = {
+ dragging,
+ dropTarget,
+ collapsed,
+ creating,
+ setDragging,
+ setDropTarget,
+ setCreating,
+ toggleCollapsed: (folderPath) =>
+ setCollapsed((previous) => {
+ const next = new Set(previous);
+ if (!next.delete(folderPath)) {
+ next.add(folderPath);
+ }
+
+ return next;
+ }),
+ move: (item, destination) =>
+ void actions.moveRegistration(item, destination),
+ };
+ const rootDrop = dropTarget?.key === "root";
+
+ if (registrations.tree.length === 0 && creating === null) {
+ return (
+ <p className="text-muted-foreground px-3 py-2 text-xs">
+ No compositions found. Add a{" "}
+ <code className="font-mono">&lt;Composition&gt;</code> to your Root
+ file.
+ </p>
+ );
+ }
+
+ return (
+ // The area below the rows accepts drops to move an item to the root.
+ <div
+ className={cn(
+ "flex min-h-full flex-col pb-6",
+ rootDrop && "bg-selection-dim/20",
+ )}
+ onDragOver={(event) => {
+ if (dragging === null || getItemParentName(dragging) === null) {
+ return;
+ }
+
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ if (!rootDrop) {
+ setDropTarget({ key: "root", position: "inside" });
+ }
+ }}
+ onDragLeave={(event) => {
+ if (
+ rootDrop &&
+ !event.currentTarget.contains(event.relatedTarget as Node | null)
+ ) {
+ setDropTarget(null);
+ }
+ }}
+ onDrop={(event) => {
+ event.preventDefault();
+ setDropTarget(null);
+ setDragging(null);
+ if (dragging !== null && getItemParentName(dragging) !== null) {
+ tree.move(toCompositionTreeItem(dragging), { type: "root" });
+ }
+ }}
+ >
+ <TreeItems
+ items={registrations.tree}
+ parentName={null}
+ level={0}
+ tree={tree}
+ />
+ </div>
+ );
+};
+
const FileRow: React.FC<{
readonly filePath: string;
readonly active: boolean;
@@ -221,9 +723,9 @@ const FileRow: React.FC<{
};
export const SidebarPanel: React.FC = () => {
- const { state, dispatch, actions, compositions, activeComposition } =
- useEditor();
- const [creating, setCreating] = useState<"composition" | "file" | null>(null);
+ const { state, dispatch, actions } = useEditor();
+ const [creating, setCreating] = useState<Creating | null>(null);
+ const compositionsTab = state.layout.sidebarTab === "compositions";
return (
<Tabs
@@ -240,18 +742,24 @@ export const SidebarPanel: React.FC = () => {
<TabsTrigger value="compositions">Compositions</TabsTrigger>
<TabsTrigger value="files">Files</TabsTrigger>
<div className="flex-1" />
+ {compositionsTab ? (
+ <ToolbarButton
+ size="icon-xs"
+ label="New folder"
+ onClick={() => setCreating({ type: "folder", parentName: null })}
+ className="mb-1"
+ >
+ <FolderPlusIcon />
+ </ToolbarButton>
+ ) : null}
<ToolbarButton
size="icon-xs"
- label={
- state.layout.sidebarTab === "compositions"
- ? "New composition"
- : "New file"
- }
+ label={compositionsTab ? "New composition" : "New file"}
onClick={() =>
setCreating(
- state.layout.sidebarTab === "compositions"
- ? "composition"
- : "file",
+ compositionsTab
+ ? { type: "composition", parentName: null }
+ : { type: "file" },
)
}
className="mb-1"
@@ -263,34 +771,15 @@ export const SidebarPanel: React.FC = () => {
value="compositions"
className="min-h-0 overflow-y-auto py-1"
>
- {creating === "composition" ? (
- <InlineInput
- placeholder="New composition ID"
- onSubmit={(id) => {
- setCreating(null);
- void actions.addComposition(id);
- }}
- onCancel={() => setCreating(null)}
- />
- ) : null}
- {compositions.length === 0 ? (
- <p className="text-muted-foreground px-3 py-2 text-xs">
- No compositions found. Add a{" "}
- <code className="font-mono">&lt;Composition&gt;</code> to your Root
- file.
- </p>
- ) : (
- compositions.map((composition) => (
- <CompositionRow
- key={composition.id}
- composition={composition}
- active={activeComposition?.id === composition.id}
- />
- ))
- )}
+ <RegistrationTree
+ creating={
+ creating !== null && creating.type !== "file" ? creating : null
+ }
+ setCreating={setCreating}
+ />
</TabsContent>
<TabsContent value="files" className="min-h-0 overflow-y-auto py-1">
- {creating === "file" ? (
+ {creating?.type === "file" ? (
<InlineInput
placeholder={`${PROJECT_DIR}/NewComponent.tsx`}
initialValue={`${PROJECT_DIR}/`}
diff --git a/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts b/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts
index b1dd87f9b6..259426bc0c 100644
--- a/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts
+++ b/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts
@@ -13,28 +13,38 @@ import {
import {
addComposition,
addElement,
+ addFolder,
applyCodemodChanges,
createElement,
deleteComposition,
deleteNodes as deleteNodesCodemod,
duplicateComposition,
duplicateNodes as duplicateNodesCodemod,
+ moveComposition,
+ moveFolder,
renameComposition,
+ renameFolder,
reorderNode as reorderNodeCodemod,
resolveCompositionComponent,
setCompositionDefaultProps,
splitSequences,
+ unwrapFolder,
updateCompositionMetadata,
updateMultipleNodeProps,
updateNodeKeyframes,
updateNodeProps,
wrapNode,
type CodemodElement,
+ type CodemodNodeResult,
type CodemodProject,
type CodemodResult,
type CodemodValue,
+ type CompositionDestination,
type CompositionMetadata,
+ type CompositionTreeItem,
+ type FolderReference,
type NodeKeyframeUpdate,
+ type NodePathRemapping,
type NodePropChange,
type NodeReference,
type SequencePropUpdate,
@@ -61,7 +71,12 @@ import {
type KeyframedProp,
type KeyframeSelectionItem,
} from "../model/keyframes";
-import { areSiblingNodes, getNodeReference, type Layer } from "../model/layers";
+import {
+ areSiblingNodes,
+ chainNodePathRemappings,
+ getNodeReference,
+ type Layer,
+} from "../model/layers";
import { filesAreEqual, getFileName, toCodemodProject } from "../model/project";
import { resolveProjectPathInput } from "@/lib/project-paths";
import type { PlaybackStore } from "./use-playback";
@@ -119,13 +134,22 @@ export const useEditorActions = ({
const getProject = () => toCodemodProject(ref.current.state.files);
+ /**
+ * Applies a codemod as one undoable edit. Node-path remappings of the
+ * result are handed to the Canvas, which applies them together with the
+ * Fast Refresh update of the compiled source, so the selection and the
+ * layer list keep pointing at the same elements.
+ */
const applyCodemod = async (
- run: (project: CodemodProject) => Promise<CodemodResult> | CodemodResult,
+ run: (
+ project: CodemodProject,
+ ) =>
+ | Promise<CodemodResult | CodemodNodeResult>
+ | CodemodResult
+ | CodemodNodeResult,
{
- clearSelection = false,
onApplied,
}: {
- clearSelection?: boolean;
onApplied?: (changed: boolean) => void;
} = {},
) => {
@@ -145,8 +169,10 @@ export const useEditorActions = ({
const changed = !filesAreEqual(project.files, files);
dispatch({ type: "set-files", files, coalesceKey: null });
- if (clearSelection) {
- ref.current.host?.controller.selection.clear();
+ if (changed && "nodePathRemappings" in result) {
+ ref.current.host?.controller.queueSequenceNodePathRemappings(
+ result.nodePathRemappings,
+ );
}
onApplied?.(changed);
@@ -310,8 +336,10 @@ export const useEditorActions = ({
async (project) => {
let current = project;
const touched = new Set<string>();
- const collect = (result: CodemodResult) => {
+ const remappings: NodePathRemapping[][] = [];
+ const collect = (result: CodemodNodeResult) => {
current = applyCodemodChanges(current, result.changes);
+ remappings.push(result.nodePathRemappings);
for (const change of result.changes) {
touched.add(change.filePath);
}
@@ -359,6 +387,7 @@ export const useEditorActions = ({
? []
: [{ filePath, previousContents, nextContents }];
}),
+ nodePathRemappings: chainNodePathRemappings(remappings),
};
},
{
@@ -569,38 +598,31 @@ export const ${componentName}: React.FC = () => {
ref.current.host?.controller.selection.clear();
},
- // Layers
+ // Layers. The selection follows the edited nodes through the node-path
+ // remappings of each result.
deleteNodes: (nodes: NodeReference[]) =>
- applyCodemod((project) => deleteNodesCodemod({ project, nodes }), {
- clearSelection: true,
- }),
+ applyCodemod((project) => deleteNodesCodemod({ project, nodes })),
duplicateNodes: (nodes: NodeReference[]) =>
- applyCodemod((project) => duplicateNodesCodemod({ project, nodes }), {
- clearSelection: true,
- }),
+ applyCodemod((project) => duplicateNodesCodemod({ project, nodes })),
splitNodesAtPlayhead: (nodes: NodeReference[]) => {
const frame = currentFrame();
- return applyCodemod(
- (project) =>
- splitSequences({
- project,
- splits: nodes.map((node) => ({ node, frame })),
- }),
- { clearSelection: true },
+ return applyCodemod((project) =>
+ splitSequences({
+ project,
+ splits: nodes.map((node) => ({ node, frame })),
+ }),
);
},
wrapNode: (node: NodeReference, wrapper: "Sequence" | "AbsoluteFill") =>
- applyCodemod(
- (project) =>
- wrapNode({
- project,
- node,
- wrapper: createElement({
- component: wrapper,
- importPath: "remotion",
- }),
+ applyCodemod((project) =>
+ wrapNode({
+ project,
+ node,
+ wrapper: createElement({
+ component: wrapper,
+ importPath: "remotion",
}),
- { clearSelection: true },
+ }),
),
reorderNode: (node: NodeReference, direction: "up" | "down") => {
const siblings = ref.current.layers
@@ -627,15 +649,13 @@ export const ${componentName}: React.FC = () => {
return Promise.resolve(false);
}
- return applyCodemod(
- (project) =>
- reorderNodeCodemod({
- project,
- node,
- target,
- position: direction === "up" ? "before" : "after",
- }),
- { clearSelection: true },
+ return applyCodemod((project) =>
+ reorderNodeCodemod({
+ project,
+ node,
+ target,
+ position: direction === "up" ? "before" : "after",
+ }),
);
},
updateNodeProps: (
@@ -1014,7 +1034,10 @@ export const ${componentName}: React.FC = () => {
return ok;
},
- addComposition: async (compositionId: string) => {
+ addComposition: async (
+ compositionId: string,
+ folder: FolderReference | null,
+ ) => {
const { compositionFile, compositions, state } = ref.current;
if (!compositionFile) {
return false;
@@ -1080,6 +1103,7 @@ export const ${componentName}: React.FC = () => {
fps: 30,
durationInFrames: 150,
},
+ folder: folder ?? undefined,
});
const files = {
...applyCodemodChanges(project, result.changes).files,
@@ -1097,6 +1121,79 @@ export const ${componentName}: React.FC = () => {
return false;
}
},
+ /**
+ * Moves a composition or folder within the registration file: into a
+ * folder, to the root, or before or after another registration.
+ */
+ moveRegistration: (
+ item: CompositionTreeItem,
+ destination: CompositionDestination,
+ ) => {
+ const { compositionFile } = ref.current;
+ if (!compositionFile) {
+ return Promise.resolve(false);
+ }
+
+ return applyCodemod((project) =>
+ item.type === "composition"
+ ? moveComposition({
+ project,
+ compositionFile,
+ compositionId: item.compositionId,
+ destination,
+ })
+ : moveFolder({
+ project,
+ compositionFile,
+ folder: { name: item.name, parentName: item.parentName },
+ destination,
+ }),
+ );
+ },
+ addFolder: (name: string, parentName: string | null) => {
+ const { compositionFile } = ref.current;
+ if (!compositionFile || name.trim() === "") {
+ return Promise.resolve(false);
+ }
+
+ return applyCodemod((project) =>
+ addFolder({
+ project,
+ compositionFile,
+ folder: { name: name.trim(), parentName },
+ }),
+ );
+ },
+ renameFolder: (folder: FolderReference, newName: string) => {
+ const { compositionFile } = ref.current;
+ if (
+ !compositionFile ||
+ newName.trim() === "" ||
+ newName.trim() === folder.name
+ ) {
+ return Promise.resolve(false);
+ }
+
+ return applyCodemod((project) =>
+ renameFolder({
+ project,
+ compositionFile,
+ folder,
+ newName: newName.trim(),
+ }),
+ );
+ },
+ /** Removes a folder element; the registrations inside it stay. */
+ deleteFolder: (folder: FolderReference) => {
+ const { compositionFile } = ref.current;
+ if (!compositionFile) {
+ return Promise.resolve(false);
+ }
+
+ return applyCodemod((project) =>
+ unwrapFolder({ project, compositionFile, folder }),
+ );
+ },
setDefaultProps: (
compositionId: string,
defaultProps: Record<string, CodemodValue>,
diff --git a/packages/template-vibe-code/src/editor/hooks/use-layers.ts b/packages/template-vibe-code/src/editor/hooks/use-layers.ts
index 2b941334ce..5d175a5cac 100644
--- a/packages/template-vibe-code/src/editor/hooks/use-layers.ts
+++ b/packages/template-vibe-code/src/editor/hooks/use-layers.ts
@@ -20,7 +20,9 @@ const noopSubscribe = () => () => {};
* The source locations reported by the preview refer to the files that were
* compiled last, so everything is resolved against `compiledProject`. While
* an edit is being compiled, the layers keep describing what the preview
- * shows; they catch up as soon as the new bundle is running.
+ * shows. Codemod edits hand their node-path remappings to the Canvas, which
+ * applies them in the same commit as the Fast Refresh update; this
+ * registration confirms them and covers edits made in the code panel.
*/
export const useLayers = ({
host,
diff --git a/packages/template-vibe-code/src/editor/model/compositions.ts b/packages/template-vibe-code/src/editor/model/compositions.ts
index b0e0a7b544..ed5739a389 100644
--- a/packages/template-vibe-code/src/editor/model/compositions.ts
+++ b/packages/template-vibe-code/src/editor/model/compositions.ts
@@ -2,6 +2,8 @@ import {
getNodeProps,
getNodes,
type CodemodProject,
+ type CompositionTreeItem,
+ type FolderReference,
type NodeReference,
} from "@remotion/codemods";
@@ -11,6 +13,8 @@ export type CompositionInfo = {
filePath: string;
node: NodeReference;
line: number | null;
+ /** The enclosing folders as a slash-separated path, `null` at the root. */
+ folderPath: string | null;
width: number | null;
height: number | null;
fps: number | null;
@@ -18,7 +22,33 @@ export type CompositionInfo = {
defaultProps: Record<string, unknown> | null;
};
-const compositionTags = new Set(["Composition", "Still"]);
+export type FolderInfo = FolderReference & {
+ filePath: string;
+ node: NodeReference;
+ line: number | null;
+};
+
+export type RegistrationTreeItem =
+ | { type: "composition"; composition: CompositionInfo }
+ | { type: "folder"; folder: FolderInfo; children: RegistrationTreeItem[] };
+
+/** The <Composition>, <Still> and <Folder> elements of the registration file. */
+export type Registrations = {
+ compositions: CompositionInfo[];
+ folders: FolderInfo[];
+ tree: RegistrationTreeItem[];
+};
+
+const emptyRegistrations: Registrations = {
+ compositions: [],
+ folders: [],
+ tree: [],
+};
+
+const registrationIdentities = {
+ "dev.remotion.remotion.Composition": "Composition",
+ "dev.remotion.remotion.Still": "Still",
+} as const;
const readStatic = <T>(
props: ReturnType<typeof getNodeProps>["props"],
@@ -39,6 +69,32 @@ const isNumber = (value: unknown): value is number =>
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
+/** The folder path the codemods use as `parentName` for the folder's children. */
+export const getFolderPath = (folder: FolderReference): string =>
+ folder.parentName === null
+ ? folder.name
+ : `${folder.parentName}/${folder.name}`;
+
+export const toFolderReference = (folderPath: string): FolderReference => {
+ const segments = folderPath.split("/");
+ return {
+ name: segments[segments.length - 1],
+ parentName: segments.slice(0, -1).join("/") || null,
+ };
+};
+
+/** The tree item the codemods address a registration by. */
+export const toCompositionTreeItem = (
+ item: RegistrationTreeItem,
+): CompositionTreeItem =>
+ item.type === "composition"
+ ? { type: "composition", compositionId: item.composition.id }
+ : {
+ type: "folder",
+ name: item.folder.name,
+ parentName: item.folder.parentName,
+ };
+
/**
* Finds the file that registers <Composition> elements. This is where
* composition codemods (rename, duplicate, metadata) are applied.
@@ -59,8 +115,10 @@ export const findCompositionFile = (project: CodemodProject): string | null => {
try {
if (
- getNodes({ project, filePath }).some((node) =>
- compositionTags.has(node.tagName),
+ getNodes({ project, filePath }).some(
+ (node) =>
+ node.componentIdentity !== null &&
+ node.componentIdentity in registrationIdentities,
)
) {
return filePath;
@@ -73,51 +131,117 @@ export const findCompositionFile = (project: CodemodProject): string | null => {
return null;
};
-export const getCompositions = (
+/**
+ * Reads the registration tree in source order. Compositions and folders are
+ * attached to their closest enclosing <Folder>; other wrapper elements are
+ * skipped.
+ */
+export const getRegistrations = (
project: CodemodProject,
compositionFile: string | null,
-): CompositionInfo[] => {
+): Registrations => {
if (!compositionFile) {
- return [];
+ return emptyRegistrations;
}
try {
- return getNodes({ project, filePath: compositionFile })
- .filter((node) => compositionTags.has(node.tagName))
- .flatMap((node): CompositionInfo[] => {
- const { props } = getNodeProps({
- project,
- node,
- keys: [
- "id",
- "width",
- "height",
- "fps",
- "durationInFrames",
- "defaultProps",
- ],
- });
- const id = readStatic(props, "id", isString);
- if (!id) {
- return [];
+ const nodes = getNodes({ project, filePath: compositionFile });
+ const nodesByPath = new Map(
+ nodes.map((node) => [JSON.stringify(node.nodePath), node]),
+ );
+ const foldersByPath = new Map<
+ string,
+ Extract<RegistrationTreeItem, { type: "folder" }>
+ >();
+ const registrations: Registrations = {
+ compositions: [],
+ folders: [],
+ tree: [],
+ };
+
+ for (const node of nodes) {
+ const tagName =
+ node.componentIdentity !== null &&
+ node.componentIdentity in registrationIdentities
+ ? registrationIdentities[
+ node.componentIdentity as keyof typeof registrationIdentities
+ ]
+ : node.componentIdentity === "dev.remotion.remotion.Folder"
+ ? "Folder"
+ : null;
+ if (tagName === null) {
+ continue;
+ }
+
+ let parentPath = node.parentNodePath;
+ let parent: Extract<RegistrationTreeItem, { type: "folder" }> | null =
+ null;
+ while (parentPath !== null && parent === null) {
+ const key = JSON.stringify(parentPath);
+ parent = foldersByPath.get(key) ?? null;
+ parentPath = nodesByPath.get(key)?.parentNodePath ?? null;
+ }
+
+ const children = parent?.children ?? registrations.tree;
+ const folderPath = parent ? getFolderPath(parent.folder) : null;
+ const reference = { filePath: node.filePath, nodePath: node.nodePath };
+ if (tagName === "Folder") {
+ const { props } = getNodeProps({ project, node, keys: ["name"] });
+ const name = readStatic(props, "name", isString);
+ if (!name) {
+ continue;
}
- return [
- {
- id,
- tagName: node.tagName as "Composition" | "Still",
- filePath: node.filePath,
- node: { filePath: node.filePath, nodePath: node.nodePath },
- line: node.location?.line ?? null,
- width: readStatic(props, "width", isNumber),
- height: readStatic(props, "height", isNumber),
- fps: readStatic(props, "fps", isNumber),
- durationInFrames: readStatic(props, "durationInFrames", isNumber),
- defaultProps: readStatic(props, "defaultProps", isRecord),
- },
- ];
+ const folder: FolderInfo = {
+ name,
+ parentName: folderPath,
+ filePath: node.filePath,
+ node: reference,
+ line: node.location?.line ?? null,
+ };
+ const item = { type: "folder" as const, folder, children: [] };
+ foldersByPath.set(JSON.stringify(node.nodePath), item);
+ registrations.folders.push(folder);
+ children.push(item);
+ continue;
+ }
+
+ const { props } = getNodeProps({
+ project,
+ node,
+ keys: [
+ "id",
+ "width",
+ "height",
+ "fps",
+ "durationInFrames",
+ "defaultProps",
+ ],
});
+ const id = readStatic(props, "id", isString);
+ if (!id) {
+ continue;
+ }
+
+ const composition: CompositionInfo = {
+ id,
+ tagName,
+ filePath: node.filePath,
+ node: reference,
+ line: node.location?.line ?? null,
+ folderPath,
+ width: readStatic(props, "width", isNumber),
+ height: readStatic(props, "height", isNumber),
+ fps: readStatic(props, "fps", isNumber),
+ durationInFrames: readStatic(props, "durationInFrames", isNumber),
+ defaultProps: readStatic(props, "defaultProps", isRecord),
+ };
+ registrations.compositions.push(composition);
+ children.push({ type: "composition", composition });
+ }
+
+ return registrations;
} catch {
- return [];
+ return emptyRegistrations;
}
};
diff --git a/packages/template-vibe-code/src/editor/model/layers.ts b/packages/template-vibe-code/src/editor/model/layers.ts
index de607a6e8d..fe38ead0e6 100644
--- a/packages/template-vibe-code/src/editor/model/layers.ts
+++ b/packages/template-vibe-code/src/editor/model/layers.ts
@@ -10,6 +10,7 @@ import {
getNodes,
type CodemodProject,
type CodemodNode,
+ type NodePathRemapping,
type NodeReference,
} from "@remotion/codemods";
import type {
@@ -129,6 +130,37 @@ export const buildLayers = (
});
};
+/**
+ * The remappings of codemods that were applied one after another, expressed
+ * as one mapping from the paths of the first input project. A node that a
+ * later codemod moved again is followed to its final path.
+ */
+export const chainNodePathRemappings = (
+ batches: readonly (readonly NodePathRemapping[])[],
+): NodePathRemapping[] =>
+ batches.reduce<NodePathRemapping[]>((chained, batch) => {
+ const unchained = new Set(batch);
+ const followed = chained.map((entry) => {
+ const { newNodePath } = entry;
+ const next =
+ newNodePath === null
+ ? undefined
+ : batch.find(
+ (candidate) =>
+ candidate.filePath === entry.filePath &&
+ candidate.oldNodePath !== null &&
+ sameNodePath(candidate.oldNodePath, newNodePath),
+ );
+ if (!next) {
+ return entry;
+ }
+
+ unchained.delete(next);
+ return { ...entry, newNodePath: next.newNodePath };
+ });
+ return [...followed, ...unchained];
+ }, []);
+
export const getNodeReference = (
item: CanvasSelectionItem,
): NodeReference | null => {
diff --git a/packages/template-vibe-code/src/editor/state/editor-context.tsx b/packages/template-vibe-code/src/editor/state/editor-context.tsx
index 69c522fdff..8c261b5c24 100644
--- a/packages/template-vibe-code/src/editor/state/editor-context.tsx
+++ b/packages/template-vibe-code/src/editor/state/editor-context.tsx
@@ -6,7 +6,7 @@ import { createContext, useContext } from "react";
import type { PreviewHost } from "@/preview/bridge";
import type { EditorActions } from "../hooks/use-editor-actions";
import type { PlaybackStore } from "../hooks/use-playback";
-import type { CompositionInfo } from "../model/compositions";
+import type { CompositionInfo, Registrations } from "../model/compositions";
import type { KeyframedProp } from "../model/keyframes";
import type { Layer } from "../model/layers";
import type { EditorAction, EditorState } from "./editor-store";
@@ -24,6 +24,8 @@ export type EditorContextValue = {
/** The props of the layers that are animated with `interpolate()`. */
keyframedProps: KeyframedProp[];
project: CodemodProject;
+ /** The composition and folder tree of `compositionFile`. */
+ registrations: Registrations;
compositions: CompositionInfo[];
compositionFile: string | null;
/** The file that defines the component of the active composition. */