🎥 Make videos programmatically with React
`@remotion/studio`: Fix dragged element canvas selection (#8962)
Igor Samokhovets13ba52c010f4
diff --git a/packages/studio/src/components/SelectedOutlineOverlay.tsx b/packages/studio/src/components/SelectedOutlineOverlay.tsxindex b8a3a28898..b6de83607c 100644--- a/packages/studio/src/components/SelectedOutlineOverlay.tsx+++ b/packages/studio/src/components/SelectedOutlineOverlay.tsx@@ -166,18 +166,373 @@ const SelectedOutlineSnapIndicators: React.FC<{);};+const outlinePointEqualityTolerance = 0.5;+const outlineAreaEqualityTolerance = 0.5;+const outlineBoundsOverlapTolerance = 0.5;++const outlinePointsAreEquivalent = (+ a: SelectedOutline['points'][number],+ b: SelectedOutline['points'][number],+) => {+ return (+ Math.abs(a.x - b.x) <= outlinePointEqualityTolerance &&+ Math.abs(a.y - b.y) <= outlinePointEqualityTolerance+ );+};++const outlinesHaveEquivalentHitArea = (+ a: SelectedOutline,+ b: SelectedOutline,+): boolean => {+ if (a.points.length !== b.points.length) {+ return false;+ }++ for (let startIndex = 0; startIndex < b.points.length; startIndex++) {+ for (const direction of [1, -1]) {+ const pointsMatch = a.points.every((point, index) => {+ const bIndex =+ (startIndex + direction * index + b.points.length) % b.points.length;+ return outlinePointsAreEquivalent(point, b.points[bIndex]);+ });++ if (pointsMatch) {+ return true;+ }+ }+ }++ return false;+};++const getOutlineHitArea = (outline: SelectedOutline): number => {+ let area = 0;++ for (let i = 0; i < outline.points.length; i++) {+ const current = outline.points[i];+ const next = outline.points[(i + 1) % outline.points.length];+ area += current.x * next.y - next.x * current.y;+ }++ return Math.abs(area) / 2;+};++const getOutlineBounds = (outline: SelectedOutline) => {+ const xs = outline.points.map((point) => point.x);+ const ys = outline.points.map((point) => point.y);++ return {+ maxX: Math.max(...xs),+ maxY: Math.max(...ys),+ minX: Math.min(...xs),+ minY: Math.min(...ys),+ };+};++const outlineBoundsOverlap = (+ a: SelectedOutline,+ b: SelectedOutline,+): boolean => {+ const aBounds = getOutlineBounds(a);+ const bBounds = getOutlineBounds(b);++ return (+ aBounds.minX <= bBounds.maxX + outlineBoundsOverlapTolerance &&+ aBounds.maxX + outlineBoundsOverlapTolerance >= bBounds.minX &&+ aBounds.minY <= bBounds.maxY + outlineBoundsOverlapTolerance &&+ aBounds.maxY + outlineBoundsOverlapTolerance >= bBounds.minY+ );+};++type OutlineSequenceParent = {+ readonly id: string;+ readonly parent: string | null;+};++const getSequenceId = (target: SelectedOutlineTarget | undefined) => {+ return target?.sequence?.id ?? null;+};++const getParentBySequenceId = ({+ sequences,+ targetsByKey,+}: {+ readonly sequences: readonly OutlineSequenceParent[];+ readonly targetsByKey: ReadonlyMap<string, SelectedOutlineTarget>;+}) => {+ const parentBySequenceId = new Map<string, string | null>();++ for (const sequence of sequences) {+ parentBySequenceId.set(sequence.id, sequence.parent);+ }++ for (const target of targetsByKey.values()) {+ const sequenceId = getSequenceId(target);+ if (sequenceId !== null && !parentBySequenceId.has(sequenceId)) {+ parentBySequenceId.set(sequenceId, target.sequence.parent);+ }+ }++ return parentBySequenceId;+};++const isAncestorTarget = ({+ ancestor,+ descendant,+ parentBySequenceId,+}: {+ readonly ancestor: SelectedOutlineTarget;+ readonly descendant: SelectedOutlineTarget;+ readonly parentBySequenceId: ReadonlyMap<string, string | null>;+}): boolean => {+ const ancestorId = getSequenceId(ancestor);+ if (ancestorId === null) {+ return false;+ }++ let parentId = descendant.sequence?.parent ?? null;+ while (parentId !== null) {+ if (parentId === ancestorId) {+ return true;+ }++ parentId = parentBySequenceId.get(parentId) ?? null;+ }++ return false;+};++const orderOutlineGroup = ({+ outlines,+ parentBySequenceId,+ targetsByKey,+}: {+ readonly outlines: readonly SelectedOutline[];+ readonly parentBySequenceId: ReadonlyMap<string, string | null>;+ readonly targetsByKey: ReadonlyMap<string, SelectedOutlineTarget>;+}): readonly SelectedOutline[] => {+ const incomingEdges = new Map<string, Set<string>>();+ const outgoingEdges = new Map<string, Set<string>>();+ const outlinesByKey = new Map(+ outlines.map((outline) => [outline.key, outline]),+ );++ for (const outline of outlines) {+ incomingEdges.set(outline.key, new Set());+ outgoingEdges.set(outline.key, new Set());+ }++ const hasPath = ({+ fromKey,+ seen,+ toKey,+ }: {+ readonly fromKey: string;+ readonly seen: Set<string>;+ readonly toKey: string;+ }): boolean => {+ if (fromKey === toKey) {+ return true;+ }++ if (seen.has(fromKey)) {+ return false;+ }++ seen.add(fromKey);+ for (const nextKey of outgoingEdges.get(fromKey) ?? []) {+ if (hasPath({fromKey: nextKey, seen, toKey})) {+ return true;+ }+ }++ return false;+ };++ const addEdge = (+ before: SelectedOutline,+ after: SelectedOutline,+ options?: {readonly skipIfCycle: boolean},+ ) => {+ if (before.key === after.key) {+ return;+ }++ const incoming = incomingEdges.get(after.key);+ const outgoing = outgoingEdges.get(before.key);+ if (incoming === undefined || outgoing === undefined) {+ throw new Error('Expected outline to be registered before adding edge');+ }++ if (outgoing.has(after.key)) {+ return;+ }++ if (hasPath({fromKey: after.key, seen: new Set(), toKey: before.key})) {+ if (options?.skipIfCycle) {+ return;+ }++ throw new Error('Could not determine a stable outline rendering order');+ }++ incoming.add(before.key);+ outgoing.add(after.key);+ };++ const addAncestorConstraint = ({+ ancestor,+ descendant,+ descendantContainsSelection,+ equivalentHitArea,+ }: {+ readonly ancestor: SelectedOutline;+ readonly descendant: SelectedOutline;+ readonly descendantContainsSelection: boolean;+ readonly equivalentHitArea: boolean;+ }) => {+ // Usually, children should be above parents so nested elements are directly+ // selectable. If an unselected child has the same hit area as its parent, put+ // it below the parent so the wrapper can be selected. Once the child or+ // one of its properties is selected, keep it above the parent so it remains+ // directly draggable.+ if (equivalentHitArea && !descendantContainsSelection) {+ addEdge(descendant, ancestor);+ } else {+ addEdge(ancestor, descendant);+ }+ };++ const outlineBySequenceId = new Map<string, SelectedOutline>();+ for (const outline of outlines) {+ const sequenceId = getSequenceId(targetsByKey.get(outline.key));+ if (sequenceId !== null) {+ outlineBySequenceId.set(sequenceId, outline);+ }+ }++ // Only constrain each outline against its nearest rendered ancestor. The+ // resulting graph follows the sequence tree, so pairwise subpixel equivalence+ // cannot introduce contradictory edges across three nested outlines.+ for (const descendant of outlines) {+ const descendantTarget = targetsByKey.get(descendant.key);+ let parentId = descendantTarget?.sequence?.parent ?? null;++ while (parentId !== null) {+ const ancestor = outlineBySequenceId.get(parentId);+ if (ancestor !== undefined) {+ addAncestorConstraint({+ ancestor,+ descendant,+ descendantContainsSelection:+ (descendantTarget?.selected ?? false) ||+ (descendantTarget?.containsSelection ?? false),+ equivalentHitArea: outlinesHaveEquivalentHitArea(+ ancestor,+ descendant,+ ),+ });+ break;+ }++ parentId = parentBySequenceId.get(parentId) ?? null;+ }+ }++ // For unrelated overlapping outlines, put broader hit targets below+ // smaller ones so a large selected sequence cannot swallow clicks on+ // a more specific element in the same canvas area.+ for (let i = 0; i < outlines.length; i++) {+ for (let j = i + 1; j < outlines.length; j++) {+ const a = outlines[i];+ const b = outlines[j];+ const aTarget = targetsByKey.get(a.key);+ const bTarget = targetsByKey.get(b.key);++ if (aTarget === undefined || bTarget === undefined) {+ continue;+ }++ const aAncestorOfB = isAncestorTarget({+ ancestor: aTarget,+ descendant: bTarget,+ parentBySequenceId,+ });+ const bAncestorOfA = isAncestorTarget({+ ancestor: bTarget,+ descendant: aTarget,+ parentBySequenceId,+ });++ if (aAncestorOfB || bAncestorOfA || !outlineBoundsOverlap(a, b)) {+ continue;+ }++ const aArea = getOutlineHitArea(a);+ const bArea = getOutlineHitArea(b);++ if (Math.abs(aArea - bArea) <= outlineAreaEqualityTolerance) {+ continue;+ }++ if (aArea > bArea) {+ addEdge(a, b, {skipIfCycle: true});+ } else {+ addEdge(b, a, {skipIfCycle: true});+ }+ }+ }++ const emitted = new Set<string>();+ const visiting = new Set<string>();+ const ordered: SelectedOutline[] = [];++ const visit = (outline: SelectedOutline) => {+ if (emitted.has(outline.key)) {+ return;+ }++ if (visiting.has(outline.key)) {+ throw new Error('Could not determine a stable outline rendering order');+ }++ visiting.add(outline.key);+ for (const dependencyKey of incomingEdges.get(outline.key) ?? []) {+ const dependency = outlinesByKey.get(dependencyKey);+ if (dependency === undefined) {+ throw new Error('Expected outline dependency to exist');+ }++ visit(dependency);+ }++ visiting.delete(outline.key);+ emitted.add(outline.key);+ ordered.push(outline);+ };++ for (const outline of outlines) {+ visit(outline);+ }++ return ordered;+};+export const orderOutlinesForRendering = ({outlines,+ sequences,targetsByKey,}: {readonly outlines: readonly SelectedOutline[];+ readonly sequences: readonly OutlineSequenceParent[];readonly targetsByKey: ReadonlyMap<string, SelectedOutlineTarget>;}): readonly SelectedOutline[] => {- return [...outlines].sort((a, b) => {- const aSelected = targetsByKey.get(a.key)?.selected ?? false;- const bSelected = targetsByKey.get(b.key)?.selected ?? false;+ const parentBySequenceId = getParentBySequenceId({sequences, targetsByKey});- return Number(aSelected) - Number(bSelected);+ return orderOutlineGroup({+ outlines,+ parentBySequenceId,+ targetsByKey,});};@@ -550,8 +905,8 @@ export const SelectedOutlineOverlay: React.FC<{return new Map(outlineTargets.map((target) => [target.key, target]));}, [outlineTargets]);const outlinesForRendering = useMemo(() => {- return orderOutlinesForRendering({outlines, targetsByKey});- }, [outlines, targetsByKey]);+ return orderOutlinesForRendering({outlines, sequences, targetsByKey});+ }, [outlines, sequences, targetsByKey]);const outlinesByKey = useMemo(() => {return new Map(outlines.map((outline) => [outline.key, outline]));}, [outlines]);diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.tsindex c8964dcbdb..51c20e3a65 100644--- a/packages/studio/src/test/timeline-selection.test.ts+++ b/packages/studio/src/test/timeline-selection.test.ts@@ -1765,7 +1765,7 @@ test('Canvas outline hit targets render nested sequences above parents', () => {]);});-test('Canvas outline rendering puts selected outlines last', () => {+test('Canvas outline rendering preserves unconstrained outline order', () => {const makeOutline = (key: string): SelectedOutline => ({key,dimensions: null,@@ -1785,6 +1785,7 @@ test('Canvas outline rendering puts selected outlines last', () => {makeOutline('child'),makeOutline('sibling'),],+ sequences: [],targetsByKey: new Map([['parent', makeTarget(true)],['child', makeTarget(false)],@@ -1793,9 +1794,448 @@ test('Canvas outline rendering puts selected outlines last', () => {});expect(orderedOutlines.map((outline) => outline.key)).toEqual([+ 'parent','child','sibling',+ ]);+});++const makeTestOutline = ({+ key,+ left,+ top,+ width,+ height,+}: {+ readonly key: string;+ readonly left: number;+ readonly top: number;+ readonly width: number;+ readonly height: number;+}): SelectedOutline => ({+ key,+ dimensions: {width, height},+ points: [+ {x: left, y: top},+ {x: left + width, y: top},+ {x: left + width, y: top + height},+ {x: left, y: top + height},+ ],+});++const makeOutlineTarget = ({+ id,+ parent,+ selected = false,+}: {+ readonly id: string;+ readonly parent: string | null;+ readonly selected?: boolean;+}): SelectedOutlineTarget =>+ ({+ selected,+ sequence: {id, parent},+ }) as SelectedOutlineTarget;++const makeOutlineSequence = ({+ id,+ parent,+}: {+ readonly id: string;+ readonly parent: string | null;+}) => ({id, parent});++test('Canvas outline rendering keeps smaller nested hit targets above parents', () => {+ const orderedOutlines = orderOutlinesForRendering({+ outlines: [+ makeTestOutline({+ key: 'parent',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ makeTestOutline({+ key: 'child',+ left: 25,+ top: 25,+ width: 50,+ height: 50,+ }),+ ],+ sequences: [+ makeOutlineSequence({id: 'parent', parent: null}),+ makeOutlineSequence({id: 'child', parent: 'parent'}),+ ],+ targetsByKey: new Map([+ ['parent', makeOutlineTarget({id: 'parent', parent: null})],+ ['child', makeOutlineTarget({id: 'child', parent: 'parent'})],+ ]),+ });++ expect(orderedOutlines.map((outline) => outline.key)).toEqual(['parent',+ 'child',+ ]);+});++test('Canvas outline rendering puts equal-area child hit targets below parents', () => {+ const orderedOutlines = orderOutlinesForRendering({+ outlines: [+ makeTestOutline({+ key: 'parent',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ makeTestOutline({+ key: 'container',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ makeTestOutline({+ key: 'label',+ left: 25,+ top: 25,+ width: 50,+ height: 50,+ }),+ ],+ sequences: [+ makeOutlineSequence({id: 'parent', parent: null}),+ makeOutlineSequence({id: 'container', parent: 'parent'}),+ makeOutlineSequence({id: 'label', parent: 'container'}),+ ],+ targetsByKey: new Map([+ ['parent', makeOutlineTarget({id: 'parent', parent: null})],+ ['container', makeOutlineTarget({id: 'container', parent: 'parent'})],+ ['label', makeOutlineTarget({id: 'label', parent: 'container'})],+ ]),+ });++ expect(orderedOutlines.map((outline) => outline.key)).toEqual([+ 'container',+ 'parent',+ 'label',+ ]);+});++test('Canvas outline rendering keeps equal-area children containing selection above parents', () => {+ const outlines = [+ makeTestOutline({+ key: 'parent',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ makeTestOutline({+ key: 'child',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ ];+ const sequences = [+ makeOutlineSequence({id: 'parent', parent: null}),+ makeOutlineSequence({id: 'child', parent: 'parent'}),+ ];++ for (const selectionState of [{selected: true}, {containsSelection: true}]) {+ const orderedOutlines = orderOutlinesForRendering({+ outlines,+ sequences,+ targetsByKey: new Map([+ ['parent', makeOutlineTarget({id: 'parent', parent: null})],+ [+ 'child',+ {+ ...makeOutlineTarget({id: 'child', parent: 'parent'}),+ ...selectionState,+ },+ ],+ ]),+ });++ expect(orderedOutlines.map((outline) => outline.key)).toEqual([+ 'parent',+ 'child',+ ]);+ }+});++test('Canvas outline rendering handles transitive subpixel equivalence', () => {+ const orderedOutlines = orderOutlinesForRendering({+ outlines: [+ makeTestOutline({+ key: 'parent',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ makeTestOutline({+ key: 'child',+ left: 0.4,+ top: 0.4,+ width: 100,+ height: 100,+ }),+ makeTestOutline({+ key: 'grandchild',+ left: 0.8,+ top: 0.8,+ width: 100,+ height: 100,+ }),+ ],+ sequences: [+ makeOutlineSequence({id: 'parent', parent: null}),+ makeOutlineSequence({id: 'child', parent: 'parent'}),+ makeOutlineSequence({id: 'grandchild', parent: 'child'}),+ ],+ targetsByKey: new Map([+ ['parent', makeOutlineTarget({id: 'parent', parent: null})],+ ['child', makeOutlineTarget({id: 'child', parent: 'parent'})],+ ['grandchild', makeOutlineTarget({id: 'grandchild', parent: 'child'})],+ ]),+ });++ expect(orderedOutlines.map((outline) => outline.key)).toEqual([+ 'grandchild',+ 'child',+ 'parent',+ ]);+});++test('Canvas outline equivalence ignores polygon start vertex and winding', () => {+ const parent = makeTestOutline({+ key: 'parent',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ });+ const child: SelectedOutline = {+ ...makeTestOutline({+ key: 'child',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ points: [+ {x: 100, y: 100},+ {x: 100, y: 0},+ {x: 0, y: 0},+ {x: 0, y: 100},+ ],+ };+ const orderedOutlines = orderOutlinesForRendering({+ outlines: [parent, child],+ sequences: [+ makeOutlineSequence({id: 'parent', parent: null}),+ makeOutlineSequence({id: 'child', parent: 'parent'}),+ ],+ targetsByKey: new Map([+ ['parent', makeOutlineTarget({id: 'parent', parent: null})],+ ['child', makeOutlineTarget({id: 'child', parent: 'parent'})],+ ]),+ });++ expect(orderedOutlines.map((outline) => outline.key)).toEqual([+ 'child',+ 'parent',+ ]);+});++test('Canvas outline rendering keeps lower-third wrappers reachable below larger overlapping sequences', () => {+ const orderedOutlines = orderOutlinesForRendering({+ outlines: [+ makeTestOutline({+ key: 'lower-third-wrapper',+ left: 200,+ top: 854,+ width: 680,+ height: 138,+ }),+ makeTestOutline({+ key: 'overlapping-keyframed-sequence',+ left: 100,+ top: 700,+ width: 1000,+ height: 400,+ }),+ makeTestOutline({+ key: 'lower-third-container',+ left: 200,+ top: 854,+ width: 680,+ height: 138,+ }),+ ],+ sequences: [+ makeOutlineSequence({id: 'lower-third-wrapper', parent: null}),+ makeOutlineSequence({+ id: 'overlapping-keyframed-sequence',+ parent: null,+ }),+ makeOutlineSequence({+ id: 'lower-third-container',+ parent: 'lower-third-wrapper',+ }),+ ],+ targetsByKey: new Map([+ [+ 'lower-third-wrapper',+ makeOutlineTarget({id: 'lower-third-wrapper', parent: null}),+ ],+ [+ 'overlapping-keyframed-sequence',+ makeOutlineTarget({+ id: 'overlapping-keyframed-sequence',+ parent: null,+ selected: true,+ }),+ ],+ [+ 'lower-third-container',+ makeOutlineTarget({+ id: 'lower-third-container',+ parent: 'lower-third-wrapper',+ selected: true,+ }),+ ],+ ]),+ });++ expect(orderedOutlines.map((outline) => outline.key)).toEqual([+ 'overlapping-keyframed-sequence',+ 'lower-third-wrapper',+ 'lower-third-container',+ ]);+});++test('Canvas outline rendering orders equal-area children deterministically with unrelated outlines', () => {+ const orderedOutlines = orderOutlinesForRendering({+ outlines: [+ makeTestOutline({+ key: 'lower-third-wrapper',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ makeTestOutline({+ key: 'unrelated-keyframed-sequence',+ left: 200,+ top: 200,+ width: 100,+ height: 100,+ }),+ makeTestOutline({+ key: 'lower-third-container',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ makeTestOutline({+ key: 'lower-third-title',+ left: 25,+ top: 25,+ width: 50,+ height: 50,+ }),+ ],+ sequences: [+ makeOutlineSequence({id: 'lower-third-wrapper', parent: null}),+ makeOutlineSequence({id: 'unrelated-keyframed-sequence', parent: null}),+ makeOutlineSequence({+ id: 'lower-third-container',+ parent: 'lower-third-wrapper',+ }),+ makeOutlineSequence({+ id: 'lower-third-title',+ parent: 'lower-third-container',+ }),+ ],+ targetsByKey: new Map([+ [+ 'lower-third-wrapper',+ makeOutlineTarget({id: 'lower-third-wrapper', parent: null}),+ ],+ [+ 'unrelated-keyframed-sequence',+ makeOutlineTarget({id: 'unrelated-keyframed-sequence', parent: null}),+ ],+ [+ 'lower-third-container',+ makeOutlineTarget({+ id: 'lower-third-container',+ parent: 'lower-third-wrapper',+ }),+ ],+ [+ 'lower-third-title',+ makeOutlineTarget({+ id: 'lower-third-title',+ parent: 'lower-third-container',+ }),+ ],+ ]),+ });++ expect(orderedOutlines.map((outline) => outline.key)).toEqual([+ 'lower-third-container',+ 'lower-third-wrapper',+ 'unrelated-keyframed-sequence',+ 'lower-third-title',+ ]);+});++test('Canvas outline rendering follows hidden intermediate ancestors', () => {+ const orderedOutlines = orderOutlinesForRendering({+ outlines: [+ makeTestOutline({+ key: 'visible-parent',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ makeTestOutline({+ key: 'visible-child',+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ }),+ ],+ sequences: [+ makeOutlineSequence({id: 'visible-parent', parent: null}),+ makeOutlineSequence({id: 'hidden-wrapper', parent: 'visible-parent'}),+ makeOutlineSequence({id: 'visible-child', parent: 'hidden-wrapper'}),+ ],+ targetsByKey: new Map([+ [+ 'visible-parent',+ makeOutlineTarget({id: 'visible-parent', parent: null}),+ ],+ [+ 'visible-child',+ makeOutlineTarget({id: 'visible-child', parent: 'hidden-wrapper'}),+ ],+ ]),+ });++ expect(orderedOutlines.map((outline) => outline.key)).toEqual([+ 'visible-child',+ 'visible-parent',]);});