Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Add automatic outlines for `<Sequence layout="none">`

JonnyBurger94734f7e9dde
diff --git a/packages/canvas/src/outline-measurement.ts b/packages/canvas/src/outline-measurement.ts
index e29823a38f..ea179c56b4 100644
--- a/packages/canvas/src/outline-measurement.ts
+++ b/packages/canvas/src/outline-measurement.ts
@@ -10,6 +10,7 @@ import type {
CanvasOutlineTarget,
} from './outline-geometry';
import {getCanvasOutlinePoint} from './outline-geometry';
+import {getCanvasOutlineNodes} from './outline-nodes';
const rectToPoints = (
elementRect: DOMRect,
@@ -321,25 +322,13 @@ const getPathOutline = ({
const getElementOutlinePoints = (
element: Element,
+ elementRect: DOMRect,
containerRect: DOMRect,
- includeOutsideContainer: boolean,
): CanvasOutline['points'] | null => {
- const elementRect = element.getBoundingClientRect();
-
if (elementRect.width === 0 && elementRect.height === 0) {
return null;
}
- if (
- !includeOutsideContainer &&
- (elementRect.right <= containerRect.left ||
- elementRect.left >= containerRect.right ||
- elementRect.bottom <= containerRect.top ||
- elementRect.top >= containerRect.bottom)
- ) {
- return null;
- }
-
if (isSvgSvgElement(element)) {
return getSvgSvgElementOutlinePoints(element, containerRect);
}
@@ -392,17 +381,94 @@ export const measureCanvasOutlineTargets = (
resetBoxQuadsCache();
const containerRect = container.getBoundingClientRect();
const outlines: CanvasOutline[] = [];
+ const rects = new Map<Element | Text, DOMRect>();
+ const geometry = new Map<
+ Element,
+ Pick<CanvasOutline, 'dimensions' | 'path'> & {
+ uncroppedPoints: CanvasOutline['points'];
+ }
+ >();
for (const target of targets) {
- const element = target.ref.current;
- if (element === null) {
+ const nodes = getCanvasOutlineNodes(target.ref);
+ let left = Infinity;
+ let top = Infinity;
+ let right = -Infinity;
+ let bottom = -Infinity;
+ const measurableNodes: (Element | Text)[] = [];
+ for (const node of nodes) {
+ let rect = rects.get(node);
+ if (rect === undefined) {
+ if (node.nodeType === 3) {
+ const range = node.ownerDocument.createRange();
+ range.selectNodeContents(node);
+ rect = range.getBoundingClientRect();
+ } else {
+ rect = (node as Element).getBoundingClientRect();
+ }
+
+ rects.set(node, rect);
+ }
+
+ if (rect.width === 0 && rect.height === 0) {
+ continue;
+ }
+
+ measurableNodes.push(node);
+ left = Math.min(left, rect.left);
+ top = Math.min(top, rect.top);
+ right = Math.max(right, rect.right);
+ bottom = Math.max(bottom, rect.bottom);
+ }
+
+ if (
+ measurableNodes.length === 0 ||
+ (!target.includeOutsideContainer &&
+ (right <= containerRect.left ||
+ left >= containerRect.right ||
+ bottom <= containerRect.top ||
+ top >= containerRect.bottom))
+ ) {
+ continue;
+ }
+
+ if (measurableNodes.length !== 1 || measurableNodes[0].nodeType !== 1) {
+ const groupPoints: CanvasOutline['points'] = [
+ {x: left - containerRect.left, y: top - containerRect.top},
+ {x: right - containerRect.left, y: top - containerRect.top},
+ {x: right - containerRect.left, y: bottom - containerRect.top},
+ {x: left - containerRect.left, y: bottom - containerRect.top},
+ ];
+ outlines.push({
+ key: target.key,
+ points: groupPoints,
+ uncroppedPoints: groupPoints,
+ dimensions: null,
+ path: null,
+ });
continue;
}
+ const element = measurableNodes[0] as Element;
+ const cached = geometry.get(element);
+ if (cached) {
+ outlines.push({
+ ...cached,
+ key: target.key,
+ points: cropCanvasOutlinePoints(cached.uncroppedPoints, target.crop),
+ });
+ continue;
+ }
+
+ const elementRect = rects.get(element);
+ if (elementRect === undefined) {
+ throw new Error('Expected a measured outline element');
+ }
+
const uncroppedPoints = getElementOutlinePoints(
element,
+ elementRect,
containerRect,
- target.includeOutsideContainer,
);
if (uncroppedPoints === null) {
continue;
@@ -415,8 +481,7 @@ export const measureCanvasOutlineTargets = (
? getPathOutline({element, containerRect})
: null;
- outlines.push({
- key: target.key,
+ const measured = {
dimensions:
(typeof HTMLElement !== 'undefined' &&
element instanceof HTMLElement) ||
@@ -432,9 +497,10 @@ export const measureCanvasOutlineTargets = (
}
: null,
uncroppedPoints,
- points,
path,
- });
+ };
+ geometry.set(element, measured);
+ outlines.push({...measured, key: target.key, points});
}
return outlines;
diff --git a/packages/canvas/src/outline-nodes.ts b/packages/canvas/src/outline-nodes.ts
new file mode 100644
index 0000000000..60393d4989
--- /dev/null
+++ b/packages/canvas/src/outline-nodes.ts
@@ -0,0 +1,41 @@
+import type {RefObject} from 'react';
+import {Internals} from 'remotion';
+
+/** Resolve boxless DOM roots without adding a wrapper to the composition. */
+export const getCanvasOutlineNodes = (
+ ref: RefObject<Element | null>,
+): readonly (Element | Text)[] => {
+ const automaticNodes = Internals.SequenceOutlineInternals.getNodes(ref);
+ if (automaticNodes === null) {
+ return ref.current === null ? [] : [ref.current];
+ }
+
+ const nodes: (Element | Text)[] = [];
+ const visit = (node: Element | Text) => {
+ if (!node.isConnected) {
+ return;
+ }
+
+ if (
+ node.nodeType === 1 &&
+ node.ownerDocument.defaultView?.getComputedStyle(node as Element)
+ .display === 'contents'
+ ) {
+ for (const child of node.childNodes) {
+ if (child.nodeType === 1 || child.nodeType === 3) {
+ visit(child as Element | Text);
+ }
+ }
+
+ return;
+ }
+
+ nodes.push(node);
+ };
+
+ for (const node of automaticNodes) {
+ visit(node);
+ }
+
+ return nodes;
+};
diff --git a/packages/canvas/src/use-canvas-outline-measurements.ts b/packages/canvas/src/use-canvas-outline-measurements.ts
index 0e8e00a6ca..7ee14c68af 100644
--- a/packages/canvas/src/use-canvas-outline-measurements.ts
+++ b/packages/canvas/src/use-canvas-outline-measurements.ts
@@ -1,10 +1,12 @@
import type {MutableRefObject, RefObject} from 'react';
import {useCallback, useLayoutEffect, useRef, useState} from 'react';
+import {Internals} from 'remotion';
import type {CanvasOutline, CanvasOutlineTarget} from './outline-geometry';
import {
canvasOutlinesAreEqual,
measureCanvasOutlineTargets,
} from './outline-measurement';
+import {getCanvasOutlineNodes} from './outline-nodes';
export const useCanvasOutlineMeasurements = ({
containerRef,
@@ -26,6 +28,8 @@ export const useCanvasOutlineMeasurements = ({
const updateOutlines = useCallback(() => {
const container = containerRef.current;
if (container === null || targets.length === 0) {
+ resizeObserverRef.current?.disconnect();
+ observedElementsRef.current = new Set();
if (outlinesRef.current.length === 0) {
return;
}
@@ -35,6 +39,38 @@ export const useCanvasOutlineMeasurements = ({
return;
}
+ const resizeObserver = resizeObserverRef.current;
+ if (resizeObserver !== null) {
+ const nextObservedElements = new Set<Element>();
+ if (containerRef.current !== null) {
+ nextObservedElements.add(containerRef.current);
+ }
+
+ for (const target of targets) {
+ for (const node of getCanvasOutlineNodes(target.ref)) {
+ const element =
+ node.nodeType === 1 ? (node as Element) : node.parentElement;
+ if (element !== null) {
+ nextObservedElements.add(element);
+ }
+ }
+ }
+
+ for (const element of observedElementsRef.current) {
+ if (!nextObservedElements.has(element)) {
+ resizeObserver.unobserve(element);
+ }
+ }
+
+ for (const element of nextObservedElements) {
+ if (!observedElementsRef.current.has(element)) {
+ resizeObserver.observe(element);
+ }
+ }
+
+ observedElementsRef.current = nextObservedElements;
+ }
+
const nextOutlines = measureCanvasOutlineTargets(container, targets);
if (canvasOutlinesAreEqual(outlinesRef.current, nextOutlines)) {
return;
@@ -50,14 +86,48 @@ export const useCanvasOutlineMeasurements = ({
updateOutlinesRef.current = updateOutlines;
}
- updateOutlines();
+ // The Fiber observer discovers nodes after React's layout effects. Batch
+ // automatic measurements after that commit, including child-only updates
+ // while paused, instead of measuring stale nodes and measuring again.
+ let active = true;
+ let scheduled = false;
+ const scheduleUpdate = () => {
+ if (scheduled) return;
+ scheduled = true;
+ queueMicrotask(() => {
+ scheduled = false;
+ if (active) updateOutlines();
+ });
+ };
+
+ const ownerWindow = containerRef.current?.ownerDocument.defaultView;
+ const hasAutomaticTargets = targets.some(
+ (target) =>
+ Internals.SequenceOutlineInternals.getNodes(target.ref) !== null,
+ );
+ if (hasAutomaticTargets) {
+ latestUpdateRef.current = scheduleUpdate;
+ ownerWindow?.addEventListener(
+ Internals.CommitOrderInternals.eventName,
+ scheduleUpdate,
+ );
+ scheduleUpdate();
+ } else {
+ updateOutlines();
+ }
+
return () => {
+ active = false;
+ ownerWindow?.removeEventListener(
+ Internals.CommitOrderInternals.eventName,
+ scheduleUpdate,
+ );
latestUpdateRef.current = () => undefined;
if (updateOutlinesRef?.current === updateOutlines) {
updateOutlinesRef.current = () => undefined;
}
};
- }, [updateOutlines, updateOutlinesRef]);
+ }, [containerRef, targets, updateOutlines, updateOutlinesRef]);
useLayoutEffect(() => {
const ownerWindow = containerRef.current?.ownerDocument.defaultView;
@@ -77,6 +147,7 @@ export const useCanvasOutlineMeasurements = ({
});
});
resizeObserverRef.current = resizeObserver;
+ latestUpdateRef.current();
return () => {
if (animationFrame !== null) {
@@ -89,37 +160,5 @@ export const useCanvasOutlineMeasurements = ({
};
}, [containerRef]);
- useLayoutEffect(() => {
- const resizeObserver = resizeObserverRef.current;
- if (resizeObserver === null) {
- return;
- }
-
- const nextObservedElements = new Set<Element>();
- if (containerRef.current !== null) {
- nextObservedElements.add(containerRef.current);
- }
-
- for (const target of targets) {
- if (target.ref.current !== null) {
- nextObservedElements.add(target.ref.current);
- }
- }
-
- for (const element of observedElementsRef.current) {
- if (!nextObservedElements.has(element)) {
- resizeObserver.unobserve(element);
- }
- }
-
- for (const element of nextObservedElements) {
- if (!observedElementsRef.current.has(element)) {
- resizeObserver.observe(element);
- }
- }
-
- observedElementsRef.current = nextObservedElements;
- }, [containerRef, targets]);
-
return outlines;
};
diff --git a/packages/core/src/Sequence.tsx b/packages/core/src/Sequence.tsx
index 482ca913ae..3b4c0f26ef 100644
--- a/packages/core/src/Sequence.tsx
+++ b/packages/core/src/Sequence.tsx
@@ -29,6 +29,7 @@ import {
validateSequenceCrop,
} from './sequence-crop.js';
import {SequenceOrderMarker} from './sequence-order-marker.js';
+import {SequenceOutlineInternals} from './sequence-outline.js';
import type {SequenceContextType} from './SequenceContext.js';
import {SequenceContext} from './SequenceContext.js';
import {SequenceRegistrationContext} from './SequenceManager.js';
@@ -318,10 +319,18 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
Math.min(videoConfig.durationInFrames - from, parentSequenceDuration),
);
const sequenceRegistrationEnabled = useContext(SequenceRegistrationContext);
+ const env = useRemotionEnvironment();
+ const automaticOutlineRef = useMemo(
+ () =>
+ env.isStudio && layout === 'none' && !passedRefForOutline
+ ? SequenceOutlineInternals.createRef()
+ : null,
+ [env.isStudio, layout, passedRefForOutline],
+ );
const wrapperRefForOutline = useRef<HTMLDivElement | null>(null);
const refForOutline =
other.layout === 'none'
- ? (passedRefForOutline ?? null)
+ ? (passedRefForOutline ?? automaticOutlineRef)
: (passedRefForOutline ?? wrapperRefForOutline);
const premounting = useMemo(() => {
@@ -412,8 +421,6 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
const resolvedDocumentationLink =
documentationLink ?? 'https://www.remotion.dev/docs/sequence';
- const env = useRemotionEnvironment();
-
const isInsideSeries = useContext(IsInsideSeriesContext);
// Our assumption: Stack doesnt' change. After we symbolicate we assign it a nodePath
@@ -683,7 +690,12 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
if (hidden) {
return env.isStudio ? (
- <SequenceOrderMarker sequenceId={id}>{null}</SequenceOrderMarker>
+ <SequenceOrderMarker
+ sequenceId={id}
+ outlineChildrenRef={automaticOutlineRef}
+ >
+ {null}
+ </SequenceOrderMarker>
) : null;
}
@@ -704,7 +716,12 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
);
return env.isStudio ? (
- <SequenceOrderMarker sequenceId={id}>{sequence}</SequenceOrderMarker>
+ <SequenceOrderMarker
+ sequenceId={id}
+ outlineChildrenRef={automaticOutlineRef}
+ >
+ {sequence}
+ </SequenceOrderMarker>
) : (
sequence
);
diff --git a/packages/core/src/audio/AudioForPreview.tsx b/packages/core/src/audio/AudioForPreview.tsx
index 0bf5bc3aa1..18d31d6856 100644
--- a/packages/core/src/audio/AudioForPreview.tsx
+++ b/packages/core/src/audio/AudioForPreview.tsx
@@ -280,7 +280,9 @@ const AudioForDevelopmentForwardRefFunction: React.ForwardRefRenderFunction<
if (initialShouldPreMountAudioElements) {
return isStudio ? (
- <SequenceOrderMarker sequenceId={timelineId}>{null}</SequenceOrderMarker>
+ <SequenceOrderMarker sequenceId={timelineId} outlineChildrenRef={null}>
+ {null}
+ </SequenceOrderMarker>
) : null;
}
@@ -294,7 +296,9 @@ const AudioForDevelopmentForwardRefFunction: React.ForwardRefRenderFunction<
);
return isStudio ? (
- <SequenceOrderMarker sequenceId={timelineId}>{audio}</SequenceOrderMarker>
+ <SequenceOrderMarker sequenceId={timelineId} outlineChildrenRef={null}>
+ {audio}
+ </SequenceOrderMarker>
) : (
audio
);
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index 0dd1be5a30..1698017a38 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -167,6 +167,7 @@ import {
OverrideIdsToNodePathsSettersContext,
} from './sequence-node-path.js';
import {CommitOrderInternals} from './sequence-order-marker.js';
+import {SequenceOutlineInternals} from './sequence-outline.js';
import type {ResolvedStackLocation} from './sequence-stack-traces.js';
import {SequenceStackTracesUpdateContext} from './sequence-stack-traces.js';
import {SequenceWithoutSchema} from './Sequence.js';
@@ -338,6 +339,7 @@ export const Internals = {
SequenceManagerRefContext,
SequenceRegistrationContext,
CommitOrderInternals,
+ SequenceOutlineInternals,
SequenceStackTracesUpdateContext,
baseSchema,
sequenceSchema,
diff --git a/packages/core/src/sequence-order-marker.tsx b/packages/core/src/sequence-order-marker.tsx
index 3ae5991df0..a0d489301e 100644
--- a/packages/core/src/sequence-order-marker.tsx
+++ b/packages/core/src/sequence-order-marker.tsx
@@ -45,6 +45,7 @@ export const getFolderOrderId = ({
export const SequenceOrderMarker: React.FC<{
readonly children: React.ReactNode;
readonly sequenceId: string;
+ readonly outlineChildrenRef: React.RefObject<Element | null> | null;
}> = ({children}) => children;
Object.defineProperty(SequenceOrderMarker, SEQUENCE_ORDER_MARKER, {
diff --git a/packages/core/src/sequence-outline.ts b/packages/core/src/sequence-outline.ts
new file mode 100644
index 0000000000..5f59b9b711
--- /dev/null
+++ b/packages/core/src/sequence-outline.ts
@@ -0,0 +1,35 @@
+import type {RefObject} from 'react';
+
+type OutlineNode = Element | Text;
+type OutlineRef = RefObject<Element | null>;
+
+// Keep automatic groups separate from the public, single-element outlineRef.
+// A group only exposes .current when it has exactly one element, so consumers
+// that require an actual element never accidentally act on part of a group.
+const nodesByRef = new WeakMap<OutlineRef, readonly OutlineNode[]>();
+
+export const SequenceOutlineInternals = {
+ createRef: (): OutlineRef => {
+ const ref: OutlineRef = {current: null};
+ nodesByRef.set(ref, []);
+ return ref;
+ },
+ getNodes: (ref: OutlineRef): readonly OutlineNode[] | null => {
+ return nodesByRef.get(ref) ?? null;
+ },
+ setNodes: (ref: OutlineRef, nodes: readonly OutlineNode[]) => {
+ const previous = nodesByRef.get(ref);
+ if (
+ previous?.length === nodes.length &&
+ previous.every((node, index) => node === nodes[index])
+ ) {
+ return;
+ }
+
+ nodesByRef.set(ref, nodes);
+ ref.current =
+ nodes.length === 1 && nodes[0].nodeType === 1
+ ? (nodes[0] as Element)
+ : null;
+ },
+};
diff --git a/packages/core/src/video/VideoForPreview.tsx b/packages/core/src/video/VideoForPreview.tsx
index 1ee80723a0..a6a82862c8 100644
--- a/packages/core/src/video/VideoForPreview.tsx
+++ b/packages/core/src/video/VideoForPreview.tsx
@@ -373,7 +373,9 @@ const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<
);
return isStudio ? (
- <SequenceOrderMarker sequenceId={timelineId}>{video}</SequenceOrderMarker>
+ <SequenceOrderMarker sequenceId={timelineId} outlineChildrenRef={null}>
+ {video}
+ </SequenceOrderMarker>
) : (
video
);
diff --git a/packages/example/src/LayoutNoneOutlines.tsx b/packages/example/src/LayoutNoneOutlines.tsx
new file mode 100644
index 0000000000..9fba0effd2
--- /dev/null
+++ b/packages/example/src/LayoutNoneOutlines.tsx
@@ -0,0 +1,101 @@
+import React, {useRef} from 'react';
+import {AbsoluteFill, Sequence, useCurrentFrame} from 'remotion';
+
+const card: React.CSSProperties = {
+ position: 'absolute',
+ width: 180,
+ height: 120,
+ borderRadius: 16,
+ display: 'grid',
+ placeItems: 'center',
+ fontSize: 24,
+ fontWeight: 600,
+};
+
+// This component deliberately returns siblings, so inspecting Sequence's JSX
+// children alone would not find the elements that make up its outline.
+const Siblings: React.FC = () => {
+ const frame = useCurrentFrame();
+ return (
+ <>
+ <div style={{...card, left: 480, top: 210, background: '#2563eb'}}>
+ First child
+ </div>
+ <Sequence layout="none" name="Nested wrapperless child">
+ <div
+ style={{
+ ...card,
+ left: 730 + Math.sin(frame / 30) * 60,
+ top: 300,
+ background: '#7c3aed',
+ }}
+ >
+ Moving child
+ </div>
+ </Sequence>
+ {frame >= 90 ? (
+ <div style={{...card, left: 1000, top: 240, background: '#b45309'}}>
+ Appears at 3s
+ </div>
+ ) : null}
+ </>
+ );
+};
+
+export const LayoutNoneOutlines: React.FC = () => {
+ const outlineRef = useRef<HTMLDivElement | null>(null);
+ return (
+ <AbsoluteFill
+ style={{background: '#0f172a', color: 'white', fontFamily: 'sans-serif'}}
+ >
+ <h1 style={{margin: '48px 60px 12px', fontSize: 40}}>
+ Outlines without wrappers
+ </h1>
+ <p style={{margin: '0 60px', fontSize: 23, color: '#cbd5e1'}}>
+ Select the named sequences in the timeline. Scrub past 3s to add a
+ child.
+ </p>
+ <Sequence layout="none" name="Single rotated element">
+ <div
+ style={{
+ ...card,
+ left: 90,
+ top: 250,
+ background: '#0f766e',
+ rotate: '-15deg',
+ }}
+ >
+ Single element
+ </div>
+ </Sequence>
+ <Sequence layout="none" name="Automatic group of siblings">
+ <Siblings />
+ </Sequence>
+ <div style={{position: 'absolute', left: 80, top: 530, fontSize: 28}}>
+ <Sequence layout="none" name="Text and display contents">
+ Direct text{' '}
+ <span style={{display: 'contents'}}>
+ <span style={{color: '#38bdf8'}}>and a boxless wrapper</span>
+ </span>
+ </Sequence>
+ </div>
+ <Sequence
+ layout="none"
+ name="Explicit outlineRef wins"
+ outlineRef={outlineRef}
+ >
+ <div
+ ref={outlineRef}
+ style={{...card, left: 720, top: 500, background: '#be185d'}}
+ >
+ Explicit target
+ </div>
+ <div
+ style={{...card, left: 960, top: 500, border: '2px dashed #64748b'}}
+ >
+ Outside outline
+ </div>
+ </Sequence>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index 79d1f9a7b2..bec6c7f339 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -250,6 +250,7 @@ import {
Issue8974TransitionSeriesTimeline,
} from './Issue8974TimelineInteractivity';
import {JumpCuts, SAMPLE_SECTIONS, calculateMetadataJumpCuts} from './JumpCuts';
+import {LayoutNoneOutlines} from './LayoutNoneOutlines';
import {LightLeakExample} from './LightLeak';
import {LightLeakAnimatedSize} from './LightLeak/AnimatedSize';
import {LoopDisplayTestComp} from './LoopDisplayTest';
@@ -3115,6 +3116,14 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={2340}
/>
+ <Composition
+ id="layout-none-outlines"
+ component={LayoutNoneOutlines}
+ width={1280}
+ height={720}
+ fps={30}
+ durationInFrames={180}
+ />
<Composition
id="fast-updates"
component={FastUpdates}
diff --git a/packages/studio/src/helpers/install-fiber-sequence-order-observer.ts b/packages/studio/src/helpers/install-fiber-sequence-order-observer.ts
index e06c7dfa98..5619b3582c 100644
--- a/packages/studio/src/helpers/install-fiber-sequence-order-observer.ts
+++ b/packages/studio/src/helpers/install-fiber-sequence-order-observer.ts
@@ -1,3 +1,4 @@
+import type {RefObject} from 'react';
import {Internals} from 'remotion';
type Fiber = {
@@ -6,6 +7,9 @@ type Fiber = {
readonly memoizedProps: unknown;
readonly sibling: Fiber | null;
readonly type: unknown;
+ readonly tag: number | null;
+ readonly stateNode: unknown;
+ readonly memoizedState: unknown;
};
type FiberRoot = {
@@ -58,6 +62,10 @@ const hasFiberMarker = (fiber: Fiber, marker: symbol) =>
hasMarker(fiber.type, marker) || hasMarker(fiber.elementType, marker);
export const collectCommitOrderFromFiber = (root: FiberRoot) => {
+ const outlineNodesByRef = new Map<
+ RefObject<Element | null>,
+ (Element | Text)[]
+ >();
const sequencesByManager = new Map<string, string[]>();
const compositionsAndFoldersByManager = new Map<
string,
@@ -68,7 +76,19 @@ export const collectCommitOrderFromFiber = (root: FiberRoot) => {
fiber: Fiber,
currentSequenceManagerId: string | null,
currentCompositionManagerId: string | null,
+ outlineCollectors: readonly (Element | Text)[][] | null,
) => {
+ // A portal ends the current DOM group, but can contain new sequences:
+ // Studio itself renders the composition through a portal. Hidden
+ // Offscreen trees must not contribute geometry, including new groups.
+ const skipOutline =
+ outlineCollectors === null ||
+ (fiber.tag === 22 && fiber.memoizedState !== null);
+ let childOutlineCollectors = skipOutline
+ ? null
+ : fiber.tag === 4
+ ? []
+ : outlineCollectors;
const isSequenceManagerMarker = hasFiberMarker(
fiber,
Internals.CommitOrderInternals.sequenceManagerMarker,
@@ -108,6 +128,22 @@ export const collectCommitOrderFromFiber = (root: FiberRoot) => {
if (sequenceId !== null) {
sequencesByManager.get(sequenceManagerId)?.push(sequenceId);
}
+
+ const props = fiber.memoizedProps;
+ const outlineRef =
+ typeof props === 'object' && props !== null
+ ? (Reflect.get(props, 'outlineChildrenRef') as
+ | RefObject<Element | null>
+ | null
+ | undefined)
+ : null;
+ if (outlineRef) {
+ const nodes: (Element | Text)[] = [];
+ outlineNodesByRef.set(outlineRef, nodes);
+ if (childOutlineCollectors !== null) {
+ childOutlineCollectors = [...childOutlineCollectors, nodes];
+ }
+ }
}
if (
@@ -134,14 +170,38 @@ export const collectCommitOrderFromFiber = (root: FiberRoot) => {
}
}
+ if (
+ childOutlineCollectors !== null &&
+ childOutlineCollectors.length > 0 &&
+ (fiber.tag === 5 || fiber.tag === 6) &&
+ fiber.stateNode !== null
+ ) {
+ for (const collector of childOutlineCollectors) {
+ collector.push(fiber.stateNode as Element | Text);
+ }
+
+ // Only first-level DOM nodes belong to this group. Keep traversing
+ // for sequence order and for new groups nested inside this element.
+ childOutlineCollectors = [];
+ }
+
let {child} = fiber;
while (child !== null) {
- visit(child, sequenceManagerId, compositionManagerId);
+ visit(
+ child,
+ sequenceManagerId,
+ compositionManagerId,
+ childOutlineCollectors,
+ );
child = child.sibling;
}
};
- visit(root.current, null, null);
+ visit(root.current, null, null, []);
+ for (const [ref, nodes] of outlineNodesByRef) {
+ Internals.SequenceOutlineInternals.setNodes(ref, nodes);
+ }
+
return {
sequenceManagers: [...sequencesByManager].map(
([managerId, sequenceIds]) => ({managerId, sequenceIds}),
diff --git a/packages/studio/src/test/fiber-sequence-order-observer.test.ts b/packages/studio/src/test/fiber-sequence-order-observer.test.ts
index c477b0f929..13ebe46713 100644
--- a/packages/studio/src/test/fiber-sequence-order-observer.test.ts
+++ b/packages/studio/src/test/fiber-sequence-order-observer.test.ts
@@ -11,6 +11,9 @@ type TestFiber = {
memoizedProps: unknown;
sibling: TestFiber | null;
type: unknown;
+ tag: number | null;
+ stateNode: unknown;
+ memoizedState: unknown;
};
const makeFiber = ({
@@ -32,6 +35,9 @@ const makeFiber = ({
memoizedProps: props,
sibling: null,
type,
+ tag: null,
+ stateNode: null,
+ memoizedState: null,
};
};