🎥 Make videos programmatically with React
@remotion/canvas: Extract Studio selection state
JonnyBurger4c2d0ad08cc4
diff --git a/packages/canvas/README.md b/packages/canvas/README.mdindex 78e215b23e..6ac3a14ba5 100644--- a/packages/canvas/README.md+++ b/packages/canvas/README.md@@ -19,12 +19,9 @@ controller.selection.subscribe(() => {});controller.selection.select(- {- type: 'property',- entity: {type: 'sequence', id: 'title'},- propertyPath: ['style', 'opacity'],- },- 'add',+ sequenceSelection,+ {shiftKey: false, toggleKey: false},+ allSelectableSequences,);<Canvasdiff --git a/packages/canvas/src/canvas-controller.ts b/packages/canvas/src/canvas-controller.tsindex 961b651006..22d8a6fa26 100644--- a/packages/canvas/src/canvas-controller.ts+++ b/packages/canvas/src/canvas-controller.ts@@ -1,12 +1,10 @@-import {useState, useSyncExternalStore} from 'react';+import {useState} from 'react';import type {TSequence} from 'remotion';import {calculateTimeline} from './calculate-timeline';import type {TimelineTrackData} from './get-timeline-sequence-sort-key';import {- getCanvasSelectionItemKey,- type CanvasSelectionItem,- type CanvasSelectionMode,- type CanvasSelectionSnapshot,+ createCanvasSelectionController,+ type CanvasSelectionController,} from './selection';export type CanvasController = {@@ -14,16 +12,7 @@ export type CanvasController = {readonly getSnapshot: () => readonly TimelineTrackData[];readonly subscribe: (listener: () => void) => () => void;};- readonly selection: {- readonly getSnapshot: () => CanvasSelectionSnapshot;- readonly subscribe: (listener: () => void) => () => void;- readonly select: (- item: CanvasSelectionItem,- mode: CanvasSelectionMode,- ) => void;- readonly setSelectedItems: (items: readonly CanvasSelectionItem[]) => void;- readonly clear: () => void;- };+ readonly selection: CanvasSelectionController;};type CanvasControllerInternals = {@@ -38,12 +27,7 @@ const controllerInternals = new WeakMap<export const createCanvasController = (): CanvasController => {let timelineSnapshot: readonly TimelineTrackData[] = [];- let selectionSnapshot: CanvasSelectionSnapshot = {- selectedItems: [],- anchor: null,- };const timelineListeners = new Set<() => void>();- const selectionListeners = new Set<() => void>();const updateTimelineSnapshot = (nextSnapshot: readonly TimelineTrackData[],@@ -54,16 +38,6 @@ export const createCanvasController = (): CanvasController => {}};- const updateSelectionSnapshot = (- selectedItems: readonly CanvasSelectionItem[],- anchor: CanvasSelectionItem | null,- ) => {- selectionSnapshot = {selectedItems, anchor};- for (const listener of selectionListeners) {- listener();- }- };-const controller: CanvasController = {timeline: {getSnapshot: () => timelineSnapshot,@@ -72,65 +46,7 @@ export const createCanvasController = (): CanvasController => {return () => timelineListeners.delete(listener);},},- selection: {- getSnapshot: () => selectionSnapshot,- subscribe: (listener) => {- selectionListeners.add(listener);- return () => selectionListeners.delete(listener);- },- select: (item, mode) => {- const itemKey = getCanvasSelectionItemKey(item);- const selectedItemIndex = selectionSnapshot.selectedItems.findIndex(- (selectedItem) => getCanvasSelectionItemKey(selectedItem) === itemKey,- );-- if (mode === 'replace') {- updateSelectionSnapshot([item], item);- return;- }-- if (mode === 'add') {- if (selectedItemIndex === -1) {- updateSelectionSnapshot(- [...selectionSnapshot.selectedItems, item],- item,- );- }-- return;- }-- if (selectedItemIndex === -1) {- updateSelectionSnapshot(- [...selectionSnapshot.selectedItems, item],- item,- );- return;- }-- const nextSelectedItems = selectionSnapshot.selectedItems.filter(- (_selectedItem, index) => index !== selectedItemIndex,- );- updateSelectionSnapshot(- nextSelectedItems,- nextSelectedItems.at(-1) ?? null,- );- },- setSelectedItems: (items) => {- const keys = new Set<string>();- const selectedItems = items.filter((item) => {- const key = getCanvasSelectionItemKey(item);- if (keys.has(key)) {- return false;- }-- keys.add(key);- return true;- });- updateSelectionSnapshot(selectedItems, selectedItems.at(-1) ?? null);- },- clear: () => updateSelectionSnapshot([], null),- },+ selection: createCanvasSelectionController(),};controllerInternals.set(controller, {@@ -153,16 +69,6 @@ export const useCanvasController = (): CanvasController => {return controller;};-export const useCanvasSelection = (- controller: CanvasController,-): CanvasSelectionSnapshot => {- return useSyncExternalStore(- controller.selection.subscribe,- controller.selection.getSnapshot,- controller.selection.getSnapshot,- );-};-export const getCanvasControllerInternals = (controller: CanvasController,): CanvasControllerInternals => {diff --git a/packages/canvas/src/index.ts b/packages/canvas/src/index.tsindex b7134a2661..e4b4b2edd9 100644--- a/packages/canvas/src/index.ts+++ b/packages/canvas/src/index.ts@@ -1,11 +1,7 @@export {calculateTimeline} from './calculate-timeline';export {Canvas} from './canvas';export type {CanvasProps} from './canvas';-export {- createCanvasController,- useCanvasController,- useCanvasSelection,-} from './canvas-controller';+export {createCanvasController, useCanvasController} from './canvas-controller';export type {CanvasController} from './canvas-controller';export {getConnectedCompositions} from './get-connected-compositions';export {@@ -21,12 +17,19 @@ export type {TimelineTrackData,TimelineTrackWithOriginalTimings,} from './get-timeline-sequence-sort-key';-export {getCanvasSelectionItemKey} from './selection';+export {+ createCanvasSelectionController,+ EMPTY_CANVAS_SELECTION,+ getCanvasSelectionAfterInteraction,+ getCanvasSelectionItemKey,+ getCanvasSequenceSelectionKey,+ useCanvasSelection,+ useCanvasSelectionController,+} from './selection';export type {- CanvasEntityReference,- CanvasPropertyPath,+ CanvasSelectionController,CanvasSelectionItem,- CanvasSelectionMode,+ CanvasSelectionInteraction,CanvasSelectionSnapshot,} from './selection';export {diff --git a/packages/canvas/src/selection.ts b/packages/canvas/src/selection.tsindex 6f9f2b8a40..f83c734774 100644--- a/packages/canvas/src/selection.ts+++ b/packages/canvas/src/selection.ts@@ -1,40 +1,43 @@-export type CanvasEntityReference =+import {useState, useSyncExternalStore} from 'react';+import type {SequenceNodePathInfo} from './get-timeline-sequence-sort-key';++export type CanvasSelectionItem =+ | {+ readonly type: 'guide';+ readonly guideId: string;+ }| {readonly type: 'sequence';- readonly id: string;+ readonly nodePathInfo: SequenceNodePathInfo;}| {- readonly type: 'effect';- readonly id: string;- readonly sequenceId: string;+ readonly type: 'sequence-prop';+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly key: string;}| {- readonly type: 'guide';- readonly id: string;- };--export type CanvasPropertyPath = readonly (string | number)[];--export type CanvasSelectionItem =+ readonly type: 'sequence-all-effects';+ readonly nodePathInfo: SequenceNodePathInfo;+ }| {- readonly type: 'entity';- readonly entity: CanvasEntityReference;+ readonly type: 'sequence-effect';+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly i: number;}| {- readonly type: 'property';- readonly entity: CanvasEntityReference;- readonly propertyPath: CanvasPropertyPath;+ readonly type: 'sequence-effect-prop';+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly i: number;+ readonly key: string;}| {readonly type: 'keyframe';- readonly entity: CanvasEntityReference;- readonly propertyPath: CanvasPropertyPath;+ readonly nodePathInfo: SequenceNodePathInfo;readonly frame: number;}| {readonly type: 'easing';- readonly entity: CanvasEntityReference;- readonly propertyPath: CanvasPropertyPath;+ readonly nodePathInfo: SequenceNodePathInfo;readonly fromFrame: number;readonly toFrame: number;readonly segmentIndex: number;@@ -45,33 +48,287 @@ export type CanvasSelectionSnapshot = {readonly anchor: CanvasSelectionItem | null;};-export type CanvasSelectionMode = 'replace' | 'add' | 'toggle';+export type CanvasSelectionInteraction = {+ readonly shiftKey: boolean;+ readonly toggleKey: boolean;+};++export const EMPTY_CANVAS_SELECTION: CanvasSelectionSnapshot = {+ selectedItems: [],+ anchor: null,+};++const getCanvasNodePathInfoKey = (info: SequenceNodePathInfo): string =>+ [+ `${info.sequenceSubscriptionKey.absolutePath}:${JSON.stringify(+ info.sequenceSubscriptionKey.nodePath,+ )}:${info.sequenceSubscriptionKey.sequenceKeys.join('\0')}`,+ info.auxiliaryKeys.join('.'),+ info.index,+ ].join('.');++export const getCanvasSequenceSelectionKey = (+ nodePathInfo: SequenceNodePathInfo,+): string => getCanvasNodePathInfoKey({...nodePathInfo, auxiliaryKeys: []});export const getCanvasSelectionItemKey = (item: CanvasSelectionItem,): string => {- const entity =- item.entity.type === 'effect'- ? [item.entity.type, item.entity.sequenceId, item.entity.id]- : [item.entity.type, item.entity.id];-switch (item.type) {- case 'entity':- return JSON.stringify([item.type, entity]);- case 'property':- return JSON.stringify([item.type, entity, item.propertyPath]);+ case 'guide':+ return `guide.${item.guideId}`;+ case 'sequence':+ return `${getCanvasSequenceSelectionKey(item.nodePathInfo)}.sequence`;+ case 'sequence-prop':+ return `${getCanvasSequenceSelectionKey(+ item.nodePathInfo,+ )}.sequence-prop.${item.key}`;+ case 'sequence-all-effects':+ return `${getCanvasSequenceSelectionKey(+ item.nodePathInfo,+ )}.sequence-all-effects`;+ case 'sequence-effect':+ return `${getCanvasSequenceSelectionKey(+ item.nodePathInfo,+ )}.sequence-effect.${item.i}`;+ case 'sequence-effect-prop':+ return `${getCanvasSequenceSelectionKey(+ item.nodePathInfo,+ )}.sequence-effect-prop.${item.i}.${item.key}`;case 'keyframe':- return JSON.stringify([item.type, entity, item.propertyPath, item.frame]);+ return `${getCanvasNodePathInfoKey(item.nodePathInfo)}.keyframe.${+ item.frame+ }`;case 'easing':- return JSON.stringify([- item.type,- entity,- item.propertyPath,- item.fromFrame,- item.toFrame,- item.segmentIndex,- ]);+ return `${getCanvasNodePathInfoKey(item.nodePathInfo)}.easing.${+ item.segmentIndex+ }`;default:- throw new Error('Unknown Canvas selection item');+ throw new Error(+ `Unexpected Canvas selection type: ${item satisfies never}`,+ );+ }+};++const getCanvasSelectionType = (item: CanvasSelectionItem) => item.type;++const areCanvasSelectionTypesCompatible = (+ firstType: CanvasSelectionItem['type'],+ secondType: CanvasSelectionItem['type'],+): boolean => {+ if (firstType === secondType) {+ return true;+ }++ return (+ (firstType === 'sequence-prop' && secondType === 'sequence-effect-prop') ||+ (firstType === 'sequence-effect-prop' && secondType === 'sequence-prop') ||+ (firstType === 'keyframe' && secondType === 'easing') ||+ (firstType === 'easing' && secondType === 'keyframe')+ );+};++const isCanvasSelectionCompatibleWithType = (+ item: CanvasSelectionItem,+ type: CanvasSelectionItem['type'],+) => areCanvasSelectionTypesCompatible(getCanvasSelectionType(item), type);++const getCanvasSelectionAnchor = (+ selectedItems: readonly CanvasSelectionItem[],+ previousAnchor: CanvasSelectionItem | null,+ targetType: CanvasSelectionItem['type'],+) => {+ if (previousAnchor && getCanvasSelectionType(previousAnchor) === targetType) {+ return previousAnchor;}++ for (let i = selectedItems.length - 1; i >= 0; i--) {+ const candidate = selectedItems[i];+ if (getCanvasSelectionType(candidate) === targetType) {+ return candidate;+ }+ }++ return null;+};++const getCanvasRangeSelection = ({+ anchor,+ clickedItem,+ allSelectableItems,+}: {+ readonly anchor: CanvasSelectionItem;+ readonly clickedItem: CanvasSelectionItem;+ readonly allSelectableItems: readonly CanvasSelectionItem[];+}): readonly CanvasSelectionItem[] => {+ const anchorKey = getCanvasSelectionItemKey(anchor);+ const clickedKey = getCanvasSelectionItemKey(clickedItem);+ const orderedOfType = allSelectableItems.filter(+ (item) => getCanvasSelectionType(item) === clickedItem.type,+ );+ const anchorIndex = orderedOfType.findIndex(+ (item) => getCanvasSelectionItemKey(item) === anchorKey,+ );+ const clickedIndex = orderedOfType.findIndex(+ (item) => getCanvasSelectionItemKey(item) === clickedKey,+ );++ if (anchorIndex === -1 || clickedIndex === -1) {+ return [clickedItem];+ }++ const [from, to] =+ anchorIndex < clickedIndex+ ? [anchorIndex, clickedIndex]+ : [clickedIndex, anchorIndex];+ return orderedOfType.slice(from, to + 1);+};++export const getCanvasSelectionAfterInteraction = ({+ currentState,+ clickedItem,+ interaction,+ allSelectableItems,+}: {+ readonly currentState: CanvasSelectionSnapshot;+ readonly clickedItem: CanvasSelectionItem;+ readonly interaction: CanvasSelectionInteraction;+ readonly allSelectableItems: readonly CanvasSelectionItem[];+}): CanvasSelectionSnapshot => {+ const {selectedItems, anchor: previousAnchor} = currentState;+ const clickedType = getCanvasSelectionType(clickedItem);+ if (clickedType === 'guide') {+ return {+ selectedItems: [clickedItem],+ anchor: clickedItem,+ };+ }++ const nextAnchor = getCanvasSelectionAnchor(+ selectedItems,+ previousAnchor,+ clickedType,+ );+ const clickedKey = getCanvasSelectionItemKey(clickedItem);++ if (interaction.shiftKey && nextAnchor) {+ return {+ selectedItems: getCanvasRangeSelection({+ anchor: nextAnchor,+ clickedItem,+ allSelectableItems,+ }),+ anchor: nextAnchor,+ };+ }++ if (interaction.toggleKey) {+ const compatibleItems = selectedItems.filter((item) =>+ isCanvasSelectionCompatibleWithType(item, clickedType),+ );+ const existingKeySet = new Set(+ compatibleItems.map(getCanvasSelectionItemKey),+ );+ if (existingKeySet.has(clickedKey)) {+ const toggledSelection = compatibleItems.filter(+ (item) => getCanvasSelectionItemKey(item) !== clickedKey,+ );+ return {+ selectedItems: toggledSelection,+ anchor: toggledSelection.length === 0 ? null : clickedItem,+ };+ }++ const selectableOrderMap = new Map(+ allSelectableItems+ .filter((item) =>+ isCanvasSelectionCompatibleWithType(item, clickedType),+ )+ .map(+ (item, index) => [getCanvasSelectionItemKey(item), index] as const,+ ),+ );+ const extendedSelection = [...compatibleItems, clickedItem].sort((a, b) => {+ return (+ (selectableOrderMap.get(getCanvasSelectionItemKey(a)) ?? 0) -+ (selectableOrderMap.get(getCanvasSelectionItemKey(b)) ?? 0)+ );+ });+ return {+ selectedItems: extendedSelection,+ anchor: clickedItem,+ };+ }++ return {+ selectedItems: [clickedItem],+ anchor: clickedItem,+ };+};++export type CanvasSelectionController = {+ readonly getSnapshot: () => CanvasSelectionSnapshot;+ readonly subscribe: (listener: () => void) => () => void;+ readonly select: (+ item: CanvasSelectionItem,+ interaction: CanvasSelectionInteraction,+ allSelectableItems: readonly CanvasSelectionItem[],+ ) => void;+ readonly setSelectedItems: (items: readonly CanvasSelectionItem[]) => void;+ readonly setSnapshot: (snapshot: CanvasSelectionSnapshot) => void;+ readonly clear: () => void;+};++export const createCanvasSelectionController =+ (): CanvasSelectionController => {+ let snapshot = EMPTY_CANVAS_SELECTION;+ const listeners = new Set<() => void>();++ const setSnapshot = (nextSnapshot: CanvasSelectionSnapshot) => {+ snapshot = nextSnapshot;+ for (const listener of listeners) {+ listener();+ }+ };++ return {+ getSnapshot: () => snapshot,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ select: (item, interaction, allSelectableItems) => {+ setSnapshot(+ getCanvasSelectionAfterInteraction({+ currentState: snapshot,+ clickedItem: item,+ interaction,+ allSelectableItems,+ }),+ );+ },+ setSelectedItems: (items) => {+ setSnapshot({+ selectedItems: items,+ anchor: items.at(-1) ?? null,+ });+ },+ setSnapshot,+ clear: () => setSnapshot(EMPTY_CANVAS_SELECTION),+ };+ };++export const useCanvasSelectionController = (): CanvasSelectionController => {+ const [controller] = useState(createCanvasSelectionController);+ return controller;+};++export const useCanvasSelection = (+ controller: CanvasSelectionController,+): CanvasSelectionSnapshot => {+ return useSyncExternalStore(+ controller.subscribe,+ controller.getSnapshot,+ controller.getSnapshot,+ );};diff --git a/packages/canvas/src/test/selection.test.ts b/packages/canvas/src/test/selection.test.tsindex 0febc855fd..ae21bc74c8 100644--- a/packages/canvas/src/test/selection.test.ts+++ b/packages/canvas/src/test/selection.test.ts@@ -1,53 +1,96 @@import {expect, test} from 'bun:test';-import {createCanvasController, type CanvasSelectionItem} from '../index';+import {+ createCanvasSelectionController,+ type CanvasSelectionItem,+ type SequenceNodePathInfo,+} from '../index';-test('stores a heterogeneous multi-selection through the public controller', () => {- const controller = createCanvasController();+const makeNodePathInfo = (+ id: string,+ auxiliaryKeys: string[] = [],+): SequenceNodePathInfo => ({+ sequenceSubscriptionKey: {+ absolutePath: '/src/Composition.tsx',+ effectKeys: [],+ nodePath: ['sequence', id],+ sequenceKeys: [],+ videoConfigValues: null,+ },+ auxiliaryKeys,+ index: 0,+ numberOfSequencesWithThisNodePath: 1,+ supportsEffects: true,+});++test('stores Studio-compatible heterogeneous multi-selection state', () => {+ const controller = createCanvasSelectionController();let updates = 0;- const unsubscribe = controller.selection.subscribe(() => {+ const unsubscribe = controller.subscribe(() => {updates++;});- const sequence: CanvasSelectionItem = {- type: 'entity',- entity: {type: 'sequence', id: 'intro'},+ const sequences: CanvasSelectionItem[] = ['intro', 'title', 'outro'].map(+ (id) => ({type: 'sequence', nodePathInfo: makeNodePathInfo(id)}),+ );+ const sequenceProperty: CanvasSelectionItem = {+ type: 'sequence-prop',+ nodePathInfo: makeNodePathInfo('intro', ['controls', 'style.opacity']),+ key: 'style.opacity',};const effectProperty: CanvasSelectionItem = {- type: 'property',- entity: {type: 'effect', id: 'blur', sequenceId: 'intro'},- propertyPath: ['radius'],+ type: 'sequence-effect-prop',+ nodePathInfo: makeNodePathInfo('intro', ['effects', '0', 'radius']),+ i: 0,+ key: 'radius',+ };+ const keyframe: CanvasSelectionItem = {+ type: 'keyframe',+ nodePathInfo: makeNodePathInfo('intro', ['controls', 'style.opacity']),+ frame: 0,};const easing: CanvasSelectionItem = {type: 'easing',- entity: {type: 'sequence', id: 'intro'},- propertyPath: ['style', 'opacity'],+ nodePathInfo: makeNodePathInfo('intro', ['controls', 'style.opacity']),fromFrame: 0,toFrame: 30,segmentIndex: 0,};- controller.selection.select(sequence, 'replace');- controller.selection.select(effectProperty, 'add');- controller.selection.select(easing, 'add');-- expect(controller.selection.getSnapshot()).toEqual({- selectedItems: [sequence, effectProperty, easing],- anchor: easing,+ controller.select(+ sequences[0],+ {shiftKey: false, toggleKey: false},+ sequences,+ );+ controller.select(+ sequences[2],+ {shiftKey: true, toggleKey: false},+ sequences,+ );+ expect(controller.getSnapshot()).toEqual({+ selectedItems: sequences,+ anchor: sequences[0],});+ controller.select(sequenceProperty, {shiftKey: false, toggleKey: false}, [+ sequenceProperty,+ effectProperty,+ ]);+ controller.select(effectProperty, {shiftKey: false, toggleKey: true}, [+ sequenceProperty,+ effectProperty,+ ]);- controller.selection.select(effectProperty, 'toggle');- expect(controller.selection.getSnapshot()).toEqual({- selectedItems: [sequence, easing],- anchor: easing,+ expect(controller.getSnapshot()).toEqual({+ selectedItems: [sequenceProperty, effectProperty],+ anchor: effectProperty,});- controller.selection.setSelectedItems([sequence, sequence, effectProperty]);- expect(controller.selection.getSnapshot()).toEqual({- selectedItems: [sequence, effectProperty],- anchor: effectProperty,+ controller.setSelectedItems([keyframe, easing]);+ expect(controller.getSnapshot()).toEqual({+ selectedItems: [keyframe, easing],+ anchor: easing,});- controller.selection.clear();- expect(controller.selection.getSnapshot()).toEqual({+ controller.clear();+ expect(controller.getSnapshot()).toEqual({selectedItems: [],anchor: null,});diff --git a/packages/player-example/pages/canvas.tsx b/packages/player-example/pages/canvas.tsxindex e015125cfe..e8bb871d46 100644--- a/packages/player-example/pages/canvas.tsx+++ b/packages/player-example/pages/canvas.tsx@@ -4,7 +4,8 @@ import {useCanvasController,useCanvasSelection,type CanvasSelectionItem,- type CanvasSelectionMode,+ type SequenceNodePathInfo,+ type TimelineTrackData,} from '@remotion/canvas';import React, {useSyncExternalStore} from 'react';import {AbsoluteFill, Sequence, useCurrentFrame} from 'remotion';@@ -44,6 +45,26 @@ const CanvasComposition: React.FC = () => {);};+const getExampleNodePathInfo = (+ layer: TimelineTrackData,+): SequenceNodePathInfo => {+ return (+ layer.nodePathInfo ?? {+ sequenceSubscriptionKey: {+ absolutePath: 'canvas-example',+ effectKeys: [],+ nodePath: ['sequence', layer.sequence.id],+ sequenceKeys: [],+ videoConfigValues: null,+ },+ auxiliaryKeys: [],+ index: 0,+ numberOfSequencesWithThisNodePath: 1,+ supportsEffects: layer.sequence.controls?.supportsEffects === true,+ }+ );+};+const CanvasPage: React.FC = () => {const controller = useCanvasController();const layers = useSyncExternalStore(@@ -51,10 +72,14 @@ const CanvasPage: React.FC = () => {controller.timeline.getSnapshot,controller.timeline.getSnapshot,);- const selection = useCanvasSelection(controller);+ const selection = useCanvasSelection(controller.selection);const selectedKeys = new Set(selection.selectedItems.map(getCanvasSelectionItemKey),);+ const selectableLayers: CanvasSelectionItem[] = layers.map((layer) => ({+ type: 'sequence',+ nodePathInfo: getExampleNodePathInfo(layer),+ }));return (<main@@ -103,23 +128,22 @@ const CanvasPage: React.FC = () => {) : (<ol style={{paddingLeft: 24}}>{layers.map((layer) => {- const entity = {- type: 'sequence' as const,- id: layer.sequence.id,- };+ const nodePathInfo = getExampleNodePathInfo(layer);const layerSelection: CanvasSelectionItem = {- type: 'entity',- entity,+ type: 'sequence',+ nodePathInfo,};const opacitySelection: CanvasSelectionItem = {- type: 'property',- entity,- propertyPath: ['style', 'opacity'],+ type: 'sequence-prop',+ nodePathInfo,+ key: 'style.opacity',};const easingSelection: CanvasSelectionItem = {type: 'easing',- entity,- propertyPath: ['style', 'opacity'],+ nodePathInfo: {+ ...nodePathInfo,+ auxiliaryKeys: ['controls', 'style.opacity'],+ },fromFrame: layer.sequence.from,toFrame: Math.min(layer.sequence.from + 30,@@ -149,13 +173,14 @@ const CanvasPage: React.FC = () => {type="button"aria-pressed={layerSelected}onClick={(event) => {- const mode: CanvasSelectionMode =- event.metaKey || event.ctrlKey- ? 'toggle'- : event.shiftKey- ? 'add'- : 'replace';- controller.selection.select(layerSelection, mode);+ controller.selection.select(+ layerSelection,+ {+ shiftKey: event.shiftKey,+ toggleKey: event.metaKey || event.ctrlKey,+ },+ selectableLayers,+ );}}style={{backgroundColor: layerSelected ? '#ddd6fe' : 'white',@@ -181,7 +206,8 @@ const CanvasPage: React.FC = () => {onClick={() =>controller.selection.select(opacitySelection,- 'toggle',+ {shiftKey: false, toggleKey: true},+ [opacitySelection],)}>@@ -193,7 +219,8 @@ const CanvasPage: React.FC = () => {onClick={() =>controller.selection.select(easingSelection,- 'toggle',+ {shiftKey: false, toggleKey: true},+ [easingSelection],)}>@@ -218,9 +245,9 @@ const CanvasPage: React.FC = () => {Selection ({selection.selectedItems.length})</h2><p style={{fontSize: 14}}>- Click a layer to replace the selection. Shift-click adds a layer;- Command/Ctrl-click toggles it. Property and easing buttons toggle- heterogeneous items.+ Click a layer to replace the selection. Shift-click selects a+ contiguous range; Command/Ctrl-click toggles a layer. Property and+ easing buttons demonstrate different selection item types.</p><button type="button" onClick={controller.selection.clear}>Clear selectiondiff --git a/packages/studio/src/components/Timeline/TimelineSelection.tsx b/packages/studio/src/components/Timeline/TimelineSelection.tsxindex 9c7848d626..05072ec72f 100644--- a/packages/studio/src/components/Timeline/TimelineSelection.tsx+++ b/packages/studio/src/components/Timeline/TimelineSelection.tsx@@ -1,3 +1,14 @@+import {+ EMPTY_CANVAS_SELECTION,+ getCanvasSelectionAfterInteraction,+ getCanvasSelectionItemKey,+ getCanvasSequenceSelectionKey,+ useCanvasSelection,+ useCanvasSelectionController,+ type CanvasSelectionInteraction,+ type CanvasSelectionItem,+ type CanvasSelectionSnapshot,+} from '@remotion/canvas';import {canEditEasingForInterpolationFunction,stringifySequenceExpandedRowKey,@@ -139,57 +150,14 @@ export const getTimelineRowHighlightBackground = ({export const TIMELINE_BACKGROUND = TIMELINE_BACKGROUND_COLOR;export const TIMELINE_TICKS_BACKGROUND = BACKGROUND;-export type TimelineSelection =- | {- readonly type: 'guide';- readonly guideId: string;- }- | {- readonly type: 'sequence';- readonly nodePathInfo: SequenceNodePathInfo;- }- | {- readonly type: 'sequence-prop';- readonly nodePathInfo: SequenceNodePathInfo;- readonly key: string;- }- | {- readonly type: 'sequence-all-effects';- readonly nodePathInfo: SequenceNodePathInfo;- }- | {- readonly type: 'sequence-effect';- readonly nodePathInfo: SequenceNodePathInfo;- readonly i: number;- }- | {- readonly type: 'sequence-effect-prop';- readonly nodePathInfo: SequenceNodePathInfo;- readonly i: number;- readonly key: string;- }- | {- readonly type: 'keyframe';- readonly nodePathInfo: SequenceNodePathInfo;- readonly frame: number;- }- | {- readonly type: 'easing';- readonly nodePathInfo: SequenceNodePathInfo;- readonly fromFrame: number;- readonly toFrame: number;- readonly segmentIndex: number;- };+export type TimelineSelection = CanvasSelectionItem;export type TimelineEasingSelection = Extract<TimelineSelection,{type: 'easing'}>;-export type TimelineSelectionInteraction = {- readonly shiftKey: boolean;- readonly toggleKey: boolean;-};+export type TimelineSelectionInteraction = CanvasSelectionInteraction;export const isTimelineSelectionModifierEvent = ({shiftKey,@@ -219,15 +187,10 @@ export const shouldSelectTimelineRowOnPointerDown = ({);};-export type TimelineSelectionState = {- readonly selectedItems: readonly TimelineSelection[];- readonly anchor: TimelineSelection | null;-};+export type TimelineSelectionState = CanvasSelectionSnapshot;-export const EMPTY_TIMELINE_SELECTION_STATE: TimelineSelectionState = {- selectedItems: [],- anchor: null,-};+export const EMPTY_TIMELINE_SELECTION_STATE: TimelineSelectionState =+ EMPTY_CANVAS_SELECTION;export type TimelineMarqueeRect = {readonly left: number;@@ -243,162 +206,8 @@ export type TimelineMarqueeSelectionCandidate = {readonly rect: TimelineMarqueeRect;};-const getTimelineSelectionType = (item: TimelineSelection) => item.type;--const areTimelineSelectionTypesCompatible = (- firstType: TimelineSelection['type'],- secondType: TimelineSelection['type'],-): boolean => {- if (firstType === secondType) {- return true;- }-- return (- (firstType === 'sequence-prop' && secondType === 'sequence-effect-prop') ||- (firstType === 'sequence-effect-prop' && secondType === 'sequence-prop') ||- (firstType === 'keyframe' && secondType === 'easing') ||- (firstType === 'easing' && secondType === 'keyframe')- );-};--const isTimelineSelectionCompatibleWithType = (- item: TimelineSelection,- type: TimelineSelection['type'],-) => areTimelineSelectionTypesCompatible(getTimelineSelectionType(item), type);--const getTimelineSelectionAnchor = (- selectedItems: readonly TimelineSelection[],- previousAnchor: TimelineSelection | null,- targetType: TimelineSelection['type'],-) => {- if (- previousAnchor &&- getTimelineSelectionType(previousAnchor) === targetType- ) {- return previousAnchor;- }-- for (let i = selectedItems.length - 1; i >= 0; i--) {- const candidate = selectedItems[i];- if (getTimelineSelectionType(candidate) === targetType) {- return candidate;- }- }-- return null;-};--const getRangeSelection = ({- anchor,- clickedItem,- allSelectableItems,-}: {- readonly anchor: TimelineSelection;- readonly clickedItem: TimelineSelection;- readonly allSelectableItems: readonly TimelineSelection[];-}): readonly TimelineSelection[] => {- const anchorKey = getTimelineSelectionKey(anchor);- const clickedKey = getTimelineSelectionKey(clickedItem);- const orderedOfType = allSelectableItems.filter(- (item) => getTimelineSelectionType(item) === clickedItem.type,- );- const anchorIndex = orderedOfType.findIndex(- (item) => getTimelineSelectionKey(item) === anchorKey,- );- const clickedIndex = orderedOfType.findIndex(- (item) => getTimelineSelectionKey(item) === clickedKey,- );-- if (anchorIndex === -1 || clickedIndex === -1) {- return [clickedItem];- }-- const [from, to] =- anchorIndex < clickedIndex- ? [anchorIndex, clickedIndex]- : [clickedIndex, anchorIndex];- return orderedOfType.slice(from, to + 1);-};--export const getTimelineSelectionAfterInteraction = ({- currentState,- clickedItem,- interaction,- allSelectableItems,-}: {- readonly currentState: TimelineSelectionState;- readonly clickedItem: TimelineSelection;- readonly interaction: TimelineSelectionInteraction;- readonly allSelectableItems: readonly TimelineSelection[];-}): TimelineSelectionState => {- const {selectedItems, anchor: previousAnchor} = currentState;- const clickedType = getTimelineSelectionType(clickedItem);- if (clickedType === 'guide') {- return {- selectedItems: [clickedItem],- anchor: clickedItem,- };- }-- const nextAnchor = getTimelineSelectionAnchor(- selectedItems,- previousAnchor,- clickedType,- );- const clickedKey = getTimelineSelectionKey(clickedItem);-- if (interaction.shiftKey && nextAnchor) {- return {- selectedItems: getRangeSelection({- anchor: nextAnchor,- clickedItem,- allSelectableItems,- }),- anchor: nextAnchor,- };- }-- if (interaction.toggleKey) {- const compatibleItems = selectedItems.filter((item) =>- isTimelineSelectionCompatibleWithType(item, clickedType),- );- const existingKeySet = new Set(- compatibleItems.map(getTimelineSelectionKey),- );- if (existingKeySet.has(clickedKey)) {- const toggledSelection = compatibleItems.filter(- (item) => getTimelineSelectionKey(item) !== clickedKey,- );- return {- selectedItems: toggledSelection,- anchor: toggledSelection.length === 0 ? null : clickedItem,- };- }-- const selectableOrderMap = new Map(- allSelectableItems- .filter((item) =>- isTimelineSelectionCompatibleWithType(item, clickedType),- )- .map((item, index) => [getTimelineSelectionKey(item), index] as const),- );- const extendedSelection = [...compatibleItems, clickedItem].sort((a, b) => {- return (- (selectableOrderMap.get(getTimelineSelectionKey(a)) ?? 0) -- (selectableOrderMap.get(getTimelineSelectionKey(b)) ?? 0)- );- });- return {- selectedItems: extendedSelection,- anchor: clickedItem,- };- }-- return {- selectedItems: [clickedItem],- anchor: clickedItem,- };-};+export const getTimelineSelectionAfterInteraction =+ getCanvasSelectionAfterInteraction;export const getAvailableTimelineSelectionState = ({availableKeys,@@ -750,42 +559,7 @@ export const getTimelineSelectionFromNodePathInfo = (return null;};-export const getTimelineSelectionKey = (item: TimelineSelection): string => {- switch (item.type) {- case 'guide':- return `guide.${item.guideId}`;- case 'sequence':- return `${getTimelineSequenceSelectionKey(item.nodePathInfo)}.sequence`;- case 'sequence-prop':- return `${getTimelineSequenceSelectionKey(- item.nodePathInfo,- )}.sequence-prop.${item.key}`;- case 'sequence-all-effects':- return `${getTimelineSequenceSelectionKey(- item.nodePathInfo,- )}.sequence-all-effects`;- case 'sequence-effect':- return `${getTimelineSequenceSelectionKey(- item.nodePathInfo,- )}.sequence-effect.${item.i}`;- case 'sequence-effect-prop':- return `${getTimelineSequenceSelectionKey(- item.nodePathInfo,- )}.sequence-effect-prop.${item.i}.${item.key}`;- case 'keyframe':- return `${timelineNodePathInfoToKey(item.nodePathInfo)}.keyframe.${- item.frame- }`;- case 'easing':- return `${timelineNodePathInfoToKey(item.nodePathInfo)}.easing.${- item.segmentIndex- }`;- default:- throw new Error(- `Unexpected timeline selection type: ${item satisfies never}`,- );- }-};+export const getTimelineSelectionKey = getCanvasSelectionItemKey;const nodePathDescendsFrom = (descendant: SequenceNodePathInfo,@@ -983,9 +757,7 @@ export const getSelectableTimelineItems = ({});};-export const getTimelineSequenceSelectionKey = (- nodePathInfo: SequenceNodePathInfo,-): string => timelineNodePathInfoToKey({...nodePathInfo, auxiliaryKeys: []});+export const getTimelineSequenceSelectionKey = getCanvasSequenceSelectionKey;export const TimelineSelectAllKeybindings: React.FC<{readonly timeline: readonly TimelineTrackData[];@@ -1169,10 +941,8 @@ export const TimelineSelectionProvider: React.FC<{(previewServerState.type === 'connected' ||window.remotion_isReadOnlyStudio);const keyframeOperationsAvailable = canUseKeyframeOperations();- const [selectedItems, setSelectedItems] = useState<- readonly TimelineSelection[]- >([]);- const selectionAnchor = useRef<TimelineSelection | null>(null);+ const selectionController = useCanvasSelectionController();+ const selectionState = useCanvasSelection(selectionController);const selectionScope = useRef<string | null>(null);const marqueeSelectableItems = useRef(new Map<@@ -1191,11 +961,10 @@ export const TimelineSelectionProvider: React.FC<{useEffect(() => {if (!canSelect) {selectionScope.current = null;- selectionAnchor.current = null;setRevealRequest(null);- setSelectedItems([]);+ selectionController.clear();}- }, [canSelect]);+ }, [canSelect, selectionController]);const canSelectItem = useCallback((item: TimelineSelection) =>@@ -1206,22 +975,10 @@ export const TimelineSelectionProvider: React.FC<{[canSelect, keyframeOperationsAvailable],);- const getCurrentAvailableSelectionState = useCallback(- (currentSelectedItems: readonly TimelineSelection[]) => {- if (selectionScope.current !== timelineSelectionScope) {- return EMPTY_TIMELINE_SELECTION_STATE;- }-- return {- selectedItems: currentSelectedItems,- anchor: selectionAnchor.current,- };- },- [timelineSelectionScope],- );-const availableSelectionState =- getCurrentAvailableSelectionState(selectedItems);+ selectionScope.current === timelineSelectionScope+ ? selectionState+ : EMPTY_TIMELINE_SELECTION_STATE;const availableSelectedItems = availableSelectionState.selectedItems;const requestRevealSelectionItem = useCallback((item: TimelineSelection) => {@@ -1256,30 +1013,13 @@ export const TimelineSelectionProvider: React.FC<{);useEffect(() => {- setSelectedItems((currentSelectedItems) => {- const nextState =- selectionScope.current === timelineSelectionScope- ? {- selectedItems: currentSelectedItems,- anchor: selectionAnchor.current,- }- : EMPTY_TIMELINE_SELECTION_STATE;-- selectionScope.current = timelineSelectionScope;- selectionAnchor.current = nextState.anchor;-- if (- nextState.selectedItems.length === currentSelectedItems.length &&- nextState.selectedItems.every(- (item, index) => item === currentSelectedItems[index],- )- ) {- return currentSelectedItems;- }+ if (selectionScope.current === timelineSelectionScope) {+ return;+ }- return nextState.selectedItems;- });- }, [timelineSelectionScope]);+ selectionScope.current = timelineSelectionScope;+ selectionController.clear();+ }, [selectionController, timelineSelectionScope]);const selectedKeys = useMemo(() => new Set(availableSelectedItems.map(getTimelineSelectionKey)),@@ -1313,29 +1053,18 @@ export const TimelineSelectionProvider: React.FC<{requestRevealSelectionItem(item);}- setSelectedItems((currentSelectedItems) => {- const currentSelectionState =- getCurrentAvailableSelectionState(currentSelectedItems);-- const nextState = getTimelineSelectionAfterInteraction({- currentState: {- selectedItems: currentSelectionState.selectedItems,- anchor: currentSelectionState.anchor,- },- clickedItem: item,- interaction,- allSelectableItems,- });- selectionScope.current = timelineSelectionScope;- selectionAnchor.current = nextState.anchor;- return nextState.selectedItems;- });+ if (selectionScope.current !== timelineSelectionScope) {+ selectionController.clear();+ }++ selectionScope.current = timelineSelectionScope;+ selectionController.select(item, interaction, allSelectableItems);},[canSelectItem,expandParentsForSelectionItem,- getCurrentAvailableSelectionState,requestRevealSelectionItem,+ selectionController,timelineSelectionScope,],);@@ -1354,19 +1083,18 @@ export const TimelineSelectionProvider: React.FC<{}selectionScope.current = timelineSelectionScope;- selectionAnchor.current =- items.length === 0 ? null : items[items.length - 1];expandParentsForSelectionItems(items);if (options.reveal && items.length === 1) {requestRevealSelectionItem(items[0]);}- setSelectedItems(items);+ selectionController.setSelectedItems(items);},[canSelectItem,expandParentsForSelectionItems,requestRevealSelectionItem,+ selectionController,timelineSelectionScope,],);@@ -1429,9 +1157,8 @@ export const TimelineSelectionProvider: React.FC<{const clearSelection = useCallback(() => {selectionScope.current = null;- selectionAnchor.current = null;- setSelectedItems([]);- }, []);+ selectionController.clear();+ }, [selectionController]);const containsSelection = useCallback((nodePathInfo: SequenceNodePathInfo) => {