🎥 Make videos programmatically with React
Share outline polygons and interaction management with Studio
Jonny Burger5489b9e0855f
diff --git a/packages/canvas/README.md b/packages/canvas/README.mdindex 9d32df27fd..ee01ad0cba 100644--- a/packages/canvas/README.md+++ b/packages/canvas/README.md@@ -39,14 +39,38 @@ falls back to the mounted sequence ID; that fallback is not a persistent sourcereference across remounts. Outlines require a registered DOM ref, so a`Sequence` with `layout="none"` has no outline of its own.-For custom authoring UIs, `createCanvasHoverController()`,-`measureCanvasOutlineTargets()`, `useCanvasOutlineMeasurements()`, and-`orderCanvasOutlinesForRendering()` are independent primitives also consumed by-Studio. Measurements include transformed HTML/SVG bounds and cropping, in+For custom authoring UIs, Studio and Canvas consume the same outline APIs:++- `getCanvasSelectableOutlines()` discovers registered outline targets;+ `getCanvasVisibleOutlineTargets()` filters them by frame.+- `getCanvasOutlineActivity()` gates active measurement, and+ `getCanvasActiveOutlineTargets()` keeps selected or hovered source groups+ active when the pointer leaves the canvas.+- `getCanvasOutlineLayoutTargets()` distinguishes direct sequence selection+ from selected properties, highlights matching source instances, and resolves+ clicks to the first visible instance of a source node.+- `useCanvasOutlines()` measures targets, clears stale canvas hover, and returns+ `outlinesForRendering`, `outlinesByKey`, `targetsByKey`, and+ `hoveredNodePathKey`. Set `freezeOrder` during a captured drag to keep SVG+ nodes in place. Supply `crop` alongside the layout target fields.+- `CanvasOutlinePolygon` renders the SVG polygon with shared geometry and hover+ behavior. Render it inside your overlay's `<svg>`, pass visibility, selection,+ colors, and `onHoverChange`, and compose editing handlers through normal SVG+ props. It forwards its ref for pointer capture and hit testing.+- `handleCanvasOutlinePointerDown()` consumes a primary pointer event and+ returns a selection decision, preserving an existing multiselection on plain+ clicks. Dragging hosts honor `deferSelection` until release; selection-only+ hosts apply `shouldUpdateSelection` immediately. Studio adds its drag and+ source-editing behavior around this decision.++Lower-level `createCanvasHoverController()`, `measureCanvasOutlineTargets()`,+`useCanvasOutlineMeasurements()`, and `orderCanvasOutlinesForRendering()` remain+available independently. Measurements include transformed HTML/SVG bounds and cropping, inunscaled overlay pixels. The overlay must share the elements' document andmust not have a CSS transform or SVG viewBox scaling. The measurement hookobserves element sizes; invoke its `updateOutlinesRef` after position, transform,frame, or viewport changes. Keep frame subscriptions in the active overlay and-omit inactive targets to avoid unnecessary layout reads.+omit inactive targets to avoid unnecessary layout reads. `useCanvasOutlines()`+also accepts this ref and does not subscribe to playback itself.Source writes and transform editing handles remain the host's responsibility.diff --git a/packages/canvas/src/canvas-outline-overlay.tsx b/packages/canvas/src/canvas-outline-overlay.tsxindex f7f0ce83a5..1ebce9232c 100644--- a/packages/canvas/src/canvas-outline-overlay.tsx+++ b/packages/canvas/src/canvas-outline-overlay.tsx@@ -1,14 +1,21 @@import type {RefObject} from 'react';import React, {useEffect, useCallback, useMemo, useRef, useState} from 'react';-import {Internals} from 'remotion';+import {Internals, type TSequence} from 'remotion';import type {CanvasController} from './canvas-controller';-import type {- SequenceNodePathInfo,- TimelineTrackData,-} from './get-timeline-sequence-sort-key';-import {useCanvasHover} from './hover';-import type {CanvasOutlineTarget} from './outline-geometry';-import {orderCanvasOutlinesForRendering} from './outline-order';+import {CanvasOutlinePolygon} from './canvas-outline-polygon';+import {useCanvasHover, useCanvasSequenceHover} from './hover';+import type {CanvasOutline} from './outline-geometry';+import {handleCanvasOutlinePointerDown} from './outline-interaction';+import {+ getCanvasActiveOutlineTargets,+ getCanvasOutlineActivity,+ getCanvasOutlineLayoutTargets,+ getCanvasSelectableOutlines,+ getCanvasSelectedSequenceKeys,+ getCanvasSequenceKeysContainingSelection,+ getCanvasVisibleOutlineTargets,+ type CanvasSelectableOutline,+} from './outline-targets';import {getCanvasSequenceSelectionKey,useCanvasSelection,@@ -16,18 +23,10 @@ import {} from './selection';import type {CanvasSequenceNodePathResolver} from './sequence-node-path';import {timelineSequenceNodePathToKey} from './timeline-sequence-node-path-to-key';-import {useCanvasOutlineMeasurements} from './use-canvas-outline-measurements';+import {useCanvasOutlines} from './use-canvas-outlines';import {useCanvasRuntimeValueSnapshots} from './use-runtime-value-snapshots';import {useSyncExternalStore} from './use-sync-external-store';-type OutlineLayer = {- readonly track: TimelineTrackData;- readonly key: string;- readonly nodePathKey: string;- readonly nodePathInfo: SequenceNodePathInfo;- readonly selection: CanvasSelectionItem;-};-const overlayStyle: React.CSSProperties = {position: 'absolute',inset: 0,@@ -36,65 +35,133 @@ const overlayStyle: React.CSSProperties = {outline: 'none',};+const CanvasOutlineElement = React.memo(+ ({+ controller,+ containerRef,+ outline,+ target,+ selectableItems,+ }: {+ readonly controller: CanvasController;+ readonly containerRef: RefObject<SVGSVGElement | null>;+ readonly outline: CanvasOutline;+ readonly target: ReturnType<typeof getCanvasOutlineLayoutTargets>[number];+ readonly selectableItems: readonly CanvasSelectionItem[];+ }) => {+ const {hovered, onPointerEnter, onPointerLeave} = useCanvasSequenceHover(+ controller.hover,+ target.nodePathInfo,+ 'canvas',+ );+ const onHoverChange = useCallback(+ (key: string | null) => {+ if (key === null) {+ onPointerLeave();+ } else {+ onPointerEnter();+ }+ },+ [onPointerEnter, onPointerLeave],+ );+ const onPointerDown = useCallback(+ (event: React.PointerEvent<SVGPolygonElement>) => {+ const decision = handleCanvasOutlinePointerDown({+ event,+ polygon: event.currentTarget,+ hasTarget: true,+ selected: target.selected,+ containsSelection: target.containsSelection,+ translateWithCommandKey: false,+ isMac: false,+ });+ if (decision === null) {+ return;+ }++ containerRef.current?.focus({preventScroll: true});+ // A host with dragging may defer this selection until pointer release.+ if (decision.shouldUpdateSelection) {+ controller.selection.select(+ target.selection,+ decision.interaction,+ selectableItems,+ );+ }+ },+ [containerRef, controller.selection, selectableItems, target],+ );+ return (+ <CanvasOutlinePolygon+ outline={outline}+ directlySelected={target.selected}+ data-selected={target.selected}+ dragging={false}+ visible={target.showSelectedOutline || hovered}+ interactive+ stroke="#0b84f3"+ fill="transparent"+ onHoverChange={onHoverChange}+ onPointerDown={onPointerDown}+ />+ );+ },+);+// Only this leaf subscribes to the frame. An idle, unselected Canvas does not// measure its composition or render its layer list on every playback frame.const ActiveCanvasOutlines = React.memo(({controller,containerRef,- layers,+ selectableOutlines,+ sequences,+ selectableItems,measureAll,}: {readonly controller: CanvasController;readonly containerRef: RefObject<SVGSVGElement | null>;- readonly layers: readonly OutlineLayer[];+ readonly selectableOutlines: readonly CanvasSelectableOutline[];+ readonly sequences: readonly TSequence[];+ readonly selectableItems: readonly CanvasSelectionItem[];readonly measureAll: boolean;}) => {const frame = Internals.Timeline.useTimelinePosition();- const selection = useCanvasSelection(controller.selection);+ const {selectedItems} = useCanvasSelection(controller.selection);const hover = useCanvasHover(controller.hover);- const selectedSourceKeys = useMemo(- () =>- new Set(- selection.selectedItems.flatMap((item) =>- item.type === 'guide'- ? []- : [- timelineSequenceNodePathToKey(- item.nodePathInfo.sequenceSubscriptionKey,- ),- ],- ),- ),- [selection.selectedItems],+ const selectedSequenceKeys = useMemo(+ () => getCanvasSelectedSequenceKeys(selectedItems),+ [selectedItems],);- const selectedKeys = useMemo(- () =>- new Set(- selection.selectedItems.flatMap((item) =>- item.type === 'guide'- ? []- : [getCanvasSequenceSelectionKey(item.nodePathInfo)],- ),- ),- [selection.selectedItems],+ const sequenceKeysContainingSelection = useMemo(+ () => getCanvasSequenceKeysContainingSelection(selectedItems),+ [selectedItems],);+ const hoveredTimelineNodePathKey =+ hover?.source === 'timeline' ? hover.nodePathKey : null;const activeLayers = useMemo(() =>- layers.filter(- ({track, nodePathKey}) =>- track.sequence.refForOutline !== null &&- track.sequence.showInTimeline &&- (measureAll ||- selectedSourceKeys.has(nodePathKey) ||- hover?.nodePathKey === nodePathKey),- ),- [hover?.nodePathKey, layers, measureAll, selectedSourceKeys],+ getCanvasActiveOutlineTargets({+ targets: selectableOutlines,+ selectedSequenceKeys,+ sequenceKeysContainingSelection,+ hoveredNodePathKey: hoveredTimelineNodePathKey,+ measureAll,+ }),+ [+ hoveredTimelineNodePathKey,+ measureAll,+ selectableOutlines,+ selectedSequenceKeys,+ sequenceKeysContainingSelection,+ ],);+ // Subscribe before filtering by the playback frame to avoid resubscribing+ // every frame when sequences enter or leave the composition.const runtimeControls = useMemo(() =>- activeLayers.flatMap(({track}) =>- track.sequence.controls ? [track.sequence.controls] : [],+ activeLayers.flatMap(({sequence}) =>+ sequence.controls ? [sequence.controls] : [],),[activeLayers],);@@ -109,144 +176,64 @@ const ActiveCanvasOutlines = React.memo(),[runtimeControls, runtimeSnapshots],);- const visibleLayers = useMemo(- () =>- activeLayers.filter(- ({track: {sequence}}) =>- frame >= sequence.from && frame < sequence.from + sequence.duration,- ),- [activeLayers, frame],- );const targets = useMemo(() =>- visibleLayers.map((layer) => {- const {sequence} = layer.track;- const values = sequence.controls- ? (valuesByStore.get(sequence.controls.runtimeValues) ?? {})+ getCanvasOutlineLayoutTargets({+ selectableOutlines: getCanvasVisibleOutlineTargets({+ targets: activeLayers,+ timelinePosition: frame,+ }),+ selectedSequenceKeys,+ sequenceKeysContainingSelection,+ targetKey: null,+ }).map((target) => {+ 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]: 0;return {- ...layer,- sequence,- ref: sequence.refForOutline!,+ ...target,crop: Internals.resolveSequenceCrop({cropLeft: cropValue('cropLeft'),cropRight: cropValue('cropRight'),cropTop: cropValue('cropTop'),cropBottom: cropValue('cropBottom'),}),- selected: selectedKeys.has(layer.key),- containsSelection: selectedKeys.has(layer.key),- includeOutsideContainer:- selectedSourceKeys.has(layer.nodePathKey) ||- hover?.nodePathKey === layer.nodePathKey,};}),[- hover?.nodePathKey,+ activeLayers,+ frame,+ selectedSequenceKeys,+ sequenceKeysContainingSelection,valuesByStore,- selectedKeys,- selectedSourceKeys,- visibleLayers,],);- const outlines = useCanvasOutlineMeasurements({+ const {outlinesForRendering, targetsByKey} = useCanvasOutlines({containerRef,- targets: targets satisfies readonly CanvasOutlineTarget[],+ targets,+ sequences,+ hoverController: controller.hover,+ freezeOrder: false,updateOutlinesRef: null,});- const targetsByKey = useMemo(- () => new Map(targets.map((target) => [target.key, target])),- [targets],- );- const sequences = useMemo(- () => layers.map(({track}) => track.sequence),- [layers],- );- const orderedOutlines = useMemo(- () =>- orderCanvasOutlinesForRendering({- outlines,- sequences,- targetsByKey,- }),- [outlines, sequences, targetsByKey],- );- const selectableItems = useMemo(- () => layers.map((layer) => layer.selection),- [layers],- );- useEffect(() => {- const current = controller.hover.getSnapshot();- if (- current?.source === 'canvas' &&- !outlines.some((outline) => outline.key === current.key)- ) {- controller.hover.clear('canvas');- }- }, [controller.hover, outlines]);-return (<>- {orderedOutlines.map((outline) => {+ {outlinesForRendering.map((outline) => {const target = targetsByKey.get(outline.key);- if (!target) {- return null;- }-- const visible =- selectedSourceKeys.has(target.nodePathKey) ||- hover?.nodePathKey === target.nodePathKey;- return (- <polygon+ return target ? (+ <CanvasOutlineElementkey={outline.key}- data-remotion-canvas-outline-key={outline.key}- data-selected={target.selected}- points={outline.points- .map((point) => `${point.x},${point.y}`)- .join(' ')}- fill="transparent"- stroke="#0b84f3"- strokeWidth={2}- strokeOpacity={visible ? 1 : 0}- vectorEffect="non-scaling-stroke"- pointerEvents="all"- onPointerEnter={() =>- controller.hover.setHoveredSequence({- key: target.key,- nodePathKey: target.nodePathKey,- source: 'canvas',- })- }- onPointerLeave={() =>- controller.hover.setHoveredSequence((current) =>- current?.source === 'canvas' && current.key === target.key- ? null- : current,- )- }- onPointerDown={(event) => {- if (event.button !== 0) {- return;- }-- event.preventDefault();- event.stopPropagation();- containerRef.current?.focus({preventScroll: true});- controller.selection.select(- target.selection,- {- shiftKey: event.shiftKey,- toggleKey: event.metaKey || event.ctrlKey,- },- selectableItems,- );- }}+ controller={controller}+ containerRef={containerRef}+ outline={outline}+ target={target}+ selectableItems={selectableItems}/>- );+ ) : null;})}</>);@@ -275,46 +262,56 @@ export const CanvasOutlineOverlay = React.memo();const selection = useCanvasSelection(controller.selection);const hover = useCanvasHover(controller.hover);- const layers = useMemo(+ const sequences = useMemo(+ () => tracks.map(({sequence}) => sequence),+ [tracks],+ );+ const resolvedTracks = useMemo(() =>- tracks.flatMap((track, index): OutlineLayer[] => {- const nodePathInfo = resolveSequenceNodePathInfo(track, index);- if (- nodePathInfo === null ||- nodePathInfo.auxiliaryKeys.length !== 0- ) {- return [];- }-- return [- {- track,- key: getCanvasSequenceSelectionKey(nodePathInfo),- nodePathKey: timelineSequenceNodePathToKey(- nodePathInfo.sequenceSubscriptionKey,- ),- nodePathInfo,- selection: {type: 'sequence', nodePathInfo},- },- ];- }),+ tracks.map((track, index) => ({+ ...track,+ nodePathInfo: resolveSequenceNodePathInfo(track, index),+ })),[resolveSequenceNodePathInfo, tracks],);+ const selectableOutlines = useMemo(+ () =>+ getCanvasSelectableOutlines({+ tracks: resolvedTracks,+ timelinePosition: null,+ resolveSequenceNodePathInfo: null,+ }),+ [resolvedTracks],+ );+ const selectableItems = useMemo(+ () =>+ resolvedTracks.flatMap(({nodePathInfo}): CanvasSelectionItem[] =>+ nodePathInfo === null || nodePathInfo.auxiliaryKeys.length !== 0+ ? []+ : [{type: 'sequence', nodePathInfo}],+ ),+ [resolvedTracks],+ );useEffect(() => {controller.hover.setHoveredSequence((current) => {if (current === null) {return current;}- return layers.some((layer) =>- current.source === 'timeline'- ? layer.nodePathKey === current.nodePathKey- : layer.key === current.key,+ return selectableItems.some(+ (item) =>+ item.type !== 'guide' &&+ (current.source === 'timeline'+ ? timelineSequenceNodePathToKey(+ item.nodePathInfo.sequenceSubscriptionKey,+ ) === current.nodePathKey+ : getCanvasSequenceSelectionKey(item.nodePathInfo) ===+ current.key),)? current: null;});- }, [controller.hover, layers]);+ }, [controller.hover, selectableItems]);useEffect(() => {const ownerWindow = containerRef.current?.ownerDocument.defaultView;const clearHover = () => {@@ -329,10 +326,15 @@ export const CanvasOutlineOverlay = React.memo(controller.hover.clear('canvas');};}, [controller.hover]);- const active =- hovered ||- selection.selectedItems.some((item) => item.type !== 'guide') ||- hover?.source === 'timeline';+ const {measurementActive, measureAllOutlines} = getCanvasOutlineActivity({+ canvasHovered: hovered,+ dragging: false,+ contextMenuOpen: false,+ hasSelection: selection.selectedItems.some(+ (item) => item.type !== 'guide',+ ),+ hoveredSequence: hover,+ });return (<svgref={attachContainer}@@ -366,12 +368,14 @@ export const CanvasOutlineOverlay = React.memo(}}}>- {active && container !== null ? (+ {measurementActive && container !== null ? (<ActiveCanvasOutlinescontroller={controller}containerRef={containerRef}- layers={layers}- measureAll={hovered}+ selectableOutlines={selectableOutlines}+ sequences={sequences}+ selectableItems={selectableItems}+ measureAll={measureAllOutlines}/>) : null}</svg>diff --git a/packages/canvas/src/canvas-outline-polygon.tsx b/packages/canvas/src/canvas-outline-polygon.tsxnew file mode 100644index 0000000000..94aeca2f94--- /dev/null+++ b/packages/canvas/src/canvas-outline-polygon.tsx@@ -0,0 +1,81 @@+import React, {forwardRef, memo, useCallback, useMemo} from 'react';+import type {CanvasOutline} from './outline-geometry';++export type CanvasOutlinePolygonProps = Omit<+ React.SVGProps<SVGPolygonElement>,+ | 'ref'+ | 'children'+ | 'points'+ | 'fill'+ | 'stroke'+ | 'strokeOpacity'+ | 'strokeWidth'+ | 'vectorEffect'+ | 'pointerEvents'+ | 'onPointerEnter'+ | 'onPointerLeave'+> & {+ readonly outline: CanvasOutline;+ readonly directlySelected: boolean;+ readonly dragging: boolean;+ readonly visible: boolean;+ readonly interactive: boolean;+ readonly fill: string;+ readonly stroke: string;+ readonly onHoverChange: (key: string | null) => void;+};++/** Shared outline geometry and hover behavior, with editing handlers supplied by the host. */+export const CanvasOutlinePolygon = memo(+ forwardRef<SVGPolygonElement, CanvasOutlinePolygonProps>(+ (+ {+ outline,+ directlySelected,+ dragging,+ visible,+ interactive,+ fill,+ stroke,+ onHoverChange,+ ...props+ },+ ref,+ ) => {+ const points = useMemo(+ () => outline.points.map((point) => `${point.x},${point.y}`).join(' '),+ [outline.points],+ );+ const onPointerEnter = useCallback(() => {+ if (!dragging) {+ onHoverChange(outline.key);+ }+ }, [dragging, onHoverChange, outline.key]);+ const onPointerLeave = useCallback(() => {+ if (!dragging) {+ onHoverChange(null);+ }+ }, [dragging, onHoverChange]);++ return (+ <polygon+ {...props}+ ref={ref}+ data-remotion-canvas-outline-key={outline.key}+ data-remotion-directly-selected-outline={+ directlySelected ? 'true' : undefined+ }+ points={points}+ fill={fill}+ stroke={stroke}+ strokeOpacity={visible ? 1 : 0}+ strokeWidth={2}+ vectorEffect="non-scaling-stroke"+ pointerEvents={interactive ? 'all' : 'none'}+ onPointerEnter={onPointerEnter}+ onPointerLeave={onPointerLeave}+ />+ );+ },+ ),+);diff --git a/packages/canvas/src/index.ts b/packages/canvas/src/index.tsindex 2a508cf0da..75dd96e6b8 100644--- a/packages/canvas/src/index.ts+++ b/packages/canvas/src/index.ts@@ -30,6 +30,28 @@ export type {CanvasOutlineSequenceParent,} from './outline-order';export {useCanvasOutlineMeasurements} from './use-canvas-outline-measurements';+export {useCanvasOutlines} from './use-canvas-outlines';+export type {CanvasOutlineRenderTarget} from './use-canvas-outlines';+export {CanvasOutlinePolygon} from './canvas-outline-polygon';+export type {CanvasOutlinePolygonProps} from './canvas-outline-polygon';+export {+ getCanvasOutlineSelectionInteraction,+ handleCanvasOutlinePointerDown,+} from './outline-interaction';+export type {CanvasOutlinePointerDownDecision} from './outline-interaction';+export {+ getCanvasActiveOutlineTargets,+ getCanvasOutlineActivity,+ getCanvasOutlineLayoutTargets,+ getCanvasSelectableOutlines,+ getCanvasSelectedSequenceKeys,+ getCanvasSequenceKeysContainingSelection,+ getCanvasVisibleOutlineTargets,+} from './outline-targets';+export type {+ CanvasSelectableOutline,+ CanvasOutlineLayoutTarget,+} from './outline-targets';export {getCanvasSequenceNodePathInfo} from './sequence-node-path';export type {CanvasSequenceNodePathResolver} from './sequence-node-path';export {getConnectedCompositions} from './get-connected-compositions';diff --git a/packages/canvas/src/outline-interaction.ts b/packages/canvas/src/outline-interaction.tsnew file mode 100644index 0000000000..afe3c7033e--- /dev/null+++ b/packages/canvas/src/outline-interaction.ts@@ -0,0 +1,122 @@+import type {CanvasSelectionInteraction} from './selection';++export type CanvasOutlinePointerDownDecision = {+ readonly interaction: CanvasSelectionInteraction;+ readonly temporaryTranslate: boolean;+ readonly shouldUpdateSelection: boolean;+ readonly deferSelection: boolean;+ readonly dragExistingSelection: boolean;+ readonly pointerInsideSelectedOutline: boolean;+};++export const getCanvasOutlineSelectionInteraction = ({+ shiftKey,+ metaKey,+ ctrlKey,+}: {+ readonly shiftKey: boolean;+ readonly metaKey: boolean;+ readonly ctrlKey: boolean;+}): CanvasSelectionInteraction => ({+ shiftKey,+ toggleKey: metaKey || ctrlKey,+});++/**+ * Consumes a primary pointer down and decides how it affects the selection.+ * Hosts with dragging defer the selection until pointer release when requested;+ * hosts without dragging can apply every requested selection immediately.+ */+export const handleCanvasOutlinePointerDown = ({+ event,+ polygon,+ hasTarget,+ selected,+ containsSelection,+ translateWithCommandKey,+ isMac,+}: {+ readonly event: Pick<+ PointerEvent,+ | 'button'+ | 'clientX'+ | 'clientY'+ | 'shiftKey'+ | 'metaKey'+ | 'ctrlKey'+ | 'preventDefault'+ | 'stopPropagation'+ >;+ readonly polygon: SVGPolygonElement | null;+ readonly hasTarget: boolean;+ readonly selected: boolean;+ readonly containsSelection: boolean;+ readonly translateWithCommandKey: boolean;+ readonly isMac: boolean;+}): CanvasOutlinePointerDownDecision | null => {+ if (event.button !== 0 || !hasTarget) {+ return null;+ }++ event.preventDefault();+ event.stopPropagation();++ const temporaryTranslate =+ translateWithCommandKey &&+ (selected || containsSelection) &&+ (isMac ? event.metaKey : event.ctrlKey);+ const interaction = temporaryTranslate+ ? {shiftKey: false, toggleKey: false}+ : getCanvasOutlineSelectionInteraction(event);+ const shouldUpdateSelection =+ !selected || interaction.shiftKey || interaction.toggleKey;+ const ownerSvg = polygon?.ownerSVGElement;+ let pointerInsideSelectedOutline = false;+ if (ownerSvg) {+ const screenPoint = ownerSvg.createSVGPoint();+ screenPoint.x = event.clientX;+ screenPoint.y = event.clientY;+ pointerInsideSelectedOutline = Array.from(+ ownerSvg.querySelectorAll<SVGPolygonElement>(+ 'polygon[data-remotion-directly-selected-outline="true"]',+ ),+ ).some((selectedPolygon) => {+ const screenTransform = selectedPolygon.getScreenCTM();+ if (screenTransform === null) {+ return false;+ }++ // A collapsed transform has no hittable area and cannot be inverted.+ if (+ screenTransform.a * screenTransform.d -+ screenTransform.b * screenTransform.c ===+ 0+ ) {+ return false;+ }++ const polygonPoint = screenPoint.matrixTransform(+ screenTransform.inverse(),+ );+ return (+ selectedPolygon.isPointInFill(polygonPoint) ||+ selectedPolygon.isPointInStroke(polygonPoint)+ );+ });+ }++ const deferSelection =+ !selected &&+ !interaction.shiftKey &&+ !interaction.toggleKey &&+ (containsSelection || pointerInsideSelectedOutline);++ return {+ interaction,+ temporaryTranslate,+ shouldUpdateSelection,+ deferSelection,+ dragExistingSelection: selected || deferSelection,+ pointerInsideSelectedOutline,+ };+};diff --git a/packages/canvas/src/outline-targets.ts b/packages/canvas/src/outline-targets.tsnew file mode 100644index 0000000000..551601aff5--- /dev/null+++ b/packages/canvas/src/outline-targets.ts@@ -0,0 +1,246 @@+import type {RefObject} from 'react';+import type {TSequence} from 'remotion';+import type {+ SequenceNodePathInfo,+ TimelineTrackData,+} from './get-timeline-sequence-sort-key';+import type {CanvasHover} from './hover';+import {+ getCanvasSequenceSelectionKey,+ type CanvasSelectionItem,+} from './selection';+import type {CanvasSequenceNodePathResolver} from './sequence-node-path';+import {timelineSequenceNodePathToKey} from './timeline-sequence-node-path-to-key';++export type CanvasSelectableOutline = {+ readonly depth: number;+ readonly keyframeDisplayOffset: number;+ readonly key: string;+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly sequence: TSequence;+};++export type CanvasOutlineLayoutTarget = CanvasSelectableOutline & {+ readonly nodePathKey: string;+ readonly ref: RefObject<Element | null>;+ readonly selected: boolean;+ readonly containsSelection: boolean;+ readonly showSelectedOutline: boolean;+ readonly selection: Extract<CanvasSelectionItem, {type: 'sequence'}>;+};++export const getCanvasVisibleOutlineTargets = <+ T extends {readonly sequence: Pick<TSequence, 'from' | 'duration'>},+>({+ targets,+ timelinePosition,+}: {+ readonly targets: readonly T[];+ readonly timelinePosition: number;+}): T[] => {+ return targets.filter(+ ({sequence}) =>+ timelinePosition >= sequence.from &&+ timelinePosition < sequence.from + sequence.duration,+ );+};++/** A null timeline position includes all registered, selectable instances. */+export const getCanvasSelectableOutlines = ({+ tracks,+ timelinePosition,+ resolveSequenceNodePathInfo,+}: {+ readonly tracks: readonly TimelineTrackData[];+ readonly timelinePosition: number | null;+ readonly resolveSequenceNodePathInfo: CanvasSequenceNodePathResolver | null;+}): CanvasSelectableOutline[] => {+ const selectableOutlines = tracks+ .flatMap((track, index): CanvasSelectableOutline[] => {+ const {sequence} = track;+ if (!sequence.showInTimeline || sequence.refForOutline === null) {+ return [];+ }++ const nodePathInfo =+ resolveSequenceNodePathInfo === null+ ? track.nodePathInfo+ : resolveSequenceNodePathInfo(track, index);+ if (nodePathInfo === null || nodePathInfo.auxiliaryKeys.length !== 0) {+ return [];+ }++ return [+ {+ depth: track.depth,+ keyframeDisplayOffset: track.keyframeDisplayOffset,+ key: getCanvasSequenceSelectionKey(nodePathInfo),+ nodePathInfo,+ sequence,+ },+ ];+ })+ .sort((a, b) => a.depth - b.depth);++ return timelinePosition === null+ ? selectableOutlines+ : getCanvasVisibleOutlineTargets({+ targets: selectableOutlines,+ timelinePosition,+ });+};++export const getCanvasSelectedSequenceKeys = (+ selectedItems: readonly CanvasSelectionItem[],+): Set<string> => {+ return new Set(+ selectedItems+ .filter((item) => item.type === 'sequence')+ .map((item) => getCanvasSequenceSelectionKey(item.nodePathInfo)),+ );+};++export const getCanvasSequenceKeysContainingSelection = (+ selectedItems: readonly CanvasSelectionItem[],+): Set<string> => {+ return new Set(+ selectedItems+ .filter((item) => item.type !== 'guide')+ .map((item) => getCanvasSequenceSelectionKey(item.nodePathInfo)),+ );+};++/** Keeps every instance of an active source while the canvas is inactive. */+export const getCanvasActiveOutlineTargets = <+ T extends Pick<CanvasSelectableOutline, 'key' | 'nodePathInfo'>,+>({+ targets,+ selectedSequenceKeys,+ sequenceKeysContainingSelection,+ hoveredNodePathKey,+ measureAll,+}: {+ readonly targets: readonly T[];+ readonly selectedSequenceKeys: ReadonlySet<string>;+ readonly sequenceKeysContainingSelection: ReadonlySet<string>;+ readonly hoveredNodePathKey: string | null;+ readonly measureAll: boolean;+}): readonly T[] => {+ if (measureAll) {+ return targets;+ }++ const activeNodePathKeys = new Set<string>();+ for (const {key, nodePathInfo} of targets) {+ const nodePathKey = timelineSequenceNodePathToKey(+ nodePathInfo.sequenceSubscriptionKey,+ );+ if (+ selectedSequenceKeys.has(key) ||+ sequenceKeysContainingSelection.has(key) ||+ nodePathKey === hoveredNodePathKey+ ) {+ activeNodePathKeys.add(nodePathKey);+ }+ }++ return targets.filter(({nodePathInfo}) =>+ activeNodePathKeys.has(+ timelineSequenceNodePathToKey(nodePathInfo.sequenceSubscriptionKey),+ ),+ );+};++/** Builds selection state shared by canvas instances of the same source. */+export const getCanvasOutlineLayoutTargets = ({+ selectableOutlines,+ selectedSequenceKeys,+ sequenceKeysContainingSelection,+ targetKey,+}: {+ readonly selectableOutlines: readonly CanvasSelectableOutline[];+ readonly selectedSequenceKeys: ReadonlySet<string>;+ readonly sequenceKeysContainingSelection: ReadonlySet<string>;+ readonly targetKey: string | null;+}): CanvasOutlineLayoutTarget[] => {+ const firstNodePathInfoBySourceNode = new Map<string, SequenceNodePathInfo>();+ const selectedSourceNodeKeys = new Set<string>();+ for (const {key, nodePathInfo} of selectableOutlines) {+ const sourceNodeKey = timelineSequenceNodePathToKey(+ nodePathInfo.sequenceSubscriptionKey,+ );+ if (selectedSequenceKeys.has(key)) {+ selectedSourceNodeKeys.add(sourceNodeKey);+ }++ const currentFirst = firstNodePathInfoBySourceNode.get(sourceNodeKey);+ if (currentFirst === undefined || nodePathInfo.index < currentFirst.index) {+ firstNodePathInfoBySourceNode.set(sourceNodeKey, nodePathInfo);+ }+ }++ return selectableOutlines.flatMap((selectableOutline) => {+ const {key, nodePathInfo, sequence} = selectableOutline;+ if (targetKey !== null && targetKey !== key) {+ return [];+ }++ if (sequence.refForOutline === null) {+ throw new Error('Expected sequence to have a ref for outline');+ }++ const nodePathKey = timelineSequenceNodePathToKey(+ nodePathInfo.sequenceSubscriptionKey,+ );+ const selectionNodePathInfo =+ firstNodePathInfoBySourceNode.get(nodePathKey);+ if (selectionNodePathInfo === undefined) {+ throw new Error('Expected a first sequence for the source node');+ }++ const containsSelection = sequenceKeysContainingSelection.has(key);+ return [+ {+ ...selectableOutline,+ nodePathKey,+ ref: sequence.refForOutline,+ selected: selectedSequenceKeys.has(key),+ containsSelection,+ showSelectedOutline:+ containsSelection || selectedSourceNodeKeys.has(nodePathKey),+ selection: {+ type: 'sequence' as const,+ nodePathInfo: selectionNodePathInfo,+ },+ },+ ];+ });+};++/** Activation keeps frame subscriptions out of an idle outline overlay. */+export const getCanvasOutlineActivity = ({+ canvasHovered,+ dragging,+ contextMenuOpen,+ hasSelection,+ hoveredSequence,+}: {+ readonly canvasHovered: boolean;+ readonly dragging: boolean;+ readonly contextMenuOpen: boolean;+ readonly hasSelection: boolean;+ readonly hoveredSequence: CanvasHover | null;+}) => {+ const measureAllOutlines = canvasHovered || dragging || contextMenuOpen;+ return {+ measurementActive:+ measureAllOutlines ||+ hasSelection ||+ hoveredSequence?.source === 'timeline',+ measureAllOutlines,+ hoveredTimelineNodePathKey:+ hoveredSequence?.source === 'timeline'+ ? hoveredSequence.nodePathKey+ : null,+ };+};diff --git a/packages/canvas/src/use-canvas-outlines.ts b/packages/canvas/src/use-canvas-outlines.tsnew file mode 100644index 0000000000..5913045293--- /dev/null+++ b/packages/canvas/src/use-canvas-outlines.ts@@ -0,0 +1,123 @@+import type {MutableRefObject, RefObject} from 'react';+import {useEffect, useMemo, useRef} from 'react';+import type {SequenceNodePathInfo} from './get-timeline-sequence-sort-key';+import type {CanvasHoverController} from './hover';+import {useCanvasHover} from './hover';+import type {CanvasOutlineTarget} from './outline-geometry';+import type {+ CanvasOutlineOrderTarget,+ CanvasOutlineSequenceParent,+} from './outline-order';+import {orderCanvasOutlinesForRendering} from './outline-order';+import {timelineSequenceNodePathToKey} from './timeline-sequence-node-path-to-key';+import {useCanvasOutlineMeasurements} from './use-canvas-outline-measurements';++export type CanvasOutlineRenderTarget = Omit<+ CanvasOutlineTarget,+ 'includeOutsideContainer'+> &+ CanvasOutlineOrderTarget & {+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly showSelectedOutline: boolean;+ };++/** Measure and order a host's outline targets without subscribing to playback. */+export const useCanvasOutlines = <Target extends CanvasOutlineRenderTarget>({+ containerRef,+ targets,+ sequences,+ hoverController,+ freezeOrder,+ updateOutlinesRef,+}: {+ readonly containerRef: RefObject<SVGSVGElement | null>;+ readonly targets: readonly Target[];+ readonly sequences: readonly CanvasOutlineSequenceParent[];+ readonly hoverController: CanvasHoverController;+ readonly freezeOrder: boolean;+ readonly updateOutlinesRef: MutableRefObject<() => void> | null;+}) => {+ const hover = useCanvasHover(hoverController);+ const hoveredNodePathKey = hover?.nodePathKey ?? null;+ const hoveredTimelineNodePathKey =+ hover?.source === 'timeline' ? hoveredNodePathKey : null;+ const measurementTargets = useMemo(+ () =>+ targets.map((target) => ({+ crop: target.crop,+ includeOutsideContainer:+ target.showSelectedOutline ||+ timelineSequenceNodePathToKey(+ target.nodePathInfo.sequenceSubscriptionKey,+ ) === hoveredTimelineNodePathKey,+ key: target.key,+ ref: target.ref,+ })),+ [hoveredTimelineNodePathKey, targets],+ );+ const outlines = useCanvasOutlineMeasurements({+ containerRef,+ targets: measurementTargets,+ updateOutlinesRef,+ });+ const targetsByKey = useMemo(+ () => new Map(targets.map((target) => [target.key, target])),+ [targets],+ );++ // Moving a captured polygon in the DOM can cancel the host's pointer session.+ const renderingOrderRef = useRef<readonly string[]>([]);+ const outlinesForRendering = useMemo(() => {+ if (!freezeOrder || renderingOrderRef.current.length === 0) {+ const ordered = orderCanvasOutlinesForRendering({+ outlines,+ sequences,+ targetsByKey,+ });+ renderingOrderRef.current = ordered.map((outline) => outline.key);+ return ordered;+ }++ const currentOutlinesByKey = new Map(+ outlines.map((outline) => [outline.key, outline]),+ );+ const frozenKeys = new Set(renderingOrderRef.current);+ renderingOrderRef.current = [+ ...renderingOrderRef.current,+ ...outlines+ .filter((outline) => !frozenKeys.has(outline.key))+ .map((outline) => outline.key),+ ];+ return renderingOrderRef.current.flatMap((key) => {+ const outline = currentOutlinesByKey.get(key);+ return outline === undefined ? [] : [outline];+ });+ }, [freezeOrder, outlines, sequences, targetsByKey]);+ const outlinesByKey = useMemo(+ () => new Map(outlines.map((outline) => [outline.key, outline])),+ [outlines],+ );++ useEffect(() => {+ if (+ hover?.source !== 'canvas' ||+ (targetsByKey.has(hover.key) && outlinesByKey.has(hover.key))+ ) {+ return;+ }++ hoverController.setHoveredSequence((current) =>+ current?.source === 'canvas' && current.key === hover.key+ ? null+ : current,+ );+ }, [hover, hoverController, outlinesByKey, targetsByKey]);++ return {+ outlines,+ outlinesForRendering,+ outlinesByKey,+ targetsByKey,+ hoveredNodePathKey,+ };+};diff --git a/packages/studio/src/components/SelectedOutlineOverlay.tsx b/packages/studio/src/components/SelectedOutlineOverlay.tsxindex fc081e495b..d20c1f62ea 100644--- a/packages/studio/src/components/SelectedOutlineOverlay.tsx+++ b/packages/studio/src/components/SelectedOutlineOverlay.tsx@@ -1,3 +1,11 @@+import {+ calculateTimeline,+ getCanvasSelectableOutlines,+ getCanvasVisibleOutlineTargets,+ getCanvasActiveOutlineTargets,+ getCanvasOutlineActivity,+ getCanvasOutlineLayoutTargets,+} from '@remotion/canvas';import {PlayerInternals} from '@remotion/player';import React, {useCallback,@@ -15,12 +23,10 @@ import {} from 'remotion';import {NoReactInternals} from 'remotion/no-react';import {StudioServerConnectionCtx} from '../helpers/client-id';-import type {SequenceNodePathInfo} from '../helpers/get-timeline-sequence-sort-key';import {isStudioInteractivityEnabled,isStudioSelectionEnabled,} from '../helpers/interactivity-enabled';-import {timelineSequenceNodePathToKey} from '../helpers/timeline-node-path-key';import {useIsFullscreen} from '../helpers/use-is-fullscreen';import {useRuntimeValueSnapshots} from '../helpers/use-runtime-values';import {EditorShowOutlinesContext} from '../state/editor-outlines';@@ -38,7 +44,7 @@ import {getSelectedSequenceKeys,getSelectedTransformOriginInfo,getSequenceKeysContainingSelection,- getSequencesWithSelectableOutlines,+ type getSequencesWithSelectableOutlines,} from './selected-outline-measurement';import {orderOutlinesForRendering} from './selected-outline-order';import {@@ -185,7 +191,9 @@ const getCropDragFields = ({return fields as SelectedOutlineCropDragTarget['fields'];};-type SelectableOutlines = ReturnType<typeof getSequencesWithSelectableOutlines>;+type SelectableOutlines = Readonly<+ ReturnType<typeof getSequencesWithSelectableOutlines>+>;type CalculateOutlineTargetsOptions = {readonly mode: 'controls' | 'layout';@@ -262,44 +270,15 @@ const calculateOutlineTargets = ({const previewInteractive =connectedClientId !== null && studioInteractivityEnabled;- const firstNodePathInfoBySourceNode = new Map<string, SequenceNodePathInfo>();- const selectedSourceNodeKeys = new Set<string>();- for (const {key, nodePathInfo} of selectableOutlines) {- const sourceNodeKey = timelineSequenceNodePathToKey(- nodePathInfo.sequenceSubscriptionKey,- );- if (selectedSequenceKeys.has(key)) {- selectedSourceNodeKeys.add(sourceNodeKey);- }-- const currentFirst = firstNodePathInfoBySourceNode.get(sourceNodeKey);- if (currentFirst === undefined || nodePathInfo.index < currentFirst.index) {- firstNodePathInfoBySourceNode.set(sourceNodeKey, nodePathInfo);- }- }-- return selectableOutlines.flatMap((selectableOutline) => {+ return getCanvasOutlineLayoutTargets({+ selectableOutlines,+ selectedSequenceKeys,+ sequenceKeysContainingSelection,+ targetKey,+ }).flatMap((canvasLayoutTarget) => {const {key, keyframeDisplayOffset, nodePathInfo, sequence} =- selectableOutline;- if (targetKey !== null && targetKey !== key) {- return [];- }-- if (sequence.refForOutline === null) {- throw new Error('Expected sequence to have a ref for outline');- }-- const selected = selectedSequenceKeys.has(key);- const containsSelection = sequenceKeysContainingSelection.has(key);+ canvasLayoutTarget;const nodePath = nodePathInfo.sequenceSubscriptionKey;- const sourceNodeKey = timelineSequenceNodePathToKey(nodePath);- const showSelectedOutline =- containsSelection || selectedSourceNodeKeys.has(sourceNodeKey);- const selectionNodePathInfo =- firstNodePathInfoBySourceNode.get(sourceNodeKey);- if (selectionNodePathInfo === undefined) {- throw new Error('Expected a first sequence for the source node');- }const {controls} = sequence;const nodePropStatuses = Internals.getPropStatusesCtx(@@ -392,24 +371,14 @@ const calculateOutlineTargets = ({): '50% 50%';const layoutTarget: SelectedOutlineLayoutTarget = {- key,- containsSelection,+ ...canvasLayoutTarget,crop,keyframeDisplayOffset: nodeKeyframeDisplayOffset,- nodePathInfo,- ref: sequence.refForOutline,- selected,selectedForCrop,selectedForRotation,selectedForTransformOrigin,selectedForUvHandles,- showSelectedOutline,transformOriginValue: transformOriginValueForRotation,- selection: {- type: 'sequence',- nodePathInfo: selectionNodePathInfo,- },- sequence,};if (mode === 'layout') {return [layoutTarget];@@ -715,40 +684,23 @@ const ActiveSelectedOutlineOverlayUnmemoized: React.FC<const selectableOutlines = useMemo(() => {return getSelectableOutlines(timelinePosition);}, [getSelectableOutlines, timelinePosition]);- const selectableOutlinesForLayout = useMemo(() => {- if (measureAllOutlines) {- return selectableOutlines;- }-- // A timeline item can represent multiple connected canvas instances.- // Keep every instance of an active source node without calculating targets- // for unrelated timeline items while the canvas itself is inactive.- const activeNodePathKeys = new Set<string>();- for (const {key, nodePathInfo} of selectableOutlines) {- const nodePathKey = timelineSequenceNodePathToKey(- nodePathInfo.sequenceSubscriptionKey,- );- if (- selectedSequenceKeys.has(key) ||- sequenceKeysContainingSelection.has(key) ||- nodePathKey === hoveredTimelineNodePathKey- ) {- activeNodePathKeys.add(nodePathKey);- }- }-- return selectableOutlines.filter(({nodePathInfo}) =>- activeNodePathKeys.has(- timelineSequenceNodePathToKey(nodePathInfo.sequenceSubscriptionKey),- ),- );- }, [- hoveredTimelineNodePathKey,- measureAllOutlines,- selectableOutlines,- selectedSequenceKeys,- sequenceKeysContainingSelection,- ]);+ const selectableOutlinesForLayout = useMemo(+ () =>+ getCanvasActiveOutlineTargets({+ targets: selectableOutlines,+ selectedSequenceKeys,+ sequenceKeysContainingSelection,+ hoveredNodePathKey: hoveredTimelineNodePathKey,+ measureAll: measureAllOutlines,+ }),+ [+ hoveredTimelineNodePathKey,+ measureAllOutlines,+ selectableOutlines,+ selectedSequenceKeys,+ sequenceKeysContainingSelection,+ ],+ );const outlineRuntimeControls = useMemo(() => {return selectableOutlinesForLayout.flatMap(({key, sequence}) => {if (@@ -876,8 +828,13 @@ const SelectedOutlineOverlayUnmemoized: React.FC<() => getSelectedCropInfo(selectedItems),[selectedItems],);- const getSelectableOutlines = useCallback(- (timelinePosition: number) => {+ const getSelectableOutlines = useMemo(() => {+ // Resolve source identities once per sequence snapshot, on first demand.+ // Playback only filters the cached candidates by their visible range.+ let selectableOutlines: ReturnType<+ typeof getSequencesWithSelectableOutlines+ > | null = null;+ return (timelinePosition: number) => {if (isFullscreen ||!isStudioSelectionEnabled() ||@@ -887,22 +844,28 @@ const SelectedOutlineOverlayUnmemoized: React.FC<return [];}- return getSequencesWithSelectableOutlines({- sequences,- overrideIdsToNodePaths: overrideIdToNodePathMappings,- compositions,+ selectableOutlines ??= getCanvasSelectableOutlines({+ tracks: calculateTimeline({+ sequences: [...sequences],+ overrideIdsToNodePaths: overrideIdToNodePathMappings,+ compositions,+ }),+ timelinePosition: null,+ resolveSequenceNodePathInfo: null,+ });+ return getCanvasVisibleOutlineTargets({+ targets: selectableOutlines,timelinePosition,});- },- [- compositions,- editorShowOutlines,- isFullscreen,- overrideIdToNodePathMappings,- previewSelectionAvailable,- sequences,- ],- );+ };+ }, [+ compositions,+ editorShowOutlines,+ isFullscreen,+ overrideIdToNodePathMappings,+ previewSelectionAvailable,+ sequences,+ ]);const calculateOutlineTargetsForCurrentState =useCallback<CalculateOutlineTargets>(@@ -1017,16 +980,14 @@ const SelectedOutlineOverlayUnmemoized: React.FC<},[selectItem],);- const measurementActive =- canvasHovered ||- draggingOutline ||- canvasContextMenuOpen ||- sequenceKeysContainingSelection.size > 0 ||- hoveredSequence?.source === 'timeline';- const measureAllOutlines =- canvasHovered || draggingOutline || canvasContextMenuOpen;- const hoveredTimelineNodePathKey =- hoveredSequence?.source === 'timeline' ? hoveredSequence.nodePathKey : null;+ const {measurementActive, measureAllOutlines, hoveredTimelineNodePathKey} =+ getCanvasOutlineActivity({+ canvasHovered,+ dragging: draggingOutline,+ contextMenuOpen: canvasContextMenuOpen,+ hasSelection: sequenceKeysContainingSelection.size > 0,+ hoveredSequence,+ });useLayoutEffect(() => {if (measurementActive) {return;diff --git a/packages/studio/src/components/SelectedOutlinePolygon.tsx b/packages/studio/src/components/SelectedOutlinePolygon.tsxindex 88fa9b9054..2b8f088de9 100644--- a/packages/studio/src/components/SelectedOutlinePolygon.tsx+++ b/packages/studio/src/components/SelectedOutlinePolygon.tsx@@ -1,3 +1,7 @@+import {+ CanvasOutlinePolygon,+ handleCanvasOutlinePointerDown,+} from '@remotion/canvas';import React, {useContext, useMemo, useRef, useState} from 'react';import {Internals} from 'remotion';import {StudioServerConnectionCtx} from '../helpers/client-id';@@ -38,10 +42,6 @@ import {type SelectedOutlineStaticDragChange,} from './selected-outline-drag';import type {SelectedOutline} from './selected-outline-geometry';-import {- getOutlineSelectionInteraction,- pointToString,-} from './selected-outline-measurement';import {findSelectedOutlineSnap,getSelectedOutlineSnapTargets,@@ -133,10 +133,6 @@ const SelectedOutlinePolygonUnmemoized: React.FC<{const {editorSnapping} = useContext(EditorSnappingContext);const {editorShowGuides, guidesList} = useContext(EditorShowGuidesContext);const polygonRef = useRef<SVGPolygonElement>(null);- const points = useMemo(- () => outline.points.map(pointToString).join(' '),- [outline.points],- );const [effectDropHovered, setEffectDropHovered] = useState(false);const visible = showSelectedOutline || hovered;const getEffectDropTarget = React.useCallback(() => {@@ -163,55 +159,27 @@ const SelectedOutlinePolygonUnmemoized: React.FC<{const onPointerDown = React.useCallback((event: React.PointerEvent<SVGPolygonElement>) => {const target = getTarget();- if (event.button !== 0 || target === undefined) {+ const decision = handleCanvasOutlinePointerDown({+ event,+ polygon: polygonRef.current,+ hasTarget: target !== undefined,+ selected: target?.selected ?? false,+ containsSelection,+ translateWithCommandKey,+ isMac,+ });+ if (decision === null || target === undefined) {return;}- const {drag, selected} = target;-- event.preventDefault();- event.stopPropagation();-- const temporaryTranslate =- translateWithCommandKey &&- (selected || containsSelection) &&- (isMac ? event.metaKey : event.ctrlKey);- const interaction = temporaryTranslate- ? {shiftKey: false, toggleKey: false}- : getOutlineSelectionInteraction(event);- const shouldUpdateSelection =- !selected || interaction.shiftKey || interaction.toggleKey;- const ownerSvg = polygonRef.current?.ownerSVGElement;- let pointerInsideSelectedOutline = false;- if (ownerSvg) {- const screenPoint = ownerSvg.createSVGPoint();- screenPoint.x = event.clientX;- screenPoint.y = event.clientY;- pointerInsideSelectedOutline = Array.from(- ownerSvg.querySelectorAll<SVGPolygonElement>(- 'polygon[data-remotion-directly-selected-outline="true"]',- ),- ).some((selectedPolygon) => {- const screenTransform = selectedPolygon.getScreenCTM();- if (screenTransform === null) {- return false;- }-- const polygonPoint = screenPoint.matrixTransform(- screenTransform.inverse(),- );- return (- selectedPolygon.isPointInFill(polygonPoint) ||- selectedPolygon.isPointInStroke(polygonPoint)- );- });- }-- const deferSelection =- !selected &&- !interaction.shiftKey &&- !interaction.toggleKey &&- (containsSelection || pointerInsideSelectedOutline);+ const {drag} = target;+ const {+ interaction,+ temporaryTranslate,+ shouldUpdateSelection,+ deferSelection,+ dragExistingSelection,+ } = decision;if (!deferSelection && shouldUpdateSelection) {onSelect(target.selection, interaction);}@@ -234,7 +202,6 @@ const SelectedOutlinePolygonUnmemoized: React.FC<{const startPointerX = event.clientX;const startPointerY = event.clientY;- const dragExistingSelection = selected || deferSelection;const dragTargets = dragExistingSelection? getAllDragTargets(): drag === null@@ -600,32 +567,20 @@ const SelectedOutlinePolygonUnmemoized: React.FC<{);return (- <polygon+ <CanvasOutlinePolygonref={polygonRef}{...{[PREVENT_CLEAR_SELECTION_ON_POINTER_DOWN_ATTR]: 'true',[SELECTED_OUTLINE_KEY_ATTR]: outline.key,}}- data-remotion-directly-selected-outline={- directlySelected ? 'true' : undefined- }- points={points}+ outline={outline}+ directlySelected={directlySelected}+ dragging={dragging}fill={effectDropHovered ? TIMELINE_DROP_BLUE_ALPHA_12 : TRANSPARENT}stroke={BLUE}- strokeOpacity={visible || effectDropHovered ? 1 : 0}- strokeWidth={2}- vectorEffect="non-scaling-stroke"- pointerEvents={hasTarget ? 'all' : undefined}- onPointerEnter={() => {- if (!dragging) {- onHoverChange(outline.key);- }- }}- onPointerLeave={() => {- if (!dragging) {- onHoverChange(null);- }- }}+ visible={visible || effectDropHovered}+ interactive={hasTarget}+ onHoverChange={onHoverChange}onPointerDown={onPointerDown}onPointerDownCapture={dragAwareDoubleClick.beginPointerGesture}onClick={onClick}diff --git a/packages/studio/src/components/SelectedOutlineRenderer.tsx b/packages/studio/src/components/SelectedOutlineRenderer.tsxindex 4cf7e96889..28860a9d0d 100644--- a/packages/studio/src/components/SelectedOutlineRenderer.tsx+++ b/packages/studio/src/components/SelectedOutlineRenderer.tsx@@ -1,19 +1,16 @@-import {useCanvasOutlineMeasurements} from '@remotion/canvas';+import {useCanvasOutlines} from '@remotion/canvas';import React, {useCallback,- useEffect,+ useContext,useLayoutEffect,useMemo,useRef,} from 'react';import {timelineSequenceNodePathToKey} from '../helpers/timeline-node-path-key';-import {- useSetTimelineSequenceHover,- useTimelineSequenceHoverState,-} from '../state/timeline-sequence-hover';+import {TimelineSequenceHoverContext} from '../state/timeline-sequence-hover';import {ContextMenuForTarget} from './ContextMenu';import type {SelectedOutline} from './selected-outline-geometry';-import {orderOutlinesForRendering} from './selected-outline-order';+import type {orderOutlinesForRendering} from './selected-outline-order';import type {SelectedOutlineContextMenuOpenHandler,SelectedOutlineLayoutTarget,@@ -111,79 +108,20 @@ const SelectedOutlineRendererUnmemoized: React.FC<{},[getContextMenuOpenByKey],);- const hoveredSequence = useTimelineSequenceHoverState();- const setHoveredSequence = useSetTimelineSequenceHover();- const hoveredNodePathKey = hoveredSequence?.nodePathKey ?? null;- const hoveredTimelineNodePathKey =- hoveredSequence?.source === 'timeline' ? hoveredNodePathKey : null;-- const measurementTargets = useMemo(- () =>- outlineTargets.map((target) => ({- crop: target.crop,- includeOutsideContainer:- target.showSelectedOutline ||- timelineSequenceNodePathToKey(- target.nodePathInfo.sequenceSubscriptionKey,- ) === hoveredTimelineNodePathKey,- key: target.key,- ref: target.ref,- })),- [hoveredTimelineNodePathKey, outlineTargets],- );- const outlines = useCanvasOutlineMeasurements({+ const hoverController = useContext(TimelineSequenceHoverContext);+ const {+ outlinesForRendering,+ outlinesByKey,+ targetsByKey,+ hoveredNodePathKey,+ } = useCanvasOutlines({containerRef: overlayRef,- targets: measurementTargets,+ targets: outlineTargets,+ sequences,+ hoverController,+ freezeOrder: dragging,updateOutlinesRef,});-- const targetsByKey = useMemo(() => {- return new Map(outlineTargets.map((target) => [target.key, target]));- }, [outlineTargets]);- useEffect(() => {- if (- hoveredSequence?.source === 'canvas' &&- !outlineTargets.some((target) => target.key === hoveredSequence.key)- ) {- setHoveredSequence((currentHover) =>- currentHover?.source === 'canvas' ? null : currentHover,- );- }- }, [hoveredSequence, outlineTargets, setHoveredSequence]);- // Reordering a captured SVG target can cancel the active pointer session.- const outlineRenderingOrderRef = useRef<readonly string[]>([]);- const outlinesForRendering = useMemo(() => {- if (!dragging || outlineRenderingOrderRef.current.length === 0) {- const orderedOutlines = orderOutlinesForRendering({- outlines,- sequences,- targetsByKey,- });- outlineRenderingOrderRef.current = orderedOutlines.map(- (outline) => outline.key,- );- return orderedOutlines;- }-- const currentOutlinesByKey = new Map(- outlines.map((outline) => [outline.key, outline]),- );- const frozenKeys = new Set(outlineRenderingOrderRef.current);- const newOutlines = outlines.filter(- (outline) => !frozenKeys.has(outline.key),- );- outlineRenderingOrderRef.current = [- ...outlineRenderingOrderRef.current,- ...newOutlines.map((outline) => outline.key),- ];- return outlineRenderingOrderRef.current.flatMap((key) => {- const outline = currentOutlinesByKey.get(key);- return outline === undefined ? [] : [outline];- });- }, [dragging, outlines, sequences, targetsByKey]);- const outlinesByKey = useMemo(() => {- return new Map(outlines.map((outline) => [outline.key, outline]));- }, [outlines]);const {outlinesForEditingHandles,outlinesForTransformOrigin,diff --git a/packages/studio/src/components/selected-outline-measurement.ts b/packages/studio/src/components/selected-outline-measurement.tsindex 703b3e5a43..9d8ef0f947 100644--- a/packages/studio/src/components/selected-outline-measurement.ts+++ b/packages/studio/src/components/selected-outline-measurement.ts@@ -1,3 +1,4 @@+import {getCanvasSelectableOutlines} from '@remotion/canvas';import type {_InternalTypes, OverrideIdToNodePaths, TSequence} from 'remotion';import {calculateTimeline} from '../helpers/calculate-timeline';import {BLACK, WHITE} from '../helpers/colors';@@ -15,7 +16,6 @@ import {parseKeyframeFieldFromNodePath} from './Timeline/parse-keyframe-field-frimport {getTimelineSequenceSelectionKey,type TimelineSelection,- type TimelineSelectionInteraction,} from './Timeline/TimelineSelection';import {parsedTransformOriginToUv,@@ -23,6 +23,9 @@ import {} from './Timeline/transform-origin-utils';export {+ getCanvasOutlineSelectionInteraction as getOutlineSelectionInteraction,+ getCanvasSelectedSequenceKeys as getSelectedSequenceKeys,+ getCanvasSequenceKeysContainingSelection as getSequenceKeysContainingSelection,cropCanvasOutlinePoints as cropOutlinePoints,getTransformedSvgViewportPoints,measureCanvasOutlineTargets as measureOutlineTargets,@@ -175,39 +178,6 @@ export const getSelectedOutlineRotationPivot = ({return getUvHandlePosition(points, uv);};-export const getSelectedSequenceKeys = (- selectedItems: readonly TimelineSelection[],-): Set<string> => {- return new Set(- selectedItems- .filter((item) => item.type === 'sequence')- .map((item) => getTimelineSequenceSelectionKey(item.nodePathInfo)),- );-};--export const getSequenceKeysContainingSelection = (- selectedItems: readonly TimelineSelection[],-): Set<string> => {- return new Set(- selectedItems- .filter((item) => item.type !== 'guide')- .map((item) => getTimelineSequenceSelectionKey(item.nodePathInfo)),- );-};--export const getOutlineSelectionInteraction = ({- shiftKey,- metaKey,- ctrlKey,-}: {- readonly shiftKey: boolean;- readonly metaKey: boolean;- readonly ctrlKey: boolean;-}): TimelineSelectionInteraction => ({- shiftKey,- toggleKey: metaKey || ctrlKey,-});-type SelectedEffectFields = {allFields: boolean;fieldKeys: Set<string>;@@ -431,36 +401,13 @@ export const getSequencesWithSelectableOutlines = ({readonly compositions?: readonly _InternalTypes['AnyComposition'][];readonly timelinePosition: number;}): SequenceWithSelectedOutline[] => {- return calculateTimeline({- sequences: [...sequences],- overrideIdsToNodePaths,- compositions,- })- .filter((track) => {- if (track.nodePathInfo === null) {- return false;- }-- return (- track.sequence.showInTimeline &&- timelinePosition >= track.sequence.from &&- timelinePosition < track.sequence.from + track.sequence.duration &&- track.nodePathInfo.auxiliaryKeys.length === 0- );- })- .filter((track) => track.sequence.refForOutline !== null)- .sort((a, b) => a.depth - b.depth)- .map((track) => {- if (track.nodePathInfo === null) {- throw new Error('Expected selected outline to have a node path');- }-- return {- depth: track.depth,- keyframeDisplayOffset: track.keyframeDisplayOffset,- key: getTimelineSequenceSelectionKey(track.nodePathInfo),- nodePathInfo: track.nodePathInfo,- sequence: track.sequence,- };- });+ return getCanvasSelectableOutlines({+ tracks: calculateTimeline({+ sequences: [...sequences],+ overrideIdsToNodePaths,+ compositions,+ }),+ timelinePosition,+ resolveSequenceNodePathInfo: null,+ });};diff --git a/packages/studio/src/components/selected-outline-types.ts b/packages/studio/src/components/selected-outline-types.tsindex ccf1815b56..0611c1ba75 100644--- a/packages/studio/src/components/selected-outline-types.ts+++ b/packages/studio/src/components/selected-outline-types.ts@@ -1,3 +1,8 @@+import type {+ CanvasOutlineCrop,+ CanvasOutlineLayoutTarget,+ CanvasSelectableOutline,+} from '@remotion/canvas';import type {CanUpdateSequencePropStatus,CanUpdateSequencePropStatusKeyframed,@@ -5,11 +10,8 @@ import type {InteractivitySchema,InteractivitySchemaField,SequencePropsSubscriptionKey,- TSequence,} from 'remotion';-import type {SequenceNodePathInfo} from '../helpers/get-timeline-sequence-sort-key';import type {ComboboxValue} from './NewComposition/ComboBox';-import type {TimelineSelection} from './Timeline/TimelineSelection';export type SelectedOutlineContextMenuOpenResult =| false@@ -19,27 +21,13 @@ export type SelectedOutlineContextMenuOpenHandler = () =>| SelectedOutlineContextMenuOpenResult| Promise<SelectedOutlineContextMenuOpenResult>;-export type SelectedOutlineLayoutTarget = {- readonly key: string;- readonly containsSelection: boolean;- readonly keyframeDisplayOffset: number;- readonly nodePathInfo: SequenceNodePathInfo;- readonly ref: React.RefObject<Element | null>;- readonly selected: boolean;+export type SelectedOutlineLayoutTarget = CanvasOutlineLayoutTarget & {readonly selectedForCrop: boolean;readonly selectedForRotation: boolean;readonly selectedForTransformOrigin: boolean;readonly selectedForUvHandles: boolean;- readonly showSelectedOutline: boolean;readonly transformOriginValue: string;- readonly selection: TimelineSelection;- readonly sequence: TSequence;- readonly crop: {- readonly left: number;- readonly right: number;- readonly top: number;- readonly bottom: number;- };+ readonly crop: CanvasOutlineCrop;};export type SelectedOutlineTarget = SelectedOutlineLayoutTarget & {@@ -224,13 +212,7 @@ export type SelectedOutlineRotationDragState = {readonly target: SelectedOutlineRotationDragTarget;};-export type SequenceWithSelectedOutline = {- readonly depth: number;- readonly keyframeDisplayOffset: number;- readonly key: string;- readonly nodePathInfo: SequenceNodePathInfo;- readonly sequence: TSequence;-};+export type SequenceWithSelectedOutline = CanvasSelectableOutline;export const translateFieldKey = 'style.translate';export const scaleFieldKey = 'style.scale';diff --git a/packages/studio/src/components/use-selected-outline-control-target.ts b/packages/studio/src/components/use-selected-outline-control-target.tsindex 656ab8a4fa..0dbe6941a0 100644--- a/packages/studio/src/components/use-selected-outline-control-target.ts+++ b/packages/studio/src/components/use-selected-outline-control-target.ts@@ -1,9 +1,6 @@-import React, {useLayoutEffect, useMemo, useRef} from 'react';-import {timelineSequenceNodePathToKey} from '../helpers/timeline-node-path-key';-import {- useIsTimelineSequenceHovered,- useSetTimelineSequenceHover,-} from '../state/timeline-sequence-hover';+import {useCanvasSequenceHover} from '@remotion/canvas';+import React, {useContext, useLayoutEffect, useRef} from 'react';+import {TimelineSequenceHoverContext} from '../state/timeline-sequence-hover';import type {SelectedOutlineLayoutTarget,SelectedOutlineTarget,@@ -18,7 +15,7 @@ export const useSelectedOutlineControlTarget = ({) => SelectedOutlineTarget | undefined;readonly layoutTarget: SelectedOutlineLayoutTarget | undefined;}) => {- const setHoveredSequence = useSetTimelineSequenceHover();+ const hoverController = useContext(TimelineSequenceHoverContext);const targetRef = useRef(layoutTarget);useLayoutEffect(() => {targetRef.current = layoutTarget;@@ -32,42 +29,24 @@ export const useSelectedOutlineControlTarget = ({return getLatestTargetByKey(currentTarget.key);}, [getLatestTargetByKey]);const getLayoutTarget = React.useCallback(() => targetRef.current, []);- const hoveredNodePathKey = useMemo(- () =>- layoutTarget === undefined- ? null- : timelineSequenceNodePathToKey(- layoutTarget.nodePathInfo.sequenceSubscriptionKey,- ),- [layoutTarget],+ const {hovered, onPointerEnter, onPointerLeave} = useCanvasSequenceHover(+ hoverController,+ layoutTarget?.nodePathInfo ?? null,+ 'canvas',);- const hovered = useIsTimelineSequenceHovered(hoveredNodePathKey);const controlTarget =layoutTarget !== undefined && (layoutTarget.containsSelection || hovered)? getLatestTargetByKey(layoutTarget.key): undefined;const onHoverChange = React.useCallback((key: string | null) => {- setHoveredSequence((currentHover) => {- if (key !== null) {- const hoverTarget = targetRef.current;- if (hoverTarget === undefined || hoverTarget.key !== key) {- return currentHover;- }-- return {- key,- nodePathKey: timelineSequenceNodePathToKey(- hoverTarget.nodePathInfo.sequenceSubscriptionKey,- ),- source: 'canvas',- };- }-- return currentHover?.source === 'canvas' ? null : currentHover;- });+ if (key === null) {+ onPointerLeave();+ } else if (targetRef.current?.key === key) {+ onPointerEnter();+ }},- [setHoveredSequence],+ [onPointerEnter, onPointerLeave],);return {controlTarget, getLayoutTarget, getTarget, hovered, onHoverChange};