Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/studio`: Preserve node paths after deleting sequences and other mutations that add / remove elements (#10239)

Jonny Burgerd643a07755c7
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index f493465f9e..58d76f9264 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -5,7 +5,7 @@ import {
getCanUpdateDefaultPropsForProject,
getCompositionComponentInfo,
getCompositionFile,
- insertSolidIntoProject,
+ insertSolidIntoProjectWithNodePathRemappings,
JsxElementIdentityMismatchError,
JsxElementNotFoundAtLocationError,
} from '@remotion/studio-codemods';
@@ -22,7 +22,10 @@ import {makeBrowserStudioProjectArchive} from './download-project';
import {saveSequencePropsInProject} from './save-sequence-props';
import type {VirtualProject} from './types';
-export {insertSolidIntoProject} from '@remotion/studio-codemods';
+export {
+ insertSolidIntoProject,
+ insertSolidIntoProjectWithNodePathRemappings,
+} from '@remotion/studio-codemods';
export type BrowserStudioOperationsController = BrowserStudioOperations & {
emitEvent: (event: EventSourceEvent) => void;
@@ -87,10 +90,12 @@ export const createBrowserStudioOperations = ({
const controller = createBrowserStudioProjectController({
getStaticFiles,
getProject,
- onProjectChange: (project) => {
+ onProjectChange: (project, metadata) => {
onProjectChange(project);
refreshDefaultPropsSubscriptions();
- refreshSequencePropsSubscriptions();
+ if (!metadata.skipSequencePropsUpdate) {
+ refreshSequencePropsSubscriptions();
+ }
},
});
@@ -212,15 +217,26 @@ export const createBrowserStudioOperations = ({
),
insertSolid: (request) => {
try {
- controller.applyMutation({
- fileName: request.compositionFile,
- mutate: (project) =>
- insertSolidIntoProject({
- project,
- request,
- }),
+ const result = insertSolidIntoProjectWithNodePathRemappings({
+ project: getProject(),
+ request,
+ });
+ const nodePathMutation = controller.applyMutation({
+ fileName: result.filePath,
+ mutate: () => result.project,
+ nodePathMutationFiles: [
+ {
+ absolutePath: result.filePath,
+ remappings: result.nodePathRemappings,
+ restoredNodePaths: [],
+ },
+ ],
});
- return Promise.resolve({success: true});
+ if (nodePathMutation === null) {
+ throw new Error('Could not insert <Solid>');
+ }
+
+ return Promise.resolve({success: true, nodePathMutation});
} catch (error) {
return Promise.resolve({
success: false,
@@ -239,6 +255,7 @@ export const createBrowserStudioOperations = ({
const firstTarget = request.edits[0] ?? request.captionPatches?.[0];
controller.applyMutation({
fileName: firstTarget?.fileName ?? 'Sequence props',
+ nodePathMutationFiles: null,
mutate: (project) => {
const result = saveSequencePropsInProject({project, request});
response = result.response;
diff --git a/packages/browser-studio/src/browser-studio-project-controller.ts b/packages/browser-studio/src/browser-studio-project-controller.ts
index 6db154cfa8..1e0243aeac 100644
--- a/packages/browser-studio/src/browser-studio-project-controller.ts
+++ b/packages/browser-studio/src/browser-studio-project-controller.ts
@@ -3,19 +3,26 @@ import type {
BrowserStudioOperations,
EventSourceEvent,
RedoResponse,
+ SequenceNodePathMutation,
+ SequenceNodePathRemapping,
UndoResponse,
} from '@remotion/studio-shared';
+import type {SequenceNodePath} from 'remotion';
import type {VirtualProject} from './types';
+type ProjectNodePathMutationFiles = SequenceNodePathMutation['files'];
+
type HistoryEntry = {
before: VirtualProject;
after: VirtualProject;
fileName: string;
+ nodePathMutationFiles: ProjectNodePathMutationFiles | null;
};
type ProjectMutation = {
fileName: string;
mutate: (project: VirtualProject) => VirtualProject;
+ nodePathMutationFiles: ProjectNodePathMutationFiles | null;
};
const MAX_HISTORY_ENTRIES = 100;
@@ -271,7 +278,7 @@ const getFileSource = ({
};
export type BrowserStudioProjectController = {
- applyMutation: (mutation: ProjectMutation) => VirtualProject;
+ applyMutation: (mutation: ProjectMutation) => SequenceNodePathMutation | null;
deleteStaticFile: BrowserStudioOperations['deleteStaticFile'];
emitEvent: (event: EventSourceEvent) => void;
findInFile: BrowserStudioOperations['findInFile'];
@@ -296,7 +303,10 @@ export const createBrowserStudioProjectController = ({
}: {
getStaticFiles: BrowserStudioStaticFilesGetter | null;
getProject: () => VirtualProject;
- onProjectChange: (project: VirtualProject) => void;
+ onProjectChange: (
+ project: VirtualProject,
+ metadata: {skipSequencePropsUpdate: boolean},
+ ) => void;
}): BrowserStudioProjectController => {
const resolvedGetStaticFiles: BrowserStudioStaticFilesGetter =
getStaticFiles === null
@@ -313,6 +323,8 @@ export const createBrowserStudioProjectController = ({
const lastModifiedByPath = new Map<string, number>();
let latestHmrEvent: Extract<EventSourceEvent, {type: 'hmr'}> | null = null;
let publicFileRevision = 0;
+ const nodePathMutationSessionId = `${Date.now()}:${Math.random()}`;
+ let nodePathMutationCounter = 0;
const getUndoRedoEvent = (): EventSourceEvent => ({
type: 'undo-redo-stack-changed',
@@ -358,38 +370,60 @@ export const createBrowserStudioProjectController = ({
const commitProject = ({
previousProject,
nextProject,
+ nodePathMutationFiles,
}: {
previousProject: VirtualProject;
nextProject: VirtualProject;
- }) => {
+ nodePathMutationFiles: ProjectNodePathMutationFiles | null;
+ }): SequenceNodePathMutation | null => {
const publicFilesChanged = updatePublicFileRevisions(
previousProject,
nextProject,
);
- onProjectChange(nextProject);
+ const nodePathMutation = nodePathMutationFiles
+ ? {
+ mutationId: `${nodePathMutationSessionId}:${++nodePathMutationCounter}`,
+ files: nodePathMutationFiles,
+ }
+ : null;
+ if (nodePathMutation) {
+ emit({type: 'sequence-node-paths-remapped', mutation: nodePathMutation});
+ }
+
+ onProjectChange(nextProject, {
+ skipSequencePropsUpdate: nodePathMutationFiles !== null,
+ });
if (publicFilesChanged) {
emit(getPublicFilesEvent());
}
emit(getUndoRedoEvent());
+ return nodePathMutation;
};
- const applyMutation = ({fileName, mutate}: ProjectMutation) => {
+ const applyMutation = ({
+ fileName,
+ mutate,
+ nodePathMutationFiles,
+ }: ProjectMutation) => {
const before = getProject();
const after = mutate(before);
if (after === before) {
- return before;
+ return null;
}
- undoStack.push({before, after, fileName});
+ undoStack.push({before, after, fileName, nodePathMutationFiles});
if (undoStack.length > MAX_HISTORY_ENTRIES) {
undoStack.shift();
}
redoStack.length = 0;
- commitProject({previousProject: before, nextProject: after});
- return after;
+ return commitProject({
+ previousProject: before,
+ nextProject: after,
+ nodePathMutationFiles,
+ });
};
const undo = (): Promise<UndoResponse> => {
@@ -399,11 +433,30 @@ export const createBrowserStudioProjectController = ({
}
redoStack.push(entry);
- commitProject({
+ const files = entry.nodePathMutationFiles?.map((file) => ({
+ absolutePath: file.absolutePath,
+ remappings: file.remappings.flatMap(
+ (remapping): SequenceNodePathRemapping[] =>
+ remapping.newNodePath === null
+ ? []
+ : [
+ {
+ oldNodePath: remapping.newNodePath,
+ newNodePath: remapping.oldNodePath,
+ },
+ ],
+ ),
+ restoredNodePaths: file.remappings.flatMap(
+ (remapping): SequenceNodePath[] =>
+ remapping.newNodePath === null ? [remapping.oldNodePath] : [],
+ ),
+ }));
+ const nodePathMutation = commitProject({
previousProject: getProject(),
nextProject: entry.before,
+ nodePathMutationFiles: files ?? null,
});
- return Promise.resolve({success: true});
+ return Promise.resolve({success: true, nodePathMutation});
};
const redo = (): Promise<RedoResponse> => {
@@ -413,11 +466,12 @@ export const createBrowserStudioProjectController = ({
}
undoStack.push(entry);
- commitProject({
+ const nodePathMutation = commitProject({
previousProject: getProject(),
nextProject: entry.after,
+ nodePathMutationFiles: entry.nodePathMutationFiles,
});
- return Promise.resolve({success: true});
+ return Promise.resolve({success: true, nodePathMutation});
};
return {
@@ -433,6 +487,7 @@ export const createBrowserStudioProjectController = ({
applyMutation({
fileName: canonicalPath,
+ nodePathMutationFiles: null,
mutate: (project) => {
const nextPublicFiles = getCanonicalPublicFiles(project);
delete nextPublicFiles[canonicalPath];
@@ -483,6 +538,7 @@ export const createBrowserStudioProjectController = ({
applyMutation({
fileName: oldPath,
+ nodePathMutationFiles: null,
mutate: (project) => {
const nextPublicFiles = getCanonicalPublicFiles(project);
nextPublicFiles[newPath] = nextPublicFiles[oldPath];
@@ -523,6 +579,7 @@ export const createBrowserStudioProjectController = ({
: new Uint8Array(contents.slice(0));
applyMutation({
fileName: canonicalPath,
+ nodePathMutationFiles: null,
mutate: (project) => ({
...project,
publicFiles: {
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index 98a484dfec..38a5288720 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -3,6 +3,7 @@ import type {EventSourceEvent} from '@remotion/studio-shared';
import {
createBrowserStudioOperations,
insertSolidIntoProject,
+ insertSolidIntoProjectWithNodePathRemappings,
} from '../browser-studio-operations';
import {createBlankTemplateProject} from '../templates/blank';
import type {VirtualProject} from '../types';
@@ -137,13 +138,13 @@ export const MyComponent = () => <AbsoluteFill>Existing</AbsoluteFill>;
position: null,
},
});
- expect(result).toEqual({success: true});
+ expect(result.success).toBe(true);
expect(currentProject.files['/project/src/MyComponent.tsx']).toContain(
'<Solid width={1280}',
);
});
-test('wraps a self-closing root and aliases conflicting bindings', () => {
+test('wraps a self-closing root, aliases bindings, and remaps the root', () => {
const project: VirtualProject = {
rootDir: '/project',
entryPoint: '/project/src/index.tsx',
@@ -158,7 +159,21 @@ registerRoot(Root);
`,
},
};
- const updated = insertSolid(project, '/project/src/index.tsx');
+ const {project: updated, nodePathRemappings} =
+ insertSolidIntoProjectWithNodePathRemappings({
+ project,
+ request: {
+ compositionFile: '/project/src/index.tsx',
+ compositionId: 'MyComp',
+ from: null,
+ element: {
+ type: 'solid',
+ width: 1280,
+ height: 720,
+ position: null,
+ },
+ },
+ });
const output = updated.files['/project/src/index.tsx'];
expect(output).toContain(
@@ -166,6 +181,100 @@ registerRoot(Root);
);
expect(output).toContain('<RemotionSequence>');
expect(output).toContain('<RemotionSolid width={1280}');
+ expect(nodePathRemappings).toHaveLength(1);
+ expect(nodePathRemappings[0].newNodePath).not.toEqual(
+ nodePathRemappings[0].oldNodePath,
+ );
+});
+
+test('inserting a Solid broadcasts remappings without refreshing stale subscriptions', async () => {
+ const fileName = '/project/src/Composition.tsx';
+ let currentProject: VirtualProject = {
+ rootDir: '/project',
+ entryPoint: '/project/src/index.tsx',
+ files: {
+ '/project/src/index.tsx': `import {registerRoot} from 'remotion';
+import {Root} from './Composition';
+registerRoot(Root);`,
+ [fileName]: `import {Composition, Sequence} from 'remotion';
+export const Component = () => <Sequence from={10} durationInFrames={20} />;
+export const Root = () => <Composition id="MyComp" component={Component} durationInFrames={60} fps={30} width={1280} height={720} />;`,
+ },
+ };
+ const operations = createBrowserStudioOperations({
+ dependencyVersions: {},
+ getStaticFiles: null,
+ getProject: () => currentProject,
+ onProjectChange: (nextProject) => {
+ currentProject = nextProject;
+ },
+ });
+ const events: EventSourceEvent[] = [];
+ operations.subscribeToEvent((event) => events.push(event));
+ const subscription = await operations.subscribeToSequenceProps({
+ fileName: 'src/Composition.tsx',
+ line: 2,
+ column: 31,
+ nodePath: null,
+ componentIdentity: 'dev.remotion.remotion.Sequence',
+ keys: ['from', 'durationInFrames'],
+ assetKeys: [],
+ effects: [],
+ clientId: 'browser-studio',
+ videoConfigValues: {
+ durationInFrames: 60,
+ fps: 30,
+ height: 720,
+ width: 1280,
+ },
+ });
+ if (!subscription.success) {
+ throw new Error('Expected sequence props subscription to succeed');
+ }
+
+ events.length = 0;
+ const result = await operations.insertSolid({
+ compositionFile: fileName,
+ compositionId: 'MyComp',
+ from: null,
+ element: {
+ type: 'solid',
+ width: 1280,
+ height: 720,
+ position: null,
+ },
+ });
+ if (!result.success) {
+ throw new Error(result.reason);
+ }
+
+ expect(result.nodePathMutation.files).toEqual([
+ {
+ absolutePath: fileName,
+ remappings: [
+ {
+ oldNodePath: subscription.nodePath.nodePath,
+ newNodePath: expect.any(Array),
+ },
+ ],
+ restoredNodePaths: [],
+ },
+ ]);
+ expect(
+ events.filter((event) => event.type === 'sequence-node-paths-remapped'),
+ ).toEqual([
+ {
+ type: 'sequence-node-paths-remapped',
+ mutation: result.nodePathMutation,
+ },
+ ]);
+ expect(
+ events.some(
+ (event) =>
+ event.type === 'lost-node-path' ||
+ event.type === 'sequence-props-updated',
+ ),
+ ).toBe(false);
});
test('reports invalid timeline Solid input without changing the project', async () => {
@@ -372,9 +481,15 @@ export const Root = () => <Composition id="MyComp" component={Component} duratio
}
expect(update.result.props.from).toEqual({status: 'static', codeValue: 15});
- expect(await operations.undo()).toEqual({success: true});
+ expect(await operations.undo()).toEqual({
+ success: true,
+ nodePathMutation: null,
+ });
expect(currentProject.files[fileName]).toContain('from={10}');
- expect(await operations.redo()).toEqual({success: true});
+ expect(await operations.redo()).toEqual({
+ success: true,
+ nodePathMutation: null,
+ });
expect(currentProject.files[fileName]).toContain('from={15}');
currentProject = {
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 a048c646c3..6463f6404a 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
@@ -29,9 +29,13 @@ test('mutates virtual files, emits events, and preserves undo and redo history',
},
});
const events: EventSourceEvent[] = [];
- const unsubscribe = operations.subscribeToEvent((event) =>
- events.push(event),
- );
+ const contentsAtMutation: string[] = [];
+ const unsubscribe = operations.subscribeToEvent((event) => {
+ events.push(event);
+ if (event.type === 'sequence-node-paths-remapped') {
+ contentsAtMutation.push(project.files['/project/src/Composition.tsx']);
+ }
+ });
expect(events.slice(0, 2).map((event) => event.type)).toEqual([
'init',
@@ -57,17 +61,45 @@ test('mutates virtual files, emits events, and preserves undo and redo history',
},
from: null,
});
- expect(insertResult).toEqual({success: true});
+ if (!insertResult.success) {
+ throw new Error(insertResult.reason);
+ }
+
+ expect(
+ events.findLast((event) => event.type === 'sequence-node-paths-remapped'),
+ ).toEqual({
+ type: 'sequence-node-paths-remapped',
+ mutation: insertResult.nodePathMutation,
+ });
+ expect(contentsAtMutation).toEqual([
+ initialProject.files['/project/src/Composition.tsx'],
+ ]);
expect(project.files['/project/src/Composition.tsx']).toContain(
'<Solid width={1280}',
);
const {redo, undo} = operations;
- expect(await undo()).toEqual({success: true});
+ const undoResult = await undo();
+ expect(undoResult.success).toBe(true);
+ if (!undoResult.success || undoResult.nodePathMutation === null) {
+ throw new Error('Expected undo to remap node paths');
+ }
+
+ expect(undoResult.nodePathMutation.files).toEqual(
+ insertResult.nodePathMutation.files,
+ );
expect(project.files['/project/src/Composition.tsx']).toBe(
initialProject.files['/project/src/Composition.tsx'],
);
- expect(await redo()).toEqual({success: true});
+ const redoResult = await redo();
+ expect(redoResult.success).toBe(true);
+ if (!redoResult.success || redoResult.nodePathMutation === null) {
+ throw new Error('Expected redo to remap node paths');
+ }
+
+ expect(redoResult.nodePathMutation.files).toEqual(
+ insertResult.nodePathMutation.files,
+ );
expect(project.files['/project/src/Composition.tsx']).toContain(
'<Solid width={1280}',
);
@@ -112,11 +144,11 @@ test('mutates virtual files, emits events, and preserves undo and redo history',
});
expect(project.publicFiles?.['renamed.bin']).toBeUndefined();
- expect(await undo()).toEqual({success: true});
+ expect(await undo()).toEqual({success: true, nodePathMutation: null});
expect(project.publicFiles?.['renamed.bin']).toEqual(
new Uint8Array([0, 127, 128, 255]),
);
- expect(await undo()).toEqual({success: true});
+ expect(await undo()).toEqual({success: true, nodePathMutation: null});
expect(project.publicFiles?.['nested/upload.bin']).toEqual(
new Uint8Array([0, 127, 128, 255]),
);
diff --git a/packages/browser-studio/src/test/download-project.test.ts b/packages/browser-studio/src/test/download-project.test.ts
index 2d0d66f494..011dfd5f87 100644
--- a/packages/browser-studio/src/test/download-project.test.ts
+++ b/packages/browser-studio/src/test/download-project.test.ts
@@ -38,7 +38,7 @@ test('downloads the current Browser Studio project as a runnable archive', async
},
from: null,
});
- expect(insertResult).toEqual({success: true});
+ expect(insertResult.success).toBe(true);
const archive = await operations.downloadProject();
diff --git a/packages/bundler/src/fast-refresh/notify-on-refresh.ts b/packages/bundler/src/fast-refresh/notify-on-refresh.ts
new file mode 100644
index 0000000000..352bd5104a
--- /dev/null
+++ b/packages/bundler/src/fast-refresh/notify-on-refresh.ts
@@ -0,0 +1,24 @@
+import {REACT_REFRESH_FINISHED_EVENT} from '@remotion/studio-shared';
+
+type ReactRefreshRuntime = {
+ performReactRefresh: () => unknown;
+ __remotionReactRefreshWrapped: boolean | null;
+};
+
+const RefreshRuntime = require('react-refresh/runtime') as ReactRefreshRuntime;
+RefreshRuntime.__remotionReactRefreshWrapped ??= null;
+
+if (RefreshRuntime.__remotionReactRefreshWrapped === null) {
+ const originalPerformReactRefresh = RefreshRuntime.performReactRefresh;
+ RefreshRuntime.__remotionReactRefreshWrapped = true;
+ RefreshRuntime.performReactRefresh = () => {
+ // The refresh integration calls this after applying the update. Emitting
+ // here gives Studio a boundary after React refreshed its roots.
+ const result = originalPerformReactRefresh();
+ if (result !== null) {
+ window.dispatchEvent(new Event(REACT_REFRESH_FINISHED_EVENT));
+ }
+
+ return result;
+ };
+}
diff --git a/packages/bundler/src/fast-refresh/runtime.ts b/packages/bundler/src/fast-refresh/runtime.ts
index 77dc139cd9..7cdcc59100 100644
--- a/packages/bundler/src/fast-refresh/runtime.ts
+++ b/packages/bundler/src/fast-refresh/runtime.ts
@@ -43,6 +43,7 @@ declare global {
const RefreshRuntime = require('react-refresh/runtime');
import RefreshHelpers from './helpers';
+import './notify-on-refresh';
// Hook into ReactDOM initialization
RefreshRuntime.injectIntoGlobalHook(self);
diff --git a/packages/bundler/src/rspack-config.ts b/packages/bundler/src/rspack-config.ts
index e9871f76f0..dc116a63d6 100644
--- a/packages/bundler/src/rspack-config.ts
+++ b/packages/bundler/src/rspack-config.ts
@@ -86,7 +86,10 @@ export const rspackConfig = async ({
__filename: 'mock',
},
entry: getStudioEntryPoints({
- fastRefreshRuntime: null,
+ fastRefreshRuntime:
+ environment === 'development'
+ ? require.resolve('./fast-refresh/notify-on-refresh.js')
+ : null,
environmentSetup: require.resolve('./setup-environment'),
sequenceStackTraces:
environment === 'development'
diff --git a/packages/core/src/SequenceManager.tsx b/packages/core/src/SequenceManager.tsx
index 994d7b64d7..7569ba03ad 100644
--- a/packages/core/src/SequenceManager.tsx
+++ b/packages/core/src/SequenceManager.tsx
@@ -50,6 +50,12 @@ export type VisualModeDragOverrides = {
getEffectDragOverrides: GetEffectDragOverrides;
};
+export type SequencePropsStatusRemapping = {
+ previousNodePath: SequencePropsSubscriptionKey;
+ nodePath: SequencePropsSubscriptionKey | null;
+ result: CanUpdateSequencePropsResponse | null;
+};
+
export type VisualModeSetters = {
setDragOverrides: (
nodePath: SequencePropsSubscriptionKey,
@@ -73,6 +79,9 @@ export type VisualModeSetters = {
prev: CanUpdateSequencePropsResponse,
) => CanUpdateSequencePropsResponse,
) => void;
+ remapPropStatuses: (
+ remappings: readonly SequencePropsStatusRemapping[],
+ ) => void;
};
export type CanUpdateEffectPropsResponseTrue = {
@@ -157,6 +166,9 @@ export const VisualModeSettersContext = React.createContext<VisualModeSetters>({
setPropStatuses: () => {
throw new Error('VisualModeSettersContext not initialized');
},
+ remapPropStatuses: () => {
+ throw new Error('VisualModeSettersContext not initialized');
+ },
});
export type SequencePropsSubscriptionKey = {
@@ -287,6 +299,28 @@ export const SequenceManagerProvider: React.FC<{
},
[],
);
+ const remapPropStatuses = useCallback(
+ (remappings: readonly SequencePropsStatusRemapping[]) => {
+ setPropStatusesMapState((prev) => {
+ const next = {...prev};
+ for (const remapping of remappings) {
+ delete next[
+ makeSequencePropsSubscriptionKey(remapping.previousNodePath)
+ ];
+ }
+
+ for (const remapping of remappings) {
+ if (remapping.nodePath !== null && remapping.result !== null) {
+ next[makeSequencePropsSubscriptionKey(remapping.nodePath)] =
+ remapping.result;
+ }
+ }
+
+ return next;
+ });
+ },
+ [],
+ );
const registerSequence = useCallback((seq: TSequence) => {
setSequences((seqs) => {
@@ -344,6 +378,7 @@ export const SequenceManagerProvider: React.FC<{
setEffectDragOverrides,
clearEffectDragOverrides,
setPropStatuses,
+ remapPropStatuses,
};
}, [
setDragOverrides,
@@ -351,6 +386,7 @@ export const SequenceManagerProvider: React.FC<{
setEffectDragOverrides,
clearEffectDragOverrides,
setPropStatuses,
+ remapPropStatuses,
]);
return (
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index 3ee38d7044..95db609c71 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -180,6 +180,7 @@ import {
type CanUpdateSequencePropsResponseTrue,
type SequenceNodePath,
type SequencePropsSubscriptionKey,
+ type SequencePropsStatusRemapping,
type VideoConfigValues,
} from './SequenceManager.js';
import {setupEnvVariables} from './setup-env-variables.js';
@@ -498,6 +499,7 @@ export type {
InteractivitySchemaField,
SequenceNodePath,
SequencePropsSubscriptionKey,
+ SequencePropsStatusRemapping,
VideoConfigValues,
InteractivitySchema,
SerializedJSONWithCustomFields,
diff --git a/packages/core/src/sequence-node-path.tsx b/packages/core/src/sequence-node-path.tsx
index 1999d7a512..32eadee7bc 100644
--- a/packages/core/src/sequence-node-path.tsx
+++ b/packages/core/src/sequence-node-path.tsx
@@ -13,7 +13,7 @@ export type OverrideToNodePathGetters = {
export type OverrideToNodeSetters = {
setOverrideIdToNodePath: (
overrideId: string,
- nodePath: SequencePropsSubscriptionKey,
+ nodePath: SequencePropsSubscriptionKey | null,
) => void;
};
diff --git a/packages/core/src/test/html-in-canvas.test.tsx b/packages/core/src/test/html-in-canvas.test.tsx
index 392b4c2a5e..06141e7f0c 100644
--- a/packages/core/src/test/html-in-canvas.test.tsx
+++ b/packages/core/src/test/html-in-canvas.test.tsx
@@ -212,6 +212,7 @@ const SequenceTestWrapper: React.FC<{
() => ({
clearDragOverrides: () => undefined,
clearEffectDragOverrides: () => undefined,
+ remapPropStatuses: () => undefined,
setPropStatuses: () => undefined,
setDragOverrides: () => undefined,
setEffectDragOverrides: () => undefined,
diff --git a/packages/core/src/test/sequence-register-once.test.tsx b/packages/core/src/test/sequence-register-once.test.tsx
index f56228720f..6cb6641332 100644
--- a/packages/core/src/test/sequence-register-once.test.tsx
+++ b/packages/core/src/test/sequence-register-once.test.tsx
@@ -144,6 +144,7 @@ const SequenceTestWrapperWithVisualModeOverrides: React.FC<
clearDragOverrides: () => undefined,
setEffectDragOverrides: () => undefined,
clearEffectDragOverrides: () => undefined,
+ remapPropStatuses: () => undefined,
setPropStatuses: () => undefined,
}),
[],
diff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mts
index 8c92cbb50f..0c7983b5c6 100644
--- a/packages/example/e2e/studio.test.mts
+++ b/packages/example/e2e/studio.test.mts
@@ -2,8 +2,13 @@ import fs from 'fs';
import path from 'path';
import {expect, test, type Page} from '@playwright/test';
import {StudioProtocolInternals} from '@remotion/studio-protocol';
-import {STUDIO_URL, effectKeyframeE2eFile, exampleDir} from './constants.mts';
-import {navigateToSchemaTest} from './helpers.mts';
+import {
+ STUDIO_URL,
+ effectKeyframeE2eFile,
+ exampleDir,
+ lostNodePathE2eFile,
+} from './constants.mts';
+import {navigateToLostNodePathE2e, navigateToSchemaTest} from './helpers.mts';
import {startStudio, stopStudio} from './studio-server.mts';
const dropAssetOnCanvas = async ({
@@ -319,6 +324,185 @@ test.describe('visual mode', () => {
).toBeVisible();
});
+ test('should preserve following interactive elements after deleting a sibling', async ({
+ context,
+ page,
+ }) => {
+ await navigateToLostNodePathE2e(page);
+ const otherPage = await context.newPage();
+ await navigateToLostNodePathE2e(otherPage);
+ const canvas = page.locator('.remotion-studio-composition-container');
+ const otherCanvas = otherPage.locator(
+ '.remotion-studio-composition-container',
+ );
+ await expect(
+ canvas.getByText('Performance overview', {exact: true}),
+ ).toBeVisible();
+ await expect(
+ canvas.getByText('Regional growth', {exact: true}),
+ ).toHaveCount(1);
+ await expect(
+ canvas.getByText('Bars remain visible', {exact: true}),
+ ).toBeVisible();
+ await expect(
+ otherCanvas.getByText('Bars remain visible', {exact: true}),
+ ).toBeVisible();
+ const gridline = page.getByText('0% gridline', {exact: true});
+ const gridlineVisibilityToggle = gridline
+ .locator('..')
+ .locator('..')
+ .locator('[data-timeline-layer-eye]');
+ const otherGridlineVisibilityToggle = otherPage
+ .getByText('0% gridline', {exact: true})
+ .locator('..')
+ .locator('..')
+ .locator('[data-timeline-layer-eye]');
+ await expect(gridlineVisibilityToggle).toBeVisible();
+ await expect(otherGridlineVisibilityToggle).toBeVisible();
+ await page.evaluate(() => {
+ const state = window as typeof window & {
+ sequenceRemappingBadFrames: string[] | null;
+ };
+ state.sequenceRemappingBadFrames = [];
+ const sample = () => {
+ const container = document.querySelector(
+ '.remotion-studio-composition-container',
+ );
+ if (!container) {
+ requestAnimationFrame(sample);
+ return;
+ }
+
+ const regionalGrowthElements = [
+ ...container.querySelectorAll('*'),
+ ].filter((element) =>
+ [...element.childNodes].some(
+ (child) =>
+ child.nodeType === Node.TEXT_NODE &&
+ child.textContent?.trim() === 'Regional growth',
+ ),
+ );
+ if (regionalGrowthElements.length > 1) {
+ state.sequenceRemappingBadFrames?.push('duplicate-title');
+ }
+
+ if (
+ regionalGrowthElements.some(
+ (element) =>
+ getComputedStyle(element).textTransform === 'uppercase',
+ )
+ ) {
+ state.sequenceRemappingBadFrames?.push('uppercase-title');
+ }
+
+ const gridline = [...document.querySelectorAll('div')].find(
+ (element) =>
+ element.childNodes.length === 1 &&
+ element.textContent === '0% gridline',
+ );
+ const gridlineRow = gridline?.parentElement?.parentElement;
+ if (
+ gridlineRow &&
+ !gridlineRow.querySelector('[data-timeline-layer-eye]')
+ ) {
+ state.sequenceRemappingBadFrames?.push(
+ 'missing-gridline-visibility-toggle',
+ );
+ }
+
+ requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ });
+
+ const eyebrow = page.locator(
+ '[data-timeline-marquee-item][title="Eyebrow"]',
+ );
+ await eyebrow.click();
+ await page.keyboard.press('Delete');
+
+ await expect
+ .poll(() => fs.readFileSync(lostNodePathE2eFile, 'utf-8'))
+ .not.toContain('name="Eyebrow"');
+ await expect(eyebrow).toHaveCount(0, {timeout: 30_000});
+ await expect(
+ canvas.getByText('Regional growth', {exact: true}),
+ ).toHaveCount(1);
+ await expect(
+ canvas.getByText('Bars remain visible', {exact: true}),
+ ).toBeVisible();
+ await expect(
+ otherCanvas.getByText('Regional growth', {exact: true}),
+ ).toHaveCount(1);
+ await expect(
+ otherCanvas.getByText('Bars remain visible', {exact: true}),
+ ).toBeVisible();
+ await expect(
+ page.locator('[data-timeline-marquee-item][title="Title"]'),
+ ).toBeVisible();
+ await expect(
+ page.locator('[data-timeline-marquee-item][title="Chart"]'),
+ ).toBeVisible();
+ await expect(gridlineVisibilityToggle).toBeVisible();
+ await expect(otherGridlineVisibilityToggle).toBeVisible();
+
+ await page.getByRole('button', {name: /^Undo/}).click();
+ await expect
+ .poll(() => fs.readFileSync(lostNodePathE2eFile, 'utf-8'))
+ .toContain('name="Eyebrow"');
+ await expect(eyebrow).toBeVisible({timeout: 30_000});
+ await expect(
+ canvas.getByText('Performance overview', {exact: true}),
+ ).toBeVisible();
+ await expect(
+ canvas.getByText('Regional growth', {exact: true}),
+ ).toHaveCount(1);
+ await expect(
+ canvas.getByText('Bars remain visible', {exact: true}),
+ ).toBeVisible();
+ await expect(
+ otherCanvas.getByText('Performance overview', {exact: true}),
+ ).toBeVisible();
+ await expect(
+ otherCanvas.getByText('Regional growth', {exact: true}),
+ ).toHaveCount(1);
+ await expect(
+ otherCanvas.getByText('Bars remain visible', {exact: true}),
+ ).toBeVisible();
+ await expect(gridlineVisibilityToggle).toBeVisible();
+ await expect(otherGridlineVisibilityToggle).toBeVisible();
+
+ await page.getByRole('button', {name: /^Redo/}).click();
+ await expect
+ .poll(() => fs.readFileSync(lostNodePathE2eFile, 'utf-8'))
+ .not.toContain('name="Eyebrow"');
+ await expect(eyebrow).toHaveCount(0, {timeout: 30_000});
+ await expect(
+ canvas.getByText('Regional growth', {exact: true}),
+ ).toHaveCount(1);
+ await expect(
+ canvas.getByText('Bars remain visible', {exact: true}),
+ ).toBeVisible();
+ await expect(
+ otherCanvas.getByText('Regional growth', {exact: true}),
+ ).toHaveCount(1);
+ await expect(
+ otherCanvas.getByText('Bars remain visible', {exact: true}),
+ ).toBeVisible();
+ await expect(gridlineVisibilityToggle).toBeVisible();
+ await expect(otherGridlineVisibilityToggle).toBeVisible();
+ expect(
+ await page.evaluate(
+ () =>
+ (
+ window as typeof window & {
+ sequenceRemappingBadFrames: string[] | null;
+ }
+ ).sequenceRemappingBadFrames ?? [],
+ ),
+ ).toEqual([]);
+ });
+
test('should use standalone and contextual app names in portaled context menus', async ({
context,
page,
diff --git a/packages/example/src/LostNodePathE2e/LostNodePathRepro.tsx b/packages/example/src/LostNodePathE2e/LostNodePathRepro.tsx
index 1a2d350ffe..64f48b6ea2 100644
--- a/packages/example/src/LostNodePathE2e/LostNodePathRepro.tsx
+++ b/packages/example/src/LostNodePathE2e/LostNodePathRepro.tsx
@@ -1,7 +1,12 @@
import {halftone} from '@remotion/effects/halftone';
import {tint} from '@remotion/effects/tint';
-import React from 'react';
-import {AbsoluteFill, Internals, Sequence, useVideoConfig} from 'remotion';
+import {
+ AbsoluteFill,
+ Interactive,
+ Internals,
+ Sequence,
+ useVideoConfig,
+} from 'remotion';
import {SimpleSvg} from './SimpleSvg';
export const LostNodePathRepro: React.FC = () => {
@@ -17,6 +22,16 @@ export const LostNodePathRepro: React.FC = () => {
return (
<AbsoluteFill style={{backgroundColor: 'white'}}>
+ <Interactive.Div name="Eyebrow" style={{textTransform: 'uppercase'}}>
+ Performance overview
+ </Interactive.Div>
+ <Interactive.Div name="Title">Regional growth</Interactive.Div>
+ <Interactive.Div name="Chart">
+ <Interactive.Div name="Bars">Bars remain visible</Interactive.Div>
+ {[0, 25, 50, 75, 100].map((tick) => (
+ <Interactive.Div key={tick} name={`${tick}% gridline`} />
+ ))}
+ </Interactive.Div>
<Sequence
durationInFrames={durationInFrames}
_remotionInternalEffects={memoizedEffects}
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index bad9250fbc..8252b7ba06 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -1,9 +1,15 @@
import {parse} from '@babel/parser';
+import type {JSXOpeningElement} from '@babel/types';
import type {
CanUpdateDefaultPropsResponse,
CompositionComponentInfoRequest,
InsertJsxElementRequest,
+ SequenceNodePathRemapping,
} from '@remotion/studio-shared';
+import * as recast from 'recast';
+import type {SequenceNodePath} from 'remotion';
+import {getNodePathForRecastPath} from './sequence-props';
+import {parseAst} from './sequence-props/parse-ast';
export {findSearchPosition} from './find-search-position';
export {
@@ -1126,13 +1132,19 @@ export const insertSolidIntoSource = ({
};
};
-export const insertSolidIntoProject = <Project extends CodemodProject>({
+export const insertSolidIntoProjectWithNodePathRemappings = <
+ Project extends CodemodProject,
+>({
project,
request,
}: {
project: Project;
request: InsertJsxElementRequest;
-}): Project => {
+}): {
+ project: Project;
+ filePath: string;
+ nodePathRemappings: SequenceNodePathRemapping[];
+} => {
if (request.element.type !== 'solid') {
throw new Error('This codemod only supports adding <Solid>');
}
@@ -1173,16 +1185,80 @@ export const insertSolidIntoProject = <Project extends CodemodProject>({
source: resolved.source,
width: request.element.width,
});
+ const astBefore = parseAst(resolved.source);
+ const astAfter = parseAst(output);
+ const before: Array<{
+ nodePath: SequenceNodePath;
+ signature: string;
+ }> = [];
+ const after: Array<{
+ nodePath: SequenceNodePath;
+ signature: string;
+ }> = [];
+ recast.visit(astBefore, {
+ visitJSXOpeningElement(path) {
+ before.push({
+ nodePath: getNodePathForRecastPath(path, astBefore),
+ signature: recast.print(path.node as JSXOpeningElement).code,
+ });
+ return this.traverse(path);
+ },
+ });
+ recast.visit(astAfter, {
+ visitJSXOpeningElement(path) {
+ after.push({
+ nodePath: getNodePathForRecastPath(path, astAfter),
+ signature: recast.print(path.node as JSXOpeningElement).code,
+ });
+ return this.traverse(path);
+ },
+ });
+
+ let nextAfterIndex = 0;
+ const nodePathRemappings = before.flatMap(
+ ({nodePath, signature}): SequenceNodePathRemapping[] => {
+ const matchedIndex = after.findIndex(
+ (item, index) =>
+ index >= nextAfterIndex && item.signature === signature,
+ );
+ if (matchedIndex === -1) {
+ throw new Error('Could not map JSX node paths after inserting <Solid>');
+ }
+
+ nextAfterIndex = matchedIndex + 1;
+ const newNodePath = after[matchedIndex].nodePath;
+ if (JSON.stringify(nodePath) === JSON.stringify(newNodePath)) {
+ return [];
+ }
+
+ return [{oldNodePath: nodePath, newNodePath}];
+ },
+ );
return {
- ...project,
- files: {
- ...project.files,
- [resolved.filePath]: output,
+ filePath: resolved.filePath,
+ nodePathRemappings,
+ project: {
+ ...project,
+ files: {
+ ...project.files,
+ [resolved.filePath]: output,
+ },
},
};
};
+export const insertSolidIntoProject = <Project extends CodemodProject>({
+ project,
+ request,
+}: {
+ project: Project;
+ request: InsertJsxElementRequest;
+}): Project => {
+ return insertSolidIntoProjectWithNodePathRemappings({project, request})
+ .project;
+};
+
const relativeToRoot = (filePath: string, rootDir: string) => {
const normalizedFile = normalizePath(filePath);
const normalizedRoot = normalizePath(rootDir).replace(/\/$/, '');
diff --git a/packages/studio-codemods/src/sequence-props.ts b/packages/studio-codemods/src/sequence-props.ts
index 78859a26cd..d278f971c8 100644
--- a/packages/studio-codemods/src/sequence-props.ts
+++ b/packages/studio-codemods/src/sequence-props.ts
@@ -740,7 +740,7 @@ const getPropsStatus = (
return props;
};
-const getNodePathForRecastPath = (
+export const getNodePathForRecastPath = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
recastPath: any,
ast: File,
diff --git a/packages/studio-server/src/codemods/delete-jsx-node.ts b/packages/studio-server/src/codemods/delete-jsx-node.ts
index 0e9f54637e..2311d323bb 100644
--- a/packages/studio-server/src/codemods/delete-jsx-node.ts
+++ b/packages/studio-server/src/codemods/delete-jsx-node.ts
@@ -28,6 +28,10 @@ import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import {getAstNodePath} from '../helpers/get-ast-node-path';
import {formatFileContent} from './format-file-content';
+import {
+ captureJsxNodePaths,
+ getNodePathRemappings,
+} from './get-node-path-remappings';
import {parseAst, serializeAst} from './parse-ast';
const {builders: b, namedTypes} = recast.types;
@@ -421,12 +425,17 @@ export const deleteJsxNodes = async ({
formatted: boolean;
nodeLabels: string[];
logLines: number[];
+ nodePathRemappings: Array<{
+ oldNodePath: SequenceNodePath;
+ newNodePath: SequenceNodePath | null;
+ }>;
}> => {
if (nodePaths.length === 0) {
throw new Error('No JSX nodes were specified for deletion');
}
const ast = parseAst(input);
+ const capturedNodePaths = captureJsxNodePaths(ast);
const pathsToDelete = nodePaths.map((nodePath) => {
const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
if (!jsxPath) {
@@ -456,12 +465,18 @@ export const deleteJsxNodes = async ({
input: finalFile,
prettierConfigOverride,
});
+ const nodePathRemappings = getNodePathRemappings({
+ ast,
+ captured: capturedNodePaths,
+ output,
+ });
return {
output,
formatted,
nodeLabels: pathsToDelete.map(({nodeLabel}) => nodeLabel),
logLines: pathsToDelete.map(({logLine}) => logLine),
+ nodePathRemappings,
};
};
diff --git a/packages/studio-server/src/codemods/duplicate-jsx-node.ts b/packages/studio-server/src/codemods/duplicate-jsx-node.ts
index f9f26e0bf5..651b0e05f0 100644
--- a/packages/studio-server/src/codemods/duplicate-jsx-node.ts
+++ b/packages/studio-server/src/codemods/duplicate-jsx-node.ts
@@ -21,6 +21,7 @@ import type {
VariableDeclarator,
} from '@babel/types';
import {cloneNode} from '@babel/types';
+import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import {
@@ -28,6 +29,10 @@ import {
getJsxElementTagLabel,
} from './delete-jsx-node';
import {formatFileContent} from './format-file-content';
+import {
+ captureJsxNodePaths,
+ getNodePathRemappings,
+} from './get-node-path-remappings';
import {parseAst, serializeAst} from './parse-ast';
const {namedTypes} = recast.types;
@@ -429,8 +434,10 @@ export const duplicateJsxNode = async ({
formatted: boolean;
nodeLabel: string;
logLine: number;
+ nodePathRemappings: SequenceNodePathRemapping[];
}> => {
const ast = parseAst(input);
+ const capturedNodePaths = captureJsxNodePaths(ast);
const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
if (!jsxPath) {
throw new Error(
@@ -452,11 +459,17 @@ export const duplicateJsxNode = async ({
input: finalFile,
prettierConfigOverride,
});
+ const nodePathRemappings = getNodePathRemappings({
+ ast,
+ captured: capturedNodePaths,
+ output,
+ });
return {
output,
formatted,
nodeLabel,
logLine,
+ nodePathRemappings,
};
};
diff --git a/packages/studio-server/src/codemods/get-node-path-remappings.ts b/packages/studio-server/src/codemods/get-node-path-remappings.ts
new file mode 100644
index 0000000000..fa2f39d7f5
--- /dev/null
+++ b/packages/studio-server/src/codemods/get-node-path-remappings.ts
@@ -0,0 +1,74 @@
+import type {File, JSXOpeningElement} from '@babel/types';
+import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
+import * as recast from 'recast';
+import type {SequenceNodePath} from 'remotion';
+import {getNodePathForRecastPath} from '../preview-server/routes/can-update-sequence-props';
+import {parseAst} from './parse-ast';
+
+export type CapturedJsxNodePath = {
+ node: JSXOpeningElement;
+ nodePath: SequenceNodePath;
+};
+
+export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {
+ const captured: CapturedJsxNodePath[] = [];
+ recast.visit(ast, {
+ visitJSXOpeningElement(path) {
+ captured.push({
+ node: path.node as JSXOpeningElement,
+ nodePath: getNodePathForRecastPath(path, ast),
+ });
+ return this.traverse(path);
+ },
+ });
+
+ return captured;
+};
+
+export const getNodePathRemappings = ({
+ ast,
+ captured,
+ output,
+}: {
+ ast: File;
+ captured: CapturedJsxNodePath[];
+ output: string;
+}): SequenceNodePathRemapping[] => {
+ const nodesAfterMutation: JSXOpeningElement[] = [];
+ recast.visit(ast, {
+ visitJSXOpeningElement(path) {
+ nodesAfterMutation.push(path.node as JSXOpeningElement);
+ return this.traverse(path);
+ },
+ });
+
+ const finalAst = parseAst(output);
+ const finalNodePaths: SequenceNodePath[] = [];
+ recast.visit(finalAst, {
+ visitJSXOpeningElement(path) {
+ finalNodePaths.push(getNodePathForRecastPath(path, finalAst));
+ return this.traverse(path);
+ },
+ });
+
+ if (nodesAfterMutation.length !== finalNodePaths.length) {
+ throw new Error('Could not map JSX node paths after modifying JSX nodes');
+ }
+
+ const finalNodePathByNode = new Map<JSXOpeningElement, SequenceNodePath>();
+ for (let i = 0; i < nodesAfterMutation.length; i++) {
+ finalNodePathByNode.set(nodesAfterMutation[i], finalNodePaths[i]);
+ }
+
+ return captured.flatMap(({node, nodePath}) => {
+ const newNodePath = finalNodePathByNode.get(node) ?? null;
+ if (
+ newNodePath !== null &&
+ JSON.stringify(nodePath) === JSON.stringify(newNodePath)
+ ) {
+ return [];
+ }
+
+ return [{oldNodePath: nodePath, newNodePath}];
+ });
+};
diff --git a/packages/studio-server/src/codemods/reorder-sequence.ts b/packages/studio-server/src/codemods/reorder-sequence.ts
index eeab1e8681..8d50c59b56 100644
--- a/packages/studio-server/src/codemods/reorder-sequence.ts
+++ b/packages/studio-server/src/codemods/reorder-sequence.ts
@@ -1,5 +1,8 @@
import type {JSXElement, JSXFragment} from '@babel/types';
-import type {ReorderSequencePosition} from '@remotion/studio-shared';
+import type {
+ ReorderSequencePosition,
+ SequenceNodePathRemapping,
+} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import {
@@ -7,6 +10,10 @@ import {
getJsxElementTagLabel,
} from './delete-jsx-node';
import {formatFileContent} from './format-file-content';
+import {
+ captureJsxNodePaths,
+ getNodePathRemappings,
+} from './get-node-path-remappings';
import {parseAst, serializeAst} from './parse-ast';
const {namedTypes} = recast.types;
@@ -47,8 +54,10 @@ export const reorderSequence = async ({
formatted: boolean;
sequenceLabel: string;
logLine: number;
+ nodePathRemappings: SequenceNodePathRemapping[];
}> => {
const ast = parseAst(input);
+ const capturedNodePaths = captureJsxNodePaths(ast);
const sourcePath = findJsxElementPathForDeletion(ast, sourceNodePath);
if (!sourcePath) {
throw new Error(
@@ -113,11 +122,17 @@ export const reorderSequence = async ({
input: finalFile,
prettierConfigOverride,
});
+ const nodePathRemappings = getNodePathRemappings({
+ ast,
+ captured: capturedNodePaths,
+ output,
+ });
return {
output,
formatted,
sequenceLabel,
logLine,
+ nodePathRemappings,
};
};
diff --git a/packages/studio-server/src/codemods/split-jsx-sequence.ts b/packages/studio-server/src/codemods/split-jsx-sequence.ts
index d54006641f..11f5e55af2 100644
--- a/packages/studio-server/src/codemods/split-jsx-sequence.ts
+++ b/packages/studio-server/src/codemods/split-jsx-sequence.ts
@@ -12,6 +12,7 @@ import type {
ReturnStatement,
} from '@babel/types';
import {cloneNode} from '@babel/types';
+import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import {
@@ -19,6 +20,10 @@ import {
getJsxElementTagLabel,
} from './delete-jsx-node';
import {formatFileContent} from './format-file-content';
+import {
+ captureJsxNodePaths,
+ getNodePathRemappings,
+} from './get-node-path-remappings';
import {parseAst, serializeAst} from './parse-ast';
const {builders: b, namedTypes} = recast.types;
@@ -367,12 +372,14 @@ export const splitJsxSequence = async ({
formatted: boolean;
nodeLabel: string;
logLine: number;
+ nodePathRemappings: SequenceNodePathRemapping[];
}> => {
if (!Number.isInteger(splitFrame)) {
throw new Error('Split frame must be an integer');
}
const ast = parseAst(input);
+ const capturedNodePaths = captureJsxNodePaths(ast);
const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
if (!jsxPath) {
throw new Error(
@@ -454,6 +461,11 @@ export const splitJsxSequence = async ({
input: finalFile,
prettierConfigOverride,
});
+ const nodePathRemappings = getNodePathRemappings({
+ ast,
+ captured: capturedNodePaths,
+ output,
+ });
return {
output,
@@ -463,5 +475,6 @@ export const splitJsxSequence = async ({
jsxElement.openingElement.loc?.start.line ??
jsxElement.loc?.start.line ??
1,
+ nodePathRemappings,
};
};
diff --git a/packages/studio-server/src/file-watcher.ts b/packages/studio-server/src/file-watcher.ts
index 530fb51642..89cc6157cb 100644
--- a/packages/studio-server/src/file-watcher.ts
+++ b/packages/studio-server/src/file-watcher.ts
@@ -1,9 +1,25 @@
import fs, {readFileSync, writeFileSync} from 'node:fs';
+export type FileChangeMetadata = {
+ skipSequencePropsUpdate: boolean;
+};
+
+type WriteFileAndNotifyFileWatchersOptions = {
+ file: string;
+ content: string;
+ originatorClientId: string | undefined;
+ metadata: FileChangeMetadata | null;
+};
+
export type FileChangeEvent =
| {type: 'created'; content: string; originatorClientId: string | undefined}
| {type: 'deleted'}
- | {type: 'changed'; content: string; originatorClientId: string | undefined};
+ | {
+ type: 'changed';
+ content: string;
+ originatorClientId: string | undefined;
+ skipSequencePropsUpdate: boolean;
+ };
type OnChange = (event: FileChangeEvent) => void;
@@ -33,9 +49,7 @@ export type FileWatcherRegistry = {
unwatch: () => void;
};
writeFileAndNotifyFileWatchers: (
- file: string,
- content: string,
- originatorClientId: string | undefined,
+ options: WriteFileAndNotifyFileWatchersOptions,
) => void;
};
@@ -121,7 +135,12 @@ export const createFileWatcherRegistry = (): FileWatcherRegistry => {
}
shared.lastKnownContent = content;
- event = {type: 'changed', content, originatorClientId: undefined};
+ event = {
+ type: 'changed',
+ content,
+ originatorClientId: undefined,
+ skipSequencePropsUpdate: false,
+ };
}
if (!event) {
@@ -148,11 +167,12 @@ export const createFileWatcherRegistry = (): FileWatcherRegistry => {
};
};
- const _writeFileAndNotifyFileWatchers = (
- file: string,
- content: string,
- originatorClientId: string | undefined,
- ) => {
+ const _writeFileAndNotifyFileWatchers = ({
+ file,
+ content,
+ originatorClientId,
+ metadata,
+ }: WriteFileAndNotifyFileWatchersOptions) => {
writeFileSync(file, content);
const shared = sharedWatchers.get(getRegistryKey(file, false));
@@ -164,7 +184,12 @@ export const createFileWatcherRegistry = (): FileWatcherRegistry => {
shared.existedBefore = true;
for (const subscriber of shared.subscribers) {
- subscriber({type: 'changed', content, originatorClientId});
+ subscriber({
+ type: 'changed',
+ content,
+ originatorClientId,
+ skipSequencePropsUpdate: metadata?.skipSequencePropsUpdate ?? false,
+ });
}
};
@@ -207,14 +232,10 @@ export const installFileWatcher: FileWatcherRegistry['installFileWatcher'] = (
};
export const writeFileAndNotifyFileWatchers: FileWatcherRegistry['writeFileAndNotifyFileWatchers'] =
- (file, content, originatorClientId) => {
+ (options) => {
if (!currentRegistry) {
return;
}
- getFileWatcherRegistry().writeFileAndNotifyFileWatchers(
- file,
- content,
- originatorClientId,
- );
+ getFileWatcherRegistry().writeFileAndNotifyFileWatchers(options);
};
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index 8de59d8371..b436cdfedf 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -16,17 +16,21 @@ import type {
ObjectProperty,
VariableDeclaration,
} from '@babel/types';
-import {insertSolidIntoSource} from '@remotion/studio-codemods';
import type {ComponentProp} from '@remotion/studio-protocol';
import {
isUrl,
type InsertableCompositionElement,
type InsertableCompositionElementPosition,
+ type SequenceNodePathRemapping,
} from '@remotion/studio-shared';
import type {namedTypes} from 'ast-types';
import * as recast from 'recast';
import {NoReactInternals} from 'remotion/no-react';
import {formatFileContent} from '../codemods/format-file-content';
+import {
+ captureJsxNodePaths,
+ getNodePathRemappings,
+} from '../codemods/get-node-path-remappings';
import {parseAst, serializeAst} from '../codemods/parse-ast';
import {stripParenthesizedExtra} from '../codemods/strip-parenthesized-extra';
import {parseValueExpression} from '../codemods/update-nested-prop';
@@ -2304,6 +2308,7 @@ export const insertJsxElementIntoComposition = async ({
output: string;
formatted: boolean;
logLine: number;
+ nodePathRemappings: SequenceNodePathRemapping[];
}> => {
const location = await resolveCompositionComponentWithFile({
remotionRoot,
@@ -2320,80 +2325,71 @@ export const insertJsxElementIntoComposition = async ({
remotionRoot,
fileName: location.fileName,
});
- let finalFile: string;
- let logLine: number;
- if (element.type === 'solid' && from === null && wrapInSequence === null) {
- const inserted = insertSolidIntoSource({
- exportName: location.exportName,
- height: element.height,
- position: element.position,
- source: input,
- width: element.width,
- });
- finalFile = inserted.output;
- logLine = inserted.line;
- } else {
- const ast = parseAst(input);
- if (
- element.type === 'composition' &&
- element.compositionId === compositionId
- ) {
- throw new Error('Cannot insert a composition into itself');
- }
+ const ast = parseAst(input);
+ const capturedNodePaths = captureJsxNodePaths(ast);
+ if (
+ element.type === 'composition' &&
+ element.compositionId === compositionId
+ ) {
+ throw new Error('Cannot insert a composition into itself');
+ }
- const sequenceWrapper =
- element.type === 'composition'
- ? {
- dimensions: {width: element.width, height: element.height},
- durationInFrames: element.durationInFrames,
- name: element.compositionId,
+ const sequenceWrapper =
+ element.type === 'composition'
+ ? {
+ dimensions: {width: element.width, height: element.height},
+ durationInFrames: element.durationInFrames,
+ name: element.compositionId,
+ position: element.position,
+ from,
+ }
+ : from === null ||
+ element.type === 'asset' ||
+ element.type === 'svg' ||
+ element.type === 'component'
+ ? wrapInSequence
+ : {
+ dimensions: null,
+ durationInFrames: null,
+ name: null,
position: element.position,
from,
- }
- : from === null ||
- element.type === 'asset' ||
- element.type === 'svg' ||
- element.type === 'component'
- ? wrapInSequence
- : {
- dimensions: null,
- durationInFrames: null,
- name: null,
- position: element.position,
- from,
- };
- const elementToInsert = await createInsertableJsxElement({
- addPositionStyleToComponent: sequenceWrapper === null,
- ast,
- destinationFileName: location.fileName,
- element,
- from,
- remotionRoot,
- });
- const finalElementToInsert = sequenceWrapper
- ? createSequenceWrappedElement({
- child: elementToInsert,
- dimensions: sequenceWrapper.dimensions,
- durationInFrames: sequenceWrapper.durationInFrames ?? null,
- from: sequenceWrapper.from,
- name: sequenceWrapper.name,
- position: sequenceWrapper.position,
- sequenceLocalName: ensureSequenceImport(ast),
- })
- : elementToInsert;
- logLine = addElementToComponentRoot({
- ast,
- exportName: location.exportName,
- element: finalElementToInsert,
- });
-
- finalFile = serializeAst(ast);
- }
+ };
+ const elementToInsert = await createInsertableJsxElement({
+ addPositionStyleToComponent: sequenceWrapper === null,
+ ast,
+ destinationFileName: location.fileName,
+ element,
+ from,
+ remotionRoot,
+ });
+ const finalElementToInsert = sequenceWrapper
+ ? createSequenceWrappedElement({
+ child: elementToInsert,
+ dimensions: sequenceWrapper.dimensions,
+ durationInFrames: sequenceWrapper.durationInFrames ?? null,
+ from: sequenceWrapper.from,
+ name: sequenceWrapper.name,
+ position: sequenceWrapper.position,
+ sequenceLocalName: ensureSequenceImport(ast),
+ })
+ : elementToInsert;
+ const logLine = addElementToComponentRoot({
+ ast,
+ exportName: location.exportName,
+ element: finalElementToInsert,
+ });
+ const finalFile = serializeAst(ast);
const {output, formatted} = await formatFileContent({
input: finalFile,
prettierConfigOverride,
});
+ const nodePathRemappings = getNodePathRemappings({
+ ast,
+ captured: capturedNodePaths,
+ output,
+ });
return {
fileName: location.fileName,
@@ -2402,5 +2398,6 @@ export const insertJsxElementIntoComposition = async ({
output,
formatted,
logLine,
+ nodePathRemappings,
};
};
diff --git a/packages/studio-server/src/preview-server/live-events.ts b/packages/studio-server/src/preview-server/live-events.ts
index ffedb04ea3..174ef41b5f 100644
--- a/packages/studio-server/src/preview-server/live-events.ts
+++ b/packages/studio-server/src/preview-server/live-events.ts
@@ -157,6 +157,9 @@ export const waitForLiveEventsListener = (): Promise<LiveEventsServer> => {
});
};
+export const getLiveEventsListener = (): LiveEventsServer | null =>
+ liveEventsListener;
+
export const setLiveEventsListener = (listener: LiveEventsServer) => {
liveEventsListener = listener;
waiters.forEach((w) => w(listener));
diff --git a/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts b/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts
index a97804b889..85ad4d1782 100644
--- a/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts
+++ b/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts
@@ -98,10 +98,16 @@ export const addEffectKeyframeHandler: ApiHandler<
},
entryType: 'effect-props',
suppressHmrOnFileRestore: true,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(absolutePath);
suppressBundlerUpdateForFile(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: null,
+ });
logEffectUpdate({
fileRelativeToRoot,
diff --git a/packages/studio-server/src/preview-server/routes/add-effect.ts b/packages/studio-server/src/preview-server/routes/add-effect.ts
index 46de54c77a..fa5791546e 100644
--- a/packages/studio-server/src/preview-server/routes/add-effect.ts
+++ b/packages/studio-server/src/preview-server/routes/add-effect.ts
@@ -69,9 +69,15 @@ export const addEffectHandler: ApiHandler<
},
entryType: 'add-effect',
suppressHmrOnFileRestore: false,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: null,
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
diff --git a/packages/studio-server/src/preview-server/routes/add-keyframes.ts b/packages/studio-server/src/preview-server/routes/add-keyframes.ts
index 7dd562c16f..c213d0823c 100644
--- a/packages/studio-server/src/preview-server/routes/add-keyframes.ts
+++ b/packages/studio-server/src/preview-server/routes/add-keyframes.ts
@@ -262,7 +262,10 @@ export const addKeyframes = async ({
}
pushTransactionToUndoStack({
- snapshots,
+ snapshots: snapshots.map((snapshot) => ({
+ ...snapshot,
+ nodePathRemappings: null,
+ })),
logLevel,
remotionRoot,
description: getBatchDescription({totalKeyframes, firstKeyframe}),
@@ -280,11 +283,12 @@ export const addKeyframes = async ({
for (const snapshot of snapshots) {
suppressUndoStackInvalidation(snapshot.filePath);
suppressBundlerUpdateForFile(snapshot.filePath);
- writeFileAndNotifyFileWatchers(
- snapshot.filePath,
- snapshot.newContents,
- clientId,
- );
+ writeFileAndNotifyFileWatchers({
+ file: snapshot.filePath,
+ content: snapshot.newContents,
+ originatorClientId: clientId,
+ metadata: null,
+ });
}
for (const log of sequenceLogs) {
diff --git a/packages/studio-server/src/preview-server/routes/add-sequence-keyframe.ts b/packages/studio-server/src/preview-server/routes/add-sequence-keyframe.ts
index 422efc42c4..1edb139479 100644
--- a/packages/studio-server/src/preview-server/routes/add-sequence-keyframe.ts
+++ b/packages/studio-server/src/preview-server/routes/add-sequence-keyframe.ts
@@ -84,10 +84,16 @@ export const addSequenceKeyframeHandler: ApiHandler<
},
entryType: 'sequence-props',
suppressHmrOnFileRestore: true,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(absolutePath);
suppressBundlerUpdateForFile(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: null,
+ });
logUpdate({
fileRelativeToRoot,
diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
index a49e8c21e4..9b635fa245 100644
--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts
+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
@@ -249,6 +249,7 @@ export const applyCodemodHandler: ApiHandler<
oldContents: input,
newContents: null,
logLine,
+ nodePathRemappings: null,
},
];
let componentFilePath: string | null = null;
@@ -268,6 +269,7 @@ export const applyCodemodHandler: ApiHandler<
oldContents: null,
newContents: componentFileContents,
logLine: 1,
+ nodePathRemappings: null,
});
pushTransactionToUndoStack({
snapshots,
@@ -294,6 +296,7 @@ export const applyCodemodHandler: ApiHandler<
},
entryType,
suppressHmrOnFileRestore: false,
+ nodePathRemappings: null,
});
}
@@ -302,13 +305,19 @@ export const applyCodemodHandler: ApiHandler<
suppressUndoStackInvalidation(componentFilePath);
}
- writeFileAndNotifyFileWatchers(filePath, formatted, undefined);
+ writeFileAndNotifyFileWatchers({
+ file: filePath,
+ content: formatted,
+ originatorClientId: undefined,
+ metadata: null,
+ });
if (componentFilePath && componentFileContents !== null) {
- writeFileAndNotifyFileWatchers(
- componentFilePath,
- componentFileContents,
- undefined,
- );
+ writeFileAndNotifyFileWatchers({
+ file: componentFilePath,
+ content: componentFileContents,
+ originatorClientId: undefined,
+ metadata: null,
+ });
}
const logMessage = getCodemodLogMessage(codemod);
diff --git a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts
index 2a9d09d4c1..c3ee69dfe5 100644
--- a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts
+++ b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts
@@ -115,10 +115,16 @@ export const applyVisualControlHandler: ApiHandler<
},
entryType: 'visual-control',
suppressHmrOnFileRestore: true,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(absolutePath);
suppressBundlerUpdateForFile(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, undefined);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: undefined,
+ metadata: null,
+ });
waitForLiveEventsListener().then((listener) => {
listener.sendEventToClient({
diff --git a/packages/studio-server/src/preview-server/routes/batch-update-keyframe-settings.ts b/packages/studio-server/src/preview-server/routes/batch-update-keyframe-settings.ts
index 242261ea55..694efe79f9 100644
--- a/packages/studio-server/src/preview-server/routes/batch-update-keyframe-settings.ts
+++ b/packages/studio-server/src/preview-server/routes/batch-update-keyframe-settings.ts
@@ -215,7 +215,10 @@ export const batchUpdateKeyframeSettings = async ({
}
pushTransactionToUndoStack({
- snapshots,
+ snapshots: snapshots.map((snapshot) => ({
+ ...snapshot,
+ nodePathRemappings: null,
+ })),
logLevel,
remotionRoot,
description:
@@ -235,11 +238,12 @@ export const batchUpdateKeyframeSettings = async ({
for (const snapshot of snapshots) {
suppressUndoStackInvalidation(snapshot.filePath);
suppressBundlerUpdateForFile(snapshot.filePath);
- writeFileAndNotifyFileWatchers(
- snapshot.filePath,
- snapshot.newContents,
- clientId,
- );
+ writeFileAndNotifyFileWatchers({
+ file: snapshot.filePath,
+ content: snapshot.newContents,
+ originatorClientId: clientId,
+ metadata: null,
+ });
}
for (const log of sequenceLogs) {
diff --git a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
index 4c991a15f3..de2420d560 100644
--- a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
+++ b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
@@ -757,7 +757,7 @@ const getPropsStatus = (
return props;
};
-const getNodePathForRecastPath = (
+export const getNodePathForRecastPath = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
recastPath: any,
ast: File,
diff --git a/packages/studio-server/src/preview-server/routes/delete-effect.ts b/packages/studio-server/src/preview-server/routes/delete-effect.ts
index 72f85472a6..092e72d82b 100644
--- a/packages/studio-server/src/preview-server/routes/delete-effect.ts
+++ b/packages/studio-server/src/preview-server/routes/delete-effect.ts
@@ -104,13 +104,15 @@ export const deleteEffectHandler: ApiHandler<
},
entryType: 'delete-effect',
suppressHmrOnFileRestore: false,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(update.absolutePath);
- writeFileAndNotifyFileWatchers(
- update.absolutePath,
- update.output,
- undefined,
- );
+ writeFileAndNotifyFileWatchers({
+ file: update.absolutePath,
+ content: update.output,
+ originatorClientId: undefined,
+ metadata: null,
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
diff --git a/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts b/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts
index 971cd13cb1..1dabb2b3d4 100644
--- a/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts
+++ b/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts
@@ -9,6 +9,7 @@ import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
import {formatLogFileLocation} from '../format-log-file-location';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
printUndoHint,
pushToUndoStack,
@@ -57,7 +58,7 @@ export const deleteJsxNodeHandler: ApiHandler<
const fileContents = readFileSync(absolutePath, 'utf-8');
- const {output, formatted, nodeLabels, logLines} =
+ const {output, formatted, nodeLabels, logLines, nodePathRemappings} =
await deleteJsxNodes({
input: fileContents,
nodePaths: fileItems.map((item) => item.nodePath),
@@ -70,10 +71,18 @@ export const deleteJsxNodeHandler: ApiHandler<
output,
formatted,
nodeLabels,
+ nodePathRemappings,
logLine: Math.min(...logLines),
};
}),
);
+ const nodePathMutation = broadcastSequenceNodePathMutation(
+ updates.map((update) => ({
+ absolutePath: update.absolutePath,
+ remappings: update.nodePathRemappings,
+ restoredNodePaths: [],
+ })),
+ );
for (const update of updates) {
const deletedNodeDescription = getDeletedNodeDescription(
@@ -93,13 +102,15 @@ export const deleteJsxNodeHandler: ApiHandler<
},
entryType: 'delete-jsx-node',
suppressHmrOnFileRestore: false,
+ nodePathRemappings: update.nodePathRemappings,
});
suppressUndoStackInvalidation(update.absolutePath);
- writeFileAndNotifyFileWatchers(
- update.absolutePath,
- update.output,
- undefined,
- );
+ writeFileAndNotifyFileWatchers({
+ file: update.absolutePath,
+ content: update.output,
+ originatorClientId: undefined,
+ metadata: {skipSequencePropsUpdate: true},
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
@@ -124,6 +135,7 @@ export const deleteJsxNodeHandler: ApiHandler<
return {
success: true,
+ nodePathMutation,
};
} catch (err) {
return {
diff --git a/packages/studio-server/src/preview-server/routes/delete-keyframes.ts b/packages/studio-server/src/preview-server/routes/delete-keyframes.ts
index 851353d3cd..652c834bb9 100644
--- a/packages/studio-server/src/preview-server/routes/delete-keyframes.ts
+++ b/packages/studio-server/src/preview-server/routes/delete-keyframes.ts
@@ -276,7 +276,10 @@ export const deleteKeyframes = async ({
}
pushTransactionToUndoStack({
- snapshots,
+ snapshots: snapshots.map((snapshot) => ({
+ ...snapshot,
+ nodePathRemappings: null,
+ })),
logLevel,
remotionRoot,
description: getBatchDescription({totalKeyframes, firstKeyframe}),
@@ -292,11 +295,12 @@ export const deleteKeyframes = async ({
for (const snapshot of snapshots) {
suppressUndoStackInvalidation(snapshot.filePath);
suppressBundlerUpdateForFile(snapshot.filePath);
- writeFileAndNotifyFileWatchers(
- snapshot.filePath,
- snapshot.newContents,
- clientId,
- );
+ writeFileAndNotifyFileWatchers({
+ file: snapshot.filePath,
+ content: snapshot.newContents,
+ originatorClientId: clientId,
+ metadata: null,
+ });
}
for (const log of sequenceLogs) {
diff --git a/packages/studio-server/src/preview-server/routes/duplicate-effect.ts b/packages/studio-server/src/preview-server/routes/duplicate-effect.ts
index 3e9dc2b18b..46c2809c3e 100644
--- a/packages/studio-server/src/preview-server/routes/duplicate-effect.ts
+++ b/packages/studio-server/src/preview-server/routes/duplicate-effect.ts
@@ -96,13 +96,15 @@ export const duplicateEffectHandler: ApiHandler<
},
entryType: 'duplicate-effect',
suppressHmrOnFileRestore: false,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(update.absolutePath);
- writeFileAndNotifyFileWatchers(
- update.absolutePath,
- update.output,
- undefined,
- );
+ writeFileAndNotifyFileWatchers({
+ file: update.absolutePath,
+ content: update.output,
+ originatorClientId: undefined,
+ metadata: null,
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
diff --git a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
index c50931503a..2703d39fc7 100644
--- a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
+++ b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
@@ -9,6 +9,7 @@ import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
import {formatLogFileLocation} from '../format-log-file-location';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
printUndoHint,
pushToUndoStack,
@@ -35,10 +36,15 @@ export const duplicateJsxNodeHandler: ApiHandler<
const fileContents = readFileSync(absolutePath, 'utf-8');
- const {output, formatted, nodeLabel, logLine} = await duplicateJsxNode({
- input: fileContents,
- nodePath,
- });
+ const {output, formatted, nodeLabel, logLine, nodePathRemappings} =
+ await duplicateJsxNode({input: fileContents, nodePath});
+ const nodePathMutation = broadcastSequenceNodePathMutation([
+ {
+ absolutePath,
+ remappings: nodePathRemappings,
+ restoredNodePaths: [],
+ },
+ ]);
pushToUndoStack({
filePath: absolutePath,
@@ -53,9 +59,15 @@ export const duplicateJsxNodeHandler: ApiHandler<
},
entryType: 'duplicate-jsx-node',
suppressHmrOnFileRestore: false,
+ nodePathRemappings,
});
suppressUndoStackInvalidation(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, undefined);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: undefined,
+ metadata: {skipSequencePropsUpdate: true},
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
@@ -79,6 +91,7 @@ export const duplicateJsxNodeHandler: ApiHandler<
return {
success: true,
+ nodePathMutation,
};
} catch (err) {
return {
diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.ts
index 410a2c61b0..975111ff42 100644
--- a/packages/studio-server/src/preview-server/routes/insert-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts
@@ -8,6 +8,7 @@ import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {insertJsxElementIntoComposition} from '../../helpers/resolve-composition-component';
import type {ApiHandler} from '../api-types';
import {formatLogFileLocation} from '../format-log-file-location';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
printUndoHint,
pushTransactionToUndoStack,
@@ -166,7 +167,6 @@ export const insertElementHandler: ApiHandler<
position,
},
});
-
const finalPlan = await getElementInstallPlan({
compositionFile,
compositionId,
@@ -191,6 +191,14 @@ export const insertElementHandler: ApiHandler<
throw new Error('Element source changed during installation');
}
+ const nodePathMutation = broadcastSequenceNodePathMutation([
+ {
+ absolutePath: inserted.fileName,
+ remappings: inserted.nodePathRemappings,
+ restoredNodePaths: [],
+ },
+ ]);
+
pushTransactionToUndoStack({
snapshots: [
...(shouldWriteElementFile
@@ -200,6 +208,7 @@ export const insertElementHandler: ApiHandler<
oldContents: plan.existingElementSource,
newContents: element.sourceCode,
logLine: 1,
+ nodePathRemappings: null,
},
]
: []),
@@ -208,6 +217,7 @@ export const insertElementHandler: ApiHandler<
oldContents: inserted.oldContents,
newContents: inserted.output,
logLine: inserted.logLine,
+ nodePathRemappings: inserted.nodePathRemappings,
},
],
logLevel,
@@ -226,18 +236,20 @@ export const insertElementHandler: ApiHandler<
suppressUndoStackInvalidation(inserted.fileName);
if (shouldWriteElementFile) {
- writeFileAndNotifyFileWatchers(
- plan.elementFileName,
- element.sourceCode,
- undefined,
- );
+ writeFileAndNotifyFileWatchers({
+ file: plan.elementFileName,
+ content: element.sourceCode,
+ originatorClientId: undefined,
+ metadata: null,
+ });
}
- writeFileAndNotifyFileWatchers(
- inserted.fileName,
- inserted.output,
- undefined,
- );
+ writeFileAndNotifyFileWatchers({
+ file: inserted.fileName,
+ content: inserted.output,
+ originatorClientId: undefined,
+ metadata: {skipSequencePropsUpdate: true},
+ });
const compositionLocationLabel = formatLogFileLocation({
remotionRoot,
@@ -268,7 +280,7 @@ export const insertElementHandler: ApiHandler<
printUndoHint(logLevel);
- return {success: true};
+ return {success: true, nodePathMutation};
} catch (err) {
return {
success: false,
diff --git a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
index d30da18537..8077f7e749 100644
--- a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
@@ -12,6 +12,7 @@ import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {insertJsxElementIntoComposition} from '../../helpers/resolve-composition-component';
import type {ApiHandler} from '../api-types';
import {formatLogFileLocation} from '../format-log-file-location';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
printUndoHint,
pushToUndoStack,
@@ -239,15 +240,29 @@ export const insertJsxElementHandler: ApiHandler<
`[insert-jsx-element] Received request for compositionFile="${compositionFile}" compositionId="${compositionId}" element="${element.type}"`,
);
- const {fileName, source, oldContents, output, formatted, logLine} =
- await insertJsxElementIntoComposition({
- remotionRoot,
- compositionFile,
- compositionId,
- element,
- from,
- prettierConfigOverride: null,
- });
+ const {
+ fileName,
+ source,
+ oldContents,
+ output,
+ formatted,
+ logLine,
+ nodePathRemappings,
+ } = await insertJsxElementIntoComposition({
+ remotionRoot,
+ compositionFile,
+ compositionId,
+ element,
+ from,
+ prettierConfigOverride: null,
+ });
+ const nodePathMutation = broadcastSequenceNodePathMutation([
+ {
+ absolutePath: fileName,
+ remappings: nodePathRemappings,
+ restoredNodePaths: [],
+ },
+ ]);
pushToUndoStack({
filePath: fileName,
@@ -262,9 +277,15 @@ export const insertJsxElementHandler: ApiHandler<
},
entryType: 'insert-jsx-element',
suppressHmrOnFileRestore: false,
+ nodePathRemappings,
});
suppressUndoStackInvalidation(fileName);
- writeFileAndNotifyFileWatchers(fileName, output, undefined);
+ writeFileAndNotifyFileWatchers({
+ file: fileName,
+ content: output,
+ originatorClientId: undefined,
+ metadata: {skipSequencePropsUpdate: true},
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
@@ -288,6 +309,7 @@ export const insertJsxElementHandler: ApiHandler<
return {
success: true,
+ nodePathMutation,
};
} catch (err) {
return {
diff --git a/packages/studio-server/src/preview-server/routes/move-keyframes.ts b/packages/studio-server/src/preview-server/routes/move-keyframes.ts
index 1698d692e4..10f9d8364f 100644
--- a/packages/studio-server/src/preview-server/routes/move-keyframes.ts
+++ b/packages/studio-server/src/preview-server/routes/move-keyframes.ts
@@ -288,7 +288,10 @@ export const moveKeyframes = async ({
}
pushTransactionToUndoStack({
- snapshots,
+ snapshots: snapshots.map((snapshot) => ({
+ ...snapshot,
+ nodePathRemappings: null,
+ })),
logLevel,
remotionRoot,
description: getBatchDescription({totalKeyframes, firstKeyframe}),
@@ -304,11 +307,12 @@ export const moveKeyframes = async ({
for (const snapshot of snapshots) {
suppressUndoStackInvalidation(snapshot.filePath);
suppressBundlerUpdateForFile(snapshot.filePath);
- writeFileAndNotifyFileWatchers(
- snapshot.filePath,
- snapshot.newContents,
- clientId,
- );
+ writeFileAndNotifyFileWatchers({
+ file: snapshot.filePath,
+ content: snapshot.newContents,
+ originatorClientId: clientId,
+ metadata: null,
+ });
}
for (const log of sequenceLogs) {
diff --git a/packages/studio-server/src/preview-server/routes/paste-effects.ts b/packages/studio-server/src/preview-server/routes/paste-effects.ts
index 562e7c039a..39e9f814ad 100644
--- a/packages/studio-server/src/preview-server/routes/paste-effects.ts
+++ b/packages/studio-server/src/preview-server/routes/paste-effects.ts
@@ -83,9 +83,15 @@ export const pasteEffectsHandler: ApiHandler<
},
entryType: 'paste-effects',
suppressHmrOnFileRestore: false,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: null,
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
diff --git a/packages/studio-server/src/preview-server/routes/reorder-effect.ts b/packages/studio-server/src/preview-server/routes/reorder-effect.ts
index 5a478ff728..a375cbcada 100644
--- a/packages/studio-server/src/preview-server/routes/reorder-effect.ts
+++ b/packages/studio-server/src/preview-server/routes/reorder-effect.ts
@@ -60,9 +60,15 @@ export const reorderEffectHandler: ApiHandler<
},
entryType: 'reorder-effect',
suppressHmrOnFileRestore: false,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: null,
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
diff --git a/packages/studio-server/src/preview-server/routes/reorder-sequence.ts b/packages/studio-server/src/preview-server/routes/reorder-sequence.ts
index a0de5cc149..70e11eb59c 100644
--- a/packages/studio-server/src/preview-server/routes/reorder-sequence.ts
+++ b/packages/studio-server/src/preview-server/routes/reorder-sequence.ts
@@ -9,6 +9,7 @@ import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
import {formatLogFileLocation} from '../format-log-file-location';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
printUndoHint,
pushToUndoStack,
@@ -40,14 +41,20 @@ export const reorderSequenceHandler: ApiHandler<
});
const fileContents = readFileSync(absolutePath, 'utf-8');
- const {output, formatted, sequenceLabel, logLine} = await reorderSequence(
- {
+ const {output, formatted, sequenceLabel, logLine, nodePathRemappings} =
+ await reorderSequence({
input: fileContents,
sourceNodePath: sourceNodePath.nodePath,
targetNodePath: targetNodePath.nodePath,
position,
+ });
+ const nodePathMutation = broadcastSequenceNodePathMutation([
+ {
+ absolutePath,
+ remappings: nodePathRemappings,
+ restoredNodePaths: [],
},
- );
+ ]);
pushToUndoStack({
filePath: absolutePath,
@@ -62,9 +69,15 @@ export const reorderSequenceHandler: ApiHandler<
},
entryType: 'reorder-sequence',
suppressHmrOnFileRestore: false,
+ nodePathRemappings,
});
suppressUndoStackInvalidation(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: {skipSequencePropsUpdate: true},
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
@@ -88,6 +101,7 @@ export const reorderSequenceHandler: ApiHandler<
return {
success: true,
+ nodePathMutation,
};
} catch (err) {
return {
diff --git a/packages/studio-server/src/preview-server/routes/save-effect-props.ts b/packages/studio-server/src/preview-server/routes/save-effect-props.ts
index d9f7fec27a..8a09cb87ca 100644
--- a/packages/studio-server/src/preview-server/routes/save-effect-props.ts
+++ b/packages/studio-server/src/preview-server/routes/save-effect-props.ts
@@ -136,10 +136,16 @@ export const saveEffectPropsHandler: ApiHandler<
},
entryType: 'effect-props',
suppressHmrOnFileRestore: true,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(absolutePath);
suppressBundlerUpdateForFile(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: null,
+ });
logEffectUpdate({
fileRelativeToRoot,
diff --git a/packages/studio-server/src/preview-server/routes/save-multiple-effect-props.ts b/packages/studio-server/src/preview-server/routes/save-multiple-effect-props.ts
index 202e67a82f..7912fa0f10 100644
--- a/packages/studio-server/src/preview-server/routes/save-multiple-effect-props.ts
+++ b/packages/studio-server/src/preview-server/routes/save-multiple-effect-props.ts
@@ -150,7 +150,10 @@ export const saveMultipleEffectPropsHandler: ApiHandler<
}
pushTransactionToUndoStack({
- snapshots,
+ snapshots: snapshots.map((snapshot) => ({
+ ...snapshot,
+ nodePathRemappings: null,
+ })),
logLevel,
remotionRoot,
description: {
@@ -164,7 +167,12 @@ export const saveMultipleEffectPropsHandler: ApiHandler<
for (const [absolutePath, output] of outputByPath) {
suppressUndoStackInvalidation(absolutePath);
suppressBundlerUpdateForFile(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: null,
+ });
}
for (const index of edits.keys()) {
diff --git a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts
index 60c49e8a29..bf0fc32fd6 100644
--- a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts
+++ b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts
@@ -558,7 +558,10 @@ export const saveSequencePropsHandler: ApiHandler<
shouldSuppressHmrForSequencePropEdits(edits);
pushTransactionToUndoStack({
- snapshots,
+ snapshots: snapshots.map((snapshot) => ({
+ ...snapshot,
+ nodePathRemappings: null,
+ })),
logLevel,
remotionRoot,
description: {undoMessage, redoMessage},
@@ -572,7 +575,12 @@ export const saveSequencePropsHandler: ApiHandler<
suppressBundlerUpdateForFile(absolutePath);
}
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: null,
+ });
}
for (const {edits: groupEdits, fileRelativeToRoot} of editGroups.values()) {
diff --git a/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts b/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts
index e2e02c61f7..40377401cc 100644
--- a/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts
+++ b/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts
@@ -9,6 +9,7 @@ import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
import {formatLogFileLocation} from '../format-log-file-location';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
printUndoHint,
pushToUndoStack,
@@ -35,11 +36,15 @@ export const splitJsxSequenceHandler: ApiHandler<
const fileContents = readFileSync(absolutePath, 'utf-8');
- const {output, formatted, nodeLabel, logLine} = await splitJsxSequence({
- input: fileContents,
- nodePath,
- splitFrame,
- });
+ const {output, formatted, nodeLabel, logLine, nodePathRemappings} =
+ await splitJsxSequence({input: fileContents, nodePath, splitFrame});
+ const nodePathMutation = broadcastSequenceNodePathMutation([
+ {
+ absolutePath,
+ remappings: nodePathRemappings,
+ restoredNodePaths: [],
+ },
+ ]);
pushToUndoStack({
filePath: absolutePath,
@@ -54,9 +59,15 @@ export const splitJsxSequenceHandler: ApiHandler<
},
entryType: 'split-jsx-sequence',
suppressHmrOnFileRestore: false,
+ nodePathRemappings,
});
suppressUndoStackInvalidation(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, undefined);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: undefined,
+ metadata: {skipSequencePropsUpdate: true},
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
@@ -84,6 +95,7 @@ export const splitJsxSequenceHandler: ApiHandler<
return {
success: true,
+ nodePathMutation,
};
} catch (err) {
return {
diff --git a/packages/studio-server/src/preview-server/routes/update-config.ts b/packages/studio-server/src/preview-server/routes/update-config.ts
index 8d6a2b7fd6..a0f4b875d9 100644
--- a/packages/studio-server/src/preview-server/routes/update-config.ts
+++ b/packages/studio-server/src/preview-server/routes/update-config.ts
@@ -211,11 +211,12 @@ export const updateConfigHandler: ApiHandler<
}
const configContents = readFileSync(configFile, 'utf8');
- writeFileAndNotifyFileWatchers(
- configFile,
- updateConfigFile({configContents, updates: input.updates}),
- input.clientId,
- );
+ writeFileAndNotifyFileWatchers({
+ file: configFile,
+ content: updateConfigFile({configContents, updates: input.updates}),
+ originatorClientId: input.clientId,
+ metadata: null,
+ });
return {success: true};
};
diff --git a/packages/studio-server/src/preview-server/routes/update-default-props.ts b/packages/studio-server/src/preview-server/routes/update-default-props.ts
index d75527f583..655a7063d2 100644
--- a/packages/studio-server/src/preview-server/routes/update-default-props.ts
+++ b/packages/studio-server/src/preview-server/routes/update-default-props.ts
@@ -69,10 +69,16 @@ export const updateDefaultPropsHandler: ApiHandler<
},
entryType: 'default-props',
suppressHmrOnFileRestore: true,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(projectInfo.rootFile);
suppressBundlerUpdateForFile(projectInfo.rootFile);
- writeFileAndNotifyFileWatchers(projectInfo.rootFile, output, undefined);
+ writeFileAndNotifyFileWatchers({
+ file: projectInfo.rootFile,
+ content: output,
+ originatorClientId: undefined,
+ metadata: null,
+ });
const locationLabel = formatLogFileLocation({
remotionRoot,
diff --git a/packages/studio-server/src/preview-server/routes/update-effect-keyframe-settings.ts b/packages/studio-server/src/preview-server/routes/update-effect-keyframe-settings.ts
index d376bf634a..b0db2745e0 100644
--- a/packages/studio-server/src/preview-server/routes/update-effect-keyframe-settings.ts
+++ b/packages/studio-server/src/preview-server/routes/update-effect-keyframe-settings.ts
@@ -100,10 +100,16 @@ export const updateEffectKeyframeSettingsHandler: ApiHandler<
},
entryType: 'effect-props',
suppressHmrOnFileRestore: true,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(absolutePath);
suppressBundlerUpdateForFile(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: null,
+ });
logEffectUpdate({
fileRelativeToRoot,
diff --git a/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.ts b/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.ts
index 72c39752af..9cd2a1763c 100644
--- a/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.ts
+++ b/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.ts
@@ -87,10 +87,16 @@ export const updateSequenceKeyframeSettingsHandler: ApiHandler<
},
entryType: 'sequence-props',
suppressHmrOnFileRestore: true,
+ nodePathRemappings: null,
});
suppressUndoStackInvalidation(absolutePath);
suppressBundlerUpdateForFile(absolutePath);
- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: clientId,
+ metadata: null,
+ });
logUpdate({
fileRelativeToRoot,
diff --git a/packages/studio-server/src/preview-server/sequence-node-path-mutation.ts b/packages/studio-server/src/preview-server/sequence-node-path-mutation.ts
new file mode 100644
index 0000000000..dc527778ae
--- /dev/null
+++ b/packages/studio-server/src/preview-server/sequence-node-path-mutation.ts
@@ -0,0 +1,31 @@
+import {randomUUID} from 'node:crypto';
+import type {
+ SequenceNodePathMutation,
+ SequenceNodePathRemapping,
+} from '@remotion/studio-shared';
+import type {SequenceNodePath} from 'remotion';
+import {getLiveEventsListener} from './live-events';
+
+const mutationSessionId = randomUUID();
+let mutationCounter = 0;
+
+export const broadcastSequenceNodePathMutation = (
+ files: Array<{
+ absolutePath: string;
+ remappings: SequenceNodePathRemapping[];
+ restoredNodePaths: SequenceNodePath[];
+ }>,
+): SequenceNodePathMutation => {
+ mutationCounter++;
+ const mutation: SequenceNodePathMutation = {
+ mutationId: `${mutationSessionId}:${mutationCounter}`,
+ files,
+ };
+
+ getLiveEventsListener()?.sendEventToClient({
+ type: 'sequence-node-paths-remapped',
+ mutation,
+ });
+
+ return mutation;
+};
diff --git a/packages/studio-server/src/preview-server/sequence-props-watchers.ts b/packages/studio-server/src/preview-server/sequence-props-watchers.ts
index 45f928182c..ebca41556c 100644
--- a/packages/studio-server/src/preview-server/sequence-props-watchers.ts
+++ b/packages/studio-server/src/preview-server/sequence-props-watchers.ts
@@ -24,6 +24,10 @@ import {
type WatcherInfo = {
unwatch: () => void;
refCount: number;
+ currentNodePath: Extract<
+ SubscribeToSequencePropsResponse,
+ {success: true}
+ >['nodePath'];
};
const sequencePropsWatchers: Record<string, Record<string, WatcherInfo>> = {};
@@ -212,12 +216,17 @@ export const subscribeToSequencePropsWatchers = ({
const {nodePath} = initialResult;
const watcherKey = getWatcherKey(nodePath, assetKeys);
- // If a watcher already exists for this key, just bump the ref count
- if (sequencePropsWatchers[clientId]?.[watcherKey]) {
- sequencePropsWatchers[clientId][watcherKey].refCount++;
+ const existingWatcher = sequencePropsWatchers[clientId]?.[watcherKey];
+ if (existingWatcher) {
+ existingWatcher.refCount++;
return initialResult;
}
+ const watcherInfo: WatcherInfo = {
+ unwatch: () => undefined,
+ refCount: 1,
+ currentNodePath: nodePath,
+ };
const {unwatch} = installFileWatcher({
file: absolutePath,
existenceOnly: false,
@@ -230,10 +239,14 @@ export const subscribeToSequencePropsWatchers = ({
return;
}
+ if (event.type === 'changed' && event.skipSequencePropsUpdate) {
+ return;
+ }
+
try {
const result = computeSequencePropsStatusFromContent({
fileContents: event.content,
- nodePath: nodePath.nodePath,
+ nodePath: watcherInfo.currentNodePath.nodePath,
componentIdentity,
keys,
assetKeys,
@@ -260,7 +273,7 @@ export const subscribeToSequencePropsWatchers = ({
listener.sendEventToClientId(clientId, {
type: 'sequence-props-updated',
fileName,
- nodePath,
+ nodePath: watcherInfo.currentNodePath,
result,
});
});
@@ -284,12 +297,13 @@ export const subscribeToSequencePropsWatchers = ({
}
},
});
+ watcherInfo.unwatch = unwatch;
if (!sequencePropsWatchers[clientId]) {
sequencePropsWatchers[clientId] = {};
}
- sequencePropsWatchers[clientId][watcherKey] = {unwatch, refCount: 1};
+ sequencePropsWatchers[clientId][watcherKey] = watcherInfo;
return initialResult;
};
diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.ts
index c920c22fc4..a7c3e63f35 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -1,6 +1,12 @@
import {existsSync, rmSync, readFileSync} from 'node:fs';
import type {LogLevel} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
+import type {
+ RedoResponse,
+ SequenceNodePathRemapping,
+ UndoResponse,
+} from '@remotion/studio-shared';
+import type {SequenceNodePath} from 'remotion';
import {parseAst} from '../codemods/parse-ast';
import {readVisualControlValues} from '../codemods/read-visual-control-values';
import {
@@ -9,6 +15,7 @@ import {
} from '../file-watcher';
import {formatLogFileLocation} from './format-log-file-location';
import {waitForLiveEventsListener} from './live-events';
+import {broadcastSequenceNodePathMutation} from './sequence-node-path-mutation';
import {suppressBundlerUpdateForFile} from './watch-ignore-next-change';
export interface UndoEntryDescription {
@@ -51,6 +58,7 @@ type UndoEntrySnapshot = {
newContents: string | null;
/** 1-based source line for terminal/IDE file links (e.g. path:line). */
logLine: number;
+ nodePathRemappings: SequenceNodePathRemapping[] | null;
};
type UndoEntry = {
@@ -156,6 +164,7 @@ export function pushToUndoStack({
description,
entryType,
suppressHmrOnFileRestore,
+ nodePathRemappings,
}: {
filePath: string;
oldContents: string;
@@ -166,6 +175,7 @@ export function pushToUndoStack({
description: UndoEntryDescription;
entryType: UndoEntryType;
suppressHmrOnFileRestore: boolean;
+ nodePathRemappings: SequenceNodePathRemapping[] | null;
}) {
pushTransactionToUndoStack({
snapshots: [
@@ -174,6 +184,7 @@ export function pushToUndoStack({
oldContents,
newContents,
logLine,
+ nodePathRemappings,
},
],
logLevel,
@@ -197,6 +208,7 @@ export function pushTransactionToUndoStack({
oldContents: string | null;
newContents: string | null;
logLine: number;
+ nodePathRemappings: SequenceNodePathRemapping[] | null;
}>;
logLevel: LogLevel;
remotionRoot: string;
@@ -269,6 +281,7 @@ export function pushToRedoStack({
oldContents,
newContents,
logLine,
+ nodePathRemappings: null,
},
],
description,
@@ -420,7 +433,7 @@ function logFileAction(action: string, filePath: string, logLine: number) {
);
}
-export function popUndo(): {success: true} | {success: false; reason: string} {
+export function popUndo(): UndoResponse {
const entry = undoStack.pop();
if (!entry) {
return {success: false, reason: 'Nothing to undo'};
@@ -448,6 +461,38 @@ export function popUndo(): {success: true} | {success: false; reason: string} {
redoStack.shift();
}
+ const files = entry.snapshots.flatMap((snapshot) => {
+ if (snapshot.nodePathRemappings === null) {
+ return [];
+ }
+
+ return [
+ {
+ absolutePath: snapshot.filePath,
+ remappings: snapshot.nodePathRemappings.flatMap(
+ (remapping): SequenceNodePathRemapping[] => {
+ if (remapping.newNodePath === null) {
+ return [];
+ }
+
+ return [
+ {
+ oldNodePath: remapping.newNodePath,
+ newNodePath: remapping.oldNodePath,
+ },
+ ];
+ },
+ ),
+ restoredNodePaths: snapshot.nodePathRemappings.flatMap(
+ (remapping): SequenceNodePath[] =>
+ remapping.newNodePath === null ? [remapping.oldNodePath] : [],
+ ),
+ },
+ ];
+ });
+ const nodePathMutation =
+ files.length === 0 ? null : broadcastSequenceNodePathMutation(files);
+
for (const snapshot of entry.snapshots) {
suppressUndoStackInvalidation(snapshot.filePath);
if (entry.suppressHmrOnFileRestore) {
@@ -457,11 +502,15 @@ export function popUndo(): {success: true} | {success: false; reason: string} {
if (snapshot.oldContents === null) {
rmSync(snapshot.filePath, {force: true});
} else {
- writeFileAndNotifyFileWatchers(
- snapshot.filePath,
- snapshot.oldContents,
- undefined,
- );
+ writeFileAndNotifyFileWatchers({
+ file: snapshot.filePath,
+ content: snapshot.oldContents,
+ originatorClientId: undefined,
+ metadata:
+ snapshot.nodePathRemappings === null
+ ? null
+ : {skipSequencePropsUpdate: true},
+ });
}
}
@@ -486,10 +535,10 @@ export function popUndo(): {success: true} | {success: false; reason: string} {
}
broadcastState();
- return {success: true};
+ return {success: true, nodePathMutation};
}
-export function popRedo(): {success: true} | {success: false; reason: string} {
+export function popRedo(): RedoResponse {
const entry = redoStack.pop();
if (!entry) {
return {success: false, reason: 'Nothing to redo'};
@@ -521,17 +570,37 @@ export function popRedo(): {success: true} | {success: false; reason: string} {
undoStack.shift();
}
+ const files = snapshotsWithNewContents.flatMap((snapshot) => {
+ if (snapshot.nodePathRemappings === null) {
+ return [];
+ }
+
+ return [
+ {
+ absolutePath: snapshot.filePath,
+ remappings: snapshot.nodePathRemappings,
+ restoredNodePaths: [],
+ },
+ ];
+ });
+ const nodePathMutation =
+ files.length === 0 ? null : broadcastSequenceNodePathMutation(files);
+
for (const snapshot of snapshotsWithNewContents) {
suppressUndoStackInvalidation(snapshot.filePath);
if (entry.suppressHmrOnFileRestore) {
suppressBundlerUpdateForFile(snapshot.filePath);
}
- writeFileAndNotifyFileWatchers(
- snapshot.filePath,
- snapshot.newContents,
- undefined,
- );
+ writeFileAndNotifyFileWatchers({
+ file: snapshot.filePath,
+ content: snapshot.newContents,
+ originatorClientId: undefined,
+ metadata:
+ snapshot.nodePathRemappings === null
+ ? null
+ : {skipSequencePropsUpdate: true},
+ });
}
RenderInternals.Log.verbose(
@@ -555,7 +624,7 @@ export function popRedo(): {success: true} | {success: false; reason: string} {
}
broadcastState();
- return {success: true};
+ return {success: true, nodePathMutation};
}
/*
diff --git a/packages/studio-server/src/test/add-keyframes.test.ts b/packages/studio-server/src/test/add-keyframes.test.ts
index a7effe66c0..7d056743f8 100644
--- a/packages/studio-server/src/test/add-keyframes.test.ts
+++ b/packages/studio-server/src/test/add-keyframes.test.ts
@@ -145,10 +145,10 @@ test('addKeyframes batches sequence and effect adds into one undo entry', async
);
expect(getUndoStack()).toHaveLength(1);
- expect(popUndo()).toEqual({success: true});
+ expect(popUndo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(filePath, 'utf-8')).toBe(input);
- expect(popRedo()).toEqual({success: true});
+ expect(popRedo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(filePath, 'utf-8')).toBe(output);
} finally {
clearUndoStackForTests();
diff --git a/packages/studio-server/src/test/batch-update-keyframe-settings.test.ts b/packages/studio-server/src/test/batch-update-keyframe-settings.test.ts
index 8b08cfa260..f26baaa39c 100644
--- a/packages/studio-server/src/test/batch-update-keyframe-settings.test.ts
+++ b/packages/studio-server/src/test/batch-update-keyframe-settings.test.ts
@@ -125,11 +125,11 @@ test('batches sequence and effect easing changes into one undo entry', async ()
expect(effectOutput).toContain('easing: [Easing.bezier(0.42, 0, 1, 1)]');
expect(getUndoStack()).toHaveLength(1);
- expect(popUndo()).toEqual({success: true});
+ expect(popUndo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(sequenceFilePath, 'utf-8')).toBe(input);
expect(readFileSync(effectFilePath, 'utf-8')).toBe(input);
- expect(popRedo()).toEqual({success: true});
+ expect(popRedo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(sequenceFilePath, 'utf-8')).toBe(sequenceOutput);
expect(readFileSync(effectFilePath, 'utf-8')).toBe(effectOutput);
} finally {
diff --git a/packages/studio-server/src/test/delete-jsx-node.test.ts b/packages/studio-server/src/test/delete-jsx-node.test.ts
index dcc7007eb3..00915f4e01 100644
--- a/packages/studio-server/src/test/delete-jsx-node.test.ts
+++ b/packages/studio-server/src/test/delete-jsx-node.test.ts
@@ -1,5 +1,22 @@
import {expect, test} from 'bun:test';
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
+import {tmpdir} from 'node:os';
+import {join} from 'node:path';
+import type {EventSourceEvent} from '@remotion/studio-shared';
import {deleteJsxNode, deleteJsxNodes} from '../codemods/delete-jsx-node';
+import {
+ createFileWatcherRegistry,
+ setFileWatcherRegistry,
+} from '../file-watcher';
+import {setLiveEventsListener} from '../preview-server/live-events';
+import {deleteJsxNodeHandler} from '../preview-server/routes/delete-jsx-node';
+import {subscribeToSequenceProps} from '../preview-server/routes/subscribe-to-sequence-props';
+import {unsubscribeClientSequencePropsWatchers} from '../preview-server/sequence-props-watchers';
+import {
+ clearUndoStackForTests,
+ popRedo,
+ popUndo,
+} from '../preview-server/undo-stack';
import {lineColumnToNodePath} from './test-utils';
const sample = `import React from 'react';
@@ -127,3 +144,210 @@ test('deleteJsxNodes removes multiple JSX children in one transform', async () =
expect(nodeLabels).toEqual(['<div>', '<span>']);
expect(logLines).toEqual([7, 8]);
});
+
+const interactiveSiblings = `import {Interactive} from 'remotion';
+
+export const X = () => {
+ return (
+ <div>
+ <Interactive.Div name="Eyebrow" />
+ <Interactive.Div name="Title" />
+ <Interactive.Div name="Chart" />
+ </div>
+ );
+};
+`;
+
+test('deleting a JSX node broadcasts node path mutations for all clients', async () => {
+ clearUndoStackForTests();
+ const cleanupFileWatcher = setFileWatcherRegistry(
+ createFileWatcherRegistry(),
+ );
+ const remotionRoot = mkdtempSync(join(tmpdir(), 'remotion-delete-node-'));
+ const fileName = 'Comp.tsx';
+ const filePath = join(remotionRoot, fileName);
+ const clientId = 'delete-node-test';
+ writeFileSync(filePath, interactiveSiblings);
+ const events: EventSourceEvent[] = [];
+ const mutationBroadcastFileContents: string[] = [];
+ const cleanupLiveEvents = setLiveEventsListener({
+ addNewClientListener: () => () => undefined,
+ closeConnections: () => Promise.resolve(),
+ router: () => Promise.resolve(),
+ sendEventToClient: (event) => {
+ events.push(event);
+ if (event.type === 'sequence-node-paths-remapped') {
+ mutationBroadcastFileContents.push(readFileSync(filePath, 'utf-8'));
+ }
+ },
+ sendEventToClientId: (_clientId, event) => {
+ events.push(event);
+ return true;
+ },
+ });
+ const apiHandlerContext = {
+ binariesDirectory: null,
+ configFile: null,
+ entryPoint: filePath,
+ getDefaultCodingAgent: () => null,
+ getDefaultEditor: () => null,
+ logLevel: 'error' as const,
+ methods: {
+ addJob: () => undefined,
+ cancelJob: () => undefined,
+ removeJob: () => undefined,
+ },
+ publicDir: remotionRoot,
+ remotionRoot,
+ request: {} as never,
+ response: {} as never,
+ };
+
+ try {
+ for (const line of [6, 7, 8]) {
+ const result = await subscribeToSequenceProps({
+ ...apiHandlerContext,
+ input: {
+ assetKeys: [],
+ clientId,
+ column: 0,
+ componentIdentity: 'dev.remotion.remotion.Interactive.Div',
+ effects: [],
+ fileName,
+ keys: ['name'],
+ line,
+ nodePath: lineColumnToNodePath(interactiveSiblings, line),
+ videoConfigValues: {
+ durationInFrames: 100,
+ fps: 30,
+ height: 1080,
+ width: 1920,
+ },
+ },
+ });
+ expect(result.success).toBe(true);
+ }
+
+ const response = await deleteJsxNodeHandler({
+ ...apiHandlerContext,
+ input: {
+ nodes: [
+ {
+ fileName,
+ nodePath: lineColumnToNodePath(interactiveSiblings, 6),
+ },
+ ],
+ },
+ });
+ if (!response.success) {
+ throw new Error(response.reason);
+ }
+
+ await Promise.resolve();
+
+ const output = readFileSync(filePath, 'utf-8');
+ expect(output).not.toContain('Eyebrow');
+ expect(output).toContain('name="Title"');
+ expect(output).toContain('name="Chart"');
+ expect(response.nodePathMutation.files).toEqual([
+ {
+ absolutePath: filePath,
+ remappings: [
+ {
+ oldNodePath: lineColumnToNodePath(interactiveSiblings, 6),
+ newNodePath: null,
+ },
+ {
+ oldNodePath: lineColumnToNodePath(interactiveSiblings, 7),
+ newNodePath: lineColumnToNodePath(output, 6),
+ },
+ {
+ oldNodePath: lineColumnToNodePath(interactiveSiblings, 8),
+ newNodePath: lineColumnToNodePath(output, 7),
+ },
+ ],
+ restoredNodePaths: [],
+ },
+ ]);
+ expect(
+ events.filter((event) => event.type === 'sequence-node-paths-remapped'),
+ ).toEqual([
+ {
+ type: 'sequence-node-paths-remapped',
+ mutation: response.nodePathMutation,
+ },
+ ]);
+ expect(mutationBroadcastFileContents).toEqual([interactiveSiblings]);
+ expect(events.some((event) => event.type === 'lost-node-path')).toBe(false);
+ expect(
+ events.some((event) => event.type === 'sequence-props-updated'),
+ ).toBe(false);
+
+ events.length = 0;
+ const undoResponse = popUndo();
+ if (!undoResponse.success || undoResponse.nodePathMutation === null) {
+ throw new Error('Expected undo to include a node path mutation');
+ }
+
+ await Promise.resolve();
+ expect(readFileSync(filePath, 'utf-8')).toBe(interactiveSiblings);
+ expect(events.some((event) => event.type === 'lost-node-path')).toBe(false);
+ expect(undoResponse.nodePathMutation.files).toEqual([
+ {
+ absolutePath: filePath,
+ remappings: [
+ {
+ oldNodePath: lineColumnToNodePath(output, 6),
+ newNodePath: lineColumnToNodePath(interactiveSiblings, 7),
+ },
+ {
+ oldNodePath: lineColumnToNodePath(output, 7),
+ newNodePath: lineColumnToNodePath(interactiveSiblings, 8),
+ },
+ ],
+ restoredNodePaths: [lineColumnToNodePath(interactiveSiblings, 6)],
+ },
+ ]);
+ expect(
+ events.filter((event) => event.type === 'sequence-node-paths-remapped'),
+ ).toEqual([
+ {
+ type: 'sequence-node-paths-remapped',
+ mutation: undoResponse.nodePathMutation,
+ },
+ ]);
+ expect(mutationBroadcastFileContents).toEqual([
+ interactiveSiblings,
+ output,
+ ]);
+
+ events.length = 0;
+ const redoResponse = popRedo();
+ if (!redoResponse.success || redoResponse.nodePathMutation === null) {
+ throw new Error('Expected redo to include a node path mutation');
+ }
+
+ await Promise.resolve();
+ expect(readFileSync(filePath, 'utf-8')).toBe(output);
+ expect(events.some((event) => event.type === 'lost-node-path')).toBe(false);
+ expect(
+ events.filter((event) => event.type === 'sequence-node-paths-remapped'),
+ ).toEqual([
+ {
+ type: 'sequence-node-paths-remapped',
+ mutation: redoResponse.nodePathMutation,
+ },
+ ]);
+ expect(mutationBroadcastFileContents).toEqual([
+ interactiveSiblings,
+ output,
+ interactiveSiblings,
+ ]);
+ } finally {
+ unsubscribeClientSequencePropsWatchers(clientId);
+ cleanupLiveEvents();
+ cleanupFileWatcher();
+ clearUndoStackForTests();
+ rmSync(remotionRoot, {recursive: true, force: true});
+ }
+});
diff --git a/packages/studio-server/src/test/delete-keyframes.test.ts b/packages/studio-server/src/test/delete-keyframes.test.ts
index c14543a978..0ad0df9974 100644
--- a/packages/studio-server/src/test/delete-keyframes.test.ts
+++ b/packages/studio-server/src/test/delete-keyframes.test.ts
@@ -117,10 +117,10 @@ test('deleteKeyframes batches sequence and effect deletes into one undo entry',
expect(output).toContain('amount: 0.6');
expect(getUndoStack()).toHaveLength(1);
- expect(popUndo()).toEqual({success: true});
+ expect(popUndo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(filePath, 'utf-8')).toBe(input);
- expect(popRedo()).toEqual({success: true});
+ expect(popRedo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(filePath, 'utf-8')).toBe(output);
} finally {
clearUndoStackForTests();
diff --git a/packages/studio-server/src/test/duplicate-jsx-node.test.ts b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
index 6d40341502..ca517600fc 100644
--- a/packages/studio-server/src/test/duplicate-jsx-node.test.ts
+++ b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
@@ -1,6 +1,6 @@
import {expect, test} from 'bun:test';
import {duplicateJsxNode} from '../codemods/duplicate-jsx-node';
-import {lineColumnToNodePath} from './test-utils';
+import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
const sample = `import React from 'react';
import {AbsoluteFill} from 'remotion';
@@ -25,6 +25,27 @@ test('duplicateJsxNode inserts a sibling JSX element', async () => {
expect(output).toContain('<AbsoluteFill>');
});
+test('duplicateJsxNode remaps following JSX siblings', async () => {
+ const input = `export const X = () => (
+ <div>
+ <span data-name="duplicate" />
+ <span data-name="following" />
+ </div>
+);
+`;
+ const {output, nodePathRemappings} = await duplicateJsxNode({
+ input,
+ nodePath: lineContainingToNodePath(input, 'data-name="duplicate"'),
+ });
+
+ expect(nodePathRemappings).toEqual([
+ {
+ oldNodePath: lineContainingToNodePath(input, 'data-name="following"'),
+ newNodePath: lineContainingToNodePath(output, 'data-name="following"'),
+ },
+ ]);
+});
+
const onlyReturn = `import React from 'react';
export const X: React.FC = () => {
diff --git a/packages/studio-server/src/test/file-watcher.test.ts b/packages/studio-server/src/test/file-watcher.test.ts
index e801f6008e..e4995c1054 100644
--- a/packages/studio-server/src/test/file-watcher.test.ts
+++ b/packages/studio-server/src/test/file-watcher.test.ts
@@ -46,19 +46,26 @@ test('multiple watchers on the same file share a single OS watcher', () => {
expect(w2.exists).toBe(true);
// writeFileAndNotifyFileWatchers should notify both
- registry.writeFileAndNotifyFileWatchers(tmpFile, 'updated', undefined);
+ registry.writeFileAndNotifyFileWatchers({
+ file: tmpFile,
+ content: 'updated',
+ originatorClientId: undefined,
+ metadata: null,
+ });
expect(cb1).toHaveBeenCalledTimes(1);
expect(cb1).toHaveBeenCalledWith({
type: 'changed',
content: 'updated',
originatorClientId: undefined,
+ skipSequencePropsUpdate: false,
});
expect(cb2).toHaveBeenCalledTimes(1);
expect(cb2).toHaveBeenCalledWith({
type: 'changed',
content: 'updated',
originatorClientId: undefined,
+ skipSequencePropsUpdate: false,
});
w1.unwatch();
@@ -111,7 +118,12 @@ test('unwatching one subscriber does not affect the other', () => {
w1.unwatch();
- registry.writeFileAndNotifyFileWatchers(tmpFile, 'after-unwatch', undefined);
+ registry.writeFileAndNotifyFileWatchers({
+ file: tmpFile,
+ content: 'after-unwatch',
+ originatorClientId: undefined,
+ metadata: null,
+ });
expect(cb1).toHaveBeenCalledTimes(0);
expect(cb2).toHaveBeenCalledTimes(1);
@@ -119,6 +131,7 @@ test('unwatching one subscriber does not affect the other', () => {
type: 'changed',
content: 'after-unwatch',
originatorClientId: undefined,
+ skipSequencePropsUpdate: false,
});
w2.unwatch();
@@ -135,7 +148,12 @@ test('writeFileAndNotifyFileWatchers passes content to subscribers', () => {
},
});
- registry.writeFileAndNotifyFileWatchers(tmpFile, 'hello world', undefined);
+ registry.writeFileAndNotifyFileWatchers({
+ file: tmpFile,
+ content: 'hello world',
+ originatorClientId: undefined,
+ metadata: null,
+ });
const event = receivedEvent!;
expect(event.type).toBe('changed');
@@ -155,7 +173,12 @@ test('writeFileAndNotifyFileWatchers writes the file to disk', () => {
onChange: () => {},
});
- registry.writeFileAndNotifyFileWatchers(tmpFile, 'disk content', undefined);
+ registry.writeFileAndNotifyFileWatchers({
+ file: tmpFile,
+ content: 'disk content',
+ originatorClientId: undefined,
+ metadata: null,
+ });
expect(readFileSync(tmpFile, 'utf-8')).toBe('disk content');
@@ -164,7 +187,12 @@ test('writeFileAndNotifyFileWatchers writes the file to disk', () => {
test('writeFileAndNotifyFileWatchers works even without watchers', () => {
// Should not throw
- registry.writeFileAndNotifyFileWatchers(tmpFile, 'no watchers', undefined);
+ registry.writeFileAndNotifyFileWatchers({
+ file: tmpFile,
+ content: 'no watchers',
+ originatorClientId: undefined,
+ metadata: null,
+ });
expect(readFileSync(tmpFile, 'utf-8')).toBe('no watchers');
});
@@ -179,7 +207,12 @@ test('duplicate content from fs.watchFile is suppressed', async () => {
});
// Simulate a write via our API β€” sets lastKnownContent
- registry.writeFileAndNotifyFileWatchers(tmpFile, 'new content', undefined);
+ registry.writeFileAndNotifyFileWatchers({
+ file: tmpFile,
+ content: 'new content',
+ originatorClientId: undefined,
+ metadata: null,
+ });
expect(cb).toHaveBeenCalledTimes(1);
// Wait for fs.watchFile to poll (100ms interval + generous buffer)
@@ -208,11 +241,12 @@ test('registries are isolated from each other', () => {
onChange: cb2,
});
- registry.writeFileAndNotifyFileWatchers(
- tmpFile,
- 'from registry 1',
- undefined,
- );
+ registry.writeFileAndNotifyFileWatchers({
+ file: tmpFile,
+ content: 'from registry 1',
+ originatorClientId: undefined,
+ metadata: null,
+ });
expect(cb1).toHaveBeenCalledTimes(1);
expect(cb2).toHaveBeenCalledTimes(0);
diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.ts
index 7897ba1b87..26edc7b74a 100644
--- a/packages/studio-server/src/test/insert-element.test.ts
+++ b/packages/studio-server/src/test/insert-element.test.ts
@@ -10,6 +10,7 @@ import {
import {tmpdir} from 'node:os';
import path from 'node:path';
import type {
+ EventSourceEvent,
InsertElementRequest,
PrepareElementInstallRequest,
} from '@remotion/studio-shared';
@@ -65,13 +66,29 @@ const makeFixture = () => {
const compositionFile = path.join(remotionRoot, 'Root.tsx');
const elementFile = path.join(remotionRoot, 'lower-third.element.tsx');
writeFileSync(compositionFile, compositionSource);
+ const events: EventSourceEvent[] = [];
+ const contentsAtMutation: string[] = [];
+ const watcherSkipSequencePropsUpdates: boolean[] = [];
clearUndoStackForTests();
- const cleanupFileWatcher = setFileWatcherRegistry(
- createFileWatcherRegistry(),
- );
+ const fileWatcherRegistry = createFileWatcherRegistry();
+ const cleanupFileWatcher = setFileWatcherRegistry(fileWatcherRegistry);
+ const {unwatch} = fileWatcherRegistry.installFileWatcher({
+ file: compositionFile,
+ existenceOnly: false,
+ onChange: (event) => {
+ if (event.type === 'changed') {
+ watcherSkipSequencePropsUpdates.push(event.skipSequencePropsUpdate);
+ }
+ },
+ });
const cleanupLiveEvents = setLiveEventsListener({
- sendEventToClient: () => undefined,
+ sendEventToClient: (event) => {
+ events.push(event);
+ if (event.type === 'sequence-node-paths-remapped') {
+ contentsAtMutation.push(readFileSync(compositionFile, 'utf-8'));
+ }
+ },
sendEventToClientId: () => true,
router: () => Promise.resolve(),
closeConnections: () => Promise.resolve(),
@@ -143,6 +160,7 @@ const makeFixture = () => {
const cleanup = () => {
clearUndoStackForTests();
+ unwatch();
cleanupLiveEvents();
cleanupFileWatcher();
rmSync(remotionRoot, {force: true, recursive: true});
@@ -155,8 +173,11 @@ const makeFixture = () => {
cleanup,
prepareInstall,
compositionFile,
+ contentsAtMutation,
elementFile,
+ events,
outsideRoot,
+ watcherSkipSequencePropsUpdates,
};
};
@@ -186,7 +207,26 @@ test('creates a new Element file without an overwrite conflict', async () => {
try {
const response = await fixture.callHandler(false);
- expect(response).toEqual({success: true});
+ if (!response.success) {
+ throw new Error(
+ response.type === 'error'
+ ? response.reason
+ : 'Unexpected file conflict',
+ );
+ }
+
+ expect(
+ fixture.events.filter(
+ (event) => event.type === 'sequence-node-paths-remapped',
+ ),
+ ).toEqual([
+ {
+ type: 'sequence-node-paths-remapped',
+ mutation: response.nodePathMutation,
+ },
+ ]);
+ expect(fixture.contentsAtMutation).toEqual([compositionSource]);
+ expect(fixture.watcherSkipSequencePropsUpdates).toEqual([true]);
expect(readFileSync(fixture.elementFile, 'utf-8')).toBe(
incomingElementSource,
);
@@ -212,7 +252,7 @@ test('installs an Element with a component-owned Sequence', async () => {
position: {x: 120, y: 80},
});
- expect(response).toEqual({success: true});
+ expect(response.success).toBe(true);
expect(readFileSync(fixture.elementFile, 'utf-8')).toBe(
incomingElementSource,
);
@@ -235,7 +275,7 @@ test('reuses an identical Element file without an overwrite conflict', async ()
writeFileSync(fixture.elementFile, incomingElementSource);
const response = await fixture.callHandler(false);
- expect(response).toEqual({success: true});
+ expect(response.success).toBe(true);
expect(readFileSync(fixture.elementFile, 'utf-8')).toBe(
incomingElementSource,
);
@@ -361,7 +401,7 @@ test('overwrites conflicting source and undo restores both files', async () => {
writeFileSync(fixture.elementFile, existingElementSource);
const response = await fixture.callHandler(true);
- expect(response).toEqual({success: true});
+ expect(response.success).toBe(true);
expect(readFileSync(fixture.elementFile, 'utf-8')).toBe(
incomingElementSource,
);
@@ -370,7 +410,12 @@ test('overwrites conflicting source and undo restores both files', async () => {
);
expect(getUndoStack()).toHaveLength(1);
- expect(popUndo()).toEqual({success: true});
+ const undoResponse = popUndo();
+ expect(undoResponse.success).toBe(true);
+ if (!undoResponse.success || undoResponse.nodePathMutation === null) {
+ throw new Error('Expected undo to include a node path mutation');
+ }
+
expect(readFileSync(fixture.elementFile, 'utf-8')).toBe(
existingElementSource,
);
diff --git a/packages/studio-server/src/test/jsx-node-path-mutation-routes.test.ts b/packages/studio-server/src/test/jsx-node-path-mutation-routes.test.ts
new file mode 100644
index 0000000000..a8be54f196
--- /dev/null
+++ b/packages/studio-server/src/test/jsx-node-path-mutation-routes.test.ts
@@ -0,0 +1,217 @@
+import {expect, test} from 'bun:test';
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
+import {tmpdir} from 'node:os';
+import {join} from 'node:path';
+import type {
+ EventSourceEvent,
+ SequenceNodePathMutation,
+} from '@remotion/studio-shared';
+import {
+ createFileWatcherRegistry,
+ setFileWatcherRegistry,
+} from '../file-watcher';
+import {setLiveEventsListener} from '../preview-server/live-events';
+import {duplicateJsxNodeHandler} from '../preview-server/routes/duplicate-jsx-node';
+import {insertJsxElementHandler} from '../preview-server/routes/insert-jsx-element';
+import {reorderSequenceHandler} from '../preview-server/routes/reorder-sequence';
+import {splitJsxSequenceHandler} from '../preview-server/routes/split-jsx-sequence';
+import {
+ clearUndoStackForTests,
+ popRedo,
+ popUndo,
+} from '../preview-server/undo-stack';
+import {lineContainingToNodePath} from './test-utils';
+
+const initialSource = `import {Composition, Sequence} from 'remotion';
+
+export const Comp = () => (
+ <>
+ <Sequence name="a" from={0} durationInFrames={50} />
+ <Sequence name="b" from={10} durationInFrames={50} />
+ <Sequence name="c" from={20} durationInFrames={50} />
+ </>
+);
+
+export const InsertComp = () => <div />;
+
+export const Root = () => (
+ <>
+ <Composition id="comp" component={Comp} durationInFrames={100} fps={30} width={1920} height={1080} />
+ <Composition id="insert" component={InsertComp} durationInFrames={100} fps={30} width={1920} height={1080} />
+ </>
+);
+`;
+
+test('JSX structure routes broadcast and return node path mutations before writing', async () => {
+ clearUndoStackForTests();
+ const fileWatcherRegistry = createFileWatcherRegistry();
+ const cleanupFileWatcher = setFileWatcherRegistry(fileWatcherRegistry);
+ const remotionRoot = mkdtempSync(join(tmpdir(), 'remotion-jsx-mutations-'));
+ const fileName = 'Comp.tsx';
+ const filePath = join(remotionRoot, fileName);
+ writeFileSync(filePath, initialSource);
+ const watcherSkipSequencePropsUpdates: boolean[] = [];
+ const {unwatch} = fileWatcherRegistry.installFileWatcher({
+ file: filePath,
+ existenceOnly: false,
+ onChange: (event) => {
+ if (event.type === 'changed') {
+ watcherSkipSequencePropsUpdates.push(event.skipSequencePropsUpdate);
+ }
+ },
+ });
+ const events: EventSourceEvent[] = [];
+ const contentsAtMutation: string[] = [];
+ const cleanupLiveEvents = setLiveEventsListener({
+ addNewClientListener: () => () => undefined,
+ closeConnections: () => Promise.resolve(),
+ router: () => Promise.resolve(),
+ sendEventToClient: (event) => {
+ events.push(event);
+ if (event.type === 'sequence-node-paths-remapped') {
+ contentsAtMutation.push(readFileSync(filePath, 'utf-8'));
+ }
+ },
+ sendEventToClientId: () => true,
+ });
+ const handlerContext = {
+ binariesDirectory: null,
+ configFile: null,
+ entryPoint: filePath,
+ getDefaultCodingAgent: () => null,
+ getDefaultEditor: () => null,
+ logLevel: 'error' as const,
+ methods: {
+ addJob: () => undefined,
+ cancelJob: () => undefined,
+ removeJob: () => undefined,
+ },
+ publicDir: remotionRoot,
+ remotionRoot,
+ request: {} as never,
+ response: {} as never,
+ };
+ const assertMutation = ({
+ before,
+ mutation,
+ }: {
+ before: string;
+ mutation: SequenceNodePathMutation;
+ }) => {
+ expect(
+ events.filter((event) => event.type === 'sequence-node-paths-remapped'),
+ ).toEqual([{type: 'sequence-node-paths-remapped', mutation}]);
+ expect(contentsAtMutation).toEqual([before]);
+ expect(watcherSkipSequencePropsUpdates).toEqual([true]);
+ expect(mutation.files[0].absolutePath).toBe(filePath);
+ expect(mutation.files[0].remappings.length).toBeGreaterThan(0);
+ events.length = 0;
+ contentsAtMutation.length = 0;
+ watcherSkipSequencePropsUpdates.length = 0;
+ };
+
+ try {
+ let before = readFileSync(filePath, 'utf-8');
+ const subscriptionKey = (search: string) => ({
+ absolutePath: filePath,
+ assetKeys: [],
+ effectKeys: [],
+ nodePath: lineContainingToNodePath(before, search),
+ sequenceKeys: ['name'],
+ videoConfigValues: null,
+ });
+ const reorderResponse = await reorderSequenceHandler({
+ ...handlerContext,
+ input: {
+ clientId: 'initiating-client',
+ fileName,
+ position: 'after',
+ sourceNodePath: subscriptionKey('name="a"'),
+ targetNodePath: subscriptionKey('name="c"'),
+ },
+ });
+ if (!reorderResponse.success) {
+ throw new Error(reorderResponse.reason);
+ }
+
+ assertMutation({before, mutation: reorderResponse.nodePathMutation});
+
+ before = readFileSync(filePath, 'utf-8');
+ const duplicateResponse = await duplicateJsxNodeHandler({
+ ...handlerContext,
+ input: {
+ fileName,
+ nodePath: lineContainingToNodePath(before, 'name="b"'),
+ },
+ });
+ if (!duplicateResponse.success) {
+ throw new Error(duplicateResponse.reason);
+ }
+
+ assertMutation({before, mutation: duplicateResponse.nodePathMutation});
+
+ before = readFileSync(filePath, 'utf-8');
+ const splitResponse = await splitJsxSequenceHandler({
+ ...handlerContext,
+ input: {
+ fileName,
+ nodePath: lineContainingToNodePath(before, 'name="c"'),
+ splitFrame: 30,
+ },
+ });
+ if (!splitResponse.success) {
+ throw new Error(splitResponse.reason);
+ }
+
+ assertMutation({before, mutation: splitResponse.nodePathMutation});
+
+ before = readFileSync(filePath, 'utf-8');
+ const insertResponse = await insertJsxElementHandler({
+ ...handlerContext,
+ input: {
+ compositionFile: fileName,
+ compositionId: 'insert',
+ element: {
+ type: 'solid',
+ width: 1920,
+ height: 1080,
+ position: null,
+ },
+ from: null,
+ },
+ });
+ if (!insertResponse.success) {
+ throw new Error(insertResponse.reason);
+ }
+
+ assertMutation({before, mutation: insertResponse.nodePathMutation});
+
+ for (let i = 0; i < 4; i++) {
+ before = readFileSync(filePath, 'utf-8');
+ const undoResponse = popUndo();
+ if (!undoResponse.success || undoResponse.nodePathMutation === null) {
+ throw new Error('Expected undo to include a node path mutation');
+ }
+
+ assertMutation({before, mutation: undoResponse.nodePathMutation});
+ }
+
+ expect(readFileSync(filePath, 'utf-8')).toBe(initialSource);
+
+ for (let i = 0; i < 4; i++) {
+ before = readFileSync(filePath, 'utf-8');
+ const redoResponse = popRedo();
+ if (!redoResponse.success || redoResponse.nodePathMutation === null) {
+ throw new Error('Expected redo to include a node path mutation');
+ }
+
+ assertMutation({before, mutation: redoResponse.nodePathMutation});
+ }
+ } finally {
+ unwatch();
+ cleanupLiveEvents();
+ cleanupFileWatcher();
+ clearUndoStackForTests();
+ rmSync(remotionRoot, {recursive: true, force: true});
+ }
+});
diff --git a/packages/studio-server/src/test/reorder-sequence.test.ts b/packages/studio-server/src/test/reorder-sequence.test.ts
index 95170a40e2..8ed4d0ac1f 100644
--- a/packages/studio-server/src/test/reorder-sequence.test.ts
+++ b/packages/studio-server/src/test/reorder-sequence.test.ts
@@ -1,6 +1,6 @@
import {expect, test} from 'bun:test';
import {reorderSequence} from '../codemods/reorder-sequence';
-import {lineColumnToNodePath} from './test-utils';
+import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
const buildInput = () => `import {Sequence} from 'remotion';
@@ -17,7 +17,7 @@ export const Comp = () => {
test('reorderSequence moves a sequence forward', async () => {
const input = buildInput();
- const {output, sequenceLabel} = await reorderSequence({
+ const {output, sequenceLabel, nodePathRemappings} = await reorderSequence({
input,
sourceNodePath: lineColumnToNodePath(input, 6),
targetNodePath: lineColumnToNodePath(input, 8),
@@ -27,6 +27,20 @@ test('reorderSequence moves a sequence forward', async () => {
expect(sequenceLabel).toBe('<Sequence>');
expect(output.indexOf('name="b"')).toBeLessThan(output.indexOf('name="c"'));
expect(output.indexOf('name="c"')).toBeLessThan(output.indexOf('name="a"'));
+ expect(nodePathRemappings).toEqual([
+ {
+ oldNodePath: lineContainingToNodePath(input, 'name="a"'),
+ newNodePath: lineContainingToNodePath(output, 'name="a"'),
+ },
+ {
+ oldNodePath: lineContainingToNodePath(input, 'name="b"'),
+ newNodePath: lineContainingToNodePath(output, 'name="b"'),
+ },
+ {
+ oldNodePath: lineContainingToNodePath(input, 'name="c"'),
+ newNodePath: lineContainingToNodePath(output, 'name="c"'),
+ },
+ ]);
});
test('reorderSequence moves a sequence backward', async () => {
diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.ts
index efe47f7699..2ac0d7b639 100644
--- a/packages/studio-server/src/test/resolve-composition-component.test.ts
+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts
@@ -8,6 +8,7 @@ import {
resolveCompositionComponent,
} from '../helpers/resolve-composition-component';
import {insertJsxElementHandler} from '../preview-server/routes/insert-jsx-element';
+import {lineContainingToNodePath} from './test-utils';
const remotionRoot = path.join(__dirname, '..', '..', '..', 'example');
@@ -435,18 +436,16 @@ test('wraps a self-closing root in a Sequence before inserting', async () => {
'',
].join('\n'),
);
- await fs.writeFile(
- path.join(tempDir, 'MyComp.tsx'),
- [
- "import {Video} from '@remotion/media';",
- "import {staticFile} from 'remotion';",
- '',
- 'export const MyComp: React.FC = () => {',
- '\treturn <Video src={staticFile("background.mov")} />;',
- '};',
- '',
- ].join('\n'),
- );
+ const componentInput = [
+ "import {Video} from '@remotion/media';",
+ "import {staticFile} from 'remotion';",
+ '',
+ 'export const MyComp: React.FC = () => {',
+ '\treturn <Video src={staticFile("background.mov")} />;',
+ '};',
+ '',
+ ].join('\n');
+ await fs.writeFile(path.join(tempDir, 'MyComp.tsx'), componentInput);
const result = await insertJsxElementIntoComposition({
remotionRoot: tempDir,
@@ -474,6 +473,12 @@ test('wraps a self-closing root in a Sequence before inserting', async () => {
);
expect(result.output).toContain('</Sequence>');
expect(result.output).toContain("<Audio src={staticFile('music.mp3')} />");
+ expect(result.nodePathRemappings).toEqual([
+ {
+ oldNodePath: lineContainingToNodePath(componentInput, '<Video'),
+ newNodePath: lineContainingToNodePath(result.output, '<Video'),
+ },
+ ]);
} finally {
await fs.rm(tempDir, {recursive: true, force: true});
}
diff --git a/packages/studio-server/src/test/save-multiple-effect-props.test.ts b/packages/studio-server/src/test/save-multiple-effect-props.test.ts
index 7cfa7c0e3f..12e1b0e976 100644
--- a/packages/studio-server/src/test/save-multiple-effect-props.test.ts
+++ b/packages/studio-server/src/test/save-multiple-effect-props.test.ts
@@ -125,9 +125,9 @@ export const Comp = () => {
expect(response.results).toHaveLength(2);
expect(getUndoStack()).toHaveLength(1);
- expect(popUndo()).toEqual({success: true});
+ expect(popUndo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(filePath, 'utf-8')).toBe(input);
- expect(popRedo()).toEqual({success: true});
+ expect(popRedo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(filePath, 'utf-8')).toBe(output);
} finally {
clearUndoStackForTests();
diff --git a/packages/studio-server/src/test/save-sequence-props.test.ts b/packages/studio-server/src/test/save-sequence-props.test.ts
index e0290070e8..d1c499da0f 100644
--- a/packages/studio-server/src/test/save-sequence-props.test.ts
+++ b/packages/studio-server/src/test/save-sequence-props.test.ts
@@ -199,7 +199,7 @@ test('saveSequenceProps saves inline caption patches as an undoable source edit'
expect(getUndoStack()).toHaveLength(1);
expect(getUndoStack()[0]?.suppressHmrOnFileRestore).toBe(false);
- expect(popUndo()).toEqual({success: true});
+ expect(popUndo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(filePath, 'utf-8')).toBe(input);
} finally {
clearUndoStackForTests();
@@ -308,7 +308,7 @@ export const Comp = () => {
expect(output).toContain('interpolate(frame, [10, 30], [0, 1])');
expect(getUndoStack()).toHaveLength(1);
- expect(popUndo()).toEqual({success: true});
+ expect(popUndo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(filePath, 'utf-8')).toBe(input);
} finally {
clearUndoStackForTests();
@@ -423,7 +423,7 @@ export const Comp = () => {
expect(output).toContain("['3px 4px', '23px 44px']");
expect(getUndoStack()).toHaveLength(1);
- expect(popUndo()).toEqual({success: true});
+ expect(popUndo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(filePath, 'utf-8')).toBe(input);
} finally {
clearUndoStackForTests();
diff --git a/packages/studio-server/src/test/split-jsx-sequence.test.ts b/packages/studio-server/src/test/split-jsx-sequence.test.ts
index 5d0c517b7a..a1c51b602c 100644
--- a/packages/studio-server/src/test/split-jsx-sequence.test.ts
+++ b/packages/studio-server/src/test/split-jsx-sequence.test.ts
@@ -10,7 +10,7 @@ import {
import {setLiveEventsListener} from '../preview-server/live-events';
import {splitJsxSequenceHandler} from '../preview-server/routes/split-jsx-sequence';
import {getUndoStack} from '../preview-server/undo-stack';
-import {lineColumnToNodePath} from './test-utils';
+import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
const wrap = (
sequence: string,
@@ -46,6 +46,24 @@ test('splitJsxSequence splits a sequence with no duration', async () => {
expect(output).toContain('<Sequence from={30} trimBefore={30} />');
});
+test('splitJsxSequence remaps following JSX siblings', async () => {
+ const input = wrap(
+ '<Sequence name="split" from={0} durationInFrames={50} />\n\t\t\t<Sequence name="following" />',
+ );
+ const {output, nodePathRemappings} = await splitJsxSequence({
+ input,
+ nodePath: lineContainingToNodePath(input, 'name="split"'),
+ splitFrame: 30,
+ });
+
+ expect(nodePathRemappings).toEqual([
+ {
+ oldNodePath: lineContainingToNodePath(input, 'name="following"'),
+ newNodePath: lineContainingToNodePath(output, 'name="following"'),
+ },
+ ]);
+});
+
test('splitJsxSequence omits right Infinity duration', async () => {
const output = await split(
'<Sequence from={0} durationInFrames={Infinity} />',
diff --git a/packages/studio-server/src/test/test-utils.ts b/packages/studio-server/src/test/test-utils.ts
index 4a42cfe716..ac0f9fd897 100644
--- a/packages/studio-server/src/test/test-utils.ts
+++ b/packages/studio-server/src/test/test-utils.ts
@@ -38,3 +38,17 @@ export const lineColumnToNodePath = (
return result;
};
+
+export const lineContainingToNodePath = (
+ input: string,
+ search: string,
+): SequenceNodePath => {
+ const line = input
+ .split('\n')
+ .findIndex((sourceLine) => sourceLine.includes(search));
+ if (line === -1) {
+ throw new Error(`Could not find ${JSON.stringify(search)} in source`);
+ }
+
+ return lineColumnToNodePath(input, line + 1);
+};
diff --git a/packages/studio-server/src/test/undo-stack.test.ts b/packages/studio-server/src/test/undo-stack.test.ts
index ec5bb8cf84..f0b6929007 100644
--- a/packages/studio-server/src/test/undo-stack.test.ts
+++ b/packages/studio-server/src/test/undo-stack.test.ts
@@ -40,12 +40,14 @@ test('undo and redo restore every file in a transaction', () => {
oldContents: 'old first',
newContents: 'new first',
logLine: 1,
+ nodePathRemappings: null,
},
{
filePath: secondFile,
oldContents: 'old second',
newContents: 'new second',
logLine: 1,
+ nodePathRemappings: null,
},
],
logLevel: 'error',
@@ -58,11 +60,11 @@ test('undo and redo restore every file in a transaction', () => {
suppressHmrOnFileRestore: true,
});
- expect(popUndo()).toEqual({success: true});
+ expect(popUndo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(firstFile, 'utf-8')).toBe('old first');
expect(readFileSync(secondFile, 'utf-8')).toBe('old second');
- expect(popRedo()).toEqual({success: true});
+ expect(popRedo()).toEqual({success: true, nodePathMutation: null});
expect(readFileSync(firstFile, 'utf-8')).toBe('new first');
expect(readFileSync(secondFile, 'utf-8')).toBe('new second');
} finally {
diff --git a/packages/studio-server/src/test/update-config.test.ts b/packages/studio-server/src/test/update-config.test.ts
index b49d7fe92f..d24b60918a 100644
--- a/packages/studio-server/src/test/update-config.test.ts
+++ b/packages/studio-server/src/test/update-config.test.ts
@@ -158,6 +158,7 @@ test('persists an arbitrary valid config setter through the route', async () =>
].join('\n'),
originatorClientId: 'settings-client',
type: 'changed',
+ skipSequencePropsUpdate: false,
});
} finally {
unwatch();
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index e5c162584c..b0fd48a833 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -40,6 +40,7 @@ import type {
CompletedClientRender,
RequiredChromiumOptions,
} from './render-job';
+import type {SequenceNodePathMutation} from './sequence-node-path-mutation';
import type {SymbolicatedStackFrame} from './stack-types';
import type {EnumPath} from './stringify-default-props';
@@ -534,6 +535,7 @@ export type ReorderSequenceRequest = {
export type ReorderSequenceResponse =
| {
success: true;
+ nodePathMutation: SequenceNodePathMutation;
}
| {
success: false;
@@ -756,6 +758,7 @@ export type DeleteJsxNodeRequest = {
export type DeleteJsxNodeResponse =
| {
success: true;
+ nodePathMutation: SequenceNodePathMutation;
}
| {
success: false;
@@ -771,6 +774,7 @@ export type DuplicateJsxNodeRequest = {
export type DuplicateJsxNodeResponse =
| {
success: true;
+ nodePathMutation: SequenceNodePathMutation;
}
| {
success: false;
@@ -787,6 +791,7 @@ export type SplitJsxSequenceRequest = {
export type SplitJsxSequenceResponse =
| {
success: true;
+ nodePathMutation: SequenceNodePathMutation;
}
| {
success: false;
@@ -852,6 +857,7 @@ export type InsertJsxElementRequest = {
export type InsertJsxElementResponse =
| {
success: true;
+ nodePathMutation: SequenceNodePathMutation;
}
| {
success: false;
@@ -921,6 +927,7 @@ export type InsertElementFileConflict = {
export type InsertElementResponse =
| {
success: true;
+ nodePathMutation: SequenceNodePathMutation;
}
| {
success: false;
@@ -1061,6 +1068,7 @@ export type UndoRequest = {};
export type UndoResponse =
| {
success: true;
+ nodePathMutation: SequenceNodePathMutation | null;
}
| {
success: false;
@@ -1071,6 +1079,7 @@ export type RedoRequest = {};
export type RedoResponse =
| {
success: true;
+ nodePathMutation: SequenceNodePathMutation | null;
}
| {
success: false;
diff --git a/packages/studio-shared/src/event-source-event.ts b/packages/studio-shared/src/event-source-event.ts
index 1b93115d2c..5f8e03161a 100644
--- a/packages/studio-shared/src/event-source-event.ts
+++ b/packages/studio-shared/src/event-source-event.ts
@@ -11,6 +11,7 @@ import type {ConfigFileChangeType} from './config-file-change';
import type {HotMiddlewareMessage} from './hot-middleware';
import type {RenderDefaults} from './render-defaults';
import type {CompletedClientRender, RenderJob} from './render-job';
+import type {SequenceNodePathMutation} from './sequence-node-path-mutation';
import type {StudioRuntimeConfig} from './studio-runtime-config';
export type EventSourceEvent =
@@ -75,6 +76,10 @@ export type EventSourceEvent =
nodePath: SequencePropsSubscriptionKey;
result: CanUpdateSequencePropsResponse;
}
+ | {
+ type: 'sequence-node-paths-remapped';
+ mutation: SequenceNodePathMutation;
+ }
| {
type: 'lost-node-path';
fileName: string;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index d34f05b561..ef3f012464 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -144,8 +144,13 @@ export {
type KeyframeSettings,
} from './api-requests';
export type {BrowserStudioOperations} from './browser-studio-operations';
+export type {
+ SequenceNodePathMutation,
+ SequenceNodePathRemapping,
+} from './sequence-node-path-mutation';
export type {ApplyVisualControlCodemod, RecastCodemod} from './codemods';
export {compositionDragDataToSymbolicatedStack} from './composition-drag-data';
+export {REACT_REFRESH_FINISHED_EVENT} from './react-refresh-event';
export {
getConfigFileChangeMessage,
type ConfigFileChangeType,
diff --git a/packages/studio-shared/src/react-refresh-event.ts b/packages/studio-shared/src/react-refresh-event.ts
new file mode 100644
index 0000000000..304a405af2
--- /dev/null
+++ b/packages/studio-shared/src/react-refresh-event.ts
@@ -0,0 +1 @@
+export const REACT_REFRESH_FINISHED_EVENT = 'remotion-react-refresh-finished';
diff --git a/packages/studio-shared/src/sequence-node-path-mutation.ts b/packages/studio-shared/src/sequence-node-path-mutation.ts
new file mode 100644
index 0000000000..08b643f85f
--- /dev/null
+++ b/packages/studio-shared/src/sequence-node-path-mutation.ts
@@ -0,0 +1,15 @@
+import type {SequenceNodePath} from 'remotion';
+
+export type SequenceNodePathRemapping = {
+ oldNodePath: SequenceNodePath;
+ newNodePath: SequenceNodePath | null;
+};
+
+export type SequenceNodePathMutation = {
+ mutationId: string;
+ files: Array<{
+ absolutePath: string;
+ remappings: SequenceNodePathRemapping[];
+ restoredNodePaths: SequenceNodePath[];
+ }>;
+};
diff --git a/packages/studio/src/FastRefreshProvider.tsx b/packages/studio/src/FastRefreshProvider.tsx
index a387d9fe8c..d9aa219eec 100644
--- a/packages/studio/src/FastRefreshProvider.tsx
+++ b/packages/studio/src/FastRefreshProvider.tsx
@@ -1,12 +1,8 @@
+import {REACT_REFRESH_FINISHED_EVENT} from '@remotion/studio-shared';
import React, {useCallback, useEffect, useMemo, useState} from 'react';
+import {flushSync} from 'react-dom';
import {FastRefreshContext} from './fast-refresh-context';
-declare const __webpack_module__: {
- hot: {
- addStatusHandler(callback: (status: string) => void): void;
- };
-};
-
export const FastRefreshProvider: React.FC<{
readonly children: React.ReactNode;
}> = ({children}) => {
@@ -18,15 +14,24 @@ export const FastRefreshProvider: React.FC<{
}, []);
useEffect(() => {
- if (typeof __webpack_module__ !== 'undefined') {
- if (__webpack_module__.hot) {
- __webpack_module__.hot.addStatusHandler((status) => {
- if (status === 'idle') {
- setFastRefreshes((i) => i + 1);
- }
- });
- }
- }
+ const onReactRefreshFinished = () => {
+ // Commit consumers and their layout effects before the browser paints
+ // the refreshed composition with stale node-path statuses.
+ flushSync(() => {
+ setFastRefreshes((i) => i + 1);
+ });
+ };
+
+ window.addEventListener(
+ REACT_REFRESH_FINISHED_EVENT,
+ onReactRefreshFinished,
+ );
+ return () => {
+ window.removeEventListener(
+ REACT_REFRESH_FINISHED_EVENT,
+ onReactRefreshFinished,
+ );
+ };
}, []);
const value = useMemo(
diff --git a/packages/studio/src/components/InspectorOpenInEditor.tsx b/packages/studio/src/components/InspectorOpenInEditor.tsx
index 9e8811d369..c186d4a4b6 100644
--- a/packages/studio/src/components/InspectorOpenInEditor.tsx
+++ b/packages/studio/src/components/InspectorOpenInEditor.tsx
@@ -1,6 +1,6 @@
import type {DefaultCodingAgent} from '@remotion/renderer';
import type {EditorPickerId} from '@remotion/studio-shared';
-import React, {useCallback, useContext, useMemo, useState} from 'react';
+import React, {useCallback, useContext, useMemo, useRef, useState} from 'react';
import type {OriginalPosition} from '../error-overlay/react-overlay/utils/get-source-map';
import {StudioServerConnectionCtx} from '../helpers/client-id';
import {
@@ -68,6 +68,7 @@ export const InspectorOpenInEditor: React.FC<{
const {tabIndex} = useZIndex();
const [hovered, setHovered] = useState(false);
const [dropdownOpened, setDropdownOpened] = useState(false);
+ const ignorePointerEnter = useRef(false);
const editorPickerAvailable = canUseEditorPicker(
previewServerState.type === 'connected',
);
@@ -119,6 +120,7 @@ export const InspectorOpenInEditor: React.FC<{
const onDropdownOpenChange = useCallback((open: boolean) => {
setDropdownOpened(open);
if (!open) {
+ ignorePointerEnter.current = true;
setHovered(false);
}
}, []);
@@ -191,8 +193,15 @@ export const InspectorOpenInEditor: React.FC<{
return (
<div
style={splitButton}
- onPointerEnter={() => setHovered(true)}
- onPointerLeave={() => setHovered(false)}
+ onPointerEnter={() => {
+ if (!ignorePointerEnter.current) {
+ setHovered(true);
+ }
+ }}
+ onPointerLeave={() => {
+ ignorePointerEnter.current = false;
+ setHovered(false);
+ }}
>
<button
aria-label={`Open in ${editorName}`}
diff --git a/packages/studio/src/components/SequencePropsSubscriptionProvider.tsx b/packages/studio/src/components/SequencePropsSubscriptionProvider.tsx
index d7cfbd44dd..b9bf78df27 100644
--- a/packages/studio/src/components/SequencePropsSubscriptionProvider.tsx
+++ b/packages/studio/src/components/SequencePropsSubscriptionProvider.tsx
@@ -49,9 +49,19 @@ export const SequencePropsSubscriptionProvider: React.FC<{
);
const setOverrideIdToNodePath = useCallback(
- (overrideId: string, state: SequencePropsSubscriptionKey) => {
+ (overrideId: string, state: SequencePropsSubscriptionKey | null) => {
setOverrideIdToNodePathMap((prev) => {
const existing = prev[overrideId];
+ if (state === null) {
+ if (!existing) {
+ return prev;
+ }
+
+ const next = {...prev};
+ delete next[overrideId];
+ return next;
+ }
+
if (existing && existing === state) {
return prev;
}
diff --git a/packages/studio/src/components/Timeline/SequencePropsObserver.tsx b/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
index d1f43dc022..3364a8b210 100644
--- a/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
+++ b/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
@@ -1,12 +1,35 @@
-import type {EventSourceEvent} from '@remotion/studio-shared';
-import {useContext, useEffect} from 'react';
+import {type EventSourceEvent} from '@remotion/studio-shared';
+import {useContext, useEffect, useLayoutEffect, useRef} from 'react';
+import type {
+ SequencePropsStatusRemapping,
+ SequencePropsSubscriptionKey,
+} from 'remotion';
import {Internals} from 'remotion';
+import {FastRefreshContext} from '../../fast-refresh-context';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
+import {takePendingSequenceNodePathMutations} from '../../helpers/sequence-node-path-mutations';
+import {ExpandedTracksSetterContext} from '../ExpandedTracksProvider';
export const SequencePropsObserver = () => {
const {subscribeToEvent} = useContext(StudioServerConnectionCtx);
- const {setPropStatuses} = useContext(Internals.VisualModeSettersContext);
-
+ const {remapPropStatuses, setPropStatuses} = useContext(
+ Internals.VisualModeSettersContext,
+ );
+ const propStatusesRef = useContext(
+ Internals.VisualModePropStatusesRefContext,
+ );
+ const {overrideIdToNodePathMappings} = useContext(
+ Internals.OverrideIdsToNodePathsGettersContext,
+ );
+ const overrideIdToNodePathMappingsRef = useRef(overrideIdToNodePathMappings);
+ overrideIdToNodePathMappingsRef.current = overrideIdToNodePathMappings;
+ const {setOverrideIdToNodePath} = useContext(
+ Internals.OverrideIdsToNodePathsSettersContext,
+ );
+ const {fastRefreshes} = useContext(FastRefreshContext);
+ const {migrateExpandedTracksForSubscriptionKey} = useContext(
+ ExpandedTracksSetterContext,
+ );
useEffect(() => {
const handleEvent = (event: EventSourceEvent) => {
if (event.type !== 'sequence-props-updated') {
@@ -23,5 +46,131 @@ export const SequencePropsObserver = () => {
};
}, [setPropStatuses, subscribeToEvent]);
+ useLayoutEffect(() => {
+ const mutations = takePendingSequenceNodePathMutations();
+ if (mutations.length === 0) {
+ return;
+ }
+
+ const statusRemappings: SequencePropsStatusRemapping[] = [];
+ const overrideUpdates: Array<{
+ overrideId: string;
+ nodePath: SequencePropsSubscriptionKey | null;
+ }> = [];
+
+ for (const [overrideId, previousNodePath] of Object.entries(
+ overrideIdToNodePathMappingsRef.current,
+ )) {
+ let {nodePath} = previousNodePath;
+ let wasRemapped = false;
+ let wasDeleted = false;
+ let runtimeNodePathExists = true;
+ const previousNodePathString = JSON.stringify(previousNodePath.nodePath);
+
+ for (const mutation of mutations) {
+ for (const file of mutation.files) {
+ if (file.absolutePath !== previousNodePath.absolutePath) {
+ continue;
+ }
+
+ // Prop statuses follow source nodes to their new paths. Override IDs,
+ // however, follow React's runtime instances. After deleting an unkeyed
+ // sibling, React reuses the instance already at the destination path.
+ // Keep that mapping in place and only remove mappings for vacated paths.
+ const runtimeNodePathIsSource = file.remappings.some(
+ (item) =>
+ JSON.stringify(item.oldNodePath) === previousNodePathString,
+ );
+ const runtimeNodePathIsDestination = file.remappings.some(
+ (item) =>
+ item.newNodePath !== null &&
+ JSON.stringify(item.newNodePath) === previousNodePathString,
+ );
+ const runtimeNodePathWasRestored = file.restoredNodePaths.some(
+ (item) => JSON.stringify(item) === previousNodePathString,
+ );
+ if (runtimeNodePathIsSource) {
+ runtimeNodePathExists =
+ runtimeNodePathIsDestination || runtimeNodePathWasRestored;
+ } else if (
+ runtimeNodePathIsDestination ||
+ runtimeNodePathWasRestored
+ ) {
+ runtimeNodePathExists = true;
+ }
+
+ if (wasDeleted) {
+ const wasRestored = file.restoredNodePaths.some(
+ (restoredNodePath) =>
+ JSON.stringify(restoredNodePath) === JSON.stringify(nodePath),
+ );
+ if (wasRestored) {
+ wasDeleted = false;
+ }
+
+ continue;
+ }
+
+ const remapping = file.remappings.find(
+ (item) =>
+ JSON.stringify(item.oldNodePath) === JSON.stringify(nodePath),
+ );
+ if (!remapping) {
+ continue;
+ }
+
+ wasRemapped = true;
+ if (remapping.newNodePath === null) {
+ wasDeleted = true;
+ continue;
+ }
+
+ nodePath = remapping.newNodePath;
+ }
+ }
+
+ if (!wasRemapped) {
+ continue;
+ }
+
+ const nextNodePath = wasDeleted ? null : {...previousNodePath, nodePath};
+ const previousStatusKey =
+ Internals.makeSequencePropsSubscriptionKey(previousNodePath);
+ statusRemappings.push({
+ previousNodePath,
+ nodePath: nextNodePath,
+ result: propStatusesRef.current[previousStatusKey] ?? null,
+ });
+
+ overrideUpdates.push({
+ overrideId,
+ nodePath: runtimeNodePathExists ? previousNodePath : null,
+ });
+ }
+
+ remapPropStatuses(statusRemappings);
+
+ for (const event of overrideUpdates) {
+ setOverrideIdToNodePath(event.overrideId, event.nodePath);
+ }
+
+ for (const event of statusRemappings) {
+ if (event.nodePath === null) {
+ continue;
+ }
+
+ migrateExpandedTracksForSubscriptionKey(
+ event.previousNodePath,
+ event.nodePath,
+ );
+ }
+ }, [
+ fastRefreshes,
+ migrateExpandedTracksForSubscriptionKey,
+ propStatusesRef,
+ remapPropStatuses,
+ setOverrideIdToNodePath,
+ ]);
+
return null;
};
diff --git a/packages/studio/src/components/Timeline/SubscribeToNodePaths.tsx b/packages/studio/src/components/Timeline/SubscribeToNodePaths.tsx
index 4008a9c238..db8527ab56 100644
--- a/packages/studio/src/components/Timeline/SubscribeToNodePaths.tsx
+++ b/packages/studio/src/components/Timeline/SubscribeToNodePaths.tsx
@@ -15,7 +15,8 @@ export const SubscribeToNodePaths: FC<{
readonly getStack: () => string | null;
readonly effects: readonly EffectDefinition<unknown>[];
}> = ({overrideId, componentIdentity, schema, getStack, effects}) => {
- const originalLocation = useResolveStackAndReactToChange(getStack);
+ const {resolvedLocation, stack, preferMappedNodePath} =
+ useResolveStackAndReactToChange(getStack);
const effectSubscriptions = useMemo<InteractivitySchema[]>(() => {
return effects
@@ -30,7 +31,9 @@ export const SubscribeToNodePaths: FC<{
componentIdentity,
schema,
effects: effectSubscriptions,
- originalLocation,
+ originalLocation: resolvedLocation,
+ preferMappedNodePath,
+ stack,
});
return null;
diff --git a/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts b/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts
index 12348abd86..5a62422ceb 100644
--- a/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts
+++ b/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts
@@ -13,6 +13,8 @@ import {
type Key = string;
+// The generated stack distinguishes Fast Refresh instances even when source maps
+// resolve both the old and new JSX nodes to the same line and column.
const makeKey = ({
fileName,
line,
@@ -22,6 +24,7 @@ const makeKey = ({
assetKeys,
effectKeys,
videoConfigValues,
+ stack,
}: {
fileName: string;
line: number;
@@ -31,8 +34,9 @@ const makeKey = ({
assetKeys: string[];
effectKeys: string[][];
videoConfigValues: VideoConfigValues;
+ stack: string | null;
}): Key =>
- `${fileName}\0${line}\0${column}\0${componentIdentity ?? ''}\0${sequenceKeys.join('\0')}\0${assetKeys.join('\0')}\0${effectKeys.map((keys) => keys.join('\0')).join('\0\0')}\0${JSON.stringify(videoConfigValues)}`;
+ `${fileName}\0${line}\0${column}\0${componentIdentity ?? ''}\0${sequenceKeys.join('\0')}\0${assetKeys.join('\0')}\0${effectKeys.map((keys) => keys.join('\0')).join('\0\0')}\0${JSON.stringify(videoConfigValues)}\0${stack ?? ''}`;
type SubscribeResult = Awaited<ReturnType<typeof subscribeToSequenceProps>>;
@@ -60,6 +64,7 @@ export const acquireSequencePropsSubscription = ({
applyOnce,
applyEach,
videoConfigValues,
+ stack,
}: {
fileName: string;
line: number;
@@ -72,6 +77,7 @@ export const acquireSequencePropsSubscription = ({
applyOnce: ApplyResult;
applyEach: ApplyResult;
videoConfigValues: VideoConfigValues;
+ stack: string | null;
}): {release: () => void} => {
const sequenceKeys = getAllSchemaKeys(schema);
const assetKeys = getAssetSchemaKeys(schema);
@@ -85,6 +91,7 @@ export const acquireSequencePropsSubscription = ({
assetKeys,
effectKeys,
videoConfigValues,
+ stack,
});
let entry = entries.get(key);
diff --git a/packages/studio/src/components/Timeline/use-open-sequence-in-apps.ts b/packages/studio/src/components/Timeline/use-open-sequence-in-apps.ts
index e44e14fcc7..4a4b1c922c 100644
--- a/packages/studio/src/components/Timeline/use-open-sequence-in-apps.ts
+++ b/packages/studio/src/components/Timeline/use-open-sequence-in-apps.ts
@@ -18,7 +18,9 @@ import {useResolveStackAndReactToChange} from './use-resolved-stack-react-to-cha
export const useOpenSequenceInApps = (sequence: TSequence) => {
const {previewServerState} = useContext(StudioServerConnectionCtx);
const previewConnected = previewServerState.type === 'connected';
- const originalLocation = useResolveStackAndReactToChange(sequence.getStack);
+ const {resolvedLocation: originalLocation} = useResolveStackAndReactToChange(
+ sequence.getStack,
+ );
const editorPickerAvailable = canUseEditorPicker(previewConnected);
const editorInfo = useDefaultEditorInfo(editorPickerAvailable);
const codingAgentInfo = useDefaultCodingAgentInfo(editorPickerAvailable);
diff --git a/packages/studio/src/components/Timeline/use-resolved-stack-react-to-change.ts b/packages/studio/src/components/Timeline/use-resolved-stack-react-to-change.ts
index 21bb982b29..0c646d8160 100644
--- a/packages/studio/src/components/Timeline/use-resolved-stack-react-to-change.ts
+++ b/packages/studio/src/components/Timeline/use-resolved-stack-react-to-change.ts
@@ -1,14 +1,15 @@
import type {EventSourceEvent} from '@remotion/studio-shared';
import {useContext, useEffect, useRef, useState} from 'react';
import type {ResolvedStackLocation} from 'remotion';
+import {FastRefreshContext} from '../../fast-refresh-context';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
-import {useResolvedStack} from './use-resolved-stack';
+import {hasResolvedStack, useResolvedStack} from './use-resolved-stack';
// This case: https://github.com/remotion-dev/remotion/issues/7393
// A code change has been made and we cannot re-calculate the stack right away.
// In that case, we wait for fast refresh, wait for the new stack trace, triggering a new event.
-const matchesLostNodePathEvent = (
+const matchesSourceLocation = (
event: Extract<EventSourceEvent, {type: 'lost-node-path'}>,
location: ResolvedStackLocation | null,
): boolean => {
@@ -27,10 +28,39 @@ export const useResolveStackAndReactToChange = (
getStack: () => string | null,
) => {
const {subscribeToEvent} = useContext(StudioServerConnectionCtx);
- const [stack, setStack] = useState<string | null>(() => getStack());
- const resolvedLocation = useResolvedStack(stack);
+ const {fastRefreshes} = useContext(FastRefreshContext);
+ const [stackState, setStackState] = useState(() => ({
+ stack: getStack(),
+ preferMappedNodePath: true,
+ }));
+ const resolvedLocationFromStack = useResolvedStack(stackState.stack);
+ const resolvedLocation = hasResolvedStack(stackState.stack)
+ ? resolvedLocationFromStack
+ : null;
const resolvedLocationRef = useRef(resolvedLocation);
resolvedLocationRef.current = resolvedLocation;
+ const getStackRef = useRef(getStack);
+ getStackRef.current = getStack;
+
+ useEffect(() => {
+ if (fastRefreshes === 0) {
+ return;
+ }
+
+ const newStack = getStackRef.current();
+ setStackState((current) => {
+ if (newStack === current.stack) {
+ return current;
+ }
+
+ return {
+ stack: newStack,
+ // Resolve from the post-refresh source location. The previous node path
+ // may now belong to a sibling after a structural edit.
+ preferMappedNodePath: false,
+ };
+ });
+ }, [fastRefreshes]);
useEffect(() => {
let interval: Timer | null = null;
@@ -40,25 +70,30 @@ export const useResolveStackAndReactToChange = (
return;
}
- if (!matchesLostNodePathEvent(event, resolvedLocationRef.current)) {
+ if (!matchesSourceLocation(event, resolvedLocationRef.current)) {
return;
}
- const initialStack = getStack();
+ const initialStack = getStackRef.current();
if (interval !== null) {
clearInterval(interval);
}
interval = setInterval(() => {
- const newStack = getStack();
+ const newStack = getStackRef.current();
if (newStack !== initialStack) {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
- setStack(newStack);
+ setStackState({
+ stack: newStack,
+ // The old override ID may now belong to a sibling. Resolve the
+ // node path from the post-refresh source location instead.
+ preferMappedNodePath: false,
+ });
}
}, 10);
};
@@ -71,7 +106,11 @@ export const useResolveStackAndReactToChange = (
clearInterval(interval);
}
};
- }, [subscribeToEvent, getStack]);
+ }, [subscribeToEvent]);
- return resolvedLocation;
+ return {
+ preferMappedNodePath: stackState.preferMappedNodePath,
+ resolvedLocation,
+ stack: stackState.stack,
+ };
};
diff --git a/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts b/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts
index ba85d3af0b..e8f0a10218 100644
--- a/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts
+++ b/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts
@@ -21,12 +21,16 @@ export const useSequencePropsSubscription = ({
componentIdentity,
schema,
effects,
+ preferMappedNodePath,
+ stack,
}: {
overrideId: string;
componentIdentity: JsxComponentIdentity | null;
schema: InteractivitySchema;
effects: InteractivitySchema[];
originalLocation: OriginalPosition | null;
+ preferMappedNodePath: boolean;
+ stack: string | null;
}) => {
const {setPropStatuses} = useContext(Internals.VisualModeSettersContext);
const {setOverrideIdToNodePath} = useContext(
@@ -95,8 +99,11 @@ export const useSequencePropsSubscription = ({
schema,
componentIdentity,
effects,
- nodePath: nodePathAtResubscribe?.nodePath ?? null,
+ nodePath: preferMappedNodePath
+ ? (nodePathAtResubscribe?.nodePath ?? null)
+ : null,
clientId,
+ stack,
videoConfigValues: {
durationInFrames: videoConfig.durationInFrames,
fps: videoConfig.fps,
@@ -152,9 +159,11 @@ export const useSequencePropsSubscription = ({
locationSource,
migrateExpandedTracksForSubscriptionKey,
overrideId,
+ preferMappedNodePath,
schema,
setPropStatuses,
setOverrideIdToNodePath,
+ stack,
videoConfig,
]);
};
diff --git a/packages/studio/src/components/call-api.ts b/packages/studio/src/components/call-api.ts
index 74fdb5fb92..3862fd5791 100644
--- a/packages/studio/src/components/call-api.ts
+++ b/packages/studio/src/components/call-api.ts
@@ -1,4 +1,5 @@
import type {ApiRoutes} from '@remotion/studio-shared';
+import {queueSequenceNodePathMutationFromApiResponse} from '../helpers/sequence-node-path-mutations';
export const callApi = <Endpoint extends keyof ApiRoutes>(
endpoint: Endpoint,
@@ -22,6 +23,7 @@ export const callApi = <Endpoint extends keyof ApiRoutes>(
| {success: false; error: string},
) => {
if (data.success) {
+ queueSequenceNodePathMutationFromApiResponse(data.data);
resolve(data.data);
} else {
reject(new Error(data.error));
diff --git a/packages/studio/src/helpers/preview-server-events.ts b/packages/studio/src/helpers/preview-server-events.ts
index 09a423d271..b651cf47ea 100644
--- a/packages/studio/src/helpers/preview-server-events.ts
+++ b/packages/studio/src/helpers/preview-server-events.ts
@@ -6,6 +6,7 @@ import {
BROWSER_STUDIO_OPERATIONS_READY_EVENT,
getBrowserStudioOperations,
} from './browser-studio-operations';
+import {queueSequenceNodePathMutation} from './sequence-node-path-mutations';
export type PreviewServerConnectionState =
| {
@@ -38,6 +39,10 @@ const notifyConnectionState = () => {
};
const dispatch = (event: EventSourceEvent) => {
+ if (event.type === 'sequence-node-paths-remapped') {
+ queueSequenceNodePathMutation(event.mutation);
+ }
+
if (event.type === 'init') {
lastInitEvent = event;
connectionState = {
diff --git a/packages/studio/src/helpers/sequence-node-path-mutations.ts b/packages/studio/src/helpers/sequence-node-path-mutations.ts
new file mode 100644
index 0000000000..d4a8a131e4
--- /dev/null
+++ b/packages/studio/src/helpers/sequence-node-path-mutations.ts
@@ -0,0 +1,42 @@
+import type {SequenceNodePathMutation} from '@remotion/studio-shared';
+
+const pendingMutations: SequenceNodePathMutation[] = [];
+const seenMutationIds = new Set<string>();
+
+export const queueSequenceNodePathMutation = (
+ mutation: SequenceNodePathMutation,
+): void => {
+ if (seenMutationIds.has(mutation.mutationId)) {
+ return;
+ }
+
+ seenMutationIds.add(mutation.mutationId);
+ pendingMutations.push(mutation);
+};
+
+export const queueSequenceNodePathMutationFromApiResponse = (
+ response: unknown,
+): void => {
+ if (
+ typeof response !== 'object' ||
+ response === null ||
+ !('nodePathMutation' in response)
+ ) {
+ return;
+ }
+
+ const {nodePathMutation} = response;
+ if (
+ typeof nodePathMutation !== 'object' ||
+ nodePathMutation === null ||
+ !('mutationId' in nodePathMutation) ||
+ typeof nodePathMutation.mutationId !== 'string'
+ ) {
+ return;
+ }
+
+ queueSequenceNodePathMutation(nodePathMutation as SequenceNodePathMutation);
+};
+
+export const takePendingSequenceNodePathMutations =
+ (): SequenceNodePathMutation[] => pendingMutations.splice(0);
diff --git a/packages/transitions/src/test/transition-series-stack.test.tsx b/packages/transitions/src/test/transition-series-stack.test.tsx
index 5913b88708..e62233c8b1 100644
--- a/packages/transitions/src/test/transition-series-stack.test.tsx
+++ b/packages/transitions/src/test/transition-series-stack.test.tsx
@@ -43,6 +43,7 @@ const visualModeSetters = {
clearDragOverrides: () => undefined,
setEffectDragOverrides: () => undefined,
clearEffectDragOverrides: () => undefined,
+ remapPropStatuses: () => undefined,
setPropStatuses: () => undefined,
};