Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Fix sequence state after JSX structure edits

Jonny Burger44878113f738
diff --git a/bun.lock b/bun.lock
index 6c432fe596..d8d4c36c6d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1820,7 +1820,9 @@
"zod": "catalog:",
},
"devDependencies": {
+ "@happy-dom/global-registrator": "14.5.1",
"@remotion/eslint-config-internal": "workspace:*",
+ "@testing-library/react": "16.1.0",
"@types/semver": "7.5.3",
"@typescript/native-preview": "catalog:",
"eslint": "catalog:",
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index ae1944199c..fc5f8dd443 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -1275,7 +1275,6 @@ export const createBrowserStudioOperations = ({
nodePathMutationFiles: updates.map(({fileName, result}) => ({
absolutePath: fileName,
remappings: result.nodePathRemappings,
- restoredNodePaths: [],
})),
});
if (nodePathMutation === null) {
@@ -1317,7 +1316,6 @@ export const createBrowserStudioOperations = ({
{
absolutePath,
remappings: result.nodePathRemappings,
- restoredNodePaths: [],
},
],
});
@@ -1360,7 +1358,6 @@ export const createBrowserStudioOperations = ({
{
absolutePath,
remappings: result.nodePathRemappings,
- restoredNodePaths: [],
},
],
});
@@ -1478,7 +1475,6 @@ export const createBrowserStudioOperations = ({
{
absolutePath,
remappings: result.nodePathRemappings,
- restoredNodePaths: [],
},
],
});
@@ -1851,7 +1847,6 @@ export const createBrowserStudioOperations = ({
{
absolutePath,
remappings: result.nodePathRemappings,
- restoredNodePaths: [],
},
],
});
@@ -1900,7 +1895,6 @@ export const createBrowserStudioOperations = ({
{
absolutePath: result.filePath,
remappings: result.nodePathRemappings,
- restoredNodePaths: [],
},
],
});
@@ -2084,7 +2078,6 @@ export const createBrowserStudioOperations = ({
{
absolutePath: insertion.filePath,
remappings: insertion.nodePathRemappings,
- restoredNodePaths: [],
},
],
});
diff --git a/packages/browser-studio/src/browser-studio-project-controller.ts b/packages/browser-studio/src/browser-studio-project-controller.ts
index 959cf2c4a2..ed8ae6548f 100644
--- a/packages/browser-studio/src/browser-studio-project-controller.ts
+++ b/packages/browser-studio/src/browser-studio-project-controller.ts
@@ -7,7 +7,6 @@ import type {
SequenceNodePathRemapping,
UndoResponse,
} from '@remotion/studio-shared';
-import type {SequenceNodePath} from 'remotion';
import {
collectBrowserStudioProjectStorageGarbage,
createBrowserStudioProjectStorage,
@@ -565,20 +564,11 @@ export const createBrowserStudioProjectController = ({
redoStack.push(entry);
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] : [],
+ remappings: file.remappings.map(
+ (remapping): SequenceNodePathRemapping => ({
+ oldNodePath: remapping.newNodePath,
+ newNodePath: remapping.oldNodePath,
+ }),
),
}));
const nodePathMutation = commitProject({
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 11b31acbeb..95802b3ad4 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -216,9 +216,12 @@ 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,
+ expect(nodePathRemappings).toHaveLength(3);
+ expect(nodePathRemappings).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({oldNodePath: expect.any(Array)}),
+ expect.objectContaining({oldNodePath: null}),
+ ]),
);
});
@@ -288,13 +291,16 @@ export const Root = () => <Composition id="MyComp" component={Component} duratio
expect(result.nodePathMutation.files).toEqual([
{
absolutePath: fileName,
- remappings: [
+ remappings: expect.arrayContaining([
{
oldNodePath: subscription.nodePath.nodePath,
newNodePath: expect.any(Array),
},
- ],
- restoredNodePaths: [],
+ {
+ oldNodePath: null,
+ newNodePath: expect.any(Array),
+ },
+ ]),
},
]);
expect(
@@ -796,7 +802,6 @@ registerRoot(Root);`,
{
absolutePath: fileName,
remappings: expect.any(Array),
- restoredNodePaths: [],
},
]);
@@ -896,7 +901,6 @@ registerRoot(Root);`,
{
absolutePath: fileName,
remappings: expect.any(Array),
- restoredNodePaths: [],
},
]);
expect(
@@ -1461,7 +1465,6 @@ registerRoot(Root);`,
{
absolutePath: fileName,
remappings: expect.any(Array),
- restoredNodePaths: [],
},
]);
expect(
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 53f1ad9cb3..c94393b106 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
@@ -91,7 +91,13 @@ test('mutates virtual files, emits events, and preserves undo and redo history',
}
expect(undoResult.nodePathMutation.files).toEqual(
- insertResult.nodePathMutation.files,
+ insertResult.nodePathMutation.files.map((file) => ({
+ absolutePath: file.absolutePath,
+ remappings: file.remappings.map((remapping) => ({
+ oldNodePath: remapping.newNodePath,
+ newNodePath: remapping.oldNodePath,
+ })),
+ })),
);
expect(project.files['/project/src/Composition.tsx']).toBe(
initialProject.files['/project/src/Composition.tsx'],
@@ -135,7 +141,6 @@ test('mutates virtual files, emits events, and preserves undo and redo history',
newNodePath: null,
},
]),
- restoredNodePaths: [],
},
]);
const undoDeleteResult = await undo();
diff --git a/packages/studio-codemods/src/delete-jsx-node.ts b/packages/studio-codemods/src/delete-jsx-node.ts
index fd69707763..9e8d7fbbfa 100644
--- a/packages/studio-codemods/src/delete-jsx-node.ts
+++ b/packages/studio-codemods/src/delete-jsx-node.ts
@@ -24,6 +24,7 @@ import type {
TSAsExpression,
VariableDeclarator,
} from '@babel/types';
+import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import {
@@ -541,10 +542,7 @@ export const deleteJsxNodes = ({
formatted: boolean;
nodeLabels: string[];
logLines: number[];
- nodePathRemappings: Array<{
- oldNodePath: SequenceNodePath;
- newNodePath: SequenceNodePath | null;
- }>;
+ nodePathRemappings: SequenceNodePathRemapping[];
}> => {
if (nodePaths.length === 0) {
throw new Error('No JSX nodes were specified for deletion');
diff --git a/packages/studio-codemods/src/get-node-path-remappings.ts b/packages/studio-codemods/src/get-node-path-remappings.ts
index d9010fee47..11e585de19 100644
--- a/packages/studio-codemods/src/get-node-path-remappings.ts
+++ b/packages/studio-codemods/src/get-node-path-remappings.ts
@@ -8,6 +8,7 @@ import {parseAst} from './sequence-props/parse-ast';
export type CapturedJsxNodePath = {
node: JSXOpeningElement;
nodePath: SequenceNodePath;
+ signature: string;
};
export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {
@@ -17,6 +18,7 @@ export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {
captured.push({
node: path.node as JSXOpeningElement,
nodePath: getNodePathForRecastPath(path, ast),
+ signature: recast.prettyPrint(path.node as JSXOpeningElement).code,
});
return this.traverse(path);
},
@@ -63,17 +65,34 @@ export const getNodePathRemappings = ({
finalNodePathByNode.set(nodesAfterMutation[i], finalNodePaths[i]);
}
- const nodePathRemappings = captured.flatMap(({node, nodePath}) => {
- const newNodePath = finalNodePathByNode.get(node) ?? null;
- if (
- newNodePath !== null &&
- JSON.stringify(nodePath) === JSON.stringify(newNodePath)
- ) {
- return [];
+ const capturedNodes = new Set(captured.map(({node}) => node));
+ const nodePathRemappings: SequenceNodePathRemapping[] = captured.flatMap(
+ ({node, nodePath, signature}) => {
+ const newNodePath = finalNodePathByNode.get(node) ?? null;
+ if (
+ newNodePath !== null &&
+ JSON.stringify(nodePath) === JSON.stringify(newNodePath) &&
+ recast.prettyPrint(node).code === signature
+ ) {
+ return [];
+ }
+
+ return [{oldNodePath: nodePath, newNodePath}];
+ },
+ );
+
+ for (const node of nodesAfterMutation) {
+ if (capturedNodes.has(node)) {
+ continue;
}
- return [{oldNodePath: nodePath, newNodePath}];
- });
+ const newNodePath = finalNodePathByNode.get(node);
+ if (!newNodePath) {
+ throw new Error('Could not map inserted JSX node path');
+ }
+
+ nodePathRemappings.push({oldNodePath: null, newNodePath});
+ }
return {finalNodePathByNode, nodePathRemappings};
};
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index 8bbd7dd2e5..d482ebb4c1 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -973,7 +973,8 @@ const getNodePathRemappings = ({
});
let nextAfterIndex = 0;
- return before.flatMap(
+ const matchedAfterIndexes = new Set<number>();
+ const remappings = before.flatMap(
({nodePath, signature}): SequenceNodePathRemapping[] => {
const matchedIndex = after.findIndex(
(item, index) =>
@@ -986,6 +987,7 @@ const getNodePathRemappings = ({
}
nextAfterIndex = matchedIndex + 1;
+ matchedAfterIndexes.add(matchedIndex);
const newNodePath = after[matchedIndex].nodePath;
if (JSON.stringify(nodePath) === JSON.stringify(newNodePath)) {
return [];
@@ -994,6 +996,14 @@ const getNodePathRemappings = ({
return [{oldNodePath: nodePath, newNodePath}];
},
);
+
+ for (let i = 0; i < after.length; i++) {
+ if (!matchedAfterIndexes.has(i)) {
+ remappings.push({oldNodePath: null, newNodePath: after[i].nodePath});
+ }
+ }
+
+ return remappings;
};
export const insertSolidIntoProjectWithNodePathRemappings = <
diff --git a/packages/studio-codemods/src/split-video-from-audio.ts b/packages/studio-codemods/src/split-video-from-audio.ts
index 568f3b139b..a03117dc0d 100644
--- a/packages/studio-codemods/src/split-video-from-audio.ts
+++ b/packages/studio-codemods/src/split-video-from-audio.ts
@@ -8,6 +8,7 @@ import type {
Node,
ReturnStatement,
} from '@babel/types';
+import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import {
@@ -208,10 +209,7 @@ export const splitVideoFromAudio = async ({
formatted: boolean;
nodeLabel: string;
logLine: number;
- nodePathRemappings: Array<{
- oldNodePath: SequenceNodePath;
- newNodePath: SequenceNodePath | null;
- }>;
+ nodePathRemappings: SequenceNodePathRemapping[];
}> => {
const ast = parseAst(input);
const capturedNodePaths = captureJsxNodePaths(ast);
diff --git a/packages/studio-server/src/codemods/get-node-path-remappings.ts b/packages/studio-server/src/codemods/get-node-path-remappings.ts
index 84bed71bef..4f3219af32 100644
--- a/packages/studio-server/src/codemods/get-node-path-remappings.ts
+++ b/packages/studio-server/src/codemods/get-node-path-remappings.ts
@@ -8,6 +8,7 @@ import {parseAst} from './parse-ast';
export type CapturedJsxNodePath = {
node: JSXOpeningElement;
nodePath: SequenceNodePath;
+ signature: string;
};
export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {
@@ -17,6 +18,7 @@ export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {
captured.push({
node: path.node as JSXOpeningElement,
nodePath: getNodePathForRecastPath(path, ast),
+ signature: recast.prettyPrint(path.node as JSXOpeningElement).code,
});
return this.traverse(path);
},
@@ -63,17 +65,34 @@ export const getNodePathRemappings = ({
finalNodePathByNode.set(nodesAfterMutation[i], finalNodePaths[i]);
}
- const nodePathRemappings = captured.flatMap(({node, nodePath}) => {
- const newNodePath = finalNodePathByNode.get(node) ?? null;
- if (
- newNodePath !== null &&
- JSON.stringify(nodePath) === JSON.stringify(newNodePath)
- ) {
- return [];
+ const capturedNodes = new Set(captured.map(({node}) => node));
+ const nodePathRemappings: SequenceNodePathRemapping[] = captured.flatMap(
+ ({node, nodePath, signature}) => {
+ const newNodePath = finalNodePathByNode.get(node) ?? null;
+ if (
+ newNodePath !== null &&
+ JSON.stringify(nodePath) === JSON.stringify(newNodePath) &&
+ recast.prettyPrint(node).code === signature
+ ) {
+ return [];
+ }
+
+ return [{oldNodePath: nodePath, newNodePath}];
+ },
+ );
+
+ for (const node of nodesAfterMutation) {
+ if (capturedNodes.has(node)) {
+ continue;
}
- return [{oldNodePath: nodePath, newNodePath}];
- });
+ const newNodePath = finalNodePathByNode.get(node);
+ if (!newNodePath) {
+ throw new Error('Could not map inserted JSX node path');
+ }
+
+ nodePathRemappings.push({oldNodePath: null, newNodePath});
+ }
return {finalNodePathByNode, nodePathRemappings};
};
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 385b2c7fcc..a3bec79ef3 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
@@ -93,7 +93,6 @@ export const deleteJsxNodeHandler: ApiHandler<
updates.map((update) => ({
absolutePath: update.absolutePath,
remappings: update.nodePathRemappings,
- restoredNodePaths: [],
})),
);
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 ea0acba7f7..a69c830673 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
@@ -45,7 +45,6 @@ export const duplicateJsxNodeHandler: ApiHandler<
{
absolutePath,
remappings: nodePathRemappings,
- restoredNodePaths: [],
},
]);
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 f8fe4dde2e..254871d741 100644
--- a/packages/studio-server/src/preview-server/routes/insert-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts
@@ -207,7 +207,6 @@ export const insertElementHandler: ApiHandler<
{
absolutePath: inserted.fileName,
remappings: inserted.nodePathRemappings,
- restoredNodePaths: [],
},
]);
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 16b4f667f0..0fb6135ce4 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
@@ -264,7 +264,6 @@ export const insertJsxElementHandler: ApiHandler<
{
absolutePath: fileName,
remappings: nodePathRemappings,
- restoredNodePaths: [],
},
]);
if (insertedNodePath === null) {
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 b3092dca19..1b6c5030ec 100644
--- a/packages/studio-server/src/preview-server/routes/reorder-sequence.ts
+++ b/packages/studio-server/src/preview-server/routes/reorder-sequence.ts
@@ -55,7 +55,6 @@ export const reorderSequenceHandler: ApiHandler<
{
absolutePath,
remappings: nodePathRemappings,
- restoredNodePaths: [],
},
]);
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 29905fcf5e..93995bfdea 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
@@ -54,7 +54,6 @@ export const splitJsxSequenceHandler: ApiHandler<
{
absolutePath,
remappings: nodePathRemappings,
- restoredNodePaths: [],
},
]);
diff --git a/packages/studio-server/src/preview-server/routes/split-video-from-audio.ts b/packages/studio-server/src/preview-server/routes/split-video-from-audio.ts
index 55b3835924..fd5ed483ef 100644
--- a/packages/studio-server/src/preview-server/routes/split-video-from-audio.ts
+++ b/packages/studio-server/src/preview-server/routes/split-video-from-audio.ts
@@ -48,7 +48,6 @@ export const splitVideoFromAudioHandler: ApiHandler<
{
absolutePath,
remappings: nodePathRemappings,
- restoredNodePaths: [],
},
]);
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
index dc527778ae..475e23e367 100644
--- a/packages/studio-server/src/preview-server/sequence-node-path-mutation.ts
+++ b/packages/studio-server/src/preview-server/sequence-node-path-mutation.ts
@@ -3,7 +3,6 @@ import type {
SequenceNodePathMutation,
SequenceNodePathRemapping,
} from '@remotion/studio-shared';
-import type {SequenceNodePath} from 'remotion';
import {getLiveEventsListener} from './live-events';
const mutationSessionId = randomUUID();
@@ -13,7 +12,6 @@ export const broadcastSequenceNodePathMutation = (
files: Array<{
absolutePath: string;
remappings: SequenceNodePathRemapping[];
- restoredNodePaths: SequenceNodePath[];
}>,
): SequenceNodePathMutation => {
mutationCounter++;
diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.ts
index 026b19bd43..f61068045a 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -6,7 +6,6 @@ import type {
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 {
@@ -445,23 +444,11 @@ export function popUndo(): UndoResponse {
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] : [],
+ remappings: snapshot.nodePathRemappings.map(
+ (remapping): SequenceNodePathRemapping => ({
+ oldNodePath: remapping.newNodePath,
+ newNodePath: remapping.oldNodePath,
+ }),
),
},
];
@@ -555,7 +542,6 @@ export function popRedo(): RedoResponse {
{
absolutePath: snapshot.filePath,
remappings: snapshot.nodePathRemappings,
- restoredNodePaths: [],
},
];
});
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 75c96f6610..6aadc044fe 100644
--- a/packages/studio-server/src/test/delete-jsx-node.test.ts
+++ b/packages/studio-server/src/test/delete-jsx-node.test.ts
@@ -445,7 +445,6 @@ test('deleting a JSX node broadcasts node path mutations for all clients', async
newNodePath: lineColumnToNodePath(output, 7),
},
],
- restoredNodePaths: [],
},
]);
expect(
@@ -475,6 +474,10 @@ test('deleting a JSX node broadcasts node path mutations for all clients', async
{
absolutePath: filePath,
remappings: [
+ {
+ oldNodePath: null,
+ newNodePath: lineColumnToNodePath(interactiveSiblings, 6),
+ },
{
oldNodePath: lineColumnToNodePath(output, 6),
newNodePath: lineColumnToNodePath(interactiveSiblings, 7),
@@ -484,7 +487,6 @@ test('deleting a JSX node broadcasts node path mutations for all clients', async
newNodePath: lineColumnToNodePath(interactiveSiblings, 8),
},
],
- restoredNodePaths: [lineColumnToNodePath(interactiveSiblings, 6)],
},
]);
expect(
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 ca517600fc..b2d6663c5f 100644
--- a/packages/studio-server/src/test/duplicate-jsx-node.test.ts
+++ b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
@@ -28,20 +28,24 @@ test('duplicateJsxNode inserts a sibling JSX element', async () => {
test('duplicateJsxNode remaps following JSX siblings', async () => {
const input = `export const X = () => (
<div>
- <span data-name="duplicate" />
- <span data-name="following" />
+ <span name="duplicate" />
+ <span name="following" />
</div>
);
`;
const {output, nodePathRemappings} = await duplicateJsxNode({
input,
- nodePath: lineContainingToNodePath(input, 'data-name="duplicate"'),
+ nodePath: lineContainingToNodePath(input, 'name="duplicate"'),
});
expect(nodePathRemappings).toEqual([
{
- oldNodePath: lineContainingToNodePath(input, 'data-name="following"'),
- newNodePath: lineContainingToNodePath(output, 'data-name="following"'),
+ oldNodePath: lineContainingToNodePath(input, 'name="following"'),
+ newNodePath: lineContainingToNodePath(output, 'name="following"'),
+ },
+ {
+ oldNodePath: null,
+ newNodePath: lineContainingToNodePath(output, 'name="duplicate-copy"'),
},
]);
});
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
index c91948ca4d..fb88d056dd 100644
--- 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
@@ -110,7 +110,19 @@ test('JSX structure routes broadcast and return node path mutations before writi
watcherSkipSequencePropsUpdates.length = 0;
};
+ const invertMutationFiles = (
+ files: SequenceNodePathMutation['files'],
+ ): SequenceNodePathMutation['files'] =>
+ files.map((file) => ({
+ absolutePath: file.absolutePath,
+ remappings: file.remappings.map((remapping) => ({
+ oldNodePath: remapping.newNodePath,
+ newNodePath: remapping.oldNodePath,
+ })),
+ }));
+
try {
+ const forwardMutationFiles: SequenceNodePathMutation['files'][] = [];
let before = readFileSync(filePath, 'utf-8');
const subscriptionKey = (search: string) => ({
absolutePath: filePath,
@@ -135,6 +147,13 @@ test('JSX structure routes broadcast and return node path mutations before writi
}
assertMutation({before, mutation: reorderResponse.nodePathMutation});
+ forwardMutationFiles.push(reorderResponse.nodePathMutation.files);
+ expect(
+ reorderResponse.nodePathMutation.files[0].remappings.every(
+ (remapping) =>
+ remapping.oldNodePath !== null && remapping.newNodePath !== null,
+ ),
+ ).toBe(true);
before = readFileSync(filePath, 'utf-8');
const duplicateResponse = await duplicateJsxNodeHandler({
@@ -149,6 +168,13 @@ test('JSX structure routes broadcast and return node path mutations before writi
}
assertMutation({before, mutation: duplicateResponse.nodePathMutation});
+ forwardMutationFiles.push(duplicateResponse.nodePathMutation.files);
+ expect(
+ duplicateResponse.nodePathMutation.files[0].remappings.some(
+ (remapping) =>
+ remapping.oldNodePath === null && remapping.newNodePath !== null,
+ ),
+ ).toBe(true);
before = readFileSync(filePath, 'utf-8');
const splitResponse = await splitJsxSequenceHandler({
@@ -165,6 +191,13 @@ test('JSX structure routes broadcast and return node path mutations before writi
}
assertMutation({before, mutation: splitResponse.nodePathMutation});
+ forwardMutationFiles.push(splitResponse.nodePathMutation.files);
+ expect(
+ splitResponse.nodePathMutation.files[0].remappings.some(
+ (remapping) =>
+ remapping.oldNodePath === null && remapping.newNodePath !== null,
+ ),
+ ).toBe(true);
before = readFileSync(filePath, 'utf-8');
const insertResponse = await insertJsxElementHandler({
@@ -186,6 +219,7 @@ test('JSX structure routes broadcast and return node path mutations before writi
}
assertMutation({before, mutation: insertResponse.nodePathMutation});
+ forwardMutationFiles.push(insertResponse.nodePathMutation.files);
for (let i = 0; i < 4; i++) {
before = readFileSync(filePath, 'utf-8');
@@ -194,6 +228,9 @@ test('JSX structure routes broadcast and return node path mutations before writi
throw new Error('Expected undo to include a node path mutation');
}
+ expect(undoResponse.nodePathMutation.files).toEqual(
+ invertMutationFiles(forwardMutationFiles[3 - i]),
+ );
assertMutation({before, mutation: undoResponse.nodePathMutation});
}
@@ -206,6 +243,9 @@ test('JSX structure routes broadcast and return node path mutations before writi
throw new Error('Expected redo to include a node path mutation');
}
+ expect(redoResponse.nodePathMutation.files).toEqual(
+ forwardMutationFiles[i],
+ );
assertMutation({before, mutation: redoResponse.nodePathMutation});
}
} finally {
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 57691d651b..ad61667078 100644
--- a/packages/studio-server/src/test/resolve-composition-component.test.ts
+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts
@@ -478,6 +478,14 @@ test('wraps a self-closing root in a Sequence before inserting', async () => {
oldNodePath: lineContainingToNodePath(componentInput, '<Video'),
newNodePath: lineContainingToNodePath(result.output, '<Video'),
},
+ {
+ oldNodePath: null,
+ newNodePath: lineContainingToNodePath(result.output, '<Sequence>'),
+ },
+ {
+ oldNodePath: null,
+ newNodePath: lineContainingToNodePath(result.output, '<Audio'),
+ },
]);
} finally {
await fs.rm(tempDir, {recursive: true, force: true});
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 9df0aebf19..fe04f23ce1 100644
--- a/packages/studio-server/src/test/split-jsx-sequence.test.ts
+++ b/packages/studio-server/src/test/split-jsx-sequence.test.ts
@@ -64,10 +64,18 @@ test('splitJsxSequence remaps following JSX siblings', async () => {
});
expect(nodePathRemappings).toEqual([
+ {
+ oldNodePath: lineContainingToNodePath(input, 'name="split"'),
+ newNodePath: lineContainingToNodePath(output, 'name="split"'),
+ },
{
oldNodePath: lineContainingToNodePath(input, 'name="following"'),
newNodePath: lineContainingToNodePath(output, 'name="following"'),
},
+ {
+ oldNodePath: null,
+ newNodePath: lineContainingToNodePath(output, 'from={30}'),
+ },
]);
});
diff --git a/packages/studio-shared/src/sequence-node-path-mutation.ts b/packages/studio-shared/src/sequence-node-path-mutation.ts
index 08b643f85f..054b2e8f51 100644
--- a/packages/studio-shared/src/sequence-node-path-mutation.ts
+++ b/packages/studio-shared/src/sequence-node-path-mutation.ts
@@ -1,7 +1,9 @@
import type {SequenceNodePath} from 'remotion';
export type SequenceNodePathRemapping = {
- oldNodePath: SequenceNodePath;
+ /** `null` means the JSX node was inserted by this mutation. */
+ oldNodePath: SequenceNodePath | null;
+ /** `null` means the JSX node was deleted by this mutation. */
newNodePath: SequenceNodePath | null;
};
@@ -10,6 +12,5 @@ export type SequenceNodePathMutation = {
files: Array<{
absolutePath: string;
remappings: SequenceNodePathRemapping[];
- restoredNodePaths: SequenceNodePath[];
}>;
};
diff --git a/packages/studio/bunfig.toml b/packages/studio/bunfig.toml
new file mode 100644
index 0000000000..d20eff30d4
--- /dev/null
+++ b/packages/studio/bunfig.toml
@@ -0,0 +1,2 @@
+[test]
+preload = "./happydom.ts"
diff --git a/packages/studio/happydom.ts b/packages/studio/happydom.ts
new file mode 100644
index 0000000000..081c9085a0
--- /dev/null
+++ b/packages/studio/happydom.ts
@@ -0,0 +1,4 @@
+import {GlobalRegistrator} from '@happy-dom/global-registrator';
+
+GlobalRegistrator.register();
+window.origin = 'http://localhost:3000';
diff --git a/packages/studio/package.json b/packages/studio/package.json
index 2b57a55f84..433063f453 100644
--- a/packages/studio/package.json
+++ b/packages/studio/package.json
@@ -46,8 +46,10 @@
"zod": "catalog:"
},
"devDependencies": {
+ "@happy-dom/global-registrator": "14.5.1",
"react": "catalog:",
"react-dom": "catalog:",
+ "@testing-library/react": "16.1.0",
"@types/semver": "7.5.3",
"@remotion/eslint-config-internal": "workspace:*",
"eslint": "catalog:",
diff --git a/packages/studio/src/components/Timeline/SequencePropsObserver.tsx b/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
index 3364a8b210..3274202c3d 100644
--- a/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
+++ b/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
@@ -9,6 +9,7 @@ import {FastRefreshContext} from '../../fast-refresh-context';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import {takePendingSequenceNodePathMutations} from '../../helpers/sequence-node-path-mutations';
import {ExpandedTracksSetterContext} from '../ExpandedTracksProvider';
+import {refreshSequencePropsSubscription} from './sequence-props-subscription-store';
export const SequencePropsObserver = () => {
const {subscribeToEvent} = useContext(StudioServerConnectionCtx);
@@ -57,6 +58,7 @@ export const SequencePropsObserver = () => {
overrideId: string;
nodePath: SequencePropsSubscriptionKey | null;
}> = [];
+ const overrideIdsToRefresh = new Set<string>();
for (const [overrideId, previousNodePath] of Object.entries(
overrideIdToNodePathMappingsRef.current,
@@ -65,6 +67,7 @@ export const SequencePropsObserver = () => {
let wasRemapped = false;
let wasDeleted = false;
let runtimeNodePathExists = true;
+ let runtimeNodePathNeedsRefresh = false;
const previousNodePathString = JSON.stringify(previousNodePath.nodePath);
for (const mutation of mutations) {
@@ -74,11 +77,12 @@ export const SequencePropsObserver = () => {
}
// 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.
+ // however, follow React's runtime instances. Structural edits may reuse
+ // the instance already at a path, so only remove mappings from paths
+ // which are sources without also being destinations.
const runtimeNodePathIsSource = file.remappings.some(
(item) =>
+ item.oldNodePath !== null &&
JSON.stringify(item.oldNodePath) === previousNodePathString,
);
const runtimeNodePathIsDestination = file.remappings.some(
@@ -86,33 +90,36 @@ export const SequencePropsObserver = () => {
item.newNodePath !== null &&
JSON.stringify(item.newNodePath) === previousNodePathString,
);
- const runtimeNodePathWasRestored = file.restoredNodePaths.some(
- (item) => JSON.stringify(item) === previousNodePathString,
+ const runtimeNodePathWasInserted = file.remappings.some(
+ (item) =>
+ item.oldNodePath === null &&
+ item.newNodePath !== null &&
+ JSON.stringify(item.newNodePath) === previousNodePathString,
+ );
+ const runtimeNodePathWasUpdated = file.remappings.some(
+ (item) =>
+ item.oldNodePath !== null &&
+ item.newNodePath !== null &&
+ JSON.stringify(item.oldNodePath) === previousNodePathString &&
+ JSON.stringify(item.newNodePath) === previousNodePathString,
);
if (runtimeNodePathIsSource) {
- runtimeNodePathExists =
- runtimeNodePathIsDestination || runtimeNodePathWasRestored;
- } else if (
- runtimeNodePathIsDestination ||
- runtimeNodePathWasRestored
- ) {
+ runtimeNodePathExists = runtimeNodePathIsDestination;
+ runtimeNodePathNeedsRefresh =
+ runtimeNodePathWasInserted || runtimeNodePathWasUpdated;
+ } else if (runtimeNodePathIsDestination) {
runtimeNodePathExists = true;
+ runtimeNodePathNeedsRefresh =
+ runtimeNodePathWasInserted || runtimeNodePathWasUpdated;
}
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) =>
+ item.oldNodePath !== null &&
JSON.stringify(item.oldNodePath) === JSON.stringify(nodePath),
);
if (!remapping) {
@@ -146,6 +153,9 @@ export const SequencePropsObserver = () => {
overrideId,
nodePath: runtimeNodePathExists ? previousNodePath : null,
});
+ if (runtimeNodePathExists && runtimeNodePathNeedsRefresh) {
+ overrideIdsToRefresh.add(overrideId);
+ }
}
remapPropStatuses(statusRemappings);
@@ -154,6 +164,10 @@ export const SequencePropsObserver = () => {
setOverrideIdToNodePath(event.overrideId, event.nodePath);
}
+ for (const overrideId of overrideIdsToRefresh) {
+ refreshSequencePropsSubscription(overrideId);
+ }
+
for (const event of statusRemappings) {
if (event.nodePath === null) {
continue;
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 5a62422ceb..37e4177718 100644
--- a/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts
+++ b/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts
@@ -51,6 +51,29 @@ type Entry = {
};
const entries = new Map<Key, Entry>();
+const refreshListeners = new Map<string, Set<() => void>>();
+
+export const subscribeToSequencePropsRefresh = (
+ overrideId: string,
+ listener: () => void,
+): (() => void) => {
+ const listeners = refreshListeners.get(overrideId) ?? new Set();
+ listeners.add(listener);
+ refreshListeners.set(overrideId, listeners);
+
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) {
+ refreshListeners.delete(overrideId);
+ }
+ };
+};
+
+export const refreshSequencePropsSubscription = (overrideId: string): void => {
+ for (const listener of refreshListeners.get(overrideId) ?? []) {
+ listener();
+ }
+};
export const acquireSequencePropsSubscription = ({
fileName,
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 e8f0a10218..d197477ff2 100644
--- a/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts
+++ b/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts
@@ -2,7 +2,7 @@ import {
getAllSchemaKeys,
stringifySequenceSubscriptionKey,
} from '@remotion/studio-shared';
-import {useContext, useEffect, useMemo, useRef} from 'react';
+import {useContext, useEffect, useMemo, useRef, useState} from 'react';
import type {
JsxComponentIdentity,
SequencePropsSubscriptionKey,
@@ -12,7 +12,10 @@ import {Internals} from 'remotion';
import type {OriginalPosition} from '../../error-overlay/react-overlay/utils/get-source-map';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import {ExpandedTracksSetterContext} from '../ExpandedTracksProvider';
-import {acquireSequencePropsSubscription} from './sequence-props-subscription-store';
+import {
+ acquireSequencePropsSubscription,
+ subscribeToSequencePropsRefresh,
+} from './sequence-props-subscription-store';
import {shouldSubscribeToSourceFile} from './should-subscribe-to-source-file';
export const useSequencePropsSubscription = ({
@@ -44,6 +47,7 @@ export const useSequencePropsSubscription = ({
);
const {previewServerState: state} = useContext(StudioServerConnectionCtx);
+ const [refreshToken, setRefreshToken] = useState(0);
const previousNodePathRef = useRef<SequencePropsSubscriptionKey | null>(null);
const overrideIdToNodePathMappingsRef = useRef(overrideIdToNodePathMappings);
overrideIdToNodePathMappingsRef.current = overrideIdToNodePathMappings;
@@ -76,6 +80,12 @@ export const useSequencePropsSubscription = ({
const locationLine = validatedLocation?.line ?? null;
const locationColumn = validatedLocation?.column ?? null;
+ useEffect(() => {
+ return subscribeToSequencePropsRefresh(overrideId, () => {
+ setRefreshToken((token) => token + 1);
+ });
+ }, [overrideId]);
+
useEffect(() => {
if (
!clientId ||
@@ -160,6 +170,7 @@ export const useSequencePropsSubscription = ({
migrateExpandedTracksForSubscriptionKey,
overrideId,
preferMappedNodePath,
+ refreshToken,
schema,
setPropStatuses,
setOverrideIdToNodePath,
diff --git a/packages/studio/src/test/sequence-props-observer.test.tsx b/packages/studio/src/test/sequence-props-observer.test.tsx
new file mode 100644
index 0000000000..4d9369b6e4
--- /dev/null
+++ b/packages/studio/src/test/sequence-props-observer.test.tsx
@@ -0,0 +1,142 @@
+import {afterEach, expect, test} from 'bun:test';
+import {cleanup, render} from '@testing-library/react';
+import {Internals, type SequencePropsSubscriptionKey} from 'remotion';
+import {ExpandedTracksSetterContext} from '../components/ExpandedTracksProvider';
+import {subscribeToSequencePropsRefresh} from '../components/Timeline/sequence-props-subscription-store';
+import {SequencePropsObserver} from '../components/Timeline/SequencePropsObserver';
+import {FastRefreshContext} from '../fast-refresh-context';
+import {StudioServerConnectionCtx} from '../helpers/client-id';
+import {queueSequenceNodePathMutation} from '../helpers/sequence-node-path-mutations';
+
+afterEach(cleanup);
+
+test('refreshes prop statuses for inserted and in-place updated nodes', () => {
+ const absolutePath = '/project/src/BarChart.tsx';
+ const originalPath = ['body', 0] as const;
+ const insertedPath = ['body', 1] as const;
+ const shiftedPath = ['body', 2] as const;
+ const originalNodePath: SequencePropsSubscriptionKey = {
+ absolutePath,
+ effectKeys: [],
+ nodePath: [...originalPath],
+ sequenceKeys: ['hidden', 'name'],
+ videoConfigValues: null,
+ };
+ const insertedNodePath: SequencePropsSubscriptionKey = {
+ absolutePath,
+ effectKeys: [],
+ nodePath: [...insertedPath],
+ sequenceKeys: ['hidden', 'name'],
+ videoConfigValues: null,
+ };
+ const refreshedOverrideIds: string[] = [];
+ const setOverrideCalls: Array<{
+ overrideId: string;
+ nodePath: SequencePropsSubscriptionKey | null;
+ }> = [];
+ const statusRemappingCalls: unknown[] = [];
+ const migrationCalls: unknown[] = [];
+ const unsubscribeOriginalRefresh = subscribeToSequencePropsRefresh(
+ 'original-override',
+ () => refreshedOverrideIds.push('original-override'),
+ );
+ const unsubscribeInsertedRefresh = subscribeToSequencePropsRefresh(
+ 'inserted-override',
+ () => refreshedOverrideIds.push('inserted-override'),
+ );
+
+ queueSequenceNodePathMutation({
+ mutationId: 'inserted-runtime-path-test',
+ files: [
+ {
+ absolutePath,
+ remappings: [
+ {oldNodePath: [...originalPath], newNodePath: [...originalPath]},
+ {oldNodePath: [...insertedPath], newNodePath: [...shiftedPath]},
+ {oldNodePath: null, newNodePath: [...insertedPath]},
+ ],
+ },
+ ],
+ });
+
+ try {
+ render(
+ <StudioServerConnectionCtx.Provider
+ value={
+ {
+ previewServerState: {type: 'connected', clientId: 'client'},
+ configFileChangeRevision: 0,
+ subscribeToEvent: () => () => undefined,
+ } as never
+ }
+ >
+ <FastRefreshContext.Provider
+ value={{
+ fastRefreshes: 1,
+ manualRefreshes: 0,
+ increaseManualRefreshes: () => undefined,
+ }}
+ >
+ <ExpandedTracksSetterContext.Provider
+ value={
+ {
+ expandParentTracks: () => undefined,
+ toggleTrack: () => undefined,
+ migrateExpandedTracksForSubscriptionKey: (
+ oldKey: SequencePropsSubscriptionKey,
+ newKey: SequencePropsSubscriptionKey,
+ ) => migrationCalls.push([oldKey, newKey]),
+ } as never
+ }
+ >
+ <Internals.OverrideIdsToNodePathsGettersContext.Provider
+ value={{
+ overrideIdToNodePathMappings: {
+ 'original-override': originalNodePath,
+ 'inserted-override': insertedNodePath,
+ },
+ }}
+ >
+ <Internals.OverrideIdsToNodePathsSettersContext.Provider
+ value={{
+ setOverrideIdToNodePath: (overrideId, nodePath) =>
+ setOverrideCalls.push({overrideId, nodePath}),
+ }}
+ >
+ <Internals.VisualModePropStatusesRefContext.Provider
+ value={{current: {}}}
+ >
+ <Internals.VisualModeSettersContext.Provider
+ value={
+ {
+ remapPropStatuses: (remappings: unknown) =>
+ statusRemappingCalls.push(remappings),
+ setPropStatuses: () => undefined,
+ } as never
+ }
+ >
+ <SequencePropsObserver />
+ </Internals.VisualModeSettersContext.Provider>
+ </Internals.VisualModePropStatusesRefContext.Provider>
+ </Internals.OverrideIdsToNodePathsSettersContext.Provider>
+ </Internals.OverrideIdsToNodePathsGettersContext.Provider>
+ </ExpandedTracksSetterContext.Provider>
+ </FastRefreshContext.Provider>
+ </StudioServerConnectionCtx.Provider>,
+ );
+
+ expect(refreshedOverrideIds).toEqual([
+ 'original-override',
+ 'inserted-override',
+ ]);
+ expect(setOverrideCalls).toEqual([
+ {overrideId: 'original-override', nodePath: originalNodePath},
+ {overrideId: 'inserted-override', nodePath: insertedNodePath},
+ ]);
+ expect(statusRemappingCalls).toHaveLength(1);
+ expect(migrationCalls).toHaveLength(2);
+ } finally {
+ unsubscribeOriginalRefresh();
+ unsubscribeInsertedRefresh();
+ }
+});