An open source design system that's fully customizable and agent ready
TypeScript
feat(core): TabList scrolls when the tabs are wider than the strip (#5348)
Cindy Zhang0da2f5b0e17b
diff --git a/.changeset/tablist-scroll-overflow.md b/.changeset/tablist-scroll-overflow.mdnew file mode 100644index 0000000000..1f7e0d63eb--- /dev/null+++ b/.changeset/tablist-scroll-overflow.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[feat] TabList: a strip narrower than its tabs now scrolls instead of spilling out of its container. Every tab stays a tab — nothing is hidden behind a menu — the edges fade to show there is more, and pointers that can hover get arrow affordances; keyboard and screen-reader users reach every tab with the arrow keys, which scrolls the focused tab into view. The selected tab is scrolled back into view whenever it would be out of sight, including on mount and when the host changes `value` itself. The new `overflow` prop takes `'auto'` (the default, which today always scrolls), `'scroll'`, or `'visible'` to keep the old spill-out layout. Built on the existing `useScrollOverflow` hook, so there is no new measurement machinery and no `Carousel` in the tab strip — the documented Carousel recipe, which announced every tab as "slide N of M", is no longer needed and the stories now use the built-in behaviour.++If you followed that recipe, nothing breaks: a `Carousel` still wrapping the tabs renders and behaves exactly as it did before, because its own scroll container absorbs the strip's, which then never overflows. Removing it is worth doing anyway — it drops the `region`/"slide N of M" wrapping from the accessibility tree, and the strip's own scrolling brings a tab that straddles the edge fully into view on focus, which the carousel does not.++@cixzhangdiff --git a/apps/storybook/stories/TabList.stories.tsx b/apps/storybook/stories/TabList.stories.tsxindex 3948142618..880bd87fd6 100644--- a/apps/storybook/stories/TabList.stories.tsx+++ b/apps/storybook/stories/TabList.stories.tsx@@ -3,7 +3,6 @@import {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {TabList, Tab, TabMenu} from '@astryxdesign/core/TabList';-import {Carousel} from '@astryxdesign/core/Carousel';import {Button} from '@astryxdesign/core/Button';import {PlusIcon, FunnelIcon} from '@heroicons/react/24/outline';@@ -300,9 +299,10 @@ export const FillLayout: Story = {};/**- * When tabs overflow, wrap TabList's children in Carousel.- * The Carousel handles scroll, fade masks, and arrow buttons.- * Each tab keeps its intrinsic label width — no truncation.+ * A strip narrower than its tabs scrolls. Every tab stays a tab — nothing is+ * hidden behind a menu — and the edges fade to show there is more. Pointers+ * that can hover also get arrow affordances; keyboard users reach every tab+ * with the arrow keys, which scrolls the focused tab into view.*/export const Overflow: Story = {render: () => {@@ -310,7 +310,55 @@ export const Overflow: Story = {return (<div style={{maxWidth: '400px', border: '1px dashed #ccc'}}><TabList value={value} onChange={setValue}>- <Carousel gap={0.5} hasSnap={false}>+ <Tab value="overview" label="Overview" />+ <Tab value="activity" label="Activity" />+ <Tab value="members" label="Members" />+ <Tab value="settings" label="Settings" />+ <Tab value="integrations" label="Integrations" />+ <Tab value="billing" label="Billing & Plans" />+ <Tab value="security" label="Security" />+ <Tab value="notifications" label="Notifications" />+ <Tab value="api" label="API Keys" />+ </TabList>+ </div>+ );+ },+};++/**+ * Overflow with divider — typical page header in a narrow viewport. The+ * selected indicator still sits on the rail while the strip scrolls.+ */+export const OverflowWithDivider: Story = {+ render: () => {+ const [value, setValue] = useState('dashboard');+ return (+ <div style={{maxWidth: '350px'}}>+ <TabList value={value} onChange={setValue} hasDivider size="lg">+ <Tab value="dashboard" label="Dashboard" />+ <Tab value="analytics" label="Analytics" />+ <Tab value="reports" label="Reports" />+ <Tab value="customers" label="Customers" />+ <Tab value="products" label="Products" />+ <Tab value="orders" label="Orders" />+ </TabList>+ </div>+ );+ },+};++/**+ * A tab selected while it is out of view is scrolled back in — on mount and+ * whenever the host changes `value` itself.+ */+export const OverflowSelectedOffscreen: Story = {+ render: () => {+ const [value, setValue] = useState('api');+ return (+ <div+ style={{display: 'grid', gap: '8px', maxWidth: '400px', minWidth: 0}}>+ <div style={{border: '1px dashed #ccc', minWidth: 0}}>+ <TabList value={value} onChange={setValue}><Tab value="overview" label="Overview" /><Tab value="activity" label="Activity" /><Tab value="members" label="Members" />@@ -320,30 +368,46 @@ export const Overflow: Story = {<Tab value="security" label="Security" /><Tab value="notifications" label="Notifications" /><Tab value="api" label="API Keys" />- </Carousel>- </TabList>+ </TabList>+ </div>+ <div style={{display: 'flex', gap: '4px'}}>+ <Button+ label="Select first"+ variant="secondary"+ size="sm"+ onClick={() => setValue('overview')}+ />+ <Button+ label="Select last"+ variant="secondary"+ size="sm"+ onClick={() => setValue('api')}+ />+ </div></div>);},};/**- * Overflow with divider — typical page header in a narrow viewport.+ * `overflow="visible"` opts out: the tabs keep their intrinsic widths and spill+ * out of the strip, for a host that handles overflow itself.*/-export const OverflowWithDivider: Story = {+export const OverflowVisible: Story = {render: () => {- const [value, setValue] = useState('dashboard');+ const [value, setValue] = useState('overview');return (- <div style={{maxWidth: '350px'}}>- <TabList value={value} onChange={setValue} hasDivider size="lg">- <Carousel gap={0.5} hasSnap={false}>- <Tab value="dashboard" label="Dashboard" />- <Tab value="analytics" label="Analytics" />- <Tab value="reports" label="Reports" />- <Tab value="customers" label="Customers" />- <Tab value="products" label="Products" />- <Tab value="orders" label="Orders" />- </Carousel>+ <div style={{maxWidth: '400px', border: '1px dashed #ccc'}}>+ <TabList value={value} onChange={setValue} overflow="visible">+ <Tab value="overview" label="Overview" />+ <Tab value="activity" label="Activity" />+ <Tab value="members" label="Members" />+ <Tab value="settings" label="Settings" />+ <Tab value="integrations" label="Integrations" />+ <Tab value="billing" label="Billing & Plans" />+ <Tab value="security" label="Security" />+ <Tab value="notifications" label="Notifications" />+ <Tab value="api" label="API Keys" /></TabList></div>);diff --git a/packages/core/src/TabList/TabList.doc.mjs b/packages/core/src/TabList/TabList.doc.mjsindex 8ca233fbc6..e9932aea57 100644--- a/packages/core/src/TabList/TabList.doc.mjs+++ b/packages/core/src/TabList/TabList.doc.mjs@@ -16,6 +16,8 @@ export const docs = {theming: {targets: [{className: 'astryx-tab-list', visualProps: ['size']},+ {className: 'astryx-tab-strip'},+ {className: 'astryx-tab-scroll-button'},{className: 'astryx-tab', states: ['selected']},{className: 'astryx-tab-indicator', states: ['selected']},{className: 'astryx-tab-menu'},@@ -58,6 +60,12 @@ export const docs = {description: 'Whether to show a bottom border divider under the tab list.',default: 'false',},+ {+ name: 'overflow',+ type: "'auto' | 'scroll' | 'visible'",+ description: "What happens when the tabs are wider than the strip. 'auto' lets the component choose, which today always scrolls. 'scroll' scrolls the tabs horizontally, with edge fades and arrow affordances for pointers that can hover. 'visible' turns overflow handling off and lets the tabs spill out of the strip. The selected tab is always scrolled back into view.",+ default: "'auto'",+ },{name: 'children',type: 'ReactNode',@@ -88,7 +96,7 @@ export const docs = {'TabList provides tab-style navigation for organizing content into categorized sections. Use it to let users switch between related views without leaving the page, with overflow items handled by a built-in "more" menu.',bestPractices: [{ guidance: true, description: 'Keep tab labels short and descriptive so users can quickly scan available sections.' },- { guidance: true, description: 'Use TabMenu to group overflow items when horizontal space is limited rather than scrolling tabs off-screen.' },+ { guidance: true, description: 'Leave overflow handling on: a strip narrower than its tabs scrolls, and the selected tab is kept in view. Use TabMenu when you want a curated group of extra options rather than a scrolling strip.' },{ guidance: true, description: 'When using hasDivider with action buttons alongside tabs, match the Button size to the TabList size (both md, both sm); the divided tab strip reserves space so tabs and same-size buttons align to a shared baseline above the rail.' },{ guidance: false, description: 'Use tabs for sequential steps or workflows; use a stepper or wizard pattern instead.' },{ guidance: false, description: 'Place more than 6–8 visible tabs before the overflow menu; prioritize the most important categories.' },@@ -109,7 +117,7 @@ export const docsZh = {'TabList provides tab-style navigation for organizing content into categorized sections. Use it to let users switch between related views without leaving the page, with overflow items handled by a built-in "more" menu.',bestPractices: [{ guidance: true, description: 'Keep tab labels short and descriptive so users can quickly scan available sections.' },- { guidance: true, description: 'Use TabMenu to group overflow items when horizontal space is limited rather than scrolling tabs off-screen.' },+ { guidance: true, description: 'Leave overflow handling on: a strip narrower than its tabs scrolls, and the selected tab is kept in view. Use TabMenu when you want a curated group of extra options rather than a scrolling strip.' },{ guidance: true, description: 'When using hasDivider with action buttons alongside tabs, match the Button size to the TabList size (both md, both sm); the divided tab strip reserves space so tabs and same-size buttons align to a shared baseline above the rail.' },{ guidance: false, description: 'Use tabs for sequential steps or workflows; use a stepper or wizard pattern instead.' },{ guidance: false, description: 'Place more than 6–8 visible tabs before the overflow menu; prioritize the most important categories.' },@@ -131,7 +139,7 @@ export const docsDense = {'TabList provides tab-style navigation for organizing content into categorized sections. Use it to let users switch between related views without leaving the page, with overflow items handled by a built-in "more" menu.',bestPractices: [{ guidance: true, description: 'Keep tab labels short and descriptive so users can quickly scan available sections.' },- { guidance: true, description: 'Use TabMenu to group overflow items when horizontal space is limited rather than scrolling tabs off-screen.' },+ { guidance: true, description: 'Leave overflow handling on: a strip narrower than its tabs scrolls, and the selected tab is kept in view. Use TabMenu when you want a curated group of extra options rather than a scrolling strip.' },{ guidance: true, description: 'When using hasDivider with action buttons alongside tabs, match the Button size to the TabList size (both md, both sm); the divided tab strip reserves space so tabs and same-size buttons align to a shared baseline above the rail.' },{ guidance: false, description: 'Use tabs for sequential steps or workflows; use a stepper or wizard pattern instead.' },{ guidance: false, description: 'Place more than 6–8 visible tabs before the overflow menu; prioritize the most important categories.' },diff --git a/packages/core/src/TabList/TabList.test.tsx b/packages/core/src/TabList/TabList.test.tsxindex 9ad44bc2d4..0e7adbdd1a 100644--- a/packages/core/src/TabList/TabList.test.tsx+++ b/packages/core/src/TabList/TabList.test.tsx@@ -13,6 +13,7 @@ import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {TabList} from './TabList';+import type {TabListProps} from './TabList';import {Tab} from './Tab';import {TabMenu} from './TabMenu';import {LinkProvider} from '../Link/LinkProvider';@@ -960,3 +961,352 @@ describe('TabMenu keyboard navigation (roving tabindex)', () => {expect(hidePopover).toHaveBeenCalled();});});++describe('TabList overflow (scroll)', () => {+ const STRIP = '.astryx-tab-strip';+ const ARROW = '.astryx-tab-scroll-button';++ /** jsdom has no layout, so the scroll box is described by hand. */+ function fakeScrollBox(+ strip: HTMLElement,+ {+ scrollWidth,+ clientWidth,+ scrollLeft = 0,+ }: {scrollWidth: number; clientWidth: number; scrollLeft?: number},+ ) {+ Object.defineProperty(strip, 'scrollWidth', {+ value: scrollWidth,+ configurable: true,+ });+ Object.defineProperty(strip, 'clientWidth', {+ value: clientWidth,+ configurable: true,+ });+ Object.defineProperty(strip, 'scrollLeft', {+ value: scrollLeft,+ writable: true,+ configurable: true,+ });+ }++ /**+ * Places the strip at 0..width and a tab at the given offsets, so the+ * keep-selected-visible arithmetic has real numbers to work with.+ */+ function fakeGeometry(+ strip: HTMLElement,+ tabValue: string,+ {+ stripWidth,+ tabLeft,+ tabRight,+ }: {stripWidth: number; tabLeft: number; tabRight: number},+ ) {+ strip.getBoundingClientRect = () =>+ ({left: 0, right: stripWidth, width: stripWidth}) as DOMRect;+ const tab = strip.querySelector<HTMLElement>(+ `[data-tab-value="${tabValue}"]`,+ );+ if (tab) {+ tab.getBoundingClientRect = () =>+ ({+ left: tabLeft,+ right: tabRight,+ width: tabRight - tabLeft,+ }) as DOMRect;+ }+ }++ function renderStrip(props: Partial<TabListProps> = {}) {+ const utils = render(+ <TabList value="a" onChange={() => {}} {...props}>+ <Tab value="a" label="Alpha" />+ <Tab value="b" label="Beta" />+ <Tab value="c" label="Gamma" />+ </TabList>,+ );+ const strip = utils.container.querySelector<HTMLElement>(STRIP);+ if (!strip) {+ throw new Error('no tab strip');+ }+ return {...utils, strip};+ }++ it('renders the tabs inside a scroll strip by default', () => {+ const {strip} = renderStrip();+ expect(strip.querySelectorAll('[data-tab-value]')).toHaveLength(3);+ });++ it('offers an end arrow while there are tabs past the end, and pressing it scrolls', () => {+ const {container, strip} = renderStrip();+ fakeScrollBox(strip, {scrollWidth: 600, clientWidth: 300});+ const scrollBy = vi.fn();+ strip.scrollBy = scrollBy;+ fireEvent.scroll(strip);++ const arrows = container.querySelectorAll(ARROW);+ expect(arrows).toHaveLength(1);++ fireEvent.click(arrows[0]);+ expect(scrollBy).toHaveBeenCalledWith({left: 240});+ });++ it('offers both arrows once the strip is scrolled away from the start', () => {+ const {container, strip} = renderStrip();+ fakeScrollBox(strip, {scrollWidth: 600, clientWidth: 300, scrollLeft: 150});+ strip.scrollBy = vi.fn();+ fireEvent.scroll(strip);++ expect(container.querySelectorAll(ARROW)).toHaveLength(2);+ });++ it('keeps the arrows out of the tab order and out of the accessibility tree', () => {+ const {container, strip} = renderStrip();+ fakeScrollBox(strip, {scrollWidth: 600, clientWidth: 300});+ strip.scrollBy = vi.fn();+ fireEvent.scroll(strip);++ const arrow = container.querySelector<HTMLElement>(ARROW);+ expect(arrow?.getAttribute('aria-hidden')).toBe('true');+ expect(arrow?.tabIndex).toBe(-1);+ });++ it('scrolls a selected tab that starts out of view back into view on mount', () => {+ const scrollBy = vi.fn();+ // The strip mounts before the effect runs, so the geometry has to be in+ // place on the prototype rather than on an element we can reach first.+ const originalScrollBy = Element.prototype.scrollBy;+ const originalRect = Element.prototype.getBoundingClientRect;+ Element.prototype.scrollBy = scrollBy;+ Element.prototype.getBoundingClientRect = function (this: Element) {+ return (+ this.classList.contains('astryx-tab-strip')+ ? {left: 0, right: 300, width: 300}+ : {left: 420, right: 500, width: 80}+ ) as DOMRect;+ };++ render(+ <TabList value="c" onChange={() => {}}>+ <Tab value="a" label="Alpha" />+ <Tab value="b" label="Beta" />+ <Tab value="c" label="Gamma" />+ </TabList>,+ );++ expect(scrollBy).toHaveBeenCalledWith(+ expect.objectContaining({behavior: 'instant'}),+ );+ expect(scrollBy.mock.calls[0][0].left).toBeGreaterThan(0);+ Element.prototype.scrollBy = originalScrollBy;+ Element.prototype.getBoundingClientRect = originalRect;+ });++ it('keeps the selected tab in view when the host changes value without focus', () => {+ const {strip, rerender} = renderStrip({value: 'a'});+ const scrollBy = vi.fn();+ strip.scrollBy = scrollBy;+ fakeGeometry(strip, 'c', {stripWidth: 300, tabLeft: 420, tabRight: 500});++ rerender(+ <TabList value="c" onChange={() => {}}>+ <Tab value="a" label="Alpha" />+ <Tab value="b" label="Beta" />+ <Tab value="c" label="Gamma" />+ </TabList>,+ );++ expect(scrollBy).toHaveBeenCalledTimes(1);+ expect(scrollBy.mock.calls[0][0].left).toBeGreaterThan(0);+ });++ it('leaves a tab that is already in view alone', () => {+ const {strip, rerender} = renderStrip({value: 'a'});+ const scrollBy = vi.fn();+ strip.scrollBy = scrollBy;+ fakeGeometry(strip, 'b', {stripWidth: 300, tabLeft: 80, tabRight: 140});++ rerender(+ <TabList value="b" onChange={() => {}}>+ <Tab value="a" label="Alpha" />+ <Tab value="b" label="Beta" />+ <Tab value="c" label="Gamma" />+ </TabList>,+ );++ expect(scrollBy).not.toHaveBeenCalled();+ });++ it('reveals on a selection change, not on an unrelated overflow change', () => {+ const {strip, rerender} = renderStrip({value: 'c', overflow: 'visible'});+ const scrollBy = vi.fn();+ strip.scrollBy = scrollBy;+ fakeGeometry(strip, 'c', {stripWidth: 300, tabLeft: 420, tabRight: 500});++ // Turning scrolling on re-measures the strip, and that one reveal is the+ // resize path's. The selection has not moved, so nothing may add a second.+ rerender(+ <TabList value="c" onChange={() => {}} overflow="scroll">+ <Tab value="a" label="Alpha" />+ <Tab value="b" label="Beta" />+ <Tab value="c" label="Gamma" />+ </TabList>,+ );++ expect(scrollBy).toHaveBeenCalledTimes(1);++ fakeGeometry(strip, 'a', {stripWidth: 300, tabLeft: -200, tabRight: -120});+ rerender(+ <TabList value="a" onChange={() => {}} overflow="scroll">+ <Tab value="a" label="Alpha" />+ <Tab value="b" label="Beta" />+ <Tab value="c" label="Gamma" />+ </TabList>,+ );++ expect(scrollBy).toHaveBeenCalledTimes(2);+ expect(scrollBy.mock.calls[1][0].left).toBeLessThan(0);+ });++ it('finishes the job on focus: a tab only half in view is scrolled clear', () => {+ const {strip} = renderStrip({value: 'a'});+ const scrollBy = vi.fn();+ strip.scrollBy = scrollBy;+ // The browser scrolls a focused tab into view only when it is entirely+ // outside the box, so this one — straddling the end edge — stays cut off.+ fakeGeometry(strip, 'c', {stripWidth: 300, tabLeft: 260, tabRight: 340});++ const tab = strip.querySelector<HTMLElement>('[data-tab-value="c"]');+ fireEvent.focus(tab!, {bubbles: true});++ expect(scrollBy).toHaveBeenCalledTimes(1);+ expect(scrollBy.mock.calls[0][0].left).toBeCloseTo(40);+ });++ it('reveals a half-visible overflow menu trigger too, not just tabs', () => {+ const {container} = render(+ <TabList value="a" onChange={() => {}}>+ <Tab value="a" label="Alpha" />+ <Tab value="b" label="Beta" />+ <TabMenu label="More" options={[{value: 'c', label: 'Gamma'}]} />+ </TabList>,+ );+ const strip = container.querySelector<HTMLElement>(STRIP);+ if (!strip) {+ throw new Error('no tab strip');+ }+ const scrollBy = vi.fn();+ strip.scrollBy = scrollBy;+ strip.getBoundingClientRect = () =>+ ({left: 0, right: 300, width: 300}) as DOMRect;+ const trigger = strip.querySelector<HTMLElement>('[data-tab-menu]');+ if (!trigger) {+ throw new Error('no menu trigger');+ }+ trigger.getBoundingClientRect = () =>+ ({left: 260, right: 340, width: 80}) as DOMRect;++ fireEvent.focus(trigger, {bubbles: true});++ expect(scrollBy).toHaveBeenCalledTimes(1);+ expect(scrollBy.mock.calls[0][0].left).toBeCloseTo(40);+ });++ it('fades out at the strip’s own edge, not at the bleed edge', () => {+ // The scroll box is a ring-bleed wider than the TabList on each side while+ // it holds focus, so a fade that ran to the box edge would paint tabs+ // outside the component and past the arrow that caps that edge.+ const bleed = 'var(--_tab-strip-bleed)';+ const {strip} = renderStrip();+ strip.scrollBy = vi.fn();++ fakeScrollBox(strip, {scrollWidth: 600, clientWidth: 300});+ fireEvent.scroll(strip);+ expect(getComputedStyle(strip).maskImage).toContain(`transparent ${bleed}`);++ fakeScrollBox(strip, {scrollWidth: 600, clientWidth: 300, scrollLeft: 150});+ fireEvent.scroll(strip);+ expect(getComputedStyle(strip).maskImage).toContain(+ `transparent calc(100% - ${bleed})`,+ );+ });++ it('is no wider than the TabList until the strip holds focus', () => {+ // The bleed is real geometry: while the strip carries it, its border box+ // sticks out of the TabList's and every ancestor that scrolls counts it.+ // jsdom has no layout, so the box is read off the declarations: padding+ // and its cancelling margin are both the bleed, and the bleed is zero+ // until a ring needs keeping whole. `:has(:focus-visible)` flips it --+ // covered in a browser, since jsdom does not recompute style on a focus+ // change.+ const {strip} = renderStrip();+ const cs = getComputedStyle(strip);++ expect(cs.getPropertyValue('--_tab-strip-bleed')).toBe('0px');+ expect(cs.paddingInline).toBe('var(--_tab-strip-bleed)');+ expect(cs.marginInline).toBe('calc(-1 * (var(--_tab-strip-bleed)))');+ });++ it('does not hand focus to an arrow, which is hidden from assistive tech', () => {+ const {container, strip} = renderStrip();+ fakeScrollBox(strip, {scrollWidth: 600, clientWidth: 300});+ strip.scrollBy = vi.fn();+ fireEvent.scroll(strip);++ const arrow = container.querySelector<HTMLElement>(ARROW);+ const prevented = !fireEvent.mouseDown(arrow!);+ expect(prevented).toBe(true);+ });++ it('overflow="visible" scrolls nothing and offers no arrows', () => {+ const {container, strip, rerender} = renderStrip({+ value: 'a',+ overflow: 'visible',+ });+ const scrollBy = vi.fn();+ strip.scrollBy = scrollBy;+ fakeScrollBox(strip, {scrollWidth: 600, clientWidth: 300});+ fakeGeometry(strip, 'c', {stripWidth: 300, tabLeft: 420, tabRight: 500});+ fireEvent.scroll(strip);++ rerender(+ <TabList value="c" onChange={() => {}} overflow="visible">+ <Tab value="a" label="Alpha" />+ <Tab value="b" label="Beta" />+ <Tab value="c" label="Gamma" />+ </TabList>,+ );++ expect(container.querySelectorAll(ARROW)).toHaveLength(0);+ expect(scrollBy).not.toHaveBeenCalled();+ });++ it('shows the reading start of a stop too wide to fit', () => {+ const {strip} = renderStrip({value: 'a'});+ const scrollBy = vi.fn();+ strip.scrollBy = scrollBy;+ // Wider than the strip, so one end stays hidden either way. Aligning the+ // end would land a long label on its last words.+ fakeGeometry(strip, 'c', {stripWidth: 300, tabLeft: 420, tabRight: 800});++ const tab = strip.querySelector<HTMLElement>('[data-tab-value="c"]');+ fireEvent.focus(tab!, {bubbles: true});++ expect(scrollBy.mock.calls[0][0].left).toBeCloseTo(420);+ });++ it('shows the reading start of an over-wide stop in RTL too', () => {+ const {strip} = renderStrip({value: 'a'});+ const scrollBy = vi.fn();+ strip.scrollBy = scrollBy;+ strip.style.direction = 'rtl';+ fakeGeometry(strip, 'c', {stripWidth: 300, tabLeft: -500, tabRight: -120});++ const tab = strip.querySelector<HTMLElement>('[data-tab-value="c"]');+ fireEvent.focus(tab!, {bubbles: true});++ // RTL reads from the right edge, so that is the end to bring flush.+ expect(scrollBy.mock.calls[0][0].left).toBeCloseTo(-420);+ });+});diff --git a/packages/core/src/TabList/TabList.tsx b/packages/core/src/TabList/TabList.tsxindex b5f7d3b0af..aa2c984b35 100644--- a/packages/core/src/TabList/TabList.tsx+++ b/packages/core/src/TabList/TabList.tsx@@ -4,11 +4,13 @@/*** @file TabList.tsx- * @input Uses React, StyleX, TabListContext, useListFocus, useKeyboardHint- * @output Exports TabList component and TabListProps type+ * @input Uses React, StyleX, TabListContext, useListFocus, useKeyboardHint,+ * useScrollOverflow, Icon+ * @output Exports TabList component, TabListProps and TabListOverflow types* @position Nav wrapper; provides TabListContext to Tab and TabMenu children.* Owns roving-tabindex keyboard navigation (Arrow/Home/End) across the tab- * strip via the shared useListFocus hook so it is a single Tab stop.+ * strip via the shared useListFocus hook so it is a single Tab stop, and+ * owns horizontal scrolling when the tabs are wider than the strip.** SYNC: When modified, update:* - /packages/core/src/TabList/TabList.doc.mjs@@ -17,18 +19,39 @@* - /packages/cli/assets/templates/blocks/components/TabList/ (showcase blocks)*/-import React, {useCallback, useMemo, type ReactNode} from 'react';+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ type ReactNode,+} from 'react';import * as stylex from '@stylexjs/stylex';-import {borderVars, colorVars, spacingVars} from '../theme/tokens.stylex';+import {+ borderVars,+ colorVars,+ durationVars,+ easeVars,+ focusVars,+ radiusVars,+ shadowVars,+ sizeVars,+ spacingVars,+} from '../theme/tokens.stylex';import type {BaseProps} from '../BaseProps';import {TabListContext} from './TabListContext';import type {TabListSize} from './TabListContext';import {useSize} from '../SizeContext/SizeContext';-import {mergeProps} from '../utils';+import {mergeProps, rtlStyles} from '../utils';import {useListFocus} from '../hooks/useListFocus';import {useKeyboardHint} from '../hooks/useKeyboardHint';+import {useScrollOverflow} from '../hooks/useScrollOverflow';+import {isRtlElement} from '../hooks/isRtlElement';+import {Icon} from '../Icon';import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';import {themeProps} from '../utils/themeProps';+import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';+import {focusOutlineProps} from '../utils/focusOutline.stylex';import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';@@ -39,6 +62,24 @@ import {useMergedRefs} from '../hooks/useMergedRefs';*/const TAB_STOP_SELECTOR = '[data-tab-value],[data-tab-menu]';+function preventFocus(e: React.MouseEvent) {+ e.preventDefault();+}++/** Fraction of the visible strip an arrow press scrolls. */+const SCROLL_PAGE_RATIO = 0.8;++/**+ * How a strip narrower than its tabs behaves.+ *+ * - `'auto'` — the component picks the strategy. Today that is always+ * `'scroll'`.+ * - `'scroll'` — the tabs scroll horizontally. Every tab stays a tab.+ * - `'visible'` — no overflow handling: tabs keep their intrinsic widths and+ * spill out of the strip, as they did before overflow existed.+ */+export type TabListOverflow = 'auto' | 'scroll' | 'visible';+export interface TabListProps extends Omit<BaseProps<HTMLElement>, 'onChange'> {ref?: React.Ref<HTMLElement>;/**@@ -67,12 +108,72 @@ export interface TabListProps extends Omit<BaseProps<HTMLElement>, 'onChange'> {* @default false*/hasDivider?: boolean;+ /**+ * What happens when the tabs are wider than the strip.+ *+ * `'auto'` lets the component choose; today it always scrolls. `'scroll'`+ * scrolls the tabs horizontally, with edge fades and — for pointers that+ * can hover — arrow affordances. `'visible'` turns overflow handling off and+ * lets the tabs spill out of the strip.+ *+ * The selected tab is always scrolled back into view.+ * @default 'auto'+ */+ overflow?: TabListOverflow;/*** Tab and TabMenu children.*/children: ReactNode;}+/**+ * A scroll container clips at its padding box, and two things a tab paints sit+ * outside its own box: the focus ring (offset + width) and the selected+ * indicator, which `--_tab-indicator-bottom` pushes further down when a+ * divider rail is reserved. The strip pads by that much and takes the padding+ * straight back off with a negative margin, so nothing is clipped and the tabs+ * stay exactly where they were.+ *+ * A bleed is not free, though. The padding is real geometry: the strip's+ * border box sticks out of the TabList's, and any ancestor that scrolls counts+ * that as something to scroll to. So the ring's share of the bleed is taken+ * only while a ring is actually drawn inside the strip -- the same+ * `:has(:focus-visible)` condition that draws it -- and at rest the strip is+ * exactly as wide and as tall as the TabList, as it was before the strip could+ * scroll. The indicator's share is always taken, because the indicator is+ * always drawn.+ *+ * Turning the bleed on moves nothing: padding and negative margin cancel, so+ * the border box grows outwards and the content stays put.+ */+const RING_BLEED = `calc(${focusVars['--focus-outline-width']} + ${focusVars['--focus-outline-offset']})`;+const BLEED_VAR = '--_tab-strip-bleed';+const BLEED = `var(${BLEED_VAR})`;+const INDICATOR_BLEED = 'calc(-1 * var(--_tab-indicator-bottom, -1px))';+const BLOCK_END_BLEED = `max(${BLEED}, ${INDICATOR_BLEED})`;++/** How far the edge fade runs; wide enough to sit under an arrow. */+const FADE_WIDTH = spacingVars['--spacing-8'];++/**+ * Where the fade turns fully opaque, and — the same distance, for the same+ * reason — how far a revealed stop is kept clear of the edge. Declared as+ * scroll-padding so the browser's own focus scrolling uses it too, and read+ * back from the computed style so the arithmetic below has one source of+ * truth with the CSS.+ */+const SCROLL_EDGE_INSET = `calc(${BLEED} + ${FADE_WIDTH})`;++/**+ * The fade reaches transparent at the strip's *own* edge, not at the bleed+ * edge — otherwise the scroll container paints tabs past the TabList's box,+ * past a divider rail, and past the scroll arrow that caps that edge. Masking+ * the bleed costs nothing: only a faded edge is masked, and a stop at a faded+ * edge never holds focus, so the bleed is still there when the ring needs it.+ */+const FADE_FROM_START = `linear-gradient(to right, transparent ${BLEED}, black ${SCROLL_EDGE_INSET})`;+const FADE_FROM_END = `linear-gradient(to left, transparent ${BLEED}, black ${SCROLL_EDGE_INSET})`;+const styles = stylex.create({nav: {display: 'flex',@@ -80,6 +181,7 @@ const styles = stylex.create({gap: spacingVars['--spacing-0-5'],maxWidth: '100%',minWidth: 0,+ position: 'relative',},fill: {width: '100%',@@ -97,6 +199,114 @@ const styles = stylex.create({paddingBlockEnd: spacingVars['--spacing-1'],'--_tab-indicator-bottom': `calc(-1 * (${spacingVars['--spacing-1']} + ${borderVars['--border-width']}))`,},+ strip: {+ display: 'flex',+ alignItems: 'stretch',+ // Inherited rather than restated so an `xstyle` gap override on the+ // TabList still reaches the tabs.+ gap: 'inherit',+ flexGrow: 1,+ flexShrink: 1,+ minWidth: 0,+ // Content-height, not stretched: the bleed padding below is inside the+ // strip's own height, and a stretched height would push the tabs out of+ // the scrollport.+ alignSelf: 'flex-start',+ },+ stripScroll: {+ overflowX: 'auto',+ overflowY: 'hidden',+ overscrollBehaviorX: 'contain',+ scrollPaddingInline: SCROLL_EDGE_INSET,+ scrollbarWidth: 'none',+ scrollBehavior: {+ default: 'smooth',+ '@media (prefers-reduced-motion: reduce)': 'auto',+ },+ [BLEED_VAR]: {+ default: '0px',+ ':has(:focus-visible)': RING_BLEED,+ },+ paddingBlockStart: BLEED,+ marginBlockStart: `calc(-1 * (${BLEED}))`,+ paddingBlockEnd: BLOCK_END_BLEED,+ marginBlockEnd: `calc(-1 * (${BLOCK_END_BLEED}))`,+ paddingInline: BLEED,+ marginInline: `calc(-1 * (${BLEED}))`,+ maskImage: 'none',+ transitionProperty: 'mask-image',+ transitionDuration: {+ default: durationVars['--duration-medium'],+ '@media (prefers-reduced-motion: reduce)': '0ms',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ },+ fadeStart: {+ maskImage: {+ default: FADE_FROM_START,+ ':is([dir="rtl"] *)': FADE_FROM_END,+ },+ },+ fadeEnd: {+ maskImage: {+ default: FADE_FROM_END,+ ':is([dir="rtl"] *)': FADE_FROM_START,+ },+ },+ fadeBoth: {+ maskImage: `linear-gradient(to right, transparent ${BLEED}, black ${SCROLL_EDGE_INSET}, black calc(100% - ${SCROLL_EDGE_INSET}), transparent calc(100% - ${BLEED}))`,+ },+ arrow: {+ position: 'absolute',+ insetBlockStart: 0,+ // A pointer-only affordance: keyboard and assistive-technology users move+ // through the strip with the arrow keys, which scrolls the focused tab+ // into view on its own.+ display: {+ default: 'none',+ '@media (hover: hover)': 'flex',+ },+ alignItems: 'center',+ justifyContent: 'center',+ padding: 0,+ borderWidth: 0,+ borderStyle: 'none',+ borderRadius: radiusVars['--radius-full'],+ // Opaque, because it sits over the tabs it scrolls: the strip's edge fade+ // thins the content underneath but does not clear it.+ backgroundColor: colorVars['--color-background-popover'],+ boxShadow: shadowVars['--shadow-low'],+ color: {+ default: colorVars['--color-text-secondary'],+ ':hover:where(:not(:disabled,[aria-disabled="true"]))':+ colorVars['--color-text-primary'],+ },+ cursor: {+ default: 'pointer',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ },+ arrowStart: {+ insetInlineStart: 0,+ },+ arrowEnd: {+ insetInlineEnd: 0,+ },+});++const arrowSizeStyles = stylex.create({+ sm: {+ width: sizeVars['--size-element-sm'],+ height: sizeVars['--size-element-sm'],+ },+ md: {+ width: sizeVars['--size-element-md'],+ height: sizeVars['--size-element-md'],+ },+ lg: {+ width: sizeVars['--size-element-lg'],+ height: sizeVars['--size-element-lg'],+ },});/**@@ -122,6 +332,7 @@ export function TabList({size: sizeProp,layout = 'hug',hasDivider = false,+ overflow = 'auto',xstyle,className,style,@@ -137,6 +348,7 @@ export function TabList({const t = useTranslator();const ariaLabel = ariaLabelFromProps ?? t('@astryx.tabList.label');const size = useSize(sizeProp, 'md');+ const hasScroll = overflow !== 'visible';// Roving-tabindex keyboard navigation across the tab strip via the shared// hook. `orientation: 'both'` accepts both arrow axes per the WAI-ARIA APG@@ -165,6 +377,116 @@ export function TabList({onBlur: onHintBlur,} = useKeyboardHint();+ const {scrollRef, overflowStart, overflowEnd} = useScrollOverflow();+ const stripRef = useRef<HTMLDivElement | null>(null);++ const attachStrip = useCallback(+ (el: HTMLDivElement | null) => {+ stripRef.current = el;+ scrollRef(hasScroll ? el : null);+ },+ [hasScroll, scrollRef],+ );++ const revealStop = useCallback(+ (stop: HTMLElement | null) => {+ const strip = stripRef.current;+ if (!hasScroll || !strip || !stop) {+ return;+ }+ const stripBox = strip.getBoundingClientRect();+ const stopBox = stop.getBoundingClientRect();+ const inset = parseFloat(getComputedStyle(strip).scrollPaddingLeft) || 0;+ const pastEnd = stopBox.right - (stripBox.right - inset);+ const pastStart = stopBox.left - (stripBox.left + inset);+ // A stop wider than the space kept clear cannot be shown whole, so show+ // its reading start, the way `scrollIntoView({inline: 'nearest'})` does.+ const tooWide = stopBox.width > stripBox.width - 2 * inset;+ const delta = tooWide+ ? isRtlElement(strip)+ ? pastEnd+ : pastStart+ : pastEnd > 0+ ? pastEnd+ : pastStart < 0+ ? pastStart+ : 0;+ if (delta !== 0) {+ // Not an animation: the strip has to arrive already showing the right+ // tab, so this overrides the CSS smooth behaviour arrow presses use.+ strip.scrollBy({left: delta, behavior: 'instant'});+ }+ },+ [hasScroll],+ );++ const revealSelectedTab = useCallback(() => {+ const strip = stripRef.current;+ if (!strip) {+ return;+ }+ revealStop(+ Array.from(strip.querySelectorAll<HTMLElement>('[data-tab-value]')).find(+ el => el.dataset.tabValue === value,+ ) ?? null,+ );+ }, [revealStop, value]);++ // Both reveals below reach the callback through a ref instead of depending+ // on it: its identity also changes with `overflow`, and that is not a reason+ // to scroll anything.+ const revealSelectedTabRef = useRef(revealSelectedTab);+ useEffect(() => {+ revealSelectedTabRef.current = revealSelectedTab;+ }, [revealSelectedTab]);++ // The tab you are on has to be visible. Selection can move without focus —+ // on mount, or when the host sets `value` itself — and neither scrolls the+ // strip the way clicking or arrowing to a tab does. The check is what makes+ // a selection change the trigger, rather than the effect happening to run.+ const revealedValueRef = useRef<string | null>(null);+ useEffect(() => {+ if (revealedValueRef.current === value) {+ return;+ }+ revealedValueRef.current = value;+ revealSelectedTabRef.current();+ }, [value]);++ // ...and it has to stay visible when the strip is what moved. A strip that+ // fitted at one width can hide the selected tab at a narrower one, and no+ // prop changes when that happens. This one re-reveals the same selection by+ // design, which is why the check above sits in the effect rather than in+ // `revealSelectedTab`.+ //+ // The wrapper is observed rather than the strip because the shared observer+ // keeps one callback per element and `useScrollOverflow` already holds the+ // strip's.+ useEffect(() => {+ const root = listRef.current;+ if (!hasScroll || !root) {+ return;+ }+ const onResize = () => revealSelectedTabRef.current();+ observeResize(root, onResize);+ return () => unobserveResize(root);+ }, [hasScroll, listRef]);++ const scrollByPage = useCallback((direction: -1 | 1) => {+ const strip = stripRef.current;+ if (!strip) {+ return;+ }+ // Under RTL the scroll axis is inverted, so flip the physical delta.+ const rtlSign = isRtlElement(strip) ? -1 : 1;+ strip.scrollBy({+ left: rtlSign * direction * strip.clientWidth * SCROLL_PAGE_RATIO,+ });+ }, []);++ const scrollToStart = useCallback(() => scrollByPage(-1), [scrollByPage]);+ const scrollToEnd = useCallback(() => scrollByPage(1), [scrollByPage]);+const contextValue = useMemo(() => ({value, onChange, size, layout}),[value, onChange, size, layout],@@ -190,8 +512,12 @@ export function TabList({}onHintFocus(e);handleFocus(e);+ // The browser scrolls a focused element into view only when it is+ // entirely outside the scrollport, so arrowing onto a half-visible stop+ // leaves it cut off under the fade. Finish the job it started.+ revealStop(e.target.closest(TAB_STOP_SELECTOR));},- [onFocusProp, onHintFocus, handleFocus],+ [onFocusProp, onHintFocus, handleFocus, revealStop],);const handleRootBlur = useCallback(@@ -205,6 +531,16 @@ export function TabList({[onBlurProp, onHintBlur],);+ const fadeStyle = !hasScroll+ ? null+ : overflowStart && overflowEnd+ ? styles.fadeBoth+ : overflowStart+ ? styles.fadeStart+ : overflowEnd+ ? styles.fadeEnd+ : null;+return (<TabListContext value={contextValue}><nav@@ -226,7 +562,66 @@ export function TabList({className,style,)}>- {children}+ <div+ ref={attachStrip}+ {...mergeProps(+ themeProps('tab-strip'),+ stylex.props(+ styles.strip,+ hasScroll && styles.stripScroll,+ fadeStyle,+ ),+ )}>+ {children}+ </div>+ {hasScroll && overflowStart && (+ <button+ type="button"+ aria-hidden="true"+ tabIndex={-1}+ // Nothing hidden from assistive technology should end up holding+ // focus, and a click would put it here.+ onMouseDown={preventFocus}+ onClick={scrollToStart}+ {...mergeProps(+ themeProps('tab-scroll-button'),+ focusOutlineProps.focusVisible(+ styles.arrow,+ styles.arrowStart,+ arrowSizeStyles[size],+ ),+ )}>+ <Icon+ icon="chevronLeft"+ size="sm"+ color="inherit"+ xstyle={rtlStyles.mirror}+ />+ </button>+ )}+ {hasScroll && overflowEnd && (+ <button+ type="button"+ aria-hidden="true"+ tabIndex={-1}+ onMouseDown={preventFocus}+ onClick={scrollToEnd}+ {...mergeProps(+ themeProps('tab-scroll-button'),+ focusOutlineProps.focusVisible(+ styles.arrow,+ styles.arrowEnd,+ arrowSizeStyles[size],+ ),+ )}>+ <Icon+ icon="chevronRight"+ size="sm"+ color="inherit"+ xstyle={rtlStyles.mirror}+ />+ </button>+ )}{hintElement}</nav></TabListContext>diff --git a/packages/core/src/TabList/index.ts b/packages/core/src/TabList/index.tsindex e80c62a243..ab394cf08e 100644--- a/packages/core/src/TabList/index.ts+++ b/packages/core/src/TabList/index.ts@@ -12,7 +12,7 @@*/export {TabList} from './TabList';-export type {TabListProps} from './TabList';+export type {TabListProps, TabListOverflow} from './TabList';export {Tab} from './Tab';export type {TabProps} from './Tab';diff --git a/packages/core/src/utils/sharedResizeObserver.ts b/packages/core/src/utils/sharedResizeObserver.tsindex ff75c37b54..0633be9c21 100644--- a/packages/core/src/utils/sharedResizeObserver.ts+++ b/packages/core/src/utils/sharedResizeObserver.ts@@ -24,7 +24,15 @@ type ResizeCallback = (entry: ResizeObserverEntry) => void;let observer: ResizeObserver | null = null;const callbacks = new Map<Element, ResizeCallback>();-function getObserver(): ResizeObserver {+/**+ * The shared observer, or null where the API does not exist (jsdom, an old+ * browser). Callers still get the one-shot measurement `observeResize` fires+ * on registration; live resize updates are the part that needs the API.+ */+function getObserver(): ResizeObserver | null {+ if (typeof ResizeObserver === 'undefined') {+ return null;+ }if (!observer) {observer = new ResizeObserver(entries => {for (const entry of entries) {@@ -64,7 +72,7 @@ export function observeResize(callback: ResizeCallback,): void {callbacks.set(element, callback);- getObserver().observe(element);+ getObserver()?.observe(element);// Fire once immediately so callers get an initial measurement// without duplicating their logic outside the observer path.