Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

OverflowList: report the collapsed set with onOverflowChange (#5199)

Cindy Zhang7e6b73b48700
diff --git a/.changeset/overflowlist-on-overflow-change.md b/.changeset/overflowlist-on-overflow-change.md
new file mode 100644
index 0000000000..a996deb9e3
--- /dev/null
+++ b/.changeset/overflowlist-on-overflow-change.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `OverflowList` can now hand its collapsed items to a menu you already render, via `onOverflowChange(overflowItems)`. `overflowRenderer` only describes an indicator the list mounts itself, and only while items overflow — so a row that already carries a standing "…" menu had no way to collect the collapsed items into it, and adding an indicator gave the user two menus side by side. Watching from the outside was not reachable either: a reporter component placed inside `overflowRenderer` mounts twice (the hidden measurement copy always receives _every_ item, so it cannot tell you what is actually collapsed), and nothing fires when the row widens back out and the set empties. The new callback reports the collapsed set whenever its membership or order changes, and leaves the anchor entirely to the caller. It fires once measurement has collapsed something, fires again with an empty array once the row widens back out and everything fits, and is silent while nothing overflows — including on mount, so a list that fits from the start never calls it. It never reports the pre-measurement state, which is an empty set whether or not the row actually overflows; hold the collapsed set in state initialised to `[]` and it is correct at every moment. Reports run from a layout effect after measurement, so the menu updates in the same frame as the collapse. The measurement container is now observed for size changes, so child-size changes refresh every OverflowList and direct `useOverflow` consumer even when the available container width does not change. Keyed membership and order changes are re-measured before `onOverflowChange` reports them. Stable React keys distinguish same-count membership and order changes, while unrelated re-renders and callback identity changes do not re-fire it. Both APIs may be used together; using `onOverflowChange` alone adds nothing to the row.
+
+@cixzhang
diff --git a/apps/storybook/stories/OverflowList.stories.tsx b/apps/storybook/stories/OverflowList.stories.tsx
index 8b911fb639..e94efb08f4 100644
--- a/apps/storybook/stories/OverflowList.stories.tsx
+++ b/apps/storybook/stories/OverflowList.stories.tsx
@@ -3,6 +3,7 @@
import type {Meta, StoryObj} from '@storybook/react';
import {useState} from 'react';
import {OverflowList} from '@astryxdesign/core/OverflowList';
+import type {OverflowItem} from '@astryxdesign/core/OverflowList';
import {Button} from '@astryxdesign/core/Button';
import {Badge} from '@astryxdesign/core/Badge';
import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';
@@ -414,3 +415,45 @@ export const CappedMultiRow: Story = {
);
},
};
+
+// A row that already owns a menu — the collapsed actions join it instead of
+// growing a second anchor. Drag the container's resize handle: the "More" menu
+// stays put and its entries appear and disappear as the row narrows and widens.
+export const StandingAnchor: Story = {
+ render: () => {
+ const actions = ['Rerun', 'Branch', 'Share', 'Export', 'Duplicate'];
+ const [hidden, setHidden] = useState<OverflowItem[]>([]);
+ return (
+ <div
+ style={{
+ resize: 'horizontal',
+ overflow: 'hidden',
+ border: '1px dashed #ccc',
+ padding: 8,
+ width: 520,
+ minWidth: 140,
+ maxWidth: '100%',
+ }}
+ data-testid="standing-anchor"
+ data-hidden-count={hidden.length}>
+ <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
+ <div style={{flex: '1 1 auto', minWidth: 0}}>
+ <OverflowList gap={2} onOverflowChange={setHidden}>
+ {actions.map(action => (
+ <Button key={action} label={action} size="sm" />
+ ))}
+ </OverflowList>
+ </div>
+ <DropdownMenu
+ button={{label: 'More', variant: 'ghost', size: 'sm'}}
+ items={[
+ ...hidden.map(({index}) => ({label: actions[index]})),
+ {label: 'Rename session'},
+ {label: 'Delete session'},
+ ]}
+ />
+ </div>
+ </div>
+ );
+ },
+};
diff --git a/packages/core/src/OverflowList/OverflowList.doc.mjs b/packages/core/src/OverflowList/OverflowList.doc.mjs
index 22ad8dbfb8..ceb0c897a1 100644
--- a/packages/core/src/OverflowList/OverflowList.doc.mjs
+++ b/packages/core/src/OverflowList/OverflowList.doc.mjs
@@ -48,6 +48,12 @@ export const docs = {
description:
'Render function for the overflow indicator. Receives the list of hidden items (each with child and index). Only called when items are overflowing.',
},
+ {
+ name: 'onOverflowChange',
+ type: '(overflowItems: OverflowItem[]) => void',
+ description:
+ 'Called whenever the collapsed set changes: with the collapsed items once something collapses, and with an empty array once the row widens back out. Membership and order changes report even when the count stays the same; unrelated re-renders and callback identity changes do not. Silent while nothing overflows, including on mount. Use stable React keys for dynamic items.',
+ },
{
name: 'gap',
type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',
@@ -58,7 +64,8 @@ export const docs = {
{
name: 'minVisibleItems',
type: 'number',
- description: 'Minimum number of items to always show, even when overflowing.',
+ description:
+ 'Minimum number of items to always show, even when overflowing.',
default: '0',
},
{
@@ -96,18 +103,37 @@ export const docs = {
},
],
theming: {
- targets: [
- {className: 'astryx-overflow-list'},
- ],
+ targets: [{className: 'astryx-overflow-list'}],
},
usage: {
description:
'A horizontal list that automatically hides items when they exceed the available width. Use OverflowList for breadcrumbs, toolbars, tag lists, or any row that needs to collapse gracefully at smaller sizes.',
bestPractices: [
- { guidance: true, description: 'Provide a meaningful overflowRenderer: a "+N more" badge, a dropdown, or a count indicator.' },
- { guidance: true, description: 'Set minVisibleItems to keep key items visible, and maxVisibleItems to cap the row at a fixed count regardless of available width.' },
- { guidance: true, description: 'Use maxRows to let items wrap onto a bounded number of rows (e.g. a two-row tag cloud) before collapsing the rest into the indicator.' },
- { guidance: false, description: 'Use OverflowList for a vertical stack; horizontal multi-row wrap is supported via maxRows, but items still flow left-to-right, not top-to-bottom.' },
+ {
+ guidance: true,
+ description:
+ 'Provide a meaningful overflowRenderer: a "+N more" badge, a dropdown, or a count indicator.',
+ },
+ {
+ guidance: true,
+ description:
+ 'When the row already has its own menu, use onOverflowChange to feed the collapsed items into it instead of adding a second anchor with overflowRenderer.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set minVisibleItems to keep key items visible, and maxVisibleItems to cap the row at a fixed count regardless of available width.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use maxRows to let items wrap onto a bounded number of rows (e.g. a two-row tag cloud) before collapsing the rest into the indicator.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use OverflowList for a vertical stack; horizontal multi-row wrap is supported via maxRows, but items still flow left-to-right, not top-to-bottom.',
+ },
],
},
};
@@ -129,6 +155,12 @@ export const docsZh = {
description:
'溢出指示器的渲染函数。接收隐藏项目列表(每项包含 child 和 index)。仅在有溢出项时调用。',
},
+ {
+ name: 'onOverflowChange',
+ type: '(overflowItems: OverflowItem[]) => void',
+ description:
+ '折叠项集合变化时调用:发生折叠时传入折叠项,行重新变宽、全部放得下时传入空数组。没有溢出时(包括挂载时)不会调用。用于将折叠项交给周围界面已有的菜单,避免列表再挂载一个自己的指示器。',
+ },
{
name: 'gap',
type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',
@@ -180,36 +212,85 @@ export const docsZh = {
description:
'A horizontal list that automatically hides items when they exceed the available width. Use OverflowList for breadcrumbs, toolbars, tag lists, or any row that needs to collapse gracefully at smaller sizes.',
bestPractices: [
- { guidance: true, description: 'Provide a meaningful overflowRenderer: a "+N more" badge, a dropdown, or a count indicator.' },
- { guidance: true, description: 'Set minVisibleItems to keep key items visible, and maxVisibleItems to cap the row at a fixed count regardless of available width.' },
- { guidance: true, description: 'Use maxRows to let items wrap onto a bounded number of rows (e.g. a two-row tag cloud) before collapsing the rest into the indicator.' },
- { guidance: false, description: 'Use OverflowList for a vertical stack; horizontal multi-row wrap is supported via maxRows, but items still flow left-to-right, not top-to-bottom.' },
+ {
+ guidance: true,
+ description:
+ 'Provide a meaningful overflowRenderer: a "+N more" badge, a dropdown, or a count indicator.',
+ },
+ {
+ guidance: true,
+ description:
+ 'When the row already has its own menu, use onOverflowChange to feed the collapsed items into it instead of adding a second anchor with overflowRenderer.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set minVisibleItems to keep key items visible, and maxVisibleItems to cap the row at a fixed count regardless of available width.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use maxRows to let items wrap onto a bounded number of rows (e.g. a two-row tag cloud) before collapsing the rest into the indicator.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use OverflowList for a vertical stack; horizontal multi-row wrap is supported via maxRows, but items still flow left-to-right, not top-to-bottom.',
+ },
],
},
};
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
- description: 'horizontal list w/ overflow indicator: hides items beyond container width',
+ description:
+ 'horizontal list w/ overflow indicator: hides items beyond container width',
usage: {
description:
'A horizontal list that automatically hides items when they exceed the available width. Use OverflowList for breadcrumbs, toolbars, tag lists, or any row that needs to collapse gracefully at smaller sizes.',
bestPractices: [
- { guidance: true, description: 'Provide a meaningful overflowRenderer: a "+N more" badge, a dropdown, or a count indicator.' },
- { guidance: true, description: 'Set minVisibleItems to keep key items visible, and maxVisibleItems to cap the row at a fixed count regardless of available width.' },
- { guidance: true, description: 'Use maxRows to let items wrap onto a bounded number of rows (e.g. a two-row tag cloud) before collapsing the rest into the indicator.' },
- { guidance: false, description: 'Use OverflowList for a vertical stack; horizontal multi-row wrap is supported via maxRows, but items still flow left-to-right, not top-to-bottom.' },
+ {
+ guidance: true,
+ description:
+ 'Provide a meaningful overflowRenderer: a "+N more" badge, a dropdown, or a count indicator.',
+ },
+ {
+ guidance: true,
+ description:
+ 'When the row already has its own menu, use onOverflowChange to feed the collapsed items into it instead of adding a second anchor with overflowRenderer.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set minVisibleItems to keep key items visible, and maxVisibleItems to cap the row at a fixed count regardless of available width.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use maxRows to let items wrap onto a bounded number of rows (e.g. a two-row tag cloud) before collapsing the rest into the indicator.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use OverflowList for a vertical stack; horizontal multi-row wrap is supported via maxRows, but items still flow left-to-right, not top-to-bottom.',
+ },
],
},
propDescriptions: {
children: 'items to render, each child should be a single element',
- overflowRenderer: 'renders overflow indicator, receives hidden items w/ index',
+ overflowRenderer:
+ 'renders overflow indicator, receives hidden items w/ index',
+ onOverflowChange:
+ 'fires w/ collapsed items when membership/order changes (empty once the row fits again); ignores unrelated renders/callback identity; stable React keys required for dynamic items',
gap: 'item gap as spacing step',
minVisibleItems: 'min items always shown even when overflowing',
- maxVisibleItems: 'max items ever shown (cap); extra items collapse to indicator; min wins if smaller',
- maxRows: 'wrap items across up to N rows then collapse rest (number, not boolean); undefined = single line',
+ maxVisibleItems:
+ 'max items ever shown (cap); extra items collapse to indicator; min wins if smaller',
+ maxRows:
+ 'wrap items across up to N rows then collapse rest (number, not boolean); undefined = single line',
collapseFrom: 'which end to collapse from',
- behavior: 'observeSelf (default) or observeParent for content-sized containers',
+ behavior:
+ 'observeSelf (default) or observeParent for content-sized containers',
xstyle: 'StyleX styles, use stylex.create() values only',
},
};
diff --git a/packages/core/src/OverflowList/OverflowList.test.tsx b/packages/core/src/OverflowList/OverflowList.test.tsx
index 6d7653f59f..1c25aa6657 100644
--- a/packages/core/src/OverflowList/OverflowList.test.tsx
+++ b/packages/core/src/OverflowList/OverflowList.test.tsx
@@ -17,8 +17,10 @@
*/
import {describe, it, expect, beforeAll, afterAll, vi} from 'vitest';
-import {render, screen, within} from '@testing-library/react';
+import {render, screen, within, act, waitFor} from '@testing-library/react';
+import {useState} from 'react';
import {OverflowList} from './OverflowList';
+import type {OverflowItem} from './OverflowList';
const originalOffsetWidth = Object.getOwnPropertyDescriptor(
HTMLElement.prototype,
@@ -28,12 +30,27 @@ const originalResizeObserver = (
globalThis as unknown as {ResizeObserver?: unknown}
).ResizeObserver;
-/** No-op ResizeObserver — the shared observer fires its initial callback
- * synchronously on observe(), so the algorithm still measures on mount. */
+const resizeObservers = new Set<StubResizeObserver>();
+
+/** ResizeObserver stub with an explicit trigger for resize-path tests. */
class StubResizeObserver {
+ constructor(private callback: ResizeObserverCallback) {
+ resizeObservers.add(this);
+ }
+
observe(): void {}
unobserve(): void {}
- disconnect(): void {}
+ disconnect(): void {
+ resizeObservers.delete(this);
+ }
+
+ takeRecords(): ResizeObserverEntry[] {
+ return [];
+ }
+
+ trigger(target: Element): void {
+ this.callback([{target} as ResizeObserverEntry], this);
+ }
}
beforeAll(() => {
@@ -88,6 +105,29 @@ const indicator =
</span>
);
+/** Notify the shared observer that an element's size changed. */
+function triggerResize(target: Element): void {
+ act(() => {
+ for (const observer of resizeObservers) {
+ observer.trigger(target);
+ }
+ });
+}
+
+/** The indices the most recent onOverflowChange call reported. */
+function indicesOf(spy: {mock: {calls: unknown[][]}}): number[] {
+ const last = spy.mock.calls[spy.mock.calls.length - 1];
+ return (last[0] as {index: number}[]).map(i => i.index);
+}
+
+/** The labels the most recent onOverflowChange call reported. */
+function labelsOf(spy: {mock: {calls: unknown[][]}}): string[] {
+ const last = spy.mock.calls[spy.mock.calls.length - 1];
+ return (last[0] as OverflowItem[]).map(item =>
+ String((item.child.props as {children?: unknown}).children),
+ );
+}
+
describe('OverflowList', () => {
describe('when all items fit', () => {
it('renders every item and no overflow indicator', () => {
@@ -524,4 +564,510 @@ describe('OverflowList', () => {
expect(within(vis).queryByText('B')).not.toBeInTheDocument();
});
});
+
+ describe('onOverflowChange', () => {
+ it('stays silent when nothing overflows', () => {
+ const onOverflowChange = vi.fn();
+ render(
+ <OverflowList
+ gap={0}
+ data-w="1000"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ <button type="button" data-w="40">
+ A
+ </button>
+ <button type="button" data-w="40">
+ B
+ </button>
+ </OverflowList>,
+ );
+ expect(onOverflowChange).not.toHaveBeenCalled();
+ });
+
+ it('fires once on mount while overflowing, with the measured set', () => {
+ const onOverflowChange = vi.fn();
+ render(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ <button type="button" data-w="40">
+ A
+ </button>
+ <button type="button" data-w="40">
+ B
+ </button>
+ <button type="button" data-w="40">
+ C
+ </button>
+ </OverflowList>,
+ );
+ expect(onOverflowChange).toHaveBeenCalledTimes(1);
+ expect(indicesOf(onOverflowChange)).toEqual([1, 2]);
+ });
+
+ it('reports the collapsed items by original index', () => {
+ const onOverflowChange = vi.fn();
+ render(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ <button type="button" data-w="40">
+ A
+ </button>
+ <button type="button" data-w="40">
+ B
+ </button>
+ <button type="button" data-w="40">
+ C
+ </button>
+ </OverflowList>,
+ );
+ expect(indicesOf(onOverflowChange)).toEqual([1, 2]);
+ });
+
+ it('reports an empty set again once the container fits everything', () => {
+ const onOverflowChange = vi.fn();
+ const items = [
+ <button type="button" data-w="40" key="a">
+ A
+ </button>,
+ <button type="button" data-w="40" key="b">
+ B
+ </button>,
+ <button type="button" data-w="40" key="c">
+ C
+ </button>,
+ ];
+ const {rerender} = render(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {items}
+ </OverflowList>,
+ );
+ expect(indicesOf(onOverflowChange)).toEqual([1, 2]);
+
+ rerender(
+ <OverflowList
+ gap={0}
+ data-w="1000"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {items}
+ </OverflowList>,
+ );
+ triggerResize(visibleContainer());
+ expect(onOverflowChange).toHaveBeenCalledTimes(2);
+ expect(indicesOf(onOverflowChange)).toEqual([]);
+ });
+
+ it('does not re-fire when the collapsed set is unchanged', () => {
+ const spy = vi.fn();
+ const items = [
+ <button type="button" data-w="40" key="a">
+ A
+ </button>,
+ <button type="button" data-w="40" key="b">
+ B
+ </button>,
+ ];
+ // A fresh inline callback each render — the guard is the collapsed set,
+ // not the callback's identity.
+ const {rerender} = render(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={o => {
+ spy(o);
+ }}>
+ {items}
+ </OverflowList>,
+ );
+ expect(spy).toHaveBeenCalledTimes(1);
+ rerender(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={o => {
+ spy(o);
+ }}>
+ {items}
+ </OverflowList>,
+ );
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports same-count membership and order changes', () => {
+ const onOverflowChange = vi.fn();
+ const renderItems = (labels: string[]) =>
+ labels.map(label => (
+ <button type="button" data-w="40" key={label}>
+ {label}
+ </button>
+ ));
+ const {rerender} = render(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {renderItems(['A', 'B', 'C'])}
+ </OverflowList>,
+ );
+ expect(labelsOf(onOverflowChange)).toEqual(['B', 'C']);
+
+ rerender(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {renderItems(['A', 'C', 'B'])}
+ </OverflowList>,
+ );
+ expect(labelsOf(onOverflowChange)).toEqual(['C', 'B']);
+
+ rerender(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {renderItems(['A', 'D', 'B'])}
+ </OverflowList>,
+ );
+ expect(onOverflowChange).toHaveBeenCalledTimes(3);
+ expect(labelsOf(onOverflowChange)).toEqual(['D', 'B']);
+ });
+
+ it('reports one measured set when unequal-width items reorder', async () => {
+ const onOverflowChange = vi.fn();
+ const items = {
+ wide: (
+ <button type="button" data-w="200" key="wide">
+ Wide
+ </button>
+ ),
+ a: (
+ <button type="button" data-w="50" key="a">
+ A
+ </button>
+ ),
+ b: (
+ <button type="button" data-w="50" key="b">
+ B
+ </button>
+ ),
+ };
+ const {rerender} = render(
+ <OverflowList
+ gap={0}
+ data-w="150"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {items.wide}
+ {items.a}
+ {items.b}
+ </OverflowList>,
+ );
+ expect(indicesOf(onOverflowChange)).toEqual([0, 1, 2]);
+
+ rerender(
+ <OverflowList
+ gap={0}
+ data-w="150"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {items.a}
+ {items.b}
+ {items.wide}
+ </OverflowList>,
+ );
+
+ await waitFor(() => {
+ expect(visibleContainer()).toHaveTextContent('AB');
+ });
+ expect(onOverflowChange).toHaveBeenCalledTimes(2);
+ expect(indicesOf(onOverflowChange)).toEqual([2]);
+ });
+
+ it('re-measures same-count content changes with stable keys', () => {
+ const onOverflowChange = vi.fn();
+ const renderItems = (
+ items: {key: string; label: string; width: number}[],
+ ) =>
+ items.map(item => (
+ <button type="button" data-w={item.width} key={item.key}>
+ {item.label}
+ </button>
+ ));
+ const {rerender} = render(
+ <OverflowList
+ gap={0}
+ data-w="300"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {renderItems([
+ {key: 'a', label: 'A', width: 60},
+ {key: 'b', label: 'B', width: 60},
+ {key: 'c', label: 'C', width: 60},
+ {key: 'd', label: 'D', width: 60},
+ ])}
+ </OverflowList>,
+ );
+ expect(onOverflowChange).not.toHaveBeenCalled();
+
+ rerender(
+ <OverflowList
+ gap={0}
+ data-w="300"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {renderItems([
+ {key: 'a', label: 'A', width: 60},
+ {key: 'b', label: 'B', width: 60},
+ {key: 'c', label: 'Wide', width: 200},
+ {key: 'd', label: 'D', width: 60},
+ ])}
+ </OverflowList>,
+ );
+ triggerResize(measureContainer());
+
+ expect(onOverflowChange).toHaveBeenCalledTimes(1);
+ expect(indicesOf(onOverflowChange)).toEqual([2, 3]);
+ expect(visibleContainer()).toHaveTextContent('AB');
+ expect(visibleContainer()).not.toHaveTextContent('Wide');
+ });
+
+ it('reports only the measured set when the number of children changes', () => {
+ const onOverflowChange = vi.fn();
+ const renderItems = (labels: string[], width: number) =>
+ labels.map(label => (
+ <button type="button" data-w={width} key={label}>
+ {label}
+ </button>
+ ));
+ const {rerender} = render(
+ <OverflowList
+ gap={0}
+ data-w="220"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {renderItems(['A', 'B', 'C', 'D', 'E'], 100)}
+ </OverflowList>,
+ );
+ expect(indicesOf(onOverflowChange)).toEqual([2, 3, 4]);
+
+ rerender(
+ <OverflowList
+ gap={0}
+ data-w="220"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {renderItems(['Go', 'Up'], 40)}
+ </OverflowList>,
+ );
+ expect(onOverflowChange).toHaveBeenCalledTimes(2);
+ expect(indicesOf(onOverflowChange)).toEqual([]);
+
+ rerender(
+ <OverflowList
+ gap={0}
+ data-w="220"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ {renderItems(['A', 'B', 'C', 'D', 'E'], 100)}
+ </OverflowList>,
+ );
+ expect(onOverflowChange).toHaveBeenCalledTimes(3);
+ expect(indicesOf(onOverflowChange)).toEqual([2, 3, 4]);
+ });
+
+ it('uses a replacement callback only for the next set change', () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const items = [
+ <button type="button" data-w="40" key="a">
+ A
+ </button>,
+ <button type="button" data-w="40" key="b">
+ B
+ </button>,
+ ];
+ const {rerender} = render(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={first}>
+ {items}
+ </OverflowList>,
+ );
+ expect(first).toHaveBeenCalledTimes(1);
+
+ rerender(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={second}>
+ {items}
+ </OverflowList>,
+ );
+ expect(second).not.toHaveBeenCalled();
+
+ rerender(
+ <OverflowList
+ gap={0}
+ data-w="1000"
+ data-testid="ov"
+ onOverflowChange={second}>
+ {items}
+ </OverflowList>,
+ );
+ triggerResize(visibleContainer());
+ expect(first).toHaveBeenCalledTimes(1);
+ expect(second).toHaveBeenCalledTimes(1);
+ expect(indicesOf(second)).toEqual([]);
+ });
+
+ it('settles when the callback stores the collapsed set in state', () => {
+ const onReport = vi.fn();
+
+ function Harness() {
+ const [hidden, setHidden] = useState<OverflowItem[]>([]);
+ return (
+ <>
+ <output data-testid="hidden-count">{hidden.length}</output>
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={items => {
+ onReport(items);
+ setHidden(items);
+ }}>
+ <button type="button" data-w="40">
+ A
+ </button>
+ <button type="button" data-w="40">
+ B
+ </button>
+ </OverflowList>
+ </>
+ );
+ }
+
+ render(<Harness />);
+ expect(onReport).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId('hidden-count')).toHaveTextContent('1');
+ });
+
+ it('does not report after unmount', () => {
+ const onOverflowChange = vi.fn();
+ const {unmount} = render(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ <button type="button" data-w="40">
+ A
+ </button>
+ <button type="button" data-w="40">
+ B
+ </button>
+ </OverflowList>,
+ );
+ const container = visibleContainer();
+ const measure = measureContainer();
+ expect(onOverflowChange).toHaveBeenCalledTimes(1);
+
+ unmount();
+ triggerResize(container);
+ triggerResize(measure);
+ expect(onOverflowChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports the leading items with collapseFrom="start"', () => {
+ const onOverflowChange = vi.fn();
+ render(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ collapseFrom="start"
+ onOverflowChange={onOverflowChange}>
+ <button type="button" data-w="40">
+ A
+ </button>
+ <button type="button" data-w="40">
+ B
+ </button>
+ <button type="button" data-w="40">
+ C
+ </button>
+ </OverflowList>,
+ );
+ expect(indicesOf(onOverflowChange)).toEqual([0, 1]);
+ });
+
+ it('adds no indicator of its own, so an outside anchor stands alone', () => {
+ const onOverflowChange = vi.fn();
+ render(
+ <OverflowList
+ gap={0}
+ data-w="60"
+ data-testid="ov"
+ onOverflowChange={onOverflowChange}>
+ <button type="button" data-w="40">
+ A
+ </button>
+ <button type="button" data-w="40">
+ B
+ </button>
+ <button type="button" data-w="40">
+ C
+ </button>
+ </OverflowList>,
+ );
+ expect(indicesOf(onOverflowChange)).toEqual([1, 2]);
+ expect(visibleContainer().textContent).toBe('A');
+ // Nothing beyond the items themselves is measured either.
+ expect(measureContainer().children).toHaveLength(3);
+ });
+
+ it('reports alongside an overflowRenderer without disturbing it', () => {
+ const onOverflowChange = vi.fn();
+ render(
+ <OverflowList
+ gap={0}
+ data-w="100"
+ data-testid="ov"
+ overflowRenderer={indicator('more:')}
+ onOverflowChange={onOverflowChange}>
+ <button type="button" data-w="40">
+ A
+ </button>
+ <button type="button" data-w="40">
+ B
+ </button>
+ <button type="button" data-w="40">
+ C
+ </button>
+ </OverflowList>,
+ );
+ expect(indicesOf(onOverflowChange)).toEqual([1, 2]);
+ expect(visibleContainer().textContent).toBe('Amore:1,2');
+ });
+ });
});
diff --git a/packages/core/src/OverflowList/OverflowList.tsx b/packages/core/src/OverflowList/OverflowList.tsx
index 128d47b9fd..c709ac8530 100644
--- a/packages/core/src/OverflowList/OverflowList.tsx
+++ b/packages/core/src/OverflowList/OverflowList.tsx
@@ -18,12 +18,20 @@
* - /packages/cli/assets/templates/blocks/components/OverflowList/ (showcase blocks)
*/
-import {type ReactNode, type ReactElement, Children} from 'react';
+import {
+ type ReactNode,
+ type ReactElement,
+ Children,
+ useCallback,
+ useRef,
+ useState,
+} from 'react';
import type {BaseProps} from '../BaseProps';
import type {SpacingStep} from '../utils/types';
import * as stylex from '@stylexjs/stylex';
import {mergeProps} from '../utils';
import {useOverflow} from '../hooks/useOverflow';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {spacingVars} from '../theme/tokens.stylex';
import {themeProps} from '../utils/themeProps';
@@ -187,6 +195,47 @@ export interface OverflowListProps extends BaseProps<HTMLDivElement> {
* ```
*/
overflowRenderer?: (overflowItems: OverflowItem[]) => ReactNode;
+
+ /**
+ * Called with the items that are currently collapsed, whenever that set
+ * changes.
+ *
+ * Use it when the collapsed items belong in a menu the surrounding UI
+ * already renders (a row that already has its own "…" button), so the list
+ * does not grow a second anchor beside it. `overflowRenderer` cannot serve
+ * that case: it is only rendered while items overflow, and its measurement
+ * copy always receives every item.
+ *
+ * The contract:
+ * - It fires once measurement has collapsed something, and again with an
+ * empty array once the row widens back out and everything fits.
+ * - It is **silent while nothing overflows** — including on mount, so a list
+ * that fits from the start never calls it. There is no report of the
+ * pre-measurement state, which would always be an empty set whether or not
+ * the row actually overflows. Hold the collapsed set in state initialised
+ * to `[]` and it is correct at every moment; if you remount the list while
+ * keeping that state, reset it yourself.
+ * - Reports are keyed on the collapsed items' original indices and React
+ * keys. Membership and order changes report even when the count stays the
+ * same; unrelated re-renders and callback identity changes do not.
+ *
+ * Give dynamic children stable React keys. Items include their current
+ * original `index`; use it to look up your own data rather than storing
+ * `child`.
+ *
+ * @example
+ * ```
+ * const [hidden, setHidden] = useState<OverflowItem[]>([]);
+ * <>
+ * <OverflowList onOverflowChange={setHidden}>{items}</OverflowList>
+ * <DropdownMenu
+ * button={{label: 'More', variant: 'ghost'}}
+ * items={[...alwaysThere, ...hidden.map(({index}) => actions[index])]}
+ * />
+ * </>
+ * ```
+ */
+ onOverflowChange?: (overflowItems: OverflowItem[]) => void;
}
/**
@@ -219,6 +268,7 @@ export function OverflowList({
collapseFrom = 'end',
behavior = 'observeSelf',
overflowRenderer,
+ onOverflowChange,
xstyle,
className,
style,
@@ -263,11 +313,59 @@ export function OverflowList({
// so the indicator renders at its maximum possible width.
const measureIndicator = overflowRenderer?.(allItems);
+ // Re-run measurement when keyed children change without resizing the row.
+ // The measured key delays reporting until that measurement has committed.
+ // Lists without the callback skip all identity work.
+ const measurementKey = onOverflowChange
+ ? JSON.stringify({
+ children: childArray.map((child, index) => [index, child.key]),
+ gap,
+ minVisibleItems,
+ maxVisibleItems,
+ maxRows,
+ collapseFrom,
+ behavior,
+ })
+ : '';
+ const [measuredKey, setMeasuredKey] = useState(measurementKey);
+ const reportMeasureRef = useCallback(
+ (element: HTMLElement | null) => {
+ measureRef(element);
+ if (element) {
+ setMeasuredKey(measurementKey);
+ }
+ },
+ [measureRef, measurementKey],
+ );
+
+ // Report after measurement, before paint, so a standing menu updates in the
+ // same frame as the visible row. Keys distinguish membership and order while
+ // suppressing callback-only or unrelated re-renders. The initial empty key
+ // suppresses the optimistic pre-measurement render.
+ const overflowKey = onOverflowChange
+ ? JSON.stringify(overflowItems.map(({child, index}) => [index, child.key]))
+ : '[]';
+ const reportedKeyRef = useRef('[]');
+ const overflowItemsRef = useRef(overflowItems);
+ overflowItemsRef.current = overflowItems;
+
+ useIsomorphicLayoutEffect(() => {
+ if (
+ !onOverflowChange ||
+ measuredKey !== measurementKey ||
+ reportedKeyRef.current === overflowKey
+ ) {
+ return;
+ }
+ reportedKeyRef.current = overflowKey;
+ onOverflowChange(overflowItemsRef.current);
+ }, [measuredKey, measurementKey, overflowKey, onOverflowChange]);
+
return (
<>
{/* Hidden measurement container */}
<div
- ref={measureRef}
+ ref={reportMeasureRef}
aria-hidden="true"
inert
{...stylex.props(styles.measureContainer, gapStyles[gap])}>
diff --git a/packages/core/src/hooks/useOverflow.doc.mjs b/packages/core/src/hooks/useOverflow.doc.mjs
index 3e43992feb..5098739d90 100644
--- a/packages/core/src/hooks/useOverflow.doc.mjs
+++ b/packages/core/src/hooks/useOverflow.doc.mjs
@@ -4,7 +4,17 @@
export const docs = {
name: 'useOverflow',
displayName: 'useOverflow',
- keywords: ['overflow', 'truncate', 'responsive', 'collapse', 'resize', 'measure', 'hidden', 'more', 'breadcrumb'],
+ keywords: [
+ 'overflow',
+ 'truncate',
+ 'responsive',
+ 'collapse',
+ 'resize',
+ 'measure',
+ 'hidden',
+ 'more',
+ 'breadcrumb',
+ ],
params: [
{
name: 'itemCount',
@@ -28,7 +38,8 @@ export const docs = {
{
name: 'options.minVisibleItems',
type: 'number',
- description: 'Minimum number of items to always show, even if they don\'t fit.',
+ description:
+ "Minimum number of items to always show, even if they don't fit.",
default: '0',
required: false,
},
@@ -42,7 +53,8 @@ export const docs = {
{
name: 'options.behavior',
type: "'observeParent' | 'observeSelf'",
- description: "Which element to observe for overflow calculations. 'observeParent' uses the container's parent element width, allowing the visible container to remain content-sized.",
+ description:
+ "Which element to observe for overflow calculations. 'observeParent' uses the container's parent element width, allowing the visible container to remain content-sized.",
default: "'observeSelf'",
required: false,
},
@@ -56,7 +68,8 @@ export const docs = {
{
name: 'measureRef',
type: 'React.RefCallback<HTMLElement>',
- description: 'Ref callback to attach to the hidden measurement container that holds all items.',
+ description:
+ 'Ref callback to attach to the hidden measurement container that holds all items.',
},
{
name: 'visibleCount',
@@ -66,16 +79,29 @@ export const docs = {
{
name: 'hasOverflow',
type: 'boolean',
- description: 'Whether any items are overflowing (visibleCount < itemCount).',
+ description:
+ 'Whether any items are overflowing (visibleCount < itemCount).',
},
],
usage: {
description:
- 'Measures children rendered in a hidden container to determine how many fit in the available width without flickering. Uses ResizeObserver to react to container size changes. The measurement container should hold all items plus an optional overflow indicator element (identified by a data-overflow-indicator attribute).',
+ 'Measures children rendered in a hidden container to determine how many fit in the available width without flickering. Uses ResizeObserver to react to container and measured-child size changes. The measurement container should hold all items plus an optional overflow indicator element (identified by a data-overflow-indicator attribute).',
bestPractices: [
- { guidance: true, description: 'Render all items into the measureRef container (hidden) and only the first visibleCount items into the containerRef container (visible).' },
- { guidance: true, description: 'Include an overflow indicator (e.g., "+N more" button) as the last child of the measurement container with a data-overflow-indicator attribute.' },
- { guidance: false, description: 'Use for vertical overflow; this hook measures horizontal width only.' },
+ {
+ guidance: true,
+ description:
+ 'Render all items into the measureRef container (hidden) and only the first visibleCount items into the containerRef container (visible).',
+ },
+ {
+ guidance: true,
+ description:
+ 'Include an overflow indicator (e.g., "+N more" button) as the last child of the measurement container with a data-overflow-indicator attribute.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use for vertical overflow; this hook measures horizontal width only.',
+ },
],
},
relatedComponents: ['OverflowList', 'Breadcrumb'],
@@ -87,28 +113,43 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
export const docsDense = {
description:
- 'Measures children rendered in hidden container to determine how many fit in available width w/o flickering. Uses ResizeObserver to react to container size changes. Measurement container should hold all items plus optional overflow indicator element (identified by data-overflow-indicator attribute).',
+ 'Measures children rendered in hidden container to determine how many fit in available width w/o flickering. Uses ResizeObserver to react to container and measured-child size changes. Measurement container should hold all items plus optional overflow indicator element (identified by data-overflow-indicator attribute).',
paramDescriptions: {
itemCount: 'total # items to measure for overflow.',
options: 'config for overflow behavior.',
'options.gap': 'gap between items in px. Used in width calculations.',
- 'options.minVisibleItems': "min # items to always show, even if they don't fit.",
+ 'options.minVisibleItems':
+ "min # items to always show, even if they don't fit.",
'options.collapseFrom': 'which end to collapse items from.',
- 'options.behavior': "which element to observe for overflow calculations. 'observeParent' uses container's parent element width, allowing visible container to remain content-sized.",
+ 'options.behavior':
+ "which element to observe for overflow calculations. 'observeParent' uses container's parent element width, allowing visible container to remain content-sized.",
},
returnDescriptions: {
containerRef: 'ref callback for visible container element.',
- measureRef: 'ref callback for hidden measurement container holding all items.',
+ measureRef:
+ 'ref callback for hidden measurement container holding all items.',
visibleCount: '# items that fit in visible container.',
hasOverflow: 'whether any items overflowing (visibleCount < itemCount).',
},
usage: {
description:
- 'Measures children rendered in hidden container to determine how many fit in available width w/o flickering. Uses ResizeObserver to react to container size changes. Measurement container should hold all items plus optional overflow indicator element (identified by data-overflow-indicator attribute).',
+ 'Measures children rendered in hidden container to determine how many fit in available width w/o flickering. Uses ResizeObserver to react to container and measured-child size changes. Measurement container should hold all items plus optional overflow indicator element (identified by data-overflow-indicator attribute).',
bestPractices: [
- { guidance: true, description: 'Render all items into measureRef container (hidden) + only first visibleCount items into containerRef container (visible).' },
- { guidance: true, description: 'Include overflow indicator (e.g. "+N more" button) as last child of measurement container w/ data-overflow-indicator attribute.' },
- { guidance: false, description: 'Use for vertical overflow; this hook measures horizontal width only.' },
+ {
+ guidance: true,
+ description:
+ 'Render all items into measureRef container (hidden) + only first visibleCount items into containerRef container (visible).',
+ },
+ {
+ guidance: true,
+ description:
+ 'Include overflow indicator (e.g. "+N more" button) as last child of measurement container w/ data-overflow-indicator attribute.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use for vertical overflow; this hook measures horizontal width only.',
+ },
],
},
};
diff --git a/packages/core/src/hooks/useOverflow.ts b/packages/core/src/hooks/useOverflow.ts
index d5853ec15a..8391c5faad 100644
--- a/packages/core/src/hooks/useOverflow.ts
+++ b/packages/core/src/hooks/useOverflow.ts
@@ -9,8 +9,9 @@
* @position Core hook; used by OverflowList and consumers for overflow patterns
*
* Measures children rendered in a hidden container to determine how many fit
- * in the available width, without flickering. Uses ResizeObserver to react
- * to container size changes. Supports an optional item cap (`maxVisibleItems`)
+ * in the available width, without flickering. Observes both the visible and
+ * hidden measurement containers so changes to available width or measured child
+ * sizes recalculate the result. Supports an optional item cap (`maxVisibleItems`)
* and bounded multi-row wrapping (`maxRows`); the fit/clamp/row-packing math
* lives in the pure `computeOverflow` helper.
*
@@ -136,6 +137,7 @@ export function useOverflow(
const containerElRef = useRef<HTMLElement | null>(null);
const measureElRef = useRef<HTMLElement | null>(null);
const observedElRef = useRef<HTMLElement | null>(null);
+ const observedMeasureElRef = useRef<HTMLElement | null>(null);
const calculate = useCallback(() => {
const container = containerElRef.current;
@@ -236,10 +238,20 @@ export function useOverflow(
const measureRef = useCallback(
(el: HTMLElement | null) => {
+ if (observedMeasureElRef.current) {
+ unobserveResize(observedMeasureElRef.current);
+ observedMeasureElRef.current = null;
+ }
+
measureElRef.current = el;
- if (el) {
- calculate();
+ if (!el) {
+ return;
}
+
+ observeResize(el, () => {
+ calculate();
+ });
+ observedMeasureElRef.current = el;
},
[calculate],
);