Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Show outline for selected sequence (#7824)

Jonny Burger843f2fb9d01a
diff --git a/packages/example/src/CenteredSolid.tsx b/packages/example/src/CenteredSolid.tsx
new file mode 100644
index 0000000000..bcb2c2762a
--- /dev/null
+++ b/packages/example/src/CenteredSolid.tsx
@@ -0,0 +1,21 @@
+import React from 'react';
+import {Solid} from 'remotion';
+
+const CenteredSolid: React.FC = () => {
+ return (
+ <Solid
+ width={240}
+ height={240}
+ color={'#d8d8d8'}
+ style={{
+ position: 'absolute',
+ left: '50%',
+ top: '50%',
+ transform: 'translate(-50%, -50%)',
+ rotate: '40deg',
+ }}
+ />
+ );
+};
+
+export default CenteredSolid;
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index f7e71a106f..03514b41cc 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -367,6 +367,14 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={120}
/>
+ <Composition
+ id="centered-solid"
+ lazyComponent={() => import('./CenteredSolid')}
+ width={1080}
+ height={1080}
+ fps={30}
+ durationInFrames={60}
+ />
</Folder>
<Folder name="dynamic-parameters">
<Composition
diff --git a/packages/studio/src/components/EditorContent.tsx b/packages/studio/src/components/EditorContent.tsx
index 5a6a8c0557..035503acf2 100644
--- a/packages/studio/src/components/EditorContent.tsx
+++ b/packages/studio/src/components/EditorContent.tsx
@@ -7,6 +7,7 @@ import {SplitterElement} from './Splitter/SplitterElement';
import {SplitterHandle} from './Splitter/SplitterHandle';
import {Timeline} from './Timeline/Timeline';
import {TimelineEmptyState} from './Timeline/TimelineEmptyState';
+import {TimelineSelectionProvider} from './Timeline/TimelineSelection';
const noop = () => undefined;
@@ -26,25 +27,33 @@ export const EditorContent: React.FC<{
const showTimeline =
canvasContent !== null && canvasContent.type === 'composition';
+ const content = (
+ <SplitterContainer
+ orientation="horizontal"
+ id="top-to-bottom"
+ maxFlex={0.9}
+ minFlex={0.2}
+ defaultFlex={0.75}
+ >
+ <SplitterElement sticky={null} type="flexer">
+ {children}
+ </SplitterElement>
+ <SplitterHandle allowToCollapse="none" onCollapse={noop} />
+ <SplitterElement sticky={null} type="anti-flexer">
+ {showTimeline ? <Timeline /> : <TimelineEmptyState />}
+ </SplitterElement>
+ </SplitterContainer>
+ );
+
return (
<div style={container}>
<InitialCompositionLoader />
<MenuToolbar readOnlyStudio={readOnlyStudio} />
- <SplitterContainer
- orientation="horizontal"
- id="top-to-bottom"
- maxFlex={0.9}
- minFlex={0.2}
- defaultFlex={0.75}
- >
- <SplitterElement sticky={null} type="flexer">
- {children}
- </SplitterElement>
- <SplitterHandle allowToCollapse="none" onCollapse={noop} />
- <SplitterElement sticky={null} type="anti-flexer">
- {showTimeline ? <Timeline /> : <TimelineEmptyState />}
- </SplitterElement>
- </SplitterContainer>
+ {showTimeline ? (
+ <TimelineSelectionProvider>{content}</TimelineSelectionProvider>
+ ) : (
+ content
+ )}
</div>
);
};
diff --git a/packages/studio/src/components/Preview.tsx b/packages/studio/src/components/Preview.tsx
index 286760cc45..92c674c5d7 100644
--- a/packages/studio/src/components/Preview.tsx
+++ b/packages/studio/src/components/Preview.tsx
@@ -16,6 +16,7 @@ import type {Dimensions} from '../helpers/is-current-selected-still';
import {CheckerboardContext} from '../state/checkerboard';
import {VERTICAL_SCROLLBAR_CLASSNAME} from './Menu/is-menu-item';
import {RenderPreview} from './RenderPreview';
+import {SelectedOutlineOverlay} from './SelectedOutlineOverlay';
import {Spinner} from './Spinner';
import {StaticFilePreview} from './StaticFilePreview';
@@ -271,6 +272,7 @@ const CompWhenItHasDimensions: React.FC<{
xCorrection={xCorrection}
yCorrection={yCorrection}
/>
+ <SelectedOutlineOverlay />
</div>
);
};
diff --git a/packages/studio/src/components/SelectedOutlineOverlay.tsx b/packages/studio/src/components/SelectedOutlineOverlay.tsx
new file mode 100644
index 0000000000..c2477742c4
--- /dev/null
+++ b/packages/studio/src/components/SelectedOutlineOverlay.tsx
@@ -0,0 +1,371 @@
+import React, {useContext, useEffect, useMemo, useRef, useState} from 'react';
+import type {OverrideIdToNodePaths, TSequence} from 'remotion';
+import {Internals} from 'remotion';
+import {calculateTimeline} from '../helpers/calculate-timeline';
+import {BLUE} from '../helpers/colors';
+import {
+ ENABLE_OUTLINES,
+ getTimelineSequenceSelectionKey,
+ type TimelineSelection,
+ useTimelineSelection,
+} from './Timeline/TimelineSelection';
+
+type OutlinePoint = {
+ readonly x: number;
+ readonly y: number;
+};
+
+type OutlineQuad = {
+ readonly p1: DOMPointReadOnly;
+ readonly p2: DOMPointReadOnly;
+ readonly p3: DOMPointReadOnly;
+ readonly p4: DOMPointReadOnly;
+};
+
+type ElementWithBoxQuads = HTMLElement & {
+ readonly getBoxQuads: () => readonly OutlineQuad[];
+};
+
+type SelectedOutline = {
+ readonly key: string;
+ readonly points: readonly [
+ OutlinePoint,
+ OutlinePoint,
+ OutlinePoint,
+ OutlinePoint,
+ ];
+};
+
+type SelectedOutlineTarget = {
+ readonly key: string;
+ readonly ref: React.RefObject<HTMLElement | null>;
+};
+
+const outlineContainer: React.CSSProperties = {
+ position: 'absolute',
+ inset: 0,
+ pointerEvents: 'none',
+ overflow: 'visible',
+};
+
+const pointToString = (point: OutlinePoint) => `${point.x},${point.y}`;
+
+const hasBoxQuads = (element: HTMLElement): element is ElementWithBoxQuads => {
+ return typeof (element as {getBoxQuads?: unknown}).getBoxQuads === 'function';
+};
+
+const rectToPoints = (
+ elementRect: DOMRect,
+ containerRect: DOMRect,
+): SelectedOutline['points'] => {
+ const left = elementRect.left - containerRect.left;
+ const top = elementRect.top - containerRect.top;
+ const right = elementRect.right - containerRect.left;
+ const bottom = elementRect.bottom - containerRect.top;
+
+ return [
+ {x: left, y: top},
+ {x: right, y: top},
+ {x: right, y: bottom},
+ {x: left, y: bottom},
+ ];
+};
+
+const parseTransformOrigin = (transformOrigin: string): OutlinePoint => {
+ const [x = '0', y = '0'] = transformOrigin.split(' ');
+
+ return {
+ x: Number.parseFloat(x) || 0,
+ y: Number.parseFloat(y) || 0,
+ };
+};
+
+const transformPoint = ({
+ matrix,
+ origin,
+ point,
+}: {
+ readonly matrix: DOMMatrix;
+ readonly origin: OutlinePoint;
+ readonly point: OutlinePoint;
+}): OutlinePoint => {
+ const transformed = new DOMPoint(
+ point.x - origin.x,
+ point.y - origin.y,
+ ).matrixTransform(matrix);
+
+ return {
+ x: transformed.x + origin.x,
+ y: transformed.y + origin.y,
+ };
+};
+
+// Chromium does not expose getBoxQuads(), so reconstruct the border-box corners
+// from the element transform and scale them into the measured canvas position.
+const getTransformedBorderBoxPoints = ({
+ containerRect,
+ element,
+ elementRect,
+}: {
+ readonly containerRect: DOMRect;
+ readonly element: HTMLElement;
+ readonly elementRect: DOMRect;
+}): SelectedOutline['points'] => {
+ const width = element.offsetWidth;
+ const height = element.offsetHeight;
+
+ if (width === 0 || height === 0) {
+ return rectToPoints(elementRect, containerRect);
+ }
+
+ const style = window.getComputedStyle(element);
+ const matrix =
+ style.transform === 'none'
+ ? new DOMMatrix()
+ : new DOMMatrix(style.transform);
+ const origin = parseTransformOrigin(style.transformOrigin);
+ const localPoints: SelectedOutline['points'] = [
+ transformPoint({matrix, origin, point: {x: 0, y: 0}}),
+ transformPoint({matrix, origin, point: {x: width, y: 0}}),
+ transformPoint({matrix, origin, point: {x: width, y: height}}),
+ transformPoint({matrix, origin, point: {x: 0, y: height}}),
+ ];
+ const minX = Math.min(...localPoints.map((point) => point.x));
+ const maxX = Math.max(...localPoints.map((point) => point.x));
+ const minY = Math.min(...localPoints.map((point) => point.y));
+ const maxY = Math.max(...localPoints.map((point) => point.y));
+ const localWidth = maxX - minX;
+ const localHeight = maxY - minY;
+
+ if (localWidth === 0 || localHeight === 0) {
+ return rectToPoints(elementRect, containerRect);
+ }
+
+ const scaleX = elementRect.width / localWidth;
+ const scaleY = elementRect.height / localHeight;
+ const projectPoint = (point: OutlinePoint): OutlinePoint => ({
+ x: elementRect.left + (point.x - minX) * scaleX - containerRect.left,
+ y: elementRect.top + (point.y - minY) * scaleY - containerRect.top,
+ });
+
+ return [
+ projectPoint(localPoints[0]),
+ projectPoint(localPoints[1]),
+ projectPoint(localPoints[2]),
+ projectPoint(localPoints[3]),
+ ];
+};
+
+const getElementOutlinePoints = (
+ element: HTMLElement,
+ containerRect: DOMRect,
+): SelectedOutline['points'] | null => {
+ const elementRect = element.getBoundingClientRect();
+
+ if (elementRect.width === 0 && elementRect.height === 0) {
+ return null;
+ }
+
+ if (!hasBoxQuads(element)) {
+ return getTransformedBorderBoxPoints({
+ containerRect,
+ element,
+ elementRect,
+ });
+ }
+
+ const quad = element.getBoxQuads()[0];
+ if (!quad) {
+ return rectToPoints(elementRect, containerRect);
+ }
+
+ return [
+ {x: quad.p1.x - containerRect.left, y: quad.p1.y - containerRect.top},
+ {x: quad.p2.x - containerRect.left, y: quad.p2.y - containerRect.top},
+ {x: quad.p3.x - containerRect.left, y: quad.p3.y - containerRect.top},
+ {x: quad.p4.x - containerRect.left, y: quad.p4.y - containerRect.top},
+ ];
+};
+
+const getSelectedSequenceKeys = (
+ selectedItems: readonly TimelineSelection[],
+): Set<string> => {
+ return new Set(
+ selectedItems.map((item) =>
+ getTimelineSequenceSelectionKey(item.nodePathInfo),
+ ),
+ );
+};
+
+const getSequencesWithSelectedOutlines = ({
+ selectedItems,
+ sequences,
+ overrideIdsToNodePaths,
+}: {
+ readonly selectedItems: readonly TimelineSelection[];
+ readonly sequences: readonly TSequence[];
+ readonly overrideIdsToNodePaths: OverrideIdToNodePaths;
+}): TSequence[] => {
+ const selectedSequenceKeys = getSelectedSequenceKeys(selectedItems);
+
+ if (selectedSequenceKeys.size === 0) {
+ return [];
+ }
+
+ return calculateTimeline({
+ sequences: [...sequences],
+ overrideIdsToNodePaths,
+ })
+ .filter((track) => {
+ if (track.nodePathInfo === null) {
+ return false;
+ }
+
+ return selectedSequenceKeys.has(
+ getTimelineSequenceSelectionKey(track.nodePathInfo),
+ );
+ })
+ .map((track) => track.sequence)
+ .filter((sequence) => sequence.refForOutline !== null);
+};
+
+const measureOutlines = (
+ container: SVGSVGElement,
+ targets: readonly SelectedOutlineTarget[],
+): SelectedOutline[] => {
+ const containerRect = container.getBoundingClientRect();
+ const outlines: SelectedOutline[] = [];
+
+ for (const target of targets) {
+ const element = target.ref.current;
+ if (element === null) {
+ continue;
+ }
+
+ const points = getElementOutlinePoints(element, containerRect);
+ if (points === null) {
+ continue;
+ }
+
+ outlines.push({key: target.key, points});
+ }
+
+ return outlines;
+};
+
+const outlinesAreEqual = (
+ a: readonly SelectedOutline[],
+ b: readonly SelectedOutline[],
+): boolean => {
+ if (a.length !== b.length) {
+ return false;
+ }
+
+ for (let i = 0; i < a.length; i++) {
+ if (a[i].key !== b[i].key) {
+ return false;
+ }
+
+ for (let j = 0; j < a[i].points.length; j++) {
+ if (
+ Math.abs(a[i].points[j].x - b[i].points[j].x) > 0.01 ||
+ Math.abs(a[i].points[j].y - b[i].points[j].y) > 0.01
+ ) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+};
+
+export const SelectedOutlineOverlay: React.FC = () => {
+ const {selectedItems} = useTimelineSelection();
+ const {sequences} = useContext(Internals.SequenceManager);
+ const {overrideIdToNodePathMappings} = useContext(
+ Internals.OverrideIdsToNodePathsGettersContext,
+ );
+ const [outlines, setOutlines] = useState<readonly SelectedOutline[]>([]);
+ const overlayRef = useRef<SVGSVGElement>(null);
+
+ const selectedOutlineTargets = useMemo((): SelectedOutlineTarget[] => {
+ if (!ENABLE_OUTLINES) {
+ return [];
+ }
+
+ return getSequencesWithSelectedOutlines({
+ selectedItems,
+ sequences,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ }).map((sequence) => {
+ if (sequence.refForOutline === null) {
+ throw new Error('Expected sequence to have a ref for outline');
+ }
+
+ return {
+ key: sequence.id,
+ ref: sequence.refForOutline,
+ };
+ });
+ }, [overrideIdToNodePathMappings, selectedItems, sequences]);
+
+ useEffect(() => {
+ if (selectedOutlineTargets.length === 0) {
+ setOutlines((prevOutlines) =>
+ prevOutlines.length === 0 ? prevOutlines : [],
+ );
+ return;
+ }
+
+ let animationFrame: number | null = null;
+
+ const updateOutlines = () => {
+ if (overlayRef.current) {
+ const nextOutlines = measureOutlines(
+ overlayRef.current,
+ selectedOutlineTargets,
+ );
+ setOutlines((prevOutlines) =>
+ outlinesAreEqual(prevOutlines, nextOutlines)
+ ? prevOutlines
+ : nextOutlines,
+ );
+ }
+
+ animationFrame = requestAnimationFrame(updateOutlines);
+ };
+
+ updateOutlines();
+
+ return () => {
+ if (animationFrame !== null) {
+ cancelAnimationFrame(animationFrame);
+ }
+ };
+ }, [selectedOutlineTargets]);
+
+ if (selectedOutlineTargets.length === 0) {
+ return null;
+ }
+
+ return (
+ <svg
+ ref={overlayRef}
+ style={outlineContainer}
+ width="100%"
+ height="100%"
+ aria-hidden="true"
+ >
+ {outlines.map((outline) => (
+ <polygon
+ key={outline.key}
+ points={outline.points.map(pointToString).join(' ')}
+ fill="none"
+ stroke={BLUE}
+ strokeWidth={2}
+ vectorEffect="non-scaling-stroke"
+ />
+ ))}
+ </svg>
+ );
+};
diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsx
index b44e46b3f7..283d9a127a 100644
--- a/packages/studio/src/components/Timeline/Timeline.tsx
+++ b/packages/studio/src/components/Timeline/Timeline.tsx
@@ -23,7 +23,7 @@ import {TimelinePinchZoom} from './TimelinePinchZoom';
import {TimelinePlayCursorSyncer} from './TimelinePlayCursorSyncer';
import {TimelineScrollable} from './TimelineScrollable';
import {
- TimelineSelectionProvider,
+ TimelineSelectAllKeybindings,
useTimelineSelection,
} from './TimelineSelection';
import {TimelineSlider} from './TimelineSlider';
@@ -118,61 +118,60 @@ const TimelineInner: React.FC = () => {
const hasBeenCut = filtered.length > shown.length;
return (
- <TimelineSelectionProvider timeline={shown}>
- <TimelineClearSelectionArea>
- {sequences.map((sequence) => {
- if (!sequence.controls || !previewConnected || !sequence.getStack()) {
- return null;
- }
-
- return (
- <SubscribeToNodePaths
- key={sequence.id}
- overrideId={sequence.controls.overrideId}
- schema={sequence.controls.schema}
- getStack={sequence.getStack}
- effects={sequence.effects}
- />
- );
- })}
- <SequencePropsObserver />
- <TimelineHeightContainer shown={shown} hasBeenCut={hasBeenCut}>
- {isStill ? (
- <TimelineList timeline={shown} />
- ) : (
- <TimelineWidthProvider>
- <TimelinePinchZoom />
- <SplitterContainer
- orientation="vertical"
- defaultFlex={0.2}
- id="names-to-timeline"
- maxFlex={0.5}
- minFlex={0.15}
+ <TimelineClearSelectionArea>
+ {sequences.map((sequence) => {
+ if (!sequence.controls || !previewConnected || !sequence.getStack()) {
+ return null;
+ }
+
+ return (
+ <SubscribeToNodePaths
+ key={sequence.id}
+ overrideId={sequence.controls.overrideId}
+ schema={sequence.controls.schema}
+ getStack={sequence.getStack}
+ effects={sequence.effects}
+ />
+ );
+ })}
+ <SequencePropsObserver />
+ <TimelineSelectAllKeybindings timeline={shown} />
+ <TimelineHeightContainer shown={shown} hasBeenCut={hasBeenCut}>
+ {isStill ? (
+ <TimelineList timeline={shown} />
+ ) : (
+ <TimelineWidthProvider>
+ <TimelinePinchZoom />
+ <SplitterContainer
+ orientation="vertical"
+ defaultFlex={0.2}
+ id="names-to-timeline"
+ maxFlex={0.5}
+ minFlex={0.15}
+ >
+ <SplitterElement
+ type="flexer"
+ sticky={<TimelineTimePlaceholders />}
>
- <SplitterElement
- type="flexer"
- sticky={<TimelineTimePlaceholders />}
- >
- <TimelineList timeline={shown} />
- </SplitterElement>
- <SplitterHandle onCollapse={noop} allowToCollapse="none" />
- <SplitterElement type="anti-flexer" sticky={null}>
- <TimelineScrollable>
- <TimelineTracks timeline={shown} hasBeenCut={hasBeenCut} />
- <TimelinePlayCursorSyncer />
- <TimelineInOutPointer />
- <TimelineTimeIndicators />
- <TimelineDragHandler />
- <TimelineInOutDragHandler />
- <TimelineSlider />
- </TimelineScrollable>
- </SplitterElement>
- </SplitterContainer>
- </TimelineWidthProvider>
- )}
- </TimelineHeightContainer>
- </TimelineClearSelectionArea>
- </TimelineSelectionProvider>
+ <TimelineList timeline={shown} />
+ </SplitterElement>
+ <SplitterHandle onCollapse={noop} allowToCollapse="none" />
+ <SplitterElement type="anti-flexer" sticky={null}>
+ <TimelineScrollable>
+ <TimelineTracks timeline={shown} hasBeenCut={hasBeenCut} />
+ <TimelinePlayCursorSyncer />
+ <TimelineInOutPointer />
+ <TimelineTimeIndicators />
+ <TimelineDragHandler />
+ <TimelineInOutDragHandler />
+ <TimelineSlider />
+ </TimelineScrollable>
+ </SplitterElement>
+ </SplitterContainer>
+ </TimelineWidthProvider>
+ )}
+ </TimelineHeightContainer>
+ </TimelineClearSelectionArea>
);
};
diff --git a/packages/studio/src/components/Timeline/TimelineSelection.tsx b/packages/studio/src/components/Timeline/TimelineSelection.tsx
index 3d4de43060..dd4308ac06 100644
--- a/packages/studio/src/components/Timeline/TimelineSelection.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSelection.tsx
@@ -60,6 +60,7 @@ export const getTimelineSelectedTrackHighlightStyle = (
export const SELECTION_ENABLED = false;
export const TIMELINE_TOP_DRAG = false;
+export const ENABLE_OUTLINES = false;
export type TimelineSelection =
| {
@@ -141,7 +142,11 @@ export const getSelectableTimelineSequenceSelections = (
});
};
-const TimelineSelectAllKeybindings: React.FC<{
+export const getTimelineSequenceSelectionKey = (
+ nodePathInfo: SequenceNodePathInfo,
+): string => timelineNodePathInfoToKey({...nodePathInfo, auxiliaryKeys: []});
+
+export const TimelineSelectAllKeybindings: React.FC<{
readonly timeline: readonly TrackWithHash[];
}> = ({timeline}) => {
const keybindings = useKeybinding();
@@ -179,8 +184,7 @@ const TimelineSelectAllKeybindings: React.FC<{
export const TimelineSelectionProvider: React.FC<{
readonly children: React.ReactNode;
- readonly timeline: readonly TrackWithHash[];
-}> = ({children, timeline}) => {
+}> = ({children}) => {
const {previewServerState} = useContext(StudioServerConnectionCtx);
const canSelect =
SELECTION_ENABLED &&
@@ -267,7 +271,6 @@ export const TimelineSelectionProvider: React.FC<{
return (
<TimelineSelectionContext.Provider value={value}>
{children}
- <TimelineSelectAllKeybindings timeline={timeline} />
<TimelineDeleteKeybindings />
</TimelineSelectionContext.Provider>
);
diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.ts
index 4b9df24bf8..44b10ee898 100644
--- a/packages/studio/src/test/timeline-selection.test.ts
+++ b/packages/studio/src/test/timeline-selection.test.ts
@@ -1,7 +1,9 @@
import {expect, test} from 'bun:test';
import type {SequenceNodePath, SequencePropsSubscriptionKey} from 'remotion';
import {
+ ENABLE_OUTLINES,
getSelectableTimelineSequenceSelections,
+ getTimelineSequenceSelectionKey,
SELECTION_ENABLED,
TIMELINE_TOP_DRAG,
} from '../components/Timeline/TimelineSelection';
@@ -32,6 +34,10 @@ test('Timeline top drag should not be enabled', () => {
expect(TIMELINE_TOP_DRAG).toBe(false);
});
+test('Timeline outlines should not be enabled', () => {
+ expect(ENABLE_OUTLINES).toBe(false);
+});
+
test('Cmd+A selection only targets selectable timeline sequences', () => {
const sequenceNodePathInfo = makeNodePathInfo(['body', 0], []);
const effectNodePathInfo = makeNodePathInfo(['body', 1], ['effects', '0']);
@@ -49,3 +55,19 @@ test('Cmd+A selection only targets selectable timeline sequences', () => {
},
]);
});
+
+test('Child timeline selections resolve to the parent sequence selection key', () => {
+ const sequenceNodePathInfo = makeNodePathInfo(['body', 0], []);
+ const effectNodePathInfo = makeNodePathInfo(['body', 0], ['effects', '0']);
+ const propNodePathInfo = makeNodePathInfo(
+ ['body', 0],
+ ['controls', 'opacity'],
+ );
+
+ expect(getTimelineSequenceSelectionKey(effectNodePathInfo)).toBe(
+ getTimelineSequenceSelectionKey(sequenceNodePathInfo),
+ );
+ expect(getTimelineSequenceSelectionKey(propNodePathInfo)).toBe(
+ getTimelineSequenceSelectionKey(sequenceNodePathInfo),
+ );
+});