An open source design system that's fully customizable and agent ready
TypeScript
fix(OverflowList): a resize shows the new visible set in the same frame (height-changing folds stay one frame late) (#9926)
Cindy Zhangb1f604c9f16d
diff --git a/.changeset/overflow-resize-before-paint.md b/.changeset/overflow-resize-before-paint.mdnew file mode 100644index 0000000000..45656fe66a--- /dev/null+++ b/.changeset/overflow-resize-before-paint.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] When an `OverflowList` (or a `useOverflow` host) resizes, it now shows the new visible set in the same frame. Before, the resize rendered after the frame painted, so one frame showed the old set at the new width: items spilled past the edge as the box shrank, or stayed collapsed as it grew. A resize now measures again in a microtask before paint, every list that one resize reports renders together, and a resize that changes nothing renders nothing. A resize whose new set can change the list's own height (a taller indicator appearing, a multi-row list filling a different number of rows or measuring a new row height, or, with `behavior="observeParent"`, the indicator appearing or disappearing, which changes how the list fills its parent, or a list sized from its items, such as a flex item beside a menu that can shrink) still renders one frame later, as before, because rendering it before paint would make the browser report a ResizeObserver loop error. A resize that folds the list before paint can make Chromium report "ResizeObserver loop completed with undelivered notifications" once in that frame when another observer watches an outer element (Storybook's preview observes `<body>`); no notification is lost, and an error monitor should ignore this message.++Tests: a resize the observer reports now applies in a microtask, still before paint. A test that calls a mocked `ResizeObserver` callback and asserts synchronously right after it should first await the update by wrapping the call in `await act(async () => { … })`.++@cixzhangdiff --git a/docs/specs/components/OverflowList/OverflowList.spec.md b/docs/specs/components/OverflowList/OverflowList.spec.mdindex fbd3abcaeb..2894f5fb3f 100644--- a/docs/specs/components/OverflowList/OverflowList.spec.md+++ b/docs/specs/components/OverflowList/OverflowList.spec.md@@ -33,15 +33,15 @@ system_specs: []## Contract at a glance-| Area | Contract |-| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | `children`, `overflowRenderer`, `onOverflowChange`, `gap`, `minVisibleItems`, `maxVisibleItems`, `maxRows`, `collapseFrom`, `behavior`, root `BaseProps`, `ref`. |-| Behavior | Shows as many caller items as fit the measured width, row count, and count limits, and hands the rest to a caller-rendered indicator and callback. |-| End-user impact | People see a single tidy row (or a few rows) of items, with a caller's "more" control standing in for the ones that do not fit. |-| Builder impact | None; the record describes shipped behavior. |-| Compatibility/readiness | Released behavior recorded as current; no API, default, or output changes. |-| Review checks | Reject a measurement copy that is exposed or focusable, an indicator on the wrong edge, a callback that fires before measurement or repeats an unchanged set. |-| Governing rules | `architecture:component-theming-surface`; `architecture:public-component-api` INV5–INV8. |+| Area | Contract |+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `children`, `overflowRenderer`, `onOverflowChange`, `gap`, `minVisibleItems`, `maxVisibleItems`, `maxRows`, `collapseFrom`, `behavior`, root `BaseProps`, `ref`. |+| Behavior | Shows as many caller items as fit the measured width, row count, and count limits, and hands the rest to a caller-rendered indicator and callback. |+| End-user impact | People see a single tidy row (or a few rows) of items, with a caller's "more" control standing in for the ones that do not fit. |+| Builder impact | A resize that folds the list before paint can make Chromium report "ResizeObserver loop completed with undelivered notifications" once in that frame when another observer watches an outer element (Storybook's preview observes `<body>`); no notification is lost, and an error monitor should ignore this message. (PR1) A test that fires a mocked ResizeObserver callback and asserts synchronously after it awaits the update first, for example with `await act(async () => { … })` (PR1). |+| Compatibility/readiness | Released behavior recorded as current; no API, default, or output changes. |+| Review checks | Reject a measurement copy that is exposed or focusable, an indicator on the wrong edge, a callback that fires before measurement or repeats an unchanged set. |+| Governing rules | `architecture:component-theming-surface`; `architecture:public-component-api` INV5–INV8. |This table is a review projection; the body below is authoritative.@@ -61,7 +61,8 @@ Consumer syntax and examples belong in `OverflowList.doc.mjs`.target, or styling output changes.- Controlled/uncontrolled behavior: not applicable; the visible count ismeasured.-- Migration decision: none+- Migration decision: test timing only: a test that fires a mocked+ ResizeObserver callback awaits the update before asserting; no API changes.Consumer migration instructions belong in consumer docs and release notes.@@ -130,6 +131,18 @@ Consumer migration instructions belong in consumer docs and release notes.- **PR1 — Measurement.** OverflowList observes the measured box's size, rendersevery item in the hidden copy and the visible ones again in the list, andreports collapsed sets after measurement, before the frame paints.+ Exception: a resize whose new collapsed set can change the list's own+ height (its tallest child, the indicator included, or the rows a multi-row+ list fills, or a multi-row list's measured row height), that shows or+ hides the indicator under `observeParent`, where the list's parent fill+ changes (FR4), or whose observed box is sized from the list's items (a list+ in a flex item sized from its content beside a sibling that can shrink)+ applies that set one frame+ later, because folding before paint there makes Chromium report a+ ResizeObserver loop error; the visible-count change in that case paints one+ frame late (Current state).+- Current state: a resize whose new collapsed set can change the list's own height (a multi-row list's measured row height included), shows or hides the indicator under `observeParent`, or changes a list whose observed box is sized from its items, paints the previous visible set for one frame, then the new one.+- Known effect: A resize that folds the list before paint can make Chromium report "ResizeObserver loop completed with undelivered notifications" once in that frame when another observer watches an outer element (Storybook's preview observes `<body>`); no notification is lost, and an error monitor should ignore this message.## Accessibility contract@@ -179,17 +192,18 @@ The hidden measurement copy is implementation structure, not consumer anatomy.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------- |-| FR1, AR1 | `OverflowList.test.tsx` measurement-container and rendering-contract tests | Hidden copy; indicator measured against all items; visible class | A measurement copy that is not `aria-hidden` and `inert`, an indicator measured against fewer items, or a target off the visible container fails. | `audit:OverflowList/theming` |-| FR2, ORD1 | `OverflowList.test.tsx` fit, overflow, `minVisibleItems`, and cap tests; `useOverflow.test.ts` (including `observeParent`); `computeOverflow.test.ts`; stable visual baselines `core-overflowlist--default` (neutral and probe themes) | All fit; end and start; floor; cap; floor over cap | Wrong visible items, too few under a floor, too many under a cap, or a cap beating the floor fails; a changed default row comes back changed for review. | `audit:OverflowList/behavior` |-| FR3 | `OverflowList.test.tsx` indicator-placement and no-renderer tests | End; start; no renderer | An indicator on the wrong side, or one rendered without a renderer, fails. | `audit:OverflowList/anatomy` |-| FR4 | `OverflowList.test.tsx` gap and `maxRows` tests | Gap change; `maxRows` 2 and 1 | No class change for a new gap or for wrapping, or wrapping at `maxRows={1}`, fails. Gap: the row height limit and the `observeParent` fill have no check. | `audit:OverflowList/layout` |-| FR5, ORD2 | `OverflowList.test.tsx` `onOverflowChange` suite | Silent fit; mount; original indices; back to empty; unchanged; reorder; content change; count change; callback swap; state update; unmount; start | A callback that fires without overflow, repeats an unchanged set, misses a change, reports unmeasured content, loops on state, or fires after unmount fails. | `audit:OverflowList/behavior` |-| FR6 | `OverflowList.test.tsx` ref and passthrough tests | Ref; DOM props | A ref on another element or a dropped DOM prop fails. Gap: no test covers `className`, `style`, or the `xstyle` merge order. | `audit:OverflowList/api` |-| AR2, PR1 | Source review | Collapsed items | Gap: no automated check covers keyboard reach to collapsed items or the observer lifecycle. | `audit:OverflowList/a11y` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, or stale mappings fail repository validation. | `audit:OverflowList/theming` |-| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on `OverflowList / Default` | The first two visible items; LTR and RTL | A first item that is not at the inline start of the second fails D2. | `audit:OverflowList/i18n-rtl` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |+| FR1, AR1 | `OverflowList.test.tsx` measurement-container and rendering-contract tests | Hidden copy; indicator measured against all items; visible class | A measurement copy that is not `aria-hidden` and `inert`, an indicator measured against fewer items, or a target off the visible container fails. | `audit:OverflowList/theming` |+| FR2, ORD1 | `OverflowList.test.tsx` fit, overflow, `minVisibleItems`, and cap tests; `useOverflow.test.ts` (including `observeParent`); `computeOverflow.test.ts`; stable visual baselines `core-overflowlist--default` (neutral and probe themes) | All fit; end and start; floor; cap; floor over cap | Wrong visible items, too few under a floor, too many under a cap, or a cap beating the floor fails; a changed default row comes back changed for review. | `audit:OverflowList/behavior` |+| FR3 | `OverflowList.test.tsx` indicator-placement and no-renderer tests | End; start; no renderer | An indicator on the wrong side, or one rendered without a renderer, fails. | `audit:OverflowList/anatomy` |+| FR4 | `OverflowList.test.tsx` gap and `maxRows` tests | Gap change; `maxRows` 2 and 1 | No class change for a new gap or for wrapping, or wrapping at `maxRows={1}`, fails. Gap: the row height limit and the `observeParent` fill have no check. | `audit:OverflowList/layout` |+| FR5, ORD2 | `OverflowList.test.tsx` `onOverflowChange` suite | Silent fit; mount; original indices; back to empty; unchanged; reorder; content change; count change; callback swap; state update; unmount; start | A callback that fires without overflow, repeats an unchanged set, misses a change, reports unmeasured content, loops on state, or fires after unmount fails. | `audit:OverflowList/behavior` |+| FR6 | `OverflowList.test.tsx` ref and passthrough tests | Ref; DOM props | A ref on another element or a dropped DOM prop fails. Gap: no test covers `className`, `style`, or the `xstyle` merge order. | `audit:OverflowList/api` |+| AR2 | Source review | Collapsed items | Gap: no automated check covers keyboard reach to collapsed items. | `audit:OverflowList/a11y` |+| PR1 | `useOverflow.test.ts` "when the observer reports a resize" suite (a scripted observer; the new count is checked before the next task runs) | Single row shrinks; single row grows; two lists in one delivery; a resize that changes nothing; a single-row fold that shows a taller indicator; a multi-row fold that keeps its rows; a multi-row fold that changes its rows; a multi-row fold whose indicator wraps onto a new row; a multi-row fold whose shown indicator can be narrower than the measured one; a fold that hides a plain-text indicator taller than the items; an `observeParent` fold that shows or hides the indicator; an `observeParent` fold that keeps it; a multi-row list that measures a new row height; a fold in a list whose width follows its items and in one whose width does not | A height-keeping resize whose new count renders only after paint, a delivery that renders each list separately, a resize that changes nothing yet renders, or a fold that can change the list's own height or its `observeParent` fill and renders before paint, fails. Gap: no test covers the observer lifecycle (subscriptions released on unmount and ref change). | `audit:OverflowList/a11y` |+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, or stale mappings fail repository validation. | `audit:OverflowList/theming` |+| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on `OverflowList / Default` | The first two visible items; LTR and RTL | A first item that is not at the inline start of the second fails D2. | `audit:OverflowList/i18n-rtl` |## Decision logdiff --git a/packages/cli/api/template/use-overflow-hook-usage.test.tsx b/packages/cli/api/template/use-overflow-hook-usage.test.tsxindex 7ffee50f11..4b5ee76b15 100644--- a/packages/cli/api/template/use-overflow-hook-usage.test.tsx+++ b/packages/cli/api/template/use-overflow-hook-usage.test.tsx@@ -92,13 +92,14 @@ describe('useOverflow example', () => {]);});- it('moves the actions that do not fit into More, and back on resize', () => {+ it('moves the actions that do not fit into More, and back on resize', async () => {// Three 100px actions, three 4px gaps and the 100px More button fit 450px.const row = renderExample(450);expect(labels(row)).toEqual(['Bold', 'Italic', 'Underline', 'More']);rowWidth = 1000;- act(() => {+ // The hook measures a reported resize again in a microtask, before paint.+ await act(async () => {resize([{target: row} as unknown as ResizeObserverEntry],{} as ResizeObserver,diff --git a/packages/core/src/OverflowList/OverflowList.test.tsx b/packages/core/src/OverflowList/OverflowList.test.tsxindex 1c25aa6657..aa669c75f5 100644--- a/packages/core/src/OverflowList/OverflowList.test.tsx+++ b/packages/core/src/OverflowList/OverflowList.test.tsx@@ -105,9 +105,12 @@ const indicator =</span>);-/** Notify the shared observer that an element's size changed. */-function triggerResize(target: Element): void {- act(() => {+/**+ * Notify the shared observer that an element's size changed. The list+ * measures again in a microtask before paint, so this awaits it.+ */+async function triggerResize(target: Element): Promise<void> {+ await act(async () => {for (const observer of resizeObservers) {observer.trigger(target);}@@ -630,7 +633,7 @@ describe('OverflowList', () => {expect(indicesOf(onOverflowChange)).toEqual([1, 2]);});- it('reports an empty set again once the container fits everything', () => {+ it('reports an empty set again once the container fits everything', async () => {const onOverflowChange = vi.fn();const items = [<button type="button" data-w="40" key="a">@@ -663,7 +666,7 @@ describe('OverflowList', () => {{items}</OverflowList>,);- triggerResize(visibleContainer());+ await triggerResize(visibleContainer());expect(onOverflowChange).toHaveBeenCalledTimes(2);expect(indicesOf(onOverflowChange)).toEqual([]);});@@ -800,7 +803,7 @@ describe('OverflowList', () => {expect(indicesOf(onOverflowChange)).toEqual([2]);});- it('re-measures same-count content changes with stable keys', () => {+ it('re-measures same-count content changes with stable keys', async () => {const onOverflowChange = vi.fn();const renderItems = (items: {key: string; label: string; width: number}[],@@ -840,7 +843,7 @@ describe('OverflowList', () => {])}</OverflowList>,);- triggerResize(measureContainer());+ await triggerResize(measureContainer());expect(onOverflowChange).toHaveBeenCalledTimes(1);expect(indicesOf(onOverflowChange)).toEqual([2, 3]);@@ -892,7 +895,7 @@ describe('OverflowList', () => {expect(indicesOf(onOverflowChange)).toEqual([2, 3, 4]);});- it('uses a replacement callback only for the next set change', () => {+ it('uses a replacement callback only for the next set change', async () => {const first = vi.fn();const second = vi.fn();const items = [@@ -934,7 +937,7 @@ describe('OverflowList', () => {{items}</OverflowList>,);- triggerResize(visibleContainer());+ await triggerResize(visibleContainer());expect(first).toHaveBeenCalledTimes(1);expect(second).toHaveBeenCalledTimes(1);expect(indicesOf(second)).toEqual([]);@@ -972,7 +975,7 @@ describe('OverflowList', () => {expect(screen.getByTestId('hidden-count')).toHaveTextContent('1');});- it('does not report after unmount', () => {+ it('does not report after unmount', async () => {const onOverflowChange = vi.fn();const {unmount} = render(<OverflowList@@ -993,8 +996,8 @@ describe('OverflowList', () => {expect(onOverflowChange).toHaveBeenCalledTimes(1);unmount();- triggerResize(container);- triggerResize(measure);+ await triggerResize(container);+ await triggerResize(measure);expect(onOverflowChange).toHaveBeenCalledTimes(1);});diff --git a/packages/core/src/hooks/computeOverflow.ts b/packages/core/src/hooks/computeOverflow.tsindex 3f88af50da..b4b215ec6c 100644--- a/packages/core/src/hooks/computeOverflow.ts+++ b/packages/core/src/hooks/computeOverflow.ts@@ -162,7 +162,7 @@ function packRows(}/** Count how many rows a set of items occupies when wrapped at availableWidth. */-function countRows(+export function countRows(orderedWidths: number[],gap: number,availableWidth: number,diff --git a/packages/core/src/hooks/useOverflow.test.ts b/packages/core/src/hooks/useOverflow.test.tsindex 124091f425..069b6284fb 100644--- a/packages/core/src/hooks/useOverflow.test.ts+++ b/packages/core/src/hooks/useOverflow.test.ts@@ -15,6 +15,7 @@ function mockMeasure(itemWidths: number[],indicatorWidth?: number,itemHeight = 0,+ indicatorHeight = itemHeight,): HTMLElement {const children: {offsetWidth: number; offsetHeight: number}[] =itemWidths.map(w => ({@@ -22,16 +23,21 @@ function mockMeasure(offsetHeight: itemHeight,}));if (indicatorWidth != null) {- children.push({offsetWidth: indicatorWidth, offsetHeight: itemHeight});+ children.push({offsetWidth: indicatorWidth, offsetHeight: indicatorHeight});}return {children} as unknown as HTMLElement;}+// The callback of the most recently created observer. The shared observer+// outlives a test while any element stays observed, so a delivery goes to it.+let latestObserverCallback: ResizeObserverCallback | null = null;+// Stubs ResizeObserver — fires callback immediately on observe, like the real oneclass FakeResizeObserver {callback: ResizeObserverCallback;constructor(cb: ResizeObserverCallback) {this.callback = cb;+ latestObserverCallback = cb;}observe = vi.fn(() => {this.callback([], this);@@ -502,3 +508,397 @@ describe('useOverflow with behavior=observeParent', () => {expect(result.current.hasOverflow).toBe(true);});});++describe('useOverflow when the observer reports a resize (component:OverflowList PR1)', () => {+ // A box whose width a test changes, as a resize would.+ function resizableBox(width: number): {offsetWidth: number} & Element {+ return {offsetWidth: width} as unknown as {offsetWidth: number} & Element;+ }++ // Reports resizes the way the browser does: after layout, outside act(). A+ // microtask still runs before the frame paints; a render scheduled as a+ // task runs after it. So the test checks state once microtasks have run.+ async function deliverBeforePaint(...targets: Element[]): Promise<void> {+ const actGlobal = globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean};+ const wasActEnvironment = actGlobal.IS_REACT_ACT_ENVIRONMENT;+ actGlobal.IS_REACT_ACT_ENVIRONMENT = false;+ try {+ for (const target of targets) {+ latestObserverCallback?.(+ [{target} as unknown as ResizeObserverEntry],+ {} as ResizeObserver,+ );+ }+ await Promise.resolve();+ await Promise.resolve();+ } finally {+ actGlobal.IS_REACT_ACT_ENVIRONMENT = wasActEnvironment;+ }+ }++ it.each([+ ['shrinks', 200, 100, 3, 1],+ ['grows', 100, 200, 1, 3],+ ])(+ 'renders the new visible count before the frame paints when the box %s',+ async (_label, fromWidth, toWidth, before, after) => {+ const {result} = renderHook(() => useOverflow(3, {gap: 10}));+ const box = resizableBox(fromWidth);++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50], 30));+ result.current.containerRef(box as unknown as HTMLElement);+ });+ expect(result.current.visibleCount).toBe(before);++ box.offsetWidth = toWidth;+ await deliverBeforePaint(box);++ expect(result.current.visibleCount).toBe(after);+ },+ );++ it.each([0, 20])(+ 'renders nothing for a resize that changes no measured value (items %ipx tall)',+ async itemHeight => {+ let renders = 0;+ const {result} = renderHook(() => {+ renders++;+ return useOverflow(3, {gap: 10, maxRows: 2});+ });+ const box = resizableBox(200);++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50], 30, itemHeight));+ result.current.containerRef(box as unknown as HTMLElement);+ });+ const settled = renders;++ box.offsetWidth = 220;+ await deliverBeforePaint(box);++ expect(renders).toBe(settled);+ },+ );++ it('renders after paint when a multi-row fold changes the rows the list fills', async () => {+ const {result} = renderHook(() => useOverflow(6, {gap: 10, maxRows: 2}));+ const box = resizableBox(120);+ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50, 50, 50, 50], 30, 20));+ result.current.containerRef(box as unknown as HTMLElement);+ });+ expect(result.current.visibleCount).toBe(3);+ expect(result.current.rows).toBe(2);++ // At 260px the three shown items and the indicator fit on one row, so+ // the list is one row tall; the new set fills two rows.+ box.offsetWidth = 260;+ await deliverBeforePaint(box);+ expect(result.current.visibleCount).toBe(3);++ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 0));+ });+ expect(result.current.visibleCount).toBe(6);+ expect(result.current.rows).toBe(2);+ });++ it('renders after paint when the new set fits one row but its indicator wraps', async () => {+ const {result} = renderHook(() => useOverflow(5, {gap: 0, maxRows: 2}));+ // At 100px one item shows, and the indicator wraps onto the second row.+ const box = resizableBox(100);+ act(() => {+ result.current.measureRef(mockMeasure([60, 60, 60, 150, 60], 60, 20));+ result.current.containerRef(box as unknown as HTMLElement);+ });+ expect(result.current.visibleCount).toBe(1);++ // At 200px the shown item and the indicator fit on one row. The new set,+ // three items, fills one row, and its indicator wraps onto a second.+ box.offsetWidth = 200;+ await deliverBeforePaint(box);+ expect(result.current.visibleCount).toBe(1);++ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 0));+ });+ expect(result.current.visibleCount).toBe(3);+ });++ it('renders after paint when a single-row fold shows an indicator taller than the items', async () => {+ const {result} = renderHook(() => useOverflow(3, {gap: 10}));+ const box = resizableBox(200);+ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50], 30, 20, 40));+ result.current.containerRef(box as unknown as HTMLElement);+ });+ expect(result.current.visibleCount).toBe(3);++ // At 100px one item and the 40px indicator show, so the list grows taller.+ box.offsetWidth = 100;+ await deliverBeforePaint(box);+ expect(result.current.visibleCount).toBe(3);++ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 0));+ });+ expect(result.current.visibleCount).toBe(1);+ });++ it('renders after paint when a fold hides a plain-text indicator taller than the items', async () => {+ const {result} = renderHook(() => useOverflow(3, {gap: 10}));+ // The indicator renders as a text node, which the list's element+ // children do not include; the measure copy wraps it in an element.+ const box = resizableBox(100);+ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50], 30, 16, 24));+ result.current.containerRef(box as unknown as HTMLElement);+ });+ expect(result.current.visibleCount).toBe(1);++ // At 200px all three items fit, so the 24px indicator line goes away.+ box.offsetWidth = 200;+ await deliverBeforePaint(box);+ expect(result.current.visibleCount).toBe(1);++ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 0));+ });+ expect(result.current.visibleCount).toBe(3);+ });++ it('renders after paint when the shown indicator can be narrower than the measured one', async () => {+ const {result} = renderHook(() => useOverflow(5, {gap: 0, maxRows: 2}));+ const box = resizableBox(400);+ act(() => {+ // The measured indicator holds all five items; one for two is narrower.+ result.current.measureRef(mockMeasure([50, 50, 50, 180, 50], 44, 20));+ result.current.containerRef(box as unknown as HTMLElement);+ });+ expect(result.current.visibleCount).toBe(5);++ // At 170px the five shown items fill two clipped rows. Three items with+ // the measured indicator need two rows, without it one, so the rows the+ // new set fills are not known.+ box.offsetWidth = 170;+ await deliverBeforePaint(box);+ expect(result.current.visibleCount).toBe(5);++ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 0));+ });+ expect(result.current.visibleCount).toBe(3);+ });++ it('renders before paint when a multi-row fold keeps the rows the list fills', async () => {+ const {result} = renderHook(() => useOverflow(6, {gap: 10, maxRows: 2}));+ const box = resizableBox(260);+ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50, 50, 50, 50], 30, 20));+ result.current.containerRef(box as unknown as HTMLElement);+ });+ expect(result.current.visibleCount).toBe(6);++ // At 120px the six shown items wrap past two rows; the list clips at two.+ box.offsetWidth = 120;+ await deliverBeforePaint(box);++ expect(result.current.visibleCount).toBe(3);+ });++ // Under observeParent, OverflowList fills its parent's width only while+ // items are collapsed (component:OverflowList FR4). A fold that shows or+ // hides the indicator changes the list's width inside the observed parent,+ // which can change the parent's height when a sibling wraps.+ function boxWithParent(parentWidth: number): {+ container: HTMLElement;+ parent: {clientWidth: number} & Element;+ } {+ vi.stubGlobal('getComputedStyle', () => ({+ paddingLeft: '0px',+ paddingRight: '0px',+ }));+ const parent = {clientWidth: parentWidth} as unknown as {+ clientWidth: number;+ } & Element;+ const container = {offsetWidth: 0} as unknown as HTMLElement;+ Object.defineProperty(container, 'parentElement', {+ value: parent,+ configurable: true,+ });+ return {container, parent};+ }++ it.each([+ ['shows', 200, 100, 3, 1],+ ['hides', 100, 200, 1, 3],+ ])(+ 'renders after paint when an observeParent fold %s the indicator',+ async (_label, fromWidth, toWidth, before, after) => {+ const {result} = renderHook(() =>+ useOverflow(3, {gap: 10, behavior: 'observeParent'}),+ );+ const {container, parent} = boxWithParent(fromWidth);+ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50], 30));+ result.current.containerRef(container);+ });+ expect(result.current.visibleCount).toBe(before);++ parent.clientWidth = toWidth;+ await deliverBeforePaint(parent);+ expect(result.current.visibleCount).toBe(before);++ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 0));+ });+ expect(result.current.visibleCount).toBe(after);+ },+ );++ it('renders before paint when an observeParent fold keeps the indicator', async () => {+ const {result} = renderHook(() =>+ useOverflow(4, {gap: 10, behavior: 'observeParent'}),+ );+ const {container, parent} = boxWithParent(160);+ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50, 50], 30));+ result.current.containerRef(container);+ });+ expect(result.current.visibleCount).toBe(2);++ parent.clientWidth = 100;+ await deliverBeforePaint(parent);+ expect(result.current.visibleCount).toBe(1);+ expect(result.current.hasOverflow).toBe(true);+ });++ it('renders after paint when a multi-row list measures a new row height', async () => {+ const {result} = renderHook(() => useOverflow(6, {gap: 10, maxRows: 2}));+ const box = resizableBox(120);+ const measure = mockMeasure([50, 50, 50, 50, 50, 50], 30, 20);+ act(() => {+ result.current.measureRef(measure);+ result.current.containerRef(box as unknown as HTMLElement);+ });+ expect(result.current.rowHeight).toBe(20);++ // The items grow taller at the same width (a late web font, a theme or+ // density change). The list's max height follows the row height.+ for (const child of Array.from(measure.children)) {+ (child as unknown as {offsetHeight: number}).offsetHeight = 32;+ }+ await deliverBeforePaint(box);+ expect(result.current.rowHeight).toBe(20);++ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 0));+ });+ expect(result.current.rowHeight).toBe(32);+ });++ // A box with a real style declaration. `followsItems` makes its width drop+ // under size containment, as a list sized from its content does.+ function styledBox(+ width: number,+ followsItems: boolean,+ ): {+ offsetWidth: number;+ offsetHeight: number;+ style: CSSStyleDeclaration;+ } & Element {+ const style = document.createElement('div').style;+ const box = {+ style,+ offsetHeight: 28,+ hasAttribute: (name: string) => name === 'style' && style.length > 0,+ getAttribute: (name: string) =>+ name === 'style' && style.length > 0 ? style.cssText : null,+ removeAttribute: (name: string) => {+ if (name === 'style') {+ style.cssText = '';+ }+ },+ get offsetWidth() {+ return followsItems && style.getPropertyValue('contain') !== ''+ ? 0+ : width;+ },+ set offsetWidth(next: number) {+ width = next;+ },+ };+ return box as unknown as typeof box & Element;+ }++ it.each([+ ['follows its items: after paint', true, 3],+ ['does not follow its items: before paint', false, 1],+ ])(+ 'renders a fold whose list width %s',+ async (_label, followsItems, beforePaint) => {+ const {result} = renderHook(() => useOverflow(3, {gap: 10}));+ const box = styledBox(200, followsItems);+ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50], 30));+ result.current.containerRef(box as unknown as HTMLElement);+ });+ expect(result.current.visibleCount).toBe(3);++ box.offsetWidth = 100;+ await deliverBeforePaint(box);+ expect(result.current.visibleCount).toBe(beforePaint);+ // The probe leaves no inline style behind.+ expect(box.style.getPropertyValue('contain')).toBe('');++ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 0));+ });+ expect(result.current.visibleCount).toBe(1);+ },+ );++ it('leaves no style attribute on a list that had none after the probe', async () => {+ const {result} = renderHook(() => useOverflow(3, {gap: 10}));+ let width = 200;+ const list = document.createElement('div');+ Object.defineProperty(list, 'offsetWidth', {get: () => width});+ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50], 30));+ result.current.containerRef(list);+ });+ expect(result.current.visibleCount).toBe(3);++ width = 100;+ await deliverBeforePaint(list);+ expect(result.current.visibleCount).toBe(1);+ expect(list.hasAttribute('style')).toBe(false);+ });++ it('measures every list that one delivery reports, then renders once', async () => {+ let renders = 0;+ const {result} = renderHook(() => {+ renders++;+ return [useOverflow(3, {gap: 10}), useOverflow(3, {gap: 10})] as const;+ });+ const first = resizableBox(200);+ const second = resizableBox(200);++ act(() => {+ result.current[0].measureRef(mockMeasure([50, 50, 50], 30));+ result.current[0].containerRef(first as unknown as HTMLElement);+ result.current[1].measureRef(mockMeasure([50, 50, 50], 30));+ result.current[1].containerRef(second as unknown as HTMLElement);+ });+ const settled = renders;++ first.offsetWidth = 100;+ second.offsetWidth = 100;+ await deliverBeforePaint(first, second);++ expect(result.current[0].visibleCount).toBe(1);+ expect(result.current[1].visibleCount).toBe(1);+ expect(renders).toBe(settled + 1);+ });+});diff --git a/packages/core/src/hooks/useOverflow.ts b/packages/core/src/hooks/useOverflow.tsindex 7991b5b530..67f68bbbc0 100644--- a/packages/core/src/hooks/useOverflow.ts+++ b/packages/core/src/hooks/useOverflow.ts@@ -4,7 +4,8 @@/*** @file useOverflow.ts- * @input Uses React useState, useCallback, useRef; useIsomorphicLayoutEffect+ * @input Uses React useState, useCallback, useRef; react-dom flushSync;+ * useIsomorphicLayoutEffect* @output Exports useOverflow hook for measuring and managing horizontal overflow* @position Core hook; used by OverflowList and consumers for overflow patterns.* Hidden copies of the children are measured, so nothing flickers. The@@ -16,9 +17,10 @@*/import {useState, useCallback, useRef} from 'react';+import {flushSync} from 'react-dom';import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';import {observeResize} from '../utils/sharedResizeObserver';-import {computeOverflow} from './computeOverflow';+import {computeOverflow, countRows} from './computeOverflow';import {useDevWarning} from './useDevWarning';export interface UseOverflowOptions {@@ -85,6 +87,161 @@ export interface UseOverflowReturn {rowHeight: number;}+// A measurement either applies its result at once or returns the update to+// apply after the frame paints.+type Measure = (timing: 'now' | 'beforePaint') => (() => void) | undefined;++// Measurements that the resize observer reported in the current frame.+const pendingMeasures = new Set<Measure>();++/**+ * Measures again for a resize the observer reported.+ *+ * The observer reports after layout and before paint. A state update here+ * renders in a later task, after the frame paints. A microtask still runs+ * before paint. It measures every reported list and renders the results once.+ * An update that a measurement returns renders in a later task, after paint.+ */+function measureBeforePaint(measure: Measure): void {+ if (pendingMeasures.size === 0) {+ queueMicrotask(() => {+ const measures = [...pendingMeasures];+ pendingMeasures.clear();+ const afterPaint: (() => void)[] = [];+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the new visible set must render before the frame that reported the resize paints+ flushSync(() => {+ for (const run of measures) {+ const deferred = run('beforePaint');+ if (deferred) {+ afterPaint.push(deferred);+ }+ }+ });+ for (const update of afterPaint) {+ update();+ }+ });+ }+ pendingMeasures.add(measure);+}++/**+ * The registration call runs while React commits the ref, before paint, so it+ * measures at once.+ */+function observeForOverflow(element: Element, measure: Measure): () => void {+ let isRegistering = true;+ const unobserve = observeResize(element, () => {+ if (isRegistering) {+ measure('now');+ } else {+ measureBeforePaint(measure);+ }+ });+ isRegistering = false;+ return unobserve;+}++/** A visible set as the list renders it, sized from the measure copy. */+interface RenderedSet {+ widths: number[];+ heights: number[];+ /** The measured indicator, when the set collapses items. */+ indicator: {width: number; height: number} | null;+ indicatorFirst: boolean;+}++/**+ * The rows a set fills at `availableWidth`, up to `maxRows`, or `null` when+ * they are not known. The measured indicator holds every item, so the+ * rendered one can be narrower. When the rows with and without it differ,+ * the rows are not known.+ */+function rowsFilled(+ set: RenderedSet,+ gap: number,+ availableWidth: number,+ maxRows: number,+): number | null {+ const rowsWithout = Math.min(+ countRows(set.widths, gap, availableWidth),+ maxRows,+ );+ if (!set.indicator) {+ return rowsWithout;+ }+ const widths = set.indicatorFirst+ ? [set.indicator.width, ...set.widths]+ : [...set.widths, set.indicator.width];+ const rowsWith = Math.min(countRows(widths, gap, availableWidth), maxRows);+ return rowsWith === rowsWithout ? rowsWith : null;+}++/**+ * The list's height follows its tallest child and, in a multi-row list, the+ * rows it fills.+ */+function canChangeListHeight(+ now: RenderedSet,+ next: RenderedSet,+ gap: number,+ availableWidth: number,+ maxRows: number,+): boolean {+ const tallest = (set: RenderedSet) =>+ Math.max(0, ...set.heights, set.indicator?.height ?? 0);+ if (tallest(now) !== tallest(next)) {+ return true;+ }+ if (maxRows <= 1) {+ return false;+ }+ const rowsNow = rowsFilled(now, gap, availableWidth, maxRows);+ const rowsNext = rowsFilled(next, gap, availableWidth, maxRows);+ return rowsNow === null || rowsNext === null || rowsNow !== rowsNext;+}++/**+ * Whether the observed element's size follows the list's items: a list in a+ * flex item sized from its content, a shrink-to-fit box, or such an ancestor.+ * A fold then changes an observed size, so it cannot render inside the+ * observer step. Size containment drops the items' contribution to the+ * list's inline size, so a size that moves under it follows the items. The+ * probe reverts at once, before any observer or the frame can see it.+ */+function observedSizeFollowsItems(+ list: HTMLElement,+ observed: HTMLElement,+): boolean {+ const style = list.style as CSSStyleDeclaration | undefined;+ if (style == null || typeof style.setProperty !== 'function') {+ return false;+ }+ const hadStyleAttribute = list.hasAttribute('style');+ const value = style.getPropertyValue('contain');+ const priority = style.getPropertyPriority('contain');+ const width = observed.offsetWidth;+ const height = observed.offsetHeight;+ style.setProperty('contain', 'inline-size', 'important');+ const follows =+ observed.offsetWidth !== width || observed.offsetHeight !== height;+ if (value !== '') {+ style.setProperty('contain', value, priority);+ } else if (hadStyleAttribute) {+ style.removeProperty('contain');+ } else {+ style.removeProperty('contain');+ // Chromium writes the inline style back to the attribute lazily. Reading+ // the attribute first stops the removal from leaving `style=""`.+ void list.getAttribute('style');+ list.removeAttribute('style');+ }+ // Lay out again now. A later observer in this delivery reads the current+ // layout without updating it, so it would get the contained size.+ void observed.offsetWidth;+ return follows;+}+/*** Hook for managing horizontal overflow of a list of items.*@@ -129,6 +286,9 @@ export function useOverflow(const [visibleCount, setVisibleCount] = useState(itemCount);const [rows, setRows] = useState(1);const [rowHeight, setRowHeight] = useState(0);+ // The values last written to state. A measurement that matches them writes+ // nothing, so a resize that changes nothing renders nothing.+ const appliedRef = useRef({visibleCount: itemCount, rows: 1, rowHeight: 0});const containerElRef = useRef<HTMLElement | null>(null);const measureElRef = useRef<HTMLElement | null>(null);const observedElRef = useRef<HTMLElement | null>(null);@@ -136,80 +296,148 @@ export function useOverflow(const unobserveContainerRef = useRef<(() => void) | null>(null);const unobserveMeasureRef = useRef<(() => void) | null>(null);- const calculate = useCallback(() => {- const container = containerElRef.current;- const measure = measureElRef.current;- if (!container || !measure) {- return;- }+ const apply = useCallback(+ (nextVisible: number, nextRows: number, nextRowHeight: number) => {+ const applied = appliedRef.current;+ if (applied.visibleCount !== nextVisible) {+ applied.visibleCount = nextVisible;+ setVisibleCount(nextVisible);+ }+ if (applied.rows !== nextRows) {+ applied.rows = nextRows;+ setRows(nextRows);+ }+ if (applied.rowHeight !== nextRowHeight) {+ applied.rowHeight = nextRowHeight;+ setRowHeight(nextRowHeight);+ }+ },+ [],+ );- let availableWidth: number;+ const calculate: Measure = useCallback(+ (timing = 'now') => {+ const container = containerElRef.current;+ const measure = measureElRef.current;+ if (!container || !measure) {+ return;+ }- if (observeParent && container.parentElement) {- const parent = container.parentElement;- const parentStyle = getComputedStyle(parent);- availableWidth =- parent.clientWidth -- parseFloat(parentStyle.paddingLeft) -- parseFloat(parentStyle.paddingRight);- } else {- availableWidth = container.offsetWidth;- }+ let availableWidth: number;++ if (observeParent && container.parentElement) {+ const parent = container.parentElement;+ const parentStyle = getComputedStyle(parent);+ availableWidth =+ parent.clientWidth -+ parseFloat(parentStyle.paddingLeft) -+ parseFloat(parentStyle.paddingRight);+ } else {+ availableWidth = container.offsetWidth;+ }- const allChildren = Array.from(measure.children) as HTMLElement[];-- // The measurement container holds itemCount items, plus optionally- // an overflow indicator as the last child.- const hasIndicator = allChildren.length > itemCount;- const children = hasIndicator- ? allChildren.slice(0, itemCount)- : allChildren;- const indicatorWidth = hasIndicator- ? allChildren[allChildren.length - 1].offsetWidth- : 0;-- if (children.length === 0) {- // eslint-disable-next-line @eslint-react/set-state-in-effect -- overflow count is derived from measured DOM widths- setVisibleCount(0);- // eslint-disable-next-line @eslint-react/set-state-in-effect -- derived from measured DOM- setRows(0);- return;- }+ const allChildren = Array.from(measure.children) as HTMLElement[];++ // The measurement container holds itemCount items, plus optionally+ // an overflow indicator as the last child.+ const hasIndicator = allChildren.length > itemCount;+ const children = hasIndicator+ ? allChildren.slice(0, itemCount)+ : allChildren;+ const indicatorWidth = hasIndicator+ ? allChildren[allChildren.length - 1].offsetWidth+ : 0;- const widths = children.map(child => child.offsetWidth);- const measuredRowHeight = children.reduce(- (max, child) => Math.max(max, child.offsetHeight || 0),- 0,- );+ if (children.length === 0) {+ apply(0, 0, appliedRef.current.rowHeight);+ return;+ }- const {visibleCount: nextVisible, rows: nextRows} = computeOverflow({- widths,+ const widths = children.map(child => child.offsetWidth);+ const measuredRowHeight = children.reduce(+ (max, child) => Math.max(max, child.offsetHeight || 0),+ 0,+ );++ const {visibleCount: nextVisible, rows: nextRows} = computeOverflow({+ widths,+ gap,+ availableWidth,+ indicatorWidth,+ minVisibleItems,+ maxVisibleItems,+ maxRows,+ collapseFrom,+ });++ // Folding to a new list height inside the resize step makes Chromium+ // report a loop error. That update renders after paint. The measure copy+ // sizes both sets, a plain-text indicator included.+ if (timing === 'beforePaint') {+ const indicator = hasIndicator+ ? allChildren[allChildren.length - 1]+ : null;+ const renderedSet = (count: number): RenderedSet => {+ const shown =+ collapseFrom === 'end'+ ? children.slice(0, count)+ : children.slice(children.length - count);+ return {+ widths: shown.map(child => child.offsetWidth),+ heights: shown.map(child => child.offsetHeight || 0),+ indicator:+ indicator && count < itemCount+ ? {width: indicatorWidth, height: indicator.offsetHeight || 0}+ : null,+ indicatorFirst: collapseFrom === 'start',+ };+ };+ // Under observeParent the list fills its parent's width only while+ // items are collapsed. A fold that shows or hides the indicator+ // changes that width, which can change the observed parent's height+ // when a sibling wraps.+ const changesParentFill =+ observeParent &&+ appliedRef.current.visibleCount < itemCount !==+ nextVisible < itemCount;+ // A multi-row list's max height follows the measured row height.+ const changesRowHeight =+ (maxRows ?? 1) > 1 &&+ measuredRowHeight !== appliedRef.current.rowHeight;+ const observed =+ observeParent && container.parentElement+ ? container.parentElement+ : container;+ if (+ changesParentFill ||+ changesRowHeight ||+ (nextVisible !== appliedRef.current.visibleCount &&+ observedSizeFollowsItems(container, observed)) ||+ canChangeListHeight(+ renderedSet(appliedRef.current.visibleCount),+ renderedSet(nextVisible),+ gap,+ availableWidth,+ maxRows ?? 1,+ )+ ) {+ return () => apply(nextVisible, nextRows, measuredRowHeight);+ }+ }+ apply(nextVisible, nextRows, measuredRowHeight);+ return undefined;+ },+ [+ itemCount,gap,- availableWidth,- indicatorWidth,minVisibleItems,maxVisibleItems,maxRows,collapseFrom,- });-- // eslint-disable-next-line @eslint-react/set-state-in-effect -- overflow count is derived from measured DOM widths- setVisibleCount(nextVisible);- // eslint-disable-next-line @eslint-react/set-state-in-effect -- derived from measured DOM- setRows(prev => (prev === nextRows ? prev : nextRows));- // eslint-disable-next-line @eslint-react/set-state-in-effect -- derived from measured DOM- setRowHeight(prev =>- prev === measuredRowHeight ? prev : measuredRowHeight,- );- }, [- itemCount,- gap,- minVisibleItems,- maxVisibleItems,- maxRows,- collapseFrom,- observeParent,- ]);+ observeParent,+ apply,+ ],+ );const containerRef = useCallback((el: HTMLElement | null) => {@@ -223,9 +451,7 @@ export function useOverflow(if (el) {const target =observeParent && el.parentElement ? el.parentElement : el;- unobserveContainerRef.current = observeResize(target, () => {- calculate();- });+ unobserveContainerRef.current = observeForOverflow(target, calculate);observedElRef.current = target;}},@@ -243,9 +469,7 @@ export function useOverflow(return;}- unobserveMeasureRef.current = observeResize(el, () => {- calculate();- });+ unobserveMeasureRef.current = observeForOverflow(el, calculate);observedMeasureElRef.current = el;},[calculate],@@ -254,7 +478,7 @@ export function useOverflow(// Syncs the visible count with the rendered layout. It measures again after// the items change.useIsomorphicLayoutEffect(() => {- calculate();+ calculate('now');}, [calculate]);const hasOverflow = visibleCount < itemCount;