An open source design system that's fully customizable and agent ready
TypeScript
overflow (#668)
Andrey Goder80f49e9c2d7a
diff --git a/apps/storybook/stories/OverflowList.stories.tsx b/apps/storybook/stories/OverflowList.stories.tsxnew file mode 100644index 0000000000..a91e8c3eb3--- /dev/null+++ b/apps/storybook/stories/OverflowList.stories.tsx@@ -0,0 +1,305 @@+import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {XDSOverflowList} from '@xds/core/OverflowList';+import {XDSButton} from '@xds/core/Button';+import {XDSBadge} from '@xds/core/Badge';+import {XDSDropdownMenu} from '@xds/core/DropdownMenu';+import {XDSTextInput} from '@xds/core/TextInput';++const meta: Meta<typeof XDSOverflowList> = {+ title: 'Core/XDSOverflowList',+ component: XDSOverflowList,+ tags: ['autodocs'],+ argTypes: {+ gap: {+ control: {type: 'number', min: 0, max: 10},+ description:+ 'Gap between items as a spacing token step (0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10)',+ },+ minVisibleItems: {+ control: {type: 'number', min: 0, max: 10},+ description: 'Minimum number of items to always show',+ },+ collapseFrom: {+ control: 'select',+ options: ['start', 'end'],+ description: 'Which end to collapse items from',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSOverflowList>;++// Basic usage - resize the container to see overflow behavior+export const Default: Story = {+ render: () => (+ <div style={{maxWidth: 400, border: '1px dashed #ccc', padding: 8}}>+ <XDSOverflowList+ gap={2}+ overflowRenderer={overflowItems => (+ <XDSButton+ label={`+${overflowItems.length} more`}+ variant="ghost"+ size="sm"+ />+ )}>+ <XDSButton label="Edit" size="sm" />+ <XDSButton label="Duplicate" size="sm" />+ <XDSButton label="Share" size="sm" />+ <XDSButton label="Archive" size="sm" />+ <XDSButton label="Delete" size="sm" />+ </XDSOverflowList>+ </div>+ ),+};++// Resizable container to interactively test overflow+export const Resizable: Story = {+ render: () => (+ <div+ style={{+ resize: 'horizontal',+ overflow: 'hidden',+ border: '1px dashed #ccc',+ padding: 8,+ width: 500,+ minWidth: 100,+ maxWidth: '100%',+ }}>+ <XDSOverflowList+ gap={2}+ overflowRenderer={overflowItems => (+ <XDSButton+ label={`+${overflowItems.length} more`}+ variant="ghost"+ size="sm"+ />+ )}>+ <XDSButton label="Dashboard" size="sm" />+ <XDSButton label="Analytics" size="sm" />+ <XDSButton label="Reports" size="sm" />+ <XDSButton label="Settings" size="sm" />+ <XDSButton label="Users" size="sm" />+ <XDSButton label="Billing" size="sm" />+ <XDSButton label="Integrations" size="sm" />+ </XDSOverflowList>+ </div>+ ),+};++// All items fit - no overflow indicator shown+export const NoOverflow: Story = {+ render: () => (+ <div style={{maxWidth: 600, border: '1px dashed #ccc', padding: 8}}>+ <XDSOverflowList+ gap={2}+ overflowRenderer={overflowItems => (+ <XDSButton+ label={`+${overflowItems.length} more`}+ variant="ghost"+ size="sm"+ />+ )}>+ <XDSButton label="Edit" size="sm" />+ <XDSButton label="Save" size="sm" />+ </XDSOverflowList>+ </div>+ ),+};++// With badges instead of buttons+export const WithBadges: Story = {+ render: () => (+ <div+ style={{+ resize: 'horizontal',+ overflow: 'hidden',+ border: '1px dashed #ccc',+ padding: 8,+ width: 300,+ minWidth: 80,+ }}>+ <XDSOverflowList+ gap={1}+ overflowRenderer={overflowItems => (+ <XDSBadge variant="neutral">+{overflowItems.length}</XDSBadge>+ )}>+ <XDSBadge variant="info">React</XDSBadge>+ <XDSBadge variant="success">TypeScript</XDSBadge>+ <XDSBadge variant="warning">StyleX</XDSBadge>+ <XDSBadge variant="neutral">Storybook</XDSBadge>+ <XDSBadge variant="error">Vitest</XDSBadge>+ </XDSOverflowList>+ </div>+ ),+};++// Collapse from start+export const CollapseFromStart: Story = {+ render: () => (+ <div style={{maxWidth: 300, border: '1px dashed #ccc', padding: 8}}>+ <XDSOverflowList+ gap={2}+ collapseFrom="start"+ overflowRenderer={overflowItems => (+ <XDSButton+ label={`+${overflowItems.length} more`}+ variant="ghost"+ size="sm"+ />+ )}>+ <XDSButton label="Step 1" size="sm" />+ <XDSButton label="Step 2" size="sm" />+ <XDSButton label="Step 3" size="sm" />+ <XDSButton label="Step 4" size="sm" />+ <XDSButton label="Step 5" size="sm" />+ </XDSOverflowList>+ </div>+ ),+};++// With dropdown menu as overflow indicator+export const WithDropdownOverflow: Story = {+ render: () => {+ const actions = ['Save', 'Edit', 'Duplicate', 'Share', 'Archive', 'Delete'];+ return (+ <div+ style={{+ resize: 'horizontal',+ overflow: 'hidden',+ border: '1px dashed #ccc',+ padding: 8,+ width: 350,+ minWidth: 100,+ maxWidth: '100%',+ }}>+ <XDSOverflowList+ gap={2}+ overflowRenderer={overflowItems => (+ <XDSDropdownMenu+ button={{+ label: `+${overflowItems.length}`,+ variant: 'ghost',+ size: 'sm',+ }}+ items={overflowItems.map(({index}) => ({+ label: actions[index],+ onClick: () => console.log(actions[index]),+ }))}+ />+ )}>+ <XDSButton label="Save" size="sm" variant="primary" />+ <XDSButton label="Edit" size="sm" />+ <XDSButton label="Duplicate" size="sm" />+ <XDSButton label="Share" size="sm" />+ <XDSButton label="Archive" size="sm" />+ <XDSButton label="Delete" size="sm" variant="destructive" />+ </XDSOverflowList>+ </div>+ );+ },+};++// Alongside another element — the input wraps and hides when space is tight+export const WithSiblingElement: Story = {+ render: () => {+ const [search, setSearch] = useState('');+ return (+ <div+ style={{+ resize: 'horizontal',+ overflow: 'hidden',+ border: '1px dashed #ccc',+ minWidth: 100,+ width: 600,+ }}>+ <div+ style={{+ display: 'flex',+ flexWrap: 'wrap',+ alignItems: 'center',+ gap: 8,+ padding: 8,+ height: 44,+ }}>+ <XDSOverflowList+ gap={2}+ behavior="observeParent"+ overflowRenderer={overflowItems => (+ <XDSButton+ label={`+${overflowItems.length} more`}+ variant="ghost"+ size="sm"+ />+ )}>+ <XDSButton label="Dashboard" size="sm" />+ <XDSButton label="Analytics" size="sm" />+ <XDSButton label="Reports" size="sm" />+ <XDSButton label="Settings" size="sm" />+ <XDSButton label="Users" size="sm" />+ <XDSButton label="Billing" size="sm" />+ </XDSOverflowList>+ <div style={{width: 70, flexShrink: 0}}>+ <XDSTextInput+ label="Search"+ isLabelHidden+ placeholder="Search..."+ size="sm"+ value={search}+ onChange={setSearch}+ />+ </div>+ </div>+ </div>+ );+ },+};++// Dynamic items+export const DynamicItems: Story = {+ render: () => {+ const [count, setCount] = useState(5);+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>+ <div style={{display: 'flex', gap: 8, alignItems: 'center'}}>+ <XDSButton+ label="Remove"+ size="sm"+ onClick={() => setCount(c => Math.max(1, c - 1))}+ />+ <XDSButton+ label="Add"+ size="sm"+ onClick={() => setCount(c => c + 1)}+ />+ <span>{count} items</span>+ </div>+ <div+ style={{+ resize: 'horizontal',+ overflow: 'hidden',+ border: '1px dashed #ccc',+ padding: 8,+ width: 400,+ minWidth: 100,+ maxWidth: '100%',+ }}>+ <XDSOverflowList+ gap={2}+ overflowRenderer={items => (+ <XDSButton+ label={`+${items.length} more`}+ variant="ghost"+ size="sm"+ />+ )}>+ {Array.from({length: count}, (_, i) => (+ <XDSButton key={i} label={`Item ${i + 1}`} size="sm" />+ ))}+ </XDSOverflowList>+ </div>+ </div>+ );+ },+};diff --git a/packages/core/package.json b/packages/core/package.jsonindex 17497cef22..4847f760a3 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -220,6 +220,12 @@"import": "./dist/NumberInput/index.mjs","require": "./dist/NumberInput/index.js"},+ "./OverflowList": {+ "source": "./src/OverflowList/index.ts",+ "types": "./dist/OverflowList/index.d.ts",+ "import": "./dist/OverflowList/index.mjs",+ "require": "./dist/OverflowList/index.js"+ },"./Pagination": {"source": "./src/Pagination/index.ts","types": "./dist/Pagination/index.d.ts",diff --git a/packages/core/src/OverflowList/XDSOverflowList.tsx b/packages/core/src/OverflowList/XDSOverflowList.tsxnew file mode 100644index 0000000000..16f95c0b27--- /dev/null+++ b/packages/core/src/OverflowList/XDSOverflowList.tsx@@ -0,0 +1,277 @@+/**+ * @file XDSOverflowList.tsx+ * @input Uses React, StyleX, useOverflow hook+ * @output Exports XDSOverflowList component and XDSOverflowListProps type+ * @position Core implementation; consumed by index.ts+ *+ * Renders a horizontal list of items, hiding those that don't fit in the+ * available width and optionally showing an overflow indicator.+ * Uses a hidden measurement container to avoid flickering.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/OverflowList/index.ts (exports if types change)+ */++'use client';++import {type ReactNode, type ReactElement, Children} from 'react';+import type {XDSBaseProps} from '../XDSBaseProps';+import type {SpacingStep} from '../utils/types';+import * as stylex from '@stylexjs/stylex';+import {xdsClassName, mergeProps} from '../utils';+import {useOverflow} from '../hooks/useOverflow';+import {spacingVars} from '../theme/tokens.stylex';++const styles = stylex.create({+ container: {+ display: 'flex',+ alignItems: 'center',+ overflow: 'hidden',+ whiteSpace: 'nowrap',+ minWidth: 0,+ },+ fillParent: {+ width: '100%',+ },+ measureContainer: {+ position: 'absolute',+ visibility: 'hidden',+ height: 0,+ overflow: 'hidden',+ display: 'flex',+ alignItems: 'center',+ whiteSpace: 'nowrap',+ pointerEvents: 'none',+ },+ measureIndicator: {+ display: 'inline-flex',+ },+});++const gapStyles = stylex.create({+ 0: {gap: spacingVars['--spacing-0']},+ 0.5: {gap: spacingVars['--spacing-0-5']},+ 1: {gap: spacingVars['--spacing-1']},+ 1.5: {gap: spacingVars['--spacing-1-5']},+ 2: {gap: spacingVars['--spacing-2']},+ 3: {gap: spacingVars['--spacing-3']},+ 4: {gap: spacingVars['--spacing-4']},+ 5: {gap: spacingVars['--spacing-5']},+ 6: {gap: spacingVars['--spacing-6']},+ 8: {gap: spacingVars['--spacing-8']},+ 10: {gap: spacingVars['--spacing-10']},+});++/**+ * Maps spacing token steps to pixel values for overflow calculations.+ */+const spacingToPx: Record<SpacingStep, number> = {+ 0: 0,+ 0.5: 2,+ 1: 4,+ 1.5: 6,+ 2: 8,+ 3: 12,+ 4: 16,+ 5: 20,+ 6: 24,+ 8: 32,+ 10: 40,+};++export interface XDSOverflowItem {+ /** The React element for this item */+ child: ReactElement;+ /** The index of this item in the original children list */+ index: number;+}++export interface XDSOverflowListProps extends XDSBaseProps<HTMLDivElement> {+ /** Ref forwarded to the visible container element */+ ref?: React.Ref<HTMLDivElement>;++ /**+ * The items to render. Each child should be a single element.+ */+ children: ReactNode;++ /**+ * Gap between items as a spacing token step.+ * Accepts: 0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10+ * @default 2+ */+ gap?: SpacingStep;++ /**+ * Minimum number of items to always show.+ * @default 0+ */+ minVisibleItems?: number;++ /**+ * Which end to collapse items from.+ * @default 'end'+ */+ collapseFrom?: 'start' | 'end';++ /**+ * Which element to observe for overflow calculations.+ * - `'observeSelf'`: uses the container's own width (default)+ * - `'observeParent'`: observes the parent element's content width+ * for overflow calculations. This keeps the overflow list+ * content-sized while still detecting available space for+ * grow-back. Siblings that don't fit can wrap and be clipped by+ * the parent's overflow.+ * @default 'observeSelf'+ */+ behavior?: 'observeParent' | 'observeSelf';++ /**+ * Render function for the overflow indicator. Receives the list of+ * items that are not visible, each with its original index. Only called+ * when there are overflowing items.+ *+ * The indicator is automatically measured in a hidden container to+ * reserve the correct amount of space.+ *+ * @example+ * ```+ * const labels = ['Save', 'Edit', 'Share'];+ * <XDSOverflowList+ * overflowRenderer={(overflowItems) => (+ * <XDSDropdownMenu+ * button={{label: `+${overflowItems.length}`, variant: 'ghost'}}+ * items={overflowItems.map(({index}) => ({ label: labels[index] }))}+ * />+ * )}+ * >+ * {labels.map(l => <XDSButton key={l} label={l} />)}+ * </XDSOverflowList>+ * ```+ */+ overflowRenderer?: (overflowItems: XDSOverflowItem[]) => ReactNode;+}++/**+ * A horizontal list that hides items that don't fit and shows an overflow indicator.+ *+ * Uses a hidden measurement container to determine which items fit without+ * causing visual flickering. The overflow indicator is also measured+ * automatically so no manual width value is needed.+ *+ * @example+ * ```+ * <XDSOverflowList+ * gap={2}+ * overflowRenderer={(items) => (+ * <XDSButton label={`+${items.length} more`} variant="ghost" />+ * )}+ * >+ * <XDSButton label="Action 1" />+ * <XDSButton label="Action 2" />+ * <XDSButton label="Action 3" />+ * <XDSButton label="Action 4" />+ * </XDSOverflowList>+ * ```+ */+export function XDSOverflowList({+ children,+ gap = 2,+ minVisibleItems = 0,+ collapseFrom = 'end',+ behavior = 'observeSelf',+ overflowRenderer,+ xstyle,+ className,+ style,+ ref,+ ...props+}: XDSOverflowListProps) {+ const childArray = Children.toArray(children) as ReactElement[];+ const itemCount = childArray.length;++ const gapPx = spacingToPx[gap];++ const observeParent = behavior === 'observeParent';++ const {containerRef, measureRef, visibleCount, hasOverflow} = useOverflow(+ itemCount,+ {+ gap: gapPx,+ minVisibleItems,+ collapseFrom,+ behavior,+ },+ );++ const allItems: XDSOverflowItem[] = childArray.map((child, index) => ({+ child,+ index,+ }));++ let visibleItems: XDSOverflowItem[];+ let overflowItems: XDSOverflowItem[];++ if (collapseFrom === 'end') {+ visibleItems = allItems.slice(0, visibleCount);+ overflowItems = allItems.slice(visibleCount);+ } else {+ visibleItems = allItems.slice(itemCount - visibleCount);+ overflowItems = allItems.slice(0, itemCount - visibleCount);+ }++ // Render a placeholder for measurement — uses all items as overflow+ // so the indicator renders at its maximum possible width.+ const measureIndicator = overflowRenderer?.(allItems);++ return (+ <>+ {/* Hidden measurement container */}+ <div+ ref={measureRef}+ aria-hidden="true"+ inert+ {...stylex.props(styles.measureContainer, gapStyles[gap])}>+ {childArray}+ {measureIndicator != null && (+ <div {...stylex.props(styles.measureIndicator)}>+ {measureIndicator}+ </div>+ )}+ </div>++ {/* Visible container */}+ <div+ ref={el => {+ containerRef(el);+ if (typeof ref === 'function') {+ ref(el);+ } else if (ref) {+ (ref as React.MutableRefObject<HTMLDivElement | null>).current = el;+ }+ }}+ {...mergeProps(+ xdsClassName('overflow-list'),+ stylex.props(+ styles.container,+ gapStyles[gap],+ observeParent && hasOverflow && styles.fillParent,+ xstyle,+ ),+ className,+ style,+ )}+ {...props}>+ {collapseFrom === 'start' &&+ hasOverflow &&+ overflowRenderer?.(overflowItems)}+ {visibleItems.map(({child}) => child)}+ {collapseFrom === 'end' &&+ hasOverflow &&+ overflowRenderer?.(overflowItems)}+ </div>+ </>+ );+}++XDSOverflowList.displayName = 'XDSOverflowList';diff --git a/packages/core/src/OverflowList/index.ts b/packages/core/src/OverflowList/index.tsnew file mode 100644index 0000000000..cb0eb13432--- /dev/null+++ b/packages/core/src/OverflowList/index.ts@@ -0,0 +1,6 @@+/**+ * @file OverflowList component barrel export+ */++export {XDSOverflowList} from './XDSOverflowList';+export type {XDSOverflowListProps, XDSOverflowItem} from './XDSOverflowList';diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 0de3772e86..afb387fd04 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -17,3 +17,6 @@ export {useListFocus} from './useListFocus';export type {UseListFocusOptions, UseListFocusReturn} from './useListFocus';export {useMediaQuery} from './useMediaQuery';++export {useOverflow} from './useOverflow';+export type {UseOverflowOptions, UseOverflowReturn} from './useOverflow';diff --git a/packages/core/src/hooks/useOverflow.test.ts b/packages/core/src/hooks/useOverflow.test.tsnew file mode 100644index 0000000000..92450c7a7b--- /dev/null+++ b/packages/core/src/hooks/useOverflow.test.ts@@ -0,0 +1,413 @@+import {describe, it, expect, vi, beforeEach} from 'vitest';+import {renderHook, act} from '@testing-library/react';+import {useOverflow} from './useOverflow';++// Builds a mock container element with a given offsetWidth+function mockContainer(width: number): HTMLElement {+ return {offsetWidth: width} as unknown as HTMLElement;+}++// Builds a mock measure element whose children have the given widths.+// If indicatorWidth is provided, an extra child is appended as the overflow indicator.+function mockMeasure(+ itemWidths: number[],+ indicatorWidth?: number,+): HTMLElement {+ const children: Array<{offsetWidth: number}> = itemWidths.map(w => ({+ offsetWidth: w,+ }));+ if (indicatorWidth != null) {+ children.push({offsetWidth: indicatorWidth});+ }+ return {children} as unknown as HTMLElement;+}++// Stubs ResizeObserver — fires callback immediately on observe, like the real one+class FakeResizeObserver {+ callback: ResizeObserverCallback;+ constructor(cb: ResizeObserverCallback) {+ this.callback = cb;+ }+ observe = vi.fn(() => {+ this.callback([], this as unknown as ResizeObserver);+ });+ unobserve = vi.fn();+ disconnect = vi.fn();+}++beforeEach(() => {+ vi.stubGlobal('ResizeObserver', FakeResizeObserver);+});++describe('useOverflow', () => {+ it('shows all items when they fit', () => {+ // 3 items of 50px each, gap 10 → total = 50+10+50+10+50 = 170, container = 200+ const {result} = renderHook(() => useOverflow(3, {gap: 10}));++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50]));+ result.current.containerRef(mockContainer(200));+ });++ expect(result.current.visibleCount).toBe(3);+ expect(result.current.hasOverflow).toBe(false);+ });++ it('hides items that do not fit', () => {+ // 4 items of 50px, gap 10, indicator 30px, container 150+ // Item 1: 50, not last → reserve 30+10=40 → 50+40=90 ≤ 150 ✓ (total=50)+ // Item 2: 50+10+50=110, not last → reserve 40 → 110+40=150 ≤ 150 ✓ (total=110)+ // Item 3: 110+10+50=170, not last → reserve 40 → 170+40=210 > 150 ✗+ // → visibleCount = 2+ const {result} = renderHook(() => useOverflow(4, {gap: 10}));++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50, 50], 30));+ result.current.containerRef(mockContainer(150));+ });++ expect(result.current.visibleCount).toBe(2);+ expect(result.current.hasOverflow).toBe(true);+ });++ it('shows zero items when nothing fits and minVisibleItems is 0', () => {+ // 3 items of 100px, container 50, indicator 30+ // Item 1: 100, not last → reserve 30+0=30 → 100+30=130 > 50, count=0 ≥ min(0) → break+ const {result} = renderHook(() => useOverflow(3, {gap: 0}));++ act(() => {+ result.current.measureRef(mockMeasure([100, 100, 100], 30));+ result.current.containerRef(mockContainer(50));+ });++ expect(result.current.visibleCount).toBe(0);+ expect(result.current.hasOverflow).toBe(true);+ });++ it('respects minVisibleItems even when items do not fit', () => {+ // 3 items of 100px, container 50, indicator 30, minVisibleItems 2+ // Item 1: 100 > 50+reserved, but count(0) < min(2) → continue+ // Item 2: 200 > 50, but count(1) < min(2) → continue+ // Item 3: last item (i=2, length=3) → reservedWidth=0 → 300 > 50, count(2) ≥ min(2) → break+ // → visibleCount = max(min(2, 3), 2) = 2+ const {result} = renderHook(() =>+ useOverflow(3, {gap: 0, minVisibleItems: 2}),+ );++ act(() => {+ result.current.measureRef(mockMeasure([100, 100, 100], 30));+ result.current.containerRef(mockContainer(50));+ });++ expect(result.current.visibleCount).toBe(2);+ expect(result.current.hasOverflow).toBe(true);+ });++ it('handles no gap', () => {+ // 3 items of 40px, no gap → total = 120, container = 100, indicator = 20+ // Item 1: 40, not last → reserve 20+0=20 → 40+20=60 ≤ 100 ✓ (total=40)+ // Item 2: 40+40=80, not last → reserve 20+20=40... wait+ // gap=0, so gapWidth for i>0 is 0. reservedWidth = indicatorWidth + (count>0 ? gap : 0)+ // gap=0, so reservedWidth = 20 + 0 = 20+ // Item 2: 80, reserve 20 → 100 ≤ 100 ✓ (total=80)+ // Item 3: 120, last → reserve 0 → 120 > 100, count(2) ≥ 0 → break+ // → visibleCount = 2+ const {result} = renderHook(() => useOverflow(3, {gap: 0}));++ act(() => {+ result.current.measureRef(mockMeasure([40, 40, 40], 20));+ result.current.containerRef(mockContainer(100));+ });++ expect(result.current.visibleCount).toBe(2);+ expect(result.current.hasOverflow).toBe(true);+ });++ it('works without an overflow indicator', () => {+ // 3 items of 50px, gap 10, no indicator, container 130+ // total needed = 50+10+50+10+50 = 170 > 130+ // Item 1: 50, not last → reserve 0 → 50 ≤ 130 ✓+ // Item 2: 110, not last → reserve 0 → 110 ≤ 130 ✓+ // Item 3: 170, last → reserve 0 → 170 > 130 → break+ // → visibleCount = 2+ const {result} = renderHook(() => useOverflow(3, {gap: 10}));++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50]));+ result.current.containerRef(mockContainer(130));+ });++ expect(result.current.visibleCount).toBe(2);+ expect(result.current.hasOverflow).toBe(true);+ });++ it('handles items with different widths', () => {+ // Items: 30, 80, 40, 60. Gap 10. Indicator 25. Container 200.+ // Item 1 (30): not last → reserve 25+0=25 → 30+25=55 ≤ 200 ✓ (total=30)+ // Item 2 (80): 30+10+80=120, not last → reserve 25+10=35 → 120+35=155 ≤ 200 ✓ (total=120)+ // Item 3 (40): 120+10+40=170, not last → reserve 35 → 170+35=205 > 200 → break+ // → visibleCount = 2+ const {result} = renderHook(() => useOverflow(4, {gap: 10}));++ act(() => {+ result.current.measureRef(mockMeasure([30, 80, 40, 60], 25));+ result.current.containerRef(mockContainer(200));+ });++ expect(result.current.visibleCount).toBe(2);+ expect(result.current.hasOverflow).toBe(true);+ });++ it('collapses from start', () => {+ // Items: 30, 80, 40. Gap 10. Indicator 25. Container 100.+ // collapseFrom='start' reverses widths → ordered: [40, 80, 30]+ // Item 1 (40): not last → reserve 25+0=25 → 40+25=65 ≤ 100 ✓ (total=40)+ // Item 2 (80): 40+10+80=130, not last → reserve 25+10=35 → 130+35=165 > 100 → break+ // → visibleCount = 1 (the last 1 item is kept visible)+ const {result} = renderHook(() =>+ useOverflow(3, {gap: 10, collapseFrom: 'start'}),+ );++ act(() => {+ result.current.measureRef(mockMeasure([30, 80, 40], 25));+ result.current.containerRef(mockContainer(100));+ });++ expect(result.current.visibleCount).toBe(1);+ expect(result.current.hasOverflow).toBe(true);+ });++ it('handles zero children', () => {+ const {result} = renderHook(() => useOverflow(0));++ act(() => {+ result.current.measureRef(mockMeasure([]));+ result.current.containerRef(mockContainer(200));+ });++ expect(result.current.visibleCount).toBe(0);+ expect(result.current.hasOverflow).toBe(false);+ });++ it('shows all items when exact fit with indicator not needed', () => {+ // 3 items of 50px, gap 10 → total = 170, container = 170, indicator present+ // Item 1 (50): not last → reserve 30+0=30 → 50+30=80 ≤ 170 ✓ (total=50)+ // Item 2 (50): 50+10+50=110, not last → reserve 30+10=40 → 110+40=150 ≤ 170 ✓ (total=110)+ // Item 3 (50): 110+10+50=170, last → reserve 0 → 170 ≤ 170 ✓ (total=170)+ // → visibleCount = 3, all fit so no overflow+ const {result} = renderHook(() => useOverflow(3, {gap: 10}));++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50], 30));+ result.current.containerRef(mockContainer(170));+ });++ expect(result.current.visibleCount).toBe(3);+ expect(result.current.hasOverflow).toBe(false);+ });++ it('recalculates when container resizes', () => {+ const {result} = renderHook(() => useOverflow(3, {gap: 10}));++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50], 30));+ result.current.containerRef(mockContainer(170));+ });++ expect(result.current.visibleCount).toBe(3);++ // Simulate resize by calling containerRef with a smaller container+ act(() => {+ result.current.containerRef(mockContainer(100));+ });++ expect(result.current.visibleCount).toBe(1);+ expect(result.current.hasOverflow).toBe(true);+ });++ it('cleans up ResizeObserver on unmount', () => {+ const {result, unmount} = renderHook(() => useOverflow(3));++ const container = mockContainer(200);+ act(() => {+ result.current.containerRef(container);+ });++ // Get the observer that was created+ const observer = (+ FakeResizeObserver as unknown as {mock: {instances: FakeResizeObserver[]}}+ ).mock?.instances;+ // Instead, check disconnect is called when ref is set to null+ act(() => {+ result.current.containerRef(null);+ });++ // Setting ref to null should disconnect the previous observer+ unmount();+ });++ it('single item that fits', () => {+ const {result} = renderHook(() => useOverflow(1, {gap: 10}));++ act(() => {+ result.current.measureRef(mockMeasure([50]));+ result.current.containerRef(mockContainer(100));+ });++ expect(result.current.visibleCount).toBe(1);+ expect(result.current.hasOverflow).toBe(false);+ });++ it('does not re-render when visibleCount stays the same', () => {+ let renderCount = 0;+ const {result} = renderHook(() => {+ renderCount++;+ return useOverflow(3, {gap: 10});+ });++ const initialRenderCount = renderCount;++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50]));+ result.current.containerRef(mockContainer(200));+ });++ // All items fit (visibleCount stays 3 = initial), so no state change → no extra render+ expect(renderCount).toBe(initialRenderCount);+ expect(result.current.visibleCount).toBe(3);+ });++ it('renders exactly once more when visibleCount changes', () => {+ let renderCount = 0;+ const {result} = renderHook(() => {+ renderCount++;+ return useOverflow(4, {gap: 10});+ });++ const afterInitialRender = renderCount;++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50, 50], 30));+ result.current.containerRef(mockContainer(150));+ });++ // visibleCount changes from 4 → 2, so exactly one additional render+ expect(renderCount).toBe(afterInitialRender + 1);+ expect(result.current.visibleCount).toBe(2);+ });++ it('does not re-render on resize when visibleCount is unchanged', () => {+ let renderCount = 0;+ const {result} = renderHook(() => {+ renderCount++;+ return useOverflow(3, {gap: 10});+ });++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50]));+ result.current.containerRef(mockContainer(200));+ });++ const afterSetup = renderCount;++ // Resize to a still-large-enough container — visibleCount stays 3+ act(() => {+ result.current.containerRef(mockContainer(300));+ });++ expect(renderCount).toBe(afterSetup);+ expect(result.current.visibleCount).toBe(3);+ });++ it('single item that does not fit without minVisibleItems', () => {+ const {result} = renderHook(() => useOverflow(1, {gap: 0}));++ act(() => {+ result.current.measureRef(mockMeasure([200], 30));+ result.current.containerRef(mockContainer(100));+ });++ // Single item is the last item, so reservedWidth=0 → 200 > 100 → break at count=0+ expect(result.current.visibleCount).toBe(0);+ expect(result.current.hasOverflow).toBe(true);+ });+});++describe('useOverflow with behavior=observeParent', () => {+ function mockContainerWithParent(+ parentWidth: number,+ parentPadding = 0,+ ): HTMLElement {+ const container = {offsetWidth: 0} as unknown as HTMLElement;++ const parent = {clientWidth: parentWidth};++ vi.stubGlobal('getComputedStyle', () => ({+ paddingLeft: `${parentPadding}px`,+ paddingRight: `${parentPadding}px`,+ }));++ Object.defineProperty(container, 'parentElement', {+ value: parent,+ configurable: true,+ });++ return container;+ }++ it('uses parent content width as available space', () => {+ // Parent: 400px wide, 8px padding each side → available = 384+ // 4 items of 50px, gap 10 → total = 230 ≤ 384 → all fit+ const {result} = renderHook(() =>+ useOverflow(4, {gap: 10, behavior: 'observeParent'}),+ );++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50, 50], 30));+ result.current.containerRef(mockContainerWithParent(400, 8));+ });++ expect(result.current.visibleCount).toBe(4);+ expect(result.current.hasOverflow).toBe(false);+ });++ it('overflows when parent content width is too small', () => {+ // Parent: 200px, padding 8 each side → available = 184+ // 4 items of 50px, gap 10, indicator 30+ // Item 1 (50): reserve 30 → 80 ≤ 184 ✓+ // Item 2 (50): 110, reserve 40 → 150 ≤ 184 ✓+ // Item 3 (50): 170, reserve 40 → 210 > 184 → break+ // → visibleCount = 2+ const {result} = renderHook(() =>+ useOverflow(4, {gap: 10, behavior: 'observeParent'}),+ );++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50, 50], 30));+ result.current.containerRef(mockContainerWithParent(200, 8));+ });++ expect(result.current.visibleCount).toBe(2);+ expect(result.current.hasOverflow).toBe(true);+ });++ it('accounts for parent padding', () => {+ // Parent: 200px, padding 40 each side → available = 120+ // 3 items of 50px, gap 10, no indicator → total = 170 > 120+ // Item 1 (50): not last, reserve 0 → 50 ≤ 120 ✓+ // Item 2 (50): 110, not last, reserve 0 → 110 ≤ 120 ✓+ // Item 3 (50): 170, last, reserve 0 → 170 > 120 → break+ // → visibleCount = 2+ const {result} = renderHook(() =>+ useOverflow(3, {gap: 10, behavior: 'observeParent'}),+ );++ act(() => {+ result.current.measureRef(mockMeasure([50, 50, 50]));+ result.current.containerRef(mockContainerWithParent(200, 40));+ });++ expect(result.current.visibleCount).toBe(2);+ expect(result.current.hasOverflow).toBe(true);+ });+});diff --git a/packages/core/src/hooks/useOverflow.ts b/packages/core/src/hooks/useOverflow.tsnew file mode 100644index 0000000000..fd405bbdf0--- /dev/null+++ b/packages/core/src/hooks/useOverflow.ts@@ -0,0 +1,214 @@+/**+ * @file useOverflow.ts+ * @input Uses React useState, useLayoutEffect, useCallback, useRef+ * @output Exports useOverflow hook for measuring and managing horizontal overflow+ * @position Core hook; used by XDSOverflowList 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.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/index.ts+ */++'use client';++import {useState, useLayoutEffect, useCallback, useRef} from 'react';++export interface UseOverflowOptions {+ /**+ * Gap between items in pixels. Used in width calculations.+ * @default 0+ */+ gap?: number;++ /**+ * Minimum number of items to always show, even if they don't fit.+ * @default 0+ */+ minVisibleItems?: number;++ /**+ * Which end to collapse items from.+ * @default 'end'+ */+ collapseFrom?: 'start' | 'end';++ /**+ * Which element to observe for overflow calculations.+ * - `'observeSelf'`: uses the container's own width (default)+ * - `'observeParent'`: observes the container's parent element for+ * resize and uses the parent's content width. This allows the+ * visible container to remain content-sized while still detecting+ * available space for grow-back. Siblings that don't fit alongside+ * the items can wrap and be clipped by the parent's overflow.+ * @default 'observeSelf'+ */+ behavior?: 'observeParent' | 'observeSelf';+}++export interface UseOverflowReturn {+ /** Ref to attach to the visible container element */+ containerRef: React.RefCallback<HTMLElement>;+ /** Ref to attach to the hidden measurement container */+ measureRef: React.RefCallback<HTMLElement>;+ /** Number of items that fit in the visible container */+ visibleCount: number;+ /** Whether any items are overflowing */+ hasOverflow: boolean;+}++/**+ * Hook for managing horizontal overflow of a list of items.+ *+ * Renders all items into a hidden measurement container, then calculates+ * how many fit in the visible container's width. Uses ResizeObserver to+ * recalculate when the container resizes.+ *+ * The measurement container should contain all items followed by the+ * overflow indicator element (if any). The indicator is identified by+ * a `data-overflow-indicator` attribute.+ *+ * @example+ * ```+ * const { containerRef, measureRef, visibleCount, hasOverflow } = useOverflow(5, {+ * gap: 8,+ * });+ * ```+ */+export function useOverflow(+ itemCount: number,+ options: UseOverflowOptions = {},+): UseOverflowReturn {+ const {+ gap = 0,+ minVisibleItems = 0,+ collapseFrom = 'end',+ behavior = 'observeSelf',+ } = options;++ const observeParent = behavior === 'observeParent';++ const [visibleCount, setVisibleCount] = useState(itemCount);+ const containerElRef = useRef<HTMLElement | null>(null);+ const measureElRef = useRef<HTMLElement | null>(null);+ const observerRef = useRef<ResizeObserver | null>(null);++ const calculate = useCallback(() => {+ const container = containerElRef.current;+ const measure = measureElRef.current;+ if (!container || !measure) return;++ 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) {+ setVisibleCount(0);+ return;+ }++ // Collect widths of all children+ const widths = children.map(child => child.offsetWidth);++ // Determine how many items fit+ let totalWidth = 0;+ let count = 0;++ const orderedWidths =+ collapseFrom === 'end' ? widths : [...widths].reverse();++ for (let i = 0; i < orderedWidths.length; i++) {+ const itemWidth = orderedWidths[i];+ const gapWidth = i > 0 ? gap : 0;+ const candidateWidth = totalWidth + itemWidth + gapWidth;++ // If this isn't the last item, we need to reserve space for the indicator+ const isLastItem = i === orderedWidths.length - 1;+ const reservedWidth = isLastItem+ ? 0+ : indicatorWidth + (count > 0 || indicatorWidth > 0 ? gap : 0);++ if (+ candidateWidth + reservedWidth > availableWidth &&+ count >= minVisibleItems+ ) {+ break;+ }++ totalWidth = candidateWidth;+ count++;+ }++ setVisibleCount(Math.max(Math.min(count, itemCount), minVisibleItems));+ }, [itemCount, gap, minVisibleItems, collapseFrom, observeParent]);++ const containerRef = useCallback(+ (el: HTMLElement | null) => {+ containerElRef.current = el;++ // Clean up previous observer+ if (observerRef.current) {+ observerRef.current.disconnect();+ observerRef.current = null;+ }++ if (el) {+ const ro = new ResizeObserver(() => {+ calculate();+ });+ const target =+ observeParent && el.parentElement ? el.parentElement : el;+ ro.observe(target);+ observerRef.current = ro;+ }+ },+ [calculate, observeParent],+ );++ const measureRef = useCallback(+ (el: HTMLElement | null) => {+ measureElRef.current = el;+ if (el) {+ calculate();+ }+ },+ [calculate],+ );++ // Recalculate when itemCount changes+ useLayoutEffect(() => {+ calculate();+ }, [calculate]);++ const hasOverflow = visibleCount < itemCount;++ return {+ containerRef,+ measureRef,+ visibleCount,+ hasOverflow,+ };+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 2f45343a92..7f02ba4093 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -97,6 +97,9 @@ export * from './StatusDot';// Spinner loading indicatorexport * from './Spinner';+// Overflow list+export * from './OverflowList';+// Hooksexport * from './hooks';