An open source design system that's fully customizable and agent ready
TypeScript
fix(Carousel): the scroll area is a named group, a tab stop only while it overflows (#8155)
Christopher Chedeau26784d22e770
diff --git a/.changeset/carousel-scroll-area-name.md b/.changeset/carousel-scroll-area-name.mdnew file mode 100644index 0000000000..eba964bdd7--- /dev/null+++ b/.changeset/carousel-scroll-area-name.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Carousel's scroll area is a group named like the carousel, so a screen-reader user who tabs onto it hears where they are. It is a tab stop only while its content overflows; a carousel that fits no longer adds an empty stop.++@vjeuxdiff --git a/.changeset/scroll-overflow-follows-content.md b/.changeset/scroll-overflow-follows-content.mdnew file mode 100644index 0000000000..7ad175e627--- /dev/null+++ b/.changeset/scroll-overflow-follows-content.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `useScrollOverflow` measures again when the container's content changes with the container keeping its size: a child added, removed or resized, or a new gap or padding. Carousel's scroll area, a tab stop only while its content overflows, and its edge buttons and fades follow slides added or removed and a slide that grows; TabList's fades follow its tabs the same way.++@vjeuxdiff --git a/packages/core/src/Carousel/Carousel.doc.mjs b/packages/core/src/Carousel/Carousel.doc.mjsindex c9510e61bc..3317a6d7a2 100644--- a/packages/core/src/Carousel/Carousel.doc.mjs+++ b/packages/core/src/Carousel/Carousel.doc.mjs@@ -14,7 +14,7 @@ export const docs = {{guidance: true, description: 'Enable scroll-snap when each item should land precisely at the start edge, like a gallery or product list.'},{guidance: true, description: 'Reach for hasLoop on small, cyclable sets like a photo gallery, where wrapping past the last item back to the first feels natural.'},{guidance: true, description: 'Always provide an aria-label that describes what the carousel contains, like "Featured products" or "Team members".'},- {guidance: true, description: 'Carousel implements the WAI-ARIA APG carousel pattern (https://www.w3.org/WAI/ARIA/apg/patterns/carousel/) without auto-rotation: the region is labelled and carries aria-roledescription="carousel", each item is a group named "Slide N of M", and the scroll container is a tab stop so keyboard users can pan it with the arrow keys.'},+ {guidance: true, description: 'Carousel implements the WAI-ARIA APG carousel pattern (https://www.w3.org/WAI/ARIA/apg/patterns/carousel/) without auto-rotation: the region is labelled and carries aria-roledescription="carousel", each item is a group named "Slide N of M", and the scroll container is a tab stop while its content overflows, so keyboard users can pan it with the arrow keys; while everything fits it stays out of the tab order.'},{guidance: true, description: 'Use a consistent gap and item width so the carousel looks intentional, not like content overflowing by accident.'},{guidance: true, description: 'Trust the built-in navigation: trackpad users can swipe horizontally, and mouse users can hold Shift while scrolling the wheel to move through items.'},{guidance: false, description: 'Use a carousel for content every user must see. Not everyone scrolls horizontally, so put critical content above the fold.'},diff --git a/packages/core/src/Carousel/Carousel.spec.md b/packages/core/src/Carousel/Carousel.spec.mdindex f697b8be00..73fe470016 100644--- a/packages/core/src/Carousel/Carousel.spec.md+++ b/packages/core/src/Carousel/Carousel.spec.md@@ -27,15 +27,15 @@ system_specs: [spec:AST-085, spec:AST-025]## Contract at a glance-| Area | Contract |-| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | None changes. |-| Behavior | An edge scroll button whose direction has run out is hidden and takes no tab stop. When the focused edge button runs out, focus moves to the scroll area. |-| End-user impact | A keyboard user who scrolls to the first or last item stays inside the carousel instead of landing on the page body or on an invisible control. The scroll area has no role or name yet, so screen-reader users hear little at the destination until it meets `spec:AST-025` FR12. |-| Builder impact | None. |-| Compatibility/readiness | No API change. Shipped Carousel and its current tests still use native `disabled` and hand focus to the opposite button; they change with conformance work. |-| Review checks | Reject focus left on a hidden edge button, focus dropped to the page body, or an edge handoff that moves focus to anything but the scroll area. |-| Governing rules | `spec:AST-085` FR1, FR4; `spec:AST-025` FR12; `architecture:interaction-modality` INV1. |+| Area | Contract |+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Public contract | None changes. |+| Behavior | An edge scroll button whose direction has run out is hidden and takes no tab stop. When the focused edge button runs out, focus moves to the scroll area. |+| End-user impact | A keyboard user who scrolls to the first or last item stays inside the carousel instead of landing on the page body or on an invisible control. The scroll area is a group named like the carousel (`spec:AST-025` FR12), so screen-reader users hear where they landed. |+| Builder impact | None. |+| Compatibility/readiness | No API change. Shipped Carousel and its current tests still use native `disabled` and hand focus to the opposite button; they change with conformance work. |+| Review checks | Reject focus left on a hidden edge button, focus dropped to the page body, or an edge handoff that moves focus to anything but the scroll area. |+| Governing rules | `spec:AST-085` FR1, FR4; `spec:AST-025` FR12; `architecture:interaction-modality` INV1. |This table is a review projection; the body below is authoritative.diff --git a/packages/core/src/Carousel/Carousel.test.tsx b/packages/core/src/Carousel/Carousel.test.tsxindex f2cfb100c0..d3182ad0c3 100644--- a/packages/core/src/Carousel/Carousel.test.tsx+++ b/packages/core/src/Carousel/Carousel.test.tsx@@ -2,15 +2,18 @@import {describe, it, expect, vi} from 'vitest';import {createRef} from 'react';-import {render, screen, fireEvent} from '@testing-library/react';+import {act, render, screen, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Carousel, type CarouselHandle} from './Carousel';// Mock ResizeObserver (not available in jsdom)class MockResizeObserver {+ /** The shared observer, so a test can deliver a resize. */+ static last: MockResizeObserver | null = null;callback: ResizeObserverCallback;constructor(callback: ResizeObserverCallback) {this.callback = callback;+ MockResizeObserver.last = this;}observe() {}unobserve() {}@@ -43,8 +46,9 @@ describe('Carousel', () => {</Carousel>,);// APG carousel pattern: each slide container is role=group with- // aria-roledescription="slide" and an "N of M" accessible name.- const slides = screen.getAllByRole('group');+ // aria-roledescription="slide" and an "N of M" accessible name. (The+ // scroll area around them is a group too, named like the carousel.)+ const slides = screen.getAllByRole('group', {name: /^Slide /});expect(slides).toHaveLength(3);slides.forEach((slide, i) => {expect(slide).toHaveAttribute('aria-roledescription', 'slide');@@ -52,6 +56,123 @@ describe('Carousel', () => {});});+ describe('scroll area (spec:AST-025 FR12)', () => {+ function getScroller() {+ return screen.getByRole('group', {name: 'Photos'});+ }++ function setOverflow(el: HTMLElement, overflowing: boolean) {+ Object.defineProperty(el, 'scrollWidth', {+ value: overflowing ? 500 : 200,+ configurable: true,+ });+ Object.defineProperty(el, 'clientWidth', {+ value: 200,+ configurable: true,+ });+ fireEvent.scroll(el);+ }++ it('is a group named like the carousel', () => {+ render(+ <Carousel aria-label="Photos">+ <div>One</div>+ <div>Two</div>+ </Carousel>,+ );+ const scroller = getScroller();+ expect(scroller).toHaveAttribute('role', 'group');+ expect(scroller).toHaveAccessibleName('Photos');+ // It is the region's scroll container, not a slide.+ expect(scroller).not.toHaveAttribute('aria-roledescription');+ expect(scroller.parentElement).toBe(+ screen.getByRole('region', {name: 'Photos'}),+ );+ });++ // Named by its owner (spec:AST-025 FR12): the caller's label above, else+ // the carousel's translated default.+ it("takes the carousel's translated default name when the caller gives none", () => {+ render(+ <Carousel>+ <div>One</div>+ <div>Two</div>+ </Carousel>,+ );+ const scroller = screen.getByRole('group', {name: 'Carousel'});+ expect(scroller).toHaveAccessibleName('Carousel');+ expect(scroller.parentElement).toBe(+ screen.getByRole('region', {name: 'Carousel'}),+ );+ });++ it('takes a tab stop only while its content overflows', () => {+ render(+ <Carousel aria-label="Photos">+ <div>One</div>+ <div>Two</div>+ </Carousel>,+ );+ const scroller = getScroller();+ // Fitting: out of the tab order, still focusable from script (FR2).+ setOverflow(scroller, false);+ expect(scroller).toHaveAttribute('tabindex', '-1');+ act(() => scroller.focus());+ expect(scroller).toHaveFocus();+ act(() => scroller.blur());+ // Overflowing: a tab stop.+ setOverflow(scroller, true);+ expect(scroller).toHaveAttribute('tabindex', '0');+ // Fitting again: leaves the tab order.+ setOverflow(scroller, false);+ expect(scroller).toHaveAttribute('tabindex', '-1');+ });++ // The content can come to overflow, or stop, with the scroll area+ // keeping its size: the tab stop follows it.+ it('follows its content: slides added or removed, or a slide that grows, move the tab stop', async () => {+ const slides = (count: number) =>+ Array.from({length: count}, (_, i) => <div key={i}>Slide {i}</div>);+ const view = render(<Carousel aria-label="Photos">{slides(1)}</Carousel>);+ const scroller = getScroller();+ // A 200 px scroll area; 150 px of content per slide, plus what a slide+ // grows by.+ let grown = 0;+ Object.defineProperty(scroller, 'clientWidth', {+ value: 200,+ configurable: true,+ });+ Object.defineProperty(scroller, 'scrollWidth', {+ configurable: true,+ get: () => scroller.children.length * 150 + grown,+ });+ expect(scroller).toHaveAttribute('tabindex', '-1');++ view.rerender(<Carousel aria-label="Photos">{slides(2)}</Carousel>);+ await act(async () => {});+ expect(scroller).toHaveAttribute('tabindex', '0');++ view.rerender(<Carousel aria-label="Photos">{slides(1)}</Carousel>);+ await act(async () => {});+ expect(scroller).toHaveAttribute('tabindex', '-1');++ // The one slide's content grows past the scroll area.+ grown = 100;+ const observer = MockResizeObserver.last;+ act(() => {+ observer?.callback(+ [+ {+ target: scroller.firstElementChild,+ } as unknown as ResizeObserverEntry,+ ],+ observer,+ );+ });+ expect(scroller).toHaveAttribute('tabindex', '0');+ });+ });+it('renders children', () => {render(<Carousel aria-label="Test carousel">diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsxindex f41bc90f01..d8b1a3c695 100644--- a/packages/core/src/Carousel/Carousel.tsx+++ b/packages/core/src/Carousel/Carousel.tsx@@ -14,7 +14,9 @@* scroll control. Exposes APG* carousel semantics: the root is a labelled region with* aria-roledescription="carousel" and each item wrapper is a group with- * aria-roledescription="slide" named "Slide N of M".+ * aria-roledescription="slide" named "Slide N of M". The scroll area is a+ * group named like the carousel and a tab stop only while its content+ * overflows (AST-025 FR12).** SYNC: When modified, update:* - /packages/core/src/Carousel/index.ts (exports)@@ -591,7 +593,13 @@ export function Carousel({aria-roledescription="carousel"><divref={composedRef}- tabIndex={0}+ // The scroll area takes keyboard scrolling (spec:AST-025 FR12): a+ // group named like the carousel, in the tab order only while its+ // content overflows. While it fits it still takes focus+ // programmatically, for the edge buttons' hand-off (FR2).+ role="group"+ aria-label={ariaLabel}+ tabIndex={hasOverflow ? 0 : -1}onWheel={handleWheel}{...mergeProps(themeProps('carousel-scroller', {diff --git a/packages/core/src/Carousel/__tests__/Carousel.a11y.known-failures.ts b/packages/core/src/Carousel/__tests__/Carousel.a11y.known-failures.tsindex 88fe373bbc..e7304612d4 100644--- a/packages/core/src/Carousel/__tests__/Carousel.a11y.known-failures.ts+++ b/packages/core/src/Carousel/__tests__/Carousel.a11y.known-failures.ts@@ -9,19 +9,4 @@import type {KnownFailure} from '@astryxdesign/a11y-spec';-export const CAROUSEL_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [- {- expectation: 'carousel.scroller.role-and-name',- binding: 'Carousel',- state: 'scroller-keyboard',- evidenceLayer: 'accessibility-tree',- failureEquals:- 'the browser exposes the focusable scroll container with no role',- standardsReference:- 'WCAG 2.2 4.1.2 Name, Role, Value; Astryx spec:AST-025 FR12 — a viewport that takes keyboard scrolling must provide an appropriate role and accessible name',- userImpact:- 'A keyboard user who tabs onto the scroll container hears nothing about where they are or what the arrow keys will do; the named region around it is the only clue.',- reason:- 'This test-only binding records the gap; naming the scroll container is a Carousel markup change that ships as its own spec-backed fix.',- },-];+export const CAROUSEL_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [];diff --git a/packages/core/src/hooks/useScrollOverflow.doc.mjs b/packages/core/src/hooks/useScrollOverflow.doc.mjsindex 18b5018553..f9b03d61af 100644--- a/packages/core/src/hooks/useScrollOverflow.doc.mjs+++ b/packages/core/src/hooks/useScrollOverflow.doc.mjs@@ -30,7 +30,7 @@ export const docs = {],usage: {description:- 'Tracks scroll overflow state for a horizontally scrollable container. Returns a ref callback and state booleans that update as the user scrolls or the container resizes. Uses scroll event listeners and ResizeObserver for reactive updates. Tolerance of 1px is applied to avoid sub-pixel false positives.',+ 'Tracks scroll overflow state for a horizontally scrollable container. Returns a ref callback and state booleans that update as the user scrolls, the container resizes, or its content changes (a child added, removed or resized, or a new gap or padding). Uses scroll event listeners, ResizeObserver and MutationObserver for reactive updates. Tolerance of 1px is applied to avoid sub-pixel false positives.',bestPractices: [{ guidance: true, description: 'Use to show/hide scroll navigation buttons or fade edges on carousels and horizontal lists.' },{ guidance: true, description: 'Apply the scrollRef to a container with overflow-x: auto or overflow-x: scroll.' },diff --git a/packages/core/src/hooks/useScrollOverflow.test.tsx b/packages/core/src/hooks/useScrollOverflow.test.tsxindex d6e3667f2b..8faccc3c70 100644--- a/packages/core/src/hooks/useScrollOverflow.test.tsx+++ b/packages/core/src/hooks/useScrollOverflow.test.tsx@@ -3,7 +3,8 @@/*** @file useScrollOverflow.test.tsx* @input Uses vitest, @testing-library/react, useScrollOverflow- * @output Unit tests for the hook's measurement and its rendered-only gate+ * @output Unit tests for the hook's measurement, what it observes (the+ * container's scroll and size, and its content), and its rendered-only gate* @position Testing; jsdom lays nothing out, so the scroll box is faked and* `checkVisibility` is stubbed per element.*/@@ -18,7 +19,10 @@ import {useScrollOverflow} from './useScrollOverflow';let deliverResize: ((entries: ResizeObserverEntry[]) => void) | null = null;class FakeResizeObserver implements ResizeObserver {+ /** The shared observer, so a test can read what it observes. */+ static last: FakeResizeObserver | null = null;constructor(callback: ResizeObserverCallback) {+ FakeResizeObserver.last = this;deliverResize = entries => callback(entries, this);}observe = vi.fn();@@ -69,7 +73,9 @@ beforeEach(() => {afterEach(() => {vi.unstubAllGlobals();+ vi.restoreAllMocks();deliverResize = null;+ FakeResizeObserver.last = null;});describe('useScrollOverflow', () => {@@ -200,6 +206,101 @@ describe('useScrollOverflow', () => {unmount();});+ // The overflow is the content's width against the container's: it changes+ // when the content does, with the container keeping its size.+ it('measures again when a child is added or removed, though the container keeps its size', async () => {+ const el = document.createElement('div');+ fakeScrollBox(el, {scrollWidth: 300, clientWidth: 300});+ stubRendered(el, true);+ const {result, unmount} = renderHook(() => useScrollOverflow());+ act(() => {+ result.current.scrollRef(el);+ });+ expect(result.current.hasOverflow).toBe(false);++ const child = document.createElement('div');+ fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300});+ await act(async () => {+ el.append(child);+ });+ expect(result.current.hasOverflow).toBe(true);++ fakeScrollBox(el, {scrollWidth: 300, clientWidth: 300});+ await act(async () => {+ child.remove();+ });+ expect(result.current.hasOverflow).toBe(false);+ unmount();+ });++ it('measures again when a child resizes, though the container keeps its size', () => {+ const el = document.createElement('div');+ const child = document.createElement('div');+ el.append(child);+ fakeScrollBox(el, {scrollWidth: 300, clientWidth: 300});+ stubRendered(el, true);+ const {result, unmount} = renderHook(() => useScrollOverflow());+ act(() => {+ result.current.scrollRef(el);+ });+ expect(result.current.hasOverflow).toBe(false);++ // The child's content grows past the container.+ fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300});+ act(() => {+ deliverResize?.([resizeEntry(child)]);+ });+ expect(result.current.hasOverflow).toBe(true);+ unmount();+ });++ it("measures again when the container's class or style changes, as a new gap does", async () => {+ const el = document.createElement('div');+ fakeScrollBox(el, {scrollWidth: 300, clientWidth: 300});+ stubRendered(el, true);+ const {result, unmount} = renderHook(() => useScrollOverflow());+ act(() => {+ result.current.scrollRef(el);+ });+ expect(result.current.hasOverflow).toBe(false);++ fakeScrollBox(el, {scrollWidth: 340, clientWidth: 300});+ await act(async () => {+ el.className = 'wider-gap';+ });+ expect(result.current.hasOverflow).toBe(true);++ fakeScrollBox(el, {scrollWidth: 300, clientWidth: 300});+ await act(async () => {+ el.style.columnGap = '0px';+ });+ expect(result.current.hasOverflow).toBe(false);+ unmount();+ });++ it('stops observing the content when the container detaches', () => {+ const el = document.createElement('div');+ const child = document.createElement('div');+ el.append(child);+ fakeScrollBox(el, {scrollWidth: 300, clientWidth: 300});+ stubRendered(el, true);+ const disconnect = vi.spyOn(MutationObserver.prototype, 'disconnect');+ const {result, unmount} = renderHook(() => useScrollOverflow());+ act(() => {+ result.current.scrollRef(el);+ });+ const observer = FakeResizeObserver.last;+ expect(observer?.observe).toHaveBeenCalledWith(child);++ act(() => {+ result.current.scrollRef(null);+ });+ expect(disconnect).toHaveBeenCalled();+ expect(observer?.unobserve).toHaveBeenCalledWith(child);+ expect(observer?.unobserve).toHaveBeenCalledWith(el);+ unmount();+ });+it('follows a scroll on a rendered container', () => {const el = document.createElement('div');fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300});diff --git a/packages/core/src/hooks/useScrollOverflow.ts b/packages/core/src/hooks/useScrollOverflow.tsindex e4e2d1867c..11818a5e47 100644--- a/packages/core/src/hooks/useScrollOverflow.ts+++ b/packages/core/src/hooks/useScrollOverflow.ts@@ -10,12 +10,15 @@* state** Observes a scroll container and reports whether content overflows at the- * start, end, or both edges. Updates on every scroll, and on a resize while- * the container is rendered: a layout read on an element the browser is not+ * start, end, or both edges. Updates on every scroll, and while the container+ * is rendered on what else changes the overflow with or without the+ * container resizing: its own size, a child's size (a slide's content+ * growing), a child added or removed, and its class or style (a new gap or+ * padding). A layout read on an element the browser is not* rendering (an ancestor with `display: none`, or a `content-visibility:* hidden` subtree) either answers zeros or makes the browser lay out that- * whole hidden subtree for the answer, so a resize observation delivered for- * a hidden container, and the measurement at registration inside one, are+ * whole hidden subtree for the answer, so an observation delivered for a+ * hidden container, and the measurement at registration inside one, are* skipped; the hook keeps its last state until the resize observation that* follows the reveal (one frame after it paints). A scroll is measured* whether or not the container is rendered: a scroll of a hidden container@@ -52,11 +55,57 @@ function isRendered(el: HTMLElement): boolean {return typeof el.checkVisibility !== 'function' || el.checkVisibility();}+/**+ * Observes what changes `el`'s overflow besides its scroll: its own size,+ * each child's size, the children added or removed, and its class or style.+ * Returns the teardown, which ends every observation.+ */+function observeContent(el: HTMLElement, measure: () => void): () => void {+ const unobserveContainer = observeResize(el, measure);+ const unobserveChildren = new Map<Element, () => void>();+ const followChildren = () => {+ const children = new Set(el.children);+ for (const [child, unobserve] of unobserveChildren) {+ if (!children.has(child)) {+ unobserve();+ unobserveChildren.delete(child);+ }+ }+ for (const child of children) {+ if (!unobserveChildren.has(child)) {+ unobserveChildren.set(child, observeResize(child, measure));+ }+ }+ };+ followChildren();+ const mutations =+ typeof MutationObserver === 'function'+ ? new MutationObserver(() => {+ followChildren();+ measure();+ })+ : null;+ mutations?.observe(el, {+ childList: true,+ attributes: true,+ attributeFilter: ['class', 'style'],+ });+ return () => {+ mutations?.disconnect();+ for (const unobserve of unobserveChildren.values()) {+ unobserve();+ }+ unobserveChildren.clear();+ unobserveContainer();+ };+}+/*** Tracks scroll overflow state for a horizontally scrollable container.** Returns a ref callback to attach to the scroll container and a state- * object that updates as the user scrolls or the container resizes.+ * object that updates as the user scrolls, the container resizes, or its+ * content changes.** @example* ```@@ -95,10 +144,10 @@ export function useScrollOverflow() {});}, []);- // Registration and resize: only a rendered container. A hidden one has no- // edges to report, and reading its layout would make the browser render- // the hidden subtree it sits in; the resize observation that follows the- // reveal measures again.+ // Registration, resize and content changes: only a rendered container. A+ // hidden one has no edges to report, and reading its layout would make the+ // browser render the hidden subtree it sits in; the resize observation that+ // follows the reveal measures again.const measure = useCallback(() => {const el = elRef.current;if (el && isRendered(el)) {@@ -129,7 +178,7 @@ export function useScrollOverflow() {if (el) {el.addEventListener('scroll', measureOnScroll, {passive: true});- unobserveRef.current = observeResize(el, measure);+ unobserveRef.current = observeContent(el, measure);}},[measure, measureOnScroll],