🎥 Make videos programmatically with React
`@remotion/canvas`: Add `getCanvasKeyframeToggle()` and `startCanvasKeyframeDrag()` for editing keyframes outside the Studio
JonnyBurger00315d04679d
diff --git a/bun.lock b/bun.lockindex 1b3b8355f3..61dddd8c5d 100644--- a/bun.lock+++ b/bun.lock@@ -239,6 +239,7 @@"version": "4.0.529","dependencies": {"@remotion/player": "workspace:*",+ "@remotion/studio-shared": "workspace:*","remotion": "workspace:*",},"devDependencies": {diff --git a/packages/canvas/bundle.ts b/packages/canvas/bundle.tsindex aecd71a704..dbef6efe0a 100644--- a/packages/canvas/bundle.ts+++ b/packages/canvas/bundle.ts@@ -5,7 +5,13 @@ if (process.env.NODE_ENV !== 'production') {throw new Error('This script must be run using NODE_ENV=production');}-const external = ['@remotion/player', 'react', 'react-dom', 'remotion'];+const external = [+ '@remotion/player',+ '@remotion/studio-shared',+ 'react',+ 'react-dom',+ 'remotion',+];console.time('Generated.');const esmOutput = await build({diff --git a/packages/canvas/package.json b/packages/canvas/package.jsonindex 0dfa5113cd..1267661f82 100644--- a/packages/canvas/package.json+++ b/packages/canvas/package.json@@ -25,6 +25,7 @@},"dependencies": {"@remotion/player": "workspace:*",+ "@remotion/studio-shared": "workspace:*","remotion": "workspace:*"},"peerDependencies": {diff --git a/packages/canvas/src/canvas-internals.ts b/packages/canvas/src/canvas-internals.tsindex dc2f056b47..e543f673d3 100644--- a/packages/canvas/src/canvas-internals.ts+++ b/packages/canvas/src/canvas-internals.ts@@ -99,6 +99,25 @@ export {resolveKeyframeSourceFrame,} from './keyframe-frames';export type {KeyframeSourceFrame} from './keyframe-frames';+export {+ getNextKeyframeDisplayFrame,+ getPreviousKeyframeDisplayFrame,+ hasKeyframeAtSourceFrame,+} from './keyframe-navigation';+export {+ getCanvasKeyframeValueAtSourceFrame,+ getCanvasKeyframeValueToAdd,+ isCanvasKeyframablePropStatus,+ normalizeFontWeightForKeyframe,+} from './keyframe-value';+export {+ canMoveCanvasKeyframes,+ getBoundedKeyframeDragDelta,+ getCanvasKeyframeMove,+ getMovedCanvasKeyframeOverride,+ getMovedCanvasKeyframeStatus,+} from './keyframe-move';+export type {CanvasKeyframeMoveTarget} from './keyframe-move';export {canvasOutlineSnapThresholdPx,findCanvasOutlineSnap,diff --git a/packages/canvas/src/index.ts b/packages/canvas/src/index.tsindex 26f6be1342..8a789872ff 100644--- a/packages/canvas/src/index.ts+++ b/packages/canvas/src/index.ts@@ -42,6 +42,26 @@ export type {CanvasSequencePropsChangeHandler,CanvasSequencePropStatusResolver,} from './sequence-props-change';+export {+ getCanvasKeyframeDisplayFrame,+ getCanvasKeyframes,+ getCanvasKeyframeSourceFrame,+ getCanvasKeyframeToggle,+ getCanvasPropValueAtFrame,+} from './keyframes';+export type {+ CanvasKeyframe,+ CanvasKeyframeChange,+ CanvasKeyframeOperation,+ CanvasKeyframeToggle,+ CanvasKeyframeTrack,+} from './keyframes';+export type {CanvasKeyframeMove} from './keyframe-move';+export {startCanvasKeyframeDrag} from './keyframe-drag';+export type {+ CanvasKeyframeDragEnd,+ CanvasKeyframeDragTarget,+} from './keyframe-drag';export type {CanvasOutline,CanvasOutlinePoint,diff --git a/packages/canvas/src/keyframe-drag.ts b/packages/canvas/src/keyframe-drag.tsnew file mode 100644index 0000000000..6b3acde61e--- /dev/null+++ b/packages/canvas/src/keyframe-drag.ts@@ -0,0 +1,226 @@+import type {+ CanUpdateSequencePropStatusKeyframed,+ InteractivitySchema,+} from 'remotion';+import {Internals} from 'remotion';+import type {CanvasOverridesController} from './canvas-controller';+import type {SequenceNodePathInfo} from './get-timeline-sequence-sort-key';+import {+ canMoveCanvasKeyframes,+ getBoundedKeyframeDragDelta,+ getCanvasKeyframeMove,+ getMovedCanvasKeyframeOverride,+ type CanvasKeyframeMoveTarget,+} from './keyframe-move';+import type {CanvasKeyframeChange, CanvasKeyframeTrack} from './keyframes';+import {getCanvasKeyframeSourceFrame} from './keyframes';+import {+ isPointerSessionRelease,+ startCapturedPointerSession,+} from './pointer-session';++export const canvasKeyframeDragThresholdPx = 3;++/** A keyframe that a timeline drag moves. */+export type CanvasKeyframeDragTarget = {+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly track: CanvasKeyframeTrack;+ readonly schema: InteractivitySchema;+ readonly key: string;+ readonly propStatus: CanUpdateSequencePropStatusKeyframed;+ /** The keyframe in composition frames. */+ readonly frame: number;+};++export type CanvasKeyframeDragEnd = {+ /**+ * One move per prop whose keyframes changed position. Empty when the+ * pointer did not move past the drag threshold, returned to the start,+ * or the move cannot be applied; the overrides are cleared in that case.+ * Otherwise, persist the changes and clear the overrides of every+ * `nodePathInfo` afterwards.+ */+ readonly changes: readonly CanvasKeyframeChange[];+ /** How far the keyframes moved, in composition frames. */+ readonly delta: number;+ readonly dragged: boolean;+ /** False when the gesture was cancelled, e.g. by the window losing focus. */+ readonly released: boolean;+};++type DragGroup = {+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly schema: InteractivitySchema;+ readonly key: string;+ readonly targets: CanvasKeyframeMoveTarget[];+};++const groupCanvasKeyframeDragTargets = (+ targets: readonly CanvasKeyframeDragTarget[],+): DragGroup[] => {+ const groups = new Map<string, DragGroup>();+ for (const target of targets) {+ const sourceFrame = getCanvasKeyframeSourceFrame({+ track: target.track,+ propStatus: target.propStatus,+ frame: target.frame,+ });+ if (+ !target.propStatus.keyframes.some(+ (keyframe) => keyframe.frame === sourceFrame,+ )+ ) {+ continue;+ }++ const groupKey = `${Internals.makeSequencePropsSubscriptionKey(+ target.nodePathInfo.sequenceSubscriptionKey,+ )}\0${target.key}`;+ const group = groups.get(groupKey) ?? {+ nodePathInfo: target.nodePathInfo,+ schema: target.schema,+ key: target.key,+ targets: [],+ };+ groups.set(groupKey, group);+ group.targets.push({+ propStatus: target.propStatus,+ displayFrame: target.frame,+ sourceFrame,+ keyframePlaybackRate: target.track.keyframePlaybackRate,+ });+ }++ return [...groups.values()];+};++/**+ * Moves keyframes along the timeline with the pointer. The moved positions+ * are previewed through `overrides` and reported once the pointer is+ * released. Returns a function that cancels the gesture.+ */+export const startCanvasKeyframeDrag = ({+ event,+ captureTarget,+ targets,+ pixelsPerFrame,+ durationInFrames,+ overrides,+ onDragStart,+ onDragMove,+ onDragEnd,+}: {+ readonly event: Pick<PointerEvent, 'button' | 'pointerId' | 'clientX'>;+ readonly captureTarget: Element;+ readonly targets: readonly CanvasKeyframeDragTarget[];+ /** The width of one composition frame on the timeline. */+ readonly pixelsPerFrame: number;+ readonly durationInFrames: number;+ readonly overrides: CanvasOverridesController;+ readonly onDragStart: (() => void) | null;+ /** Called with the previewed movement in composition frames whenever it changes. */+ readonly onDragMove: ((delta: number) => void) | null;+ readonly onDragEnd: (end: CanvasKeyframeDragEnd) => void;+}): (() => void) => {+ const groups = groupCanvasKeyframeDragTargets(targets);+ const moveTargets = groups.flatMap((group) => group.targets);+ const startClientX = event.clientX;+ let dragged = false;+ let lastDelta = 0;+ let previewed = false;++ const clearOverrides = () => {+ if (!previewed) {+ return;+ }++ previewed = false;+ for (const group of groups) {+ overrides.clear(group.nodePathInfo);+ }+ };++ const canMove = (delta: number) =>+ groups.every((group) =>+ canMoveCanvasKeyframes({targets: group.targets, delta}),+ );++ return startCapturedPointerSession({+ event,+ captureTarget,+ onMove: (moveEvent) => {+ const clientXDelta = moveEvent.clientX - startClientX;+ if (!dragged && Math.abs(clientXDelta) < canvasKeyframeDragThresholdPx) {+ return;+ }++ if (moveTargets.length === 0 || pixelsPerFrame <= 0) {+ return;+ }++ moveEvent.preventDefault();+ const delta = getBoundedKeyframeDragDelta({+ delta: Math.round(clientXDelta / pixelsPerFrame),+ durationInFrames,+ targets: moveTargets,+ });+ if (dragged && delta === lastDelta) {+ return;+ }++ if (!dragged) {+ dragged = true;+ onDragStart?.();+ }++ lastDelta = delta;+ // A move that cannot be applied shows the keyframes at their original+ // positions until the pointer moves on.+ if (!canMove(delta)) {+ clearOverrides();+ onDragMove?.(0);+ return;+ }++ previewed = true;+ for (const group of groups) {+ overrides.set(+ group.nodePathInfo,+ group.key,+ getMovedCanvasKeyframeOverride({targets: group.targets, delta}),+ );+ }++ onDragMove?.(delta);+ },+ onEnd: (reason, endEvent) => {+ const released = isPointerSessionRelease(reason, endEvent);+ const moved =+ dragged && released && lastDelta !== 0 && canMove(lastDelta);+ if (!moved) {+ clearOverrides();+ onDragEnd({changes: [], delta: 0, dragged, released});+ return;+ }++ onDragEnd({+ changes: groups.map(+ (group): CanvasKeyframeChange => ({+ nodePathInfo: group.nodePathInfo,+ key: group.key,+ schema: group.schema,+ operation: {+ type: 'move',+ moves: group.targets.map((target) =>+ getCanvasKeyframeMove(target, lastDelta),+ ),+ },+ }),+ ),+ delta: lastDelta,+ dragged,+ released,+ });+ },+ });+};diff --git a/packages/canvas/src/keyframe-move.ts b/packages/canvas/src/keyframe-move.tsnew file mode 100644index 0000000000..d4bedd613e--- /dev/null+++ b/packages/canvas/src/keyframe-move.ts@@ -0,0 +1,124 @@+import {+ canMoveKeyframesWithoutCollisions,+ moveKeyframesInPropStatus,+} from '@remotion/studio-shared';+import type {+ CanUpdateSequencePropStatusKeyframed,+ DragOverrideValue,+} from 'remotion';+import {+ getKeyframePlaybackRate,+ resolveKeyframeSourceFrame,+} from './keyframe-frames';++export type CanvasKeyframeMove = {+ readonly fromFrame: number;+ readonly toFrame: number;+};++/** A keyframe that is moved along the timeline. */+export type CanvasKeyframeMoveTarget = {+ readonly propStatus: CanUpdateSequencePropStatusKeyframed;+ /** The keyframe in composition frames. */+ readonly displayFrame: number;+ /** The keyframe in the clock of the interpolation. */+ readonly sourceFrame: number;+ readonly keyframePlaybackRate: number;+};++/** Keeps every moved keyframe inside the composition. */+export const getBoundedKeyframeDragDelta = ({+ delta,+ durationInFrames,+ targets,+}: {+ readonly delta: number;+ readonly durationInFrames: number;+ readonly targets: readonly {readonly displayFrame: number}[];+}) => {+ if (targets.length === 0 || durationInFrames <= 0) {+ return 0;+ }++ const minDelta = Math.max(...targets.map((target) => -target.displayFrame));+ const maxDelta = Math.min(+ ...targets.map((target) => durationInFrames - 1 - target.displayFrame),+ );++ return Math.min(Math.max(delta, minDelta), maxDelta);+};++/** Converts a movement in composition frames into a move of the source keyframe. */+export const getCanvasKeyframeMove = (+ target: CanvasKeyframeMoveTarget,+ delta: number,+): CanvasKeyframeMove => ({+ fromFrame: target.sourceFrame,+ toFrame: resolveKeyframeSourceFrame(+ target.sourceFrame ++ delta *+ getKeyframePlaybackRate(target.propStatus, target.keyframePlaybackRate),+ target.propStatus,+ ),+});++/**+ * Whether the keyframes of one prop can be moved by `delta` frames: every+ * moved keyframe exists and no two moved keyframes end up on the same frame.+ * A keyframe that is not moved and lies on a destination frame is replaced.+ */+export const canMoveCanvasKeyframes = ({+ targets,+ delta,+}: {+ /** Keyframes of the same prop. */+ readonly targets: readonly CanvasKeyframeMoveTarget[];+ readonly delta: number;+}): boolean => {+ const [first] = targets;+ if (!first) {+ return true;+ }++ return canMoveKeyframesWithoutCollisions({+ status: first.propStatus,+ moves: targets.map((target) => getCanvasKeyframeMove(target, delta)),+ });+};++/** The keyframed status of a prop after moving some of its keyframes. */+export const getMovedCanvasKeyframeStatus = ({+ targets,+ delta,+}: {+ /** Keyframes of the same prop. */+ readonly targets: readonly CanvasKeyframeMoveTarget[];+ readonly delta: number;+}): CanUpdateSequencePropStatusKeyframed => {+ const [first] = targets;+ if (!first) {+ throw new Error('Expected a keyframe to move');+ }++ const moved = moveKeyframesInPropStatus({+ status: first.propStatus,+ moves: targets.map((target) => getCanvasKeyframeMove(target, delta)),+ });+ if (moved.status !== 'keyframed') {+ throw new Error('Expected keyframed status');+ }++ return moved;+};++/** Previews moved keyframes through a drag override. */+export const getMovedCanvasKeyframeOverride = ({+ targets,+ delta,+}: {+ readonly targets: readonly CanvasKeyframeMoveTarget[];+ readonly delta: number;+}): DragOverrideValue => ({+ type: 'keyframed',+ status: getMovedCanvasKeyframeStatus({targets, delta}),+});diff --git a/packages/studio/src/components/Timeline/get-keyframe-navigation.ts b/packages/canvas/src/keyframe-navigation.tssimilarity index 100%rename from packages/studio/src/components/Timeline/get-keyframe-navigation.tsrename to packages/canvas/src/keyframe-navigation.tsdiff --git a/packages/canvas/src/keyframe-value.ts b/packages/canvas/src/keyframe-value.tsnew file mode 100644index 0000000000..557853382b--- /dev/null+++ b/packages/canvas/src/keyframe-value.ts@@ -0,0 +1,120 @@+import {isSchemaFieldKeyframable} from '@remotion/studio-shared';+import type {+ CanUpdateSequencePropStatus,+ DragOverrideValue,+ InteractivitySchema,+} from 'remotion';+import {Internals} from 'remotion';+import {getKeyframeLocalFrame} from './keyframe-frames';++export const normalizeFontWeightForKeyframe = (+ value: unknown,+): number | null => {+ if (value === 'normal') {+ return 400;+ }++ if (value === 'bold') {+ return 700;+ }++ if (typeof value === 'number') {+ return Number.isFinite(value) ? value : null;+ }++ if (typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value)) {+ return Number(value);+ }++ return null;+};++/**+ * Whether keyframes can be added to a prop: the schema field supports+ * interpolation and the source value is not computed.+ */+export const isCanvasKeyframablePropStatus = ({+ propStatus,+ schema,+ key,+}: {+ readonly propStatus: CanUpdateSequencePropStatus;+ readonly schema: InteractivitySchema;+ readonly key: string;+}): boolean => {+ if (propStatus.status === 'computed') {+ return false;+ }++ if (propStatus.status === 'static' && propStatus.canKeyframe === false) {+ return false;+ }++ return isSchemaFieldKeyframable({schema, key});+};++/**+ * The value a prop has at a frame of its source clock, including an active+ * drag override. Static props return their code value, keyframed props the+ * interpolated value. `null` when the source has no value, e.g. a computed+ * prop or a static prop that is not set and has no default.+ */+export const getCanvasKeyframeValueAtSourceFrame = ({+ propStatus,+ sourceFrame,+ defaultValue,+ dragOverrideValue,+}: {+ readonly propStatus: CanUpdateSequencePropStatus;+ readonly sourceFrame: number;+ readonly defaultValue: unknown;+ readonly dragOverrideValue: DragOverrideValue | undefined;+}): unknown | null => {+ if (propStatus.status === 'computed') {+ return null;+ }++ const value = Internals.getEffectiveVisualModeValue({+ propStatus,+ dragOverrideValue,+ frame: getKeyframeLocalFrame(sourceFrame, propStatus),+ defaultValue,+ shouldResortToDefaultValueIfUndefined: true,+ });++ return value === undefined ? null : value;+};++/**+ * The value to write into a new keyframe of a prop: the current value,+ * converted to a representation that can be interpolated.+ */+export const getCanvasKeyframeValueToAdd = ({+ propStatus,+ schema,+ key,+ sourceFrame,+ defaultValue,+ dragOverrideValue,+}: {+ readonly propStatus: CanUpdateSequencePropStatus;+ readonly schema: InteractivitySchema;+ readonly key: string;+ readonly sourceFrame: number;+ readonly defaultValue: unknown;+ readonly dragOverrideValue: DragOverrideValue | undefined;+}): unknown | null => {+ const value = getCanvasKeyframeValueAtSourceFrame({+ propStatus,+ sourceFrame,+ defaultValue,+ dragOverrideValue,+ });+ if (value === null) {+ return null;+ }++ return schema[key]?.type === 'font-weight'+ ? normalizeFontWeightForKeyframe(value)+ : value;+};diff --git a/packages/canvas/src/keyframes.ts b/packages/canvas/src/keyframes.tsnew file mode 100644index 0000000000..93178d7232--- /dev/null+++ b/packages/canvas/src/keyframes.ts@@ -0,0 +1,242 @@+import type {CanUpdateSequencePropStatus, InteractivitySchema} from 'remotion';+import {Internals} from 'remotion';+import type {+ SequenceNodePathInfo,+ TimelineTrackData,+} from './get-timeline-sequence-sort-key';+import {+ getKeyframeDisplayOffset,+ getKeyframePlaybackRate,+ getKeyframeSourceFrame,+ getTimelineKeyframes,+} from './keyframe-frames';+import type {CanvasKeyframeMove} from './keyframe-move';+import {+ getNextKeyframeDisplayFrame,+ getPreviousKeyframeDisplayFrame,+ hasKeyframeAtSourceFrame,+} from './keyframe-navigation';+import {+ getCanvasKeyframeValueAtSourceFrame,+ getCanvasKeyframeValueToAdd,+ isCanvasKeyframablePropStatus,+} from './keyframe-value';++/** The timing of a track that places its keyframes on the composition timeline. */+export type CanvasKeyframeTrack = Pick<+ TimelineTrackData,+ 'keyframeDisplayOffset' | 'keyframePlaybackRate'+>;++/** A keyframe of a prop, positioned in composition frames. */+export type CanvasKeyframe = {+ readonly frame: number;+ readonly value: unknown;+};++/**+ * An edit of the keyframes of one prop. The frames are in the clock of the+ * interpolation, as `updateNodeKeyframes()` from @remotion/codemods expects.+ */+export type CanvasKeyframeOperation =+ | {+ /** Adds a keyframe, or replaces the value of the keyframe at `frame`. */+ readonly type: 'add';+ readonly frame: number;+ readonly value: unknown;+ }+ | {+ readonly type: 'remove';+ readonly frame: number;+ /** The static value to write when the last keyframe is removed; `null` keeps the removed value. */+ readonly valueWhenLastKeyframeDeleted: unknown | null;+ }+ | {+ readonly type: 'move';+ readonly moves: CanvasKeyframeMove[];+ };++export type CanvasKeyframeChange = {+ /** The registered source node of the sequence. */+ readonly nodePathInfo: SequenceNodePathInfo;+ /** The interactivity schema key in dot notation, e.g. `style.opacity`. */+ readonly key: string;+ /** The interactivity schema of the element, for the codemods. */+ readonly schema: InteractivitySchema;+ readonly operation: CanvasKeyframeOperation;+};++/** The keyframes of a prop, placed on the composition timeline. */+export const getCanvasKeyframes = ({+ track,+ propStatus,+}: {+ readonly track: CanvasKeyframeTrack;+ readonly propStatus: CanUpdateSequencePropStatus | null;+}): CanvasKeyframe[] => {+ return getTimelineKeyframes(+ propStatus,+ track.keyframeDisplayOffset,+ track.keyframePlaybackRate,+ );+};++/**+ * Converts a composition frame to the frame clock of the prop's+ * interpolation, in which keyframe operations are expressed.+ */+export const getCanvasKeyframeSourceFrame = ({+ track,+ propStatus,+ frame,+}: {+ readonly track: CanvasKeyframeTrack;+ readonly propStatus: CanUpdateSequencePropStatus | null;+ readonly frame: number;+}): number => {+ return getKeyframeSourceFrame({+ displayFrame: frame,+ keyframeDisplayOffset: getKeyframeDisplayOffset({+ propStatus,+ keyframeDisplayOffset: track.keyframeDisplayOffset,+ keyframePlaybackRate: track.keyframePlaybackRate,+ }),+ keyframePlaybackRate: track.keyframePlaybackRate,+ propStatus,+ });+};++/** Converts a frame of the prop's interpolation to a composition frame. */+export const getCanvasKeyframeDisplayFrame = ({+ track,+ propStatus,+ sourceFrame,+}: {+ readonly track: CanvasKeyframeTrack;+ readonly propStatus: CanUpdateSequencePropStatus | null;+ readonly sourceFrame: number;+}): number => {+ return (+ sourceFrame /+ getKeyframePlaybackRate(propStatus, track.keyframePlaybackRate) ++ getKeyframeDisplayOffset({+ propStatus,+ keyframeDisplayOffset: track.keyframeDisplayOffset,+ keyframePlaybackRate: track.keyframePlaybackRate,+ })+ );+};++const getSchemaFieldDefault = (+ schema: InteractivitySchema,+ key: string,+): unknown => {+ const field = Internals.getFlatSchemaWithAllKeys(schema)[key];+ return field !== undefined && 'default' in field ? field.default : undefined;+};++/**+ * The value a prop has at a composition frame according to the source: the+ * code value of a static prop, the interpolated value of a keyframed prop,+ * or the schema default when the prop is not set. `null` for computed props.+ */+export const getCanvasPropValueAtFrame = ({+ track,+ schema,+ key,+ propStatus,+ frame,+}: {+ readonly track: CanvasKeyframeTrack;+ readonly schema: InteractivitySchema;+ readonly key: string;+ readonly propStatus: CanUpdateSequencePropStatus;+ readonly frame: number;+}): unknown | null => {+ return getCanvasKeyframeValueAtSourceFrame({+ propStatus,+ sourceFrame: getCanvasKeyframeSourceFrame({track, propStatus, frame}),+ defaultValue: getSchemaFieldDefault(schema, key),+ dragOverrideValue: undefined,+ });+};++export type CanvasKeyframeToggle = {+ /** Whether keyframes can be added to the prop. */+ readonly keyframable: boolean;+ /** Whether the prop has a keyframe at the frame. */+ readonly hasKeyframe: boolean;+ /** The composition frame of the closest keyframe before the frame, if any. */+ readonly previousFrame: number | null;+ /** The composition frame of the closest keyframe after the frame, if any. */+ readonly nextFrame: number | null;+ /**+ * Removes the keyframe at the frame, or adds one with the value the prop+ * has there. `null` when the prop cannot be keyframed.+ */+ readonly change: CanvasKeyframeChange | null;+};++/** Describes the keyframe button of a prop at a composition frame. */+export const getCanvasKeyframeToggle = ({+ nodePathInfo,+ track,+ schema,+ key,+ propStatus,+ frame,+ durationInFrames,+}: {+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly track: CanvasKeyframeTrack;+ readonly schema: InteractivitySchema;+ readonly key: string;+ readonly propStatus: CanUpdateSequencePropStatus;+ readonly frame: number;+ readonly durationInFrames: number;+}): CanvasKeyframeToggle => {+ const keyframes = getCanvasKeyframes({track, propStatus});+ const sourceFrame = getCanvasKeyframeSourceFrame({track, propStatus, frame});+ const hasKeyframe =+ propStatus.status === 'keyframed' &&+ hasKeyframeAtSourceFrame(propStatus.keyframes, sourceFrame);+ const keyframable = isCanvasKeyframablePropStatus({propStatus, schema, key});+ const base = {nodePathInfo, key, schema};++ let change: CanvasKeyframeChange | null = null;+ if (hasKeyframe) {+ change = {+ ...base,+ operation: {+ type: 'remove',+ frame: sourceFrame,+ valueWhenLastKeyframeDeleted: null,+ },+ };+ } else if (keyframable) {+ const value = getCanvasKeyframeValueToAdd({+ propStatus,+ schema,+ key,+ sourceFrame,+ defaultValue: getSchemaFieldDefault(schema, key),+ dragOverrideValue: undefined,+ });+ change =+ value === null+ ? null+ : {...base, operation: {type: 'add', frame: sourceFrame, value}};+ }++ return {+ keyframable,+ hasKeyframe,+ previousFrame: getPreviousKeyframeDisplayFrame(+ keyframes,+ frame,+ durationInFrames,+ ),+ nextFrame: getNextKeyframeDisplayFrame(keyframes, frame, durationInFrames),+ change,+ };+};diff --git a/packages/canvas/src/test/keyframe-move.test.ts b/packages/canvas/src/test/keyframe-move.test.tsnew file mode 100644index 0000000000..f26fa13615--- /dev/null+++ b/packages/canvas/src/test/keyframe-move.test.ts@@ -0,0 +1,50 @@+import {expect, test} from 'bun:test';+import {getBoundedKeyframeDragDelta} from '../keyframe-move';++test('bounded keyframe drag delta stays inside the composition timeline', () => {+ expect(+ getBoundedKeyframeDragDelta({+ targets: [{displayFrame: 10}],+ delta: -20,+ durationInFrames: 100,+ }),+ ).toBe(-10);++ expect(+ getBoundedKeyframeDragDelta({+ targets: [{displayFrame: 90}],+ delta: 20,+ durationInFrames: 100,+ }),+ ).toBe(9);+});++test('bounded keyframe drag delta allows negative source frames when display frames stay in range', () => {+ expect(+ getBoundedKeyframeDragDelta({+ targets: [{displayFrame: 30}],+ delta: -30,+ durationInFrames: 100,+ }),+ ).toBe(-30);+});++test('bounded keyframe drag delta clamps multi-selection at the first timeline edge', () => {+ const targets = [{displayFrame: 20}, {displayFrame: 95}];++ expect(+ getBoundedKeyframeDragDelta({+ targets,+ delta: -30,+ durationInFrames: 100,+ }),+ ).toBe(-20);++ expect(+ getBoundedKeyframeDragDelta({+ targets,+ delta: 10,+ durationInFrames: 100,+ }),+ ).toBe(4);+});diff --git a/packages/canvas/src/test/keyframe-navigation.test.ts b/packages/canvas/src/test/keyframe-navigation.test.tsnew file mode 100644index 0000000000..8583bad224--- /dev/null+++ b/packages/canvas/src/test/keyframe-navigation.test.ts@@ -0,0 +1,66 @@+import {expect, test} from 'bun:test';+import {+ getNextKeyframeDisplayFrame,+ getPreviousKeyframeDisplayFrame,+ hasKeyframeAtSourceFrame,+} from '../keyframe-navigation';++const keyframes = [{frame: 10}, {frame: 30}, {frame: 90}];+const durationInFrames = 100;++test('getPreviousKeyframeDisplayFrame returns the nearest earlier keyframe', () => {+ 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, 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', () => {+ expect(hasKeyframeAtSourceFrame(keyframes, 10)).toBe(true);+ expect(hasKeyframeAtSourceFrame(keyframes, 11)).toBe(false);+});diff --git a/packages/studio/src/test/normalize-font-weight-for-keyframe.test.ts b/packages/canvas/src/test/normalize-font-weight-for-keyframe.test.tssimilarity index 86%rename from packages/studio/src/test/normalize-font-weight-for-keyframe.test.tsrename to packages/canvas/src/test/normalize-font-weight-for-keyframe.test.tsindex 65d84caec1..b9fb1be261 100644--- a/packages/studio/src/test/normalize-font-weight-for-keyframe.test.ts+++ b/packages/canvas/src/test/normalize-font-weight-for-keyframe.test.ts@@ -1,5 +1,5 @@import {expect, test} from 'bun:test';-import {normalizeFontWeightForKeyframe} from '../components/Timeline/normalize-font-weight-for-keyframe';+import {normalizeFontWeightForKeyframe} from '../keyframe-value';test('normalizes font weights before keyframing', () => {expect(normalizeFontWeightForKeyframe(650)).toBe(650);diff --git a/packages/canvas/tsconfig.json b/packages/canvas/tsconfig.jsonindex ebcfea2f5d..5a7f4cf798 100644--- a/packages/canvas/tsconfig.json+++ b/packages/canvas/tsconfig.json@@ -12,5 +12,9 @@"emitDeclarationOnly": true},"include": ["src"],- "references": [{"path": "../core"}, {"path": "../player"}]+ "references": [+ {"path": "../core"},+ {"path": "../player"},+ {"path": "../studio-shared"}+ ]}diff --git a/packages/docs/docs/canvas/create-canvas-controller.mdx b/packages/docs/docs/canvas/create-canvas-controller.mdxindex becb039220..2d17ae0470 100644--- a/packages/docs/docs/canvas/create-canvas-controller.mdx+++ b/packages/docs/docs/canvas/create-canvas-controller.mdx@@ -72,7 +72,7 @@ Passing an unchanged mapping is a no-op, so the function may be called from a `tPreview prop values on mounted sequences without changing the source. Overrides are applied to sequences that have a `nodePathInfo`, so register node paths first. They are kept while the composition stays mounted and are not persisted; write the final value to the source, for example with [`updateNodeProps()`](/docs/codemods/update-node-props), and clear the override once the update has been applied.-The Canvas sets overrides itself while an outline is being [moved](/docs/canvas/canvas#onsequencepropschange) and leaves them in place for you to clear after persisting.+The Canvas sets overrides itself while an outline is being [moved](/docs/canvas/canvas#onsequencepropschange), and [`startCanvasKeyframeDrag()`](/docs/canvas/start-canvas-keyframe-drag) sets them while keyframes are dragged. Both leave them in place for you to clear after persisting.#### set()diff --git a/packages/docs/docs/canvas/get-canvas-keyframe-display-frame.mdx b/packages/docs/docs/canvas/get-canvas-keyframe-display-frame.mdxnew file mode 100644index 0000000000..9604ab5236--- /dev/null+++ b/packages/docs/docs/canvas/get-canvas-keyframe-display-frame.mdx@@ -0,0 +1,57 @@+---+image: /generated/articles-docs-canvas-get-canvas-keyframe-display-frame.png+title: getCanvasKeyframeDisplayFrame()+crumb: '@remotion/canvas'+---++# getCanvasKeyframeDisplayFrame()<AvailableFrom v="4.0.530" />++Converts a frame of a prop's `interpolate()` expression to a composition frame. It is the inverse of [`getCanvasKeyframeSourceFrame()`](/docs/canvas/get-canvas-keyframe-source-frame).++:::warning++_Experimental API_: This package is not stable. Its public API may change without a major version bump.++:::++```ts twoslash title="seek-to-keyframe.ts"+// @moduleResolution: bundler+import {getCanvasKeyframeDisplayFrame, type TimelineTrackData} from '@remotion/canvas';+import type {CanUpdateSequencePropStatus} from 'remotion';+declare const track: TimelineTrackData;+declare const propStatus: CanUpdateSequencePropStatus;+declare const seek: (frame: number) => void;+// ---cut---+export const seekToKeyframe = (sourceFrame: number) => {+ seek(getCanvasKeyframeDisplayFrame({track, propStatus, sourceFrame}));+};+```++## Parameters++An object with the following properties:++### track++The `TimelineTrackData` of the sequence from [`controller.timeline`](/docs/canvas/create-canvas-controller#timeline). Only `keyframeDisplayOffset` and `keyframePlaybackRate` are read.++### propStatus++How the prop is written in the source, as the `props` of [`getNodeProps()`](/docs/codemods/get-node-props) report it, or `null`.++### sourceFrame++A frame in the clock of the interpolation, for example the `frame` of a keyframe in a `'keyframed'` prop status.++## Return value++The composition frame at which the keyframe applies. It may be fractional when the sequence has a `playbackRate`.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio="" hideServers />++## See also++- [`getCanvasKeyframeSourceFrame()`](/docs/canvas/get-canvas-keyframe-source-frame)+- [`getCanvasKeyframes()`](/docs/canvas/get-canvas-keyframes)diff --git a/packages/docs/docs/canvas/get-canvas-keyframe-source-frame.mdx b/packages/docs/docs/canvas/get-canvas-keyframe-source-frame.mdxnew file mode 100644index 0000000000..288f5448e7--- /dev/null+++ b/packages/docs/docs/canvas/get-canvas-keyframe-source-frame.mdx@@ -0,0 +1,74 @@+---+image: /generated/articles-docs-canvas-get-canvas-keyframe-source-frame.png+title: getCanvasKeyframeSourceFrame()+crumb: '@remotion/canvas'+---++# getCanvasKeyframeSourceFrame()<AvailableFrom v="4.0.530" />++Converts a composition frame to the frame clock of a prop's `interpolate()` expression, in which keyframe operations are expressed.++:::warning++_Experimental API_: This package is not stable. Its public API may change without a major version bump.++:::++```ts twoslash title="add-keyframe-at-playhead.ts"+// @moduleResolution: bundler+import {+ getCanvasKeyframeSourceFrame,+ type CanvasKeyframeChange,+ type SequenceNodePathInfo,+ type TimelineTrackData,+} from '@remotion/canvas';+import type {CanUpdateSequencePropStatus, InteractivitySchema} from 'remotion';+declare const nodePathInfo: SequenceNodePathInfo;+declare const track: TimelineTrackData;+declare const schema: InteractivitySchema;+declare const propStatus: CanUpdateSequencePropStatus;+declare const playhead: number;+// ---cut---+export const setOpacityAtPlayhead = (value: number): CanvasKeyframeChange => ({+ nodePathInfo,+ key: 'style.opacity',+ schema,+ operation: {+ type: 'add',+ frame: getCanvasKeyframeSourceFrame({track, propStatus, frame: playhead}),+ value,+ },+});+```++The keyframes of a nested or trimmed sequence are shifted on the composition timeline, and a `playbackRate` stretches them. `getCanvasKeyframeToggle()` and `startCanvasKeyframeDrag()` perform this conversion themselves; use this function when you construct a `CanvasKeyframeChange` yourself, for example to write a value edited in an inspector as a keyframe at the playhead.++## Parameters++An object with the following properties:++### track++The `TimelineTrackData` of the sequence from [`controller.timeline`](/docs/canvas/create-canvas-controller#timeline). Only `keyframeDisplayOffset` and `keyframePlaybackRate` are read.++### propStatus++How the prop is written in the source, as the `props` of [`getNodeProps()`](/docs/codemods/get-node-props) report it, or `null`. A keyframed status resolves rounding errors of the conversion to the existing keyframe frame, so an edit at a displayed keyframe hits that keyframe.++### frame++The composition frame to convert.++## Return value++The frame in the clock of the interpolation. Pass it as `frame` of an `add` or `remove` operation to [`updateNodeKeyframes()`](/docs/codemods/update-node-keyframes).++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio="" hideServers />++## See also++- [`getCanvasKeyframeDisplayFrame()`](/docs/canvas/get-canvas-keyframe-display-frame)+- [`getCanvasKeyframes()`](/docs/canvas/get-canvas-keyframes)+- [`getCanvasKeyframeToggle()`](/docs/canvas/get-canvas-keyframe-toggle)diff --git a/packages/docs/docs/canvas/get-canvas-keyframe-toggle.mdx b/packages/docs/docs/canvas/get-canvas-keyframe-toggle.mdxnew file mode 100644index 0000000000..1e5ba83f8d--- /dev/null+++ b/packages/docs/docs/canvas/get-canvas-keyframe-toggle.mdx@@ -0,0 +1,157 @@+---+image: /generated/articles-docs-canvas-get-canvas-keyframe-toggle.png+title: getCanvasKeyframeToggle()+crumb: '@remotion/canvas'+---++# getCanvasKeyframeToggle()<AvailableFrom v="4.0.530" />++Describes the keyframe button of a prop at a frame: whether the prop can be keyframed, whether a keyframe exists at the frame, where the neighboring keyframes are, and the change that adds or removes a keyframe there.++:::warning++_Experimental API_: This package is not stable. Its public API may change without a major version bump.++:::++```tsx twoslash title="KeyframeButton.tsx"+// @moduleResolution: bundler+import {+ getCanvasKeyframeToggle,+ type CanvasKeyframeChange,+ type SequenceNodePathInfo,+ type TimelineTrackData,+} from '@remotion/canvas';+import type {CanUpdateSequencePropStatus, InteractivitySchema} from 'remotion';+declare const nodePathInfo: SequenceNodePathInfo;+declare const track: TimelineTrackData;+declare const schema: InteractivitySchema;+declare const propStatus: CanUpdateSequencePropStatus;+declare const frame: number;+declare const durationInFrames: number;+declare const persist: (change: CanvasKeyframeChange) => void;+declare const seek: (frame: number) => void;+// ---cut---+export const KeyframeButton = () => {+ const toggle = getCanvasKeyframeToggle({+ nodePathInfo,+ track,+ schema,+ key: 'style.opacity',+ propStatus,+ frame,+ durationInFrames,+ });+ if (!toggle.keyframable && !toggle.hasKeyframe) {+ return null;+ }++ return (+ <>+ <button+ disabled={toggle.previousFrame === null}+ onClick={() => seek(toggle.previousFrame!)}+ >+ ◀+ </button>+ <button+ disabled={toggle.change === null}+ onClick={() => persist(toggle.change!)}+ >+ {toggle.hasKeyframe ? '◆' : '◇'}+ </button>+ <button+ disabled={toggle.nextFrame === null}+ onClick={() => seek(toggle.nextFrame!)}+ >+ ▶+ </button>+ </>+ );+};+```++## Parameters++An object with the following properties:++### nodePathInfo++The `SequenceNodePathInfo` of the sequence, from a track or a selection item. It is passed through to the returned `change`.++### track++The `TimelineTrackData` of the sequence from [`controller.timeline`](/docs/canvas/create-canvas-controller#timeline). Its `keyframeDisplayOffset` and `keyframePlaybackRate` convert `frame` to the frame clock of the interpolation.++### schema++The interactivity schema of the element, from [`track.sequence.controls`](/docs/canvas/create-canvas-controller#sequencecontrols). It decides whether the field can be keyframed and provides the default value of an unset prop.++### key++The schema key of the prop in dot notation, for example `'style.opacity'`.++### propStatus++How the prop is written in the source, as the `props` of [`getNodeProps()`](/docs/codemods/get-node-props) report it.++### frame++The composition frame at which the button acts, usually the playhead.++### durationInFrames++The duration of the composition. Keyframes outside of it are not offered for navigation.++## Return value++A `CanvasKeyframeToggle` object with the following properties.++### keyframable++Whether a keyframe can be added: the field type supports interpolation and the value is not computed in code.++### hasKeyframe++Whether the prop has a keyframe at `frame`.++### previousFrame++The composition frame of the closest keyframe before `frame`, or `null`.++### nextFrame++The composition frame of the closest keyframe after `frame`, or `null`.++### change++A `CanvasKeyframeChange`, or `null` when neither adding nor removing is possible. When `hasKeyframe` is `true`, its `operation` is `{type: 'remove', frame, valueWhenLastKeyframeDeleted: null}`; otherwise `{type: 'add', frame, value}` with the value the prop has at the frame: the interpolated value of a keyframed prop, the code value of a static prop, or the schema default. Font weights are normalized to numbers so they can be interpolated.++`frame` in the operation is in the frame clock of the interpolation. Persist the change with [`updateNodeKeyframes()`](/docs/codemods/update-node-keyframes): a `CanvasKeyframeChange` carries `nodePathInfo` to resolve the node, the `key`, the `schema` and the `operation`, which matches the `updates` entries of the codemod.++```tsx twoslash title="Persisting a change"+// @moduleResolution: bundler+import type {CanvasKeyframeChange} from '@remotion/canvas';+import {updateNodeKeyframes, type CodemodProject} from '@remotion/codemods';+declare const project: CodemodProject;+// ---cut---+export const persist = (change: CanvasKeyframeChange) => {+ const {absolutePath, nodePath} = change.nodePathInfo.sequenceSubscriptionKey;+ return updateNodeKeyframes({+ project,+ node: {filePath: absolutePath, nodePath},+ updates: [{key: change.key, operation: change.operation}],+ schema: change.schema,+ });+};+```++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio="" hideServers />++## See also++- [`getCanvasKeyframes()`](/docs/canvas/get-canvas-keyframes)+- [`getCanvasPropValueAtFrame()`](/docs/canvas/get-canvas-prop-value-at-frame)+- [`updateNodeKeyframes()`](/docs/codemods/update-node-keyframes)diff --git a/packages/docs/docs/canvas/get-canvas-keyframes.mdx b/packages/docs/docs/canvas/get-canvas-keyframes.mdxnew file mode 100644index 0000000000..a1d4d0275b--- /dev/null+++ b/packages/docs/docs/canvas/get-canvas-keyframes.mdx@@ -0,0 +1,68 @@+---+image: /generated/articles-docs-canvas-get-canvas-keyframes.png+title: getCanvasKeyframes()+crumb: '@remotion/canvas'+---++# getCanvasKeyframes()<AvailableFrom v="4.0.530" />++Places the keyframes of a prop on the composition timeline. Use it to draw keyframe markers in a timeline row.++:::warning++_Experimental API_: This package is not stable. Its public API may change without a major version bump.++:::++```tsx twoslash title="KeyframeRow.tsx"+// @moduleResolution: bundler+import {getCanvasKeyframes, type TimelineTrackData} from '@remotion/canvas';+import type {CanUpdateSequencePropStatus} from 'remotion';+declare const track: TimelineTrackData;+declare const propStatus: CanUpdateSequencePropStatus;+declare const pixelsPerFrame: number;+// ---cut---+export const KeyframeRow = () => {+ const keyframes = getCanvasKeyframes({track, propStatus});+ return (+ <div style={{position: 'relative'}}>+ {keyframes.map((keyframe) => (+ <div+ key={keyframe.frame}+ style={{position: 'absolute', left: keyframe.frame * pixelsPerFrame}}+ >+ ◆+ </div>+ ))}+ </div>+ );+};+```++A prop animated with `interpolate()` stores its keyframes in the frame clock of that expression. A sequence that starts later than frame 0, a nested `<Sequence>` or a `playbackRate` shift and stretch those frames on the composition timeline. This function applies the timing of the track so the markers line up with the playhead.++## Parameters++An object with the following properties:++### track++The `TimelineTrackData` of the sequence from [`controller.timeline`](/docs/canvas/create-canvas-controller#timeline). Only `keyframeDisplayOffset` and `keyframePlaybackRate` are read.++### propStatus++How the prop is written in the source, as the `props` of [`getNodeProps()`](/docs/codemods/get-node-props) report it. `null` or a status other than `'keyframed'` yields no keyframes.++## Return value++An array of `CanvasKeyframe` objects with `frame` in composition frames and `value`, ordered like the keyframes of the source. Frames may be fractional or lie outside the composition.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio="" hideServers />++## See also++- [`getCanvasKeyframeToggle()`](/docs/canvas/get-canvas-keyframe-toggle)+- [`startCanvasKeyframeDrag()`](/docs/canvas/start-canvas-keyframe-drag)+- [`getCanvasKeyframeSourceFrame()`](/docs/canvas/get-canvas-keyframe-source-frame)diff --git a/packages/docs/docs/canvas/get-canvas-prop-value-at-frame.mdx b/packages/docs/docs/canvas/get-canvas-prop-value-at-frame.mdxnew file mode 100644index 0000000000..85134e402d--- /dev/null+++ b/packages/docs/docs/canvas/get-canvas-prop-value-at-frame.mdx@@ -0,0 +1,75 @@+---+image: /generated/articles-docs-canvas-get-canvas-prop-value-at-frame.png+title: getCanvasPropValueAtFrame()+crumb: '@remotion/canvas'+---++# getCanvasPropValueAtFrame()<AvailableFrom v="4.0.530" />++Reads the value a prop has at a composition frame according to the source code. Use it to show the value of an animated prop at the playhead in an inspector.++:::warning++_Experimental API_: This package is not stable. Its public API may change without a major version bump.++:::++```tsx twoslash title="OpacityField.tsx"+// @moduleResolution: bundler+import {getCanvasPropValueAtFrame, type TimelineTrackData} from '@remotion/canvas';+import type {CanUpdateSequencePropStatus, InteractivitySchema} from 'remotion';+declare const track: TimelineTrackData;+declare const schema: InteractivitySchema;+declare const propStatus: CanUpdateSequencePropStatus;+declare const playhead: number;+// ---cut---+export const OpacityField = () => {+ const value = getCanvasPropValueAtFrame({+ track,+ schema,+ key: 'style.opacity',+ propStatus,+ frame: playhead,+ });+ return <input type="number" value={typeof value === 'number' ? value : ''} readOnly />;+};+```++## Parameters++An object with the following properties:++### track++The `TimelineTrackData` of the sequence from [`controller.timeline`](/docs/canvas/create-canvas-controller#timeline). Only `keyframeDisplayOffset` and `keyframePlaybackRate` are read.++### schema++The interactivity schema of the element, from [`track.sequence.controls`](/docs/canvas/create-canvas-controller#sequencecontrols). It provides the default of an unset prop.++### key++The schema key of the prop in dot notation, for example `'style.opacity'`.++### propStatus++How the prop is written in the source, as the `props` of [`getNodeProps()`](/docs/codemods/get-node-props) report it.++### frame++The composition frame at which to read the value.++## Return value++The interpolated value of a `'keyframed'` prop at the frame, the code value of a `'static'` prop, or the schema default when the prop is not set. `null` for a `'computed'` prop or when no value is known.++The value reflects the source, not an active override from [`controller.overrides`](/docs/canvas/create-canvas-controller#overrides).++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio="" hideServers />++## See also++- [`getCanvasKeyframeToggle()`](/docs/canvas/get-canvas-keyframe-toggle)+- [`getCanvasKeyframeSourceFrame()`](/docs/canvas/get-canvas-keyframe-source-frame)diff --git a/packages/docs/docs/canvas/index.mdx b/packages/docs/docs/canvas/index.mdxindex 407b3fd1e3..1a62daa208 100644--- a/packages/docs/docs/canvas/index.mdx+++ b/packages/docs/docs/canvas/index.mdx@@ -134,6 +134,12 @@ While a value is being dragged, [`controller.overrides`](/docs/canvas/create-canPass [`onSequencePropsChange`](/docs/canvas/canvas#onsequencepropschange) to `<Canvas>` to let users move elements by dragging their outlines or pressing the arrow keys. The Canvas previews the movement itself and reports the final `style.translate` values to the callback. With [`getSequencePropStatuses`](/docs/canvas/canvas#getsequencepropstatuses), it respects how the source is written: computed values cannot be moved and keyframed values receive a keyframe.+## Keyframes<AvailableFrom v="4.0.530" />++Props animated with `interpolate()` are reported as `keyframed` by [`getNodeProps()`](/docs/codemods/get-node-props). The package converts between the frame clock of the interpolation and the composition timeline, so a timeline can show and edit those keyframes like the Remotion Studio does.++[`getCanvasKeyframes()`](/docs/canvas/get-canvas-keyframes) places the keyframes of a prop on the timeline. [`getCanvasKeyframeToggle()`](/docs/canvas/get-canvas-keyframe-toggle) describes a keyframe button at the playhead and returns the change that adds or removes a keyframe there, while [`getCanvasPropValueAtFrame()`](/docs/canvas/get-canvas-prop-value-at-frame) reads the animated value for an inspector. [`startCanvasKeyframeDrag()`](/docs/canvas/start-canvas-keyframe-drag) moves keyframes with the pointer, previewing the result through `controller.overrides`. Every edit is a `CanvasKeyframeChange` whose `operation` you pass to [`updateNodeKeyframes()`](/docs/codemods/update-node-keyframes).+## APIsimport {TableOfContents} from './table-of-contents';diff --git a/packages/docs/docs/canvas/start-canvas-keyframe-drag.mdx b/packages/docs/docs/canvas/start-canvas-keyframe-drag.mdxnew file mode 100644index 0000000000..9cd6734d3c--- /dev/null+++ b/packages/docs/docs/canvas/start-canvas-keyframe-drag.mdx@@ -0,0 +1,155 @@+---+image: /generated/articles-docs-canvas-start-canvas-keyframe-drag.png+title: startCanvasKeyframeDrag()+crumb: '@remotion/canvas'+---++# startCanvasKeyframeDrag()<AvailableFrom v="4.0.530" />++Moves keyframes along the timeline with the pointer. Call it from the `pointerdown` handler of a keyframe marker. While the pointer moves, the new positions are previewed on the canvas through [`controller.overrides`](/docs/canvas/create-canvas-controller#overrides); when it is released, the resulting moves are reported for you to persist.++:::warning++_Experimental API_: This package is not stable. Its public API may change without a major version bump.++:::++```tsx twoslash title="KeyframeMarker.tsx"+// @moduleResolution: bundler+import {+ startCanvasKeyframeDrag,+ type CanvasController,+ type CanvasKeyframeChange,+ type CanvasKeyframeDragTarget,+} from '@remotion/canvas';+declare const controller: CanvasController;+declare const target: CanvasKeyframeDragTarget;+declare const pixelsPerFrame: number;+declare const durationInFrames: number;+declare const persist: (changes: readonly CanvasKeyframeChange[]) => void;+// ---cut---+export const KeyframeMarker = () => {+ return (+ <button+ style={{position: 'absolute', left: target.frame * pixelsPerFrame}}+ onPointerDown={(event) => {+ startCanvasKeyframeDrag({+ event,+ captureTarget: event.currentTarget,+ targets: [target],+ pixelsPerFrame,+ durationInFrames,+ overrides: controller.overrides,+ onDragStart: null,+ onDragMove: null,+ onDragEnd: ({changes}) => {+ if (changes.length > 0) {+ persist(changes);+ }+ },+ });+ }}+ >+ ◆+ </button>+ );+};+```++The movement starts after the pointer has travelled 3 pixels and is rounded to whole composition frames. The keyframes stay inside the composition. Dropping a keyframe onto another keyframe of the same prop replaces that keyframe, like in the Remotion Studio.++## Parameters++An object with the following properties:++### event++The `PointerEvent` that starts the gesture. Its `button`, `pointerId` and `clientX` are read.++### captureTarget++The element that captures the pointer for the duration of the gesture, usually the marker that was pressed.++### targets++The keyframes to move, as `CanvasKeyframeDragTarget` objects. Dragging one marker of a multi-selection should pass every selected keyframe.++#### nodePathInfo++The `SequenceNodePathInfo` of the sequence the keyframe belongs to. The overrides are set on it.++#### track++The `TimelineTrackData` of the sequence, for its `keyframeDisplayOffset` and `keyframePlaybackRate`.++#### schema++The interactivity schema of the element, passed through to the reported changes.++#### key++The schema key of the keyframed prop, for example `'style.opacity'`.++#### propStatus++The `'keyframed'` prop status of the prop, as the `props` of [`getNodeProps()`](/docs/codemods/get-node-props) report it.++#### frame++The composition frame of the keyframe, as returned by [`getCanvasKeyframes()`](/docs/canvas/get-canvas-keyframes). Targets that do not correspond to a keyframe of the prop are ignored.++### pixelsPerFrame++The width of one composition frame on your timeline.++### durationInFrames++The duration of the composition, which bounds the movement.++### overrides++The [`overrides`](/docs/canvas/create-canvas-controller#overrides) of the `CanvasController` that previews the composition.++### onDragStart++Called once the pointer has moved past the drag threshold, or `null`.++### onDragMove++Called with the previewed movement in composition frames whenever it changes, or `null`. Use it to draw the dragged markers at their new positions. The value is `0` while the move cannot be applied.++### onDragEnd++Called when the pointer is released or the gesture is cancelled, with a `CanvasKeyframeDragEnd` object.++#### changes++One `CanvasKeyframeChange` per prop whose keyframes moved, with a `{type: 'move', moves}` operation in the frame clock of the interpolation. Persist them with [`updateNodeKeyframes()`](/docs/codemods/update-node-keyframes) and clear the overrides of each `nodePathInfo` once the update has been applied; until then, the canvas keeps showing the moved keyframes.++The array is empty when the pointer did not move past the threshold, returned to the start, the move cannot be applied or the gesture was cancelled. The overrides are cleared in that case.++#### delta++How far the keyframes moved, in composition frames. Add it to the frames of your selected keyframes to keep them selected.++#### dragged++Whether the pointer moved past the drag threshold. A click without a drag has `dragged: false`; select the marker in that case.++#### released++`false` when the gesture was cancelled, for example because the window lost focus.++## Return value++A function that cancels the gesture.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio="" hideServers />++## See also++- [`getCanvasKeyframes()`](/docs/canvas/get-canvas-keyframes)+- [`getCanvasKeyframeToggle()`](/docs/canvas/get-canvas-keyframe-toggle)+- [`createCanvasController()`](/docs/canvas/create-canvas-controller)diff --git a/packages/docs/docs/canvas/table-of-contents.tsx b/packages/docs/docs/canvas/table-of-contents.tsxindex 383cfaf1b2..b6249b27cd 100644--- a/packages/docs/docs/canvas/table-of-contents.tsx+++ b/packages/docs/docs/canvas/table-of-contents.tsx@@ -50,6 +50,30 @@ export const TableOfContents: React.FC = () => {<strong>getCanvasSelectionItemKey()</strong><div>Compare selection items by identity</div></TOCItem>+ <TOCItem link="/docs/canvas/get-canvas-keyframes">+ <strong>getCanvasKeyframes()</strong>+ <div>Place the keyframes of a prop on the timeline</div>+ </TOCItem>+ <TOCItem link="/docs/canvas/get-canvas-keyframe-toggle">+ <strong>getCanvasKeyframeToggle()</strong>+ <div>Add, remove and navigate keyframes at a frame</div>+ </TOCItem>+ <TOCItem link="/docs/canvas/start-canvas-keyframe-drag">+ <strong>startCanvasKeyframeDrag()</strong>+ <div>Move keyframes along the timeline with the pointer</div>+ </TOCItem>+ <TOCItem link="/docs/canvas/get-canvas-prop-value-at-frame">+ <strong>getCanvasPropValueAtFrame()</strong>+ <div>Read the value of a prop at a frame from the source</div>+ </TOCItem>+ <TOCItem link="/docs/canvas/get-canvas-keyframe-source-frame">+ <strong>getCanvasKeyframeSourceFrame()</strong>+ <div>Convert a composition frame to the interpolation clock</div>+ </TOCItem>+ <TOCItem link="/docs/canvas/get-canvas-keyframe-display-frame">+ <strong>getCanvasKeyframeDisplayFrame()</strong>+ <div>Convert an interpolation frame to the composition</div>+ </TOCItem></Grid></div>);diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex a899feaeb3..3d1f504b42 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -2067,6 +2067,12 @@ const sidebars: SidebarsConfig = {'canvas/get-canvas-sequence-node-path-info','canvas/get-canvas-sequence-source-location','canvas/get-canvas-selection-item-key',+ 'canvas/get-canvas-keyframes',+ 'canvas/get-canvas-keyframe-toggle',+ 'canvas/start-canvas-keyframe-drag',+ 'canvas/get-canvas-prop-value-at-frame',+ 'canvas/get-canvas-keyframe-source-frame',+ 'canvas/get-canvas-keyframe-display-frame',],},],diff --git a/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsx b/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsxindex 990970a9d0..17ac4a92b0 100644--- a/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsx+++ b/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsx@@ -1,4 +1,4 @@-import {isSchemaFieldKeyframable} from '@remotion/studio-shared';+import {CanvasInternals} from '@remotion/canvas';import React, {useCallback, useContext, useMemo} from 'react';import type {CanUpdateSequencePropStatus,@@ -34,18 +34,12 @@ import {type DeleteEffectKeyframeChange,type DeleteSequenceKeyframeChange,} from './call-delete-keyframe';-import {- getNextKeyframeDisplayFrame,- getPreviousKeyframeDisplayFrame,- hasKeyframeAtSourceFrame,-} from './get-keyframe-navigation';import {getKeyframePlaybackRate,getKeyframeDisplayOffset,getKeyframeSourceFrame,getTimelineKeyframes,} from './get-timeline-keyframes';-import {normalizeFontWeightForKeyframe} from './normalize-font-weight-for-keyframe';import {ensureFrameIsInViewport} from './timeline-scroll-logic';import {TimelineKeyframeDiamondIcon} from './TimelineKeyframeDiamondIcon';import {useTimelineKeyframeTracks} from './TimelineKeyframeTracksContext';@@ -56,6 +50,14 @@ import {type TimelineSelection,} from './TimelineSelection';+const {+ getCanvasKeyframeValueToAdd,+ getNextKeyframeDisplayFrame,+ getPreviousKeyframeDisplayFrame,+ hasKeyframeAtSourceFrame,+ isCanvasKeyframablePropStatus,+} = CanvasInternals;+const NAV_BUTTON_SIZE = 14;const INSPECTOR_NAV_BUTTON_WIDTH = NAV_BUTTON_SIZE / 2;const INSPECTOR_PREVIOUS_BUTTON_EXTRA_GAP = 1;@@ -365,21 +367,21 @@ const getAddChange = (target: KeyframeControlTarget,): AddSequenceKeyframeChange | AddEffectKeyframeChange | null => {if (- target.propStatus.status === 'computed' ||- (target.propStatus.status === 'static' &&- target.propStatus.canKeyframe === false) ||- !isSchemaFieldKeyframable({schema: target.schema, key: target.fieldKey}) ||+ !isCanvasKeyframablePropStatus({+ propStatus: target.propStatus,+ schema: target.schema,+ key: target.fieldKey,+ }) ||hasTargetKeyframeAtCurrentFrame(target)) {return null;}- const value = getCurrentKeyframeValue({+ const value = getCanvasKeyframeValueToAdd({propStatus: target.propStatus,- jsxFrame:- (target.sourceFrame +- (target.propStatus.keyframeDisplayOffsetAdjustment ?? 0)) /- (target.propStatus.keyframePlaybackRateAdjustment ?? 1),+ schema: target.schema,+ key: target.fieldKey,+ sourceFrame: target.sourceFrame,defaultValue: target.defaultValue,dragOverrideValue: target.dragOverrideValue,});@@ -387,21 +389,12 @@ const getAddChange = (return null;}- const fieldSchema = target.schema[target.fieldKey];- const normalizedValue =- fieldSchema?.type === 'font-weight'- ? normalizeFontWeightForKeyframe(value)- : value;- if (normalizedValue === null) {- return null;- }-const change = {fileName: target.fileName,nodePath: target.nodePath,fieldKey: target.fieldKey,sourceFrame: target.sourceFrame,- value: normalizedValue,+ value,schema: target.schema,};@@ -447,40 +440,6 @@ const hasEffectIndex = <T extends object>(return 'effectIndex' in change;};-function getCurrentKeyframeValue({- propStatus,- jsxFrame,- defaultValue,- dragOverrideValue,-}: {- propStatus: CanUpdateSequencePropStatus;- jsxFrame: number;- defaultValue: unknown;- dragOverrideValue: DragOverrideValue | undefined;-}): unknown | null {- if (isKeyframedStatus(propStatus)) {- return Internals.getEffectiveVisualModeValue({- propStatus,- dragOverrideValue,- frame: jsxFrame,- defaultValue,- shouldResortToDefaultValueIfUndefined: true,- });- }-- if (propStatus.status === 'static') {- return Internals.getEffectiveVisualModeValue({- propStatus,- dragOverrideValue,- frame: jsxFrame,- defaultValue,- shouldResortToDefaultValueIfUndefined: true,- });- }-- return null;-}-export const shouldShowTimelineKeyframeControls = ({propStatus,selected,@@ -638,13 +597,11 @@ export const TimelineKeyframeControls: React.FC<{selected: propertySelected,});- const keyframable =- !(propStatus.status === 'static' && propStatus.canKeyframe === false) &&- isSchemaFieldKeyframable({- schema,- key: fieldKey,- });- const canAddKeyframe = keyframable;+ const canAddKeyframe = isCanvasKeyframablePropStatus({+ propStatus,+ schema,+ key: fieldKey,+ });const canToggleKeyframe =canUseKeyframeOperations() &&propStatus.status !== 'computed' &&diff --git a/packages/studio/src/components/Timeline/get-bounded-keyframe-drag-delta.ts b/packages/studio/src/components/Timeline/get-bounded-keyframe-drag-delta.tsdeleted file mode 100644index 963dfc1df3..0000000000--- a/packages/studio/src/components/Timeline/get-bounded-keyframe-drag-delta.ts+++ /dev/null@@ -1,24 +0,0 @@-export type TimelineKeyframeDragBoundsTarget = {- readonly displayFrame: number;-};--export const getBoundedKeyframeDragDelta = ({- delta,- durationInFrames,- targets,-}: {- readonly delta: number;- readonly durationInFrames: number;- readonly targets: readonly TimelineKeyframeDragBoundsTarget[];-}) => {- if (targets.length === 0 || durationInFrames <= 0) {- return 0;- }-- const minDelta = Math.max(...targets.map((target) => -target.displayFrame));- const maxDelta = Math.min(- ...targets.map((target) => durationInFrames - 1 - target.displayFrame),- );-- return Math.min(Math.max(delta, minDelta), maxDelta);-};diff --git a/packages/studio/src/components/Timeline/normalize-font-weight-for-keyframe.ts b/packages/studio/src/components/Timeline/normalize-font-weight-for-keyframe.tsdeleted file mode 100644index bad05e30c9..0000000000--- a/packages/studio/src/components/Timeline/normalize-font-weight-for-keyframe.ts+++ /dev/null@@ -1,21 +0,0 @@-export const normalizeFontWeightForKeyframe = (- value: unknown,-): number | null => {- if (value === 'normal') {- return 400;- }-- if (value === 'bold') {- return 700;- }-- if (typeof value === 'number') {- return Number.isFinite(value) ? value : null;- }-- if (typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value)) {- return Number(value);- }-- return null;-};diff --git a/packages/studio/src/components/Timeline/use-timeline-keyframe-drag.ts b/packages/studio/src/components/Timeline/use-timeline-keyframe-drag.tsindex cf63be5a00..7290e6584f 100644--- a/packages/studio/src/components/Timeline/use-timeline-keyframe-drag.ts+++ b/packages/studio/src/components/Timeline/use-timeline-keyframe-drag.ts@@ -1,12 +1,8 @@-import {- canMoveKeyframesWithoutCollisions,- moveKeyframesInPropStatus,-} from '@remotion/studio-shared';+import {CanvasInternals} from '@remotion/canvas';import type React from 'react';import {useCallback, useContext} from 'react';import type {CanUpdateSequencePropStatusKeyframed,- DragOverrideValue,InteractivitySchema,OverrideIdToNodePaths,PropStatuses,@@ -23,12 +19,9 @@ import {import {TIMELINE_PADDING} from '../../helpers/timeline-layout';import {callMoveKeyframes} from './call-move-keyframe';import {findTrackForNodePathInfo} from './find-track-for-node-path-info';-import {getBoundedKeyframeDragDelta} from './get-bounded-keyframe-drag-delta';import {- getKeyframePlaybackRate,getKeyframeDisplayOffset,getKeyframeSourceFrame,- resolveKeyframeSourceFrame,} from './get-timeline-keyframes';import {parseKeyframeFieldFromNodePath} from './parse-keyframe-field-from-node-path';import {@@ -44,6 +37,13 @@ import {} from './TimelineSelection';import {TimelineWidthContext} from './TimelineWidthProvider';+const {+ canMoveCanvasKeyframes,+ getBoundedKeyframeDragDelta,+ getCanvasKeyframeMove,+ getMovedCanvasKeyframeOverride,+} = CanvasInternals;+type TimelineKeyframeDragTargetBase = {readonly displayFrame: number;readonly fieldKey: string;@@ -355,27 +355,6 @@ const groupTargets = (targets: readonly TimelineKeyframeDragTarget[]) => {return [...groups.values()];};-const getMoveForTarget = (- target: TimelineKeyframeDragTarget,- delta: number,-) => ({- fromFrame: target.sourceFrame,- toFrame: resolveKeyframeSourceFrame(- target.sourceFrame +- delta *- getKeyframePlaybackRate(target.propStatus, target.keyframePlaybackRate),- target.propStatus,- ),-});--const getMovesForGroup = ({- group,- delta,-}: {- readonly group: readonly TimelineKeyframeDragTarget[];- readonly delta: number;-}) => group.map((target) => getMoveForTarget(target, delta));-const canMoveTimelineKeyframeDragTargets = ({targets,delta,@@ -383,43 +362,9 @@ const canMoveTimelineKeyframeDragTargets = ({readonly targets: readonly TimelineKeyframeDragTarget[];readonly delta: number;}) =>- groupTargets(targets).every((group) => {- const [first] = group;- if (!first) {- return true;- }-- return canMoveKeyframesWithoutCollisions({- status: first.propStatus,- moves: getMovesForGroup({group, delta}),- });- });--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 movedStatus = moveKeyframesInPropStatus({- status: first.propStatus,- moves: getMovesForGroup({group, delta}),- });- if (movedStatus.status !== 'keyframed') {- throw new Error('Expected keyframed status');- }-- return {- type: 'keyframed',- status: movedStatus,- };-};+ groupTargets(targets).every((group) =>+ canMoveCanvasKeyframes({targets: group, delta}),+ );const applyDragOverrides = ({delta,@@ -442,7 +387,7 @@ const applyDragOverrides = ({continue;}- const override = makeMovedKeyframedDragOverride({group, delta});+ const override = getMovedCanvasKeyframeOverride({targets: group, delta});if (first.type === 'sequence') {setDragOverrides(first.nodePath, first.fieldKey, override);continue;@@ -735,7 +680,7 @@ export const useTimelineKeyframeDrag = ({fileName: target.fileName,nodePath: target.nodePath,fieldKey: target.fieldKey,- ...getMoveForTarget(target, lastDelta),+ ...getCanvasKeyframeMove(target, lastDelta),schema: target.schema,})),effectKeyframes: targets@@ -751,7 +696,7 @@ export const useTimelineKeyframeDrag = ({nodePath: target.nodePath,effectIndex: target.effectIndex,fieldKey: target.fieldKey,- ...getMoveForTarget(target, lastDelta),+ ...getCanvasKeyframeMove(target, lastDelta),schema: target.schema,})),setPropStatuses,@@ -1011,7 +956,7 @@ export const useTimelineEasingKeyframeDrag = ({fileName: target.fileName,nodePath: target.nodePath,fieldKey: target.fieldKey,- ...getMoveForTarget(target, lastDelta),+ ...getCanvasKeyframeMove(target, lastDelta),schema: target.schema,})),effectKeyframes: targets@@ -1027,7 +972,7 @@ export const useTimelineEasingKeyframeDrag = ({nodePath: target.nodePath,effectIndex: target.effectIndex,fieldKey: target.fieldKey,- ...getMoveForTarget(target, lastDelta),+ ...getCanvasKeyframeMove(target, lastDelta),schema: target.schema,})),setPropStatuses,diff --git a/packages/studio/src/test/timeline-keyframe-navigation.test.ts b/packages/studio/src/test/timeline-keyframe-navigation.test.tsindex 912aa287b7..0dbb244613 100644--- a/packages/studio/src/test/timeline-keyframe-navigation.test.ts+++ b/packages/studio/src/test/timeline-keyframe-navigation.test.ts@@ -1,75 +1,10 @@import {expect, test} from 'bun:test';import type {CanUpdateSequencePropStatus} from 'remotion';-import {- getNextKeyframeDisplayFrame,- getPreviousKeyframeDisplayFrame,- hasKeyframeAtSourceFrame,-} from '../components/Timeline/get-keyframe-navigation';import {shouldShowTimelineKeyframeControls,shouldShowTimelineKeyframeNavigation,} from '../components/Timeline/TimelineKeyframeControls';-const keyframes = [{frame: 10}, {frame: 30}, {frame: 90}];-const durationInFrames = 100;--test('getPreviousKeyframeDisplayFrame returns the nearest earlier keyframe', () => {- 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, 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', () => {- expect(hasKeyframeAtSourceFrame(keyframes, 10)).toBe(true);- expect(hasKeyframeAtSourceFrame(keyframes, 11)).toBe(false);-});-test('timeline keyframe controls visibility follows property selection or keyframed status', () => {const staticStatus: CanUpdateSequencePropStatus = {status: 'static',diff --git a/packages/studio/src/test/timeline-keyframes.test.ts b/packages/studio/src/test/timeline-keyframes.test.tsindex bed128f372..b381a27921 100644--- a/packages/studio/src/test/timeline-keyframes.test.ts+++ b/packages/studio/src/test/timeline-keyframes.test.ts@@ -7,7 +7,6 @@ import type {import {Internals, type PropStatuses} from 'remotion';import {getInspectorKeyframeSourceFrame} from '../components/InspectorPanel/keyframe-inspector-frame';import {findTrackForNodePathInfo} from '../components/Timeline/find-track-for-node-path-info';-import {getBoundedKeyframeDragDelta} from '../components/Timeline/get-bounded-keyframe-drag-delta';import {getNodeKeyframes} from '../components/Timeline/get-node-keyframes';import {getTimelineEasingSegments} from '../components/Timeline/get-timeline-easing-segments';import {@@ -500,54 +499,6 @@ test('timeline easing segments connect adjacent display keyframes', () => {]);});-test('bounded keyframe drag delta stays inside the composition timeline', () => {- expect(- getBoundedKeyframeDragDelta({- targets: [{displayFrame: 10}],- delta: -20,- durationInFrames: 100,- }),- ).toBe(-10);-- expect(- getBoundedKeyframeDragDelta({- targets: [{displayFrame: 90}],- delta: 20,- durationInFrames: 100,- }),- ).toBe(9);-});--test('bounded keyframe drag delta allows negative source frames when display frames stay in range', () => {- expect(- getBoundedKeyframeDragDelta({- targets: [{displayFrame: 30}],- delta: -30,- durationInFrames: 100,- }),- ).toBe(-30);-});--test('bounded keyframe drag delta clamps multi-selection at the first timeline edge', () => {- const targets = [{displayFrame: 20}, {displayFrame: 95}];-- expect(- getBoundedKeyframeDragDelta({- targets,- delta: -30,- durationInFrames: 100,- }),- ).toBe(-20);-- expect(- getBoundedKeyframeDragDelta({- targets,- delta: 10,- durationInFrames: 100,- }),- ).toBe(4);-});-test('getNodeKeyframes shows a temporary sequence keyframe from drag overrides', () => {const nodePath = makeNodePath('sequence');diff --git a/packages/template-vibe-code/README.md b/packages/template-vibe-code/README.mdindex 114b6008e6..7709c44ca1 100644--- a/packages/template-vibe-code/README.md+++ b/packages/template-vibe-code/README.md@@ -5,7 +5,8 @@ A Remotion template that turns the browser into a motion graphics editor: write- **Live compilation** – the project is compiled in a Web Worker with [`@remotion/browser-bundler`](https://www.remotion.dev/docs/browser-bundler) and hot-swapped with Fast Refresh, so component state survives edits.- **Canvas** – [`@remotion/canvas`](https://www.remotion.dev/docs/canvas) renders the composition with selection outlines. Click a layer on the canvas or in the timeline to select it, drag it to move it (it snaps to the edges and center of the composition, Shift locks the axis, ⌘ disables snapping) or nudge it with the arrow keys. Switch to “Interact” mode to use the composition’s own buttons and inputs.- **Timeline** – every mounted sequence shows up as a track. Drag a track to change its `from`, drag its edges to trim `durationInFrames`, split it at the playhead, duplicate, reorder, wrap and delete. In/out points, zoomable ruler, scrubbing.-- **Inspector** – edits props of the selected element directly in the source using [`@remotion/codemods`](https://www.remotion.dev/docs/codemods): position, scale, rotation, opacity, colors, typography, text content, timing and more. Values that are animated with `interpolate()` or computed in code are shown as such. Composition metadata (size, fps, duration) and `defaultProps` are editable too.+- **Keyframes** – props animated with `interpolate()` get a keyframe row under their track. Drag keyframes to retime them, click to select them (Shift and ⌘ extend the selection), double-click to jump to them, press ⌫ to delete them. In the inspector, a diamond next to each animatable prop adds or removes a keyframe at the playhead and the arrows jump to the neighboring keyframes.+- **Inspector** – edits props of the selected element directly in the source using [`@remotion/codemods`](https://www.remotion.dev/docs/codemods): position, scale, rotation, opacity, colors, typography, text content, timing and more. Animated props show their value at the playhead; editing one writes a keyframe there. Values computed in code are shown as such. Composition metadata (size, fps, duration) and `defaultProps` are editable too.- **Code editor** – Monaco with multiple files, tabs, compiler diagnostics and “Reveal in code” from any layer.- **Render** – export MP4/WebM videos and PNG/JPEG stills in the browser with [`@remotion/web-renderer`](https://www.remotion.dev/docs/web-renderer).- **Studio-like shortcuts** – Space, ←/→, J/K/L, I/O/X, ⌘Z, ⌘D, ⌘⇧D, ⌫ and more. Press `?` for the full list.@@ -68,6 +69,10 @@ Dragging a value in the inspector or a track in the timeline does not rewrite thMoving an outline on the canvas works the same way, but the Canvas owns the gesture: it previews `style.translate` while dragging and reports the final values through the [`onSequencePropsChange`](https://www.remotion.dev/docs/canvas/canvas#onsequencepropschange) prop. The editor writes them with `updateMultipleNodeProps()` in one undoable step and releases the previews once the new bundle runs. Before a move starts, the Canvas asks the editor through [`getSequencePropStatuses`](https://www.remotion.dev/docs/canvas/canvas#getsequencepropstatuses) how the position is written: a position animated with `interpolate()` gets a keyframe at the playhead via `updateNodeKeyframes()`, and a position computed in code cannot be moved.+### Keyframes++The keyframe rows of the timeline read the `interpolate()` calls of each layer with `getNodeProps()` and place them on the composition timeline with [`getCanvasKeyframes()`](https://www.remotion.dev/docs/canvas/get-canvas-keyframes), which accounts for nested sequences and playback rates. Dragging a keyframe runs [`startCanvasKeyframeDrag()`](https://www.remotion.dev/docs/canvas/start-canvas-keyframe-drag) from `@remotion/canvas`: it previews the moved keyframes through `controller.overrides`, keeps them inside the composition, and reports the move when the pointer is released. The diamond buttons of the inspector are described by [`getCanvasKeyframeToggle()`](https://www.remotion.dev/docs/canvas/get-canvas-keyframe-toggle). Every keyframe edit is a `CanvasKeyframeChange`, which the editor passes to `updateNodeKeyframes()`.+## Commands**Start the editor**diff --git a/packages/template-vibe-code/src/editor/Editor.tsx b/packages/template-vibe-code/src/editor/Editor.tsxindex c57c89b9a0..e62fee4349 100644--- a/packages/template-vibe-code/src/editor/Editor.tsx+++ b/packages/template-vibe-code/src/editor/Editor.tsx@@ -26,6 +26,7 @@ import { useLayers } from "./hooks/use-layers";import { usePlaybackStore } from "./hooks/use-playback";import { usePreviewHost } from "./hooks/use-preview-host";import { findCompositionFile, getCompositions } from "./model/compositions";+import { getKeyframedProps } from "./model/keyframes";import { getSequencePropStatuses } from "./model/layers";import { toCodemodProject, type ProjectFiles } from "./model/project";import { EditorContext, type EditorContextValue } from "./state/editor-context";@@ -234,12 +235,36 @@ export const Editor: React.FC<{const compositionHeight =composition?.height ?? activeComposition?.height ?? 1080;+ // The animated props of the layers, for the keyframe rows of the timeline.+ const keyframedProps = useMemo(+ () =>+ getKeyframedProps({+ layers,+ project,+ videoConfig: {+ width: compositionWidth,+ height: compositionHeight,+ fps: compositionFps,+ durationInFrames: compositionDurationInFrames,+ },+ }),+ [+ compositionDurationInFrames,+ compositionFps,+ compositionHeight,+ compositionWidth,+ layers,+ project,+ ],+ );+const actions = useEditorActions({context: {state,entryPoint,host,layers,+ keyframedProps,compositions,compositionFile,activeComposition,@@ -321,6 +346,7 @@ export const Editor: React.FC<{hostError,playback,layers,+ keyframedProps,project,compositions,compositionFile,diff --git a/packages/template-vibe-code/src/editor/components/Inspector/LayerInspector.tsx b/packages/template-vibe-code/src/editor/components/Inspector/LayerInspector.tsxindex c538c84d54..5fb7271fc9 100644--- a/packages/template-vibe-code/src/editor/components/Inspector/LayerInspector.tsx+++ b/packages/template-vibe-code/src/editor/components/Inspector/LayerInspector.tsx@@ -1,9 +1,20 @@"use client";+import {+ getCanvasKeyframeSourceFrame,+ getCanvasKeyframeToggle,+ getCanvasPropValueAtFrame,+} from "@remotion/canvas";import { getNodeProps, type SequencePropUpdate } from "@remotion/codemods";-import { RotateCcwIcon } from "lucide-react";+import { ChevronLeftIcon, ChevronRightIcon, RotateCcwIcon } from "lucide-react";import React, { useMemo } from "react";+import type {+ CanUpdateSequencePropStatus,+ InteractivitySchema,+} from "remotion";import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import { usePlaybackFrame } from "../../hooks/use-playback";import { getFileName } from "../../model/project";import {getLayerLabel,@@ -28,6 +39,7 @@ import {serializeTranslate,} from "../../model/values";import { useEditor } from "../../state/editor-context";+import { KeyframeDiamond } from "../KeyframeDiamond";import { LayerActionBar } from "./LayerActions";import {BooleanField,@@ -42,6 +54,90 @@ import {type VisibleField = ReturnType<typeof getVisibleFields>[number];type PropStatus = ReturnType<typeof getNodeProps>["props"][string];+const keyframeNavButtonClass =+ "text-muted-foreground-dim hover:text-foreground disabled:hover:text-muted-foreground-dim flex h-5 w-2 items-center justify-center disabled:opacity-30";++/**+ * Previous / add-or-remove / next keyframe buttons of a prop. Only this leaf+ * follows the playhead, so the inspector does not re-render on every frame.+ */+const KeyframeControls: React.FC<{+ readonly layer: Layer;+ readonly fieldKey: string;+ readonly schema: InteractivitySchema;+ readonly status: CanUpdateSequencePropStatus;+}> = ({ layer, fieldKey, schema, status }) => {+ const { actions, playback, composition } = useEditor();+ const frame = usePlaybackFrame(playback);+ const toggle = getCanvasKeyframeToggle({+ nodePathInfo: layer.nodePathInfo,+ track: layer.track,+ schema,+ key: fieldKey,+ propStatus: status,+ frame,+ durationInFrames: composition?.durationInFrames ?? 1,+ });+ const keyframed = status.status === "keyframed";+ if (!keyframed && !toggle.keyframable) {+ return null;+ }++ return (+ <div className="flex items-center">+ <button+ type="button"+ className={cn(keyframeNavButtonClass, !keyframed && "invisible")}+ disabled={toggle.previousFrame === null}+ aria-label="Go to previous keyframe"+ onClick={() => {+ if (toggle.previousFrame !== null) {+ actions.seek(toggle.previousFrame);+ }+ }}+ >+ <ChevronLeftIcon className="size-2.5" />+ </button>+ <button+ type="button"+ className={cn(+ "flex size-4 items-center justify-center rounded disabled:opacity-30",+ toggle.hasKeyframe+ ? "text-primary"+ : "text-muted-foreground hover:text-foreground",+ )}+ disabled={toggle.change === null}+ aria-label={toggle.hasKeyframe ? "Remove keyframe" : "Add keyframe"}+ title={+ toggle.hasKeyframe+ ? "Remove the keyframe at the playhead"+ : "Add a keyframe at the playhead"+ }+ onClick={() => {+ if (toggle.change !== null) {+ void actions.commitKeyframeChanges([toggle.change]);+ }+ }}+ >+ <KeyframeDiamond filled={toggle.hasKeyframe} />+ </button>+ <button+ type="button"+ className={cn(keyframeNavButtonClass, !keyframed && "invisible")}+ disabled={toggle.nextFrame === null}+ aria-label="Go to next keyframe"+ onClick={() => {+ if (toggle.nextFrame !== null) {+ actions.seek(toggle.nextFrame);+ }+ }}+ >+ <ChevronRightIcon className="size-2.5" />+ </button>+ </div>+ );+};+// Radix Select items cannot have an empty string as value.const defaultOption = "__default__";@@ -59,57 +155,200 @@ const fontWeights = ["900",];+type PropFieldEditorProps = {+ readonly fieldKey: string;+ readonly field: VisibleField["field"];+ /** The value written in the source, or `undefined` when the prop is not set. */+ readonly codeValue: unknown;+ readonly badge: React.ReactNode;+ readonly keyframe: React.ReactNode;+ readonly onCommit: (value: unknown) => void;+ /** Shows a value on the canvas while it is being dragged. */+ readonly onPreview: (values: Record<string, unknown>) => void;+ readonly onCancelPreview: () => void;+};+const PropEditor: React.FC<{+ readonly layer: Layer;+ readonly schema: InteractivitySchema;readonly fieldKey: string;readonly field: VisibleField["field"];readonly status: PropStatus | undefined;readonly onUpdate: (updates: SequencePropUpdate[]) => void;- /** Shows a value on the canvas while it is being dragged. */readonly onPreview: (values: Record<string, unknown>) => void;readonly onCancelPreview: () => void;-}> = ({ fieldKey, field, status, onUpdate, onPreview, onCancelPreview }) => {+}> = ({+ layer,+ schema,+ fieldKey,+ field,+ status,+ onUpdate,+ onPreview,+ onCancelPreview,+}) => {const label = getFieldLabel(fieldKey, field);- const ariaLabel = label;- const preview = (value: unknown) => onPreview({ [fieldKey]: value });- if (status && status.status !== "static") {+ if (status?.status === "computed") {return (- <FieldRow label={label}>+ <FieldRow label={label} keyframe={null}><div className="text-muted-foreground-dim flex h-7 flex-1 items-center truncate font-mono text-[11px]">- {status.status === "keyframed" ? "interpolate(…)" : "expression"}+ expression</div>- <StatusBadge status={status.status} />+ <StatusBadge status="computed" /></FieldRow>);}+ const keyframe =+ status === undefined ? null : (+ <KeyframeControls+ layer={layer}+ fieldKey={fieldKey}+ schema={schema}+ status={status}+ />+ );++ if (status?.status === "keyframed") {+ return (+ <KeyframedPropEditor+ layer={layer}+ schema={schema}+ fieldKey={fieldKey}+ field={field}+ status={status}+ keyframe={keyframe}+ onPreview={onPreview}+ onCancelPreview={onCancelPreview}+ />+ );+ }+const codeValue = status?.status === "static" ? status.codeValue : undefined;const schemaDefault = "default" in field ? field.default : undefined;const defaultValue = schemaDefault === undefined ? null : schemaDefault;- const isSet = codeValue !== undefined;- const commit = (value: unknown) =>- onUpdate([{ key: fieldKey, value, defaultValue }]);- const reset = isSet ? (- <Button- variant="ghost"- size="icon-xs"- aria-label={`Reset ${label}`}- title="Reset to default"- onClick={() =>- onUpdate([{ key: fieldKey, value: undefined, defaultValue: null }])- }- >- <RotateCcwIcon />- </Button>- ) : (- <span className="size-6 shrink-0" />+ const reset =+ codeValue === undefined ? (+ <span className="size-6 shrink-0" />+ ) : (+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={`Reset ${label}`}+ title="Reset to default"+ onClick={() =>+ onUpdate([{ key: fieldKey, value: undefined, defaultValue: null }])+ }+ >+ <RotateCcwIcon />+ </Button>+ );++ return (+ <PropFieldEditor+ fieldKey={fieldKey}+ field={field}+ codeValue={codeValue}+ badge={reset}+ keyframe={keyframe}+ onCommit={(value) => onUpdate([{ key: fieldKey, value, defaultValue }])}+ onPreview={onPreview}+ onCancelPreview={onCancelPreview}+ />);+};++/**+ * Edits an animated prop at the playhead: the field shows the interpolated+ * value of the current frame and committing a value writes a keyframe there.+ */+const KeyframedPropEditor: React.FC<{+ readonly layer: Layer;+ readonly schema: InteractivitySchema;+ readonly fieldKey: string;+ readonly field: VisibleField["field"];+ readonly status: Extract<PropStatus, { status: "keyframed" }>;+ readonly keyframe: React.ReactNode;+ readonly onPreview: (values: Record<string, unknown>) => void;+ readonly onCancelPreview: () => void;+}> = ({+ layer,+ schema,+ fieldKey,+ field,+ status,+ keyframe,+ onPreview,+ onCancelPreview,+}) => {+ const { actions, playback } = useEditor();+ const frame = usePlaybackFrame(playback);+ const value = getCanvasPropValueAtFrame({+ track: layer.track,+ schema,+ key: fieldKey,+ propStatus: status,+ frame,+ });++ return (+ <PropFieldEditor+ fieldKey={fieldKey}+ field={field}+ codeValue={value ?? undefined}+ badge={<StatusBadge status="keyframed" />}+ keyframe={keyframe}+ onCommit={(next) => {+ // A scrub that ends where it started only releases the preview.+ if (next === undefined || next === value) {+ onCancelPreview();+ return;+ }++ void actions.commitKeyframeChanges([+ {+ nodePathInfo: layer.nodePathInfo,+ key: fieldKey,+ schema,+ operation: {+ type: "add",+ frame: getCanvasKeyframeSourceFrame({+ track: layer.track,+ propStatus: status,+ frame,+ }),+ value: next,+ },+ },+ ]);+ }}+ onPreview={onPreview}+ onCancelPreview={onCancelPreview}+ />+ );+};++const PropFieldEditor: React.FC<PropFieldEditorProps> = ({+ fieldKey,+ field,+ codeValue,+ badge,+ keyframe,+ onCommit: commit,+ onPreview,+ onCancelPreview,+}) => {+ const label = getFieldLabel(fieldKey, field);+ const ariaLabel = label;+ const preview = (value: unknown) => onPreview({ [fieldKey]: value });+ const schemaDefault = "default" in field ? field.default : undefined;switch (field.type) {case "number": {const current = parseNumber(codeValue);return (- <FieldRow label={label} badge={reset}>+ <FieldRow label={label} badge={badge} keyframe={keyframe}><NumberFieldariaLabel={ariaLabel}value={current}@@ -131,7 +370,7 @@ const PropEditor: React.FC<{case "boolean":return (- <FieldRow label={label} badge={reset}>+ <FieldRow label={label} badge={badge} keyframe={keyframe}><BooleanFieldariaLabel={ariaLabel}value={@@ -147,7 +386,7 @@ const PropEditor: React.FC<{case "translate": {const current = parseTranslate(codeValue ?? schemaDefault);return (- <FieldRow label={label} badge={reset}>+ <FieldRow label={label} badge={badge} keyframe={keyframe}><NumberFieldariaLabel={`${label} X`}value={current.x}@@ -180,7 +419,7 @@ const PropEditor: React.FC<{case "scale":return (- <FieldRow label={label} badge={reset}>+ <FieldRow label={label} badge={badge} keyframe={keyframe}><NumberFieldariaLabel={ariaLabel}value={parseScale(codeValue ?? schemaDefault)}@@ -196,7 +435,7 @@ const PropEditor: React.FC<{case "rotation-css":return (- <FieldRow label={label} badge={reset}>+ <FieldRow label={label} badge={badge} keyframe={keyframe}><NumberFieldariaLabel={ariaLabel}value={parseRotation(codeValue ?? schemaDefault)}@@ -211,7 +450,7 @@ const PropEditor: React.FC<{case "rotation-degrees":return (- <FieldRow label={label} badge={reset}>+ <FieldRow label={label} badge={badge} keyframe={keyframe}><NumberFieldariaLabel={ariaLabel}value={parseNumber(codeValue ?? schemaDefault) ?? 0}@@ -228,7 +467,7 @@ const PropEditor: React.FC<{case "color":return (- <FieldRow label={label} badge={reset}>+ <FieldRow label={label} badge={badge} keyframe={keyframe}><ColorFieldariaLabel={ariaLabel}value={typeof codeValue === "string" ? codeValue : ""}@@ -243,7 +482,12 @@ const PropEditor: React.FC<{case "text-content":return (- <FieldRow label={label} badge={reset} className="items-start">+ <FieldRow+ label={label}+ badge={badge}+ keyframe={keyframe}+ className="items-start"+ ><TextFieldariaLabel={ariaLabel}multiline@@ -256,7 +500,7 @@ const PropEditor: React.FC<{case "font-weight":return (- <FieldRow label={label} badge={reset}>+ <FieldRow label={label} badge={badge} keyframe={keyframe}><SelectFieldariaLabel={ariaLabel}value={codeValue === undefined ? defaultOption : String(codeValue)}@@ -282,7 +526,7 @@ const PropEditor: React.FC<{case "enum":return (- <FieldRow label={label} badge={reset}>+ <FieldRow label={label} badge={badge} keyframe={keyframe}><SelectFieldariaLabel={ariaLabel}value={@@ -301,7 +545,7 @@ const PropEditor: React.FC<{case "transform-origin":case "asset":return (- <FieldRow label={label} badge={reset}>+ <FieldRow label={label} badge={badge} keyframe={keyframe}><TextFieldariaLabel={ariaLabel}mono={field.type === "asset"}@@ -462,6 +706,8 @@ export const LayerInspector: React.FC<{ readonly layer: Layer }> = ({{items.map(({ key, field }) => (<PropEditorkey={key}+ layer={layer}+ schema={schema ?? {}}fieldKey={key}field={field}status={statuses?.[key]}diff --git a/packages/template-vibe-code/src/editor/components/Inspector/fields.tsx b/packages/template-vibe-code/src/editor/components/Inspector/fields.tsxindex d12d8d9f65..b3c3786552 100644--- a/packages/template-vibe-code/src/editor/components/Inspector/fields.tsx+++ b/packages/template-vibe-code/src/editor/components/Inspector/fields.tsx@@ -16,14 +16,25 @@ export const FieldRow: React.FC<{readonly label: React.ReactNode;readonly children: React.ReactNode;readonly badge?: React.ReactNode;+ /**+ * Keyframe controls shown before the label. Pass `null` to reserve the+ * column so rows without controls stay aligned.+ */+ readonly keyframe?: React.ReactNode;readonly className?: string;-}> = ({ label, children, badge, className }) => (+}> = ({ label, children, badge, keyframe, className }) => (<divclassName={cn(- "grid grid-cols-[88px_minmax(0,1fr)] items-center gap-2",+ "grid items-center gap-2",+ keyframe === undefined+ ? "grid-cols-[88px_minmax(0,1fr)]"+ : "grid-cols-[34px_minmax(0,64px)_minmax(0,1fr)]",className,)}>+ {keyframe === undefined ? null : (+ <div className="flex h-7 items-center">{keyframe}</div>+ )}<div className="text-muted-foreground min-w-0 truncate text-[11px]">{label}</div>@@ -40,7 +51,7 @@ export const StatusBadge: React.FC<{<spantitle={status === "keyframed"- ? "This value is animated with interpolate(). Edit the keyframes in the code."+ ? "This value is animated with interpolate(). Editing it writes a keyframe at the playhead.": "This value is computed in code and cannot be edited here."}className={cn(diff --git a/packages/template-vibe-code/src/editor/components/KeyframeDiamond.tsx b/packages/template-vibe-code/src/editor/components/KeyframeDiamond.tsxnew file mode 100644index 0000000000..a3fdc56bf3--- /dev/null+++ b/packages/template-vibe-code/src/editor/components/KeyframeDiamond.tsx@@ -0,0 +1,25 @@+import React from "react";+import { cn } from "@/lib/utils";++/** The keyframe marker used by the inspector and the timeline. */+export const KeyframeDiamond: React.FC<{+ readonly filled: boolean;+ readonly size?: number;+ readonly className?: string;+}> = ({ filled, size = 10, className }) => (+ <svg+ width={size}+ height={size}+ viewBox="0 0 10 10"+ aria-hidden+ className={cn("block shrink-0", className)}+ >+ <path+ d="M5 0.7 L9.3 5 L5 9.3 L0.7 5 Z"+ fill={filled ? "currentColor" : "none"}+ stroke="currentColor"+ strokeWidth={1.2}+ strokeLinejoin="round"+ />+ </svg>+);diff --git a/packages/template-vibe-code/src/editor/components/Timeline/Timeline.tsx b/packages/template-vibe-code/src/editor/components/Timeline/Timeline.tsxindex 3495b4a29c..b43c487978 100644--- a/packages/template-vibe-code/src/editor/components/Timeline/Timeline.tsx+++ b/packages/template-vibe-code/src/editor/components/Timeline/Timeline.tsx@@ -2,11 +2,16 @@import {getCanvasSelectionItemKey,+ startCanvasKeyframeDrag,useCanvasSelection,useCanvasSequenceHover,+ type CanvasKeyframeDragTarget,+ type CanvasSelectionInteraction,} from "@remotion/canvas";import { getNodeProps } from "@remotion/codemods";import {+ ChevronDownIcon,+ ChevronRightIcon,FilmIcon,ImageIcon,LayersIcon,@@ -25,21 +30,34 @@ import React, {import { cn } from "@/lib/utils";import { usePlaybackFrame } from "../../hooks/use-playback";import { getErrorMessage } from "../../hooks/use-preview-host";+import {+ findKeyframedProp,+ getKeyframeSelectionItem,+ getSelectedKeyframes,+ type KeyframedProp,+ type KeyframeSelectionItem,+} from "../../model/keyframes";import {getLayerLabel,getNodeReference,type Layer,} from "../../model/layers";-import { getLayerSchema, hasTimingProps } from "../../model/schemas";+import {+ getFieldLabel,+ getLayerSchema,+ hasTimingProps,+} from "../../model/schemas";import { clamp, formatTimecode } from "../../model/values";import { useEditor } from "../../state/editor-context";import { fallbackSelectionController } from "../../state/fallback-selection";import { LayerContextMenu } from "../Inspector/LayerActions";+import { KeyframeDiamond } from "../KeyframeDiamond";import { ToolbarButton } from "../TopBar";const LABEL_WIDTH = 220;const RULER_HEIGHT = 26;const ROW_HEIGHT = 30;+const KEYFRAME_ROW_HEIGHT = 22;const EDGE_WIDTH = 7;const playbackRateComponentIdentities = new Set([@@ -60,6 +78,13 @@ type DragState = {startDuration: number;};+// The keyframes being dragged are drawn shifted by the previewed delta; the+// source keeps the original frames until the move is committed.+type KeyframeDragState = {+ keys: ReadonlySet<string>;+ delta: number;+};+const getTickInterval = (pxPerFrame: number, fps: number) => {const candidates = [1,@@ -126,6 +151,8 @@ const TrackRow = memo(function TrackRow({durationInFrames,selected,drag,+ keyframeRows,+ onToggleKeyframeRows,onPointerDownBar,}: {readonly layer: Layer;@@ -134,6 +161,9 @@ const TrackRow = memo(function TrackRow({readonly durationInFrames: number;readonly selected: boolean;readonly drag: DragState | null;+ /** Whether the layer has animated props and whether their rows are shown. */+ readonly keyframeRows: "none" | "expanded" | "collapsed";+ readonly onToggleKeyframeRows: (layer: Layer) => void;readonly onPointerDownBar: (event: React.PointerEvent,layer: Layer,@@ -187,7 +217,7 @@ const TrackRow = memo(function TrackRow({"bg-background-panel border-border-dim sticky left-0 z-20 flex shrink-0 items-center gap-1.5 border-r border-b pr-2 text-xs",selected && "bg-[#141a2a]",)}- style={{ width: LABEL_WIDTH, paddingLeft: 10 + depth * 14 }}+ style={{ width: LABEL_WIDTH, paddingLeft: 6 + depth * 14 }}onClick={select}onDoubleClick={() => {if (layer.source) {@@ -199,6 +229,30 @@ const TrackRow = memo(function TrackRow({}}}>+ {keyframeRows === "none" ? (+ <span className="size-3 shrink-0" />+ ) : (+ <button+ type="button"+ className="text-muted-foreground-dim hover:text-foreground flex size-3 shrink-0 items-center justify-center"+ aria-label={+ keyframeRows === "expanded"+ ? "Hide keyframes"+ : "Show keyframes"+ }+ aria-expanded={keyframeRows === "expanded"}+ onClick={(event) => {+ event.stopPropagation();+ onToggleKeyframeRows(layer);+ }}+ >+ {keyframeRows === "expanded" ? (+ <ChevronDownIcon className="size-3" />+ ) : (+ <ChevronRightIcon className="size-3" />+ )}+ </button>+ )}<TypeIcon layer={layer} /><spanclassName={cn(@@ -291,10 +345,97 @@ const TrackRow = memo(function TrackRow({);});+/** A row with the keyframes of one animated prop, below its layer. */+const KeyframeRow = memo(function KeyframeRow({+ prop,+ pxPerFrame,+ durationInFrames,+ selectedKeys,+ keyframeDrag,+ onPointerDownKeyframe,+}: {+ readonly prop: KeyframedProp;+ readonly pxPerFrame: number;+ readonly durationInFrames: number;+ readonly selectedKeys: ReadonlySet<string>;+ readonly keyframeDrag: KeyframeDragState | null;+ readonly onPointerDownKeyframe: (+ event: React.PointerEvent<HTMLButtonElement>,+ prop: KeyframedProp,+ frame: number,+ ) => void;+}) {+ const { actions } = useEditor();+ const label = getFieldLabel(prop.key, prop.field);+ const layerSelected = selectedKeys.has(+ getCanvasSelectionItemKey(prop.layer.selectionItem),+ );++ return (+ <div+ role="row"+ className={cn("flex", layerSelected && "bg-selection-dim/20")}+ style={{ height: KEYFRAME_ROW_HEIGHT }}+ >+ <div+ className="bg-background-panel border-border-dim text-muted-foreground-dim sticky left-0 z-20 flex shrink-0 items-center gap-1.5 border-r border-b pr-2 text-[10px]"+ style={{+ width: LABEL_WIDTH,+ paddingLeft: 24 + (prop.layer.track.depth + 1) * 14,+ }}+ >+ <KeyframeDiamond filled size={7} />+ <span className="min-w-0 flex-1 truncate">{label}</span>+ </div>+ <div+ className="border-border-dim relative min-w-0 flex-1 border-b"+ style={{ width: durationInFrames * pxPerFrame }}+ data-track-area+ >+ {prop.keyframes.map((keyframe) => {+ if (keyframe.frame < 0 || keyframe.frame >= durationInFrames) {+ return null;+ }++ const itemKey = getCanvasSelectionItemKey(+ getKeyframeSelectionItem(prop, keyframe.frame),+ );+ const dragging = keyframeDrag?.keys.has(itemKey) === true;+ const frame = keyframe.frame + (dragging ? keyframeDrag.delta : 0);+ const selected = selectedKeys.has(itemKey);+ return (+ <button+ key={keyframe.frame}+ type="button"+ aria-label={`${label} keyframe at frame ${keyframe.frame}`}+ aria-pressed={selected}+ className={cn(+ "absolute top-1/2 flex size-4 -translate-x-1/2 -translate-y-1/2 items-center justify-center",+ selected || dragging+ ? "text-primary"+ : "text-muted-foreground hover:text-foreground",+ dragging ? "cursor-grabbing" : "cursor-grab",+ )}+ style={{ left: frame * pxPerFrame }}+ onPointerDown={(event) =>+ onPointerDownKeyframe(event, prop, keyframe.frame)+ }+ onDoubleClick={() => actions.seek(keyframe.frame)}+ >+ <KeyframeDiamond filled size={10} />+ </button>+ );+ })}+ </div>+ </div>+ );+});+export const Timeline: React.FC = () => {const {host,layers,+ keyframedProps,composition,playback,actions,@@ -307,6 +448,12 @@ export const Timeline: React.FC = () => {const [zoom, setZoom] = useState(1);const [drag, setDrag] = useState<DragState | null>(null);const dragRef = useRef<DragState | null>(null);+ const [keyframeDrag, setKeyframeDrag] = useState<KeyframeDragState | null>(+ null,+ );+ const [collapsedLayers, setCollapsedLayers] = useState<ReadonlySet<string>>(+ () => new Set(),+ );const durationInFrames = composition?.durationInFrames ?? 1;const fps = composition?.fps ?? 30;const basePxPerFrame = Math.max(@@ -337,6 +484,34 @@ export const Timeline: React.FC = () => {() => new Set(selection.selectedItems.map(getCanvasSelectionItemKey)),[selection.selectedItems],);+ const keyframedPropsByLayer = useMemo(() => {+ const byLayer = new Map<string, KeyframedProp[]>();+ for (const prop of keyframedProps) {+ const key = getCanvasSelectionItemKey(prop.layer.selectionItem);+ byLayer.set(key, [...(byLayer.get(key) ?? []), prop]);+ }++ return byLayer;+ }, [keyframedProps]);+ const getVisibleKeyframeRows = (layer: Layer): KeyframedProp[] => {+ const key = getCanvasSelectionItemKey(layer.selectionItem);+ return collapsedLayers.has(key)+ ? []+ : (keyframedPropsByLayer.get(key) ?? []);+ };+ const toggleKeyframeRows = useCallback((layer: Layer) => {+ const key = getCanvasSelectionItemKey(layer.selectionItem);+ setCollapsedLayers((current) => {+ const next = new Set(current);+ if (next.has(key)) {+ next.delete(key);+ } else {+ next.add(key);+ }++ return next;+ });+ }, []);const frameFromClientX = useCallback((clientX: number) => {@@ -540,6 +715,99 @@ export const Timeline: React.FC = () => {[actions, project, pxPerFrame],);+ // Selecting and dragging keyframes follows the Studio: a click selects on+ // release, dragging a selected keyframe moves the whole selection, and+ // Shift / Command extend the selection without dragging it.+ const keyframedPropsRef = useRef(keyframedProps);+ keyframedPropsRef.current = keyframedProps;+ const onPointerDownKeyframe = useCallback(+ (+ event: React.PointerEvent<HTMLButtonElement>,+ prop: KeyframedProp,+ frame: number,+ ) => {+ if (event.button !== 0 || !host) {+ return;+ }++ event.preventDefault();+ event.stopPropagation();+ const interaction: CanvasSelectionInteraction = {+ shiftKey: event.shiftKey,+ toggleKey: event.metaKey || event.ctrlKey,+ };+ const item = getKeyframeSelectionItem(prop, frame);+ const itemKey = getCanvasSelectionItemKey(item);+ const selectedKeyframes = getSelectedKeyframes(+ host.controller.selection.getSnapshot().selectedItems,+ );+ const selected = selectedKeyframes.some(+ (keyframe) => getCanvasSelectionItemKey(keyframe) === itemKey,+ );+ const modifier = interaction.shiftKey || interaction.toggleKey;+ const dragExistingSelection = selected && !modifier;+ const selectOnRelease = !selected && !modifier;+ if (modifier) {+ actions.selectKeyframes([item], interaction);+ }++ const keyframesToDrag: KeyframeSelectionItem[] =+ dragExistingSelection && selectedKeyframes.length > 0+ ? selectedKeyframes+ : [item];+ const targets = keyframesToDrag.flatMap(+ (keyframe): CanvasKeyframeDragTarget[] => {+ const target = findKeyframedProp(keyframedPropsRef.current, keyframe);+ return target+ ? [+ {+ nodePathInfo: target.layer.nodePathInfo,+ track: target.layer.track,+ schema: target.schema,+ key: target.key,+ propStatus: target.propStatus,+ frame: keyframe.frame,+ },+ ]+ : [];+ },+ );+ const dragKeys = new Set(keyframesToDrag.map(getCanvasSelectionItemKey));++ startCanvasKeyframeDrag({+ event,+ captureTarget: event.currentTarget,+ targets,+ pixelsPerFrame: pxPerFrame,+ durationInFrames,+ overrides: host.controller.overrides,+ onDragStart: null,+ onDragMove: (delta) => setKeyframeDrag({ keys: dragKeys, delta }),+ onDragEnd: ({ changes, delta, dragged, released }) => {+ setKeyframeDrag(null);+ if (changes.length === 0) {+ if (!dragged && released && selectOnRelease) {+ actions.selectKeyframes([item], interaction);+ }++ return;+ }++ // The selection follows the moved keyframes.+ actions.selectKeyframes(+ keyframesToDrag.map((keyframe) => ({+ ...keyframe,+ frame: keyframe.frame + delta,+ })),+ null,+ );+ void actions.commitKeyframeChanges(changes);+ },+ });+ },+ [actions, durationInFrames, host, pxPerFrame],+ );+const ticks = useMemo(() => {const interval = getTickInterval(pxPerFrame, fps);const result: { frame: number; label: string; major: boolean }[] = [];@@ -559,7 +827,13 @@ export const Timeline: React.FC = () => {return null;}- const contentHeight = RULER_HEIGHT + layers.length * ROW_HEIGHT;+ const contentHeight = layers.reduce(+ (height, layer) =>+ height ++ ROW_HEIGHT ++ getVisibleKeyframeRows(layer).length * KEYFRAME_ROW_HEIGHT,+ RULER_HEIGHT,+ );return (<div className="flex h-full min-h-0 flex-col">@@ -573,7 +847,8 @@ export const Timeline: React.FC = () => {</span><span className="flex-1" /><span className="text-muted-foreground-dim hidden font-mono text-[10px] lg:inline">- Drag a layer to move it · drag its edges to trim · ⌥ + scroll to zoom+ Drag a layer to move it · drag its edges to trim · drag keyframes to+ retime them · ⌥ + scroll to zoom</span><ToolbarButtonsize="icon-xs"@@ -709,20 +984,42 @@ export const Timeline: React.FC = () => {: "Waiting for the preview…"}</div>) : null}- {layers.map((layer, index) => (- <TrackRow- key={layer.track.sequence.id}- layer={layer}- index={index}- pxPerFrame={pxPerFrame}- durationInFrames={durationInFrames}- selected={selectedKeys.has(- getCanvasSelectionItemKey(layer.selectionItem),- )}- drag={drag}- onPointerDownBar={onPointerDownBar}- />- ))}+ {layers.map((layer, index) => {+ const layerKey = getCanvasSelectionItemKey(layer.selectionItem);+ const hasKeyframeRows = keyframedPropsByLayer.has(layerKey);+ return (+ <React.Fragment key={layer.track.sequence.id}>+ <TrackRow+ layer={layer}+ index={index}+ pxPerFrame={pxPerFrame}+ durationInFrames={durationInFrames}+ selected={selectedKeys.has(layerKey)}+ drag={drag}+ keyframeRows={+ !hasKeyframeRows+ ? "none"+ : collapsedLayers.has(layerKey)+ ? "collapsed"+ : "expanded"+ }+ onToggleKeyframeRows={toggleKeyframeRows}+ onPointerDownBar={onPointerDownBar}+ />+ {getVisibleKeyframeRows(layer).map((prop) => (+ <KeyframeRow+ key={prop.key}+ prop={prop}+ pxPerFrame={pxPerFrame}+ durationInFrames={durationInFrames}+ selectedKeys={selectedKeys}+ keyframeDrag={keyframeDrag}+ onPointerDownKeyframe={onPointerDownKeyframe}+ />+ ))}+ </React.Fragment>+ );+ })}{inFrame !== null && inFrame > 0 ? (<divclassName="pointer-events-none absolute top-0 z-20 bg-black/45"diff --git a/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts b/packages/template-vibe-code/src/editor/hooks/use-editor-actions.tsindex afcf47684f..f18bfcd526 100644--- a/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts+++ b/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts@@ -1,7 +1,9 @@"use client";import {+ getCanvasKeyframeToggle,getCanvasSelectionItemKey,+ type CanvasKeyframeChange,type CanvasSelectionInteraction,type CanvasSequencePropChange,type SequenceNodePathInfo,@@ -44,6 +46,13 @@ import type {} from "@/preview/bridge";import type { CompositionInfo } from "../model/compositions";import { formatSource } from "../model/format";+import {+ findKeyframedProp,+ getKeyframeSelectionItem,+ getSelectedKeyframes,+ type KeyframedProp,+ type KeyframeSelectionItem,+} from "../model/keyframes";import { areSiblingNodes, getNodeReference, type Layer } from "../model/layers";import { filesAreEqual, getFileName, toCodemodProject } from "../model/project";import { resolveProjectPathInput } from "@/lib/project-paths";@@ -62,6 +71,7 @@ type ActionContext = {entryPoint: string;host: PreviewHost | null;layers: Layer[];+ keyframedProps: KeyframedProp[];compositions: CompositionInfo[];compositionFile: string | null;activeComposition: CompositionInfo | null;@@ -198,6 +208,166 @@ export const useEditorActions = ({}};+ type NodeChange = {+ node: NodeReference;+ nodePathInfo: SequenceNodePathInfo;+ schema: InteractivitySchema;+ updates: SequencePropUpdate[];+ keyframes: NodeKeyframeUpdate[];+ };++ // Groups the props and keyframes of a canvas gesture by source node, so+ // each node is rewritten once.+ const groupNodeChanges = (+ changes: readonly (CanvasSequencePropChange | CanvasKeyframeChange)[],+ ) => {+ const controller = ref.current.host?.controller;+ const nodeChanges = new Map<string, NodeChange>();+ for (const change of changes) {+ const item = {+ type: "sequence" as const,+ nodePathInfo: change.nodePathInfo,+ };+ const node = getNodeReference(item);+ if (!node) {+ controller?.overrides.clear(change.nodePathInfo);+ continue;+ }++ const key = getCanvasSelectionItemKey(item);+ const nodeChange = nodeChanges.get(key) ?? {+ node,+ nodePathInfo: change.nodePathInfo,+ schema: change.schema,+ updates: [],+ keyframes: [],+ };+ nodeChanges.set(key, nodeChange);+ if ("operation" in change) {+ nodeChange.keyframes.push({+ key: change.key,+ operation: change.operation,+ });+ } else if (change.type === "keyframe") {+ nodeChange.keyframes.push({+ key: change.key,+ operation: {+ type: "add",+ frame: change.frame,+ value: change.value,+ },+ });+ } else {+ nodeChange.updates.push({+ key: change.key,+ value: change.value,+ defaultValue: change.defaultValue,+ });+ }+ }++ return nodeChanges;+ };++ /**+ * Writes grouped node changes to the source in one undoable step. The+ * canvas keeps previewing the values until `releasePreviews`.+ */+ const commitNodeChanges = async (nodeChanges: Map<string, NodeChange>) => {+ if (nodeChanges.size === 0) {+ return false;+ }++ const controller = ref.current.host?.controller;+ const videoConfig = {+ width: ref.current.compositionWidth,+ height: ref.current.compositionHeight,+ fps: ref.current.compositionFps,+ durationInFrames: ref.current.compositionDurationInFrames,+ };+ const release = () => {+ for (const { nodePathInfo } of nodeChanges.values()) {+ pendingPreviews.delete(+ getCanvasSelectionItemKey({ type: "sequence", nodePathInfo }),+ );+ controller?.overrides.clear(nodePathInfo);+ }+ };++ for (const [key, { nodePathInfo }] of nodeChanges) {+ pendingPreviews.set(key, nodePathInfo);+ }++ const ok = await applyCodemod(+ async (project) => {+ let current = project;+ const touched = new Set<string>();+ const collect = (result: CodemodResult) => {+ current = applyCodemodChanges(current, result.changes);+ for (const change of result.changes) {+ touched.add(change.filePath);+ }+ };++ const staticChanges = [...nodeChanges.values()].filter(+ ({ updates }) => updates.length > 0,+ );+ if (staticChanges.length > 0) {+ collect(+ updateMultipleNodeProps({+ project: current,+ changes: staticChanges.map(+ ({ node, schema, updates }): NodePropChange => ({+ node,+ schema,+ updates,+ videoConfig,+ }),+ ),+ }),+ );+ }++ for (const { node, schema, keyframes } of nodeChanges.values()) {+ if (keyframes.length > 0) {+ collect(+ await updateNodeKeyframes({+ project: current,+ node,+ updates: keyframes,+ schema,+ videoConfig,+ }),+ );+ }+ }++ // One change per file, from the input project to the final contents.+ return {+ changes: [...touched].flatMap((filePath) => {+ const previousContents = project.files[filePath] ?? null;+ const nextContents = current.files[filePath] ?? null;+ return previousContents === nextContents+ ? []+ : [{ filePath, previousContents, nextContents }];+ }),+ };+ },+ {+ onApplied: (changed) => {+ if (!changed) {+ release();+ }+ },+ },+ );+ if (!ok) {+ release();+ }++ return ok;+ };+const setZoom = (zoom: PreviewZoom) => {dispatch({ type: "set-playback", patch: { zoom } });};@@ -498,151 +668,85 @@ export const ${componentName}: React.FC = () => {* Writes the values of a canvas gesture, such as dragging outlines, to* the source. The canvas keeps previewing them until `releasePreviews`.*/- commitSequencePropChanges: async (+ commitSequencePropChanges: (changes: readonly CanvasSequencePropChange[],- ) => {- const controller = ref.current.host?.controller;- const videoConfig = {- width: ref.current.compositionWidth,- height: ref.current.compositionHeight,- fps: ref.current.compositionFps,- durationInFrames: ref.current.compositionDurationInFrames,- };- // Static values of one node are written together; a keyframed value- // receives a keyframe at the frame the canvas reported.- const nodeChanges = new Map<- string,- {- node: NodeReference;- nodePathInfo: SequenceNodePathInfo;- schema: InteractivitySchema;- updates: SequencePropUpdate[];- keyframes: NodeKeyframeUpdate[];- }- >();- for (const change of changes) {- const item = {- type: "sequence" as const,- nodePathInfo: change.nodePathInfo,- };- const node = getNodeReference(item);- if (!node) {- controller?.overrides.clear(change.nodePathInfo);- continue;- }-- const key = getCanvasSelectionItemKey(item);- const nodeChange = nodeChanges.get(key) ?? {- node,- nodePathInfo: change.nodePathInfo,- schema: change.schema,- updates: [],- keyframes: [],- };- nodeChanges.set(key, nodeChange);- if (change.type === "keyframe") {- nodeChange.keyframes.push({- key: change.key,- operation: {- type: "add",- frame: change.frame,- value: change.value,- },- });- } else {- nodeChange.updates.push({- key: change.key,- value: change.value,- defaultValue: change.defaultValue,- });- }+ ) => commitNodeChanges(groupNodeChanges(changes)),+ /**+ * Adds, removes or moves keyframes in the source. Moved keyframes stay+ * previewed on the canvas until `releasePreviews`.+ */+ commitKeyframeChanges: (changes: readonly CanvasKeyframeChange[]) =>+ commitNodeChanges(groupNodeChanges(changes)),+ /** Removes the keyframes that are selected on the timeline. */+ deleteSelectedKeyframes: () => {+ const { host, keyframedProps, compositionDurationInFrames } =+ ref.current;+ if (!host) {+ return Promise.resolve(false);}- if (nodeChanges.size === 0) {- return false;- }+ const layers = new Map<string, Layer>();+ const changes = getSelectedKeyframes(+ host.controller.selection.getSnapshot().selectedItems,+ ).flatMap((item): CanvasKeyframeChange[] => {+ const prop = findKeyframedProp(keyframedProps, item);+ if (!prop) {+ return [];+ }- const release = () => {- for (const { nodePathInfo } of nodeChanges.values()) {- pendingPreviews.delete(- getCanvasSelectionItemKey({ type: "sequence", nodePathInfo }),- );- controller?.overrides.clear(nodePathInfo);+ const { change } = getCanvasKeyframeToggle({+ nodePathInfo: prop.layer.nodePathInfo,+ track: prop.layer.track,+ schema: prop.schema,+ key: prop.key,+ propStatus: prop.propStatus,+ frame: item.frame,+ durationInFrames: compositionDurationInFrames,+ });+ if (change?.operation.type !== "remove") {+ return [];}- };- for (const [key, { nodePathInfo }] of nodeChanges) {- pendingPreviews.set(key, nodePathInfo);+ layers.set(+ getCanvasSelectionItemKey(prop.layer.selectionItem),+ prop.layer,+ );+ return [change];+ });+ if (changes.length === 0) {+ return Promise.resolve(false);}- const ok = await applyCodemod(- async (project) => {- let current = project;- const touched = new Set<string>();- const collect = (result: CodemodResult) => {- current = applyCodemodChanges(current, result.changes);- for (const change of result.changes) {- touched.add(change.filePath);- }- };-- const staticChanges = [...nodeChanges.values()].filter(- ({ updates }) => updates.length > 0,- );- if (staticChanges.length > 0) {- collect(- updateMultipleNodeProps({- project: current,- changes: staticChanges.map(- ({ node, schema, updates }): NodePropChange => ({- node,- schema,- updates,- videoConfig,- }),- ),- }),- );- }-- for (const { node, schema, keyframes } of nodeChanges.values()) {- if (keyframes.length > 0) {- collect(- await updateNodeKeyframes({- project: current,- node,- updates: keyframes,- schema,- videoConfig,- }),- );- }- }-- // One change per file, from the input project to the final contents.- return {- changes: [...touched].flatMap((filePath) => {- const previousContents = project.files[filePath] ?? null;- const nextContents = current.files[filePath] ?? null;- return previousContents === nextContents- ? []- : [{ filePath, previousContents, nextContents }];- }),- };- },- {- onApplied: (changed) => {- if (!changed) {- release();- }- },- },+ // The layers of the removed keyframes stay selected.+ host.controller.selection.setSelectedItems(+ [...layers.values()].map((layer) => layer.selectionItem),);- if (!ok) {- release();+ return commitNodeChanges(groupNodeChanges(changes));+ },+ selectKeyframes: (+ items: readonly KeyframeSelectionItem[],+ interaction: CanvasSelectionInteraction | null,+ ) => {+ const { host, keyframedProps } = ref.current;+ if (!host) {+ return;}- return ok;+ const [item] = items;+ if (interaction === null || !item || items.length > 1) {+ host.controller.selection.setSelectedItems(items);+ return;+ }++ host.controller.selection.select(+ item,+ interaction,+ keyframedProps.flatMap((prop) =>+ prop.keyframes.map((keyframe) =>+ getKeyframeSelectionItem(prop, keyframe.frame),+ ),+ ),+ );},/** Called once the preview shows the committed source again. */releasePreviews: () => {diff --git a/packages/template-vibe-code/src/editor/hooks/use-editor-shortcuts.ts b/packages/template-vibe-code/src/editor/hooks/use-editor-shortcuts.tsindex 7f0bc6c2f2..83724c798a 100644--- a/packages/template-vibe-code/src/editor/hooks/use-editor-shortcuts.ts+++ b/packages/template-vibe-code/src/editor/hooks/use-editor-shortcuts.ts@@ -172,6 +172,15 @@ export const useEditorShortcuts = ({case "Backspace":case "Delete": {if (event.repeat) return true;+ if (+ host?.controller.selection+ .getSnapshot()+ .selectedItems.some((item) => item.type === "keyframe")+ ) {+ void actions.deleteSelectedKeyframes();+ return true;+ }+const selectedNodes = getSelectedNodes(host, layers);if (selectedNodes.length > 0) {void actions.deleteNodes(selectedNodes);diff --git a/packages/template-vibe-code/src/editor/model/keyframes.ts b/packages/template-vibe-code/src/editor/model/keyframes.tsnew file mode 100644index 0000000000..cae4659028--- /dev/null+++ b/packages/template-vibe-code/src/editor/model/keyframes.ts@@ -0,0 +1,134 @@+import {+ getCanvasKeyframes,+ getCanvasSelectionItemKey,+ type CanvasKeyframe,+ type CanvasSelectionItem,+ type SequenceNodePathInfo,+} from "@remotion/canvas";+import { getNodeProps, type CodemodProject } from "@remotion/codemods";+import type {+ CanUpdateSequencePropStatusKeyframed,+ InteractivitySchema,+ InteractivitySchemaField,+ VideoConfigValues,+} from "remotion";+import { getNodeReference, type Layer } from "./layers";+import { getLayerSchema, getVisibleFields } from "./schemas";++/** A prop of a layer that is animated with `interpolate()` in the source. */+export type KeyframedProp = {+ layer: Layer;+ key: string;+ field: InteractivitySchemaField;+ schema: InteractivitySchema;+ propStatus: CanUpdateSequencePropStatusKeyframed;+ /** The keyframes placed on the composition timeline. */+ keyframes: CanvasKeyframe[];+ /** Identifies the prop in the Canvas selection, e.g. for its keyframes. */+ nodePathInfo: SequenceNodePathInfo;+};++export type KeyframeSelectionItem = Extract<+ CanvasSelectionItem,+ { type: "keyframe" }+>;++/**+ * The selection identity of a prop's keyframe row. The Canvas keeps keyframe+ * selection items under the sequence with the schema key as auxiliary path,+ * like the Remotion Studio does.+ */+export const getKeyframedPropNodePathInfo = (+ layer: Layer,+ key: string,+): SequenceNodePathInfo => ({+ ...layer.nodePathInfo,+ auxiliaryKeys: ["controls", key],+});++export const getKeyframeSelectionItem = (+ prop: Pick<KeyframedProp, "nodePathInfo">,+ frame: number,+): KeyframeSelectionItem => ({+ type: "keyframe",+ nodePathInfo: prop.nodePathInfo,+ frame,+});++const getKeyframedPropKey = (prop: Pick<KeyframedProp, "nodePathInfo">) =>+ getCanvasSelectionItemKey({+ type: "sequence-prop",+ nodePathInfo: prop.nodePathInfo,+ key: prop.nodePathInfo.auxiliaryKeys.slice(1).join("."),+ });++/**+ * The animated props of every layer, read from the source. Layers without a+ * source node or with an unparsable file have no keyframed props.+ */+export const getKeyframedProps = ({+ layers,+ project,+ videoConfig,+}: {+ layers: readonly Layer[];+ project: CodemodProject;+ videoConfig: VideoConfigValues;+}): KeyframedProp[] => {+ return layers.flatMap((layer): KeyframedProp[] => {+ const node = getNodeReference(layer.selectionItem);+ const schema = getLayerSchema(layer);+ if (!node || !schema) {+ return [];+ }++ const fields = getVisibleFields(schema);+ let props: ReturnType<typeof getNodeProps>["props"];+ try {+ props = getNodeProps({+ project,+ node,+ keys: fields.map(({ key }) => key),+ videoConfig,+ }).props;+ } catch {+ return [];+ }++ return fields.flatMap(({ key, field }): KeyframedProp[] => {+ const propStatus = props[key];+ if (propStatus?.status !== "keyframed") {+ return [];+ }++ const nodePathInfo = getKeyframedPropNodePathInfo(layer, key);+ return [+ {+ layer,+ key,+ field,+ schema,+ propStatus,+ keyframes: getCanvasKeyframes({ track: layer.track, propStatus }),+ nodePathInfo,+ },+ ];+ });+ });+};++export const getSelectedKeyframes = (+ selectedItems: readonly CanvasSelectionItem[],+): KeyframeSelectionItem[] =>+ selectedItems.filter(+ (item): item is KeyframeSelectionItem => item.type === "keyframe",+ );++/** Finds the keyframed prop a selected keyframe belongs to. */+export const findKeyframedProp = (+ props: readonly KeyframedProp[],+ item: KeyframeSelectionItem,+): KeyframedProp | null => {+ const key = getKeyframedPropKey({ nodePathInfo: item.nodePathInfo });+ return props.find((prop) => getKeyframedPropKey(prop) === key) ?? null;+};diff --git a/packages/template-vibe-code/src/editor/model/shortcuts.ts b/packages/template-vibe-code/src/editor/model/shortcuts.tsindex 77277d8e90..cd0829e884 100644--- a/packages/template-vibe-code/src/editor/model/shortcuts.ts+++ b/packages/template-vibe-code/src/editor/model/shortcuts.ts@@ -30,7 +30,7 @@ export const shortcutGroups: ShortcutGroup[] = [{ keys: ["X"], description: "Clear in / out" },{ keys: ["⌘ A"], description: "Select all layers" },{ keys: ["Esc"], description: "Clear selection" },- { keys: ["⌫"], description: "Delete selected layers" },+ { keys: ["⌫"], description: "Delete selected layers or keyframes" },{ keys: ["⌘ D"], description: "Duplicate selected layers" },{ keys: ["⌘ ⇧ D"], description: "Split selected layers at playhead" },{ keys: ["⌥ ↑", "⌥ ↓"], description: "Move layer up / down" },diff --git a/packages/template-vibe-code/src/editor/state/editor-context.tsx b/packages/template-vibe-code/src/editor/state/editor-context.tsxindex f03d4e2333..69c522fdff 100644--- a/packages/template-vibe-code/src/editor/state/editor-context.tsx+++ b/packages/template-vibe-code/src/editor/state/editor-context.tsx@@ -7,6 +7,7 @@ import type { PreviewHost } from "@/preview/bridge";import type { EditorActions } from "../hooks/use-editor-actions";import type { PlaybackStore } from "../hooks/use-playback";import type { CompositionInfo } from "../model/compositions";+import type { KeyframedProp } from "../model/keyframes";import type { Layer } from "../model/layers";import type { EditorAction, EditorState } from "./editor-store";@@ -20,6 +21,8 @@ export type EditorContextValue = {hostError: string | null;playback: PlaybackStore;layers: Layer[];+ /** The props of the layers that are animated with `interpolate()`. */+ keyframedProps: KeyframedProp[];project: CodemodProject;compositions: CompositionInfo[];compositionFile: string | null;