An open source design system that's fully customizable and agent ready
TypeScript
perf(Text): truncation measures once after the commit, in a microtask, not inside it (#9013)
Cindy Zhang13669e9edd32
diff --git a/.changeset/truncation-measures-after-layout.md b/.changeset/truncation-measures-after-layout.mdnew file mode 100644index 0000000000..85a9ea8676--- /dev/null+++ b/.changeset/truncation-measures-after-layout.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] Pages that mount many truncated `Text` and `Heading` elements at once mount faster. Each one used to measure whether its text overflows while React was still committing the page, so every measurement forced its own style and layout pass; they now measure right after the commit, all of them together, so the page reads layout once. The ellipsis, the line clamp and the full-text tooltip are unchanged.++@cixzhangdiff --git a/packages/core/src/Text/useTruncation.test.tsx b/packages/core/src/Text/useTruncation.test.tsxindex b617107622..8d1415f60e 100644--- a/packages/core/src/Text/useTruncation.test.tsx+++ b/packages/core/src/Text/useTruncation.test.tsx@@ -5,8 +5,9 @@* Tests for useTruncation*/-import {render, screen, waitFor} from '@testing-library/react';+import {act, render, screen, waitFor} from '@testing-library/react';import {afterEach, describe, it, expect, vi} from 'vitest';+import {useCallback} from 'react';import {useTruncation} from './useTruncation';function Probe({text}: {text: string}) {@@ -37,6 +38,132 @@ describe('useTruncation', () => {);});+ describe('first measurement', () => {+ afterEach(() => {+ 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 () => {+ const observed: Element[] = [];+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe(target: Element) {+ observed.push(target);+ }+ unobserve() {}+ disconnect() {}+ },+ );++ const {unmount} = render(<Probe text="a status line" />);++ // Observed, but not measured during the commit.+ expect(observed).toHaveLength(1);+ expect(screen.getByTestId('full-text')).toHaveTextContent('');++ await act(async () => {});++ expect(screen.getByTestId('full-text')).toHaveTextContent(+ 'a status line',+ );+ unmount();+ });++ // FR4/PR1: with measuring turned off before the first measurement runs,+ // nothing is measured and the hook reports no truncation.+ it('skips the first measurement when measuring turns off in the same task', async () => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ const proto = window.HTMLElement.prototype;+ const scrollWidth = Object.getOwnPropertyDescriptor(proto, 'scrollWidth');+ const offsetWidth = Object.getOwnPropertyDescriptor(proto, 'offsetWidth');+ Object.defineProperty(proto, 'scrollWidth', {+ configurable: true,+ get: () => 400,+ });+ Object.defineProperty(proto, 'offsetWidth', {+ configurable: true,+ get: () => 100,+ });+ function Unclamping({maxLines}: {maxLines: number}) {+ const truncation = useTruncation({maxLines});+ return (+ <>+ <span ref={truncation.ref}>overflowing text</span>+ <output data-testid="state">+ {String(truncation.isTruncated)}|{truncation.fullText}+ </output>+ </>+ );+ }+ try {+ // Measuring turns off in the same task, before the first measurement.+ const {rerender, unmount} = render(<Unclamping maxLines={1} />);+ rerender(<Unclamping maxLines={0} />);+ await act(async () => {});+ expect(screen.getByTestId('state')).toHaveTextContent(/^false\|$/);+ unmount();+ } finally {+ if (scrollWidth) {+ Object.defineProperty(proto, 'scrollWidth', scrollWidth);+ }+ if (offsetWidth) {+ Object.defineProperty(proto, 'offsetWidth', offsetWidth);+ }+ }+ });++ // The browser sends no second first-notification for an element the+ // shared observer already watches, so the first measurement cannot wait+ // for one.+ it('measures an element another subscriber already observes', async () => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ const {observeResize} = await import('../utils/sharedResizeObserver');+ const watched = document.createElement('span');+ function Shared({text}: {text: string}) {+ const truncation = useTruncation({maxLines: 1});+ const {ref} = truncation;+ const attach = useCallback(+ (element: HTMLElement | null) => {+ if (element && element !== watched) {+ observeResize(element, () => {});+ }+ ref(element);+ },+ [ref],+ );+ return (+ <>+ <span ref={attach}>{text}</span>+ <output data-testid="full-text">{truncation.fullText}</output>+ </>+ );+ }+ const {unmount} = render(<Shared text="already watched" />);+ await act(async () => {});+ expect(screen.getByTestId('full-text')).toHaveTextContent(+ 'already watched',+ );+ unmount();+ });+ });+describe('content observation', () => {afterEach(() => {vi.unstubAllGlobals();diff --git a/packages/core/src/Text/useTruncation.ts b/packages/core/src/Text/useTruncation.tsindex 7c24e53a79..03109ac7c3 100644--- a/packages/core/src/Text/useTruncation.ts+++ b/packages/core/src/Text/useTruncation.ts@@ -123,12 +123,30 @@ export function useTruncation(elementRef.current = element;if (element && maxLines > 0) {- // Observe via shared singleton (if available).- // observeResize fires the callback once on registration,- // so no separate initial check is needed.+ // 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.if (typeof ResizeObserver !== 'undefined') {- unobserveRef.current = observeResize(element, () => {- checkTruncation(element);+ let registered = false;+ const unobserve = observeResize(element, () => {+ if (registered) {+ checkTruncation(element);+ }+ });+ registered = true;+ 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);+ }});} else {checkTruncation(element);