Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/text-truncation-first-measure.md
Original file line number Diff line number Diff line change
@@ -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.

@humbertovirtudes
37 changes: 30 additions & 7 deletions packages/core/src/Text/useTruncation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -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',
);
Expand Down Expand Up @@ -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>
Expand Down
32 changes: 17 additions & 15 deletions packages/core/src/Text/useTruncation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: "Observe via the shared singleton, if available." restates the typeof ResizeObserver branch and the observeResize call below it. Dropping it lets the comment start with its reason:

// 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. ...

// 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);
Expand All @@ -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) {
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
queueMicrotask(() => {
if (unobserveRef.current === unobserve) {
checkTruncation(element);
}
});
}
} else {
checkTruncation(element);
}
Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/utils/sharedResizeObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: this header is now 17 lines, past the "about 12 lines" the source-comment convention sets for @input, @output, @position and SYNC:. Most of the excess is the older four-line rationale paragraph; moving it onto the callbacks declaration brings the header to about 13 lines.

* @position Utility; consumed by useTruncation, useOverflow, and any component
* that needs resize observation without creating per-instance observers
*
Expand Down Expand Up @@ -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.
*
Expand Down
Loading