An open source design system that's fully customizable and agent ready
TypeScript
perf(Layer): the observer that follows a Tooltip's trigger re-arms from its own report, with no layout read (#10235)
Cindy Zhang0d7a25130443
diff --git a/.changeset/layer-move-observer-entry-box.md b/.changeset/layer-move-observer-entry-box.mdnew file mode 100644index 0000000000..2865d81ed9--- /dev/null+++ b/.changeset/layer-move-observer-entry-box.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] While a Tooltip is open, the observer that follows its trigger through a scroll no longer reads layout to re-arm. It used to read the trigger's box once or twice and the viewport's size on each frame of a scroll. It now takes them from its own report. The Tooltip still checks its placement once per move, on the same frames as before.++@cixzhangdiff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex 203e4ebdd7..726d919bb2 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -2694,6 +2694,38 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {const TRIGGER = rect(300, 400, 30, 100);+ /**+ * An intersection report as an engine makes it: the target's box, and the+ * root's box, which is the viewport shrunk by the observer's root margin.+ */+ function report(+ options: IntersectionObserverInit | undefined,+ box: DOMRect,+ intersectionRatio: number,+ isIntersecting = intersectionRatio > 0,+ viewport = {+ width: document.documentElement.clientWidth,+ height: document.documentElement.clientHeight,+ },+ ) {+ const [top = 0, right = 0, bottom = 0, left = 0] = (+ options?.rootMargin ?? '0px 0px 0px 0px'+ )+ .split(' ')+ .map(value => -parseFloat(value));+ return {+ intersectionRatio,+ isIntersecting,+ boundingClientRect: box,+ rootBounds: rect(+ top,+ left,+ viewport.height - bottom - top,+ viewport.width - right - left,+ ),+ } as unknown as IntersectionObserverEntry;+ }+/** Let the next animation frame run, as the browser does before it paints. */async function nextFrame() {await act(@@ -2967,7 +2999,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {it('re-reads its geometry when its trigger moves in layout without resizing', async () => {const observers: {- callback: (entries: {intersectionRatio: number}[]) => void;+ callback: (entries: IntersectionObserverEntry[]) => void;options: IntersectionObserverInit;disconnected: boolean;}[] = [];@@ -2976,7 +3008,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {class {record: (typeof observers)[number];constructor(- callback: (entries: {intersectionRatio: number}[]) => void,+ callback: (entries: IntersectionObserverEntry[]) => void,options: IntersectionObserverInit,) {this.record = {callback, options, disconnected: false};@@ -3003,14 +3035,14 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {);// Its initial report: fully inside its own rect.- act(() => move?.callback([{intersectionRatio: 1}]));+ act(() => move?.callback([report(move.options, TRIGGER, 1)]));expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');// The trigger moves; the standard list now settles over it.spy.mockRestore();placeBoxes(TRIGGER, rect(16, 350, 688, 300));const before = observers.length;- act(() => move?.callback([{intersectionRatio: 0.4}]));+ act(() => move?.callback([report(move.options, TRIGGER, 0.4)]));// Re-armed on the new rect at once; read in the next frame.expect(move?.disconnected).toBe(true);expect(observers.length).toBe(before + 1);@@ -3019,6 +3051,74 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {vi.unstubAllGlobals();});+ it('follows a move from its report alone: no layout read, armed on the reported box', async () => {+ type Record = {+ callback: (entries: IntersectionObserverEntry[]) => void;+ options: IntersectionObserverInit;+ };+ const observers: Record[] = [];+ vi.stubGlobal(+ 'IntersectionObserver',+ class {+ constructor(+ callback: (entries: IntersectionObserverEntry[]) => void,+ options: IntersectionObserverInit,+ ) {+ observers.push({callback, options});+ }+ observe() {}+ disconnect() {}+ unobserve() {}+ },+ );+ const moves = () =>+ observers.filter(+ o => o.options?.root === document && o.options.rootMargin != null,+ );+ const latest = () => moves()[moves().length - 1];+ vi.spyOn(document.documentElement, 'clientWidth', 'get').mockReturnValue(+ 1280,+ );+ viewport720();+ const user = userEvent.setup();+ const spy = placeBoxes(TRIGGER, rect(200, 350, 100, 200));+ const {getByText} = render(<ClearHarness />);+ await user.click(getByText('Trigger'));+ expect(latest().options.rootMargin).toBe('-300px -780px -390px -400px');++ // Every frame of a scroll reports a move. Following it reads no layout:+ // the box and the viewport come from the report.+ const width = vi.spyOn(document.documentElement, 'clientWidth', 'get');+ const height = vi.spyOn(document.documentElement, 'clientHeight', 'get');+ const triggerReads = () =>+ spy.mock.contexts.filter(+ el => !(el as HTMLElement).hasAttribute('popover'),+ ).length;+ const readsBefore = triggerReads();+ width.mockClear();+ height.mockClear();+ const scrolled = rect(247.5, 400, 30, 100);+ const screen = {width: 1280, height: 720};+ act(() =>+ latest().callback([+ report(latest().options, scrolled, 0.4, true, screen),+ ]),+ );+ // Armed on the reported box, as a fresh read of it would arm it.+ expect(latest().options.rootMargin).toBe('-247px -780px -442px -400px');+ // A move under a pixel leaves the ratio at 1; the reported box shows it.+ const nudged = rect(247.25, 400, 30, 100);+ act(() =>+ latest().callback([report(latest().options, nudged, 1, true, screen)]),+ );+ expect(moves().length).toBe(3);+ expect(latest().options.rootMargin).toBe('-247px -780px -442px -400px');+ expect(triggerReads()).toBe(readsBefore);+ expect(width).not.toHaveBeenCalled();+ expect(height).not.toHaveBeenCalled();+ vi.unstubAllGlobals();+ });+it('reads a move its observer reports after paint in the next frame, before that frame paints, never in the reporting task', async () => {// Placing a layer afresh in the task right after the frame that scrolled// its anchor lets Chromium lay it out for one more frame against the@@ -3026,14 +3126,14 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {// clear from the second painted frame). The read waits for the next// frame, before it paints, and several reports in one frame share it.const observers: {- callback: (entries: {intersectionRatio: number}[]) => void;+ callback: (entries: IntersectionObserverEntry[]) => void;options: IntersectionObserverInit;}[] = [];vi.stubGlobal('IntersectionObserver',class {constructor(- callback: (entries: {intersectionRatio: number}[]) => void,+ callback: (entries: IntersectionObserverEntry[]) => void,options: IntersectionObserverInit,) {observers.push({callback, options});@@ -3050,7 +3150,10 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {const {container, getByText} = render(<ClearHarness />);await user.click(getByText('Trigger'));const layerEl = container.querySelector('[popover]') as HTMLElement;- act(() => latestMove()?.callback([{intersectionRatio: 1}]));+ act(() => {+ const move = latestMove();+ move?.callback([report(move.options, TRIGGER, 1)]);+ });await nextFrame();expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');@@ -3069,8 +3172,10 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {},);act(() => {- latestMove()?.callback([{intersectionRatio: 0.4}]);- latestMove()?.callback([{intersectionRatio: 0.6}]);+ const first = latestMove();+ first?.callback([report(first.options, TRIGGER, 0.4)]);+ const second = latestMove();+ second?.callback([report(second.options, TRIGGER, 0.6)]);});expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');expect(reads).not.toHaveBeenCalled();@@ -3083,7 +3188,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {});it('follows a move that spans several frames and never goes idle while a scrolled container clips its trigger', async () => {- type Entry = {intersectionRatio: number; isIntersecting?: boolean};+ type Entry = IntersectionObserverEntry;const observers: {callback: (entries: Entry[]) => void;options: IntersectionObserverInit;@@ -3129,7 +3234,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {spy.mockRestore();spy = placeBoxes(TRIGGER, rect(16, 350, 688, 300));let armed = moves().length;- act(() => latest().callback([{intersectionRatio: 0.7}]));+ act(() => latest().callback([report(latest().options, TRIGGER, 0.7)]));expect(moves().length).toBe(armed + 1);expect(latest().options.threshold).toBe(0.7);await nextFrame();@@ -3138,9 +3243,10 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {// A first report of 0 for a trigger that moved since the observer read// its rectangle re-arms at once on the new rectangle.spy.mockRestore();- spy = placeBoxes(rect(260, 400, 30, 100), rect(16, 350, 688, 300));+ const moved = rect(260, 400, 30, 100);+ spy = placeBoxes(moved, rect(16, 350, 688, 300));armed = moves().length;- act(() => latest().callback([{intersectionRatio: 0}]));+ act(() => latest().callback([report(latest().options, moved, 0)]));expect(moves().length).toBe(armed + 1);expect(latest().options.threshold).toBe(1);@@ -3149,18 +3255,18 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {// viewport waits for it to come back into view, however long that takes.const timers = vi.spyOn(globalThis, 'setTimeout');armed = moves().length;- act(() => latest().callback([{intersectionRatio: 0}]));+ act(() => latest().callback([report(latest().options, moved, 0)]));expect(moves().length).toBe(armed);expect(timers).not.toHaveBeenCalled();const visibility = visibilities()[visibilities().length - 1];expect(visibility?.options.threshold).toBe(0);act(() =>- visibility?.callback([{intersectionRatio: 0, isIntersecting: false}]),+ visibility?.callback([report(visibility.options, moved, 0, false)]),);expect(moves().length).toBe(armed);// Back in view: it re-reads and re-arms, and the visibility observer goes.act(() =>- visibility?.callback([{intersectionRatio: 0.2, isIntersecting: true}]),+ visibility?.callback([report(visibility.options, moved, 0.2, true)]),);expect(moves().length).toBe(armed + 1);expect(visibility?.disconnected).toBe(true);diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex f91c405900..76e8cabf34 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -579,6 +579,22 @@ function keepAnchorClear(layer: HTMLElement, anchor: HTMLElement | null): void {);}+/** An element's box in client px, as a rect read or an observer reports it. */+interface ClientBox {+ readonly top: number;+ readonly left: number;+ readonly right: number;+ readonly bottom: number;+ readonly width: number;+ readonly height: number;+}++/** The viewport's size in client px, without its scrollbars. */+interface ViewportSize {+ readonly width: number;+ readonly height: number;+}+/*** Call `onMove` when an element moves on screen without changing size: in* layout (a sibling above it grows, a margin changes) or because something@@ -589,18 +605,21 @@ function keepAnchorClear(layer: HTMLElement, anchor: HTMLElement | null): void {* ratio and fires the callback, which calls `onMove` and re-arms on the new* rectangle. Intersection callbacks run after the frame that moved the* element has painted, so the caller corrects that move in the next frame.+ * The element's box and the viewport are read once, when observing starts.+ * Each re-arm takes them from the report itself (its target box and its root+ * box), so following a move reads no layout.** A fresh observer's first report can already differ from its threshold: the* element is partly outside the viewport, or it kept moving between the- * rectangle read and the observer's first check, as it does every frame of a- * smooth scroll. Any such report calls `onMove` and re-arms, at the reported- * ratio, or at once on the element's new rectangle when the report is 0 and- * the element moved, so a move that spans many frames is followed frame by- * frame. A report of 0 for an element that has not moved means a scrolled- * container clips it wholly; re-arming then would report 0 again every frame.- * Instead a second IntersectionObserver, rooted at the viewport with a- * threshold of 0 (it counts every ancestor's overflow clip), waits for the- * element to come back into view, then calls `onMove` and re-arms. Nothing+ * rectangle the observer was armed on and its first check, as it does every+ * frame of a smooth scroll. Any such report calls `onMove` and re-arms, at the+ * reported ratio, or at once on the element's new rectangle when the report+ * is 0 and the element moved, so a move that spans many frames is followed+ * frame by frame. A report of 0 for an element that has not moved means a+ * scrolled container clips it wholly; re-arming then would report 0 again+ * every frame. Instead a second IntersectionObserver, rooted at the viewport+ * with a threshold of 0 (it counts every ancestor's overflow clip), waits for+ * the element to come back into view, then calls `onMove` and re-arms. Nothing* runs on a timer. Returns the function that stops observing.*/function observeMove(element: HTMLElement, onMove: () => void): () => void {@@ -608,6 +627,7 @@ function observeMove(element: HTMLElement, onMove: () => void): () => void {if (typeof IntersectionObserver === 'undefined') {return () => {};}+ const root = doc.documentElement;let observer: IntersectionObserver | null = null;let visibility: IntersectionObserver | null = null;const stop = () => {@@ -616,30 +636,37 @@ function observeMove(element: HTMLElement, onMove: () => void): () => void {visibility?.disconnect();visibility = null;};- const moved = (threshold: number) => {+ const moved = (threshold: number, box: ClientBox, viewport: ViewportSize) => {onMove();- arm(threshold);+ arm(threshold, box, viewport);};- const arm = (threshold: number) => {+ const arm = (threshold: number, rect: ClientBox, viewport: ViewportSize) => {stop();- const root = doc.documentElement;- const rect = element.getBoundingClientRect();if (rect.width === 0 || rect.height === 0) {return;}const top = Math.floor(rect.top);const left = Math.floor(rect.left);- const right = Math.floor(root.clientWidth - rect.right);- const bottom = Math.floor(root.clientHeight - rect.bottom);- const hasMoved = () => {- const now = element.getBoundingClientRect();- return (- now.top !== rect.top ||- now.left !== rect.left ||- now.width !== rect.width ||- now.height !== rect.height- );- };+ const right = Math.floor(viewport.width - rect.right);+ const bottom = Math.floor(viewport.height - rect.bottom);+ const hasMoved = (now: ClientBox) =>+ now.top !== rect.top ||+ now.left !== rect.left ||+ now.width !== rect.width ||+ now.height !== rect.height;+ // A report's root box is the viewport, here shrunk by the root margin.+ // If the report has no root box, read the viewport's size.+ const viewportOf = (+ rootBounds: DOMRectReadOnly | null,+ marginRight: number,+ marginBottom: number,+ ): ViewportSize =>+ rootBounds == null+ ? {width: root.clientWidth, height: root.clientHeight}+ : {+ width: rootBounds.right + marginRight,+ height: rootBounds.bottom + marginBottom,+ };// Clipped by a scrolled container: wait, without a timer, for the// element to come back into view. A first report that already finds it// in view only counts if it has moved, so a clip the move observer and@@ -648,11 +675,18 @@ function observeMove(element: HTMLElement, onMove: () => void): () => void {let isFirstVisible = true;visibility = new IntersectionObserver(entries => {- const visible = entries[entries.length - 1]?.isIntersecting ?? false;+ const entry = entries[entries.length - 1];const firstVisible = isFirstVisible;isFirstVisible = false;- if (visible && (!firstVisible || hasMoved())) {- moved(1);+ if (+ entry?.isIntersecting &&+ (!firstVisible || hasMoved(entry.boundingClientRect))+ ) {+ moved(+ 1,+ entry.boundingClientRect,+ viewportOf(entry.rootBounds, 0, 0),+ );}},{root: doc, threshold: 0},@@ -662,23 +696,34 @@ function observeMove(element: HTMLElement, onMove: () => void): () => void {let isFirst = true;observer = new IntersectionObserver(entries => {- const ratio = entries[entries.length - 1]?.intersectionRatio ?? 0;+ const entry = entries[entries.length - 1];+ if (entry == null) {+ return;+ }+ const ratio = entry.intersectionRatio;+ const box = entry.boundingClientRect;const first = isFirst;isFirst = false;+ const followMove = (nextThreshold: number) =>+ moved(+ nextThreshold,+ box,+ viewportOf(entry.rootBounds, right, bottom),+ );if (ratio === threshold) {// Still over its own rectangle, but a move smaller than the// rounding of the root margin can leave the ratio at 1.- if (ratio === 1 && hasMoved()) {- moved(1);+ if (ratio === 1 && hasMoved(box)) {+ followMove(1);}return;}if (!first || ratio > 0) {- moved(first ? ratio : 1);+ followMove(first ? ratio : 1);return;}- if (hasMoved()) {- moved(1);+ if (hasMoved(box)) {+ followMove(1);return;}if (visibility === null) {@@ -693,7 +738,10 @@ function observeMove(element: HTMLElement, onMove: () => void): () => void {);observer.observe(element);};- arm(1);+ arm(1, element.getBoundingClientRect(), {+ width: root.clientWidth,+ height: root.clientHeight,+ });return stop;}