Skip to content

🎥 Make videos programmatically with React

`@remotion/canvas`: Add `onSequencePropsChange` to `<Canvas>` for moving elements by dragging outlines

JonnyBurgere7e39de3f394
diff --git a/packages/canvas/src/canvas-internals.ts b/packages/canvas/src/canvas-internals.ts
index 9f89540b18..dc2f056b47 100644
--- a/packages/canvas/src/canvas-internals.ts
+++ b/packages/canvas/src/canvas-internals.ts
@@ -72,3 +72,74 @@ export {
export {sortItemsByCommitOrder} from './sort-by-commit-order';
export {timelineSequenceNodePathToKey} from './timeline-sequence-node-path-to-key';
export {useCanvasRuntimeValueSnapshots} from './use-runtime-value-snapshots';
+export {
+ isPointerSessionRelease,
+ observePointerRelease,
+ startCapturedPointerSession,
+ startDeferredCapturedPointerSession,
+} from './pointer-session';
+export type {PointerSessionEndReason} from './pointer-session';
+export {
+ parseTranslate,
+ parseTranslateWithUnits,
+ serializeTranslate,
+ serializeTranslateWithUnits,
+} from './translate-value';
+export type {
+ ParsedTranslate,
+ ParsedTranslateWithUnits,
+ TranslateUnit,
+} from './translate-value';
+export {
+ getKeyframeDisplayOffset,
+ getKeyframeLocalFrame,
+ getKeyframePlaybackRate,
+ getKeyframeSourceFrame,
+ getTimelineKeyframes,
+ resolveKeyframeSourceFrame,
+} from './keyframe-frames';
+export type {KeyframeSourceFrame} from './keyframe-frames';
+export {
+ canvasOutlineSnapThresholdPx,
+ findCanvasOutlineSnap,
+ getCanvasOutlineSnapTargets,
+} from './outline-snap';
+export type {
+ CanvasOutlineSnapAxis,
+ CanvasOutlineSnapEdge,
+ CanvasOutlineSnapGuide,
+ CanvasOutlineSnapPoint,
+ CanvasOutlineSnapResult,
+ CanvasOutlineSnapTarget,
+ CanvasOutlineSnapTargetType,
+} from './outline-snap';
+export {CanvasOutlineSnapLines} from './canvas-outline-snap-lines';
+export {
+ applyCanvasOutlineDragAxisLock,
+ applyCanvasOutlineTranslateDelta,
+ canvasOutlineDragThresholdPx,
+ canvasTranslateFieldKey,
+ clearCanvasOutlineDragOverrides,
+ createCanvasOutlineTranslateSession,
+ getCanvasOutlineNudgeDelta,
+ getCanvasOutlineNudgeDeltas,
+ getCanvasOutlineNudgeDirection,
+ getCanvasOutlineTranslateDragChanges,
+ getCanvasOutlineTranslateDragStates,
+ getCanvasOutlineTranslateDragValues,
+ isCanvasOutlineDragPastThreshold,
+ startCanvasOutlineTranslateDrag,
+} from './outline-translate-drag';
+export type {
+ CanvasOutlineDragChange,
+ CanvasOutlineKeyframedDragChange,
+ CanvasOutlineNudgeDirection,
+ CanvasOutlineStaticDragChange,
+ CanvasOutlineTranslateDragEnd,
+ CanvasOutlineTranslateDragSnapping,
+ CanvasOutlineTranslateDragState,
+ CanvasOutlineTranslatePropStatus,
+ CanvasOutlineTranslateSession,
+ CanvasOutlineTranslateTarget,
+ SetCanvasDragOverrides,
+} from './outline-translate-drag';
diff --git a/packages/canvas/src/canvas-outline-overlay.tsx b/packages/canvas/src/canvas-outline-overlay.tsx
index 1ebce9232c..77bf9c4813 100644
--- a/packages/canvas/src/canvas-outline-overlay.tsx
+++ b/packages/canvas/src/canvas-outline-overlay.tsx
@@ -1,11 +1,27 @@
+import {PlayerInternals} from '@remotion/player';
import type {RefObject} from 'react';
-import React, {useEffect, useCallback, useMemo, useRef, useState} from 'react';
-import {Internals, type TSequence} from 'remotion';
+import React, {
+ useCallback,
+ useContext,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import {Internals, type GetDragOverrides, type TSequence} from 'remotion';
import type {CanvasController} from './canvas-controller';
import {CanvasOutlinePolygon} from './canvas-outline-polygon';
+import {CanvasOutlineSnapLines} from './canvas-outline-snap-lines';
+import type {SequenceNodePathInfo} from './get-timeline-sequence-sort-key';
import {useCanvasHover, useCanvasSequenceHover} from './hover';
+import {getKeyframeDisplayOffset} from './keyframe-frames';
import type {CanvasOutline} from './outline-geometry';
import {handleCanvasOutlinePointerDown} from './outline-interaction';
+import {
+ getCanvasOutlineSnapTargets,
+ type CanvasOutlineSnapPoint,
+} from './outline-snap';
import {
getCanvasActiveOutlineTargets,
getCanvasOutlineActivity,
@@ -14,19 +30,42 @@ import {
getCanvasSelectedSequenceKeys,
getCanvasSequenceKeysContainingSelection,
getCanvasVisibleOutlineTargets,
+ type CanvasOutlineLayoutTarget,
type CanvasSelectableOutline,
} from './outline-targets';
+import {
+ applyCanvasOutlineTranslateDelta,
+ canvasTranslateFieldKey,
+ clearCanvasOutlineDragOverrides,
+ createCanvasOutlineTranslateSession,
+ getCanvasOutlineNudgeDeltas,
+ getCanvasOutlineNudgeDirection,
+ getCanvasOutlineTranslateDragChanges,
+ getCanvasOutlineTranslateDragStates,
+ startCanvasOutlineTranslateDrag,
+ type CanvasOutlineDragChange,
+ type CanvasOutlineTranslateSession,
+ type CanvasOutlineTranslateTarget,
+} from './outline-translate-drag';
import {
getCanvasSequenceSelectionKey,
useCanvasSelection,
type CanvasSelectionItem,
} from './selection';
import type {CanvasSequenceNodePathResolver} from './sequence-node-path';
+import type {
+ CanvasSequencePropChange,
+ CanvasSequencePropsChangeHandler,
+ CanvasSequencePropStatusResolver,
+} from './sequence-props-change';
import {timelineSequenceNodePathToKey} from './timeline-sequence-node-path-to-key';
import {useCanvasOutlines} from './use-canvas-outlines';
import {useCanvasRuntimeValueSnapshots} from './use-runtime-value-snapshots';
import {useSyncExternalStore} from './use-sync-external-store';
+const OUTLINE_COLOR = '#0b84f3';
+const SNAP_COLOR = '#ff00ff';
+
const overlayStyle: React.CSSProperties = {
position: 'absolute',
inset: 0,
@@ -35,6 +74,142 @@ const overlayStyle: React.CSSProperties = {
outline: 'none',
};
+type OverlayTranslateTarget = CanvasOutlineTranslateTarget & {
+ readonly nodePathInfo: SequenceNodePathInfo;
+};
+
+const getOverlayTranslateTarget = ({
+ selectableOutline,
+ getDragOverrides,
+ getPropStatuses,
+ frame,
+}: {
+ readonly selectableOutline: CanvasSelectableOutline;
+ readonly getDragOverrides: GetDragOverrides;
+ readonly getPropStatuses: CanvasSequencePropStatusResolver | null;
+ readonly frame: number;
+}): OverlayTranslateTarget | null => {
+ const {registeredNodePathInfo, sequence} = selectableOutline;
+ const {controls} = sequence;
+ if (controls === null || registeredNodePathInfo === null) {
+ return null;
+ }
+
+ // The host knows the source: a computed value cannot be moved and a
+ // keyframed one is moved by inserting a keyframe.
+ const propStatuses =
+ getPropStatuses?.(registeredNodePathInfo, [canvasTranslateFieldKey]) ??
+ null;
+ const propStatus = propStatuses?.[canvasTranslateFieldKey] ?? null;
+ if (
+ propStatus !== null &&
+ propStatus.status !== 'static' &&
+ (propStatus.status !== 'keyframed' ||
+ propStatus.interpolationFunction !== 'interpolate')
+ ) {
+ return null;
+ }
+
+ const nodePath = registeredNodePathInfo.sequenceSubscriptionKey;
+ const runtimeValues = controls.runtimeValues.getSnapshot();
+ // Overrides can switch enum variants, which decides whether translate is active.
+ const {merged} = Internals.computeEffectiveSchemaValuesDotNotation({
+ schema: controls.schema,
+ currentValue: runtimeValues,
+ overrideValues: getDragOverrides(nodePath),
+ propStatus: propStatuses ?? undefined,
+ frame:
+ (frame - selectableOutline.keyframeDisplayOffset) *
+ selectableOutline.keyframePlaybackRate,
+ });
+ const field = Internals.flattenActiveSchema(
+ controls.schema,
+ (key) => merged[key],
+ )[canvasTranslateFieldKey];
+ if (field?.type !== 'translate') {
+ return null;
+ }
+
+ return {
+ nodePath,
+ nodePathInfo: registeredNodePathInfo,
+ schema: controls.schema,
+ fieldDefault: field.default,
+ propStatus,
+ runtimeValue: runtimeValues[canvasTranslateFieldKey],
+ keyframeDisplayOffset: getKeyframeDisplayOffset({
+ propStatus,
+ keyframeDisplayOffset: selectableOutline.keyframeDisplayOffset,
+ keyframePlaybackRate: selectableOutline.keyframePlaybackRate,
+ }),
+ keyframePlaybackRate: selectableOutline.keyframePlaybackRate,
+ };
+};
+
+const toSequencePropChanges = (
+ changes: readonly CanvasOutlineDragChange[],
+ session: CanvasOutlineTranslateSession<OverlayTranslateTarget>,
+): CanvasSequencePropChange[] => {
+ const targetsByKey = new Map(
+ session.dragStates.map((dragState) => [dragState.key, dragState.target]),
+ );
+ return changes.flatMap((change): CanvasSequencePropChange[] => {
+ const target = targetsByKey.get(
+ Internals.makeSequencePropsSubscriptionKey(change.nodePath),
+ );
+ if (target === undefined) {
+ return [];
+ }
+
+ const base = {
+ nodePathInfo: target.nodePathInfo,
+ key: change.fieldKey,
+ value: change.value,
+ schema: change.schema,
+ };
+ return [
+ change.type === 'keyframed'
+ ? {...base, type: 'keyframe', frame: change.sourceFrame}
+ : {...base, type: 'static', defaultValue: target.fieldDefault ?? null},
+ ];
+ });
+};
+
+type MeasuredOutlines = {
+ readonly targets: readonly CanvasOutlineLayoutTarget[];
+ readonly outlinesByKey: ReadonlyMap<string, CanvasOutline>;
+};
+
+// Shared by every outline of the overlay; stable so outlines only re-render
+// for their own geometry and state.
+type OverlayEditing = {
+ readonly enabled: boolean;
+ readonly getScale: () => number;
+ readonly getCurrentFrame: () => number;
+ readonly getDragOverrides: GetDragOverrides;
+ readonly setDragOverrides: React.ContextType<
+ typeof Internals.VisualModeSettersContext
+ >['setDragOverrides'];
+ readonly clearDragOverrides: React.ContextType<
+ typeof Internals.VisualModeSettersContext
+ >['clearDragOverrides'];
+ readonly getTranslateTarget: (
+ selectableOutline: CanvasSelectableOutline,
+ ) => OverlayTranslateTarget | null;
+ /** The selected sources, including instances outside the current frame. */
+ readonly getSelectedTranslateTargets: () => OverlayTranslateTarget[];
+ readonly getSelectedOutlines: () => readonly CanvasOutline[];
+ readonly getSnapTargets: () => ReturnType<typeof getCanvasOutlineSnapTargets>;
+ readonly onDraggingChange: (dragging: boolean) => void;
+ readonly onSnapPointsChange: (
+ snapPoints: readonly CanvasOutlineSnapPoint[],
+ ) => void;
+ readonly commitChanges: (
+ changes: readonly CanvasOutlineDragChange[],
+ session: CanvasOutlineTranslateSession<OverlayTranslateTarget>,
+ ) => void;
+};
+
const CanvasOutlineElement = React.memo(
({
controller,
@@ -42,12 +217,16 @@ const CanvasOutlineElement = React.memo(
outline,
target,
selectableItems,
+ dragging,
+ editing,
}: {
readonly controller: CanvasController;
readonly containerRef: RefObject<SVGSVGElement | null>;
readonly outline: CanvasOutline;
- readonly target: ReturnType<typeof getCanvasOutlineLayoutTargets>[number];
+ readonly target: CanvasOutlineLayoutTarget;
readonly selectableItems: readonly CanvasSelectionItem[];
+ readonly dragging: boolean;
+ readonly editing: OverlayEditing;
}) => {
const {hovered, onPointerEnter, onPointerLeave} = useCanvasSequenceHover(
controller.hover,
@@ -80,26 +259,103 @@ const CanvasOutlineElement = React.memo(
}
containerRef.current?.focus({preventScroll: true});
- // A host with dragging may defer this selection until pointer release.
- if (decision.shouldUpdateSelection) {
+ const {
+ interaction,
+ shouldUpdateSelection,
+ deferSelection,
+ dragExistingSelection,
+ } = decision;
+ const select = () =>
controller.selection.select(
target.selection,
- decision.interaction,
+ interaction,
selectableItems,
);
+ // Clicking inside the selected group moves it; the clicked
+ // outline is selected on release if the pointer did not move.
+ if (!deferSelection && shouldUpdateSelection) {
+ select();
+ }
+
+ if (interaction.shiftKey || interaction.toggleKey) {
+ return;
+ }
+
+ const dragTargets = !editing.enabled
+ ? []
+ : dragExistingSelection
+ ? editing.getSelectedTranslateTargets()
+ : [editing.getTranslateTarget(target)].filter(
+ (dragTarget) => dragTarget !== null,
+ );
+ if (dragTargets.length === 0) {
+ if (deferSelection) {
+ select();
+ }
+
+ return;
}
+
+ const dragStates = getCanvasOutlineTranslateDragStates({
+ dragTargets,
+ getDragOverrides: editing.getDragOverrides,
+ timelinePosition: editing.getCurrentFrame(),
+ });
+ startCanvasOutlineTranslateDrag({
+ event,
+ captureTarget: event.currentTarget,
+ dragStates,
+ scale: editing.getScale(),
+ snapping: {
+ outlines: dragExistingSelection
+ ? editing.getSelectedOutlines()
+ : [outline],
+ getTargets: editing.getSnapTargets,
+ onSnapPointsChange: editing.onSnapPointsChange,
+ modifierDisablesSnapping: true,
+ },
+ setDragOverrides: editing.setDragOverrides,
+ clearDragOverrides: editing.clearDragOverrides,
+ onDragStart: () => {
+ editing.onDraggingChange(true);
+ controller.hover.clear('canvas');
+ },
+ onDragEnd: ({changes, dragged, released, session}) => {
+ if (dragged) {
+ editing.onDraggingChange(false);
+ }
+
+ if (changes.length === 0) {
+ if (deferSelection && !dragged && released) {
+ select();
+ }
+
+ return;
+ }
+
+ editing.commitChanges(changes, session);
+ },
+ });
},
- [containerRef, controller.selection, selectableItems, target],
+ [
+ containerRef,
+ controller.hover,
+ controller.selection,
+ editing,
+ outline,
+ selectableItems,
+ target,
+ ],
);
return (
<CanvasOutlinePolygon
outline={outline}
directlySelected={target.selected}
data-selected={target.selected}
- dragging={false}
+ dragging={dragging}
visible={target.showSelectedOutline || hovered}
interactive
- stroke="#0b84f3"
+ stroke={OUTLINE_COLOR}
fill="transparent"
onHoverChange={onHoverChange}
onPointerDown={onPointerDown}
@@ -118,6 +374,9 @@ const ActiveCanvasOutlines = React.memo(
sequences,
selectableItems,
measureAll,
+ dragging,
+ editing,
+ measuredRef,
}: {
readonly controller: CanvasController;
readonly containerRef: RefObject<SVGSVGElement | null>;
@@ -125,10 +384,16 @@ const ActiveCanvasOutlines = React.memo(
readonly sequences: readonly TSequence[];
readonly selectableItems: readonly CanvasSelectionItem[];
readonly measureAll: boolean;
+ readonly dragging: boolean;
+ readonly editing: OverlayEditing;
+ readonly measuredRef: React.MutableRefObject<MeasuredOutlines>;
}) => {
const frame = Internals.Timeline.useTimelinePosition();
const {selectedItems} = useCanvasSelection(controller.selection);
const hover = useCanvasHover(controller.hover);
+ const {getDragOverrides} = useContext(
+ Internals.VisualModeDragOverridesContext,
+ );
const selectedSequenceKeys = useMemo(
() => getCanvasSelectedSequenceKeys(selectedItems),
[selectedItems],
@@ -176,6 +441,8 @@ const ActiveCanvasOutlines = React.memo(
),
[runtimeControls, runtimeSnapshots],
);
+ // Overrides move and crop the elements; deriving the targets from them
+ // re-measures the outlines after each preview.
const targets = useMemo(
() =>
getCanvasOutlineLayoutTargets({
@@ -190,10 +457,26 @@ const ActiveCanvasOutlines = React.memo(
const values = target.sequence.controls
? (valuesByStore.get(target.sequence.controls.runtimeValues) ?? {})
: {};
- const cropValue = (key: string) =>
- typeof values[key] === 'number' && Number.isFinite(values[key])
- ? values[key]
+ const overrides =
+ target.registeredNodePathInfo === null
+ ? {}
+ : getDragOverrides(
+ target.registeredNodePathInfo.sequenceSubscriptionKey,
+ );
+ const cropValue = (key: string) => {
+ const override = Internals.resolveDragOverrideValue({
+ dragOverrideValue: overrides[key],
+ frame:
+ (frame - target.keyframeDisplayOffset) *
+ target.keyframePlaybackRate,
+ });
+ const value =
+ override.type === 'resolved' ? override.value : values[key];
+ return typeof value === 'number' && Number.isFinite(value)
+ ? value
: 0;
+ };
+
return {
...target,
crop: Internals.resolveSequenceCrop({
@@ -207,19 +490,24 @@ const ActiveCanvasOutlines = React.memo(
[
activeLayers,
frame,
+ getDragOverrides,
selectedSequenceKeys,
sequenceKeysContainingSelection,
valuesByStore,
],
);
- const {outlinesForRendering, targetsByKey} = useCanvasOutlines({
- containerRef,
- targets,
- sequences,
- hoverController: controller.hover,
- freezeOrder: false,
- updateOutlinesRef: null,
- });
+ const {outlinesForRendering, outlinesByKey, targetsByKey} =
+ useCanvasOutlines({
+ containerRef,
+ targets,
+ sequences,
+ hoverController: controller.hover,
+ freezeOrder: dragging,
+ updateOutlinesRef: null,
+ });
+ useLayoutEffect(() => {
+ measuredRef.current = {targets, outlinesByKey};
+ }, [measuredRef, outlinesByKey, targets]);
return (
<>
{outlinesForRendering.map((outline) => {
@@ -232,6 +520,8 @@ const ActiveCanvasOutlines = React.memo(
outline={outline}
target={target}
selectableItems={selectableItems}
+ dragging={dragging}
+ editing={editing}
/>
) : null;
})}
@@ -244,9 +534,13 @@ export const CanvasOutlineOverlay = React.memo(
({
controller,
resolveSequenceNodePathInfo,
+ onSequencePropsChange,
+ getSequencePropStatuses,
}: {
readonly controller: CanvasController;
readonly resolveSequenceNodePathInfo: CanvasSequenceNodePathResolver;
+ readonly onSequencePropsChange: CanvasSequencePropsChangeHandler | null;
+ readonly getSequencePropStatuses: CanvasSequencePropStatusResolver | null;
}) => {
const containerRef = useRef<SVGSVGElement | null>(null);
const [container, setContainer] = useState<SVGSVGElement | null>(null);
@@ -255,6 +549,13 @@ export const CanvasOutlineOverlay = React.memo(
setContainer(element);
}, []);
const [hovered, setHovered] = useState(false);
+ // The scale is captured when a drag starts; the snap lines are drawn
+ // in composition pixels and stay aligned for the whole gesture.
+ const [dragScale, setDragScale] = useState<number | null>(null);
+ const dragging = dragScale !== null;
+ const [snapPoints, setSnapPoints] = useState<
+ readonly CanvasOutlineSnapPoint[]
+ >([]);
const tracks = useSyncExternalStore(
controller.timeline.subscribe,
controller.timeline.getSnapshot,
@@ -262,6 +563,16 @@ export const CanvasOutlineOverlay = React.memo(
);
const selection = useCanvasSelection(controller.selection);
const hover = useCanvasHover(controller.hover);
+ const videoConfig = Internals.useUnsafeVideoConfig();
+ const compositionWidth = videoConfig?.width ?? 1;
+ const compositionHeight = videoConfig?.height ?? 1;
+ const {getCurrentFrame} = PlayerInternals.usePlayerMethods();
+ const {getDragOverrides} = useContext(
+ Internals.VisualModeDragOverridesContext,
+ );
+ const {setDragOverrides, clearDragOverrides} = useContext(
+ Internals.VisualModeSettersContext,
+ );
const sequences = useMemo(
() => tracks.map(({sequence}) => sequence),
[tracks],
@@ -326,9 +637,235 @@ export const CanvasOutlineOverlay = React.memo(
controller.hover.clear('canvas');
};
}, [controller.hover]);
+
+ // Gestures read the latest state through refs so the outline elements
+ // keep a stable editing object.
+ const latestRef = useRef({
+ selectableOutlines,
+ onSequencePropsChange,
+ getSequencePropStatuses,
+ compositionWidth,
+ compositionHeight,
+ getDragOverrides,
+ });
+ useLayoutEffect(() => {
+ latestRef.current = {
+ selectableOutlines,
+ onSequencePropsChange,
+ getSequencePropStatuses,
+ compositionWidth,
+ compositionHeight,
+ getDragOverrides,
+ };
+ }, [
+ compositionHeight,
+ compositionWidth,
+ getDragOverrides,
+ getSequencePropStatuses,
+ onSequencePropsChange,
+ selectableOutlines,
+ ]);
+ const measuredRef = useRef<MeasuredOutlines>({
+ targets: [],
+ outlinesByKey: new Map(),
+ });
+ const editingEnabled = onSequencePropsChange !== null;
+ const editing = useMemo((): OverlayEditing => {
+ const getLatestDragOverrides: GetDragOverrides = (nodePath) =>
+ latestRef.current.getDragOverrides(nodePath);
+ const getTranslateTarget = (selectableOutline: CanvasSelectableOutline) =>
+ getOverlayTranslateTarget({
+ selectableOutline,
+ getDragOverrides: getLatestDragOverrides,
+ getPropStatuses: latestRef.current.getSequencePropStatuses,
+ frame: getCurrentFrame(),
+ });
+ const getScale = () => {
+ const width = containerRef.current?.getBoundingClientRect().width;
+ return width ? width / latestRef.current.compositionWidth : 1;
+ };
+
+ return {
+ enabled: editingEnabled,
+ getScale,
+ getCurrentFrame,
+ getDragOverrides: getLatestDragOverrides,
+ setDragOverrides,
+ clearDragOverrides,
+ getTranslateTarget,
+ getSelectedTranslateTargets: () => {
+ const selectedKeys = getCanvasSequenceKeysContainingSelection(
+ controller.selection.getSnapshot().selectedItems,
+ );
+ // Instances of one source node share a value; move it once.
+ const targetsBySource = new Map<string, OverlayTranslateTarget>();
+ for (const selectableOutline of latestRef.current
+ .selectableOutlines) {
+ if (!selectedKeys.has(selectableOutline.key)) {
+ continue;
+ }
+
+ const dragTarget = getTranslateTarget(selectableOutline);
+ if (dragTarget === null) {
+ continue;
+ }
+
+ const sourceKey = Internals.makeSequencePropsSubscriptionKey(
+ dragTarget.nodePath,
+ );
+ if (!targetsBySource.has(sourceKey)) {
+ targetsBySource.set(sourceKey, dragTarget);
+ }
+ }
+
+ return [...targetsBySource.values()];
+ },
+ getSelectedOutlines: () => {
+ const {targets, outlinesByKey} = measuredRef.current;
+ return targets.flatMap((target) => {
+ if (
+ (!target.selected && !target.containsSelection) ||
+ getTranslateTarget(target) === null
+ ) {
+ return [];
+ }
+
+ const outline = outlinesByKey.get(target.key);
+ return outline === undefined ? [] : [outline];
+ });
+ },
+ getSnapTargets: () =>
+ getCanvasOutlineSnapTargets({
+ compositionWidth: latestRef.current.compositionWidth,
+ compositionHeight: latestRef.current.compositionHeight,
+ guides: [],
+ }),
+ onDraggingChange: (nextDragging) => {
+ setDragScale(nextDragging ? getScale() : null);
+ },
+ onSnapPointsChange: setSnapPoints,
+ commitChanges: (changes, session) => {
+ const handler = latestRef.current.onSequencePropsChange;
+ if (handler === null) {
+ clearCanvasOutlineDragOverrides({
+ clearDragOverrides,
+ dragStates: session.dragStates,
+ });
+ return;
+ }
+
+ handler(toSequencePropChanges(changes, session));
+ },
+ };
+ }, [
+ clearDragOverrides,
+ controller.selection,
+ editingEnabled,
+ getCurrentFrame,
+ setDragOverrides,
+ ]);
+
+ // Arrow keys nudge the selection by one pixel, ten with Shift. The
+ // values are committed when the key is released.
+ const nudgeSessionRef =
+ useRef<CanvasOutlineTranslateSession<OverlayTranslateTarget> | null>(
+ null,
+ );
+ const finishNudge = useCallback(() => {
+ const session = nudgeSessionRef.current;
+ if (session === null) {
+ return;
+ }
+
+ nudgeSessionRef.current = null;
+ const changes = getCanvasOutlineTranslateDragChanges({
+ dragStates: session.dragStates,
+ lastValues: session.lastValues,
+ });
+ if (changes.length === 0) {
+ clearCanvasOutlineDragOverrides({
+ clearDragOverrides,
+ dragStates: session.dragStates,
+ });
+ return;
+ }
+
+ editing.commitChanges(changes, session);
+ }, [clearDragOverrides, editing]);
+ useEffect(() => finishNudge, [finishNudge]);
+ const onKeyDown = useCallback(
+ (event: React.KeyboardEvent<SVGSVGElement>) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ event.stopPropagation();
+ controller.selection.clear();
+ return;
+ }
+
+ const direction = getCanvasOutlineNudgeDirection(event.key);
+ if (
+ direction === null ||
+ event.altKey ||
+ event.metaKey ||
+ event.ctrlKey ||
+ !editing.enabled
+ ) {
+ return;
+ }
+
+ const session =
+ nudgeSessionRef.current ??
+ (() => {
+ const dragTargets = editing.getSelectedTranslateTargets();
+ return dragTargets.length === 0
+ ? null
+ : createCanvasOutlineTranslateSession(
+ getCanvasOutlineTranslateDragStates({
+ dragTargets,
+ getDragOverrides: editing.getDragOverrides,
+ timelinePosition: editing.getCurrentFrame(),
+ }),
+ );
+ })();
+ if (session === null) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ nudgeSessionRef.current = session;
+ applyCanvasOutlineTranslateDelta({
+ session,
+ ...getCanvasOutlineNudgeDeltas({
+ deltaX: session.deltaX,
+ deltaY: session.deltaY,
+ direction,
+ shiftKey: event.shiftKey,
+ }),
+ setDragOverrides: editing.setDragOverrides,
+ });
+ },
+ [controller.selection, editing],
+ );
+ const onKeyUp = useCallback(
+ (event: React.KeyboardEvent<SVGSVGElement>) => {
+ if (
+ getCanvasOutlineNudgeDirection(event.key) === null ||
+ nudgeSessionRef.current === null
+ ) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ finishNudge();
+ },
+ [finishNudge],
+ );
+
const {measurementActive, measureAllOutlines} = getCanvasOutlineActivity({
canvasHovered: hovered,
- dragging: false,
+ dragging,
contextMenuOpen: false,
hasSelection: selection.selectedItems.some(
(item) => item.type !== 'guide',
@@ -360,13 +897,9 @@ export const CanvasOutlineOverlay = React.memo(
controller.selection.clear();
}}
onDoubleClick={(event) => event.stopPropagation()}
- onKeyDown={(event) => {
- if (event.key === 'Escape') {
- event.preventDefault();
- event.stopPropagation();
- controller.selection.clear();
- }
- }}
+ onKeyDown={onKeyDown}
+ onKeyUp={onKeyUp}
+ onBlur={finishNudge}
>
{measurementActive && container !== null ? (
<ActiveCanvasOutlines
@@ -376,8 +909,20 @@ export const CanvasOutlineOverlay = React.memo(
sequences={sequences}
selectableItems={selectableItems}
measureAll={measureAllOutlines}
+ dragging={dragging}
+ editing={editing}
+ measuredRef={measuredRef}
/>
) : null}
+ {dragScale === null ? null : (
+ <CanvasOutlineSnapLines
+ compositionHeight={compositionHeight}
+ compositionWidth={compositionWidth}
+ scale={dragScale}
+ snapPoints={snapPoints}
+ color={SNAP_COLOR}
+ />
+ )}
</svg>
);
},
diff --git a/packages/canvas/src/canvas-outline-snap-lines.tsx b/packages/canvas/src/canvas-outline-snap-lines.tsx
new file mode 100644
index 0000000000..7bb1c6a6ba
--- /dev/null
+++ b/packages/canvas/src/canvas-outline-snap-lines.tsx
@@ -0,0 +1,51 @@
+import React from 'react';
+import type {CanvasOutlineSnapPoint} from './outline-snap';
+
+export const CanvasOutlineSnapLines: React.FC<{
+ readonly compositionHeight: number;
+ readonly compositionWidth: number;
+ readonly scale: number;
+ readonly snapPoints: readonly CanvasOutlineSnapPoint[];
+ readonly color: string;
+}> = ({compositionHeight, compositionWidth, scale, snapPoints, color}) => {
+ if (snapPoints.length === 0) {
+ return null;
+ }
+
+ return (
+ <g pointerEvents="none">
+ {snapPoints.map((snapPoint) => {
+ const key = `${snapPoint.target.axis}-${snapPoint.target.type}-${snapPoint.target.position}-${snapPoint.edge}`;
+ if (snapPoint.target.axis === 'x') {
+ const x = snapPoint.target.position * scale;
+ return (
+ <line
+ key={key}
+ x1={x}
+ x2={x}
+ y1={0}
+ y2={compositionHeight * scale}
+ stroke={color}
+ strokeWidth={1}
+ vectorEffect="non-scaling-stroke"
+ />
+ );
+ }
+
+ const y = snapPoint.target.position * scale;
+ return (
+ <line
+ key={key}
+ x1={0}
+ x2={compositionWidth * scale}
+ y1={y}
+ y2={y}
+ stroke={color}
+ strokeWidth={1}
+ vectorEffect="non-scaling-stroke"
+ />
+ );
+ })}
+ </g>
+ );
+};
diff --git a/packages/canvas/src/canvas.tsx b/packages/canvas/src/canvas.tsx
index 29472d05d7..9f7febdf38 100644
--- a/packages/canvas/src/canvas.tsx
+++ b/packages/canvas/src/canvas.tsx
@@ -17,6 +17,10 @@ import {CanvasOutlineOverlay} from './canvas-outline-overlay';
import {installFiberCommitOrderObserver} from './install-fiber-sequence-order-observer';
import type {CanvasSequenceNodePathResolver} from './sequence-node-path';
import {getCanvasSequenceNodePathInfo} from './sequence-node-path';
+import type {
+ CanvasSequencePropsChangeHandler,
+ CanvasSequencePropStatusResolver,
+} from './sequence-props-change';
import {useSyncExternalStore} from './use-sync-external-store';
export type CanvasProps<
@@ -28,6 +32,18 @@ export type CanvasProps<
readonly showOutlines?: boolean;
/** Use the same resolver for your layer list and canvas selection. */
readonly resolveSequenceNodePathInfo?: CanvasSequenceNodePathResolver;
+ /**
+ * Enables moving selected outlines by dragging them or pressing the arrow
+ * keys. Called with the resulting prop values once a gesture ends; the
+ * values stay previewed through `controller.overrides` until you clear them.
+ */
+ readonly onSequencePropsChange?: CanvasSequencePropsChangeHandler;
+ /**
+ * How the props of a sequence are written in the source. Computed values
+ * cannot be moved, keyframed values receive a keyframe at the current frame.
+ * Without it, every value is treated as a static value.
+ */
+ readonly getSequencePropStatuses?: CanvasSequencePropStatusResolver;
};
// Rendered inside the Player so the controller can reach the Visual Mode
@@ -54,6 +70,8 @@ const CanvasFn = <
controller,
showOutlines = false,
resolveSequenceNodePathInfo = getCanvasSequenceNodePathInfo,
+ onSequencePropsChange,
+ getSequencePropStatuses,
...playerProps
}: CanvasProps<Schema, Props>,
ref: RefObject<PlayerRef>,
@@ -92,11 +110,19 @@ const CanvasFn = <
<CanvasOutlineOverlay
controller={controller}
resolveSequenceNodePathInfo={resolveSequenceNodePathInfo}
+ onSequencePropsChange={onSequencePropsChange ?? null}
+ getSequencePropStatuses={getSequencePropStatuses ?? null}
/>
) : null}
</>
),
- [controller, resolveSequenceNodePathInfo, showOutlines],
+ [
+ controller,
+ getSequencePropStatuses,
+ onSequencePropsChange,
+ resolveSequenceNodePathInfo,
+ showOutlines,
+ ],
);
return React.createElement(
diff --git a/packages/canvas/src/index.ts b/packages/canvas/src/index.ts
index defaf7fba7..26f6be1342 100644
--- a/packages/canvas/src/index.ts
+++ b/packages/canvas/src/index.ts
@@ -37,6 +37,11 @@ export type {
SequenceNodePathInfo,
TimelineTrackData,
} from './get-timeline-sequence-sort-key';
+export type {
+ CanvasSequencePropChange,
+ CanvasSequencePropsChangeHandler,
+ CanvasSequencePropStatusResolver,
+} from './sequence-props-change';
export type {
CanvasOutline,
CanvasOutlinePoint,
@@ -54,4 +59,27 @@ export type {
CanvasOutlineLayoutTarget,
TimelineLoopDisplay,
TimelineTrackWithOriginalTimings,
+ PointerSessionEndReason,
+ ParsedTranslate,
+ ParsedTranslateWithUnits,
+ TranslateUnit,
+ KeyframeSourceFrame,
+ CanvasOutlineSnapAxis,
+ CanvasOutlineSnapEdge,
+ CanvasOutlineSnapGuide,
+ CanvasOutlineSnapPoint,
+ CanvasOutlineSnapResult,
+ CanvasOutlineSnapTarget,
+ CanvasOutlineSnapTargetType,
+ CanvasOutlineDragChange,
+ CanvasOutlineKeyframedDragChange,
+ CanvasOutlineNudgeDirection,
+ CanvasOutlineStaticDragChange,
+ CanvasOutlineTranslateDragEnd,
+ CanvasOutlineTranslateDragSnapping,
+ CanvasOutlineTranslateDragState,
+ CanvasOutlineTranslatePropStatus,
+ CanvasOutlineTranslateSession,
+ CanvasOutlineTranslateTarget,
+ SetCanvasDragOverrides,
} from './canvas-internals';
diff --git a/packages/canvas/src/keyframe-frames.ts b/packages/canvas/src/keyframe-frames.ts
new file mode 100644
index 0000000000..a9c92fdcba
--- /dev/null
+++ b/packages/canvas/src/keyframe-frames.ts
@@ -0,0 +1,139 @@
+import type {CanUpdateSequencePropStatus} from 'remotion';
+
+export const getKeyframePlaybackRate = (
+ propStatus: CanUpdateSequencePropStatus | null | undefined,
+ keyframePlaybackRate: number,
+): number =>
+ keyframePlaybackRate *
+ (propStatus && propStatus.status !== 'computed'
+ ? (propStatus.keyframePlaybackRateAdjustment ?? 1)
+ : 1);
+
+export const getKeyframeLocalFrame = (
+ sourceFrame: number,
+ propStatus: CanUpdateSequencePropStatus,
+): number =>
+ propStatus.status === 'computed'
+ ? sourceFrame
+ : (sourceFrame + (propStatus.keyframeDisplayOffsetAdjustment ?? 0)) /
+ (propStatus.keyframePlaybackRateAdjustment ?? 1);
+
+// Keep display-clock inputs until the edited property is known, so resolving its
+// original source keyframe accounts for rounding introduced by the full offset.
+export type KeyframeSourceFrame =
+ | number
+ | {
+ readonly displayFrame: number;
+ readonly keyframeDisplayOffset: number;
+ readonly keyframePlaybackRate: number;
+ };
+
+export const getKeyframeSourceFrame = ({
+ displayFrame,
+ keyframeDisplayOffset,
+ keyframePlaybackRate,
+ propStatus,
+}: {
+ displayFrame: number;
+ keyframeDisplayOffset: number;
+ keyframePlaybackRate: number;
+ propStatus: CanUpdateSequencePropStatus | null;
+}): number => {
+ const playbackRate = getKeyframePlaybackRate(
+ propStatus,
+ keyframePlaybackRate,
+ );
+ const sourceFrame = (displayFrame - keyframeDisplayOffset) * playbackRate;
+ if (propStatus?.status !== 'keyframed') {
+ return sourceFrame;
+ }
+
+ // Converting a displayed keyframe back to source frames may introduce rounding
+ // error. Resolve its original frame so edits keep the existing keyframe identity,
+ // including when source keyframes themselves have fractional frames.
+ const tolerance =
+ Number.EPSILON *
+ Math.max(1, Math.abs(displayFrame), Math.abs(keyframeDisplayOffset)) *
+ playbackRate *
+ 8;
+ let closestFrame = sourceFrame;
+ let closestDistance = Infinity;
+ for (const keyframe of propStatus.keyframes) {
+ const distance = Math.abs(keyframe.frame - sourceFrame);
+ if (distance <= tolerance && distance < closestDistance) {
+ closestFrame = keyframe.frame;
+ closestDistance = distance;
+ }
+ }
+
+ return closestFrame;
+};
+
+export const resolveKeyframeSourceFrame = (
+ sourceFrame: KeyframeSourceFrame,
+ propStatus: CanUpdateSequencePropStatus | null,
+): number => {
+ return getKeyframeSourceFrame({
+ ...(typeof sourceFrame === 'number'
+ ? {
+ displayFrame: sourceFrame,
+ keyframeDisplayOffset: 0,
+ keyframePlaybackRate: 1 / getKeyframePlaybackRate(propStatus, 1),
+ }
+ : sourceFrame),
+ propStatus,
+ });
+};
+
+export const getKeyframeDisplayOffset = ({
+ propStatus,
+ keyframeDisplayOffset,
+ keyframePlaybackRate,
+}: {
+ propStatus: CanUpdateSequencePropStatus | null | undefined;
+ keyframeDisplayOffset: number;
+ keyframePlaybackRate: number;
+}): number => {
+ return (
+ keyframeDisplayOffset +
+ (propStatus?.status === 'keyframed' || propStatus?.status === 'static'
+ ? propStatus.keyframeDisplayOffsetAdjustment === null
+ ? 0
+ : propStatus.keyframeDisplayOffsetAdjustment /
+ getKeyframePlaybackRate(propStatus, keyframePlaybackRate)
+ : 0)
+ );
+};
+
+export const getTimelineKeyframes = (
+ propStatus: CanUpdateSequencePropStatus | null | undefined,
+ keyframeDisplayOffset = 0,
+ keyframePlaybackRate = 1,
+): {frame: number; value: unknown}[] => {
+ if (!propStatus) {
+ return [];
+ }
+
+ if (propStatus.status !== 'keyframed') {
+ return [];
+ }
+
+ const {keyframes} = propStatus;
+ const playbackRate = getKeyframePlaybackRate(
+ propStatus,
+ keyframePlaybackRate,
+ );
+ const resolvedKeyframeDisplayOffset = getKeyframeDisplayOffset({
+ propStatus,
+ keyframeDisplayOffset,
+ keyframePlaybackRate,
+ });
+ if (resolvedKeyframeDisplayOffset === 0 && playbackRate === 1) {
+ return keyframes;
+ }
+
+ return keyframes.map((keyframe) => ({
+ ...keyframe,
+ frame: keyframe.frame / playbackRate + resolvedKeyframeDisplayOffset,
+ }));
+};
diff --git a/packages/canvas/src/outline-snap.ts b/packages/canvas/src/outline-snap.ts
new file mode 100644
index 0000000000..03bb9f5d93
--- /dev/null
+++ b/packages/canvas/src/outline-snap.ts
@@ -0,0 +1,256 @@
+import type {CanvasOutline} from './outline-geometry';
+
+export const canvasOutlineSnapThresholdPx = 10;
+
+export type CanvasOutlineSnapAxis = 'x' | 'y';
+
+export type CanvasOutlineSnapTargetType =
+ | 'canvas-left'
+ | 'canvas-right'
+ | 'canvas-top'
+ | 'canvas-bottom'
+ | 'canvas-horizontal-center'
+ | 'canvas-vertical-center'
+ | 'guide-vertical'
+ | 'guide-horizontal';
+
+export type CanvasOutlineSnapTarget = {
+ readonly axis: CanvasOutlineSnapAxis;
+ readonly position: number;
+ readonly type: CanvasOutlineSnapTargetType;
+};
+
+/** A host-defined line in composition pixels that outlines snap to. */
+export type CanvasOutlineSnapGuide = {
+ readonly orientation: 'horizontal' | 'vertical';
+ readonly position: number;
+ readonly show: boolean;
+};
+
+export type CanvasOutlineSnapEdge =
+ | 'left'
+ | 'right'
+ | 'center-x'
+ | 'top'
+ | 'bottom'
+ | 'center-y';
+
+export type CanvasOutlineSnapPoint = {
+ readonly distance: number;
+ readonly edge: CanvasOutlineSnapEdge;
+ readonly target: CanvasOutlineSnapTarget;
+};
+
+export type CanvasOutlineSnapResult = {
+ readonly activeSnapPoints: readonly CanvasOutlineSnapPoint[];
+ readonly snapOffsetX: number | null;
+ readonly snapOffsetY: number | null;
+};
+
+type EdgeCheck = {
+ readonly edge: CanvasOutlineSnapEdge;
+ readonly position: number;
+};
+
+const EPSILON = 0.000001;
+
+export const getCanvasOutlineSnapTargets = ({
+ compositionHeight,
+ compositionWidth,
+ guides,
+}: {
+ readonly compositionHeight: number;
+ readonly compositionWidth: number;
+ readonly guides: readonly CanvasOutlineSnapGuide[];
+}): readonly CanvasOutlineSnapTarget[] => {
+ return [
+ {axis: 'x', position: 0, type: 'canvas-left'},
+ {
+ axis: 'x',
+ position: compositionWidth / 2,
+ type: 'canvas-horizontal-center',
+ },
+ {axis: 'x', position: compositionWidth, type: 'canvas-right'},
+ {axis: 'y', position: 0, type: 'canvas-top'},
+ {
+ axis: 'y',
+ position: compositionHeight / 2,
+ type: 'canvas-vertical-center',
+ },
+ {axis: 'y', position: compositionHeight, type: 'canvas-bottom'},
+ ...guides.flatMap((guide): CanvasOutlineSnapTarget[] => {
+ if (!guide.show) {
+ return [];
+ }
+
+ return [
+ guide.orientation === 'vertical'
+ ? {
+ axis: 'x',
+ position: guide.position,
+ type: 'guide-vertical',
+ }
+ : {
+ axis: 'y',
+ position: guide.position,
+ type: 'guide-horizontal',
+ },
+ ];
+ }),
+ ];
+};
+
+const canSnapEdgeToTarget = (
+ edge: CanvasOutlineSnapEdge,
+ target: CanvasOutlineSnapTarget,
+): boolean => {
+ if (target.type === 'canvas-horizontal-center') {
+ return edge === 'center-x';
+ }
+
+ if (target.type === 'canvas-vertical-center') {
+ return edge === 'center-y';
+ }
+
+ if (target.type === 'canvas-left' || target.type === 'canvas-right') {
+ return edge === 'left' || edge === 'right';
+ }
+
+ if (target.type === 'guide-vertical') {
+ return edge === 'left' || edge === 'right' || edge === 'center-x';
+ }
+
+ if (target.type === 'canvas-top' || target.type === 'canvas-bottom') {
+ return edge === 'top' || edge === 'bottom';
+ }
+
+ return edge === 'top' || edge === 'bottom' || edge === 'center-y';
+};
+
+const findBestSnapForAxis = ({
+ edges,
+ targets,
+ threshold,
+}: {
+ readonly edges: readonly EdgeCheck[];
+ readonly targets: readonly CanvasOutlineSnapTarget[];
+ readonly threshold: number;
+}): {
+ readonly offset: number;
+ readonly snapPoint: CanvasOutlineSnapPoint;
+} | null => {
+ let bestDistance = Infinity;
+ let bestSnaps: {
+ readonly offset: number;
+ readonly snapPoint: CanvasOutlineSnapPoint;
+ }[] = [];
+
+ for (const target of targets) {
+ for (const edge of edges) {
+ if (!canSnapEdgeToTarget(edge.edge, target)) {
+ continue;
+ }
+
+ const distance = Math.abs(edge.position - target.position);
+ if (distance > threshold || distance > bestDistance + EPSILON) {
+ continue;
+ }
+
+ if (distance < bestDistance - EPSILON) {
+ bestSnaps = [];
+ bestDistance = distance;
+ }
+
+ bestSnaps.push({
+ offset: target.position - edge.position,
+ snapPoint: {
+ distance,
+ edge: edge.edge,
+ target,
+ },
+ });
+ }
+ }
+
+ if (bestSnaps.length > 1) {
+ const centerSnap = bestSnaps.find(
+ (snap) =>
+ snap.snapPoint.target.type === 'canvas-horizontal-center' ||
+ snap.snapPoint.target.type === 'canvas-vertical-center',
+ );
+ if (centerSnap) {
+ return centerSnap;
+ }
+ }
+
+ return bestSnaps[0] ?? null;
+};
+
+/**
+ * Finds the closest snap for the bounding box of the outlines after moving
+ * them by the delta. Outlines are in overlay pixels, deltas and the result in
+ * composition pixels.
+ */
+export const findCanvasOutlineSnap = ({
+ allowX,
+ allowY,
+ deltaX,
+ deltaY,
+ outlines,
+ scale,
+ targets,
+}: {
+ readonly allowX: boolean;
+ readonly allowY: boolean;
+ readonly deltaX: number;
+ readonly deltaY: number;
+ readonly outlines: readonly CanvasOutline[];
+ readonly scale: number;
+ readonly targets: readonly CanvasOutlineSnapTarget[];
+}): CanvasOutlineSnapResult => {
+ if (outlines.length === 0) {
+ return {
+ activeSnapPoints: [],
+ snapOffsetX: null,
+ snapOffsetY: null,
+ };
+ }
+
+ const points = outlines.flatMap((outline) => outline.points);
+ const left = Math.min(...points.map((point) => point.x)) / scale + deltaX;
+ const right = Math.max(...points.map((point) => point.x)) / scale + deltaX;
+ const top = Math.min(...points.map((point) => point.y)) / scale + deltaY;
+ const bottom = Math.max(...points.map((point) => point.y)) / scale + deltaY;
+ const threshold = canvasOutlineSnapThresholdPx / scale;
+ const snapX = allowX
+ ? findBestSnapForAxis({
+ edges: [
+ {edge: 'left', position: left},
+ {edge: 'center-x', position: left + (right - left) / 2},
+ {edge: 'right', position: right},
+ ],
+ targets: targets.filter((target) => target.axis === 'x'),
+ threshold,
+ })
+ : null;
+ const snapY = allowY
+ ? findBestSnapForAxis({
+ edges: [
+ {edge: 'top', position: top},
+ {edge: 'center-y', position: top + (bottom - top) / 2},
+ {edge: 'bottom', position: bottom},
+ ],
+ targets: targets.filter((target) => target.axis === 'y'),
+ threshold,
+ })
+ : null;
+
+ return {
+ activeSnapPoints: [
+ snapX?.snapPoint ?? null,
+ snapY?.snapPoint ?? null,
+ ].filter((snapPoint) => snapPoint !== null),
+ snapOffsetX: snapX?.offset ?? null,
+ snapOffsetY: snapY?.offset ?? null,
+ };
+};
diff --git a/packages/canvas/src/outline-targets.ts b/packages/canvas/src/outline-targets.ts
index 35f10180cf..304513f879 100644
--- a/packages/canvas/src/outline-targets.ts
+++ b/packages/canvas/src/outline-targets.ts
@@ -17,7 +17,10 @@ export type CanvasSelectableOutline = {
readonly keyframeDisplayOffset: number;
readonly keyframePlaybackRate: number;
readonly key: string;
+ /** The identity used for selection and hover, from the resolver. */
readonly nodePathInfo: SequenceNodePathInfo;
+ /** The source node registered with `setSequenceNodePaths()`, which overrides require. */
+ readonly registeredNodePathInfo: SequenceNodePathInfo | null;
readonly sequence: TSequence;
};
@@ -78,6 +81,7 @@ export const getCanvasSelectableOutlines = ({
keyframePlaybackRate: track.keyframePlaybackRate,
key: getCanvasSequenceSelectionKey(nodePathInfo),
nodePathInfo,
+ registeredNodePathInfo: track.nodePathInfo,
sequence,
},
];
diff --git a/packages/canvas/src/outline-translate-drag.ts b/packages/canvas/src/outline-translate-drag.ts
new file mode 100644
index 0000000000..0e7e9de5fb
--- /dev/null
+++ b/packages/canvas/src/outline-translate-drag.ts
@@ -0,0 +1,579 @@
+import type {
+ CanUpdateSequencePropStatusKeyframed,
+ CanUpdateSequencePropStatusStatic,
+ DragOverrideValue,
+ GetDragOverrides,
+ InteractivitySchema,
+ SequencePropsSubscriptionKey,
+} from 'remotion';
+import {Internals} from 'remotion';
+import {getKeyframeLocalFrame, getKeyframeSourceFrame} from './keyframe-frames';
+import type {CanvasOutline} from './outline-geometry';
+import {
+ findCanvasOutlineSnap,
+ type CanvasOutlineSnapPoint,
+ type CanvasOutlineSnapTarget,
+} from './outline-snap';
+import {
+ isPointerSessionRelease,
+ startCapturedPointerSession,
+} from './pointer-session';
+import {parseTranslate, serializeTranslate} from './translate-value';
+
+export const canvasTranslateFieldKey = 'style.translate';
+export const canvasOutlineDragThresholdPx = 4;
+
+export type CanvasOutlineTranslatePropStatus =
+ | CanUpdateSequencePropStatusStatic
+ | CanUpdateSequencePropStatusKeyframed;
+
+/** A sequence whose `style.translate` is moved by a drag or a keyboard nudge. */
+export type CanvasOutlineTranslateTarget = {
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly schema: InteractivitySchema;
+ readonly fieldDefault: string | undefined;
+ /**
+ * How the translate prop is written in the source. `null` when the source
+ * is unknown: the movement then starts from the runtime value and results
+ * in a static value.
+ */
+ readonly propStatus: CanvasOutlineTranslatePropStatus | null;
+ /** The translate prop of the mounted element, the origin when `propStatus` is null. */
+ readonly runtimeValue: unknown;
+ readonly keyframeDisplayOffset: number;
+ readonly keyframePlaybackRate: number;
+};
+
+export type CanvasOutlineTranslateDragState<
+ Target extends CanvasOutlineTranslateTarget = CanvasOutlineTranslateTarget,
+> = {
+ readonly defaultValue: string | null;
+ readonly key: string;
+ readonly sourceFrame: number;
+ readonly startX: number;
+ readonly startY: number;
+ readonly startZ: number | null;
+ readonly target: Target;
+};
+
+export type CanvasOutlineStaticDragChange = {
+ readonly type: 'static';
+ readonly fileName: string;
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly fieldKey: string;
+ readonly value: unknown;
+ readonly defaultValue: string | null;
+ readonly schema: InteractivitySchema;
+};
+
+export type CanvasOutlineKeyframedDragChange = {
+ readonly type: 'keyframed';
+ readonly fileName: string;
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly fieldKey: string;
+ readonly sourceFrame: number;
+ readonly value: unknown;
+ readonly schema: InteractivitySchema;
+};
+
+export type CanvasOutlineDragChange =
+ | CanvasOutlineStaticDragChange
+ | CanvasOutlineKeyframedDragChange;
+
+export const getCanvasOutlineTranslateDragStates = <
+ Target extends CanvasOutlineTranslateTarget,
+>({
+ dragTargets,
+ getDragOverrides,
+ timelinePosition,
+}: {
+ readonly dragTargets: readonly Target[];
+ readonly getDragOverrides: GetDragOverrides;
+ readonly timelinePosition: number;
+}): CanvasOutlineTranslateDragState<Target>[] => {
+ return dragTargets.map((target) => {
+ const dragOverrideValue = (getDragOverrides(target.nodePath) ?? {})[
+ canvasTranslateFieldKey
+ ];
+ const sourceFrame = getKeyframeSourceFrame({
+ displayFrame: timelinePosition,
+ keyframeDisplayOffset: target.keyframeDisplayOffset,
+ keyframePlaybackRate: target.keyframePlaybackRate,
+ propStatus: target.propStatus,
+ });
+ let effectiveValue: unknown;
+ if (target.propStatus === null) {
+ const dragOverride = Internals.resolveDragOverrideValue({
+ dragOverrideValue,
+ frame: sourceFrame,
+ });
+ effectiveValue =
+ dragOverride.type === 'resolved'
+ ? dragOverride.value
+ : (target.runtimeValue ?? target.fieldDefault);
+ } else {
+ effectiveValue = Internals.getEffectiveVisualModeValue({
+ propStatus: target.propStatus,
+ dragOverrideValue,
+ defaultValue: target.fieldDefault,
+ frame: getKeyframeLocalFrame(sourceFrame, target.propStatus),
+ shouldResortToDefaultValueIfUndefined: true,
+ });
+ }
+
+ const [startX, startY, startZ] = parseTranslate(
+ String(effectiveValue ?? '0px 0px'),
+ );
+
+ return {
+ defaultValue:
+ target.fieldDefault !== undefined
+ ? JSON.stringify(target.fieldDefault)
+ : null,
+ key: Internals.makeSequencePropsSubscriptionKey(target.nodePath),
+ sourceFrame,
+ startX,
+ startY,
+ startZ,
+ target,
+ };
+ });
+};
+
+export const getCanvasOutlineTranslateDragValues = ({
+ dragStates,
+ deltaX,
+ deltaY,
+}: {
+ readonly dragStates: readonly CanvasOutlineTranslateDragState[];
+ readonly deltaX: number;
+ readonly deltaY: number;
+}): Map<string, string> => {
+ return new Map(
+ dragStates.map((dragState) => [
+ dragState.key,
+ serializeTranslate([
+ dragState.startX + deltaX,
+ dragState.startY + deltaY,
+ dragState.startZ,
+ ]),
+ ]),
+ );
+};
+
+export const applyCanvasOutlineDragAxisLock = ({
+ deltaX,
+ deltaY,
+ axisLocked,
+}: {
+ readonly deltaX: number;
+ readonly deltaY: number;
+ readonly axisLocked: boolean;
+}) => {
+ if (!axisLocked) {
+ return {deltaX, deltaY};
+ }
+
+ if (Math.abs(deltaX) >= Math.abs(deltaY)) {
+ return {deltaX, deltaY: 0};
+ }
+
+ return {deltaX: 0, deltaY};
+};
+
+export const isCanvasOutlineDragPastThreshold = ({
+ deltaX,
+ deltaY,
+}: {
+ readonly deltaX: number;
+ readonly deltaY: number;
+}) => {
+ return Math.hypot(deltaX, deltaY) >= canvasOutlineDragThresholdPx;
+};
+
+export const getCanvasOutlineTranslateDragChanges = ({
+ dragStates,
+ lastValues,
+}: {
+ readonly dragStates: readonly CanvasOutlineTranslateDragState[];
+ readonly lastValues: ReadonlyMap<string, string>;
+}): CanvasOutlineDragChange[] => {
+ const changes: CanvasOutlineDragChange[] = [];
+
+ for (const dragState of dragStates) {
+ const value = lastValues.get(dragState.key);
+ if (value === undefined) {
+ continue;
+ }
+
+ const {propStatus} = dragState.target;
+ if (propStatus?.status === 'keyframed') {
+ const startValue = serializeTranslate([
+ dragState.startX,
+ dragState.startY,
+ dragState.startZ,
+ ]);
+ if (value === startValue) {
+ continue;
+ }
+
+ changes.push({
+ type: 'keyframed',
+ fileName: dragState.target.nodePath.absolutePath,
+ nodePath: dragState.target.nodePath,
+ fieldKey: canvasTranslateFieldKey,
+ sourceFrame: dragState.sourceFrame,
+ value,
+ schema: dragState.target.schema,
+ });
+ continue;
+ }
+
+ const currentValue =
+ propStatus === null
+ ? dragState.target.runtimeValue
+ : propStatus.codeValue;
+ const shouldSave =
+ value !== currentValue &&
+ !(
+ dragState.defaultValue === JSON.stringify(value) &&
+ currentValue === undefined
+ );
+
+ if (!shouldSave) {
+ continue;
+ }
+
+ changes.push({
+ type: 'static',
+ fileName: dragState.target.nodePath.absolutePath,
+ nodePath: dragState.target.nodePath,
+ fieldKey: canvasTranslateFieldKey,
+ value,
+ defaultValue: dragState.defaultValue,
+ schema: dragState.target.schema,
+ });
+ }
+
+ return changes;
+};
+
+export const clearCanvasOutlineDragOverrides = ({
+ clearDragOverrides,
+ dragStates,
+}: {
+ readonly clearDragOverrides: (nodePath: SequencePropsSubscriptionKey) => void;
+ readonly dragStates: readonly {
+ readonly target: {readonly nodePath: SequencePropsSubscriptionKey};
+ }[];
+}) => {
+ for (const dragState of dragStates) {
+ clearDragOverrides(dragState.target.nodePath);
+ }
+};
+
+export type CanvasOutlineNudgeDirection = 'left' | 'right' | 'up' | 'down';
+
+export const getCanvasOutlineNudgeDirection = (
+ key: string,
+): CanvasOutlineNudgeDirection | null => {
+ if (key === 'ArrowLeft') {
+ return 'left';
+ }
+
+ if (key === 'ArrowRight') {
+ return 'right';
+ }
+
+ if (key === 'ArrowUp') {
+ return 'up';
+ }
+
+ if (key === 'ArrowDown') {
+ return 'down';
+ }
+
+ return null;
+};
+
+export const getCanvasOutlineNudgeDelta = ({
+ direction,
+ shiftKey,
+}: {
+ readonly direction: CanvasOutlineNudgeDirection;
+ readonly shiftKey: boolean;
+}) => {
+ const increment = shiftKey ? 10 : 1;
+ return direction === 'left' || direction === 'up' ? -increment : increment;
+};
+
+export const getCanvasOutlineNudgeDeltas = ({
+ deltaX,
+ deltaY,
+ direction,
+ shiftKey,
+}: {
+ readonly deltaX: number;
+ readonly deltaY: number;
+ readonly direction: CanvasOutlineNudgeDirection;
+ readonly shiftKey: boolean;
+}) => {
+ const delta = getCanvasOutlineNudgeDelta({direction, shiftKey});
+
+ if (direction === 'left' || direction === 'right') {
+ return {deltaX: deltaX + delta, deltaY};
+ }
+
+ return {deltaX, deltaY: deltaY + delta};
+};
+
+/** The accumulated movement of one drag or one run of keyboard nudges. */
+export type CanvasOutlineTranslateSession<
+ Target extends CanvasOutlineTranslateTarget = CanvasOutlineTranslateTarget,
+> = {
+ readonly dragStates: readonly CanvasOutlineTranslateDragState<Target>[];
+ deltaX: number;
+ deltaY: number;
+ lastValues: ReadonlyMap<string, string>;
+};
+
+export const createCanvasOutlineTranslateSession = <
+ Target extends CanvasOutlineTranslateTarget,
+>(
+ dragStates: readonly CanvasOutlineTranslateDragState<Target>[],
+): CanvasOutlineTranslateSession<Target> => ({
+ dragStates,
+ deltaX: 0,
+ deltaY: 0,
+ lastValues: new Map(),
+});
+
+export type SetCanvasDragOverrides = (
+ nodePath: SequencePropsSubscriptionKey,
+ key: string,
+ value: DragOverrideValue,
+) => void;
+
+/** Moves every sequence of the session and previews the values through overrides. */
+export const applyCanvasOutlineTranslateDelta = ({
+ session,
+ deltaX,
+ deltaY,
+ setDragOverrides,
+}: {
+ readonly session: CanvasOutlineTranslateSession;
+ readonly deltaX: number;
+ readonly deltaY: number;
+ readonly setDragOverrides: SetCanvasDragOverrides;
+}) => {
+ session.deltaX = deltaX;
+ session.deltaY = deltaY;
+ session.lastValues = getCanvasOutlineTranslateDragValues({
+ dragStates: session.dragStates,
+ deltaX,
+ deltaY,
+ });
+ for (const dragState of session.dragStates) {
+ const value = session.lastValues.get(dragState.key);
+ if (value === undefined) {
+ throw new Error('Expected drag value to be available');
+ }
+
+ const {propStatus} = dragState.target;
+ setDragOverrides(
+ dragState.target.nodePath,
+ canvasTranslateFieldKey,
+ propStatus?.status === 'keyframed'
+ ? Internals.makeKeyframedDragOverride({
+ status: propStatus,
+ frame: dragState.sourceFrame,
+ value,
+ })
+ : Internals.makeStaticDragOverride(value),
+ );
+ }
+};
+
+export type CanvasOutlineTranslateDragSnapping = {
+ /** The outlines being moved, in overlay pixels. */
+ readonly outlines: readonly CanvasOutline[];
+ readonly getTargets: () => readonly CanvasOutlineSnapTarget[];
+ readonly onSnapPointsChange: (
+ snapPoints: readonly CanvasOutlineSnapPoint[],
+ ) => void;
+ /** Whether holding Command or Ctrl while dragging bypasses snapping. */
+ readonly modifierDisablesSnapping: boolean;
+};
+
+export type CanvasOutlineTranslateDragEnd<
+ Target extends CanvasOutlineTranslateTarget,
+> = {
+ /**
+ * The values that differ from the source. Empty when the pointer did not
+ * move past the drag threshold or returned to the start; the overrides
+ * are cleared in that case. Otherwise, persist the changes and clear the
+ * overrides with `clearCanvasOutlineDragOverrides()`.
+ */
+ readonly changes: readonly CanvasOutlineDragChange[];
+ readonly dragged: boolean;
+ /** False when the gesture was cancelled, e.g. by the window losing focus. */
+ readonly released: boolean;
+ readonly session: CanvasOutlineTranslateSession<Target>;
+};
+
+/**
+ * Moves the sequences of the drag states with the pointer. Shift locks the
+ * dominant axis, the movement starts after `canvasOutlineDragThresholdPx`.
+ * Returns a function that cancels the gesture.
+ */
+export const startCanvasOutlineTranslateDrag = <
+ Target extends CanvasOutlineTranslateTarget,
+>({
+ event,
+ captureTarget,
+ dragStates,
+ scale,
+ snapping,
+ setDragOverrides,
+ clearDragOverrides,
+ onDragStart,
+ onDragEnd,
+}: {
+ readonly event: Pick<
+ PointerEvent,
+ 'button' | 'pointerId' | 'clientX' | 'clientY' | 'metaKey' | 'ctrlKey'
+ >;
+ readonly captureTarget: Element;
+ readonly dragStates: readonly CanvasOutlineTranslateDragState<Target>[];
+ /** Overlay pixels per composition pixel. */
+ readonly scale: number;
+ readonly snapping: CanvasOutlineTranslateDragSnapping | null;
+ readonly setDragOverrides: SetCanvasDragOverrides;
+ readonly clearDragOverrides: (nodePath: SequencePropsSubscriptionKey) => void;
+ readonly onDragStart: () => void;
+ readonly onDragEnd: (end: CanvasOutlineTranslateDragEnd<Target>) => void;
+}): (() => void) => {
+ const session = createCanvasOutlineTranslateSession(dragStates);
+ const startPointerX = event.clientX;
+ const startPointerY = event.clientY;
+ let currentPointerX = startPointerX;
+ let currentPointerY = startPointerY;
+ let axisLocked = false;
+ let dragStarted = false;
+ let snappingDisabled =
+ snapping?.modifierDisablesSnapping === true &&
+ (event.metaKey || event.ctrlKey);
+ let snapTargets: readonly CanvasOutlineSnapTarget[] | null = null;
+
+ const update = () => {
+ const screenDeltaX = currentPointerX - startPointerX;
+ const screenDeltaY = currentPointerY - startPointerY;
+ if (!dragStarted) {
+ if (
+ !isCanvasOutlineDragPastThreshold({
+ deltaX: screenDeltaX,
+ deltaY: screenDeltaY,
+ })
+ ) {
+ return;
+ }
+
+ dragStarted = true;
+ onDragStart();
+ }
+
+ const axisLockedDirection = axisLocked
+ ? Math.abs(screenDeltaX) >= Math.abs(screenDeltaY)
+ ? 'horizontal'
+ : 'vertical'
+ : null;
+ let {deltaX, deltaY} = applyCanvasOutlineDragAxisLock({
+ deltaX: screenDeltaX / scale,
+ deltaY: screenDeltaY / scale,
+ axisLocked,
+ });
+
+ if (snapping !== null && !snappingDisabled) {
+ snapTargets ??= snapping.getTargets();
+ const snapResult = findCanvasOutlineSnap({
+ allowX: axisLockedDirection !== 'vertical',
+ allowY: axisLockedDirection !== 'horizontal',
+ deltaX,
+ deltaY,
+ outlines: snapping.outlines,
+ scale,
+ targets: snapTargets,
+ });
+ deltaX += snapResult.snapOffsetX ?? 0;
+ deltaY += snapResult.snapOffsetY ?? 0;
+ snapping.onSnapPointsChange(snapResult.activeSnapPoints);
+ } else {
+ snapping?.onSnapPointsChange([]);
+ }
+
+ applyCanvasOutlineTranslateDelta({
+ session,
+ deltaX,
+ deltaY,
+ setDragOverrides,
+ });
+ };
+
+ const onKeyChange = (keyEvent: KeyboardEvent) => {
+ if (keyEvent.key !== 'Shift') {
+ return;
+ }
+
+ const nextAxisLocked = keyEvent.type === 'keydown';
+ if (nextAxisLocked === axisLocked) {
+ return;
+ }
+
+ axisLocked = nextAxisLocked;
+ update();
+ };
+
+ const end = startCapturedPointerSession({
+ event,
+ captureTarget,
+ onMove: (moveEvent) => {
+ moveEvent.preventDefault();
+ currentPointerX = moveEvent.clientX;
+ currentPointerY = moveEvent.clientY;
+ axisLocked = moveEvent.shiftKey;
+ snappingDisabled =
+ snapping?.modifierDisablesSnapping === true &&
+ (moveEvent.metaKey || moveEvent.ctrlKey);
+ update();
+ },
+ onEnd: (reason, endEvent) => {
+ window.removeEventListener('keydown', onKeyChange);
+ window.removeEventListener('keyup', onKeyChange);
+ if (dragStarted) {
+ snapping?.onSnapPointsChange([]);
+ }
+
+ const changes = getCanvasOutlineTranslateDragChanges({
+ dragStates: session.dragStates,
+ lastValues: session.lastValues,
+ });
+ if (changes.length === 0) {
+ clearCanvasOutlineDragOverrides({
+ clearDragOverrides,
+ dragStates: session.dragStates,
+ });
+ }
+
+ onDragEnd({
+ changes,
+ dragged: dragStarted,
+ released: isPointerSessionRelease(reason, endEvent),
+ session,
+ });
+ },
+ });
+ window.addEventListener('keydown', onKeyChange);
+ window.addEventListener('keyup', onKeyChange);
+
+ return end;
+};
diff --git a/packages/canvas/src/pointer-session.ts b/packages/canvas/src/pointer-session.ts
new file mode 100644
index 0000000000..1d18b78924
--- /dev/null
+++ b/packages/canvas/src/pointer-session.ts
@@ -0,0 +1,221 @@
+export type PointerSessionEndReason =
+ | 'pointerup'
+ | 'pointercancel'
+ | 'lostpointercapture'
+ | 'blur'
+ | 'visibilitychange'
+ | 'buttons-released'
+ | 'manual';
+
+export const isPointerSessionRelease = (
+ reason: PointerSessionEndReason,
+ event: PointerEvent | null,
+): event is PointerEvent => {
+ if (event === null) {
+ return false;
+ }
+
+ return (
+ reason === 'pointerup' ||
+ reason === 'buttons-released' ||
+ (reason === 'lostpointercapture' && event.buttons === 0)
+ );
+};
+
+type PointerSessionEvent = Pick<PointerEvent, 'button' | 'pointerId'>;
+
+const getButtonMask = (button: number) => {
+ if (button === 0) {
+ return 1;
+ }
+
+ if (button === 1) {
+ return 4;
+ }
+
+ if (button === 2) {
+ return 2;
+ }
+
+ return 1 << button;
+};
+
+const startPointerSession = ({
+ event,
+ captureTarget,
+ onMove,
+ onEnd,
+}: {
+ event: PointerSessionEvent;
+ captureTarget: Element | null;
+ onMove?: (
+ event: PointerEvent,
+ capturePointer: (target: Element) => void,
+ ) => void;
+ onEnd: (reason: PointerSessionEndReason, event: PointerEvent | null) => void;
+}): (() => void) => {
+ const {pointerId} = event;
+ const buttonMask = getButtonMask(event.button);
+ let ended = false;
+ let activeCaptureTarget: Element | null = null;
+ // Assigned once the listeners it removes exist.
+ let cleanup = () => undefined;
+
+ const end = (
+ reason: PointerSessionEndReason,
+ pointerEvent: PointerEvent | null,
+ ) => {
+ if (ended) {
+ return;
+ }
+
+ ended = true;
+ cleanup();
+ onEnd(reason, pointerEvent);
+ };
+
+ const handleLostPointerCapture = (lostEvent: Event) => {
+ const pointerEvent = lostEvent as PointerEvent;
+ if (pointerEvent.pointerId === pointerId) {
+ end('lostpointercapture', pointerEvent);
+ }
+ };
+
+ const capturePointer = (target: Element) => {
+ if (activeCaptureTarget !== null) {
+ return;
+ }
+
+ activeCaptureTarget = target;
+ try {
+ target.setPointerCapture?.(pointerId);
+ } catch {
+ // Capture is best-effort for detached targets.
+ }
+
+ target.addEventListener('lostpointercapture', handleLostPointerCapture);
+ };
+
+ const handleMove = (moveEvent: PointerEvent) => {
+ if (moveEvent.pointerId !== pointerId) {
+ return;
+ }
+
+ if ((moveEvent.buttons & buttonMask) === 0) {
+ end('buttons-released', moveEvent);
+ return;
+ }
+
+ onMove?.(moveEvent, capturePointer);
+ };
+
+ const handleUp = (upEvent: PointerEvent) => {
+ if (upEvent.pointerId === pointerId) {
+ end('pointerup', upEvent);
+ }
+ };
+
+ const handleCancel = (cancelEvent: PointerEvent) => {
+ if (cancelEvent.pointerId === pointerId) {
+ end('pointercancel', cancelEvent);
+ }
+ };
+
+ const handleBlur = () => {
+ end('blur', null);
+ };
+
+ const handleVisibilityChange = () => {
+ if (document.visibilityState === 'hidden') {
+ end('visibilitychange', null);
+ }
+ };
+
+ cleanup = () => {
+ window.removeEventListener('pointermove', handleMove);
+ window.removeEventListener('pointerup', handleUp);
+ window.removeEventListener('pointercancel', handleCancel);
+ window.removeEventListener('blur', handleBlur);
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
+ activeCaptureTarget?.removeEventListener(
+ 'lostpointercapture',
+ handleLostPointerCapture,
+ );
+
+ if (activeCaptureTarget?.hasPointerCapture?.(pointerId)) {
+ try {
+ activeCaptureTarget.releasePointerCapture(pointerId);
+ } catch {
+ // The browser may already have released capture.
+ }
+ }
+ };
+
+ if (captureTarget !== null) {
+ capturePointer(captureTarget);
+ }
+
+ window.addEventListener('pointermove', handleMove);
+ window.addEventListener('pointerup', handleUp);
+ window.addEventListener('pointercancel', handleCancel);
+ window.addEventListener('blur', handleBlur);
+ document.addEventListener('visibilitychange', handleVisibilityChange);
+
+ return () => end('manual', null);
+};
+
+// Use for a gesture owned by a Studio control, such as a slider or resize
+// handle. `captureTarget` is normally the pointerdown handler's currentTarget.
+export const startCapturedPointerSession = ({
+ event,
+ captureTarget,
+ onMove,
+ onEnd,
+}: {
+ event: PointerSessionEvent;
+ captureTarget: Element;
+ onMove?: (event: PointerEvent) => void;
+ onEnd: (reason: PointerSessionEndReason, event: PointerEvent | null) => void;
+}) => {
+ return startPointerSession({event, captureTarget, onMove, onEnd});
+};
+
+// Use when a click must remain targeted at the element under the pointer, but
+// an actual drag needs a stable capture target. Call `capturePointer()` from
+// `onMove` once the movement qualifies as a drag.
+export const startDeferredCapturedPointerSession = ({
+ event,
+ captureTarget,
+ onMove,
+ onEnd,
+}: {
+ event: PointerSessionEvent;
+ captureTarget: Element;
+ onMove: (event: PointerEvent, capturePointer: () => void) => void;
+ onEnd: (reason: PointerSessionEndReason, event: PointerEvent | null) => void;
+}) => {
+ return startPointerSession({
+ event,
+ captureTarget: null,
+ onMove: (moveEvent, capturePointer) => {
+ onMove(moveEvent, () => capturePointer(captureTarget));
+ },
+ onEnd,
+ });
+};
+
+// Use when observing a gesture that started elsewhere. This deliberately does
+// not capture the pointer from the element under it.
+export const observePointerRelease = ({
+ event,
+ onEnd,
+}: {
+ event: PointerSessionEvent;
+ onEnd: (reason: PointerSessionEndReason, event: PointerEvent | null) => void;
+}) => {
+ return startPointerSession({
+ event,
+ captureTarget: null,
+ onEnd,
+ });
+};
diff --git a/packages/canvas/src/sequence-props-change.ts b/packages/canvas/src/sequence-props-change.ts
new file mode 100644
index 0000000000..290547a0ec
--- /dev/null
+++ b/packages/canvas/src/sequence-props-change.ts
@@ -0,0 +1,40 @@
+import type {CanUpdateSequencePropStatus, InteractivitySchema} from 'remotion';
+import type {SequenceNodePathInfo} from './get-timeline-sequence-sort-key';
+
+type CanvasSequencePropChangeBase = {
+ /** The registered source node of the moved sequence. */
+ readonly nodePathInfo: SequenceNodePathInfo;
+ /** The interactivity schema key in dot notation, e.g. `style.translate`. */
+ readonly key: string;
+ readonly value: unknown;
+ /** The interactivity schema of the element, for the codemods. */
+ readonly schema: InteractivitySchema;
+};
+
+/** A prop value that a canvas gesture ended with. */
+export type CanvasSequencePropChange =
+ | (CanvasSequencePropChangeBase & {
+ readonly type: 'static';
+ /** The default of the schema field; the prop can be removed when `value` equals it. */
+ readonly defaultValue: unknown;
+ })
+ | (CanvasSequencePropChangeBase & {
+ /** The prop is keyframed in the source; add or replace the keyframe at `frame`. */
+ readonly type: 'keyframe';
+ /** In the frame clock of the interpolation, as `updateNodeKeyframes()` expects. */
+ readonly frame: number;
+ });
+
+export type CanvasSequencePropsChangeHandler = (
+ changes: readonly CanvasSequencePropChange[],
+) => void;
+
+/**
+ * How the requested props of a sequence are written in the source, as
+ * `getNodeProps()` from @remotion/codemods reports them. Return `null` when
+ * the source is unknown.
+ */
+export type CanvasSequencePropStatusResolver = (
+ nodePathInfo: SequenceNodePathInfo,
+ keys: readonly string[],
+) => Record<string, CanUpdateSequencePropStatus> | null;
diff --git a/packages/studio/src/test/selected-outline-snap.test.ts b/packages/canvas/src/test/outline-snap.test.ts
similarity index 75%
rename from packages/studio/src/test/selected-outline-snap.test.ts
rename to packages/canvas/src/test/outline-snap.test.ts
index e9a43add06..67500e4be4 100644
--- a/packages/studio/src/test/selected-outline-snap.test.ts
+++ b/packages/canvas/src/test/outline-snap.test.ts
@@ -1,11 +1,11 @@
import {expect, test} from 'bun:test';
-import type {SelectedOutline} from '../components/selected-outline-geometry';
+import type {CanvasOutline} from '../outline-geometry';
import {
- findSelectedOutlineSnap,
- getSelectedOutlineSnapTargets,
- type SelectedOutlineSnapTarget,
-} from '../components/selected-outline-snap';
-import type {Guide} from '../state/editor-guides';
+ findCanvasOutlineSnap,
+ getCanvasOutlineSnapTargets,
+ type CanvasOutlineSnapGuide,
+ type CanvasOutlineSnapTarget,
+} from '../outline-snap';
const makeOutline = ({
height,
@@ -19,7 +19,7 @@ const makeOutline = ({
readonly scale?: number;
readonly top: number;
readonly width: number;
-}): SelectedOutline => {
+}): CanvasOutline => {
const right = left + width;
const bottom = top + height;
@@ -38,17 +38,17 @@ const makeOutline = ({
};
const getTargets = (
- guides: readonly Guide[] = [],
-): readonly SelectedOutlineSnapTarget[] => {
- return getSelectedOutlineSnapTargets({
+ guides: readonly CanvasOutlineSnapGuide[] = [],
+): readonly CanvasOutlineSnapTarget[] => {
+ return getCanvasOutlineSnapTargets({
compositionHeight: 600,
compositionWidth: 1000,
guides,
});
};
-test('selected outlines snap to the horizontal and vertical canvas center', () => {
- const result = findSelectedOutlineSnap({
+test('outlines snap to the horizontal and vertical canvas center', () => {
+ const result = findCanvasOutlineSnap({
allowX: true,
allowY: true,
deltaX: 0,
@@ -66,8 +66,8 @@ test('selected outlines snap to the horizontal and vertical canvas center', () =
]);
});
-test('selected outlines snap their edges to canvas edges', () => {
- const result = findSelectedOutlineSnap({
+test('outlines snap their edges to canvas edges', () => {
+ const result = findCanvasOutlineSnap({
allowX: true,
allowY: true,
deltaX: 0,
@@ -86,7 +86,7 @@ test('selected outlines snap their edges to canvas edges', () => {
});
test('snap threshold is measured in screen pixels', () => {
- const result = findSelectedOutlineSnap({
+ const result = findCanvasOutlineSnap({
allowX: true,
allowY: true,
deltaX: 0,
@@ -106,23 +106,11 @@ test('snap threshold is measured in screen pixels', () => {
});
test('visible guides become snap targets for item edges and centers', () => {
- const guides: Guide[] = [
- {
- compositionId: 'comp',
- id: 'vertical-guide',
- orientation: 'vertical',
- position: 300,
- show: true,
- },
- {
- compositionId: 'comp',
- id: 'hidden-guide',
- orientation: 'horizontal',
- position: 240,
- show: false,
- },
+ const guides: CanvasOutlineSnapGuide[] = [
+ {orientation: 'vertical', position: 300, show: true},
+ {orientation: 'horizontal', position: 240, show: false},
];
- const result = findSelectedOutlineSnap({
+ const result = findCanvasOutlineSnap({
allowX: true,
allowY: true,
deltaX: 0,
@@ -140,7 +128,7 @@ test('visible guides become snap targets for item edges and centers', () => {
});
test('axis lock prevents snapping along the locked axis', () => {
- const result = findSelectedOutlineSnap({
+ const result = findCanvasOutlineSnap({
allowX: false,
allowY: true,
deltaX: 0,
@@ -158,7 +146,7 @@ test('axis lock prevents snapping along the locked axis', () => {
});
test('full-canvas selections prefer center snap when edges tie', () => {
- const result = findSelectedOutlineSnap({
+ const result = findCanvasOutlineSnap({
allowX: true,
allowY: true,
deltaX: 0,
diff --git a/packages/canvas/src/test/outline-translate-drag.test.ts b/packages/canvas/src/test/outline-translate-drag.test.ts
new file mode 100644
index 0000000000..5e49866029
--- /dev/null
+++ b/packages/canvas/src/test/outline-translate-drag.test.ts
@@ -0,0 +1,352 @@
+import {expect, test} from 'bun:test';
+import type {
+ InteractivitySchema,
+ SequenceNodePath,
+ SequencePropsSubscriptionKey,
+} from 'remotion';
+import {Internals} from 'remotion';
+import {
+ applyCanvasOutlineDragAxisLock,
+ canvasOutlineDragThresholdPx,
+ getCanvasOutlineNudgeDelta,
+ getCanvasOutlineNudgeDeltas,
+ getCanvasOutlineTranslateDragChanges,
+ getCanvasOutlineTranslateDragValues,
+ isCanvasOutlineDragPastThreshold,
+ type CanvasOutlineTranslateDragState,
+} from '../outline-translate-drag';
+
+const makeKey = (nodePath: SequenceNodePath): SequencePropsSubscriptionKey => ({
+ absolutePath: '/project/src/Comp.tsx',
+ nodePath,
+ sequenceKeys: ['from', 'durationInFrames'],
+ effectKeys: [],
+ videoConfigValues: null,
+});
+
+test('outline dragging applies the same delta to all selected sequences', () => {
+ const schema = {
+ 'style.translate': {type: 'translate', default: '0px 0px'},
+ } satisfies InteractivitySchema;
+ const firstNodePath = makeKey(['body', 0]);
+ const secondNodePath = makeKey(['body', 1]);
+ const dragStates = [
+ {
+ defaultValue: JSON.stringify('0px 0px'),
+ key: Internals.makeSequencePropsSubscriptionKey(firstNodePath),
+ sourceFrame: 12,
+ startX: 10,
+ startY: 20,
+ startZ: 30,
+ target: {
+ propStatus: {
+ status: 'static',
+ keyframeDisplayOffsetAdjustment: null,
+ codeValue: '10px 20px 30px',
+ },
+ fieldDefault: '0px 0px',
+ runtimeValue: undefined,
+ keyframeDisplayOffset: 30,
+ keyframePlaybackRate: 1,
+ nodePath: firstNodePath,
+ schema,
+ },
+ },
+ {
+ defaultValue: JSON.stringify('0px 0px'),
+ key: Internals.makeSequencePropsSubscriptionKey(secondNodePath),
+ sourceFrame: 12,
+ startX: -5,
+ startY: 3,
+ startZ: null,
+ target: {
+ propStatus: {
+ status: 'static',
+ keyframeDisplayOffsetAdjustment: null,
+ codeValue: '-5px 3px',
+ },
+ fieldDefault: '0px 0px',
+ runtimeValue: undefined,
+ keyframeDisplayOffset: 30,
+ keyframePlaybackRate: 1,
+ nodePath: secondNodePath,
+ schema,
+ },
+ },
+ ] satisfies CanvasOutlineTranslateDragState[];
+
+ const lastValues = getCanvasOutlineTranslateDragValues({
+ dragStates,
+ deltaX: 7.333333,
+ deltaY: -4.666667,
+ });
+
+ expect(lastValues.get(dragStates[0].key)).toBe('17.3px 15.3px 30px');
+ expect(lastValues.get(dragStates[1].key)).toBe('2.3px -1.7px');
+ expect(
+ getCanvasOutlineTranslateDragChanges({
+ dragStates,
+ lastValues,
+ }),
+ ).toEqual([
+ {
+ type: 'static',
+ fileName: '/project/src/Comp.tsx',
+ nodePath: firstNodePath,
+ fieldKey: 'style.translate',
+ value: '17.3px 15.3px 30px',
+ defaultValue: JSON.stringify('0px 0px'),
+ schema,
+ },
+ {
+ type: 'static',
+ fileName: '/project/src/Comp.tsx',
+ nodePath: secondNodePath,
+ fieldKey: 'style.translate',
+ value: '2.3px -1.7px',
+ defaultValue: JSON.stringify('0px 0px'),
+ schema,
+ },
+ ]);
+});
+
+test('outline dragging can lock movement to the dominant axis', () => {
+ expect(
+ applyCanvasOutlineDragAxisLock({
+ deltaX: 12,
+ deltaY: 7,
+ axisLocked: true,
+ }),
+ ).toEqual({deltaX: 12, deltaY: 0});
+ expect(
+ applyCanvasOutlineDragAxisLock({
+ deltaX: 12,
+ deltaY: 13,
+ axisLocked: true,
+ }),
+ ).toEqual({deltaX: 0, deltaY: 13});
+ expect(
+ applyCanvasOutlineDragAxisLock({
+ deltaX: 12,
+ deltaY: 13,
+ axisLocked: false,
+ }),
+ ).toEqual({deltaX: 12, deltaY: 13});
+});
+
+test('outline keyboard nudging moves by one or ten pixels', () => {
+ const schema = {
+ 'style.translate': {type: 'translate', default: '0px 0px'},
+ } satisfies InteractivitySchema;
+ const nodePath = makeKey(['body', 0]);
+ const dragStates = [
+ {
+ defaultValue: JSON.stringify('0px 0px'),
+ key: Internals.makeSequencePropsSubscriptionKey(nodePath),
+ sourceFrame: 12,
+ startX: 10,
+ startY: 20,
+ startZ: null,
+ target: {
+ propStatus: {
+ status: 'static',
+ keyframeDisplayOffsetAdjustment: null,
+ codeValue: '10px 20px',
+ },
+ fieldDefault: '0px 0px',
+ runtimeValue: undefined,
+ keyframeDisplayOffset: 30,
+ keyframePlaybackRate: 1,
+ nodePath,
+ schema,
+ },
+ },
+ ] satisfies CanvasOutlineTranslateDragState[];
+
+ expect(
+ getCanvasOutlineNudgeDelta({
+ direction: 'left',
+ shiftKey: false,
+ }),
+ ).toBe(-1);
+ expect(
+ getCanvasOutlineNudgeDelta({
+ direction: 'right',
+ shiftKey: true,
+ }),
+ ).toBe(10);
+ expect(
+ getCanvasOutlineNudgeDelta({
+ direction: 'up',
+ shiftKey: false,
+ }),
+ ).toBe(-1);
+ expect(
+ getCanvasOutlineNudgeDelta({
+ direction: 'down',
+ shiftKey: true,
+ }),
+ ).toBe(10);
+ const accumulatedDeltas = [
+ {direction: 'right', shiftKey: false},
+ {direction: 'right', shiftKey: false},
+ {direction: 'down', shiftKey: true},
+ ] satisfies readonly {
+ readonly direction: 'left' | 'right' | 'up' | 'down';
+ readonly shiftKey: boolean;
+ }[];
+ const finalDeltas = accumulatedDeltas.reduce(
+ (deltas, keyPress) =>
+ getCanvasOutlineNudgeDeltas({
+ ...deltas,
+ direction: keyPress.direction,
+ shiftKey: keyPress.shiftKey,
+ }),
+ {deltaX: 0, deltaY: 0},
+ );
+
+ expect(finalDeltas).toEqual({deltaX: 2, deltaY: 10});
+
+ const horizontalLastValues = getCanvasOutlineTranslateDragValues({
+ dragStates,
+ deltaX: getCanvasOutlineNudgeDelta({
+ direction: 'right',
+ shiftKey: true,
+ }),
+ deltaY: 0,
+ });
+
+ expect(horizontalLastValues.get(dragStates[0].key)).toBe('20px 20px');
+ expect(
+ getCanvasOutlineTranslateDragChanges({
+ dragStates,
+ lastValues: horizontalLastValues,
+ }),
+ ).toEqual([
+ {
+ type: 'static',
+ fileName: '/project/src/Comp.tsx',
+ nodePath,
+ fieldKey: 'style.translate',
+ value: '20px 20px',
+ defaultValue: JSON.stringify('0px 0px'),
+ schema,
+ },
+ ]);
+
+ const verticalLastValues = getCanvasOutlineTranslateDragValues({
+ dragStates,
+ deltaX: 0,
+ deltaY: getCanvasOutlineNudgeDelta({
+ direction: 'down',
+ shiftKey: true,
+ }),
+ });
+
+ expect(verticalLastValues.get(dragStates[0].key)).toBe('10px 30px');
+ expect(
+ getCanvasOutlineTranslateDragChanges({
+ dragStates,
+ lastValues: verticalLastValues,
+ }),
+ ).toEqual([
+ {
+ type: 'static',
+ fileName: '/project/src/Comp.tsx',
+ nodePath,
+ fieldKey: 'style.translate',
+ value: '10px 30px',
+ defaultValue: JSON.stringify('0px 0px'),
+ schema,
+ },
+ ]);
+});
+
+test('outline dragging starts after a screen pixel threshold', () => {
+ expect(
+ isCanvasOutlineDragPastThreshold({
+ deltaX: canvasOutlineDragThresholdPx - 0.1,
+ deltaY: 0,
+ }),
+ ).toBe(false);
+ expect(
+ isCanvasOutlineDragPastThreshold({
+ deltaX: canvasOutlineDragThresholdPx,
+ deltaY: 0,
+ }),
+ ).toBe(true);
+ expect(
+ isCanvasOutlineDragPastThreshold({
+ deltaX: 3,
+ deltaY: 3,
+ }),
+ ).toBe(true);
+});
+
+test('outline dragging keyframed translate adds a keyframe at the source frame', () => {
+ const schema = {
+ 'style.translate': {type: 'translate', default: '0px 0px'},
+ } satisfies InteractivitySchema;
+ const nodePath = makeKey(['body', 0]);
+ const dragStates = [
+ {
+ defaultValue: JSON.stringify('0px 0px'),
+ key: Internals.makeSequencePropsSubscriptionKey(nodePath),
+ sourceFrame: 20,
+ startX: 50,
+ startY: 25,
+ startZ: 15,
+ target: {
+ propStatus: {
+ status: 'keyframed',
+ keyframeDisplayOffsetAdjustment: null,
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: '0px 0px 15px'},
+ {frame: 40, value: '100px 50px 15px'},
+ ],
+ easing: [{type: 'linear'}],
+ clamping: {left: 'extend', right: 'extend'},
+ posterize: undefined,
+ output: undefined,
+ },
+ fieldDefault: '0px 0px',
+ runtimeValue: undefined,
+ keyframeDisplayOffset: 30,
+ keyframePlaybackRate: 1,
+ nodePath,
+ schema,
+ },
+ },
+ ] satisfies CanvasOutlineTranslateDragState[];
+
+ const lastValues = getCanvasOutlineTranslateDragValues({
+ dragStates,
+ deltaX: 7,
+ deltaY: -4,
+ });
+
+ expect(lastValues.get(dragStates[0].key)).toBe('57px 21px 15px');
+ expect(
+ getCanvasOutlineTranslateDragChanges({
+ dragStates,
+ lastValues,
+ }),
+ ).toEqual([
+ {
+ type: 'keyframed',
+ fileName: '/project/src/Comp.tsx',
+ nodePath,
+ fieldKey: 'style.translate',
+ sourceFrame: 20,
+ value: '57px 21px 15px',
+ schema,
+ },
+ ]);
+ expect(
+ getCanvasOutlineTranslateDragChanges({
+ dragStates,
+ lastValues: new Map([[dragStates[0].key, '50px 25px 15px']]),
+ }),
+ ).toEqual([]);
+});
diff --git a/packages/studio/src/test/pointer-session.test.ts b/packages/canvas/src/test/pointer-session.test.ts
similarity index 99%
rename from packages/studio/src/test/pointer-session.test.ts
rename to packages/canvas/src/test/pointer-session.test.ts
index ee60e8e5fd..4ff75ed1d6 100644
--- a/packages/studio/src/test/pointer-session.test.ts
+++ b/packages/canvas/src/test/pointer-session.test.ts
@@ -3,7 +3,7 @@ import {
observePointerRelease,
type PointerSessionEndReason,
startCapturedPointerSession,
-} from '../helpers/pointer-session';
+} from '../pointer-session';
class CaptureTarget extends EventTarget {
private readonly capturedPointers = new Set<number>();
diff --git a/packages/studio/src/test/timeline-translate-utils.test.ts b/packages/canvas/src/test/translate-value.test.ts
similarity index 97%
rename from packages/studio/src/test/timeline-translate-utils.test.ts
rename to packages/canvas/src/test/translate-value.test.ts
index 2f64324d34..0ea64287ee 100644
--- a/packages/studio/src/test/timeline-translate-utils.test.ts
+++ b/packages/canvas/src/test/translate-value.test.ts
@@ -4,7 +4,7 @@ import {
parseTranslateWithUnits,
serializeTranslate,
serializeTranslateWithUnits,
-} from '../components/Timeline/timeline-translate-utils';
+} from '../translate-value';
test('parseTranslate normalizes floating point noise', () => {
expect(parseTranslate('10.020000000000001px 30.240000000000002px')).toEqual([
diff --git a/packages/canvas/src/translate-value.ts b/packages/canvas/src/translate-value.ts
new file mode 100644
index 0000000000..46c87fe6a0
--- /dev/null
+++ b/packages/canvas/src/translate-value.ts
@@ -0,0 +1,112 @@
+const TRANSLATE_PATTERN =
+ /^(-?\d+(?:\.\d+)?)(px|%)?(?:\s+(-?\d+(?:\.\d+)?)(px|%)?)?(?:\s+(-?\d+(?:\.\d+)?)(px)?)?$/i;
+const translateDecimalPlaces = 1;
+
+export const roundToDecimalPlaces = (
+ value: number,
+ decimalPlaces: number,
+): number => {
+ const factor = 10 ** decimalPlaces;
+ const rounded = Math.round(value * factor) / factor;
+ return Object.is(rounded, -0) ? 0 : rounded;
+};
+
+// Drops floating point noise such as 10.020000000000001.
+const normalizeNumber = (value: number): number =>
+ roundToDecimalPlaces(value, 6);
+
+export type ParsedTranslate = readonly [number, number, number | null];
+
+export type TranslateUnit = 'px' | '%';
+
+export type ParsedTranslateWithUnits = readonly [
+ {readonly value: number; readonly unit: TranslateUnit},
+ {readonly value: number; readonly unit: TranslateUnit},
+ {readonly value: number; readonly unit: 'px'} | null,
+];
+
+export const parseTranslateWithUnits = (
+ value: string,
+): ParsedTranslateWithUnits | null => {
+ const match = value.match(TRANSLATE_PATTERN);
+ if (!match) {
+ return null;
+ }
+
+ const x = normalizeNumber(Number(match[1]));
+ const y = match[3] === undefined ? 0 : normalizeNumber(Number(match[3]));
+ const z = match[5] === undefined ? null : normalizeNumber(Number(match[5]));
+
+ if (
+ (match[2] === undefined && x !== 0) ||
+ (match[3] !== undefined && match[4] === undefined && y !== 0) ||
+ (match[5] !== undefined && match[6] === undefined && z !== 0)
+ ) {
+ return null;
+ }
+
+ return [
+ {
+ value: x,
+ unit:
+ match[2] === undefined
+ ? 'px'
+ : (match[2].toLowerCase() as TranslateUnit),
+ },
+ {
+ value: y,
+ unit:
+ match[4] === undefined
+ ? 'px'
+ : (match[4].toLowerCase() as TranslateUnit),
+ },
+ z === null
+ ? z
+ : {
+ value: z,
+ unit: 'px',
+ },
+ ];
+};
+
+/** Pixel translate coordinates; percentages and unparseable values read as the origin. */
+export const parseTranslate = (value: string): ParsedTranslate => {
+ const parsed = parseTranslateWithUnits(value);
+ if (parsed === null || parsed[0].unit !== 'px' || parsed[1].unit !== 'px') {
+ return [0, 0, null];
+ }
+
+ return [parsed[0].value, parsed[1].value, parsed[2]?.value ?? null];
+};
+
+const formatTranslateCoordinate = (
+ value: number,
+ decimalPlaces: number,
+): string => {
+ const rounded = roundToDecimalPlaces(normalizeNumber(value), decimalPlaces);
+ return String(Object.is(rounded, -0) ? 0 : rounded);
+};
+
+export const serializeTranslateWithUnits = (
+ [x, y, z]: ParsedTranslateWithUnits,
+ decimalPlaces = translateDecimalPlaces,
+): string => {
+ const xy = `${formatTranslateCoordinate(x.value, decimalPlaces)}${x.unit} ${formatTranslateCoordinate(y.value, decimalPlaces)}${y.unit}`;
+ return z === null
+ ? xy
+ : `${xy} ${formatTranslateCoordinate(z.value, decimalPlaces)}${z.unit}`;
+};
+
+export const serializeTranslate = (
+ [x, y, z]: ParsedTranslate,
+ decimalPlaces = translateDecimalPlaces,
+): string => {
+ return serializeTranslateWithUnits(
+ [
+ {value: x, unit: 'px'},
+ {value: y, unit: 'px'},
+ z === null ? null : {value: z, unit: 'px'},
+ ],
+ decimalPlaces,
+ );
+};
diff --git a/packages/docs/docs/canvas/canvas.mdx b/packages/docs/docs/canvas/canvas.mdx
index 149747e513..4499b2c3c2 100644
--- a/packages/docs/docs/canvas/canvas.mdx
+++ b/packages/docs/docs/canvas/canvas.mdx
@@ -7,7 +7,7 @@ crumb: '@remotion/canvas'
# &lt;Canvas&gt;<AvailableFrom v="4.0.527" />
-Renders a Remotion composition using [`<Player>`](/docs/player/player), registers its timeline tracks, and optionally overlays selection outlines.
+Renders a Remotion composition using [`<Player>`](/docs/player/player), registers its timeline tracks, and optionally overlays selection outlines that can be dragged to move elements.
Unlike a plain `<Player>`, the Canvas enables the interactivity of the mounted elements: each track exposes its [`controls`](/docs/canvas/create-canvas-controller#sequencecontrols) and the controller can [preview prop values](/docs/canvas/create-canvas-controller#overrides) without changing the source.
@@ -51,6 +51,52 @@ Whether to draw hover and selection outlines over the composition. Default: `fal
Clicking empty canvas space or pressing Escape while the overlay is focused clears selection. Shift-click selects a range; Command-click on macOS or Ctrl-click elsewhere toggles an item.
+### onSequencePropsChange?<AvailableFrom v="4.0.530" />
+
+Enables moving elements on the canvas. Dragging a selected outline moves every selected element; the arrow keys nudge the selection by one pixel, ten with Shift, while the overlay is focused. Shift locks a drag to the dominant axis. The moved elements snap to the edges and the center of the composition, unless Command or Ctrl is held.
+
+While the gesture is in progress, the new `style.translate` values are previewed through [`controller.overrides`](/docs/canvas/create-canvas-controller#overrides). When the gesture ends with a changed value, the callback receives one `CanvasSequencePropChange` per moved source node with `nodePathInfo`, the schema `key`, the `value` and the element's `schema`. A change with `type: 'static'` also carries the schema `defaultValue`; write it with [`updateNodeProps()`](/docs/codemods/update-node-props). A change with `type: 'keyframe'` carries the `frame` at which to add a keyframe with [`updateNodeKeyframes()`](/docs/codemods/update-node-keyframes); it is reported for props that [`getSequencePropStatuses`](#getsequencepropstatuses) describes as keyframed. Clear the overrides once the update is applied; until then, the canvas keeps showing the new position.
+
+```tsx twoslash title="Persisting a move"
+// @moduleResolution: bundler
+import type {CanvasController, CanvasSequencePropChange} from '@remotion/canvas';
+declare const controller: CanvasController;
+declare const persist: (change: CanvasSequencePropChange) => Promise<void>;
+// ---cut---
+export const onSequencePropsChange = async (changes: readonly CanvasSequencePropChange[]) => {
+ for (const change of changes) {
+ await persist(change);
+ controller.overrides.clear(change.nodePathInfo);
+ }
+};
+```
+
+Elements can be moved when they expose a `style.translate` field in their [`controls`](/docs/canvas/create-canvas-controller#sequencecontrols) and their source node is registered with [`setSequenceNodePaths()`](/docs/canvas/create-canvas-controller#setsequencenodepaths). Without the callback, outlines can be selected but not moved.
+
+### getSequencePropStatuses?<AvailableFrom v="4.0.530" />
+
+A `CanvasSequencePropStatusResolver` called with a `SequenceNodePathInfo` and the schema keys about to be edited, before a move starts. Return how those props are written in the source, as the `props` of [`getNodeProps()`](/docs/codemods/get-node-props) report them, or `null` if the source is unknown.
+
+A prop with `status: 'computed'` cannot be moved: the outline is selected but does not follow the pointer, like in the Remotion Studio. A `status: 'keyframed'` prop that uses `interpolate()` is moved by adding a keyframe at the current frame, and the gesture is previewed with the existing keyframes in place. A `status: 'static'` prop starts from its `codeValue`.
+
+By default, the source is unknown: every prop starts from the runtime value of the mounted element and is reported as a static change.
+
+```tsx twoslash title="Reading the source"
+// @moduleResolution: bundler
+import type {CanvasSequencePropStatusResolver} from '@remotion/canvas';
+import {getNodeProps, type CodemodProject} from '@remotion/codemods';
+declare const project: CodemodProject;
+// ---cut---
+export const getSequencePropStatuses: CanvasSequencePropStatusResolver = (nodePathInfo, keys) => {
+ const {absolutePath, nodePath} = nodePathInfo.sequenceSubscriptionKey;
+ return getNodeProps({
+ project,
+ node: {filePath: absolutePath, nodePath},
+ keys: [...keys],
+ }).props;
+};
+```
+
### resolveSequenceNodePathInfo?
A `CanvasSequenceNodePathResolver` called with a [`TimelineTrackData`](/docs/canvas/create-canvas-controller#timeline) and its index. It returns a `SequenceNodePathInfo` identity or `null` to make the track unselectable. The default is [`getCanvasSequenceNodePathInfo()`](/docs/canvas/get-canvas-sequence-node-path-info), which uses the identities registered with [`setSequenceNodePaths()`](/docs/canvas/create-canvas-controller#setsequencenodepaths).
diff --git a/packages/docs/docs/canvas/create-canvas-controller.mdx b/packages/docs/docs/canvas/create-canvas-controller.mdx
index e8966d9b77..becb039220 100644
--- a/packages/docs/docs/canvas/create-canvas-controller.mdx
+++ b/packages/docs/docs/canvas/create-canvas-controller.mdx
@@ -72,6 +72,8 @@ Passing an unchanged mapping is a no-op, so the function may be called from a `t
Preview 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.
+
#### set()
`set(nodePathInfo, key, value)` overrides one prop of the sequence identified by `nodePathInfo`, a `SequenceNodePathInfo` from a track or a selection item. `key` is a key of the element's interactivity schema in dot notation, such as `'style.translate'`, `'from'` or `'durationInFrames'`.
diff --git a/packages/docs/docs/canvas/index.mdx b/packages/docs/docs/canvas/index.mdx
index 3449e6a48f..407b3fd1e3 100644
--- a/packages/docs/docs/canvas/index.mdx
+++ b/packages/docs/docs/canvas/index.mdx
@@ -132,6 +132,8 @@ The Canvas exposes the [`controls`](/docs/canvas/create-canvas-controller#sequen
While a value is being dragged, [`controller.overrides`](/docs/canvas/create-canvas-controller#overrides) previews it on the canvas immediately. Persist the final value when the gesture ends, then clear the override.
+Pass [`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.
+
## APIs
import {TableOfContents} from './table-of-contents';
diff --git a/packages/docs/docs/canvas/table-of-contents.tsx b/packages/docs/docs/canvas/table-of-contents.tsx
index a3193086a9..383cfaf1b2 100644
--- a/packages/docs/docs/canvas/table-of-contents.tsx
+++ b/packages/docs/docs/canvas/table-of-contents.tsx
@@ -8,7 +8,7 @@ export const TableOfContents: React.FC = () => {
<Grid>
<TOCItem link="/docs/canvas/canvas">
<strong>{'<Canvas>'}</strong>
- <div>Preview a composition with optional selection outlines</div>
+ <div>Preview a composition with selectable, movable outlines</div>
</TOCItem>
<TOCItem link="/docs/canvas/create-canvas-controller">
<strong>createCanvasController()</strong>
diff --git a/packages/studio/src/components/SelectedOutlineCanvasRotation.tsx b/packages/studio/src/components/SelectedOutlineCanvasRotation.tsx
index 0256d0e28a..4dfa42ac48 100644
--- a/packages/studio/src/components/SelectedOutlineCanvasRotation.tsx
+++ b/packages/studio/src/components/SelectedOutlineCanvasRotation.tsx
@@ -11,7 +11,7 @@ import {
} from './ForceSpecificCursor';
import {showNotification} from './Notifications/NotificationCenter';
import {
- clearSelectedOutlineRotationDragOverrides,
+ clearSelectedOutlineDragOverrides,
getSelectedOutline3DRotationDragValues,
getSelectedOutlineRotationDragChanges,
getSelectedOutlineRotationDragStates,
@@ -244,7 +244,7 @@ export const SelectedOutlineCanvasRotation: React.FC<{
lastValues,
});
if (changes.length === 0) {
- clearSelectedOutlineRotationDragOverrides({
+ clearSelectedOutlineDragOverrides({
clearDragOverrides,
dragStates,
});
@@ -288,7 +288,7 @@ export const SelectedOutlineCanvasRotation: React.FC<{
);
})
.finally(() => {
- clearSelectedOutlineRotationDragOverrides({
+ clearSelectedOutlineDragOverrides({
clearDragOverrides,
dragStates,
});
diff --git a/packages/studio/src/components/SelectedOutlineKeyboardControls.tsx b/packages/studio/src/components/SelectedOutlineKeyboardControls.tsx
index 373002eb22..633b222f9d 100644
--- a/packages/studio/src/components/SelectedOutlineKeyboardControls.tsx
+++ b/packages/studio/src/components/SelectedOutlineKeyboardControls.tsx
@@ -1,3 +1,7 @@
+import {
+ CanvasInternals,
+ type CanvasOutlineNudgeDirection,
+} from '@remotion/canvas';
import {PlayerInternals} from '@remotion/player';
import type React from 'react';
import {useCallback, useContext, useEffect, useRef} from 'react';
@@ -6,25 +10,27 @@ import {useKeybinding} from '../helpers/use-keybinding';
import {showNotification} from './Notifications/NotificationCenter';
import {
clearSelectedOutlineDragOverrides,
- getSelectedOutlineDragChanges,
- getSelectedOutlineDragStates,
- getSelectedOutlineDragValues,
- getSelectedOutlineKeyboardNudgeDeltas,
- getSelectedOutlineKeyboardNudgeDirection,
- type SelectedOutlineKeyboardNudgeDirection,
type SelectedOutlineKeyframedDragChange,
type SelectedOutlineStaticDragChange,
} from './selected-outline-drag';
-import {
- translateFieldKey,
- type SelectedOutlineDragTarget,
- type SelectedOutlineKeyboardNudgeSession,
+import type {
+ SelectedOutlineDragTarget,
+ SelectedOutlineKeyboardNudgeSession,
} from './selected-outline-types';
import {callAddKeyframes} from './Timeline/call-add-keyframe';
import {getCurrentDuration, getCurrentFps} from './Timeline/imperative-state';
import {saveSequenceProps} from './Timeline/save-sequence-prop';
import {ensureFrameIsInViewport} from './Timeline/timeline-scroll-logic';
+const {
+ applyCanvasOutlineTranslateDelta,
+ createCanvasOutlineTranslateSession,
+ getCanvasOutlineNudgeDeltas,
+ getCanvasOutlineNudgeDirection,
+ getCanvasOutlineTranslateDragChanges,
+ getCanvasOutlineTranslateDragStates,
+} = CanvasInternals;
+
export const SelectedOutlineKeyboardControls: React.FC<{
readonly getAllDragTargets: () => readonly SelectedOutlineDragTarget[];
}> = ({getAllDragTargets}) => {
@@ -48,7 +54,7 @@ export const SelectedOutlineKeyboardControls: React.FC<{
}
keyboardNudgeSessionRef.current = null;
- const changes = getSelectedOutlineDragChanges({
+ const changes = getCanvasOutlineTranslateDragChanges({
dragStates: session.dragStates,
lastValues: session.lastValues,
});
@@ -61,6 +67,11 @@ export const SelectedOutlineKeyboardControls: React.FC<{
return;
}
+ const [
+ {
+ target: {clientId},
+ },
+ ] = session.dragStates;
const staticChanges = changes.filter(
(change): change is SelectedOutlineStaticDragChange =>
change.type === 'static',
@@ -77,7 +88,7 @@ export const SelectedOutlineKeyboardControls: React.FC<{
addedKeyframes: null,
movedKeyframes: null,
setPropStatuses,
- clientId: session.clientId,
+ clientId,
undoLabel:
changes.length > 1 ? 'Move selected sequences' : 'Move sequence',
redoLabel:
@@ -90,7 +101,7 @@ export const SelectedOutlineKeyboardControls: React.FC<{
sequenceKeyframes: keyframedChanges,
effectKeyframes: [],
setPropStatuses,
- clientId: session.clientId,
+ clientId,
}),
])
.catch((err) => {
@@ -120,10 +131,7 @@ export const SelectedOutlineKeyboardControls: React.FC<{
}, []);
const seekWithArrowKey = useCallback(
- (
- event: KeyboardEvent,
- direction: SelectedOutlineKeyboardNudgeDirection,
- ) => {
+ (event: KeyboardEvent, direction: CanvasOutlineNudgeDirection) => {
if (direction === 'up' || direction === 'down') {
return;
}
@@ -188,7 +196,7 @@ export const SelectedOutlineKeyboardControls: React.FC<{
const onArrowKeyDown = useCallback(
(event: KeyboardEvent) => {
- const direction = getSelectedOutlineKeyboardNudgeDirection(event.key);
+ const direction = getCanvasOutlineNudgeDirection(event.key);
if (direction === null) {
return;
@@ -210,66 +218,25 @@ export const SelectedOutlineKeyboardControls: React.FC<{
const activeSession =
keyboardNudgeSessionRef.current ??
- ((): SelectedOutlineKeyboardNudgeSession => {
- const [firstDragTarget] = allDragTargets;
- if (firstDragTarget === undefined) {
- throw new Error('Expected a drag target');
- }
-
- return {
- clientId: firstDragTarget.clientId,
- deltaX: 0,
- deltaY: 0,
- dragStates: getSelectedOutlineDragStates({
- dragTargets: allDragTargets,
- getDragOverrides,
- timelinePosition: getCurrentFrame(),
- }),
- lastValues: new Map(),
- };
- })();
+ createCanvasOutlineTranslateSession(
+ getCanvasOutlineTranslateDragStates({
+ dragTargets: allDragTargets,
+ getDragOverrides,
+ timelinePosition: getCurrentFrame(),
+ }),
+ );
keyboardNudgeSessionRef.current = activeSession;
- const nextDeltas = getSelectedOutlineKeyboardNudgeDeltas({
- deltaX: activeSession.deltaX,
- deltaY: activeSession.deltaY,
- direction,
- shiftKey: event.shiftKey,
- });
- activeSession.deltaX = nextDeltas.deltaX;
- activeSession.deltaY = nextDeltas.deltaY;
-
- const lastValues = getSelectedOutlineDragValues({
- dragStates: activeSession.dragStates,
- deltaX: activeSession.deltaX,
- deltaY: activeSession.deltaY,
+ applyCanvasOutlineTranslateDelta({
+ session: activeSession,
+ ...getCanvasOutlineNudgeDeltas({
+ deltaX: activeSession.deltaX,
+ deltaY: activeSession.deltaY,
+ direction,
+ shiftKey: event.shiftKey,
+ }),
+ setDragOverrides,
});
- activeSession.lastValues = lastValues;
-
- for (const dragState of activeSession.dragStates) {
- const value = lastValues.get(dragState.key);
- if (value === undefined) {
- throw new Error('Expected drag value to be available');
- }
-
- if (dragState.target.propStatus.status === 'keyframed') {
- setDragOverrides(
- dragState.target.nodePath,
- translateFieldKey,
- Internals.makeKeyframedDragOverride({
- status: dragState.target.propStatus,
- frame: dragState.sourceFrame,
- value,
- }),
- );
- } else {
- setDragOverrides(
- dragState.target.nodePath,
- translateFieldKey,
- Internals.makeStaticDragOverride(value),
- );
- }
- }
},
[
getAllDragTargets,
@@ -282,7 +249,7 @@ export const SelectedOutlineKeyboardControls: React.FC<{
const onArrowKeyUp = useCallback(
(event: KeyboardEvent) => {
- const direction = getSelectedOutlineKeyboardNudgeDirection(event.key);
+ const direction = getCanvasOutlineNudgeDirection(event.key);
if (direction === null || keyboardNudgeSessionRef.current === null) {
return;
diff --git a/packages/studio/src/components/SelectedOutlineOverlay.tsx b/packages/studio/src/components/SelectedOutlineOverlay.tsx
index aa6dd19973..f82433cf15 100644
--- a/packages/studio/src/components/SelectedOutlineOverlay.tsx
+++ b/packages/studio/src/components/SelectedOutlineOverlay.tsx
@@ -76,7 +76,6 @@ const {
export {orderOutlinesForRendering};
export {
- applySelectedOutlineDragAxisLock,
applySelectedOutlineTransformOriginAxisLock,
compensateTranslateForTransformOrigin,
getSelectedOutline3DRotationDragValues,
@@ -84,10 +83,6 @@ export {
getSelectedOutlineCropDragChanges,
getSelectedOutlineCropDragValues,
getSelectedOutlineCropFollowingTransformOrigin,
- getSelectedOutlineDragChanges,
- getSelectedOutlineDragValues,
- getSelectedOutlineKeyboardNudgeDelta,
- getSelectedOutlineKeyboardNudgeDeltas,
getSelectedOutlineRotationDragChanges,
getSelectedOutlineRotationDragStates,
getSelectedOutlineRotationDragValues,
@@ -97,7 +92,6 @@ export {
getSelectedOutlineScaleEdgeInfo,
getSelectedOutlineTransformOriginDragChanges,
getSelectedOutlineTransformOriginLockedAxis,
- isSelectedOutlineDragPastThreshold,
selectedOutlineTransformOriginSnapThresholdPx,
selectedOutlineUvSnapThresholdPx,
snapSelectedOutlineRotationDeltaDegrees,
@@ -115,7 +109,6 @@ export {
getSequencesWithSelectableOutlines,
getTransformedSvgViewportPoints,
} from './selected-outline-measurement';
-export {selectedOutlineDragThresholdPx} from './selected-outline-types';
const getEffectiveCropValue = ({
activeSchema,
@@ -536,6 +529,7 @@ const calculateOutlineTargets = ({
propStatus,
clientId: connectedClientId,
fieldDefault: fieldSchema.default,
+ runtimeValue: runtimeValues[translateFieldKey],
keyframePlaybackRate,
keyframeDisplayOffset: getKeyframeDisplayOffset({
propStatus,
diff --git a/packages/studio/src/components/SelectedOutlinePolygon.tsx b/packages/studio/src/components/SelectedOutlinePolygon.tsx
index 4b493c3b5e..27aaefa3d3 100644
--- a/packages/studio/src/components/SelectedOutlinePolygon.tsx
+++ b/packages/studio/src/components/SelectedOutlinePolygon.tsx
@@ -10,11 +10,6 @@ import {
import {createDragAwareDoubleClickTracker} from '../helpers/drag-aware-double-click';
import {isStudioInteractivityEnabled} from '../helpers/interactivity-enabled';
import {isMac} from '../helpers/is-mac';
-import {
- isPointerSessionRelease,
- startCapturedPointerSession,
- type PointerSessionEndReason,
-} from '../helpers/pointer-session';
import {EditorShowGuidesContext} from '../state/editor-guides';
import {EditorSnappingContext} from '../state/editor-snapping';
import {
@@ -29,26 +24,19 @@ import {
} from './ForceSpecificCursor';
import {showNotification} from './Notifications/NotificationCenter';
import {
- applySelectedOutlineDragAxisLock,
clearSelectedOutlineDragOverrides,
- getSelectedOutlineDragChanges,
- getSelectedOutlineDragStates,
- getSelectedOutlineDragValues,
- isSelectedOutlineDragPastThreshold,
type SelectedOutlineKeyframedDragChange,
type SelectedOutlineStaticDragChange,
} from './selected-outline-drag';
import type {SelectedOutline} from './selected-outline-geometry';
import {
- findSelectedOutlineSnap,
getSelectedOutlineSnapTargets,
type SelectedOutlineSnapPoint,
} from './selected-outline-snap';
-import {
- translateFieldKey,
- type SelectedOutlineDragTarget,
- type SelectedOutlineLayoutTarget,
- type SelectedOutlineTarget,
+import type {
+ SelectedOutlineDragTarget,
+ SelectedOutlineLayoutTarget,
+ SelectedOutlineTarget,
} from './selected-outline-types';
import {callAddKeyframes} from './Timeline/call-add-keyframe';
import {commitPendingInspectorFields} from './Timeline/focus-inspector-field';
@@ -61,7 +49,12 @@ import type {
} from './Timeline/TimelineSelection';
import {useTimelineSelection} from './Timeline/TimelineSelection';
-const {CanvasOutlinePolygon, handleCanvasOutlinePointerDown} = CanvasInternals;
+const {
+ CanvasOutlinePolygon,
+ getCanvasOutlineTranslateDragStates,
+ handleCanvasOutlinePointerDown,
+ startCanvasOutlineTranslateDrag,
+} = CanvasInternals;
export const SELECTED_OUTLINE_KEY_ATTR =
'data-remotion-studio-selected-outline-key';
@@ -201,8 +194,6 @@ const SelectedOutlinePolygonUnmemoized: React.FC<{
return;
}
- const startPointerX = event.clientX;
- const startPointerY = event.clientY;
const dragTargets = dragExistingSelection
? getAllDragTargets()
: drag === null
@@ -216,231 +207,109 @@ const SelectedOutlinePolygonUnmemoized: React.FC<{
return;
}
- const dragStates = getSelectedOutlineDragStates({
- dragTargets,
- getDragOverrides,
- timelinePosition: getCurrentFrame(),
- });
- const dragOutlines = dragExistingSelection
- ? getAllDragOutlines()
- : [outline];
const [{clientId}] = dragTargets;
- let lastValues = new Map<string, string>();
- let currentPointerX = startPointerX;
- let currentPointerY = startPointerY;
- let axisLocked = false;
- let dragStarted = false;
- let snappingDisabled =
- !temporaryTranslate && (event.metaKey || event.ctrlKey);
- let snapTargets: ReturnType<typeof getSelectedOutlineSnapTargets> | null =
- null;
-
- const updateDragOverrides = () => {
- const screenDeltaX = currentPointerX - startPointerX;
- const screenDeltaY = currentPointerY - startPointerY;
- if (!dragStarted) {
- if (
- !isSelectedOutlineDragPastThreshold({
- deltaX: screenDeltaX,
- deltaY: screenDeltaY,
- })
- ) {
- return;
- }
-
- dragStarted = true;
+ startCanvasOutlineTranslateDrag({
+ event,
+ captureTarget: event.currentTarget,
+ dragStates: getCanvasOutlineTranslateDragStates({
+ dragTargets,
+ getDragOverrides,
+ timelinePosition: getCurrentFrame(),
+ }),
+ scale,
+ snapping: editorSnapping
+ ? {
+ outlines: dragExistingSelection
+ ? getAllDragOutlines()
+ : [outline],
+ getTargets: () =>
+ getSelectedOutlineSnapTargets({
+ compositionHeight,
+ compositionWidth,
+ guides:
+ editorShowGuides && canvasContent?.type === 'composition'
+ ? guidesList.filter(
+ (guide) =>
+ guide.compositionId === canvasContent.compositionId,
+ )
+ : [],
+ }),
+ onSnapPointsChange,
+ // Command already means "translate" in rotation mode.
+ modifierDisablesSnapping: !temporaryTranslate,
+ }
+ : null,
+ setDragOverrides,
+ clearDragOverrides,
+ onDragStart: () => {
onDraggingChange(true);
forceSpecificCursor('default');
- }
-
- const axisLockedDirection = axisLocked
- ? Math.abs(screenDeltaX) >= Math.abs(screenDeltaY)
- ? 'horizontal'
- : 'vertical'
- : null;
- const dragDelta = applySelectedOutlineDragAxisLock({
- deltaX: screenDeltaX / scale,
- deltaY: screenDeltaY / scale,
- axisLocked,
- });
- let {deltaX, deltaY} = dragDelta;
-
- if (editorSnapping && !snappingDisabled) {
- snapTargets ??= getSelectedOutlineSnapTargets({
- compositionHeight,
- compositionWidth,
- guides:
- editorShowGuides && canvasContent?.type === 'composition'
- ? guidesList.filter(
- (guide) =>
- guide.compositionId === canvasContent.compositionId,
- )
- : [],
- });
- const snapResult = findSelectedOutlineSnap({
- allowX: axisLockedDirection !== 'vertical',
- allowY: axisLockedDirection !== 'horizontal',
- deltaX,
- deltaY,
- outlines: dragOutlines,
- scale,
- targets: snapTargets,
- });
-
- if (snapResult.snapOffsetX !== null) {
- deltaX += snapResult.snapOffsetX;
+ },
+ onDragEnd: ({changes, dragged, released, session}) => {
+ dragAwareDoubleClick.endPointerGesture(dragged);
+ if (dragged) {
+ stopForcingSpecificCursor();
+ onDraggingChange(false);
}
- if (snapResult.snapOffsetY !== null) {
- deltaY += snapResult.snapOffsetY;
- }
-
- onSnapPointsChange(snapResult.activeSnapPoints);
- } else {
- onSnapPointsChange([]);
- }
+ if (changes.length === 0) {
+ if (deferSelection && !dragged && released) {
+ onSelect(target.selection, interaction);
+ }
- lastValues = getSelectedOutlineDragValues({
- dragStates,
- deltaX,
- deltaY,
- });
- for (const dragState of dragStates) {
- const value = lastValues.get(dragState.key);
- if (value === undefined) {
- throw new Error('Expected drag value to be available');
- }
-
- if (dragState.target.propStatus.status === 'keyframed') {
- setDragOverrides(
- dragState.target.nodePath,
- translateFieldKey,
- Internals.makeKeyframedDragOverride({
- status: dragState.target.propStatus,
- frame: dragState.sourceFrame,
- value,
- }),
- );
- } else {
- setDragOverrides(
- dragState.target.nodePath,
- translateFieldKey,
- Internals.makeStaticDragOverride(value),
- );
- }
- }
- };
-
- const onPointerMove = (moveEvent: PointerEvent) => {
- moveEvent.preventDefault();
- currentPointerX = moveEvent.clientX;
- currentPointerY = moveEvent.clientY;
- axisLocked = moveEvent.shiftKey;
- snappingDisabled =
- !temporaryTranslate && (moveEvent.metaKey || moveEvent.ctrlKey);
- updateDragOverrides();
- };
-
- const onKeyChange = (keyEvent: KeyboardEvent) => {
- if (keyEvent.key !== 'Shift') {
- return;
- }
-
- const nextAxisLocked = keyEvent.type === 'keydown';
- if (nextAxisLocked === axisLocked) {
- return;
- }
-
- axisLocked = nextAxisLocked;
- updateDragOverrides();
- };
-
- const onPointerUp = (
- reason: PointerSessionEndReason,
- endEvent: PointerEvent | null,
- ) => {
- dragAwareDoubleClick.endPointerGesture(dragStarted);
- window.removeEventListener('keydown', onKeyChange);
- window.removeEventListener('keyup', onKeyChange);
- if (dragStarted) {
- stopForcingSpecificCursor();
- onSnapPointsChange([]);
- onDraggingChange(false);
- }
-
- const changes = getSelectedOutlineDragChanges({
- dragStates,
- lastValues,
- });
-
- if (changes.length === 0) {
- clearSelectedOutlineDragOverrides({clearDragOverrides, dragStates});
- if (
- deferSelection &&
- !dragStarted &&
- isPointerSessionRelease(reason, endEvent)
- ) {
- onSelect(target.selection, interaction);
+ return;
}
- return;
- }
-
- const staticChanges = changes.filter(
- (change): change is SelectedOutlineStaticDragChange =>
- change.type === 'static',
- );
- const keyframedChanges = changes.filter(
- (change): change is SelectedOutlineKeyframedDragChange =>
- change.type === 'keyframed',
- );
-
- Promise.all([
- staticChanges.length > 0
- ? saveSequenceProps({
- changes: staticChanges,
- addedKeyframes: null,
- movedKeyframes: null,
- setPropStatuses,
- clientId,
- undoLabel:
- changes.length > 1
- ? 'Move selected sequences'
- : 'Move sequence',
- redoLabel:
- changes.length > 1
- ? 'Move selected sequences back'
- : 'Move sequence back',
- })
- : Promise.resolve(),
- callAddKeyframes({
- sequenceKeyframes: keyframedChanges,
- effectKeyframes: [],
- setPropStatuses,
- clientId,
- }),
- ])
- .catch((err) => {
- showNotification(
- `Could not save sequence props: ${
- err instanceof Error ? err.message : String(err)
- }`,
- 4000,
- );
- })
- .finally(() => {
- clearSelectedOutlineDragOverrides({clearDragOverrides, dragStates});
- });
- };
-
- startCapturedPointerSession({
- event,
- captureTarget: event.currentTarget,
- onMove: onPointerMove,
- onEnd: onPointerUp,
+ const staticChanges = changes.filter(
+ (change): change is SelectedOutlineStaticDragChange =>
+ change.type === 'static',
+ );
+ const keyframedChanges = changes.filter(
+ (change): change is SelectedOutlineKeyframedDragChange =>
+ change.type === 'keyframed',
+ );
+
+ Promise.all([
+ staticChanges.length > 0
+ ? saveSequenceProps({
+ changes: staticChanges,
+ addedKeyframes: null,
+ movedKeyframes: null,
+ setPropStatuses,
+ clientId,
+ undoLabel:
+ changes.length > 1
+ ? 'Move selected sequences'
+ : 'Move sequence',
+ redoLabel:
+ changes.length > 1
+ ? 'Move selected sequences back'
+ : 'Move sequence back',
+ })
+ : Promise.resolve(),
+ callAddKeyframes({
+ sequenceKeyframes: keyframedChanges,
+ effectKeyframes: [],
+ setPropStatuses,
+ clientId,
+ }),
+ ])
+ .catch((err) => {
+ showNotification(
+ `Could not save sequence props: ${
+ err instanceof Error ? err.message : String(err)
+ }`,
+ 4000,
+ );
+ })
+ .finally(() => {
+ clearSelectedOutlineDragOverrides({
+ clearDragOverrides,
+ dragStates: session.dragStates,
+ });
+ });
+ },
});
- window.addEventListener('keydown', onKeyChange);
- window.addEventListener('keyup', onKeyChange);
},
[
canvasContent,
diff --git a/packages/studio/src/components/SelectedOutlineRotationCornerHandle.tsx b/packages/studio/src/components/SelectedOutlineRotationCornerHandle.tsx
index e796f1c20d..b1dde7bd99 100644
--- a/packages/studio/src/components/SelectedOutlineRotationCornerHandle.tsx
+++ b/packages/studio/src/components/SelectedOutlineRotationCornerHandle.tsx
@@ -10,7 +10,7 @@ import {
} from './ForceSpecificCursor';
import {showNotification} from './Notifications/NotificationCenter';
import {
- clearSelectedOutlineRotationDragOverrides,
+ clearSelectedOutlineDragOverrides,
getSelectedOutlineRotationDragChanges,
getSelectedOutlineRotationDragStates,
getSelectedOutlineRotationDragValues,
@@ -250,7 +250,7 @@ export const SelectedOutlineRotationCornerHandle: React.FC<{
});
if (changes.length === 0) {
- clearSelectedOutlineRotationDragOverrides({
+ clearSelectedOutlineDragOverrides({
clearDragOverrides,
dragStates,
});
@@ -300,7 +300,7 @@ export const SelectedOutlineRotationCornerHandle: React.FC<{
);
})
.finally(() => {
- clearSelectedOutlineRotationDragOverrides({
+ clearSelectedOutlineDragOverrides({
clearDragOverrides,
dragStates,
});
diff --git a/packages/studio/src/components/SelectedOutlineScaleEdgeLine.tsx b/packages/studio/src/components/SelectedOutlineScaleEdgeLine.tsx
index 421bbde3b5..2289c6efdf 100644
--- a/packages/studio/src/components/SelectedOutlineScaleEdgeLine.tsx
+++ b/packages/studio/src/components/SelectedOutlineScaleEdgeLine.tsx
@@ -9,7 +9,7 @@ import {
} from './ForceSpecificCursor';
import {showNotification} from './Notifications/NotificationCenter';
import {
- clearSelectedOutlineScaleDragOverrides,
+ clearSelectedOutlineDragOverrides,
getSelectedOutlineScaleDragChanges,
getSelectedOutlineScaleDragStates,
getSelectedOutlineScaleDragValues,
@@ -189,7 +189,7 @@ export const SelectedOutlineScaleEdgeLine: React.FC<{
});
if (changes.length === 0) {
- clearSelectedOutlineScaleDragOverrides({
+ clearSelectedOutlineDragOverrides({
clearDragOverrides,
dragStates,
});
@@ -239,7 +239,7 @@ export const SelectedOutlineScaleEdgeLine: React.FC<{
);
})
.finally(() => {
- clearSelectedOutlineScaleDragOverrides({
+ clearSelectedOutlineDragOverrides({
clearDragOverrides,
dragStates,
});
diff --git a/packages/studio/src/components/SelectedOutlineSnapIndicators.tsx b/packages/studio/src/components/SelectedOutlineSnapIndicators.tsx
index 02ab1b883d..136812fd29 100644
--- a/packages/studio/src/components/SelectedOutlineSnapIndicators.tsx
+++ b/packages/studio/src/components/SelectedOutlineSnapIndicators.tsx
@@ -1,9 +1,12 @@
+import {CanvasInternals} from '@remotion/canvas';
import React, {useLayoutEffect, useState} from 'react';
import {
selectedOutlineSnapIndicatorColor,
type SelectedOutlineSnapPoint,
} from './selected-outline-snap';
+const {CanvasOutlineSnapLines} = CanvasInternals;
+
export type UpdateSelectedOutlineSnapPoints = (
snapPoints: readonly SelectedOutlineSnapPoint[],
) => void;
@@ -14,44 +17,14 @@ export const SelectedOutlineSnapLines: React.FC<{
readonly scale: number;
readonly snapPoints: readonly SelectedOutlineSnapPoint[];
}> = ({compositionHeight, compositionWidth, scale, snapPoints}) => {
- if (snapPoints.length === 0) {
- return null;
- }
-
return (
- <g pointerEvents="none">
- {snapPoints.map((snapPoint) => {
- if (snapPoint.target.axis === 'x') {
- const x = snapPoint.target.position * scale;
- return (
- <line
- key={`${snapPoint.target.axis}-${snapPoint.target.type}-${snapPoint.target.position}-${snapPoint.edge}`}
- x1={x}
- x2={x}
- y1={0}
- y2={compositionHeight * scale}
- stroke={selectedOutlineSnapIndicatorColor}
- strokeWidth={1}
- vectorEffect="non-scaling-stroke"
- />
- );
- }
-
- const y = snapPoint.target.position * scale;
- return (
- <line
- key={`${snapPoint.target.axis}-${snapPoint.target.type}-${snapPoint.target.position}-${snapPoint.edge}`}
- x1={0}
- x2={compositionWidth * scale}
- y1={y}
- y2={y}
- stroke={selectedOutlineSnapIndicatorColor}
- strokeWidth={1}
- vectorEffect="non-scaling-stroke"
- />
- );
- })}
- </g>
+ <CanvasOutlineSnapLines
+ compositionHeight={compositionHeight}
+ compositionWidth={compositionWidth}
+ scale={scale}
+ snapPoints={snapPoints}
+ color={selectedOutlineSnapIndicatorColor}
+ />
);
};
diff --git a/packages/studio/src/components/Timeline/get-timeline-keyframes.ts b/packages/studio/src/components/Timeline/get-timeline-keyframes.ts
index 2e148da59d..331c89e61c 100644
--- a/packages/studio/src/components/Timeline/get-timeline-keyframes.ts
+++ b/packages/studio/src/components/Timeline/get-timeline-keyframes.ts
@@ -1,139 +1,12 @@
-import type {CanUpdateSequencePropStatus} from 'remotion';
-
-export const getKeyframePlaybackRate = (
- propStatus: CanUpdateSequencePropStatus | null | undefined,
- keyframePlaybackRate: number,
-): number =>
- keyframePlaybackRate *
- (propStatus && propStatus.status !== 'computed'
- ? (propStatus.keyframePlaybackRateAdjustment ?? 1)
- : 1);
-
-export const getKeyframeLocalFrame = (
- sourceFrame: number,
- propStatus: CanUpdateSequencePropStatus,
-): number =>
- propStatus.status === 'computed'
- ? sourceFrame
- : (sourceFrame + (propStatus.keyframeDisplayOffsetAdjustment ?? 0)) /
- (propStatus.keyframePlaybackRateAdjustment ?? 1);
-
-// Keep display-clock inputs until the edited property is known, so resolving its
-// original source keyframe accounts for rounding introduced by the full offset.
-export type KeyframeSourceFrame =
- | number
- | {
- readonly displayFrame: number;
- readonly keyframeDisplayOffset: number;
- readonly keyframePlaybackRate: number;
- };
-
-export const getKeyframeSourceFrame = ({
- displayFrame,
- keyframeDisplayOffset,
- keyframePlaybackRate,
- propStatus,
-}: {
- displayFrame: number;
- keyframeDisplayOffset: number;
- keyframePlaybackRate: number;
- propStatus: CanUpdateSequencePropStatus | null;
-}): number => {
- const playbackRate = getKeyframePlaybackRate(
- propStatus,
- keyframePlaybackRate,
- );
- const sourceFrame = (displayFrame - keyframeDisplayOffset) * playbackRate;
- if (propStatus?.status !== 'keyframed') {
- return sourceFrame;
- }
-
- // Converting a displayed keyframe back to source frames may introduce rounding
- // error. Resolve its original frame so edits keep the existing keyframe identity,
- // including when source keyframes themselves have fractional frames.
- const tolerance =
- Number.EPSILON *
- Math.max(1, Math.abs(displayFrame), Math.abs(keyframeDisplayOffset)) *
- playbackRate *
- 8;
- let closestFrame = sourceFrame;
- let closestDistance = Infinity;
- for (const keyframe of propStatus.keyframes) {
- const distance = Math.abs(keyframe.frame - sourceFrame);
- if (distance <= tolerance && distance < closestDistance) {
- closestFrame = keyframe.frame;
- closestDistance = distance;
- }
- }
-
- return closestFrame;
-};
-
-export const resolveKeyframeSourceFrame = (
- sourceFrame: KeyframeSourceFrame,
- propStatus: CanUpdateSequencePropStatus | null,
-): number => {
- return getKeyframeSourceFrame({
- ...(typeof sourceFrame === 'number'
- ? {
- displayFrame: sourceFrame,
- keyframeDisplayOffset: 0,
- keyframePlaybackRate: 1 / getKeyframePlaybackRate(propStatus, 1),
- }
- : sourceFrame),
- propStatus,
- });
-};
-
-export const getTimelineKeyframes = (
- propStatus: CanUpdateSequencePropStatus | null | undefined,
- keyframeDisplayOffset = 0,
- keyframePlaybackRate = 1,
-): {frame: number; value: unknown}[] => {
- if (!propStatus) {
- return [];
- }
-
- if (propStatus.status !== 'keyframed') {
- return [];
- }
-
- const {keyframes} = propStatus;
- const playbackRate = getKeyframePlaybackRate(
- propStatus,
- keyframePlaybackRate,
- );
- const resolvedKeyframeDisplayOffset = getKeyframeDisplayOffset({
- propStatus,
- keyframeDisplayOffset,
- keyframePlaybackRate,
- });
- if (resolvedKeyframeDisplayOffset === 0 && playbackRate === 1) {
- return keyframes;
- }
-
- return keyframes.map((keyframe) => ({
- ...keyframe,
- frame: keyframe.frame / playbackRate + resolvedKeyframeDisplayOffset,
- }));
-};
-
-export const getKeyframeDisplayOffset = ({
- propStatus,
- keyframeDisplayOffset,
- keyframePlaybackRate,
-}: {
- propStatus: CanUpdateSequencePropStatus | null | undefined;
- keyframeDisplayOffset: number;
- keyframePlaybackRate: number;
-}): number => {
- return (
- keyframeDisplayOffset +
- (propStatus?.status === 'keyframed' || propStatus?.status === 'static'
- ? propStatus.keyframeDisplayOffsetAdjustment === null
- ? 0
- : propStatus.keyframeDisplayOffsetAdjustment /
- getKeyframePlaybackRate(propStatus, keyframePlaybackRate)
- : 0)
- );
-};
+import {CanvasInternals} from '@remotion/canvas';
+
+export type {KeyframeSourceFrame} from '@remotion/canvas';
+
+export const {
+ getKeyframeDisplayOffset,
+ getKeyframeLocalFrame,
+ getKeyframePlaybackRate,
+ getKeyframeSourceFrame,
+ getTimelineKeyframes,
+ resolveKeyframeSourceFrame,
+} = CanvasInternals;
diff --git a/packages/studio/src/components/Timeline/timeline-translate-utils.ts b/packages/studio/src/components/Timeline/timeline-translate-utils.ts
index 17d02ac292..ec42191d61 100644
--- a/packages/studio/src/components/Timeline/timeline-translate-utils.ts
+++ b/packages/studio/src/components/Timeline/timeline-translate-utils.ts
@@ -1,106 +1,14 @@
-import {
- normalizeTimelineNumber,
- roundToDecimalPlaces,
-} from './timeline-field-utils';
-
-const TRANSLATE_PATTERN =
- /^(-?\d+(?:\.\d+)?)(px|%)?(?:\s+(-?\d+(?:\.\d+)?)(px|%)?)?(?:\s+(-?\d+(?:\.\d+)?)(px)?)?$/i;
-const translateDecimalPlaces = 1;
-
-export type ParsedTranslate = readonly [number, number, number | null];
-
-export type TranslateUnit = 'px' | '%';
-
-export type ParsedTranslateWithUnits = readonly [
- {readonly value: number; readonly unit: TranslateUnit},
- {readonly value: number; readonly unit: TranslateUnit},
- {readonly value: number; readonly unit: 'px'} | null,
-];
-
-export const parseTranslateWithUnits = (
- value: string,
-): ParsedTranslateWithUnits | null => {
- const match = value.match(TRANSLATE_PATTERN);
- if (!match) {
- return null;
- }
-
- const x = normalizeTimelineNumber(Number(match[1]));
- const y =
- match[3] === undefined ? 0 : normalizeTimelineNumber(Number(match[3]));
- const z =
- match[5] === undefined ? null : normalizeTimelineNumber(Number(match[5]));
-
- if (
- (match[2] === undefined && x !== 0) ||
- (match[3] !== undefined && match[4] === undefined && y !== 0) ||
- (match[5] !== undefined && match[6] === undefined && z !== 0)
- ) {
- return null;
- }
-
- return [
- {
- value: x,
- unit:
- match[2] === undefined
- ? 'px'
- : (match[2].toLowerCase() as TranslateUnit),
- },
- {
- value: y,
- unit:
- match[4] === undefined
- ? 'px'
- : (match[4].toLowerCase() as TranslateUnit),
- },
- z === null
- ? z
- : {
- value: z,
- unit: 'px',
- },
- ];
-};
-
-export const parseTranslate = (value: string): ParsedTranslate => {
- const parsed = parseTranslateWithUnits(value);
- if (parsed === null || parsed[0].unit !== 'px' || parsed[1].unit !== 'px') {
- return [0, 0, null];
- }
-
- return [parsed[0].value, parsed[1].value, parsed[2]?.value ?? null];
-};
-
-const formatTranslateCoordinate = (
- value: number,
- decimalPlaces: number,
-): string => {
- const normalized = normalizeTimelineNumber(value);
- const rounded = roundToDecimalPlaces(normalized, decimalPlaces);
- return String(Object.is(rounded, -0) ? 0 : rounded);
-};
-
-export const serializeTranslate = (
- [x, y, z]: ParsedTranslate,
- decimalPlaces = translateDecimalPlaces,
-): string => {
- return serializeTranslateWithUnits(
- [
- {value: x, unit: 'px'},
- {value: y, unit: 'px'},
- z === null ? null : {value: z, unit: 'px'},
- ],
- decimalPlaces,
- );
-};
-
-export const serializeTranslateWithUnits = (
- [x, y, z]: ParsedTranslateWithUnits,
- decimalPlaces = translateDecimalPlaces,
-): string => {
- const xy = `${formatTranslateCoordinate(x.value, decimalPlaces)}${x.unit} ${formatTranslateCoordinate(y.value, decimalPlaces)}${y.unit}`;
- return z === null
- ? xy
- : `${xy} ${formatTranslateCoordinate(z.value, decimalPlaces)}${z.unit}`;
-};
+import {CanvasInternals} from '@remotion/canvas';
+
+export type {
+ ParsedTranslate,
+ ParsedTranslateWithUnits,
+ TranslateUnit,
+} from '@remotion/canvas';
+
+export const {
+ parseTranslate,
+ parseTranslateWithUnits,
+ serializeTranslate,
+ serializeTranslateWithUnits,
+} = CanvasInternals;
diff --git a/packages/studio/src/components/selected-outline-drag.ts b/packages/studio/src/components/selected-outline-drag.ts
index bcab1c4bcf..9c52a6baf6 100644
--- a/packages/studio/src/components/selected-outline-drag.ts
+++ b/packages/studio/src/components/selected-outline-drag.ts
@@ -1,9 +1,14 @@
+import {
+ CanvasInternals,
+ type CanvasOutlineDragChange,
+ type CanvasOutlineKeyframedDragChange,
+ type CanvasOutlineStaticDragChange,
+} from '@remotion/canvas';
import type {
CanUpdateSequencePropStatus,
DragOverrideValue,
GetDragOverrides,
InteractivitySchema,
- SequencePropsSubscriptionKey,
} from 'remotion';
import {Internals} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
@@ -21,8 +26,6 @@ import type {
SelectedOutlineCropDragTarget,
SelectedOutlineCropFieldKey,
SelectedOutlineCropHandle,
- SelectedOutlineDragState,
- SelectedOutlineDragTarget,
SelectedOutlineRotationDragState,
SelectedOutlineRotationDragTarget,
SelectedOutlineScaleDragState,
@@ -34,7 +37,6 @@ import {
cropFieldKeys,
rotateFieldKey,
scaleFieldKey,
- selectedOutlineDragThresholdPx,
transformOriginFieldKey,
translateFieldKey,
} from './selected-outline-types';
@@ -94,184 +96,17 @@ export const getSelectedOutlineActiveSchema = ({
return Internals.flattenActiveSchema(schema, (key) => valuesDotNotation[key]);
};
-export const getSelectedOutlineDragStates = ({
- dragTargets,
- getDragOverrides,
- timelinePosition,
-}: {
- readonly dragTargets: readonly SelectedOutlineDragTarget[];
- readonly getDragOverrides: GetDragOverrides;
- readonly timelinePosition: number;
-}): SelectedOutlineDragState[] => {
- return dragTargets.map((target) => {
- const dragOverrideValue = (getDragOverrides(target.nodePath) ?? {})[
- translateFieldKey
- ];
- const sourceFrame = getKeyframeSourceFrame({
- displayFrame: timelinePosition,
- keyframeDisplayOffset: target.keyframeDisplayOffset,
- keyframePlaybackRate: target.keyframePlaybackRate,
- propStatus: target.propStatus,
- });
- const effectiveValue = Internals.getEffectiveVisualModeValue({
- propStatus: target.propStatus,
- dragOverrideValue,
- defaultValue: target.fieldDefault,
- frame: getKeyframeLocalFrame(sourceFrame, target.propStatus),
- shouldResortToDefaultValueIfUndefined: true,
- });
- const [startX, startY, startZ] = parseTranslate(
- String(effectiveValue ?? '0px 0px'),
- );
+// Moving outlines is shared with @remotion/canvas; the Studio adds scale,
+// rotation, crop and transform-origin editing on top.
+export const {
+ isCanvasOutlineDragPastThreshold: isSelectedOutlineDragPastThreshold,
+ clearCanvasOutlineDragOverrides: clearSelectedOutlineDragOverrides,
+} = CanvasInternals;
- return {
- defaultValue:
- target.fieldDefault !== undefined
- ? JSON.stringify(target.fieldDefault)
- : null,
- key: Internals.makeSequencePropsSubscriptionKey(target.nodePath),
- sourceFrame,
- startX,
- startY,
- startZ,
- target,
- };
- });
-};
-
-export const getSelectedOutlineDragValues = ({
- dragStates,
- deltaX,
- deltaY,
-}: {
- readonly dragStates: readonly SelectedOutlineDragState[];
- readonly deltaX: number;
- readonly deltaY: number;
-}): Map<string, string> => {
- return new Map(
- dragStates.map((dragState) => [
- dragState.key,
- serializeTranslate([
- dragState.startX + deltaX,
- dragState.startY + deltaY,
- dragState.startZ,
- ]),
- ]),
- );
-};
-
-export const applySelectedOutlineDragAxisLock = ({
- deltaX,
- deltaY,
- axisLocked,
-}: {
- readonly deltaX: number;
- readonly deltaY: number;
- readonly axisLocked: boolean;
-}) => {
- if (!axisLocked) {
- return {deltaX, deltaY};
- }
-
- if (Math.abs(deltaX) >= Math.abs(deltaY)) {
- return {deltaX, deltaY: 0};
- }
-
- return {deltaX: 0, deltaY};
-};
-
-export const isSelectedOutlineDragPastThreshold = ({
- deltaX,
- deltaY,
-}: {
- readonly deltaX: number;
- readonly deltaY: number;
-}) => {
- return Math.hypot(deltaX, deltaY) >= selectedOutlineDragThresholdPx;
-};
-
-export type SelectedOutlineStaticDragChange = SaveSequencePropChange & {
- readonly type: 'static';
-};
-
-export type SelectedOutlineKeyframedDragChange = {
- readonly type: 'keyframed';
- readonly fileName: string;
- readonly nodePath: SequencePropsSubscriptionKey;
- readonly fieldKey: string;
- readonly sourceFrame: number;
- readonly value: unknown;
- readonly schema: InteractivitySchema;
- readonly clientId: string;
-};
-
-export type SelectedOutlineDragChange =
- | SelectedOutlineStaticDragChange
- | SelectedOutlineKeyframedDragChange;
-
-export const getSelectedOutlineDragChanges = ({
- dragStates,
- lastValues,
-}: {
- readonly dragStates: readonly SelectedOutlineDragState[];
- readonly lastValues: ReadonlyMap<string, string>;
-}): SelectedOutlineDragChange[] => {
- const changes: SelectedOutlineDragChange[] = [];
-
- for (const dragState of dragStates) {
- const value = lastValues.get(dragState.key);
- if (value === undefined) {
- continue;
- }
-
- if (dragState.target.propStatus.status === 'keyframed') {
- const startValue = serializeTranslate([
- dragState.startX,
- dragState.startY,
- dragState.startZ,
- ]);
- if (value === startValue) {
- continue;
- }
-
- changes.push({
- type: 'keyframed',
- fileName: dragState.target.nodePath.absolutePath,
- nodePath: dragState.target.nodePath,
- fieldKey: translateFieldKey,
- sourceFrame: dragState.sourceFrame,
- value,
- schema: dragState.target.schema,
- clientId: dragState.target.clientId,
- });
- continue;
- }
-
- const stringifiedValue = JSON.stringify(value);
- const shouldSave =
- value !== dragState.target.propStatus.codeValue &&
- !(
- dragState.defaultValue === stringifiedValue &&
- dragState.target.propStatus.codeValue === undefined
- );
-
- if (!shouldSave) {
- continue;
- }
-
- changes.push({
- type: 'static',
- fileName: dragState.target.nodePath.absolutePath,
- nodePath: dragState.target.nodePath,
- fieldKey: translateFieldKey,
- value,
- defaultValue: dragState.defaultValue,
- schema: dragState.target.schema,
- });
- }
-
- return changes;
-};
+export type SelectedOutlineStaticDragChange = CanvasOutlineStaticDragChange;
+export type SelectedOutlineKeyframedDragChange =
+ CanvasOutlineKeyframedDragChange;
+export type SelectedOutlineDragChange = CanvasOutlineDragChange;
export type SelectedOutlineCropValues = Record<
SelectedOutlineCropFieldKey,
@@ -404,7 +239,6 @@ export const getSelectedOutlineCropDragChanges = ({
),
value,
schema: target.schema,
- clientId: target.clientId,
});
continue;
}
@@ -482,46 +316,6 @@ export const getSelectedOutlineCropDragChanges = ({
return changes;
};
-export type SelectedOutlineKeyboardNudgeDirection =
- | 'left'
- | 'right'
- | 'up'
- | 'down';
-
-export const getSelectedOutlineKeyboardNudgeDelta = ({
- direction,
- shiftKey,
-}: {
- readonly direction: SelectedOutlineKeyboardNudgeDirection;
- readonly shiftKey: boolean;
-}) => {
- const increment = shiftKey ? 10 : 1;
- return direction === 'left' || direction === 'up' ? -increment : increment;
-};
-
-export const getSelectedOutlineKeyboardNudgeDeltas = ({
- deltaX,
- deltaY,
- direction,
- shiftKey,
-}: {
- readonly deltaX: number;
- readonly deltaY: number;
- readonly direction: SelectedOutlineKeyboardNudgeDirection;
- readonly shiftKey: boolean;
-}) => {
- const delta = getSelectedOutlineKeyboardNudgeDelta({
- direction,
- shiftKey,
- });
-
- if (direction === 'left' || direction === 'right') {
- return {deltaX: deltaX + delta, deltaY};
- }
-
- return {deltaX, deltaY: deltaY + delta};
-};
-
export type SelectedOutlineScaleEdge = 'top' | 'right' | 'bottom' | 'left';
type SelectedOutlineScaleEdgeInfo = {
@@ -706,7 +500,6 @@ export const getSelectedOutlineScaleDragChanges = ({
sourceFrame: dragState.sourceFrame,
value,
schema: dragState.target.schema,
- clientId: dragState.target.clientId,
});
continue;
}
@@ -909,7 +702,6 @@ export const getSelectedOutlineRotationDragChanges = ({
sourceFrame: dragState.sourceFrame,
value,
schema: dragState.target.schema,
- clientId: dragState.target.clientId,
});
continue;
}
@@ -940,64 +732,6 @@ export const getSelectedOutlineRotationDragChanges = ({
return changes;
};
-export const clearSelectedOutlineDragOverrides = ({
- clearDragOverrides,
- dragStates,
-}: {
- readonly clearDragOverrides: (nodePath: SequencePropsSubscriptionKey) => void;
- readonly dragStates: readonly SelectedOutlineDragState[];
-}) => {
- for (const dragState of dragStates) {
- clearDragOverrides(dragState.target.nodePath);
- }
-};
-
-export const getSelectedOutlineKeyboardNudgeDirection = (
- key: string,
-): SelectedOutlineKeyboardNudgeDirection | null => {
- if (key === 'ArrowLeft') {
- return 'left';
- }
-
- if (key === 'ArrowRight') {
- return 'right';
- }
-
- if (key === 'ArrowUp') {
- return 'up';
- }
-
- if (key === 'ArrowDown') {
- return 'down';
- }
-
- return null;
-};
-
-export const clearSelectedOutlineScaleDragOverrides = ({
- clearDragOverrides,
- dragStates,
-}: {
- readonly clearDragOverrides: (nodePath: SequencePropsSubscriptionKey) => void;
- readonly dragStates: readonly SelectedOutlineScaleDragState[];
-}) => {
- for (const dragState of dragStates) {
- clearDragOverrides(dragState.target.nodePath);
- }
-};
-
-export const clearSelectedOutlineRotationDragOverrides = ({
- clearDragOverrides,
- dragStates,
-}: {
- readonly clearDragOverrides: (nodePath: SequencePropsSubscriptionKey) => void;
- readonly dragStates: readonly SelectedOutlineRotationDragState[];
-}) => {
- for (const dragState of dragStates) {
- clearDragOverrides(dragState.target.nodePath);
- }
-};
-
export const compensateTranslateForTransformOrigin = ({
startTranslate,
deltaOrigin,
diff --git a/packages/studio/src/components/selected-outline-snap.ts b/packages/studio/src/components/selected-outline-snap.ts
index 4102f606a2..67bdad00f6 100644
--- a/packages/studio/src/components/selected-outline-snap.ts
+++ b/packages/studio/src/components/selected-outline-snap.ts
@@ -1,283 +1,19 @@
+import {CanvasInternals} from '@remotion/canvas';
import {SELECTED_OUTLINE_SNAP_COLOR} from '../helpers/colors';
-import type {Guide} from '../state/editor-guides';
-import type {SelectedOutline} from './selected-outline-geometry';
-export const selectedOutlineSnapThresholdPx = 10;
-export const selectedOutlineSnapIndicatorColor = SELECTED_OUTLINE_SNAP_COLOR;
-
-export type SelectedOutlineSnapAxis = 'x' | 'y';
-
-export type SelectedOutlineSnapTargetType =
- | 'canvas-left'
- | 'canvas-right'
- | 'canvas-top'
- | 'canvas-bottom'
- | 'canvas-horizontal-center'
- | 'canvas-vertical-center'
- | 'guide-vertical'
- | 'guide-horizontal';
-
-export type SelectedOutlineSnapTarget = {
- readonly axis: SelectedOutlineSnapAxis;
- readonly position: number;
- readonly type: SelectedOutlineSnapTargetType;
-};
-
-export type SelectedOutlineSnapEdge =
- | 'left'
- | 'right'
- | 'center-x'
- | 'top'
- | 'bottom'
- | 'center-y';
-
-export type SelectedOutlineSnapPoint = {
- readonly distance: number;
- readonly edge: SelectedOutlineSnapEdge;
- readonly target: SelectedOutlineSnapTarget;
-};
-
-export type SelectedOutlineSnapResult = {
- readonly activeSnapPoints: readonly SelectedOutlineSnapPoint[];
- readonly snapOffsetX: number | null;
- readonly snapOffsetY: number | null;
-};
-
-type SelectedOutlineBounds = {
- readonly left: number;
- readonly right: number;
- readonly top: number;
- readonly bottom: number;
- readonly centerX: number;
- readonly centerY: number;
-};
-
-type EdgeCheck = {
- readonly edge: SelectedOutlineSnapEdge;
- readonly position: number;
-};
-
-const EPSILON = 0.000001;
-
-export const getSelectedOutlineSnapTargets = ({
- compositionHeight,
- compositionWidth,
- guides,
-}: {
- readonly compositionHeight: number;
- readonly compositionWidth: number;
- readonly guides: readonly Guide[];
-}): readonly SelectedOutlineSnapTarget[] => {
- return [
- {axis: 'x', position: 0, type: 'canvas-left'},
- {
- axis: 'x',
- position: compositionWidth / 2,
- type: 'canvas-horizontal-center',
- },
- {axis: 'x', position: compositionWidth, type: 'canvas-right'},
- {axis: 'y', position: 0, type: 'canvas-top'},
- {
- axis: 'y',
- position: compositionHeight / 2,
- type: 'canvas-vertical-center',
- },
- {axis: 'y', position: compositionHeight, type: 'canvas-bottom'},
- ...guides.flatMap((guide): SelectedOutlineSnapTarget[] => {
- if (!guide.show) {
- return [];
- }
-
- return [
- guide.orientation === 'vertical'
- ? {
- axis: 'x',
- position: guide.position,
- type: 'guide-vertical',
- }
- : {
- axis: 'y',
- position: guide.position,
- type: 'guide-horizontal',
- },
- ];
- }),
- ];
-};
-
-const getSelectedOutlineBounds = ({
- deltaX,
- deltaY,
- outlines,
- scale,
-}: {
- readonly deltaX: number;
- readonly deltaY: number;
- readonly outlines: readonly SelectedOutline[];
- readonly scale: number;
-}): SelectedOutlineBounds | null => {
- if (outlines.length === 0) {
- return null;
- }
-
- const points = outlines.flatMap((outline) => outline.points);
- const left = Math.min(...points.map((point) => point.x)) / scale + deltaX;
- const right = Math.max(...points.map((point) => point.x)) / scale + deltaX;
- const top = Math.min(...points.map((point) => point.y)) / scale + deltaY;
- const bottom = Math.max(...points.map((point) => point.y)) / scale + deltaY;
-
- return {
- left,
- right,
- top,
- bottom,
- centerX: left + (right - left) / 2,
- centerY: top + (bottom - top) / 2,
- };
-};
-
-const canSnapEdgeToTarget = (
- edge: SelectedOutlineSnapEdge,
- target: SelectedOutlineSnapTarget,
-): boolean => {
- if (target.type === 'canvas-horizontal-center') {
- return edge === 'center-x';
- }
+export type {
+ CanvasOutlineSnapAxis as SelectedOutlineSnapAxis,
+ CanvasOutlineSnapEdge as SelectedOutlineSnapEdge,
+ CanvasOutlineSnapPoint as SelectedOutlineSnapPoint,
+ CanvasOutlineSnapResult as SelectedOutlineSnapResult,
+ CanvasOutlineSnapTarget as SelectedOutlineSnapTarget,
+ CanvasOutlineSnapTargetType as SelectedOutlineSnapTargetType,
+} from '@remotion/canvas';
+
+export const {
+ canvasOutlineSnapThresholdPx: selectedOutlineSnapThresholdPx,
+ findCanvasOutlineSnap: findSelectedOutlineSnap,
+ getCanvasOutlineSnapTargets: getSelectedOutlineSnapTargets,
+} = CanvasInternals;
- if (target.type === 'canvas-vertical-center') {
- return edge === 'center-y';
- }
-
- if (target.type === 'canvas-left' || target.type === 'canvas-right') {
- return edge === 'left' || edge === 'right';
- }
-
- if (target.type === 'guide-vertical') {
- return edge === 'left' || edge === 'right' || edge === 'center-x';
- }
-
- if (target.type === 'canvas-top' || target.type === 'canvas-bottom') {
- return edge === 'top' || edge === 'bottom';
- }
-
- return edge === 'top' || edge === 'bottom' || edge === 'center-y';
-};
-
-const findBestSnapForAxis = ({
- edges,
- targets,
- threshold,
-}: {
- readonly edges: readonly EdgeCheck[];
- readonly targets: readonly SelectedOutlineSnapTarget[];
- readonly threshold: number;
-}): {
- readonly offset: number;
- readonly snapPoint: SelectedOutlineSnapPoint;
-} | null => {
- let bestDistance = Infinity;
- let bestSnaps: {
- readonly offset: number;
- readonly snapPoint: SelectedOutlineSnapPoint;
- }[] = [];
-
- for (const target of targets) {
- for (const edge of edges) {
- if (!canSnapEdgeToTarget(edge.edge, target)) {
- continue;
- }
-
- const distance = Math.abs(edge.position - target.position);
- if (distance > threshold || distance > bestDistance + EPSILON) {
- continue;
- }
-
- if (distance < bestDistance - EPSILON) {
- bestSnaps = [];
- bestDistance = distance;
- }
-
- bestSnaps.push({
- offset: target.position - edge.position,
- snapPoint: {
- distance,
- edge: edge.edge,
- target,
- },
- });
- }
- }
-
- if (bestSnaps.length > 1) {
- const centerSnap = bestSnaps.find(
- (snap) =>
- snap.snapPoint.target.type === 'canvas-horizontal-center' ||
- snap.snapPoint.target.type === 'canvas-vertical-center',
- );
- if (centerSnap) {
- return centerSnap;
- }
- }
-
- return bestSnaps[0] ?? null;
-};
-
-export const findSelectedOutlineSnap = ({
- allowX,
- allowY,
- deltaX,
- deltaY,
- outlines,
- scale,
- targets,
-}: {
- readonly allowX: boolean;
- readonly allowY: boolean;
- readonly deltaX: number;
- readonly deltaY: number;
- readonly outlines: readonly SelectedOutline[];
- readonly scale: number;
- readonly targets: readonly SelectedOutlineSnapTarget[];
-}): SelectedOutlineSnapResult => {
- const bounds = getSelectedOutlineBounds({deltaX, deltaY, outlines, scale});
- if (bounds === null) {
- return {
- activeSnapPoints: [],
- snapOffsetX: null,
- snapOffsetY: null,
- };
- }
-
- const threshold = selectedOutlineSnapThresholdPx / scale;
- const snapX = allowX
- ? findBestSnapForAxis({
- edges: [
- {edge: 'left', position: bounds.left},
- {edge: 'center-x', position: bounds.centerX},
- {edge: 'right', position: bounds.right},
- ],
- targets: targets.filter((target) => target.axis === 'x'),
- threshold,
- })
- : null;
- const snapY = allowY
- ? findBestSnapForAxis({
- edges: [
- {edge: 'top', position: bounds.top},
- {edge: 'center-y', position: bounds.centerY},
- {edge: 'bottom', position: bounds.bottom},
- ],
- targets: targets.filter((target) => target.axis === 'y'),
- threshold,
- })
- : null;
-
- return {
- activeSnapPoints: [
- snapX?.snapPoint ?? null,
- snapY?.snapPoint ?? null,
- ].filter((snapPoint) => snapPoint !== null),
- snapOffsetX: snapX?.offset ?? null,
- snapOffsetY: snapY?.offset ?? null,
- };
-};
+export const selectedOutlineSnapIndicatorColor = SELECTED_OUTLINE_SNAP_COLOR;
diff --git a/packages/studio/src/components/selected-outline-types.ts b/packages/studio/src/components/selected-outline-types.ts
index 8b14f3fadf..dadee67514 100644
--- a/packages/studio/src/components/selected-outline-types.ts
+++ b/packages/studio/src/components/selected-outline-types.ts
@@ -1,7 +1,12 @@
-import type {
- CanvasOutlineCrop,
- CanvasOutlineLayoutTarget,
- CanvasSelectableOutline,
+import {
+ CanvasInternals,
+ type CanvasOutlineCrop,
+ type CanvasOutlineLayoutTarget,
+ type CanvasOutlineTranslateDragState,
+ type CanvasOutlineTranslatePropStatus,
+ type CanvasOutlineTranslateSession,
+ type CanvasOutlineTranslateTarget,
+ type CanvasSelectableOutline,
} from '@remotion/canvas';
import type {
CanUpdateSequencePropStatus,
@@ -127,16 +132,11 @@ export type SelectedOutlineCropDragTarget = {
} | null;
};
-export type SelectedOutlineDragTarget = {
- readonly propStatus:
- | CanUpdateSequencePropStatusStatic
- | CanUpdateSequencePropStatusKeyframed;
+// The Studio knows how every translate prop is written, so the source status
+// is always available and the changes are saved through its connected client.
+export type SelectedOutlineDragTarget = CanvasOutlineTranslateTarget & {
+ readonly propStatus: CanvasOutlineTranslatePropStatus;
readonly clientId: string;
- readonly fieldDefault: string | undefined;
- readonly keyframeDisplayOffset: number;
- readonly keyframePlaybackRate: number;
- readonly nodePath: SequencePropsSubscriptionKey;
- readonly schema: InteractivitySchema;
};
export type SelectedOutlineTransformOriginDragTarget = {
@@ -198,15 +198,8 @@ export type SelectedOutlineRotationDragTarget = {
readonly transformOriginValue: string;
};
-export type SelectedOutlineDragState = {
- readonly defaultValue: string | null;
- readonly key: string;
- readonly sourceFrame: number;
- readonly startX: number;
- readonly startY: number;
- readonly startZ: number | null;
- readonly target: SelectedOutlineDragTarget;
-};
+export type SelectedOutlineDragState =
+ CanvasOutlineTranslateDragState<SelectedOutlineDragTarget>;
export type SelectedOutlineScaleDragState = {
readonly defaultValue: string | null;
@@ -230,11 +223,10 @@ export type SelectedOutlineRotationDragState = {
export type SequenceWithSelectedOutline = CanvasSelectableOutline;
-export const translateFieldKey = 'style.translate';
+export const {canvasTranslateFieldKey: translateFieldKey} = CanvasInternals;
export const scaleFieldKey = 'style.scale';
export const rotateFieldKey = 'style.rotate';
export const transformOriginFieldKey = 'style.transformOrigin';
-export const selectedOutlineDragThresholdPx = 4;
export const outlineContainer: React.CSSProperties = {
position: 'absolute',
@@ -245,10 +237,5 @@ export const outlineContainer: React.CSSProperties = {
export const emptyContextMenuValues: readonly ComboboxValue[] = [];
-export type SelectedOutlineKeyboardNudgeSession = {
- readonly dragStates: readonly SelectedOutlineDragState[];
- readonly clientId: string;
- deltaX: number;
- deltaY: number;
- lastValues: ReadonlyMap<string, string>;
-};
+export type SelectedOutlineKeyboardNudgeSession =
+ CanvasOutlineTranslateSession<SelectedOutlineDragTarget>;
diff --git a/packages/studio/src/helpers/pointer-session.ts b/packages/studio/src/helpers/pointer-session.ts
index aad7d72f47..04895fb56c 100644
--- a/packages/studio/src/helpers/pointer-session.ts
+++ b/packages/studio/src/helpers/pointer-session.ts
@@ -1,219 +1,10 @@
-export type PointerSessionEndReason =
- | 'pointerup'
- | 'pointercancel'
- | 'lostpointercapture'
- | 'blur'
- | 'visibilitychange'
- | 'buttons-released'
- | 'manual';
+import {CanvasInternals} from '@remotion/canvas';
-export const isPointerSessionRelease = (
- reason: PointerSessionEndReason,
- event: PointerEvent | null,
-): event is PointerEvent => {
- if (event === null) {
- return false;
- }
+export type {PointerSessionEndReason} from '@remotion/canvas';
- return (
- reason === 'pointerup' ||
- reason === 'buttons-released' ||
- (reason === 'lostpointercapture' && event.buttons === 0)
- );
-};
-
-type PointerSessionEvent = Pick<PointerEvent, 'button' | 'pointerId'>;
-
-const getButtonMask = (button: number) => {
- if (button === 0) {
- return 1;
- }
-
- if (button === 1) {
- return 4;
- }
-
- if (button === 2) {
- return 2;
- }
-
- return 1 << button;
-};
-
-const startPointerSession = ({
- event,
- captureTarget,
- onMove,
- onEnd,
-}: {
- event: PointerSessionEvent;
- captureTarget: Element | null;
- onMove?: (
- event: PointerEvent,
- capturePointer: (target: Element) => void,
- ) => void;
- onEnd: (reason: PointerSessionEndReason, event: PointerEvent | null) => void;
-}): (() => void) => {
- const {pointerId} = event;
- const buttonMask = getButtonMask(event.button);
- let ended = false;
- let activeCaptureTarget: Element | null = null;
-
- const capturePointer = (target: Element) => {
- if (activeCaptureTarget !== null) {
- return;
- }
-
- activeCaptureTarget = target;
- try {
- target.setPointerCapture?.(pointerId);
- } catch {
- // Capture is best-effort for detached targets.
- }
-
- target.addEventListener('lostpointercapture', handleLostPointerCapture);
- };
-
- const cleanup = () => {
- window.removeEventListener('pointermove', handleMove);
- window.removeEventListener('pointerup', handleUp);
- window.removeEventListener('pointercancel', handleCancel);
- window.removeEventListener('blur', handleBlur);
- document.removeEventListener('visibilitychange', handleVisibilityChange);
- activeCaptureTarget?.removeEventListener(
- 'lostpointercapture',
- handleLostPointerCapture,
- );
-
- if (activeCaptureTarget?.hasPointerCapture?.(pointerId)) {
- try {
- activeCaptureTarget.releasePointerCapture(pointerId);
- } catch {
- // The browser may already have released capture.
- }
- }
- };
-
- const end = (
- reason: PointerSessionEndReason,
- pointerEvent: PointerEvent | null,
- ) => {
- if (ended) {
- return;
- }
-
- ended = true;
- cleanup();
- onEnd(reason, pointerEvent);
- };
-
- function handleMove(moveEvent: PointerEvent) {
- if (moveEvent.pointerId !== pointerId) {
- return;
- }
-
- if ((moveEvent.buttons & buttonMask) === 0) {
- end('buttons-released', moveEvent);
- return;
- }
-
- onMove?.(moveEvent, capturePointer);
- }
-
- function handleUp(upEvent: PointerEvent) {
- if (upEvent.pointerId === pointerId) {
- end('pointerup', upEvent);
- }
- }
-
- function handleCancel(cancelEvent: PointerEvent) {
- if (cancelEvent.pointerId === pointerId) {
- end('pointercancel', cancelEvent);
- }
- }
-
- function handleLostPointerCapture(lostEvent: Event) {
- const pointerEvent = lostEvent as PointerEvent;
- if (pointerEvent.pointerId === pointerId) {
- end('lostpointercapture', pointerEvent);
- }
- }
-
- function handleBlur() {
- end('blur', null);
- }
-
- function handleVisibilityChange() {
- if (document.visibilityState === 'hidden') {
- end('visibilitychange', null);
- }
- }
-
- if (captureTarget !== null) {
- capturePointer(captureTarget);
- }
-
- window.addEventListener('pointermove', handleMove);
- window.addEventListener('pointerup', handleUp);
- window.addEventListener('pointercancel', handleCancel);
- window.addEventListener('blur', handleBlur);
- document.addEventListener('visibilitychange', handleVisibilityChange);
-
- return () => end('manual', null);
-};
-
-// Use for a gesture owned by a Studio control, such as a slider or resize
-// handle. `captureTarget` is normally the pointerdown handler's currentTarget.
-export const startCapturedPointerSession = ({
- event,
- captureTarget,
- onMove,
- onEnd,
-}: {
- event: PointerSessionEvent;
- captureTarget: Element;
- onMove?: (event: PointerEvent) => void;
- onEnd: (reason: PointerSessionEndReason, event: PointerEvent | null) => void;
-}) => {
- return startPointerSession({event, captureTarget, onMove, onEnd});
-};
-
-// Use when a click must remain targeted at the element under the pointer, but
-// an actual drag needs a stable capture target. Call `capturePointer()` from
-// `onMove` once the movement qualifies as a drag.
-export const startDeferredCapturedPointerSession = ({
- event,
- captureTarget,
- onMove,
- onEnd,
-}: {
- event: PointerSessionEvent;
- captureTarget: Element;
- onMove: (event: PointerEvent, capturePointer: () => void) => void;
- onEnd: (reason: PointerSessionEndReason, event: PointerEvent | null) => void;
-}) => {
- return startPointerSession({
- event,
- captureTarget: null,
- onMove: (moveEvent, capturePointer) => {
- onMove(moveEvent, () => capturePointer(captureTarget));
- },
- onEnd,
- });
-};
-
-// Use when observing a gesture that started elsewhere. This deliberately does
-// not capture the pointer from the element under it.
-export const observePointerRelease = ({
- event,
- onEnd,
-}: {
- event: PointerSessionEvent;
- onEnd: (reason: PointerSessionEndReason, event: PointerEvent | null) => void;
-}) => {
- return startPointerSession({
- event,
- captureTarget: null,
- onEnd,
- });
-};
+export const {
+ isPointerSessionRelease,
+ observePointerRelease,
+ startCapturedPointerSession,
+ startDeferredCapturedPointerSession,
+} = CanvasInternals;
diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.ts
index 139b666df6..b92ca7c7fa 100644
--- a/packages/studio/src/test/timeline-selection.test.ts
+++ b/packages/studio/src/test/timeline-selection.test.ts
@@ -36,7 +36,6 @@ import {
type SelectedOutlineUvHandle,
} from '../components/selected-outline-uv';
import {
- applySelectedOutlineDragAxisLock,
applySelectedOutlineTransformOriginAxisLock,
compensateTranslateForTransformOrigin,
getOutlineSelectionInteraction,
@@ -46,10 +45,6 @@ import {
getSelectedOutlineCropDragChanges,
getSelectedOutlineCropDragValues,
getSelectedOutlineCropFollowingTransformOrigin,
- getSelectedOutlineDragChanges,
- getSelectedOutlineDragValues,
- getSelectedOutlineKeyboardNudgeDelta,
- getSelectedOutlineKeyboardNudgeDeltas,
getSelectedOutlineRotationCornerInfo,
getSelectedOutlineRotationDeltaDegrees,
getSelectedOutlineRotationDragChanges,
@@ -63,15 +58,12 @@ import {
getSelectedSequenceKeys,
getSequencesWithSelectableOutlines,
getTransformedSvgViewportPoints,
- isSelectedOutlineDragPastThreshold,
orderOutlinesForRendering,
- selectedOutlineDragThresholdPx,
selectedOutlineTransformOriginSnapThresholdPx,
selectedOutlineUvSnapThresholdPx,
snapSelectedOutlineRotationDeltaDegrees,
snapSelectedOutlineTransformOriginUv,
snapSelectedOutlineUv,
- type SelectedOutlineDragState,
type SelectedOutlineRotationDragState,
type SelectedOutlineScaleDragState,
} from '../components/SelectedOutlineOverlay';
@@ -4872,7 +4864,6 @@ test('Crop handle changes preserve static and keyframed field behavior', () => {
sourceFrame: 12,
value: 0.35,
schema,
- clientId: 'client',
},
]);
@@ -6943,92 +6934,6 @@ test('Backspace reset skips keyframed sequence props without defaults', () => {
expect(resetTargets).toEqual([]);
});
-test('Selected outline dragging applies the same delta to all selected sequences', () => {
- const schema = {
- 'style.translate': {type: 'translate', default: '0px 0px'},
- } satisfies InteractivitySchema;
- const firstNodePath = makeKey(['body', 0]);
- const secondNodePath = makeKey(['body', 1]);
- const dragStates = [
- {
- defaultValue: JSON.stringify('0px 0px'),
- key: Internals.makeSequencePropsSubscriptionKey(firstNodePath),
- sourceFrame: 12,
- startX: 10,
- startY: 20,
- startZ: 30,
- target: {
- clientId: 'client',
- propStatus: {
- status: 'static',
- keyframeDisplayOffsetAdjustment: null,
- codeValue: '10px 20px 30px',
- },
- fieldDefault: '0px 0px',
- keyframeDisplayOffset: 30,
- keyframePlaybackRate: 1,
- nodePath: firstNodePath,
- schema,
- },
- },
- {
- defaultValue: JSON.stringify('0px 0px'),
- key: Internals.makeSequencePropsSubscriptionKey(secondNodePath),
- sourceFrame: 12,
- startX: -5,
- startY: 3,
- startZ: null,
- target: {
- clientId: 'client',
- propStatus: {
- status: 'static',
- keyframeDisplayOffsetAdjustment: null,
- codeValue: '-5px 3px',
- },
- fieldDefault: '0px 0px',
- keyframeDisplayOffset: 30,
- keyframePlaybackRate: 1,
- nodePath: secondNodePath,
- schema,
- },
- },
- ] satisfies SelectedOutlineDragState[];
-
- const lastValues = getSelectedOutlineDragValues({
- dragStates,
- deltaX: 7.333333,
- deltaY: -4.666667,
- });
-
- expect(lastValues.get(dragStates[0].key)).toBe('17.3px 15.3px 30px');
- expect(lastValues.get(dragStates[1].key)).toBe('2.3px -1.7px');
- expect(
- getSelectedOutlineDragChanges({
- dragStates,
- lastValues,
- }),
- ).toEqual([
- {
- type: 'static',
- fileName: '/project/src/Comp.tsx',
- nodePath: firstNodePath,
- fieldKey: 'style.translate',
- value: '17.3px 15.3px 30px',
- defaultValue: JSON.stringify('0px 0px'),
- schema,
- },
- {
- type: 'static',
- fileName: '/project/src/Comp.tsx',
- nodePath: secondNodePath,
- fieldKey: 'style.translate',
- value: '2.3px -1.7px',
- defaultValue: JSON.stringify('0px 0px'),
- schema,
- },
- ]);
-});
-
test('Selected outline active schema exposes default Sequence translate controls', () => {
const activeSchema = getSelectedOutlineActiveSchema({
schema: NoReactInternals.sequenceSchema,
@@ -7061,248 +6966,6 @@ test('Selected outline active schema exposes default Sequence translate controls
expect(translateField.default).toBe('0px 0px');
});
-test('Selected outline dragging can lock movement to the dominant axis', () => {
- expect(
- applySelectedOutlineDragAxisLock({
- deltaX: 12,
- deltaY: 7,
- axisLocked: true,
- }),
- ).toEqual({deltaX: 12, deltaY: 0});
- expect(
- applySelectedOutlineDragAxisLock({
- deltaX: 12,
- deltaY: 13,
- axisLocked: true,
- }),
- ).toEqual({deltaX: 0, deltaY: 13});
- expect(
- applySelectedOutlineDragAxisLock({
- deltaX: 12,
- deltaY: 13,
- axisLocked: false,
- }),
- ).toEqual({deltaX: 12, deltaY: 13});
-});
-
-test('Selected outline keyboard nudging moves by one or ten pixels', () => {
- const schema = {
- 'style.translate': {type: 'translate', default: '0px 0px'},
- } satisfies InteractivitySchema;
- const nodePath = makeKey(['body', 0]);
- const dragStates = [
- {
- defaultValue: JSON.stringify('0px 0px'),
- key: Internals.makeSequencePropsSubscriptionKey(nodePath),
- sourceFrame: 12,
- startX: 10,
- startY: 20,
- startZ: null,
- target: {
- clientId: 'client',
- propStatus: {
- status: 'static',
- keyframeDisplayOffsetAdjustment: null,
- codeValue: '10px 20px',
- },
- fieldDefault: '0px 0px',
- keyframeDisplayOffset: 30,
- keyframePlaybackRate: 1,
- nodePath,
- schema,
- },
- },
- ] satisfies SelectedOutlineDragState[];
-
- expect(
- getSelectedOutlineKeyboardNudgeDelta({
- direction: 'left',
- shiftKey: false,
- }),
- ).toBe(-1);
- expect(
- getSelectedOutlineKeyboardNudgeDelta({
- direction: 'right',
- shiftKey: true,
- }),
- ).toBe(10);
- expect(
- getSelectedOutlineKeyboardNudgeDelta({
- direction: 'up',
- shiftKey: false,
- }),
- ).toBe(-1);
- expect(
- getSelectedOutlineKeyboardNudgeDelta({
- direction: 'down',
- shiftKey: true,
- }),
- ).toBe(10);
- const accumulatedDeltas = [
- {direction: 'right', shiftKey: false},
- {direction: 'right', shiftKey: false},
- {direction: 'down', shiftKey: true},
- ] satisfies readonly {
- readonly direction: 'left' | 'right' | 'up' | 'down';
- readonly shiftKey: boolean;
- }[];
- const finalDeltas = accumulatedDeltas.reduce(
- (deltas, keyPress) =>
- getSelectedOutlineKeyboardNudgeDeltas({
- ...deltas,
- direction: keyPress.direction,
- shiftKey: keyPress.shiftKey,
- }),
- {deltaX: 0, deltaY: 0},
- );
-
- expect(finalDeltas).toEqual({deltaX: 2, deltaY: 10});
-
- const horizontalLastValues = getSelectedOutlineDragValues({
- dragStates,
- deltaX: getSelectedOutlineKeyboardNudgeDelta({
- direction: 'right',
- shiftKey: true,
- }),
- deltaY: 0,
- });
-
- expect(horizontalLastValues.get(dragStates[0].key)).toBe('20px 20px');
- expect(
- getSelectedOutlineDragChanges({
- dragStates,
- lastValues: horizontalLastValues,
- }),
- ).toEqual([
- {
- type: 'static',
- fileName: '/project/src/Comp.tsx',
- nodePath,
- fieldKey: 'style.translate',
- value: '20px 20px',
- defaultValue: JSON.stringify('0px 0px'),
- schema,
- },
- ]);
-
- const verticalLastValues = getSelectedOutlineDragValues({
- dragStates,
- deltaX: 0,
- deltaY: getSelectedOutlineKeyboardNudgeDelta({
- direction: 'down',
- shiftKey: true,
- }),
- });
-
- expect(verticalLastValues.get(dragStates[0].key)).toBe('10px 30px');
- expect(
- getSelectedOutlineDragChanges({
- dragStates,
- lastValues: verticalLastValues,
- }),
- ).toEqual([
- {
- type: 'static',
- fileName: '/project/src/Comp.tsx',
- nodePath,
- fieldKey: 'style.translate',
- value: '10px 30px',
- defaultValue: JSON.stringify('0px 0px'),
- schema,
- },
- ]);
-});
-
-test('Selected outline dragging starts after a screen pixel threshold', () => {
- expect(
- isSelectedOutlineDragPastThreshold({
- deltaX: selectedOutlineDragThresholdPx - 0.1,
- deltaY: 0,
- }),
- ).toBe(false);
- expect(
- isSelectedOutlineDragPastThreshold({
- deltaX: selectedOutlineDragThresholdPx,
- deltaY: 0,
- }),
- ).toBe(true);
- expect(
- isSelectedOutlineDragPastThreshold({
- deltaX: 3,
- deltaY: 3,
- }),
- ).toBe(true);
-});
-
-test('Selected outline dragging keyframed translate adds a keyframe at the source frame', () => {
- const schema = {
- 'style.translate': {type: 'translate', default: '0px 0px'},
- } satisfies InteractivitySchema;
- const nodePath = makeKey(['body', 0]);
- const dragStates = [
- {
- defaultValue: JSON.stringify('0px 0px'),
- key: Internals.makeSequencePropsSubscriptionKey(nodePath),
- sourceFrame: 20,
- startX: 50,
- startY: 25,
- startZ: 15,
- target: {
- clientId: 'client',
- propStatus: {
- status: 'keyframed',
- keyframeDisplayOffsetAdjustment: null,
- interpolationFunction: 'interpolate',
- keyframes: [
- {frame: 0, value: '0px 0px 15px'},
- {frame: 40, value: '100px 50px 15px'},
- ],
- easing: [{type: 'linear'}],
- clamping: {left: 'extend', right: 'extend'},
- posterize: undefined,
- output: undefined,
- },
- fieldDefault: '0px 0px',
- keyframeDisplayOffset: 30,
- keyframePlaybackRate: 1,
- nodePath,
- schema,
- },
- },
- ] satisfies SelectedOutlineDragState[];
-
- const lastValues = getSelectedOutlineDragValues({
- dragStates,
- deltaX: 7,
- deltaY: -4,
- });
-
- expect(lastValues.get(dragStates[0].key)).toBe('57px 21px 15px');
- expect(
- getSelectedOutlineDragChanges({
- dragStates,
- lastValues,
- }),
- ).toEqual([
- {
- type: 'keyframed',
- fileName: '/project/src/Comp.tsx',
- nodePath,
- fieldKey: 'style.translate',
- sourceFrame: 20,
- value: '57px 21px 15px',
- schema,
- clientId: 'client',
- },
- ]);
- expect(
- getSelectedOutlineDragChanges({
- dragStates,
- lastValues: new Map([[dragStates[0].key, '50px 25px 15px']]),
- }),
- ).toEqual([]);
-});
-
test('Selected outline edge dragging scales one axis when scale is unlinked', () => {
const schema = {
'style.scale': {type: 'scale', default: 1, max: 100},
@@ -7847,7 +7510,6 @@ test('Selected outline corner dragging keyframed rotation adds a keyframe at the
sourceFrame: 20,
value: '60deg',
schema,
- clientId: 'client',
},
]);
expect(
diff --git a/packages/template-vibe-code/README.md b/packages/template-vibe-code/README.md
index a265e8b5d5..114b6008e6 100644
--- a/packages/template-vibe-code/README.md
+++ b/packages/template-vibe-code/README.md
@@ -3,7 +3,7 @@
A Remotion template that turns the browser into a motion graphics editor: write React code, watch it compile instantly, and edit the result on the canvas, in the timeline and in the inspector — no backend, no bundler process.
- **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. Switch to “Interact” mode to use the composition’s own buttons and inputs.
+- **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.
- **Code editor** – Monaco with multiple files, tabs, compiler diagnostics and “Reveal in code” from any layer.
@@ -66,6 +66,8 @@ The browser bundler records where every JSX element was written, and the Canvas
Dragging a value in the inspector or a track in the timeline does not rewrite the source on every pointer move. The editor previews the value on the canvas with [`controller.overrides`](https://www.remotion.dev/docs/canvas/create-canvas-controller#overrides) and writes it with a codemod once the gesture ends. The preview stays in place until the recompiled project is running, so the canvas never flashes the old value.
+Moving 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.
+
## Commands
**Start the editor**
diff --git a/packages/template-vibe-code/src/editor/Editor.tsx b/packages/template-vibe-code/src/editor/Editor.tsx
index db5e3b18a9..c57c89b9a0 100644
--- a/packages/template-vibe-code/src/editor/Editor.tsx
+++ b/packages/template-vibe-code/src/editor/Editor.tsx
@@ -1,5 +1,9 @@
"use client";
+import type {
+ CanvasSequencePropChange,
+ CanvasSequencePropStatusResolver,
+} from "@remotion/canvas";
import { resolveCompositionComponent } from "@remotion/codemods";
import React, {
useCallback,
@@ -22,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 { getSequencePropStatuses } from "./model/layers";
import { toCodemodProject, type ProjectFiles } from "./model/project";
import { EditorContext, type EditorContextValue } from "./state/editor-context";
import {
@@ -131,11 +136,30 @@ export const Editor: React.FC<{
(event: PreviewKeyEvent) => shortcutHandlerRef.current(event),
[],
);
+ // The actions are created below, after the host they operate on exists.
+ const sequencePropsChangeHandlerRef = useRef<
+ (changes: readonly CanvasSequencePropChange[]) => void
+ >(() => undefined);
+ const onPreviewSequencePropsChange = useCallback(
+ (changes: readonly CanvasSequencePropChange[]) =>
+ sequencePropsChangeHandlerRef.current(changes),
+ [],
+ );
+ const sequencePropStatusResolverRef =
+ useRef<CanvasSequencePropStatusResolver>(() => null);
+ const getPreviewSequencePropStatuses =
+ useCallback<CanvasSequencePropStatusResolver>(
+ (nodePathInfo, keys) =>
+ sequencePropStatusResolverRef.current(nodePathInfo, keys),
+ [],
+ );
const { host, error: hostError } = usePreviewHost({
iframeRef,
onError: onPreviewError,
onKeyDown: onPreviewKeyDown,
+ onSequencePropsChange: onPreviewSequencePropsChange,
+ getSequencePropStatuses: getPreviewSequencePropStatuses,
});
const playback = usePlaybackStore({ host, onError: onPreviewError });
const composition = useSyncExternalStore(
@@ -234,6 +258,22 @@ export const Editor: React.FC<{
playback,
context: { state, host, layers, compositions, fps: compositionFps },
});
+ sequencePropsChangeHandlerRef.current = (changes) => {
+ void actions.commitSequencePropChanges(changes);
+ };
+ // The canvas asks before a move starts; analyze the files the edit applies to.
+ sequencePropStatusResolverRef.current = (nodePathInfo, keys) =>
+ getSequencePropStatuses({
+ project,
+ nodePathInfo,
+ keys,
+ videoConfig: {
+ width: compositionWidth,
+ height: compositionHeight,
+ fps: compositionFps,
+ durationInFrames: compositionDurationInFrames,
+ },
+ });
// Previewed values are released once the preview runs the committed source
// or the compilation failed, so they never linger over stale output.
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.ts
index 3ff2dc03ef..afcf47684f 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
@@ -3,6 +3,7 @@
import {
getCanvasSelectionItemKey,
type CanvasSelectionInteraction,
+ type CanvasSequencePropChange,
type SequenceNodePathInfo,
} from "@remotion/canvas";
import {
@@ -20,6 +21,8 @@ import {
setCompositionDefaultProps,
splitSequences,
updateCompositionMetadata,
+ updateMultipleNodeProps,
+ updateNodeKeyframes,
updateNodeProps,
wrapNode,
type CodemodElement,
@@ -27,6 +30,8 @@ import {
type CodemodResult,
type CodemodValue,
type CompositionMetadata,
+ type NodeKeyframeUpdate,
+ type NodePropChange,
type NodeReference,
type SequencePropUpdate,
} from "@remotion/codemods";
@@ -489,6 +494,156 @@ export const ${componentName}: React.FC = () => {
return ok;
},
+ /**
+ * Writes the values of a canvas gesture, such as dragging outlines, to
+ * the source. The canvas keeps previewing them until `releasePreviews`.
+ */
+ commitSequencePropChanges: async (
+ 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,
+ });
+ }
+ }
+
+ if (nodeChanges.size === 0) {
+ return false;
+ }
+
+ 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;
+ },
/** Called once the preview shows the committed source again. */
releasePreviews: () => {
const controller = ref.current.host?.controller;
diff --git a/packages/template-vibe-code/src/editor/hooks/use-preview-host.ts b/packages/template-vibe-code/src/editor/hooks/use-preview-host.ts
index da8a189512..874abcbb9c 100644
--- a/packages/template-vibe-code/src/editor/hooks/use-preview-host.ts
+++ b/packages/template-vibe-code/src/editor/hooks/use-preview-host.ts
@@ -1,5 +1,9 @@
"use client";
+import type {
+ CanvasSequencePropChange,
+ CanvasSequencePropStatusResolver,
+} from "@remotion/canvas";
import { useEffect, useRef, useState } from "react";
import type { PreviewHost, PreviewKeyEvent } from "@/preview/bridge";
@@ -14,17 +18,25 @@ export const usePreviewHost = ({
iframeRef,
onError,
onKeyDown,
+ onSequencePropsChange,
+ getSequencePropStatuses,
}: {
iframeRef: React.RefObject<HTMLIFrameElement | null>;
onError: (message: string) => void;
onKeyDown: (event: PreviewKeyEvent) => boolean;
+ onSequencePropsChange: (changes: readonly CanvasSequencePropChange[]) => void;
+ getSequencePropStatuses: CanvasSequencePropStatusResolver;
}) => {
const [host, setHost] = useState<PreviewHost | null>(null);
const [error, setError] = useState<string | null>(null);
const onErrorRef = useRef(onError);
const onKeyDownRef = useRef(onKeyDown);
+ const onSequencePropsChangeRef = useRef(onSequencePropsChange);
+ const getSequencePropStatusesRef = useRef(getSequencePropStatuses);
onErrorRef.current = onError;
onKeyDownRef.current = onKeyDown;
+ onSequencePropsChangeRef.current = onSequencePropsChange;
+ getSequencePropStatusesRef.current = getSequencePropStatuses;
useEffect(() => {
const iframe = iframeRef.current;
@@ -71,6 +83,10 @@ export const usePreviewHost = ({
created = createPreviewHost({
onError: (message) => onErrorRef.current(message),
onKeyDown: (event) => onKeyDownRef.current(event),
+ onSequencePropsChange: (changes) =>
+ onSequencePropsChangeRef.current(changes),
+ getSequencePropStatuses: (nodePathInfo, keys) =>
+ getSequencePropStatusesRef.current(nodePathInfo, keys),
});
window.clearTimeout(timeout);
setHost(created);
diff --git a/packages/template-vibe-code/src/editor/model/layers.ts b/packages/template-vibe-code/src/editor/model/layers.ts
index f2369829c5..de607a6e8d 100644
--- a/packages/template-vibe-code/src/editor/model/layers.ts
+++ b/packages/template-vibe-code/src/editor/model/layers.ts
@@ -6,12 +6,17 @@ import {
type TimelineTrackData,
} from "@remotion/canvas";
import {
+ getNodeProps,
getNodes,
type CodemodProject,
type CodemodNode,
type NodeReference,
} from "@remotion/codemods";
-import type { SequencePropsSubscriptionKey } from "remotion";
+import type {
+ CanUpdateSequencePropStatus,
+ SequencePropsSubscriptionKey,
+ VideoConfigValues,
+} from "remotion";
export type Layer = {
track: TimelineTrackData;
@@ -139,6 +144,34 @@ export const getNodeReference = (
return { filePath: absolutePath, nodePath };
};
+/**
+ * How the props of a sequence are written in the source, for the Canvas to
+ * decide what can be moved. `null` when the sequence has no source node or the
+ * file cannot be analyzed.
+ */
+export const getSequencePropStatuses = ({
+ project,
+ nodePathInfo,
+ keys,
+ videoConfig,
+}: {
+ project: CodemodProject;
+ nodePathInfo: SequenceNodePathInfo;
+ keys: readonly string[];
+ videoConfig: VideoConfigValues;
+}): Record<string, CanUpdateSequencePropStatus> | null => {
+ const node = getNodeReference({ type: "sequence", nodePathInfo });
+ if (!node) {
+ return null;
+ }
+
+ try {
+ return getNodeProps({ project, node, keys: [...keys], videoConfig }).props;
+ } catch {
+ return null;
+ }
+};
+
/** Two JSX elements that are children of the same parent element. */
export const areSiblingNodes = (a: NodeReference, b: NodeReference) => {
if (a.filePath !== b.filePath || a.nodePath.length !== b.nodePath.length) {
diff --git a/packages/template-vibe-code/src/preview/bridge.ts b/packages/template-vibe-code/src/preview/bridge.ts
index 2294e95156..843f513f71 100644
--- a/packages/template-vibe-code/src/preview/bridge.ts
+++ b/packages/template-vibe-code/src/preview/bridge.ts
@@ -7,7 +7,11 @@
import type { BrowserBundle } from "@remotion/browser-bundler";
import type { BrowserComposition } from "@remotion/browser-bundler/runtime";
-import type { CanvasController } from "@remotion/canvas";
+import type {
+ CanvasController,
+ CanvasSequencePropChange,
+ CanvasSequencePropStatusResolver,
+} from "@remotion/canvas";
import type { PlayerRef } from "@remotion/player";
import type {
CanRenderMediaOnWebResult,
@@ -108,6 +112,13 @@ export type PreviewHost = {
export type CreatePreviewHost = (callbacks: {
onError: (message: string) => void;
onKeyDown: (event: PreviewKeyEvent) => boolean;
+ /**
+ * The user moved outlines on the canvas. The values are previewed through
+ * `controller.overrides` until the editor clears them.
+ */
+ onSequencePropsChange: (changes: readonly CanvasSequencePropChange[]) => void;
+ /** How the props are written in the source; decides what can be moved. */
+ getSequencePropStatuses: CanvasSequencePropStatusResolver;
}) => PreviewHost;
declare global {
diff --git a/packages/template-vibe-code/src/preview/runtime.tsx b/packages/template-vibe-code/src/preview/runtime.tsx
index bf19fdd75c..7f3f344ddd 100644
--- a/packages/template-vibe-code/src/preview/runtime.tsx
+++ b/packages/template-vibe-code/src/preview/runtime.tsx
@@ -3,7 +3,12 @@ import {
createBrowserCompositionObserver,
type BrowserComposition,
} from "@remotion/browser-bundler/runtime";
-import { Canvas, createCanvasController } from "@remotion/canvas";
+import {
+ Canvas,
+ createCanvasController,
+ type CanvasSequencePropsChangeHandler,
+ type CanvasSequencePropStatusResolver,
+} from "@remotion/canvas";
import type { PlayerRef } from "@remotion/player";
import {
canRenderMediaOnWeb,
@@ -81,7 +86,15 @@ const PreviewApp: React.FC<{
readonly store: PreviewStore;
readonly controller: ReturnType<typeof createCanvasController>;
readonly onReady: (revision: number) => void;
-}> = ({ store, controller, onReady }) => {
+ readonly onSequencePropsChange: CanvasSequencePropsChangeHandler;
+ readonly getSequencePropStatuses: CanvasSequencePropStatusResolver;
+}> = ({
+ store,
+ controller,
+ onReady,
+ onSequencePropsChange,
+ getSequencePropStatuses,
+}) => {
const state = useSyncExternalStore(
store.subscribe,
store.getState,
@@ -159,6 +172,8 @@ const PreviewApp: React.FC<{
ref={setPlayer}
controller={controller}
showOutlines={options.showOutlines}
+ onSequencePropsChange={onSequencePropsChange}
+ getSequencePropStatuses={getSequencePropStatuses}
component={composition.component}
inputProps={composition.props}
compositionWidth={composition.width}
@@ -219,6 +234,8 @@ const isEditableTarget = (target: EventTarget | null) =>
export const createPreviewHost: CreatePreviewHost = ({
onError,
onKeyDown,
+ onSequencePropsChange,
+ getSequencePropStatuses,
}) => {
const container = document.getElementById("preview-root");
if (!container) {
@@ -276,7 +293,13 @@ export const createPreviewHost: CreatePreviewHost = ({
onUncaughtError: reportError,
});
root.render(
- <PreviewApp store={store} controller={controller} onReady={onReady} />,
+ <PreviewApp
+ store={store}
+ controller={controller}
+ onReady={onReady}
+ onSequencePropsChange={onSequencePropsChange}
+ getSequencePropStatuses={getSequencePropStatuses}
+ />,
);
const observer = createBrowserCompositionObserver({