An open source design system that's fully customizable and agent ready
TypeScript
perf(Text): take a new text's first truncation measurement from the shared observer (#10668)
Humberto Virtudes8f8b3db656d2
diff --git a/.changeset/text-truncation-first-measure.md b/.changeset/text-truncation-first-measure.mdnew file mode 100644index 0000000000..41d004337a--- /dev/null+++ b/.changeset/text-truncation-first-measure.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] Truncating Text and Heading take a newly mounted element's first measurement from the shared resize observer's first notification, after the browser's own layout, instead of forcing a layout pass after each commit. Pages and windowed tables that mount many truncating texts commit faster; the tooltip behaves as before.++@humbertovirtudesdiff --git a/packages/core/src/Text/useTruncation.test.tsx b/packages/core/src/Text/useTruncation.test.tsxindex 8d1415f60e..87592d0a65 100644--- a/packages/core/src/Text/useTruncation.test.tsx+++ b/packages/core/src/Text/useTruncation.test.tsx@@ -43,13 +43,18 @@ describe('useTruncation', () => {vi.unstubAllGlobals();});- // Measuring inside React's commit forces a style and layout pass per text- // on a page that mounts many; after the commit, every text reads together.- it('measures after the commit, not inside it', async () => {+ // Measuring inside React's commit, or in a microtask after it, forces a+ // layout pass on a page that mounts many texts. A newly observed element+ // waits for the observer's first notification, sent after layout.+ it("takes a new text's first measurement from the observer's first notification", async () => {const observed: Element[] = [];+ let notify: ResizeObserverCallback | null = null;vi.stubGlobal('ResizeObserver',class {+ constructor(callback: ResizeObserverCallback) {+ notify = callback;+ }observe(target: Element) {observed.push(target);}@@ -60,12 +65,17 @@ describe('useTruncation', () => {const {unmount} = render(<Probe text="a status line" />);- // Observed, but not measured during the commit.+ // Observed, but measured neither in the commit nor in a microtask.expect(observed).toHaveLength(1);- expect(screen.getByTestId('full-text')).toHaveTextContent('');-await act(async () => {});+ expect(screen.getByTestId('full-text')).toHaveTextContent('');+ act(() => {+ notify?.(+ [{target: observed[0]} as ResizeObserverEntry],+ {} as ResizeObserver,+ );+ });expect(screen.getByTestId('full-text')).toHaveTextContent('a status line',);@@ -94,11 +104,24 @@ describe('useTruncation', () => {configurable: true,get: () => 100,});+ const {observeResize} = await import('../utils/sharedResizeObserver');function Unclamping({maxLines}: {maxLines: number}) {const truncation = useTruncation({maxLines});+ const {ref} = truncation;+ // Another subscriber watches the span first, so the hook's first+ // measurement takes the microtask path, which the guard decides.+ const attach = useCallback(+ (element: HTMLElement | null) => {+ if (element) {+ observeResize(element, () => {});+ }+ ref(element);+ },+ [ref],+ );return (<>- <span ref={truncation.ref}>overflowing text</span>+ <span ref={attach}>overflowing text</span><output data-testid="state">{String(truncation.isTruncated)}|{truncation.fullText}</output>diff --git a/packages/core/src/Text/useTruncation.ts b/packages/core/src/Text/useTruncation.tsindex 03109ac7c3..f58236230d 100644--- a/packages/core/src/Text/useTruncation.ts+++ b/packages/core/src/Text/useTruncation.ts@@ -13,7 +13,7 @@*/import {useCallback, useRef, useState, type RefCallback} from 'react';-import {observeResize} from '../utils/sharedResizeObserver';+import {isResizeObserved, observeResize} from '../utils/sharedResizeObserver';import {observeContent} from '../utils/sharedMutationObserver';export interface UseTruncationOptions {@@ -123,17 +123,17 @@ export function useTruncation(elementRef.current = element;if (element && maxLines > 0) {- // Observe via shared singleton (if available). The first measurement- // runs after the commit, in a microtask, instead of in the call- // observeResize makes on registration: that call runs inside React's- // commit, after other components' DOM writes, and forced a style and- // layout pass per text on a page that mounts many. Every text- // registered in one commit then reads layout once, together, and a- // text whose element another subscriber already observes is measured- // too. The truncated state only decides whether to compose the- // tooltip, so nothing paints differently.+ // Observe via the shared singleton, if available. The call that+ // observeResize makes on registration runs inside React's commit, so+ // it measures nothing. The observer's first notification measures a+ // new element. The browser sends it after its own layout, so mounting+ // text forces no layout pass. An element another subscriber already+ // observes gets no new first notification, so a microtask after the+ // commit measures it. The truncated state only decides whether to+ // compose the tooltip, so nothing paints differently.if (typeof ResizeObserver !== 'undefined') {let registered = false;+ const wasObserved = isResizeObserved(element);const unobserve = observeResize(element, () => {if (registered) {checkTruncation(element);@@ -143,11 +143,13 @@ export function useTruncation(unobserveRef.current = unobserve;// Skipped when this registration has ended by then (measuring// turned off, or the element replaced, in the same task).- queueMicrotask(() => {- if (unobserveRef.current === unobserve) {- checkTruncation(element);- }- });+ if (wasObserved) {+ queueMicrotask(() => {+ if (unobserveRef.current === unobserve) {+ checkTruncation(element);+ }+ });+ }} else {checkTruncation(element);}diff --git a/packages/core/src/utils/sharedResizeObserver.ts b/packages/core/src/utils/sharedResizeObserver.tsindex 349b022337..f3dcf279dc 100644--- a/packages/core/src/utils/sharedResizeObserver.ts+++ b/packages/core/src/utils/sharedResizeObserver.ts@@ -5,7 +5,8 @@/*** @file sharedResizeObserver.ts* @input ResizeObserver API- * @output Exports observeResize / unobserveResize for shared observation+ * @output Exports observeResize / unobserveResize for shared observation, and+ * the internal isResizeObserved* @position Utility; consumed by useTruncation, useOverflow, and any component* that needs resize observation without creating per-instance observers*@@ -52,6 +53,11 @@ function getObserver(): ResizeObserver | null {return observer;}+/** Whether the shared observer already watches `element`. Internal. */+export function isResizeObserved(element: Element): boolean {+ return callbacks.has(element);+}+/*** Observe an element's size via a shared ResizeObserver singleton.*