Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Fix first keyframe edits in concise-arrow components (#11646)

Igor Samokhovets6e8df3798d8d
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 8f47e1d3fa..06f2c93185 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -1743,7 +1743,7 @@ export const createBrowserStudioOperations = ({
],
})),
});
- return {success: true};
+ return {success: true, nodePathMutation: null};
},
deleteKeyframes: async ({sequenceKeyframes, effectKeyframes}) => {
await commitKeyframeMutations({
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 387e584b3b..c6ba95f599 100644
--- a/packages/studio-server/src/preview-server/routes/add-keyframes.ts
+++ b/packages/studio-server/src/preview-server/routes/add-keyframes.ts
@@ -6,7 +6,11 @@ import type {
AddKeyframesRequest,
AddKeyframesResponse,
AddSequenceKeyframe,
+ SequenceNodePathMutation,
+ SequenceNodePathRemapping,
} from '@remotion/studio-shared';
+import {captureJsxNodePaths} from '../../codemods/get-node-path-remappings';
+import {parseAst} from '../../codemods/parse-ast';
import {
updateEffectKeyframes,
updateSequenceKeyframes,
@@ -14,6 +18,7 @@ import {
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
import {
printUndoHint,
pushTransactionToUndoStack,
@@ -47,6 +52,7 @@ type UndoSnapshot = {
readonly oldContents: string;
readonly newContents: string;
readonly logLine: number;
+ readonly nodePathRemappings: SequenceNodePathRemapping[];
};
type SequenceLog = {
@@ -109,7 +115,7 @@ export const addKeyframes = async ({
}: AddKeyframesRequest & {
readonly remotionRoot: string;
readonly logLevel: LogLevel;
-}): Promise<void> => {
+}): Promise<SequenceNodePathMutation | null> => {
const totalKeyframes = sequenceKeyframes.length + effectKeyframes.length;
if (totalKeyframes === 0) {
throw new Error('No keyframes were specified for adding');
@@ -165,6 +171,28 @@ export const addKeyframes = async ({
const fileContents = readFileSync(absolutePath, 'utf-8');
let output = fileContents;
let firstLogLine = Number.POSITIVE_INFINITY;
+ const originalNodes = captureJsxNodePaths(parseAst(fileContents));
+
+ // Keyframe codemods may wrap a concise arrow in a return statement.
+ // JSX nodes remain in order, but their node paths can all change.
+ const currentPathFor = (
+ originalPath: ResolvedSequenceKeyframe['nodePath']['nodePath'],
+ ) => {
+ const index = originalNodes.findIndex(
+ ({nodePath}) =>
+ JSON.stringify(nodePath) === JSON.stringify(originalPath),
+ );
+ if (index === -1) {
+ throw new Error('Could not find the original JSX node for keyframing');
+ }
+
+ const currentNodes = captureJsxNodePaths(parseAst(output));
+ if (currentNodes.length !== originalNodes.length) {
+ throw new Error('Could not remap JSX nodes after keyframing');
+ }
+
+ return currentNodes[index].nodePath;
+ };
for (const keyframeGroup of groupBy(group.sequenceKeyframes, (keyframe) =>
JSON.stringify(keyframe.nodePath.nodePath),
@@ -176,7 +204,7 @@ export const addKeyframes = async ({
const result = await updateSequenceKeyframes({
input: output,
- nodePath: firstSequenceKeyframe.nodePath.nodePath,
+ nodePath: currentPathFor(firstSequenceKeyframe.nodePath.nodePath),
schema: firstSequenceKeyframe.schema,
videoConfigValues: firstSequenceKeyframe.nodePath.videoConfigValues,
updates: keyframeGroup.map((keyframe) => ({
@@ -217,7 +245,9 @@ export const addKeyframes = async ({
const result = await updateEffectKeyframes({
input: output,
- sequenceNodePath: firstEffectKeyframe.sequenceNodePath.nodePath,
+ sequenceNodePath: currentPathFor(
+ firstEffectKeyframe.sequenceNodePath.nodePath,
+ ),
effectIndex: firstEffectKeyframe.effectIndex,
schema: firstEffectKeyframe.schema,
videoConfigValues:
@@ -247,11 +277,22 @@ export const addKeyframes = async ({
}
}
+ const finalNodes = captureJsxNodePaths(parseAst(output));
+ if (finalNodes.length !== originalNodes.length) {
+ throw new Error('Could not remap JSX nodes after keyframing');
+ }
+
snapshots.push({
filePath: absolutePath,
oldContents: fileContents,
newContents: output,
logLine: Number.isFinite(firstLogLine) ? firstLogLine : 1,
+ nodePathRemappings: originalNodes.flatMap(({nodePath}, index) => {
+ const newNodePath = finalNodes[index].nodePath;
+ return JSON.stringify(nodePath) === JSON.stringify(newNodePath)
+ ? []
+ : [{oldNodePath: nodePath, newNodePath}];
+ }),
});
}
@@ -261,10 +302,18 @@ export const addKeyframes = async ({
throw new Error('No keyframes were specified for adding');
}
+ const filesWithRemappings = snapshots
+ .filter((snapshot) => snapshot.nodePathRemappings.length > 0)
+ .map((snapshot) => ({
+ absolutePath: snapshot.filePath,
+ remappings: snapshot.nodePathRemappings,
+ }));
pushTransactionToUndoStack({
snapshots: snapshots.map((snapshot) => ({
...snapshot,
- nodePathRemappings: null,
+ nodePathRemappings: snapshot.nodePathRemappings.length
+ ? snapshot.nodePathRemappings
+ : null,
})),
logLevel,
remotionRoot,
@@ -281,17 +330,26 @@ export const addKeyframes = async ({
undoRedoNavigation: null,
});
+ // Visual Mode evaluates keyframes from prop statuses. Remap and refresh the
+ // subscriptions instead of remounting the composition when a hook is added.
for (const snapshot of snapshots) {
suppressUndoStackInvalidation(snapshot.filePath);
suppressBundlerUpdateForFile(snapshot.filePath);
+
writeFileAndNotifyFileWatchers({
file: snapshot.filePath,
content: snapshot.newContents,
originatorClientId: clientId,
- metadata: null,
+ metadata: snapshot.nodePathRemappings.length
+ ? {skipSequencePropsUpdate: true}
+ : null,
});
}
+ const nodePathMutation = filesWithRemappings.length
+ ? broadcastSequenceNodePathMutation(filesWithRemappings, null)
+ : null;
+
for (const log of sequenceLogs) {
logUpdate({
fileRelativeToRoot: log.fileRelativeToRoot,
@@ -324,6 +382,7 @@ export const addKeyframes = async ({
}
printUndoHint(logLevel);
+ return nodePathMutation;
};
export const addKeyframesHandler: ApiHandler<
@@ -342,7 +401,7 @@ export const addKeyframesHandler: ApiHandler<
} keyframe(s)`,
);
- await addKeyframes({
+ const nodePathMutation = await addKeyframes({
sequenceKeyframes,
effectKeyframes,
clientId,
@@ -350,5 +409,5 @@ export const addKeyframesHandler: ApiHandler<
logLevel,
});
- 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 5f289d68e0..9b22923223 100644
--- a/packages/studio-server/src/test/add-keyframes.test.ts
+++ b/packages/studio-server/src/test/add-keyframes.test.ts
@@ -2,21 +2,27 @@ 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 type {InteractivitySchema} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
+import {captureJsxNodePaths} from '../codemods/get-node-path-remappings';
+import {parseAst} from '../codemods/parse-ast';
import {
createFileWatcherRegistry,
setFileWatcherRegistry,
} from '../file-watcher';
import {setLiveEventsListener} from '../preview-server/live-events';
-import {addKeyframes} from '../preview-server/routes/add-keyframes';
+import {
+ addKeyframes,
+ addKeyframesHandler,
+} from '../preview-server/routes/add-keyframes';
import {
clearUndoStackForTests,
getUndoStack,
popRedo,
popUndo,
} from '../preview-server/undo-stack';
-import {lineColumnToNodePath} from './test-utils';
+import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
const input = `import {tint} from '@remotion/effects/tint';
import {AbsoluteFill, interpolate, useCurrentFrame} from 'remotion';
@@ -166,6 +172,138 @@ test('addKeyframes batches sequence and effect adds into one undo entry', async
}
});
+test('first keyframe in a concise-arrow component remaps its JSX node path for the next edit', async () => {
+ clearUndoStackForTests();
+ const cleanupFileWatcher = setFileWatcherRegistry(
+ createFileWatcherRegistry(),
+ );
+ const events: EventSourceEvent[] = [];
+ const cleanupLiveEvents = setLiveEventsListener({
+ addNewClientListener: () => () => undefined,
+ closeConnections: () => Promise.resolve(),
+ router: () => Promise.resolve(),
+ sendEventToClient: (event) => events.push(event),
+ sendEventToClientId: () => true,
+ });
+ const dir = mkdtempSync(join(tmpdir(), 'remotion-element-color-keyframe-'));
+ const fileName = 'Comp.tsx';
+ const filePath = join(dir, fileName);
+ const source = `import {Interactive, Sequence} from 'remotion';
+
+const ColorCardInner = ({color, controls, durationInFrames, name}) => (
+ <Sequence controls={controls} durationInFrames={durationInFrames} name={name} style={{backgroundColor: color}} />
+);
+const ColorCard = Interactive.withSchema({
+ Component: ColorCardInner,
+ componentName: '<ColorCard>',
+ schema: {color: {type: 'color', default: '#ffffff'}},
+ supportsEffects: false,
+});
+export const Target = () => (
+ <ColorCard color="#ffffff" durationInFrames={60} name="Color card" />
+);
+`;
+ const schema = {
+ color: {type: 'color', default: '#ffffff'},
+ } as const satisfies InteractivitySchema;
+ const oldPath = lineContainingToNodePath(source, '<ColorCard color=');
+ const nodePath = {
+ absolutePath: filePath,
+ assetKeys: [],
+ effectKeys: [],
+ nodePath: oldPath,
+ sequenceKeys: ['color'],
+ videoConfigValues: null,
+ };
+ const handlerContext = {
+ binariesDirectory: null,
+ configFile: null,
+ entryPoint: filePath,
+ getDefaultCodingAgent: () => null,
+ getDefaultEditor: () => null,
+ logLevel: 'error' as const,
+ methods: {
+ addJob: () => undefined,
+ cancelJob: () => undefined,
+ removeJob: () => undefined,
+ },
+ publicDir: dir,
+ remotionRoot: dir,
+ request: {} as never,
+ response: {} as never,
+ };
+
+ try {
+ writeFileSync(filePath, source);
+ const first = await addKeyframesHandler({
+ ...handlerContext,
+ input: {
+ clientId: 'test-client',
+ effectKeyframes: [],
+ sequenceKeyframes: [
+ {
+ fileName,
+ nodePath,
+ key: 'color',
+ frame: 0,
+ value: JSON.stringify('#ffffff'),
+ schema,
+ },
+ ],
+ },
+ });
+ const mutation = first.nodePathMutation;
+ if (!mutation) {
+ throw new Error('Expected a JSX node path mutation');
+ }
+
+ const remapping = mutation.files[0].remappings.find(
+ (entry) => JSON.stringify(entry.oldNodePath) === JSON.stringify(oldPath),
+ );
+ if (!remapping?.newNodePath) {
+ throw new Error('The ColorCard invocation was not remapped');
+ }
+
+ expect(events).toContainEqual({
+ type: 'sequence-node-paths-remapped',
+ mutation,
+ });
+ const afterFirst = readFileSync(filePath, 'utf-8');
+ const colorCardNode = captureJsxNodePaths(parseAst(afterFirst)).at(-1);
+ if (!colorCardNode) {
+ throw new Error('ColorCard invocation missing after first keyframe');
+ }
+
+ expect(remapping.newNodePath).toEqual(colorCardNode.nodePath);
+ const second = await addKeyframesHandler({
+ ...handlerContext,
+ input: {
+ clientId: 'test-client',
+ effectKeyframes: [],
+ sequenceKeyframes: [
+ {
+ fileName,
+ nodePath: {...nodePath, nodePath: remapping.newNodePath},
+ key: 'color',
+ frame: 30,
+ value: JSON.stringify('#ff0000'),
+ schema,
+ },
+ ],
+ },
+ });
+ expect(second.success).toBe(true);
+ const output = readFileSync(filePath, 'utf-8');
+ expect(output).toContain("['#ffffff', '#ff0000']");
+ expect(output).toContain('[0, 30]');
+ } finally {
+ clearUndoStackForTests();
+ cleanupLiveEvents();
+ cleanupFileWatcher();
+ rmSync(dir, {force: true, recursive: true});
+ }
+});
+
test('addKeyframes adds a missing effect prop before keyframing it', async () => {
clearUndoStackForTests();
const cleanupFileWatcher = setFileWatcherRegistry(
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 3239902496..b4268ac8c3 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -742,6 +742,7 @@ export type AddKeyframesRequest = {
export type AddKeyframesResponse = {
success: true;
+ nodePathMutation: SequenceNodePathMutation | null;
};
export type KeyframeSettings =
diff --git a/packages/studio/src/components/Timeline/SequencePropsObserver.tsx b/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
index 4c2f2ba9fc..bb0140f756 100644
--- a/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
+++ b/packages/studio/src/components/Timeline/SequencePropsObserver.tsx
@@ -1,5 +1,5 @@
import {type EventSourceEvent} from '@remotion/studio-shared';
-import {useContext, useEffect, useLayoutEffect, useRef} from 'react';
+import {useContext, useEffect, useLayoutEffect, useRef, useState} from 'react';
import type {
SequencePropsStatusRemapping,
SequencePropsSubscriptionKey,
@@ -7,7 +7,10 @@ import type {
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 {
+ subscribeToSequenceNodePathMutations,
+ takePendingSequenceNodePathMutations,
+} from '../../helpers/sequence-node-path-mutations';
import {ExpandedTracksSetterContext} from '../ExpandedTracksProvider';
import {refreshSequencePropsSubscription} from './sequence-props-subscription-store';
import {useTimelineSelection} from './TimelineSelection';
@@ -29,6 +32,14 @@ export const SequencePropsObserver = () => {
Internals.OverrideIdsToNodePathsSettersContext,
);
const {fastRefreshes} = useContext(FastRefreshContext);
+ const [mutationVersion, setMutationVersion] = useState(0);
+ useEffect(
+ () =>
+ subscribeToSequenceNodePathMutations(() =>
+ setMutationVersion((version) => version + 1),
+ ),
+ [],
+ );
const {migrateExpandedTracksForSubscriptionKey} = useContext(
ExpandedTracksSetterContext,
);
@@ -80,10 +91,10 @@ export const SequencePropsObserver = () => {
continue;
}
- // Prop statuses follow source nodes to their new paths. Override IDs,
- // 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.
+ // Prop statuses follow source nodes to their new paths. Override IDs
+ // normally follow React's runtime instances, which may be reused at an
+ // old path. If the old path has no runtime replacement, move its mapping
+ // to the new source path and resubscribe without remounting the instance.
const runtimeNodePathIsSource = file.remappings.some(
(item) =>
item.oldNodePath !== null &&
@@ -155,9 +166,12 @@ export const SequencePropsObserver = () => {
overrideUpdates.push({
overrideId,
- nodePath: runtimeNodePathExists ? previousNodePath : null,
+ nodePath: runtimeNodePathExists ? previousNodePath : nextNodePath,
});
- if (runtimeNodePathExists && runtimeNodePathNeedsRefresh) {
+ if (
+ !wasDeleted &&
+ (!runtimeNodePathExists || runtimeNodePathNeedsRefresh)
+ ) {
overrideIdsToRefresh.add(overrideId);
}
}
@@ -184,6 +198,7 @@ export const SequencePropsObserver = () => {
}
}, [
fastRefreshes,
+ mutationVersion,
migrateExpandedTracksForSubscriptionKey,
propStatusesRef,
remapSelectionNodePaths,
diff --git a/packages/studio/src/helpers/sequence-node-path-mutations.ts b/packages/studio/src/helpers/sequence-node-path-mutations.ts
index 6621f5a4d6..074db1cd2e 100644
--- a/packages/studio/src/helpers/sequence-node-path-mutations.ts
+++ b/packages/studio/src/helpers/sequence-node-path-mutations.ts
@@ -3,6 +3,14 @@ import {requestInsertedElementSelection} from './inserted-element-selection';
const pendingMutations: SequenceNodePathMutation[] = [];
const seenMutationIds = new Set<string>();
+const mutationListeners = new Set<() => void>();
+
+export const subscribeToSequenceNodePathMutations = (listener: () => void) => {
+ mutationListeners.add(listener);
+ return () => {
+ mutationListeners.delete(listener);
+ };
+};
export const queueSequenceNodePathMutation = (
mutation: SequenceNodePathMutation,
@@ -13,6 +21,10 @@ export const queueSequenceNodePathMutation = (
seenMutationIds.add(mutation.mutationId);
pendingMutations.push(mutation);
+ for (const listener of mutationListeners) {
+ listener();
+ }
+
if (mutation.timelineSelection !== null) {
requestInsertedElementSelection({
compositionId: mutation.timelineSelection.compositionId,
diff --git a/packages/studio/src/test/sequence-props-observer.test.tsx b/packages/studio/src/test/sequence-props-observer.test.tsx
index 7334788185..732787b390 100644
--- a/packages/studio/src/test/sequence-props-observer.test.tsx
+++ b/packages/studio/src/test/sequence-props-observer.test.tsx
@@ -176,7 +176,7 @@ test('refreshes prop statuses for inserted and in-place updated nodes', () => {
}
});
-test('keeps the selected sequence selected after its node path changes', () => {
+test('remaps selection and refreshes the subscription after a JSX node path changes', () => {
const absolutePath = '/project/src/BarChart.tsx';
const originalNodePath: SequencePropsSubscriptionKey = {
absolutePath,
@@ -185,6 +185,10 @@ test('keeps the selected sequence selected after its node path changes', () => {
sequenceKeys: ['hidden', 'name'],
videoConfigValues: null,
};
+ const refreshedOverrideIds: string[] = [];
+ const unsubscribeRefresh = subscribeToSequencePropsRefresh('card', () =>
+ refreshedOverrideIds.push('card'),
+ );
const selectionRef: {
current: ReturnType<typeof useTimelineSelection> | null;
} = {current: null};
@@ -206,7 +210,9 @@ test('keeps the selected sequence selected after its node path changes', () => {
toggleTrack: () => undefined,
migrateExpandedTracksForSubscriptionKey: () => undefined,
} as never,
- overrideIdsGetter: {overrideIdToNodePathMappings: {}},
+ overrideIdsGetter: {
+ overrideIdToNodePathMappings: {card: originalNodePath},
+ },
overrideIdsSetter: {setOverrideIdToNodePath: () => undefined},
propStatusesRef: {current: {}},
visualModeSetters: {
@@ -240,18 +246,17 @@ test('keeps the selected sequence selected after its node path changes', () => {
]);
});
- queueSequenceNodePathMutation({
- mutationId: 'reorder-selection-test',
- timelineSelection: null,
- files: [
- {
- absolutePath,
- remappings: [
- {oldNodePath: ['body', 0], newNodePath: ['body', 1]},
- {oldNodePath: ['body', 1], newNodePath: ['body', 0]},
- ],
- },
- ],
+ act(() => {
+ queueSequenceNodePathMutation({
+ mutationId: 'reorder-selection-test',
+ timelineSelection: null,
+ files: [
+ {
+ absolutePath,
+ remappings: [{oldNodePath: ['body', 0], newNodePath: ['body', 1]}],
+ },
+ ],
+ });
});
rendered.rerender(renderTree(1));
@@ -262,4 +267,6 @@ test('keeps the selected sequence selected after its node path changes', () => {
.sequenceSubscriptionKey.nodePath
: null,
).toEqual(['body', 1]);
+ expect(refreshedOverrideIds).toEqual(['card']);
+ unsubscribeRefresh();
});