🎥 Make videos programmatically with React
`@remotion/studio`: Move keyframes with sequences (#8839)
Jonny Burgerf306e47982b2
diff --git a/.agents/skills/pr/SKILL.md b/.agents/skills/pr/SKILL.mdindex 4d348ad35f..898e9e0953 100644--- a/.agents/skills/pr/SKILL.md+++ b/.agents/skills/pr/SKILL.md@@ -37,6 +37,7 @@ Use the `gh` CLI to create a pull request and use the same format as above for tWhen creating the PR, do not pass the PR body inline through a shell command (for example, avoid `--body "..."` or heredocs in `bash`). Instead:1. Write the PR body to a temporary Markdown file in the system temp directory (for example `/tmp/remotion-pr-body.md`, or a unique file created under `/tmp`).+ - If the current work was started from, fixes, or is otherwise tied to a GitHub issue, include a closing keyword in the PR body such as `Closes #1234` or `Closes https://github.com/owner/repo/issues/1234`. Preserve the issue number or URL from the user's original request if they provided one.2. Create the PR with `gh pr create --title "<title>" --body-file <path-to-temp-md-file>`.Example: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.tsindex 07858277b5..b14142be8a 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@@ -1,12 +1,18 @@import {readFileSync} from 'node:fs';import {RenderInternals} from '@remotion/renderer';import type {+ MoveEffectKeyframe,+ MoveSequenceKeyframe,SaveSequencePropEdit,SaveSequencePropsRequest,SaveSequencePropsResponse,SaveSequencePropsResult,} from '@remotion/studio-shared';import {getAllSchemaKeys} from '@remotion/studio-shared';+import {+ updateEffectKeyframes,+ updateSequenceKeyframes,+} from '../../codemods/update-keyframes/update-keyframes';import {type RemovedProp,type SequencePropsNodeUpdate,@@ -22,6 +28,7 @@ import {} from '../undo-stack';import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {computeSequencePropsStatusFromContent} from './can-update-sequence-props';+import {logEffectUpdate} from './log-updates/log-effect-update';import {logUpdate} from './log-updates/log-update';import {withSourceFileWriteQueue} from './source-file-write-queue';@@ -41,6 +48,16 @@ type ResolvedSequencePropEdit = {type SequencePropEditGroup = {fileRelativeToRoot: string;edits: ResolvedSequencePropEdit[];+ sequenceKeyframes: ResolvedSequenceKeyframe[];+ effectKeyframes: ResolvedEffectKeyframe[];+};++type ResolvedSequenceKeyframe = MoveSequenceKeyframe & {+ index: number;+};++type ResolvedEffectKeyframe = MoveEffectKeyframe & {+ index: number;};const parseSequencePropEditValue = (@@ -75,6 +92,37 @@ type SequencePropEditResult = {formatted: boolean;};+type SequenceKeyframeLog = {+ fileRelativeToRoot: string;+ line: number;+ key: string;+ oldValueString: string;+ newValueString: string;+ formatted: boolean;+};++type EffectKeyframeLog = {+ fileRelativeToRoot: string;+ line: number;+ effectName: string;+ propKey: string;+ oldValueString: string;+ newValueString: string;+ formatted: boolean;+};++const groupBy = <T>(items: T[], getKey: (item: T) => string): T[][] => {+ const groups = new Map<string, T[]>();+ for (const item of items) {+ const key = getKey(item);+ const group = groups.get(key) ?? [];+ group.push(item);+ groups.set(key, group);+ }++ return [...groups.values()];+};+export const convertSequencePropEditToCodemodChange = (edit: Pick<ResolvedSequencePropEdit,@@ -113,18 +161,27 @@ export const saveSequencePropsHandler: ApiHandler<SaveSequencePropsRequest,SaveSequencePropsResponse> = ({- input: {edits, clientId, undoLabel, redoLabel},+ input: {+ edits,+ movedKeyframes = {sequenceKeyframes: [], effectKeyframes: []},+ clientId,+ undoLabel,+ redoLabel,+ },remotionRoot,logLevel,}) =>withSourceFileWriteQueue(async () => {- if (edits.length === 0) {+ const totalKeyframeMoves =+ movedKeyframes.sequenceKeyframes.length ++ movedKeyframes.effectKeyframes.length;+ if (edits.length === 0 && totalKeyframeMoves === 0) {throw new Error('No sequence prop edits to save');}RenderInternals.Log.trace({indent: false, logLevel},- `[save-sequence-props] Received request with ${edits.length} edit(s)`,+ `[save-sequence-props] Received request with ${edits.length} edit(s) and ${totalKeyframeMoves} moved keyframe(s)`,);const editGroups = new Map<string, SequencePropEditGroup>();@@ -142,6 +199,8 @@ export const saveSequencePropsHandler: ApiHandler<const group = editGroups.get(absolutePath) ?? {fileRelativeToRoot,edits: [],+ sequenceKeyframes: [],+ effectKeyframes: [],};group.edits.push({index,@@ -161,41 +220,190 @@ export const saveSequencePropsHandler: ApiHandler<editGroups.set(absolutePath, group);}+ for (const [+ index,+ keyframe,+ ] of movedKeyframes.sequenceKeyframes.entries()) {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName: keyframe.fileName,+ action: 'modify',+ });+ const group = editGroups.get(absolutePath) ?? {+ fileRelativeToRoot,+ edits: [],+ sequenceKeyframes: [],+ effectKeyframes: [],+ };+ group.sequenceKeyframes.push({...keyframe, index});+ editGroups.set(absolutePath, group);+ }++ for (const [index, keyframe] of movedKeyframes.effectKeyframes.entries()) {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName: keyframe.fileName,+ action: 'modify',+ });+ const group = editGroups.get(absolutePath) ?? {+ fileRelativeToRoot,+ edits: [],+ sequenceKeyframes: [],+ effectKeyframes: [],+ };+ group.effectKeyframes.push({...keyframe, index});+ editGroups.set(absolutePath, group);+ }+const snapshots: SequencePropUndoSnapshot[] = [];const outputByPath = new Map<string, string>();const resultByIndex = new Map<number, SequencePropEditResult>();+ const sequenceKeyframeLogs: SequenceKeyframeLog[] = [];+ const effectKeyframeLogs: EffectKeyframeLog[] = [];for (const [absolutePath, group] of editGroups) {const fileContents = readFileSync(absolutePath, 'utf-8');+ let output = fileContents;+ let firstLogLine = Number.POSITIVE_INFINITY;- const {- output,- formatted,- results: updateResults,- } = await updateMultipleSequenceProps({- input: fileContents,- changes: group.edits.map(convertSequencePropEditToCodemodChange),- prettierConfigOverride: null,- });+ if (group.edits.length > 0) {+ const {+ output: sequencePropsOutput,+ formatted,+ results: updateResults,+ } = await updateMultipleSequenceProps({+ input: output,+ changes: group.edits.map(convertSequencePropEditToCodemodChange),+ prettierConfigOverride: null,+ });+ output = sequencePropsOutput;+ const firstUpdate = updateResults[0];+ if (firstUpdate) {+ firstLogLine = Math.min(firstLogLine, firstUpdate.logLine);+ }++ for (const [resultIndex, result] of updateResults.entries()) {+ const edit = group.edits[resultIndex];+ resultByIndex.set(edit.index, {+ oldValueString: result.oldValueStrings[0],+ logLine: result.logLine,+ removedProps: result.removedProps,+ formatted,+ });+ }+ }++ for (const keyframeGroup of groupBy(group.sequenceKeyframes, (keyframe) =>+ JSON.stringify(keyframe.nodePath.nodePath),+ )) {+ const [firstSequenceKeyframe] = keyframeGroup;+ if (!firstSequenceKeyframe) {+ continue;+ }++ const updates = groupBy(keyframeGroup, (keyframe) => keyframe.key).map(+ (keyframes) => {+ const [firstMove] = keyframes;+ if (!firstMove) {+ throw new Error('Expected keyframe');+ }++ return {+ key: firstMove.key,+ operation: {+ type: 'move' as const,+ moves: keyframes.map((keyframe) => ({+ fromFrame: keyframe.fromFrame,+ toFrame: keyframe.toFrame,+ })),+ },+ };+ },+ );++ const result = await updateSequenceKeyframes({+ input: output,+ nodePath: firstSequenceKeyframe.nodePath.nodePath,+ schema: firstSequenceKeyframe.schema,+ updates,+ });+ output = result.output;+ firstLogLine = Math.min(firstLogLine, result.logLine);++ for (const [updateIndex, update] of updates.entries()) {+ sequenceKeyframeLogs.push({+ fileRelativeToRoot: group.fileRelativeToRoot,+ line: result.logLine,+ key: update.key,+ oldValueString: result.oldValueStrings[updateIndex],+ newValueString: result.newValueStrings[updateIndex],+ formatted: result.formatted,+ });+ }+ }++ for (const keyframeGroup of groupBy(+ group.effectKeyframes,+ (keyframe) =>+ `${JSON.stringify(keyframe.sequenceNodePath.nodePath)}:${+ keyframe.effectIndex+ }`,+ )) {+ const [firstEffectKeyframe] = keyframeGroup;+ if (!firstEffectKeyframe) {+ continue;+ }++ const updates = groupBy(keyframeGroup, (keyframe) => keyframe.key).map(+ (keyframes) => {+ const [firstMove] = keyframes;+ if (!firstMove) {+ throw new Error('Expected keyframe');+ }++ return {+ key: firstMove.key,+ operation: {+ type: 'move' as const,+ moves: keyframes.map((keyframe) => ({+ fromFrame: keyframe.fromFrame,+ toFrame: keyframe.toFrame,+ })),+ },+ };+ },+ );++ const result = await updateEffectKeyframes({+ input: output,+ sequenceNodePath: firstEffectKeyframe.sequenceNodePath.nodePath,+ effectIndex: firstEffectKeyframe.effectIndex,+ schema: firstEffectKeyframe.schema,+ updates,+ });+ output = result.output;+ firstLogLine = Math.min(firstLogLine, result.logLine);++ for (const [updateIndex, update] of updates.entries()) {+ effectKeyframeLogs.push({+ fileRelativeToRoot: group.fileRelativeToRoot,+ line: result.logLine,+ effectName: result.effectCallee,+ propKey: update.key,+ oldValueString: result.oldValueStrings[updateIndex],+ newValueString: result.newValueStrings[updateIndex],+ formatted: result.formatted,+ });+ }+ }- const [{logLine: firstLogLine}] = updateResults;outputByPath.set(absolutePath, output);snapshots.push({filePath: absolutePath,oldContents: fileContents,newContents: output,- logLine: firstLogLine,+ logLine: Number.isFinite(firstLogLine) ? firstLogLine : 1,});-- for (const [resultIndex, result] of updateResults.entries()) {- const edit = group.edits[resultIndex];- resultByIndex.set(edit.index, {- oldValueString: result.oldValueStrings[0],- logLine: result.logLine,- removedProps: result.removedProps,- formatted,- });- }}const undoMessage = `↩️ ${undoLabel}`;@@ -242,6 +450,37 @@ export const saveSequencePropsHandler: ApiHandler<}}+ for (const log of sequenceKeyframeLogs) {+ logUpdate({+ fileRelativeToRoot: log.fileRelativeToRoot,+ line: log.line,+ key: log.key,+ oldValueString: log.oldValueString,+ newValueString: log.newValueString,+ defaultValueString: null,+ formatted: log.formatted,+ logLevel,+ removedProps: [],+ addedProps: [],+ });+ }++ for (const log of effectKeyframeLogs) {+ logEffectUpdate({+ fileRelativeToRoot: log.fileRelativeToRoot,+ line: log.line,+ effectName: log.effectName,+ propKey: log.propKey,+ oldValueString: log.oldValueString,+ newValueString: log.newValueString,+ defaultValueString: null,+ formatted: log.formatted,+ logLevel,+ removedProps: [],+ addedProps: [],+ });+ }+printUndoHint(logLevel);const results: SaveSequencePropsResult[] = edits.map((edit) => {diff --git a/packages/studio-server/src/test/save-sequence-props.test.ts b/packages/studio-server/src/test/save-sequence-props.test.tsindex 479f419f19..bec4201af1 100644--- a/packages/studio-server/src/test/save-sequence-props.test.ts+++ b/packages/studio-server/src/test/save-sequence-props.test.ts@@ -1,9 +1,25 @@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 {InteractivitySchema} from 'remotion';+import {NoReactInternals} from 'remotion/no-react';+import {+ createFileWatcherRegistry,+ setFileWatcherRegistry,+} from '../file-watcher';+import {setLiveEventsListener} from '../preview-server/live-events';import {convertSequencePropEditToCodemodChange,+ saveSequencePropsHandler,shouldSuppressHmrForSequencePropEdits,} from '../preview-server/routes/save-sequence-props';+import {+ clearUndoStackForTests,+ getUndoStack,+ popUndo,+} from '../preview-server/undo-stack';+import {lineColumnToNodePath} from './test-utils';const starSchema = {points: {@@ -80,3 +96,107 @@ test('saveSequenceProps forwards element schemas to the codemod', () => {schema: starSchema,});});++test('saveSequenceProps batches sequence movement and keyframe movement into one undo entry', async () => {+ clearUndoStackForTests();+ const cleanupFileWatcher = setFileWatcherRegistry(+ createFileWatcherRegistry(),+ );+ const cleanupLiveEvents = setLiveEventsListener({+ addNewClientListener: () => () => undefined,+ closeConnections: () => Promise.resolve(),+ router: () => Promise.resolve(),+ sendEventToClient: () => undefined,+ sendEventToClientId: () => undefined,+ });+ const dir = mkdtempSync(join(tmpdir(), 'remotion-save-sequence-props-'));+ const fileName = 'Comp.tsx';+ const filePath = join(dir, fileName);+ const input = `import {Sequence, interpolate, useCurrentFrame} from 'remotion';++export const Comp = () => {+\tconst frame = useCurrentFrame();+\treturn (+\t\t<Sequence+\t\t\tfrom={0}+\t\t\tstyle={{opacity: interpolate(frame, [0, 20], [0, 1])}}+\t\t/>+\t);+};+`;+ const nodePath = {+ absolutePath: fileName,+ nodePath: lineColumnToNodePath(input, 6),+ sequenceKeys: ['from', 'style.opacity'],+ effectKeys: [],+ };++ try {+ writeFileSync(filePath, input);++ await saveSequencePropsHandler({+ input: {+ edits: [+ {+ fileName,+ nodePath,+ key: 'from',+ value: {type: 'json', serialized: JSON.stringify(10)},+ defaultValue: '0',+ schema: NoReactInternals.sequenceSchema,+ sourceEdit: null,+ },+ ],+ movedKeyframes: {+ sequenceKeyframes: [+ {+ fileName,+ nodePath,+ key: 'style.opacity',+ fromFrame: 0,+ toFrame: 10,+ schema: NoReactInternals.sequenceSchema,+ },+ {+ fileName,+ nodePath,+ key: 'style.opacity',+ fromFrame: 20,+ toFrame: 30,+ schema: NoReactInternals.sequenceSchema,+ },+ ],+ effectKeyframes: [],+ },+ clientId: 'test-client',+ undoLabel: 'Move sequence',+ redoLabel: 'Move sequence back',+ },+ entryPoint: '',+ remotionRoot: dir,+ request: {} as never,+ response: {} as never,+ logLevel: 'error',+ methods: {+ addJob: () => undefined,+ cancelJob: () => undefined,+ removeJob: () => undefined,+ },+ publicDir: '',+ binariesDirectory: null,+ });++ const output = readFileSync(filePath, 'utf-8');+ expect(output).toContain('from={10}');+ expect(output).toContain('interpolate(frame, [10, 30], [0, 1])');+ expect(getUndoStack()).toHaveLength(1);++ expect(popUndo()).toEqual({success: true});+ expect(readFileSync(filePath, 'utf-8')).toBe(input);+ } finally {+ clearUndoStackForTests();+ cleanupLiveEvents();+ cleanupFileWatcher();+ rmSync(dir, {force: true, recursive: true});+ }+});diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 595aeb525c..9a383022b5 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -330,6 +330,10 @@ export type SaveSequencePropEdit = {export type SaveSequencePropsRequest = {edits: SaveSequencePropEdit[];+ movedKeyframes?: {+ sequenceKeyframes: MoveSequenceKeyframe[];+ effectKeyframes: MoveEffectKeyframe[];+ };clientId: string;undoLabel: string;redoLabel: string;diff --git a/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx b/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsxindex 5484ed4d04..f4e719f0f6 100644--- a/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx+++ b/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx@@ -10,6 +10,7 @@ import React, {useState,} from 'react';import type {+ CanUpdateSequencePropStatusKeyframed,OverrideIdToNodePaths,PropStatuses,SequencePropsSubscriptionKey,@@ -27,6 +28,10 @@ import {forceSpecificCursor,stopForcingSpecificCursor,} from '../ForceSpecificCursor';+import type {+ MoveEffectKeyframeChange,+ MoveSequenceKeyframeChange,+} from './call-move-keyframe';import {saveSequenceProps,type SaveSequencePropChange,@@ -65,9 +70,94 @@ export type TimelineSequenceLeftEdgeDragTarget = {};export type TimelineSequenceFromDragTarget = {+ readonly effectKeyframes: TimelineSequenceEffectKeyframeDragTarget[];readonly fileName: string;readonly initialFrom: number;readonly nodePath: SequencePropsSubscriptionKey;+ readonly sequenceKeyframes: TimelineSequenceKeyframeDragTarget[];+};++type TimelineSequenceKeyframeDragTarget = {+ readonly fieldKey: string;+ readonly schema: InteractivitySchema;+ readonly status: CanUpdateSequencePropStatusKeyframed;+};++type TimelineSequenceEffectKeyframeDragTarget =+ TimelineSequenceKeyframeDragTarget & {+ readonly effectIndex: number;+ };++const getKeyframedSequenceDragTargets = ({+ nodePath,+ sequence,+ propStatuses,+}: {+ readonly nodePath: SequencePropsSubscriptionKey;+ readonly sequence: TSequence;+ readonly propStatuses: PropStatuses;+}): {+ readonly effectKeyframes: TimelineSequenceEffectKeyframeDragTarget[];+ readonly sequenceKeyframes: TimelineSequenceKeyframeDragTarget[];+} => {+ const status =+ propStatuses[Internals.makeSequencePropsSubscriptionKey(nodePath)];+ if (status === null || status === undefined || !status.canUpdate) {+ return {effectKeyframes: [], sequenceKeyframes: []};+ }++ const sequenceSchema = sequence.controls?.schema;+ const sequenceKeyframes =+ sequenceSchema === undefined+ ? []+ : Object.entries(status.props).flatMap(([fieldKey, propStatus]) =>+ propStatus.status === 'keyframed'+ ? [{fieldKey, schema: sequenceSchema, status: propStatus}]+ : [],+ );++ const effectKeyframes = status.effects.flatMap((effectStatus) => {+ if (!effectStatus.canUpdate) {+ return [];+ }++ const effectSchema = sequence.effects[effectStatus.effectIndex]?.schema;+ if (effectSchema === undefined) {+ return [];+ }++ return Object.entries(effectStatus.props).flatMap(+ ([fieldKey, propStatus]) =>+ propStatus.status === 'keyframed'+ ? [+ {+ effectIndex: effectStatus.effectIndex,+ fieldKey,+ schema: effectSchema,+ status: propStatus,+ },+ ]+ : [],+ );+ });++ return {effectKeyframes, sequenceKeyframes};+};++const shiftKeyframedStatus = ({+ status,+ deltaFrames,+}: {+ readonly status: CanUpdateSequencePropStatusKeyframed;+ readonly deltaFrames: number;+}): CanUpdateSequencePropStatusKeyframed => {+ return {+ ...status,+ keyframes: status.keyframes.map((keyframe) => ({+ ...keyframe,+ frame: keyframe.frame + deltaFrames,+ })),+ };};const canUpdateDurationInFrames = ({@@ -305,6 +395,49 @@ export const getTimelineSequenceFromDragChanges = ({});};+export const getTimelineSequenceFromDragKeyframeMoves = ({+ targets,+ deltaFrames,+}: {+ readonly targets: readonly TimelineSequenceFromDragTarget[];+ readonly deltaFrames: number;+}): {+ readonly effectKeyframes: MoveEffectKeyframeChange[];+ readonly sequenceKeyframes: MoveSequenceKeyframeChange[];+} => {+ if (deltaFrames === 0) {+ return {effectKeyframes: [], sequenceKeyframes: []};+ }++ return {+ sequenceKeyframes: targets.flatMap((target) =>+ target.sequenceKeyframes.flatMap((keyframeTarget) =>+ keyframeTarget.status.keyframes.map((keyframe) => ({+ fileName: target.fileName,+ nodePath: target.nodePath,+ fieldKey: keyframeTarget.fieldKey,+ fromFrame: keyframe.frame,+ toFrame: keyframe.frame + deltaFrames,+ schema: keyframeTarget.schema,+ })),+ ),+ ),+ effectKeyframes: targets.flatMap((target) =>+ target.effectKeyframes.flatMap((keyframeTarget) =>+ keyframeTarget.status.keyframes.map((keyframe) => ({+ fileName: target.fileName,+ nodePath: target.nodePath,+ effectIndex: keyframeTarget.effectIndex,+ fieldKey: keyframeTarget.fieldKey,+ fromFrame: keyframe.frame,+ toFrame: keyframe.frame + deltaFrames,+ schema: keyframeTarget.schema,+ })),+ ),+ ),+ };+};+const findSequenceTrack = ({tracks,nodePathInfo,@@ -548,10 +681,18 @@ export const getTimelineSequenceFromDragTargets = ({const key = stringifySequenceSubscriptionKey(nodePath);if (!targets.has(key)) {+ const {effectKeyframes, sequenceKeyframes} =+ getKeyframedSequenceDragTargets({+ nodePath,+ sequence: originalSequence,+ propStatuses,+ });targets.set(key, {+ effectKeyframes,fileName: nodePath.absolutePath,initialFrom: originalSequence.from,nodePath,+ sequenceKeyframes,});}}@@ -585,13 +726,24 @@ const clearDurationDragOverrides = ({const clearFromDragOverrides = ({clearDragOverrides,+ clearEffectDragOverrides,targets,}: {readonly clearDragOverrides: (nodePath: SequencePropsSubscriptionKey) => void;+ readonly clearEffectDragOverrides: (+ nodePath: SequencePropsSubscriptionKey,+ effectIndex: number,+ ) => void;readonly targets: readonly TimelineSequenceFromDragTarget[];}) => {for (const target of targets) {clearDragOverrides(target.nodePath);+ const effectIndexes = new Set(+ target.effectKeyframes.map((keyframe) => keyframe.effectIndex),+ );+ for (const effectIndex of effectIndexes) {+ clearEffectDragOverrides(target.nodePath, effectIndex);+ }}};@@ -857,9 +1009,13 @@ export const useTimelineSequenceFromDrag = ({readonly windowWidth: number;readonly timelineDurationInFrames: number;}) => {- const {setPropStatuses, setDragOverrides, clearDragOverrides} = useContext(- Internals.VisualModeSettersContext,- );+ const {+ setPropStatuses,+ setDragOverrides,+ clearDragOverrides,+ setEffectDragOverrides,+ clearEffectDragOverrides,+ } = useContext(Internals.VisualModeSettersContext);const propStatusesRef = useContext(Internals.VisualModePropStatusesRefContext,);@@ -884,6 +1040,8 @@ export const useTimelineSequenceFromDrag = ({setPropStatuses,setDragOverrides,clearDragOverrides,+ setEffectDragOverrides,+ clearEffectDragOverrides,previewServerState,overrideIdToNodePathMappings,});@@ -892,6 +1050,8 @@ export const useTimelineSequenceFromDrag = ({setPropStatuses,setDragOverrides,clearDragOverrides,+ setEffectDragOverrides,+ clearEffectDragOverrides,previewServerState,overrideIdToNodePathMappings,};@@ -910,6 +1070,7 @@ export const useTimelineSequenceFromDrag = ({const {setPropStatuses: latestSetPropStatuses,clearDragOverrides: latestClear,+ clearEffectDragOverrides: latestClearEffect,previewServerState: latestServerState,} = latestRef.current;@@ -917,14 +1078,21 @@ export const useTimelineSequenceFromDrag = ({targets: dragState.targets,deltaFrames: dragState.latestDeltaFrames,});+ const keyframeMoves = getTimelineSequenceFromDragKeyframeMoves({+ targets: dragState.targets,+ deltaFrames: dragState.latestDeltaFrames,+ });if (!commit ||latestServerState.type !== 'connected' ||- changes.length === 0+ (changes.length === 0 &&+ keyframeMoves.sequenceKeyframes.length === 0 &&+ keyframeMoves.effectKeyframes.length === 0)) {clearFromDragOverrides({clearDragOverrides: latestClear,+ clearEffectDragOverrides: latestClearEffect,targets: dragState.targets,});return;@@ -932,12 +1100,18 @@ export const useTimelineSequenceFromDrag = ({const savePromise = saveSequenceProps({changes,+ movedKeyframes: {+ sequenceKeyframes: keyframeMoves.sequenceKeyframes,+ effectKeyframes: keyframeMoves.effectKeyframes,+ },setPropStatuses: latestSetPropStatuses,clientId: latestServerState.clientId,undoLabel:- changes.length > 1 ? 'Move selected sequences' : 'Move sequence',+ dragState.targets.length > 1+ ? 'Move selected sequences'+ : 'Move sequence',redoLabel:- changes.length > 1+ dragState.targets.length > 1? 'Move selected sequences back': 'Move sequence back',});@@ -953,6 +1127,7 @@ export const useTimelineSequenceFromDrag = ({.finally(() => {clearFromDragOverrides({clearDragOverrides: latestClear,+ clearEffectDragOverrides: latestClearEffect,targets: dragState.targets,});});@@ -1028,16 +1203,43 @@ export const useTimelineSequenceFromDrag = ({const deltaFrames = Math.round(dx / dragState.pxPerFrame);dragState.latestDeltaFrames = deltaFrames;for (const target of dragState.targets) {+ const nextFrom = getTimelineSequenceFromDragValue({+ initialFrom: target.initialFrom,+ deltaFrames,+ });latestRef.current.setDragOverrides(target.nodePath,'from',- Internals.makeStaticDragOverride(- getTimelineSequenceFromDragValue({- initialFrom: target.initialFrom,- deltaFrames,- }),- ),+ Internals.makeStaticDragOverride(nextFrom),);+ for (const keyframeTarget of target.sequenceKeyframes) {+ latestRef.current.setDragOverrides(+ target.nodePath,+ keyframeTarget.fieldKey,+ {+ type: 'keyframed',+ status: shiftKeyframedStatus({+ status: keyframeTarget.status,+ deltaFrames,+ }),+ },+ );+ }++ for (const keyframeTarget of target.effectKeyframes) {+ latestRef.current.setEffectDragOverrides(+ target.nodePath,+ keyframeTarget.effectIndex,+ keyframeTarget.fieldKey,+ {+ type: 'keyframed',+ status: shiftKeyframedStatus({+ status: keyframeTarget.status,+ deltaFrames,+ }),+ },+ );+ }}};diff --git a/packages/studio/src/components/Timeline/call-move-keyframe.ts b/packages/studio/src/components/Timeline/call-move-keyframe.tsindex 8b3f40aa2a..38445fce43 100644--- a/packages/studio/src/components/Timeline/call-move-keyframe.ts+++ b/packages/studio/src/components/Timeline/call-move-keyframe.ts@@ -33,19 +33,17 @@ const groupByNodePath = <T extends {nodePath: SequencePropsSubscriptionKey}>(return [...groups.values()];};-export const callMoveKeyframes = ({+export const applyOptimisticKeyframeMoves = ({sequenceKeyframes,effectKeyframes,setPropStatuses,- clientId,}: {sequenceKeyframes: MoveSequenceKeyframeChange[];effectKeyframes: MoveEffectKeyframeChange[];setPropStatuses: SetPropStatuses;- clientId: string;-}): Promise<void> => {+}) => {if (sequenceKeyframes.length === 0 && effectKeyframes.length === 0) {- return Promise.resolve();+ return;}for (const keyframes of groupByNodePath(sequenceKeyframes)) {@@ -84,6 +82,28 @@ export const callMoveKeyframes = ({}),);}+};++export const callMoveKeyframes = ({+ sequenceKeyframes,+ effectKeyframes,+ setPropStatuses,+ clientId,+}: {+ sequenceKeyframes: MoveSequenceKeyframeChange[];+ effectKeyframes: MoveEffectKeyframeChange[];+ setPropStatuses: SetPropStatuses;+ clientId: string;+}): Promise<void> => {+ if (sequenceKeyframes.length === 0 && effectKeyframes.length === 0) {+ return Promise.resolve();+ }++ applyOptimisticKeyframeMoves({+ sequenceKeyframes,+ effectKeyframes,+ setPropStatuses,+ });return callApi('/api/move-keyframes', {sequenceKeyframes: sequenceKeyframes.map((keyframe) => ({diff --git a/packages/studio/src/components/Timeline/save-sequence-prop.ts b/packages/studio/src/components/Timeline/save-sequence-prop.tsindex bd8f58c3df..90aded9d85 100644--- a/packages/studio/src/components/Timeline/save-sequence-prop.ts+++ b/packages/studio/src/components/Timeline/save-sequence-prop.ts@@ -8,6 +8,11 @@ import type {InteractivitySchema,} from 'remotion';import {callApi} from '../call-api';+import {+ applyOptimisticKeyframeMoves,+ type MoveEffectKeyframeChange,+ type MoveSequenceKeyframeChange,+} from './call-move-keyframe';import {enqueueSavePropChange} from './save-prop-queue';export type SetPropStatuses = (@@ -29,6 +34,10 @@ export type SaveSequencePropChange = {type SaveSequencePropsOptions = {changes: SaveSequencePropChange[];+ movedKeyframes?: {+ sequenceKeyframes: MoveSequenceKeyframeChange[];+ effectKeyframes: MoveEffectKeyframeChange[];+ };setPropStatuses: SetPropStatuses;clientId: string;undoLabel: string;@@ -45,16 +54,27 @@ const serializeSequencePropValue = (value: unknown) => {export const saveSequenceProps = ({changes,+ movedKeyframes,setPropStatuses,clientId,undoLabel,redoLabel,}: SaveSequencePropsOptions): Promise<void> => {- if (changes.length === 0) {+ const sequenceKeyframes = movedKeyframes?.sequenceKeyframes ?? [];+ const effectKeyframes = movedKeyframes?.effectKeyframes ?? [];+ if (+ changes.length === 0 &&+ sequenceKeyframes.length === 0 &&+ effectKeyframes.length === 0+ ) {return Promise.resolve();}- if (changes.length === 1) {+ if (+ changes.length === 1 &&+ sequenceKeyframes.length === 0 &&+ effectKeyframes.length === 0+ ) {const change = changes[0];if (change === undefined) {throw new Error('Expected a sequence prop change');@@ -92,6 +112,12 @@ export const saveSequenceProps = ({});}+ applyOptimisticKeyframeMoves({+ sequenceKeyframes,+ effectKeyframes,+ setPropStatuses,+ });+for (const change of changes) {setPropStatuses(change.nodePath, (prev) =>optimisticUpdateForPropStatuses({@@ -116,6 +142,25 @@ export const saveSequenceProps = ({sourceEdit: change.sourceEdit ?? null,};}),+ movedKeyframes: {+ sequenceKeyframes: sequenceKeyframes.map((keyframe) => ({+ fileName: keyframe.fileName,+ nodePath: keyframe.nodePath,+ key: keyframe.fieldKey,+ fromFrame: keyframe.fromFrame,+ toFrame: keyframe.toFrame,+ schema: keyframe.schema,+ })),+ effectKeyframes: effectKeyframes.map((keyframe) => ({+ fileName: keyframe.fileName,+ sequenceNodePath: keyframe.nodePath,+ effectIndex: keyframe.effectIndex,+ key: keyframe.fieldKey,+ fromFrame: keyframe.fromFrame,+ toFrame: keyframe.toFrame,+ schema: keyframe.schema,+ })),+ },clientId,undoLabel,redoLabel,diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.tsindex 152b39db9b..c8964dcbdb 100644--- a/packages/studio/src/test/timeline-selection.test.ts+++ b/packages/studio/src/test/timeline-selection.test.ts@@ -101,6 +101,7 @@ import {getTimelineSequenceDurationDragTargets,getTimelineSequenceDurationDragValue,getTimelineSequenceFromDragChanges,+ getTimelineSequenceFromDragKeyframeMoves,getTimelineSequenceFromDragTargets,getTimelineSequenceFromDragValue,getTimelineSequenceLeftEdgeDragChanges,@@ -1433,6 +1434,140 @@ test('Timeline from drag applies the same delta to selected sequences', () => {).toEqual([12, 22]);});+test('Timeline from drag moves all owned sequence keyframes by the same delta', () => {+ const schema = {+ 'style.translate': {type: 'translate', default: '0px 0px'},+ opacity: {type: 'number', default: 1, hiddenFromList: false},+ } satisfies InteractivitySchema;+ const nodePathInfo = makeNodePathInfo(['body', 0], []);+ const nodePath = nodePathInfo.sequenceSubscriptionKey;+ const propStatuses = makeFromPropStatuses([nodePath]);+ propStatuses[Internals.makeSequencePropsSubscriptionKey(nodePath)] = {+ canUpdate: true,+ props: {+ from: {status: 'static', codeValue: 0},+ 'style.translate': {+ status: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: '0px 0px'},+ {frame: 40, value: '100px 50px'},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'extend', right: 'extend'},+ posterize: undefined,+ },+ opacity: {+ status: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 10, value: 0},+ {frame: 20, value: 1},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'clamp', right: 'clamp'},+ posterize: undefined,+ },+ },+ effects: [],+ };+ const targets = getTimelineSequenceFromDragTargets({+ draggedNodePathInfo: nodePathInfo,+ selectedItems: [{type: 'sequence', nodePathInfo}],+ sequences: [+ makeTimelineSequence({+ schema,+ duration: 40,+ from: 0,+ }),+ ],+ overrideIdsToNodePaths: {override: nodePath},+ propStatuses,+ });++ expect(+ getTimelineSequenceFromDragKeyframeMoves({+ targets: targets ?? [],+ deltaFrames: 12,+ }).sequenceKeyframes.map((keyframe) => [+ keyframe.fieldKey,+ keyframe.fromFrame,+ keyframe.toFrame,+ ]),+ ).toEqual([+ ['style.translate', 0, 12],+ ['style.translate', 40, 52],+ ['opacity', 10, 22],+ ['opacity', 20, 32],+ ]);+});++test('Timeline from drag moves owned effect keyframes by the same delta', () => {+ const schema = {} satisfies InteractivitySchema;+ const effectSchema = {+ intensity: {type: 'number', default: 0, hiddenFromList: false},+ } satisfies InteractivitySchema;+ const nodePathInfo = makeNodePathInfo(['body', 0], [], true, [+ ['0', 'intensity'],+ ]);+ const nodePath = nodePathInfo.sequenceSubscriptionKey;+ const propStatuses = makeFromPropStatuses([nodePath]);+ propStatuses[Internals.makeSequencePropsSubscriptionKey(nodePath)] = {+ canUpdate: true,+ props: {+ from: {status: 'static', codeValue: 0},+ },+ effects: [+ {+ canUpdate: true,+ callee: 'halftone',+ importPath: '@remotion/effects/halftone',+ effectIndex: 0,+ props: {+ intensity: {+ status: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 5, value: 10},+ {frame: 25, value: 20},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'clamp', right: 'clamp'},+ posterize: undefined,+ },+ },+ },+ ],+ };+ const targets = getTimelineSequenceFromDragTargets({+ draggedNodePathInfo: nodePathInfo,+ selectedItems: [{type: 'sequence', nodePathInfo}],+ sequences: [+ makeTimelineSequence({+ schema,+ effects: [{schema: effectSchema}],+ }),+ ],+ overrideIdsToNodePaths: {override: nodePath},+ propStatuses,+ });++ expect(+ getTimelineSequenceFromDragKeyframeMoves({+ targets: targets ?? [],+ deltaFrames: -7,+ }).effectKeyframes.map((keyframe) => [+ keyframe.effectIndex,+ keyframe.fieldKey,+ keyframe.fromFrame,+ keyframe.toFrame,+ ]),+ ).toEqual([+ [0, 'intensity', 5, -2],+ [0, 'intensity', 25, 18],+ ]);+});+test('Timeline from drag supports negative offsets', () => {expect(getTimelineSequenceFromDragValue({@@ -1536,9 +1671,11 @@ test('Timeline from drag removes the prop at the default value', () => {const [change] = getTimelineSequenceFromDragChanges({targets: [{+ effectKeyframes: [],fileName: nodePathInfo.sequenceSubscriptionKey.absolutePath,initialFrom: 5,nodePath: nodePathInfo.sequenceSubscriptionKey,+ sequenceKeyframes: [],},],deltaFrames: -5,