🎥 Make videos programmatically with React
`@remotion/studio`: Drag keyframes in timeline (#8110)
Jonny Burgeraaae77b77849
diff --git a/packages/core/src/interpolate-keyframed-status.ts b/packages/core/src/interpolate-keyframed-status.tsindex c8b42b354d..5cb4942765 100644--- a/packages/core/src/interpolate-keyframed-status.ts+++ b/packages/core/src/interpolate-keyframed-status.ts@@ -28,8 +28,9 @@ export const interpolateKeyframedStatus = ({return null;}- const inputRange = keyframes.map((k) => k.frame);- const outputs = keyframes.map((k) => k.value);+ const sortedKeyframes = [...keyframes].sort((a, b) => a.frame - b.frame);+ const inputRange = sortedKeyframes.map((k) => k.frame);+ const outputs = sortedKeyframes.map((k) => k.value);if (interpolationFunction === 'interpolateColors') {if (!outputs.every((v) => typeof v === 'string')) {diff --git a/packages/core/src/test/interpolate-keyframed-status.test.ts b/packages/core/src/test/interpolate-keyframed-status.test.tsindex 74d04a1642..52e423c2fe 100644--- a/packages/core/src/test/interpolate-keyframed-status.test.ts+++ b/packages/core/src/test/interpolate-keyframed-status.test.ts@@ -20,6 +20,26 @@ test('interpolates linear numeric keyframes', () => {expect(result).toBe(50);});+test('sorts keyframes before interpolating numeric values', () => {+ const result = interpolateKeyframedStatus({+ frame: 75,+ status: {+ status: 'keyframed',+ codeValue: undefined,+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 100, value: 100},+ {frame: 50, value: 50},+ {frame: 0, value: 0},+ ],+ easing: ['linear', 'linear'],+ clamping: {left: 'extend', right: 'extend'},+ posterize: undefined,+ },+ });+ expect(result).toBe(75);+});+test('clamps when extrapolation is clamp', () => {const result = interpolateKeyframedStatus({frame: 120,diff --git a/packages/core/src/test/timeline-position-state.test.ts b/packages/core/src/test/timeline-position-state.test.tsnew file mode 100644index 0000000000..47de602677--- /dev/null+++ b/packages/core/src/test/timeline-position-state.test.ts@@ -0,0 +1,10 @@+import {expect, test} from 'bun:test';+import {clampFrameToCompositionRange} from '../timeline-position-state';++test('clamps timeline frames to the composition range', () => {+ expect(clampFrameToCompositionRange(-1, 100)).toBe(0);+ expect(clampFrameToCompositionRange(0, 100)).toBe(0);+ expect(clampFrameToCompositionRange(50, 100)).toBe(50);+ expect(clampFrameToCompositionRange(99, 100)).toBe(99);+ expect(clampFrameToCompositionRange(100, 100)).toBe(99);+});diff --git a/packages/core/src/timeline-position-state.ts b/packages/core/src/timeline-position-state.tsindex b8c4737327..145bca0cec 100644--- a/packages/core/src/timeline-position-state.ts+++ b/packages/core/src/timeline-position-state.ts@@ -47,6 +47,13 @@ export const getFrameForComposition = (composition: string) => {return window.remotion_initialFrame ?? 0;};+export const clampFrameToCompositionRange = (+ frame: number,+ durationInFrames: number,+) => {+ return Math.max(0, Math.min(Math.max(0, durationInFrames - 1), frame));+};+const useTimelinePositionFromContext = (state: TimelineContextValue,): number => {@@ -63,7 +70,7 @@ const useTimelinePositionFromContext = (state.frame[videoConfig.id] ??(env.isPlayer ? 0 : getFrameForComposition(videoConfig.id));- return Math.min(videoConfig.durationInFrames - 1, unclamped);+ return clampFrameToCompositionRange(unclamped, videoConfig.durationInFrames);};export const useTimelineContext = (): TimelineContextValue => {diff --git a/packages/player/src/use-player.ts b/packages/player/src/use-player.tsindex 75ed17262d..9eb521fd1d 100644--- a/packages/player/src/use-player.ts+++ b/packages/player/src/use-player.ts@@ -60,15 +60,22 @@ export const usePlayer = (): UsePlayerMethods => {const seek = useCallback((newFrame: number) => {+ const frameToSeekTo = config+ ? Internals.TimelinePosition.clampFrameToCompositionRange(+ newFrame,+ config.durationInFrames,+ )+ : Math.max(0, newFrame);+if (video?.id) {- setTimelinePosition((c) => ({...c, [video.id]: newFrame}));+ setTimelinePosition((c) => ({...c, [video.id]: frameToSeekTo}));}- frameRef.current = newFrame;+ frameRef.current = frameToSeekTo;- emitter.dispatchSeek(newFrame);+ emitter.dispatchSeek(frameToSeekTo);},- [emitter, setTimelinePosition, video?.id],+ [config, emitter, setTimelinePosition, video?.id],);const play = useCallback(diff --git a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.tsindex 4e20dc6567..8cb21225fd 100644--- a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts+++ b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts@@ -55,6 +55,13 @@ export type KeyframeOperation =| {type: 'remove';frame: number;+ }+ | {+ type: 'move';+ moves: {+ fromFrame: number;+ toFrame: number;+ }[];};export type SequenceKeyframeUpdate = {@@ -397,6 +404,75 @@ const removeKeyframe = ({});};+const moveKeyframes = ({+ expression,+ moves,+}: {+ expression: Expression;+ moves: {+ fromFrame: number;+ toFrame: number;+ }[];+}): ExpressionKind => {+ const existing = getInterpolationExpression(expression);+ if (!existing) {+ throw new Error('Cannot move keyframe in non-interpolated expression');+ }++ const moveMap = new Map<number, number>();+ for (const move of moves) {+ if (move.fromFrame === move.toFrame) {+ continue;+ }++ if (moveMap.has(move.fromFrame)) {+ throw new Error(`Cannot move keyframe at frame ${move.fromFrame} twice`);+ }++ moveMap.set(move.fromFrame, move.toFrame);+ }++ if (moveMap.size === 0) {+ return expression as ExpressionKind;+ }++ const frames = new Set(existing.keyframes.map((keyframe) => keyframe.frame));+ for (const fromFrame of moveMap.keys()) {+ if (!frames.has(fromFrame)) {+ throw new Error(`Cannot move keyframe at frame ${fromFrame}: not found`);+ }+ }++ const movedFromFrames = new Set(moveMap.keys());+ const nextFrames = new Set<number>();+ for (const keyframe of existing.keyframes) {+ const nextFrame = moveMap.get(keyframe.frame) ?? keyframe.frame;+ if (nextFrames.has(nextFrame)) {+ throw new Error(+ `Cannot move keyframe to frame ${nextFrame}: frame already exists`,+ );+ }++ if (!movedFromFrames.has(keyframe.frame) && moveMap.has(nextFrame)) {+ throw new Error(+ `Cannot move keyframe to frame ${nextFrame}: frame already exists`,+ );+ }++ nextFrames.add(nextFrame);+ }++ return createInterpolateExpression({+ callee: existing.callee,+ input: existing.input,+ extraArgs: existing.extraArgs,+ keyframes: existing.keyframes.map((keyframe) => ({+ ...keyframe,+ frame: moveMap.get(keyframe.frame) ?? keyframe.frame,+ })),+ });+};+const applyKeyframeOperation = ({expression,key,@@ -418,6 +494,13 @@ const applyKeyframeOperation = ({});}+ if (operation.type === 'move') {+ return {+ expression: moveKeyframes({expression, moves: operation.moves}),+ introduced: noIntroducedIdentifiers,+ };+ }+return {expression: removeKeyframe({expression, frame: operation.frame}),introduced: noIntroducedIdentifiers,diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex 0169066bf6..0fd1486543 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -15,6 +15,7 @@ import {deleteStaticFileHandler} from './routes/delete-static-file';import {duplicateJsxNodeHandler} from './routes/duplicate-jsx-node';import {insertJsxElementHandler} from './routes/insert-jsx-element';import {handleInstallPackage} from './routes/install-dependency';+import {moveKeyframesHandler} from './routes/move-keyframes';import {openInEditorHandler} from './routes/open-in-editor';import {handleOpenInFileExplorer} from './routes/open-in-file-explorer';import {pasteEffectsHandler} from './routes/paste-effects';@@ -65,6 +66,7 @@ export const allApiRoutes: {'/api/add-effect': addEffectHandler,'/api/reorder-effect': reorderEffectHandler,'/api/delete-keyframes': deleteKeyframesHandler,+ '/api/move-keyframes': moveKeyframesHandler,'/api/add-sequence-keyframe': addSequenceKeyframeHandler,'/api/add-effect-keyframe': addEffectKeyframeHandler,'/api/delete-effect': deleteEffectHandler,diff --git a/packages/studio-server/src/preview-server/routes/move-keyframes.ts b/packages/studio-server/src/preview-server/routes/move-keyframes.tsnew file mode 100644index 0000000000..35116e5fa1--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/move-keyframes.ts@@ -0,0 +1,370 @@+import {readFileSync} from 'node:fs';+import type {LogLevel} from '@remotion/renderer';+import {RenderInternals} from '@remotion/renderer';+import type {+ MoveEffectKeyframe,+ MoveKeyframesRequest,+ MoveKeyframesResponse,+ MoveSequenceKeyframe,+} from '@remotion/studio-shared';+import {+ updateEffectKeyframes,+ updateSequenceKeyframes,+} from '../../codemods/update-keyframes/update-keyframes';+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';+import type {ApiHandler} from '../api-types';+import {+ printUndoHint,+ pushTransactionToUndoStack,+ suppressUndoStackInvalidation,+} from '../undo-stack';+import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';+import {logEffectUpdate} from './log-updates/log-effect-update';+import {logUpdate} from './log-updates/log-update';+import {withSavePropsLock} from './save-props-mutex';++type ResolvedSequenceKeyframe = MoveSequenceKeyframe & {+ index: number;+ absolutePath: string;+ fileRelativeToRoot: string;+};++type ResolvedEffectKeyframe = MoveEffectKeyframe & {+ index: number;+ absolutePath: string;+ fileRelativeToRoot: string;+};++type FileGroup = {+ fileRelativeToRoot: string;+ sequenceKeyframes: ResolvedSequenceKeyframe[];+ effectKeyframes: ResolvedEffectKeyframe[];+};++type UndoSnapshot = {+ filePath: string;+ oldContents: string;+ newContents: string;+ logLine: number;+};++type SequenceLog = {+ fileRelativeToRoot: string;+ line: number;+ key: string;+ oldValueString: string;+ newValueString: string;+ formatted: boolean;+};++type EffectLog = {+ 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()];+};++const getBatchDescription = ({+ totalKeyframes,+ firstKeyframe,+}: {+ totalKeyframes: number;+ firstKeyframe: {key: string; fromFrame: number; toFrame: number};+}) => {+ if (totalKeyframes === 1) {+ return {+ undoMessage: `↩️ ${firstKeyframe.key} keyframe moved back to frame ${firstKeyframe.fromFrame}`,+ redoMessage: `↪️ ${firstKeyframe.key} keyframe moved to frame ${firstKeyframe.toFrame}`,+ };+ }++ return {+ undoMessage: `↩️ ${totalKeyframes} keyframes moved back`,+ redoMessage: `↪️ ${totalKeyframes} keyframes moved`,+ };+};++export const moveKeyframes = async ({+ sequenceKeyframes,+ effectKeyframes,+ clientId,+ remotionRoot,+ logLevel,+}: MoveKeyframesRequest & {+ remotionRoot: string;+ logLevel: LogLevel;+}): Promise<void> => {+ const totalKeyframes = sequenceKeyframes.length + effectKeyframes.length;+ if (totalKeyframes === 0) {+ throw new Error('No keyframes were specified for moving');+ }++ const fileGroups = new Map<string, FileGroup>();++ for (const [index, keyframe] of sequenceKeyframes.entries()) {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName: keyframe.fileName,+ action: 'modify',+ });+ const group = fileGroups.get(absolutePath) ?? {+ fileRelativeToRoot,+ sequenceKeyframes: [],+ effectKeyframes: [],+ };+ group.sequenceKeyframes.push({+ ...keyframe,+ index,+ absolutePath,+ fileRelativeToRoot,+ });+ fileGroups.set(absolutePath, group);+ }++ for (const [index, keyframe] of effectKeyframes.entries()) {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName: keyframe.fileName,+ action: 'modify',+ });+ const group = fileGroups.get(absolutePath) ?? {+ fileRelativeToRoot,+ sequenceKeyframes: [],+ effectKeyframes: [],+ };+ group.effectKeyframes.push({+ ...keyframe,+ index,+ absolutePath,+ fileRelativeToRoot,+ });+ fileGroups.set(absolutePath, group);+ }++ const snapshots: UndoSnapshot[] = [];+ const sequenceLogs: SequenceLog[] = [];+ const effectLogs: EffectLog[] = [];++ for (const [absolutePath, group] of fileGroups) {+ const fileContents = readFileSync(absolutePath, 'utf-8');+ let output = fileContents;+ let firstLogLine = Number.POSITIVE_INFINITY;++ 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()) {+ sequenceLogs.push({+ fileRelativeToRoot: firstSequenceKeyframe.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()) {+ effectLogs.push({+ fileRelativeToRoot: firstEffectKeyframe.fileRelativeToRoot,+ line: result.logLine,+ effectName: result.effectCallee,+ propKey: update.key,+ oldValueString: result.oldValueStrings[updateIndex],+ newValueString: result.newValueStrings[updateIndex],+ formatted: result.formatted,+ });+ }+ }++ snapshots.push({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: output,+ logLine: Number.isFinite(firstLogLine) ? firstLogLine : 1,+ });+ }++ const [firstKeyframe] =+ sequenceKeyframes.length > 0 ? sequenceKeyframes : effectKeyframes;+ if (!firstKeyframe) {+ throw new Error('No keyframes were specified for moving');+ }++ pushTransactionToUndoStack({+ snapshots,+ logLevel,+ remotionRoot,+ description: getBatchDescription({totalKeyframes, firstKeyframe}),+ entryType:+ sequenceKeyframes.length > 0 && effectKeyframes.length > 0+ ? 'keyframe-delete'+ : sequenceKeyframes.length > 0+ ? 'sequence-props'+ : 'effect-props',+ suppressHmrOnFileRestore: true,+ });++ for (const snapshot of snapshots) {+ suppressUndoStackInvalidation(snapshot.filePath);+ suppressBundlerUpdateForFile(snapshot.filePath);+ writeFileAndNotifyFileWatchers(+ snapshot.filePath,+ snapshot.newContents,+ clientId,+ );+ }++ for (const log of sequenceLogs) {+ 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 effectLogs) {+ 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);+};++export const moveKeyframesHandler: ApiHandler<+ MoveKeyframesRequest,+ MoveKeyframesResponse+> = ({+ input: {sequenceKeyframes, effectKeyframes, clientId},+ remotionRoot,+ logLevel,+}) =>+ withSavePropsLock(async () => {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[move-keyframes] Received request to move ${+ sequenceKeyframes.length + effectKeyframes.length+ } keyframe(s)`,+ );++ await moveKeyframes({+ sequenceKeyframes,+ effectKeyframes,+ clientId,+ remotionRoot,+ logLevel,+ });++ return {success: true};+ });diff --git a/packages/studio-server/src/test/update-keyframes.test.ts b/packages/studio-server/src/test/update-keyframes.test.tsindex 951a5e0dd9..e16fa2de8b 100644--- a/packages/studio-server/src/test/update-keyframes.test.ts+++ b/packages/studio-server/src/test/update-keyframes.test.ts@@ -538,6 +538,101 @@ test('updateSequenceKeyframes keeps an interpolation when one keyframe remains',expect(output).toContain('style={{scale: interpolate(frame, [100], [4])}}');});+test('updateSequenceKeyframes moves overlapping selected keyframes together', async () => {+ const input = sequenceInput.replace(+ 'interpolate(frame, [0, 100], [2, 4])',+ 'interpolate(frame, [0, 50, 100], [2, 3, 4])',+ );+ const {output, oldValueStrings, newValueStrings} =+ await updateSequenceKeyframes({+ input,+ nodePath: lineColumnToNodePath(input, getLine(input, 'scale')),+ updates: [+ {+ key: 'style.scale',+ operation: {+ type: 'move',+ moves: [+ {fromFrame: 0, toFrame: 50},+ {fromFrame: 50, toFrame: 80},+ ],+ },+ },+ ],+ });++ expect(oldValueStrings).toEqual([+ 'interpolate(frame, [0, 50, 100], [2, 3, 4])',+ ]);+ expect(newValueStrings).toEqual([+ 'interpolate(frame, [50, 80, 100], [2, 3, 4])',+ ]);+ expect(output).toContain(+ 'style={{scale: interpolate(frame, [50, 80, 100], [2, 3, 4])}}',+ );+});++test('updateSequenceKeyframes resorts keyframes when moving past an adjacent keyframe', async () => {+ const input = sequenceInput.replace(+ 'interpolate(frame, [0, 100], [2, 4])',+ 'interpolate(frame, [0, 50, 100], [2, 3, 4])',+ );+ const {output, oldValueStrings, newValueStrings} =+ await updateSequenceKeyframes({+ input,+ nodePath: lineColumnToNodePath(input, getLine(input, 'scale')),+ updates: [+ {+ key: 'style.scale',+ operation: {+ type: 'move',+ moves: [{fromFrame: 0, toFrame: 75}],+ },+ },+ ],+ });++ expect(oldValueStrings).toEqual([+ 'interpolate(frame, [0, 50, 100], [2, 3, 4])',+ ]);+ expect(newValueStrings).toEqual([+ 'interpolate(frame, [50, 75, 100], [3, 2, 4])',+ ]);+ expect(output).toContain(+ 'style={{scale: interpolate(frame, [50, 75, 100], [3, 2, 4])}}',+ );+});++test('updateSequenceKeyframes allows moving keyframes outside the sequence range', async () => {+ const input = sequenceInput.replace(+ 'interpolate(frame, [0, 100], [2, 4])',+ 'interpolate(frame, [0, 50, 100], [2, 3, 4])',+ );+ const {output, newValueStrings} = await updateSequenceKeyframes({+ input,+ nodePath: lineColumnToNodePath(input, getLine(input, 'scale')),+ updates: [+ {+ key: 'style.scale',+ operation: {+ type: 'move',+ moves: [+ {fromFrame: 0, toFrame: -15},+ {fromFrame: 100, toFrame: 140},+ ],+ },+ },+ ],+ });++ expect(newValueStrings).toEqual([+ 'interpolate(frame, [-15, 50, 140], [2, 3, 4])',+ ]);+ expect(output).toContain(+ 'style={{scale: interpolate(frame, [-15, 50, 140], [2, 3, 4])}}',+ );+});+test('updateSequenceKeyframes converts the last keyframe to a static value', async () => {const input = sequenceInput.replace('interpolate(frame, [0, 100], [2, 4])',@@ -671,6 +766,36 @@ test('updateEffectKeyframes removes a keyframe from an effect prop interpolation);});+test('updateEffectKeyframes allows moving keyframes outside the sequence range', () => {+ const {serialized, newValueStrings} = updateEffectKeyframesAst({+ input: effectInput,+ sequenceNodePath: lineColumnToNodePath(+ effectInput,+ getLine(effectInput, '<HtmlInCanvas'),+ ),+ effectIndex: 0,+ updates: [+ {+ key: 'amount',+ operation: {+ type: 'move',+ moves: [+ {fromFrame: 0, toFrame: -20},+ {fromFrame: 100, toFrame: 150},+ ],+ },+ },+ ],+ });++ expect(newValueStrings).toEqual([+ 'interpolate(frame, [-20, 50, 150], [0.2, 0.5, 0.8])',+ ]);+ expect(serialized).toContain(+ 'amount: interpolate(frame, [-20, 50, 150], [0.2, 0.5, 0.8])',+ );+});+test('updateEffectKeyframes keeps an effect prop interpolation with one keyframe', () => {const input = effectInput.replace('interpolate(frame, [0, 50, 100], [0.2, 0.5, 0.8])',diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex b4e0a4a043..cecf9bb611 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -369,6 +369,15 @@ export type DeleteSequenceKeyframe = {schema: SequenceSchema;};+export type MoveSequenceKeyframe = {+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ key: string;+ fromFrame: number;+ toFrame: number;+ schema: SequenceSchema;+};+export type AddSequenceKeyframeRequest = {fileName: string;nodePath: SequencePropsSubscriptionKey;@@ -390,6 +399,16 @@ export type DeleteEffectKeyframe = {schema: SequenceSchema;};+export type MoveEffectKeyframe = {+ fileName: string;+ sequenceNodePath: SequencePropsSubscriptionKey;+ effectIndex: number;+ key: string;+ fromFrame: number;+ toFrame: number;+ schema: SequenceSchema;+};+export type DeleteKeyframesRequest = {sequenceKeyframes: DeleteSequenceKeyframe[];effectKeyframes: DeleteEffectKeyframe[];@@ -400,6 +419,16 @@ export type DeleteKeyframesResponse = {success: true;};+export type MoveKeyframesRequest = {+ sequenceKeyframes: MoveSequenceKeyframe[];+ effectKeyframes: MoveEffectKeyframe[];+ clientId: string;+};++export type MoveKeyframesResponse = {+ success: true;+};+export type AddEffectKeyframeRequest = {fileName: string;sequenceNodePath: SequencePropsSubscriptionKey;@@ -623,6 +652,7 @@ export type ApiRoutes = {DeleteKeyframesRequest,DeleteKeyframesResponse>;+ '/api/move-keyframes': ReqAndRes<MoveKeyframesRequest, MoveKeyframesResponse>;'/api/add-sequence-keyframe': ReqAndRes<AddSequenceKeyframeRequest,AddSequenceKeyframeResponsediff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 545aa645d9..27c10d48a4 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -38,6 +38,10 @@ export {InsertableCompositionElement,InstallPackageRequest,InstallPackageResponse,+ MoveEffectKeyframe,+ MoveKeyframesRequest,+ MoveKeyframesResponse,+ MoveSequenceKeyframe,OpenInEditorRequest,OpenInEditorResponse,OpenInFileExplorerRequest,@@ -186,6 +190,11 @@ export {optimisticDeleteSequenceKeyframe,optimisticDeleteSequenceKeyframes,} from './optimistic-delete-keyframe';+export {+ optimisticMoveEffectKeyframes,+ optimisticMoveSequenceKeyframes,+ type OptimisticKeyframeMove,+} from './optimistic-move-keyframe';export {optimisticUpdateForCodeValues} from './optimistic-update-for-code-values';export {optimisticUpdateForEffectCodeValues} from './optimistic-update-for-effect-code-values';export {diff --git a/packages/studio-shared/src/optimistic-move-keyframe.ts b/packages/studio-shared/src/optimistic-move-keyframe.tsnew file mode 100644index 0000000000..94781884fa--- /dev/null+++ b/packages/studio-shared/src/optimistic-move-keyframe.ts@@ -0,0 +1,160 @@+import type {+ CanUpdateSequencePropsResponse,+ CanUpdateSequencePropStatus,+} from 'remotion';++export type OptimisticKeyframeMove = {+ readonly fieldKey: string;+ readonly fromFrame: number;+ readonly toFrame: number;+};++const moveKeyframesInPropStatus = ({+ status,+ moves,+}: {+ status: CanUpdateSequencePropStatus;+ moves: readonly {fromFrame: number; toFrame: number}[];+}): CanUpdateSequencePropStatus => {+ if (status.status !== 'keyframed') {+ return status;+ }++ const moveMap = new Map<number, number>();+ for (const move of moves) {+ if (move.fromFrame !== move.toFrame) {+ moveMap.set(move.fromFrame, move.toFrame);+ }+ }++ if (moveMap.size === 0) {+ return status;+ }++ const sourceFrames = new Set(+ status.keyframes.map((keyframe) => keyframe.frame),+ );+ for (const fromFrame of moveMap.keys()) {+ if (!sourceFrames.has(fromFrame)) {+ return status;+ }+ }++ const nextFrames = new Set<number>();+ const keyframes = status.keyframes+ .map((keyframe) => {+ const frame = moveMap.get(keyframe.frame) ?? keyframe.frame;+ if (nextFrames.has(frame)) {+ return null;+ }++ nextFrames.add(frame);+ return {+ ...keyframe,+ frame,+ };+ })+ .filter((keyframe): keyframe is NonNullable<typeof keyframe> => {+ return keyframe !== null;+ });++ if (keyframes.length !== status.keyframes.length) {+ return status;+ }++ return {+ ...status,+ keyframes: keyframes.sort((a, b) => a.frame - b.frame),+ };+};++export const optimisticMoveSequenceKeyframes = ({+ previous,+ keyframes,+}: {+ previous: CanUpdateSequencePropsResponse;+ keyframes: readonly OptimisticKeyframeMove[];+}): CanUpdateSequencePropsResponse => {+ if (!previous.canUpdate) {+ return previous;+ }++ const movesByField = new Map<string, OptimisticKeyframeMove[]>();+ for (const keyframe of keyframes) {+ const moves = movesByField.get(keyframe.fieldKey) ?? [];+ moves.push(keyframe);+ movesByField.set(keyframe.fieldKey, moves);+ }++ const props = {...previous.props};+ for (const [fieldKey, moves] of movesByField) {+ const status = props[fieldKey];+ if (!status) {+ continue;+ }++ props[fieldKey] = moveKeyframesInPropStatus({status, moves});+ }++ return {+ ...previous,+ props,+ };+};++export const optimisticMoveEffectKeyframes = ({+ previous,+ keyframes,+}: {+ previous: CanUpdateSequencePropsResponse;+ keyframes: readonly (OptimisticKeyframeMove & {effectIndex: number})[];+}): CanUpdateSequencePropsResponse => {+ if (!previous.canUpdate) {+ return previous;+ }++ const movesByEffect = new Map<number, OptimisticKeyframeMove[]>();+ for (const keyframe of keyframes) {+ const moves = movesByEffect.get(keyframe.effectIndex) ?? [];+ moves.push(keyframe);+ movesByEffect.set(keyframe.effectIndex, moves);+ }++ const effects = previous.effects.map((effect) => {+ if (!effect.canUpdate) {+ return effect;+ }++ const movesForEffect = movesByEffect.get(effect.effectIndex);+ if (!movesForEffect) {+ return effect;+ }++ const props = {...effect.props};+ const movesByField = new Map<string, OptimisticKeyframeMove[]>();+ for (const move of movesForEffect) {+ const moves = movesByField.get(move.fieldKey) ?? [];+ moves.push(move);+ movesByField.set(move.fieldKey, moves);+ }++ for (const [fieldKey, moves] of movesByField) {+ const status = props[fieldKey];+ if (!status) {+ continue;+ }++ props[fieldKey] = moveKeyframesInPropStatus({status, moves});+ }++ return {+ ...effect,+ props,+ };+ });++ return {+ ...previous,+ effects,+ };+};diff --git a/packages/studio-shared/src/test/optimistic-move-keyframe.test.ts b/packages/studio-shared/src/test/optimistic-move-keyframe.test.tsnew file mode 100644index 0000000000..39b5232183--- /dev/null+++ b/packages/studio-shared/src/test/optimistic-move-keyframe.test.ts@@ -0,0 +1,174 @@+import {expect, test} from 'bun:test';+import type {CanUpdateSequencePropsResponse} from 'remotion';+import {+ optimisticMoveEffectKeyframes,+ optimisticMoveSequenceKeyframes,+} from '../optimistic-move-keyframe';++const previous: CanUpdateSequencePropsResponse = {+ canUpdate: true,+ props: {+ scale: {+ status: 'keyframed',+ codeValue: undefined,+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: 1},+ {frame: 20, value: 2},+ {frame: 40, value: 3},+ ],+ easing: ['linear', 'linear'],+ clamping: {left: 'extend', right: 'extend'},+ posterize: undefined,+ },+ },+ effects: [+ {+ canUpdate: true,+ effectIndex: 0,+ callee: 'blur',+ importPath: null,+ props: {+ amount: {+ status: 'keyframed',+ codeValue: undefined,+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: 0.2},+ {frame: 20, value: 0.5},+ ],+ easing: ['linear'],+ clamping: {left: 'extend', right: 'extend'},+ posterize: undefined,+ },+ },+ },+ ],+};++test('optimisticMoveSequenceKeyframes moves multiple keyframes in one field', () => {+ const updated = optimisticMoveSequenceKeyframes({+ previous,+ keyframes: [+ {fieldKey: 'scale', fromFrame: 0, toFrame: 10},+ {fieldKey: 'scale', fromFrame: 20, toFrame: 30},+ ],+ });++ if (!updated.canUpdate) {+ throw new Error('expected updateable sequence');+ }++ const status = updated.props.scale;+ if (!status || status.status !== 'keyframed') {+ throw new Error('expected keyframed status');+ }++ expect(status.keyframes).toEqual([+ {frame: 10, value: 1},+ {frame: 30, value: 2},+ {frame: 40, value: 3},+ ]);+ expect(status.easing).toEqual(['linear', 'linear']);+});++test('optimisticMoveSequenceKeyframes resorts when moving past an adjacent keyframe', () => {+ const updated = optimisticMoveSequenceKeyframes({+ previous,+ keyframes: [{fieldKey: 'scale', fromFrame: 0, toFrame: 30}],+ });++ if (!updated.canUpdate) {+ throw new Error('expected updateable sequence');+ }++ const status = updated.props.scale;+ if (!status || status.status !== 'keyframed') {+ throw new Error('expected keyframed status');+ }++ expect(status.keyframes).toEqual([+ {frame: 20, value: 2},+ {frame: 30, value: 1},+ {frame: 40, value: 3},+ ]);+ expect(status.easing).toEqual(['linear', 'linear']);+});++test('optimisticMoveSequenceKeyframes allows moving keyframes before frame 0', () => {+ const updated = optimisticMoveSequenceKeyframes({+ previous,+ keyframes: [{fieldKey: 'scale', fromFrame: 0, toFrame: -12}],+ });++ if (!updated.canUpdate) {+ throw new Error('expected updateable sequence');+ }++ const status = updated.props.scale;+ if (!status || status.status !== 'keyframed') {+ throw new Error('expected keyframed status');+ }++ expect(status.keyframes).toEqual([+ {frame: -12, value: 1},+ {frame: 20, value: 2},+ {frame: 40, value: 3},+ ]);+});++test('optimisticMoveEffectKeyframes moves effect keyframes', () => {+ const updated = optimisticMoveEffectKeyframes({+ previous,+ keyframes: [+ {effectIndex: 0, fieldKey: 'amount', fromFrame: 0, toFrame: 12},+ ],+ });++ if (!updated.canUpdate) {+ throw new Error('expected updateable sequence');+ }++ const effect = updated.effects[0];+ if (!effect.canUpdate) {+ throw new Error('expected updateable effect');+ }++ const status = effect.props.amount;+ if (!status || status.status !== 'keyframed') {+ throw new Error('expected keyframed status');+ }++ expect(status.keyframes).toEqual([+ {frame: 12, value: 0.2},+ {frame: 20, value: 0.5},+ ]);+});++test('optimisticMoveEffectKeyframes allows moving keyframes beyond the sequence range', () => {+ const updated = optimisticMoveEffectKeyframes({+ previous,+ keyframes: [+ {effectIndex: 0, fieldKey: 'amount', fromFrame: 20, toFrame: 140},+ ],+ });++ if (!updated.canUpdate) {+ throw new Error('expected updateable sequence');+ }++ const effect = updated.effects[0];+ if (!effect.canUpdate) {+ throw new Error('expected updateable effect');+ }++ const status = effect.props.amount;+ if (!status || status.status !== 'keyframed') {+ throw new Error('expected keyframed status');+ }++ expect(status.keyframes).toEqual([+ {frame: 0, value: 0.2},+ {frame: 140, value: 0.5},+ ]);+});diff --git a/packages/studio/src/components/EditorContent.tsx b/packages/studio/src/components/EditorContent.tsxindex 035503acf2..4a89ffdac7 100644--- a/packages/studio/src/components/EditorContent.tsx+++ b/packages/studio/src/components/EditorContent.tsx@@ -7,6 +7,7 @@ import {SplitterElement} from './Splitter/SplitterElement';import {SplitterHandle} from './Splitter/SplitterHandle';import {Timeline} from './Timeline/Timeline';import {TimelineEmptyState} from './Timeline/TimelineEmptyState';+import {TimelineKeyframeDragStateProvider} from './Timeline/TimelineKeyframeDragState';import {TimelineSelectionProvider} from './Timeline/TimelineSelection';const noop = () => undefined;@@ -50,7 +51,11 @@ export const EditorContent: React.FC<{<InitialCompositionLoader /><MenuToolbar readOnlyStudio={readOnlyStudio} />{showTimeline ? (- <TimelineSelectionProvider>{content}</TimelineSelectionProvider>+ <TimelineSelectionProvider>+ <TimelineKeyframeDragStateProvider>+ {content}+ </TimelineKeyframeDragStateProvider>+ </TimelineSelectionProvider>) : (content)}diff --git a/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsx b/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsxindex fa2cda70ba..5199eb16af 100644--- a/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsx+++ b/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsx@@ -192,12 +192,22 @@ export const TimelineKeyframeControls: React.FC<{);const previousDisplayFrame = useMemo(- () => getPreviousKeyframeDisplayFrame(keyframes, timelinePosition),- [keyframes, timelinePosition],+ () =>+ getPreviousKeyframeDisplayFrame(+ keyframes,+ timelinePosition,+ videoConfig.durationInFrames,+ ),+ [keyframes, timelinePosition, videoConfig.durationInFrames],);const nextDisplayFrame = useMemo(- () => getNextKeyframeDisplayFrame(keyframes, timelinePosition),- [keyframes, timelinePosition],+ () =>+ getNextKeyframeDisplayFrame(+ keyframes,+ timelinePosition,+ videoConfig.durationInFrames,+ ),+ [keyframes, timelinePosition, videoConfig.durationInFrames],);const keyframable = isSchemaFieldKeyframable({diff --git a/packages/studio/src/components/Timeline/TimelineKeyframeDiamond.tsx b/packages/studio/src/components/Timeline/TimelineKeyframeDiamond.tsxindex b76ad16367..f3b5513bb6 100644--- a/packages/studio/src/components/Timeline/TimelineKeyframeDiamond.tsx+++ b/packages/studio/src/components/Timeline/TimelineKeyframeDiamond.tsx@@ -1,11 +1,13 @@-import React, {useCallback, useContext, useMemo} from 'react';+import React, {useContext, useMemo} from 'react';import {useVideoConfig} from 'remotion';import {BLUE, LIGHT_TEXT} from '../../helpers/colors';import {getXPositionOfItemInTimelineImperatively} from '../../helpers/get-left-of-timeline-slider';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';import {TIMELINE_PADDING} from '../../helpers/timeline-layout';+import {useTimelineKeyframeDragState} from './TimelineKeyframeDragState';import {useTimelineKeyframeSelection} from './TimelineSelection';import {TimelineWidthContext} from './TimelineWidthProvider';+import {useTimelineKeyframeDrag} from './use-timeline-keyframe-drag';const diamondBase: React.CSSProperties = {position: 'absolute',@@ -27,6 +29,9 @@ const TimelineKeyframeDiamondUnmemoized: React.FC<{nodePathInfo,frame,);+ const {isKeyframeDragging} = useTimelineKeyframeDragState();+ const visuallySelected =+ selected || isKeyframeDragging({nodePathInfo, frame});const style = useMemo((): React.CSSProperties | null => {if (timelineWidth === null) {@@ -36,9 +41,8 @@ const TimelineKeyframeDiamondUnmemoized: React.FC<{return {...diamondBase,backgroundColor: LIGHT_TEXT,- outline: selected ? '2px solid ' + BLUE : 'none',+ outline: visuallySelected ? '2px solid ' + BLUE : 'none',border: 'none',- cursor: 'pointer',left:getXPositionOfItemInTimelineImperatively(frame,@@ -50,20 +54,21 @@ const TimelineKeyframeDiamondUnmemoized: React.FC<{top: rowHeight / 2,transform: 'translate(-50%, -50%) rotate(45deg)',};- }, [frame, rowHeight, selected, timelineWidth, videoConfig.durationInFrames]);+ }, [+ frame,+ rowHeight,+ timelineWidth,+ videoConfig.durationInFrames,+ visuallySelected,+ ]);- const onPointerDown = useCallback(- (e: React.PointerEvent<HTMLButtonElement>) => {- if (e.button === 0) {- e.stopPropagation();- onSelect({- shiftKey: e.shiftKey,- toggleKey: e.metaKey || e.ctrlKey,- });- }- },- [onSelect],- );+ const onPointerDown = useTimelineKeyframeDrag({+ frame,+ nodePathInfo,+ onSelect,+ selectable,+ selected,+ });if (style === null) {return null;diff --git a/packages/studio/src/components/Timeline/TimelineKeyframeDragState.tsx b/packages/studio/src/components/Timeline/TimelineKeyframeDragState.tsxnew file mode 100644index 0000000000..3d86085eaa--- /dev/null+++ b/packages/studio/src/components/Timeline/TimelineKeyframeDragState.tsx@@ -0,0 +1,83 @@+import React, {+ createContext,+ useCallback,+ useContext,+ useMemo,+ useState,+} from 'react';+import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';+import {timelineNodePathInfoToKey} from '../../helpers/timeline-node-path-key';++export type TimelineDraggedKeyframe = {+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly frame: number;+};++const emptyDraggedKeyframes = new Set<string>();++export const getTimelineKeyframeDragKey = ({+ nodePathInfo,+ frame,+}: TimelineDraggedKeyframe): string => {+ return `${timelineNodePathInfoToKey(nodePathInfo)}.keyframe.${frame}`;+};++type TimelineKeyframeDragStateContextValue = {+ readonly clearDraggedKeyframes: () => void;+ readonly isKeyframeDragging: (keyframe: TimelineDraggedKeyframe) => boolean;+ readonly setDraggedKeyframes: (+ keyframes: readonly TimelineDraggedKeyframe[],+ ) => void;+};++const TimelineKeyframeDragStateContext =+ createContext<TimelineKeyframeDragStateContextValue>({+ clearDraggedKeyframes: () => undefined,+ isKeyframeDragging: () => false,+ setDraggedKeyframes: () => undefined,+ });++export const TimelineKeyframeDragStateProvider: React.FC<{+ readonly children: React.ReactNode;+}> = ({children}) => {+ const [draggedKeys, setDraggedKeys] = useState<ReadonlySet<string>>(+ emptyDraggedKeyframes,+ );++ const setDraggedKeyframes = useCallback(+ (keyframes: readonly TimelineDraggedKeyframe[]) => {+ setDraggedKeys(new Set(keyframes.map(getTimelineKeyframeDragKey)));+ },+ [],+ );++ const clearDraggedKeyframes = useCallback(() => {+ setDraggedKeys(emptyDraggedKeyframes);+ }, []);++ const isKeyframeDragging = useCallback(+ (keyframe: TimelineDraggedKeyframe) => {+ return draggedKeys.has(getTimelineKeyframeDragKey(keyframe));+ },+ [draggedKeys],+ );++ const value = useMemo(+ (): TimelineKeyframeDragStateContextValue => ({+ clearDraggedKeyframes,+ isKeyframeDragging,+ setDraggedKeyframes,+ }),+ [clearDraggedKeyframes, isKeyframeDragging, setDraggedKeyframes],+ );++ return (+ <TimelineKeyframeDragStateContext.Provider value={value}>+ {children}+ </TimelineKeyframeDragStateContext.Provider>+ );+};++export const useTimelineKeyframeDragState = () => {+ return useContext(TimelineKeyframeDragStateContext);+};diff --git a/packages/studio/src/components/Timeline/call-move-keyframe.ts b/packages/studio/src/components/Timeline/call-move-keyframe.tsnew file mode 100644index 0000000000..a944c2544a--- /dev/null+++ b/packages/studio/src/components/Timeline/call-move-keyframe.ts@@ -0,0 +1,108 @@+import {+ optimisticMoveEffectKeyframes,+ optimisticMoveSequenceKeyframes,+} from '@remotion/studio-shared';+import type {SequencePropsSubscriptionKey, SequenceSchema} from 'remotion';+import {callApi} from '../call-api';+import type {SetCodeValues} from './save-sequence-prop';++export type MoveSequenceKeyframeChange = {+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ fieldKey: string;+ fromFrame: number;+ toFrame: number;+ schema: SequenceSchema;+};++export type MoveEffectKeyframeChange = MoveSequenceKeyframeChange & {+ effectIndex: number;+};++const groupByNodePath = <T extends {nodePath: SequencePropsSubscriptionKey}>(+ keyframes: T[],+): T[][] => {+ const groups = new Map<string, T[]>();+ for (const keyframe of keyframes) {+ const key = JSON.stringify(keyframe.nodePath);+ const group = groups.get(key) ?? [];+ group.push(keyframe);+ groups.set(key, group);+ }++ return [...groups.values()];+};++export const callMoveKeyframes = ({+ sequenceKeyframes,+ effectKeyframes,+ setCodeValues,+ clientId,+}: {+ sequenceKeyframes: MoveSequenceKeyframeChange[];+ effectKeyframes: MoveEffectKeyframeChange[];+ setCodeValues: SetCodeValues;+ clientId: string;+}): Promise<void> => {+ if (sequenceKeyframes.length === 0 && effectKeyframes.length === 0) {+ return Promise.resolve();+ }++ for (const keyframes of groupByNodePath(sequenceKeyframes)) {+ const [firstKeyframe] = keyframes;+ if (!firstKeyframe) {+ continue;+ }++ setCodeValues(firstKeyframe.nodePath, (prev) =>+ optimisticMoveSequenceKeyframes({+ previous: prev,+ keyframes: keyframes.map((keyframe) => ({+ fieldKey: keyframe.fieldKey,+ fromFrame: keyframe.fromFrame,+ toFrame: keyframe.toFrame,+ })),+ }),+ );+ }++ for (const keyframes of groupByNodePath(effectKeyframes)) {+ const [firstKeyframe] = keyframes;+ if (!firstKeyframe) {+ continue;+ }++ setCodeValues(firstKeyframe.nodePath, (prev) =>+ optimisticMoveEffectKeyframes({+ previous: prev,+ keyframes: keyframes.map((keyframe) => ({+ effectIndex: keyframe.effectIndex,+ fieldKey: keyframe.fieldKey,+ fromFrame: keyframe.fromFrame,+ toFrame: keyframe.toFrame,+ })),+ }),+ );+ }++ return callApi('/api/move-keyframes', {+ 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,+ }).then(() => undefined);+};diff --git a/packages/studio/src/components/Timeline/get-keyframe-navigation.ts b/packages/studio/src/components/Timeline/get-keyframe-navigation.tsindex 046f20a14b..ed4b119152 100644--- a/packages/studio/src/components/Timeline/get-keyframe-navigation.ts+++ b/packages/studio/src/components/Timeline/get-keyframe-navigation.ts@@ -1,10 +1,22 @@+const isKeyframeInTimelineRange = (+ frame: number,+ durationInFrames: number,+): boolean => {+ return frame >= 0 && frame < durationInFrames;+};+export const getPreviousKeyframeDisplayFrame = (keyframes: readonly {frame: number}[],currentDisplayFrame: number,+ durationInFrames: number,): number | null => {let previous: number | null = null;for (const keyframe of keyframes) {- if (keyframe.frame < currentDisplayFrame) {+ if (+ isKeyframeInTimelineRange(keyframe.frame, durationInFrames) &&+ keyframe.frame < currentDisplayFrame &&+ (previous === null || keyframe.frame > previous)+ ) {previous = keyframe.frame;}}@@ -15,14 +27,20 @@ export const getPreviousKeyframeDisplayFrame = (export const getNextKeyframeDisplayFrame = (keyframes: readonly {frame: number}[],currentDisplayFrame: number,+ durationInFrames: number,): number | null => {+ let next: number | null = null;for (const keyframe of keyframes) {- if (keyframe.frame > currentDisplayFrame) {- return keyframe.frame;+ if (+ isKeyframeInTimelineRange(keyframe.frame, durationInFrames) &&+ keyframe.frame > currentDisplayFrame &&+ (next === null || keyframe.frame < next)+ ) {+ next = keyframe.frame;}}- return null;+ return next;};export const hasKeyframeAtSourceFrame = (diff --git a/packages/studio/src/components/Timeline/use-timeline-keyframe-drag.ts b/packages/studio/src/components/Timeline/use-timeline-keyframe-drag.tsnew file mode 100644index 0000000000..85749cf7f0--- /dev/null+++ b/packages/studio/src/components/Timeline/use-timeline-keyframe-drag.ts@@ -0,0 +1,554 @@+import type React from 'react';+import {useCallback, useContext} from 'react';+import type {+ CanUpdateSequencePropStatusKeyframed,+ CodeValues,+ DragOverrideValue,+ OverrideIdToNodePaths,+ SequencePropsSubscriptionKey,+ SequenceSchema,+ TSequence,+} from 'remotion';+import {Internals, useVideoConfig} from 'remotion';+import {StudioServerConnectionCtx} from '../../helpers/client-id';+import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';+import {TIMELINE_PADDING} from '../../helpers/timeline-layout';+import {callMoveKeyframes} from './call-move-keyframe';+import {findTrackForNodePathInfo} from './find-track-for-node-path-info';+import {parseKeyframeFieldFromNodePath} from './parse-keyframe-field-from-node-path';+import {useTimelineKeyframeDragState} from './TimelineKeyframeDragState';+import {+ useCurrentTimelineSelectionStateAsRef,+ type TimelineSelection,+ type TimelineSelectionInteraction,+} from './TimelineSelection';+import {TimelineWidthContext} from './TimelineWidthProvider';++type TimelineKeyframeDragTargetBase = {+ readonly displayFrame: number;+ readonly fieldKey: string;+ readonly fileName: string;+ readonly nodePath: SequencePropsSubscriptionKey;+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly propStatus: CanUpdateSequencePropStatusKeyframed;+ readonly schema: SequenceSchema;+ readonly sourceFrame: number;+};++type TimelineKeyframeDragTarget =+ | (TimelineKeyframeDragTargetBase & {+ readonly type: 'sequence';+ })+ | (TimelineKeyframeDragTargetBase & {+ readonly type: 'effect';+ readonly effectIndex: number;+ });++type TimelineKeyframeSelection = TimelineSelection & {type: 'keyframe'};++const pointerDragThreshold = 3;++const isKeyframeSelection = (+ selection: TimelineSelection,+): selection is TimelineKeyframeSelection => selection.type === 'keyframe';++const getCodeValueForTarget = ({+ codeValues,+ nodePath,+}: {+ readonly codeValues: CodeValues;+ readonly nodePath: SequencePropsSubscriptionKey;+}) => codeValues[Internals.makeSequencePropsSubscriptionKey(nodePath)];++const getTimelineKeyframeDragTarget = ({+ codeValues,+ displayFrame,+ nodePathInfo,+ overrideIdsToNodePaths,+ sequences,+}: {+ readonly codeValues: CodeValues;+ readonly displayFrame: number;+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly overrideIdsToNodePaths: OverrideIdToNodePaths;+ readonly sequences: TSequence[];+}): TimelineKeyframeDragTarget | null => {+ const field = parseKeyframeFieldFromNodePath(nodePathInfo.auxiliaryKeys);+ if (field === null) {+ return null;+ }++ const track = findTrackForNodePathInfo({+ sequences,+ overrideIdsToNodePaths,+ nodePathInfo,+ });+ const sequence = track?.sequence ?? null;+ if (!sequence?.controls) {+ return null;+ }++ const sourceFrame = displayFrame - (track?.keyframeDisplayOffset ?? 0);+ const nodePath = nodePathInfo.sequenceSubscriptionKey;+ const fileName = nodePath.absolutePath;+ const sequenceStatus = getCodeValueForTarget({codeValues, nodePath});+ if (!sequenceStatus?.canUpdate) {+ return null;+ }++ if (field.type === 'effect') {+ const effect = sequence.effects[field.effectIndex];+ const effectStatus = sequenceStatus.effects.find(+ (candidate) => candidate.effectIndex === field.effectIndex,+ );+ if (!effect || !effectStatus?.canUpdate) {+ return null;+ }++ const effectPropStatus = effectStatus.props[field.fieldKey];+ if (effectPropStatus?.status !== 'keyframed') {+ return null;+ }++ if (+ !effectPropStatus.keyframes.some(+ (keyframe) => keyframe.frame === sourceFrame,+ )+ ) {+ return null;+ }++ return {+ type: 'effect',+ displayFrame,+ effectIndex: field.effectIndex,+ fieldKey: field.fieldKey,+ fileName,+ nodePath,+ nodePathInfo,+ propStatus: effectPropStatus,+ schema: effect.schema,+ sourceFrame,+ };+ }++ const sequencePropStatus = sequenceStatus.props[field.fieldKey];+ if (sequencePropStatus?.status !== 'keyframed') {+ return null;+ }++ if (+ !sequencePropStatus.keyframes.some(+ (keyframe) => keyframe.frame === sourceFrame,+ )+ ) {+ return null;+ }++ return {+ type: 'sequence',+ displayFrame,+ fieldKey: field.fieldKey,+ fileName,+ nodePath,+ nodePathInfo,+ propStatus: sequencePropStatus,+ schema: sequence.controls.schema,+ sourceFrame,+ };+};++const getTargetGroupKey = (target: TimelineKeyframeDragTarget) => {+ return JSON.stringify({+ type: target.type,+ nodePath: target.nodePath,+ effectIndex: target.type === 'effect' ? target.effectIndex : null,+ fieldKey: target.fieldKey,+ });+};++const groupTargets = (targets: readonly TimelineKeyframeDragTarget[]) => {+ const groups = new Map<string, TimelineKeyframeDragTarget[]>();+ for (const target of targets) {+ const key = getTargetGroupKey(target);+ const group = groups.get(key) ?? [];+ group.push(target);+ groups.set(key, group);+ }++ return [...groups.values()];+};++const makeMovedKeyframedDragOverride = ({+ group,+ delta,+}: {+ readonly group: readonly TimelineKeyframeDragTarget[];+ readonly delta: number;+}): DragOverrideValue => {+ const [first] = group;+ if (!first) {+ throw new Error('Expected a keyframe drag target');+ }++ const moves = new Map(+ group.map(+ (target) => [target.sourceFrame, target.sourceFrame + delta] as const,+ ),+ );++ return {+ type: 'keyframed',+ status: {+ ...first.propStatus,+ keyframes: first.propStatus.keyframes+ .map((keyframe) => ({+ ...keyframe,+ frame: moves.get(keyframe.frame) ?? keyframe.frame,+ }))+ .sort((a, b) => a.frame - b.frame),+ },+ };+};++const applyDragOverrides = ({+ delta,+ setDragOverrides,+ setEffectDragOverrides,+ targets,+}: {+ readonly delta: number;+ readonly setDragOverrides: React.ContextType<+ typeof Internals.VisualModeSettersContext+ >['setDragOverrides'];+ readonly setEffectDragOverrides: React.ContextType<+ typeof Internals.VisualModeSettersContext+ >['setEffectDragOverrides'];+ readonly targets: readonly TimelineKeyframeDragTarget[];+}) => {+ for (const group of groupTargets(targets)) {+ const [first] = group;+ if (!first) {+ continue;+ }++ const override = makeMovedKeyframedDragOverride({group, delta});+ if (first.type === 'sequence') {+ setDragOverrides(first.nodePath, first.fieldKey, override);+ continue;+ }++ setEffectDragOverrides(+ first.nodePath,+ first.effectIndex,+ first.fieldKey,+ override,+ );+ }+};++const clearDragOverridesForTargets = ({+ clearDragOverrides,+ clearEffectDragOverrides,+ targets,+}: {+ readonly clearDragOverrides: React.ContextType<+ typeof Internals.VisualModeSettersContext+ >['clearDragOverrides'];+ readonly clearEffectDragOverrides: React.ContextType<+ typeof Internals.VisualModeSettersContext+ >['clearEffectDragOverrides'];+ readonly targets: readonly TimelineKeyframeDragTarget[];+}) => {+ const clearedSequences = new Set<string>();+ const clearedEffects = new Set<string>();++ for (const target of targets) {+ if (target.type === 'sequence') {+ const sequenceKey = JSON.stringify(target.nodePath);+ if (clearedSequences.has(sequenceKey)) {+ continue;+ }++ clearedSequences.add(sequenceKey);+ clearDragOverrides(target.nodePath);+ continue;+ }++ const effectKey = JSON.stringify({+ nodePath: target.nodePath,+ effectIndex: target.effectIndex,+ });+ if (clearedEffects.has(effectKey)) {+ continue;+ }++ clearedEffects.add(effectKey);+ clearEffectDragOverrides(target.nodePath, target.effectIndex);+ }+};++const getFrameDelta = ({+ clientXDelta,+ durationInFrames,+ timelineWidth,+}: {+ readonly clientXDelta: number;+ readonly durationInFrames: number;+ readonly timelineWidth: number;+}) => {+ const timelineContentWidth = timelineWidth - TIMELINE_PADDING * 2;+ if (timelineContentWidth <= 0) {+ return 0;+ }++ return Math.round((clientXDelta / timelineContentWidth) * durationInFrames);+};++export const useTimelineKeyframeDrag = ({+ frame,+ nodePathInfo,+ onSelect,+ selectable,+ selected,+}: {+ readonly frame: number;+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly onSelect: (interaction?: TimelineSelectionInteraction) => void;+ readonly selectable: boolean;+ readonly selected: boolean;+}) => {+ const videoConfig = useVideoConfig();+ const timelineWidth = useContext(TimelineWidthContext);+ const {previewServerState} = useContext(StudioServerConnectionCtx);+ const {sequences} = useContext(Internals.SequenceManager);+ const {overrideIdToNodePathMappings} = useContext(+ Internals.OverrideIdsToNodePathsGettersContext,+ );+ const {codeValues} = useContext(Internals.VisualModeCodeValuesContext);+ const {+ clearDragOverrides,+ clearEffectDragOverrides,+ setCodeValues,+ setDragOverrides,+ setEffectDragOverrides,+ } = useContext(Internals.VisualModeSettersContext);+ const currentSelection = useCurrentTimelineSelectionStateAsRef();+ const {clearDraggedKeyframes, setDraggedKeyframes} =+ useTimelineKeyframeDragState();++ return useCallback(+ (e: React.PointerEvent<HTMLButtonElement>) => {+ if (+ e.button !== 0 ||+ !selectable ||+ timelineWidth === null ||+ previewServerState.type !== 'connected'+ ) {+ return;+ }++ e.preventDefault();+ e.stopPropagation();++ const interaction = {+ shiftKey: e.shiftKey,+ toggleKey: e.metaKey || e.ctrlKey,+ };+ const shouldDragExistingSelection =+ selected && !interaction.shiftKey && !interaction.toggleKey;++ if (!shouldDragExistingSelection) {+ onSelect(interaction);+ }++ const clickedSelection: TimelineKeyframeSelection = {+ type: 'keyframe',+ nodePathInfo,+ frame,+ };+ const selectedKeyframes =+ currentSelection.current.selectedItems.filter(isKeyframeSelection);+ const keyframesToDrag =+ shouldDragExistingSelection && selectedKeyframes.length > 0+ ? selectedKeyframes+ : [clickedSelection];++ const startClientX = e.clientX;+ let dragTargets: TimelineKeyframeDragTarget[] | null = null;+ let hasDragged = false;+ let lastDelta = 0;++ const resolveDragTargets = () => {+ if (dragTargets !== null) {+ return dragTargets;+ }++ dragTargets = keyframesToDrag+ .map((keyframe) =>+ getTimelineKeyframeDragTarget({+ codeValues,+ displayFrame: keyframe.frame,+ nodePathInfo: keyframe.nodePathInfo,+ overrideIdsToNodePaths: overrideIdToNodePathMappings,+ sequences,+ }),+ )+ .filter(+ (target): target is TimelineKeyframeDragTarget => target !== null,+ );+ return dragTargets;+ };++ const cleanup = () => {+ window.removeEventListener('pointermove', onPointerMove);+ window.removeEventListener('pointerup', onPointerUp);+ window.removeEventListener('pointercancel', onPointerCancel);+ };++ const clearActiveOverrides = () => {+ const targets = dragTargets;+ if (targets === null) {+ return;+ }++ clearDragOverridesForTargets({+ clearDragOverrides,+ clearEffectDragOverrides,+ targets,+ });+ };++ const onPointerMove = (event: PointerEvent) => {+ const clientXDelta = event.clientX - startClientX;+ if (!hasDragged && Math.abs(clientXDelta) < pointerDragThreshold) {+ return;+ }++ const targets = resolveDragTargets();+ if (targets.length === 0) {+ cleanup();+ clearDraggedKeyframes();+ return;+ }++ const rawDelta = getFrameDelta({+ clientXDelta,+ durationInFrames: videoConfig.durationInFrames,+ timelineWidth,+ });+ const delta = rawDelta;++ if (hasDragged && delta === lastDelta) {+ return;+ }++ hasDragged = true;+ lastDelta = delta;+ setDraggedKeyframes(+ targets.map((target) => ({+ nodePathInfo: target.nodePathInfo,+ frame: target.displayFrame + delta,+ })),+ );+ applyDragOverrides({+ delta,+ setDragOverrides,+ setEffectDragOverrides,+ targets,+ });+ };++ const onPointerUp = () => {+ cleanup();++ const targets = dragTargets;+ if (!hasDragged || lastDelta === 0 || targets === null) {+ clearActiveOverrides();+ clearDraggedKeyframes();+ return;+ }++ currentSelection.current.selectItems(+ targets.map((target) => ({+ type: 'keyframe',+ nodePathInfo: target.nodePathInfo,+ frame: target.displayFrame + lastDelta,+ })),+ );++ clearActiveOverrides();+ clearDraggedKeyframes();++ callMoveKeyframes({+ sequenceKeyframes: targets+ .filter(+ (+ target,+ ): target is TimelineKeyframeDragTarget & {+ type: 'sequence';+ } => target.type === 'sequence',+ )+ .map((target) => ({+ fileName: target.fileName,+ nodePath: target.nodePath,+ fieldKey: target.fieldKey,+ fromFrame: target.sourceFrame,+ toFrame: target.sourceFrame + lastDelta,+ schema: target.schema,+ })),+ effectKeyframes: targets+ .filter(+ (+ target,+ ): target is TimelineKeyframeDragTarget & {+ type: 'effect';+ } => target.type === 'effect',+ )+ .map((target) => ({+ fileName: target.fileName,+ nodePath: target.nodePath,+ effectIndex: target.effectIndex,+ fieldKey: target.fieldKey,+ fromFrame: target.sourceFrame,+ toFrame: target.sourceFrame + lastDelta,+ schema: target.schema,+ })),+ setCodeValues,+ clientId: previewServerState.clientId,+ }).catch(() => undefined);+ };++ const onPointerCancel = () => {+ cleanup();+ clearActiveOverrides();+ clearDraggedKeyframes();+ };++ window.addEventListener('pointermove', onPointerMove);+ window.addEventListener('pointerup', onPointerUp);+ window.addEventListener('pointercancel', onPointerCancel);+ },+ [+ clearDragOverrides,+ clearEffectDragOverrides,+ clearDraggedKeyframes,+ codeValues,+ currentSelection,+ frame,+ nodePathInfo,+ onSelect,+ overrideIdToNodePathMappings,+ previewServerState,+ selectable,+ selected,+ sequences,+ setCodeValues,+ setDragOverrides,+ setDraggedKeyframes,+ setEffectDragOverrides,+ timelineWidth,+ videoConfig.durationInFrames,+ ],+ );+};diff --git a/packages/studio/src/test/timeline-keyframe-navigation.test.ts b/packages/studio/src/test/timeline-keyframe-navigation.test.tsindex fe7123d398..0c757e1af9 100644--- a/packages/studio/src/test/timeline-keyframe-navigation.test.ts+++ b/packages/studio/src/test/timeline-keyframe-navigation.test.ts@@ -6,21 +6,58 @@ import {} from '../components/Timeline/get-keyframe-navigation';const keyframes = [{frame: 10}, {frame: 30}, {frame: 90}];+const durationInFrames = 100;test('getPreviousKeyframeDisplayFrame returns the nearest earlier keyframe', () => {- expect(getPreviousKeyframeDisplayFrame(keyframes, 0)).toBe(null);- expect(getPreviousKeyframeDisplayFrame(keyframes, 10)).toBe(null);- expect(getPreviousKeyframeDisplayFrame(keyframes, 11)).toBe(10);- expect(getPreviousKeyframeDisplayFrame(keyframes, 30)).toBe(10);- expect(getPreviousKeyframeDisplayFrame(keyframes, 100)).toBe(90);+ expect(getPreviousKeyframeDisplayFrame(keyframes, 0, durationInFrames)).toBe(+ null,+ );+ expect(getPreviousKeyframeDisplayFrame(keyframes, 10, durationInFrames)).toBe(+ null,+ );+ expect(getPreviousKeyframeDisplayFrame(keyframes, 11, durationInFrames)).toBe(+ 10,+ );+ expect(getPreviousKeyframeDisplayFrame(keyframes, 30, durationInFrames)).toBe(+ 10,+ );+ expect(+ getPreviousKeyframeDisplayFrame(keyframes, 100, durationInFrames),+ ).toBe(90);});test('getNextKeyframeDisplayFrame returns the nearest later keyframe', () => {- expect(getNextKeyframeDisplayFrame(keyframes, 0)).toBe(10);- expect(getNextKeyframeDisplayFrame(keyframes, 10)).toBe(30);- expect(getNextKeyframeDisplayFrame(keyframes, 29)).toBe(30);- expect(getNextKeyframeDisplayFrame(keyframes, 90)).toBe(null);- expect(getNextKeyframeDisplayFrame(keyframes, 100)).toBe(null);+ expect(getNextKeyframeDisplayFrame(keyframes, 0, durationInFrames)).toBe(10);+ expect(getNextKeyframeDisplayFrame(keyframes, 10, durationInFrames)).toBe(30);+ expect(getNextKeyframeDisplayFrame(keyframes, 29, durationInFrames)).toBe(30);+ expect(getNextKeyframeDisplayFrame(keyframes, 90, durationInFrames)).toBe(+ null,+ );+ expect(getNextKeyframeDisplayFrame(keyframes, 100, durationInFrames)).toBe(+ null,+ );+});++test('keyframe navigation skips frames outside the timeline range', () => {+ const offTimelineKeyframes = [+ {frame: 40},+ {frame: -10},+ {frame: 100},+ {frame: 120},+ {frame: 20},+ ];++ expect(getPreviousKeyframeDisplayFrame(offTimelineKeyframes, 30, 100)).toBe(+ 20,+ );+ expect(getNextKeyframeDisplayFrame(offTimelineKeyframes, 30, 100)).toBe(40);+ expect(getPreviousKeyframeDisplayFrame(offTimelineKeyframes, 10, 100)).toBe(+ null,+ );+ expect(getNextKeyframeDisplayFrame(offTimelineKeyframes, 50, 100)).toBe(null);+ expect(getPreviousKeyframeDisplayFrame(offTimelineKeyframes, 120, 100)).toBe(+ 40,+ );});test('hasKeyframeAtSourceFrame checks source frame membership', () => {diff --git a/packages/studio/src/test/timeline-keyframes.test.ts b/packages/studio/src/test/timeline-keyframes.test.tsindex c606e7684f..2e5928f2d9 100644--- a/packages/studio/src/test/timeline-keyframes.test.ts+++ b/packages/studio/src/test/timeline-keyframes.test.ts@@ -1,12 +1,13 @@import {expect, test} from 'bun:test';-import {Internals, type CodeValues} from 'remotion';import type {CanUpdateSequencePropStatusKeyframed,SequencePropsSubscriptionKey,TSequence,} from 'remotion';+import {Internals, type CodeValues} from 'remotion';import {getNodeKeyframes} from '../components/Timeline/get-node-keyframes';import {getTimelineKeyframes} from '../components/Timeline/get-timeline-keyframes';+import {getTimelineKeyframeDragKey} from '../components/Timeline/TimelineKeyframeDragState';import {calculateTimeline} from '../helpers/calculate-timeline';import type {TimelineTreeNode} from '../helpers/timeline-layout';@@ -322,3 +323,19 @@ test('getNodeKeyframes replaces existing keyframes from keyframed drag overrides{frame: 90, value: 5},]);});++test('timeline keyframe drag keys follow the current display frame', () => {+ const {nodePathInfo} = makeSequenceFieldNode('style.scale');++ expect(+ getTimelineKeyframeDragKey({+ nodePathInfo,+ frame: 30,+ }),+ ).not.toBe(+ getTimelineKeyframeDragKey({+ nodePathInfo,+ frame: 60,+ }),+ );+});