An open source design system that's fully customizable and agent ready
TypeScript
fix(Carousel): keep focus inside the carousel at a scroll edge, and expose the scroll container to themes (#5601)
Cindy Zhang73b00a51ded3
diff --git a/.changeset/carousel-edge-focus-and-theme-target.md b/.changeset/carousel-edge-focus-and-theme-target.mdnew file mode 100644index 0000000000..baade8cd37--- /dev/null+++ b/.changeset/carousel-edge-focus-and-theme-target.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Carousel no longer drops keyboard focus to the document body when reaching a scroll edge disables the nav button in use. Focus moves to the opposite arrow instead, on the state transition that disables the button rather than on a prediction from the press, so it holds under reduced motion, under scroll-snap, and on browsers without `scrollend`. The scroll container is also now a documented theme target, `astryx-carousel-scroller`, carrying the gap, padding, snap and edge-fade props it styles, so a theme can reach the spacing and the fade it could not see before.++@cixzhangdiff --git a/.github/a11y-baseline.json b/.github/a11y-baseline.jsonindex 705f2fef8e..18a558e6c1 100644--- a/.github/a11y-baseline.json+++ b/.github/a11y-baseline.json@@ -13,46 +13,6 @@"impact": "serious","helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"},- {- "key": "Carousel::Card Content::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },- {- "key": "Carousel::Custom Content (Swatches)::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },- {- "key": "Carousel::Default::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },- {- "key": "Carousel::Few Items (No Overflow)::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },- {- "key": "Carousel::Large Gap::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },- {- "key": "Carousel::Scroll Snap::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },- {- "key": "Carousel::Thumbnails with Remove::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },- {- "key": "Carousel::Without Buttons::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },{"key": "Chat::Message Status::color-contrast","impact": "serious",diff --git a/apps/storybook/stories/Carousel.stories.tsx b/apps/storybook/stories/Carousel.stories.tsxindex 12efada07d..a1260a8234 100644--- a/apps/storybook/stories/Carousel.stories.tsx+++ b/apps/storybook/stories/Carousel.stories.tsx@@ -24,6 +24,9 @@ const styles = stylex.create({constrainedWidth: {maxWidth: 400,},+ narrowWidth: {+ maxWidth: 240,+ },card: {width: 160,flexShrink: 0,@@ -81,7 +84,12 @@ const meta: Meta<typeof Carousel> = {},hasButtons: {control: 'boolean',- description: 'Show navigation buttons on hover',+ description: 'Show navigation buttons when the content can scroll',+ },+ padding: {+ control: {type: 'select'},+ options: [0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10],+ description: 'Inline padding inside the scroll container',},hasEdgeFade: {control: 'boolean',@@ -365,3 +373,98 @@ export const ImperativeControl: Story = {);},};++export const WithPadding: Story = {+ name: 'Inline Padding',+ render: () => (+ <div {...stylex.props(styles.constrainedWidth)}>+ <p {...stylex.props(styles.label)}>+ padding=3 puts the gutter inside the scroll area, and scroll-padding+ keeps snap points on the content edge+ </p>+ <Carousel gap={1} padding={3} hasSnap aria-label="Padded gallery">+ {IMAGES.map(img => (+ <Thumbnail+ key={img.id}+ src={img.src}+ alt={img.label}+ label={img.label}+ />+ ))}+ </Carousel>+ </div>+ ),+};++export const NarrowContainer: Story = {+ name: 'Narrow Container',+ render: () => (+ <div {...stylex.props(styles.narrowWidth)}>+ <p {...stylex.props(styles.label)}>240px container</p>+ <Carousel gap={1} aria-label="Narrow gallery">+ {IMAGES.map(img => (+ <Thumbnail+ key={img.id}+ src={img.src}+ alt={img.label}+ label={img.label}+ />+ ))}+ </Carousel>+ </div>+ ),+};++export const LongTextItems: Story = {+ name: 'Long Text Items',+ render: () => (+ <div {...stylex.props(styles.constrainedWidth)}>+ <p {...stylex.props(styles.label)}>+ One very long item among short ones, and a word with no break+ opportunity+ </p>+ <Carousel gap={2} aria-label="Text items">+ <Card xstyle={styles.card}>+ <div {...stylex.props(styles.cardInner)}>+ <p {...stylex.props(styles.cardDesc)}>Short</p>+ </div>+ </Card>+ <Card xstyle={styles.card}>+ <div {...stylex.props(styles.cardInner)}>+ <p {...stylex.props(styles.cardDesc)}>+ A much longer description that runs well past the width of its+ neighbours and has to wrap inside a fixed-width card without+ pushing the row out of shape.+ </p>+ </div>+ </Card>+ <Card xstyle={styles.card}>+ <div {...stylex.props(styles.cardInner)}>+ <p {...stylex.props(styles.cardDesc)}>+ Unbreakable:+ Donaudampfschiffahrtselektrizitaetenhauptbetriebswerkbauunterbeamtengesellschaft+ </p>+ </div>+ </Card>+ </Carousel>+ </div>+ ),+};++export const SingleItem: Story = {+ name: 'Single Item',+ render: () => (+ <div {...stylex.props(styles.constrainedWidth)}>+ <p {...stylex.props(styles.label)}>+ One child: no overflow, no fade, no buttons+ </p>+ <Carousel gap={1} aria-label="Single item">+ <Thumbnail+ src={IMAGES[0].src}+ alt={IMAGES[0].label}+ label={IMAGES[0].label}+ />+ </Carousel>+ </div>+ ),+};diff --git a/packages/core/src/Carousel/Carousel.doc.mjs b/packages/core/src/Carousel/Carousel.doc.mjsindex 600738ec8d..c9510e61bc 100644--- a/packages/core/src/Carousel/Carousel.doc.mjs+++ b/packages/core/src/Carousel/Carousel.doc.mjs@@ -14,6 +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: '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.'},@@ -55,6 +56,7 @@ export const docs = {theming: {targets: [{className: 'astryx-carousel'},+ {className: 'astryx-carousel-scroller', visualProps: ['gap', 'padding', 'snap', 'edgeFade']},],},};@@ -68,6 +70,7 @@ export const docsZh = {{guidance: true, description: '当每个项目应精确对齐到起始边缘时启用滚动吸附,例如画廊或产品列表。'},{guidance: true, description: '在小型可循环的集合(如照片画廊)上使用 hasLoop,此时从最后一项绕回第一项的滚动更自然。'},{guidance: true, description: '始终提供描述轮播内容的 aria-label,例如"精选产品"或"团队成员"。'},+ {guidance: true, description: 'Carousel 实现不含自动轮播的 WAI-ARIA APG carousel 模式(https://www.w3.org/WAI/ARIA/apg/patterns/carousel/):区域带有标签和 aria-roledescription="carousel",每个项目是名为“第 N 张,共 M 张”的 group,滚动容器可获得焦点,键盘用户可用方向键平移。'},{guidance: true, description: '使用一致的间距和项目宽度,让轮播看起来是有意为之,而不是内容意外溢出。'},{guidance: true, description: '信任内置导航:触控板用户可水平滑动,鼠标用户可按住 Shift 滚动滚轮来浏览项目。'},{guidance: false, description: '将每位用户都必须看到的内容放入轮播。并非所有人都会水平滚动,关键内容应放在首屏。'},diff --git a/packages/core/src/Carousel/Carousel.test.tsx b/packages/core/src/Carousel/Carousel.test.tsxindex 3c0a368e35..db2942b1d4 100644--- a/packages/core/src/Carousel/Carousel.test.tsx+++ b/packages/core/src/Carousel/Carousel.test.tsx@@ -3,6 +3,7 @@import {describe, it, expect, vi} from 'vitest';import {createRef} from 'react';import {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)@@ -490,4 +491,363 @@ describe('Carousel', () => {expect(scrollBy.mock.calls[0][0]).toHaveProperty('left');});});++ describe('keyboard focus at the edges', () => {+ function getScroller() {+ const region = screen.getByRole('region');+ return region.firstElementChild as HTMLElement;+ }++ // jsdom has no layout, so fake an overflowing container whose scrollBy+ // moves scrollLeft and fires scroll, which is what drives the overflow+ // state the buttons and the focus hand-off both read. `land` decides where+ // the container comes to rest: the default clamps to the requested delta,+ // and the snap arm overrides it to model mandatory scroll-snap carrying the+ // container past what the press asked for.+ function makeScrollable(+ el: HTMLElement,+ scrollWidth: number,+ land?: (requested: number, maxScroll: number) => number,+ ) {+ const clientWidth = 200;+ const maxScroll = scrollWidth - clientWidth;+ Object.defineProperty(el, 'scrollWidth', {+ value: scrollWidth,+ configurable: true,+ });+ Object.defineProperty(el, 'clientWidth', {+ value: clientWidth,+ configurable: true,+ });+ Object.defineProperty(el, 'scrollLeft', {+ value: 0,+ writable: true,+ configurable: true,+ });+ el.scrollBy = ((options: ScrollToOptions) => {+ const requested = Math.max(+ 0,+ Math.min(maxScroll, el.scrollLeft + (options.left ?? 0)),+ );+ el.scrollLeft = land ? land(requested, maxScroll) : requested;+ fireEvent.scroll(el);+ }) as HTMLElement['scrollBy'];+ fireEvent.scroll(el);+ }++ it('hands focus to the opposite button when the edge disables the one in use', async () => {+ const user = userEvent.setup();+ render(+ <Carousel aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ <div>Item 3</div>+ </Carousel>,+ );+ // clientWidth 200 against a 200px step, so one press lands exactly on the+ // trailing edge and the trailing button disables.+ makeScrollable(getScroller(), 400);++ const next = screen.getByLabelText('Scroll right');+ await user.click(next);++ expect(next).toBeDisabled();+ expect(document.activeElement).toBe(screen.getByLabelText('Scroll left'));+ expect(document.activeElement).not.toBe(document.body);+ });++ it('hands off in the leading direction too', async () => {+ const user = userEvent.setup();+ render(+ <Carousel aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ <div>Item 3</div>+ </Carousel>,+ );+ const scroller = getScroller();+ makeScrollable(scroller, 400);+ // Park at the far end so the leading button is the one that runs out.+ scroller.scrollLeft = 200;+ fireEvent.scroll(scroller);++ const previous = screen.getByLabelText('Scroll left');+ await user.click(previous);++ expect(previous).toBeDisabled();+ expect(document.activeElement).toBe(+ screen.getByLabelText('Scroll right'),+ );+ });++ it('hands off under RTL, where the scroll axis is inverted', async () => {+ const user = userEvent.setup();+ render(+ <Carousel aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ <div>Item 3</div>+ </Carousel>,+ );+ const scroller = getScroller();+ // The component resolves direction with getComputedStyle, and jsdom does+ // not inherit `dir` down to it, so set it on the element itself. RTL then+ // scrolls negative, which the mock below mirrors.+ scroller.style.direction = 'rtl';+ const maxScroll = 200;+ Object.defineProperty(scroller, 'scrollWidth', {+ value: 400,+ configurable: true,+ });+ Object.defineProperty(scroller, 'clientWidth', {+ value: 200,+ configurable: true,+ });+ Object.defineProperty(scroller, 'scrollLeft', {+ value: 0,+ writable: true,+ configurable: true,+ });+ scroller.scrollBy = ((options: ScrollToOptions) => {+ scroller.scrollLeft = Math.max(+ -maxScroll,+ Math.min(0, scroller.scrollLeft + (options.left ?? 0)),+ );+ fireEvent.scroll(scroller);+ }) as HTMLElement['scrollBy'];+ fireEvent.scroll(scroller);++ const next = screen.getByLabelText('Scroll right');+ await user.click(next);++ expect(next).toBeDisabled();+ expect(document.activeElement).toBe(screen.getByLabelText('Scroll left'));+ });++ it('hands off when scroll-snap carries the container past what the press asked for', async () => {+ const user = userEvent.setup();+ render(+ <Carousel hasSnap aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ <div>Item 3</div>+ </Carousel>,+ );+ // 700 gives 500 of travel against a 200 step, so the press alone lands+ // mid-run. Mandatory snapping then carries it to the end, which is the+ // landing position no press can predict.+ makeScrollable(getScroller(), 700, (_requested, maxScroll) => maxScroll);++ const next = screen.getByLabelText('Scroll right');+ await user.click(next);++ expect(next).toBeDisabled();+ expect(document.activeElement).toBe(screen.getByLabelText('Scroll left'));+ });++ it('falls back to the scroll container when the carousel stops overflowing', async () => {+ const user = userEvent.setup();+ render(+ <Carousel aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ </Carousel>,+ );+ const scroller = getScroller();+ // The content shrinks to fit during the press, so BOTH buttons disable+ // and there is no opposite control left to receive focus.+ makeScrollable(scroller, 400, () => {+ Object.defineProperty(scroller, 'scrollWidth', {+ value: 200,+ configurable: true,+ });+ return 0;+ });++ await user.click(screen.getByLabelText('Scroll right'));++ expect(screen.getByLabelText('Scroll right')).toBeDisabled();+ expect(screen.getByLabelText('Scroll left')).toBeDisabled();+ expect(document.activeElement).toBe(scroller);+ expect(document.activeElement).not.toBe(document.body);+ });++ it('does not pull focus back after the person has left the button', () => {+ render(+ <Carousel aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ <div>Item 3</div>+ </Carousel>,+ );+ const scroller = getScroller();+ makeScrollable(scroller, 400);++ // Touch an arrow, then leave it without pressing it. Landing on <body> is+ // the case that matters: focus somewhere else is already ignored, so a+ // stale tracker only bites when there is nothing else holding focus.+ const next = screen.getByLabelText('Scroll right');+ next.focus();+ next.blur();+ expect(document.activeElement).toBe(document.body);++ // The carousel reaches the edge on its own: a swipe, a resize, anything+ // that is not this person. Their focus is not the carousel's to take.+ scroller.scrollLeft = 200;+ fireEvent.scroll(scroller);++ expect(screen.getByLabelText('Scroll right')).toBeDisabled();+ expect(document.activeElement).toBe(document.body);+ });++ it('hands off on a press, with the blur handlers in place', async () => {+ const user = userEvent.setup();+ render(+ <Carousel aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ <div>Item 3</div>+ </Carousel>,+ );+ makeScrollable(getScroller(), 400);++ // The Effect clears the tracker itself before focusing, so the commit's+ // own blur finds nothing left to clear and the guard is not what makes+ // this pass. It is here so that deleting the blur handlers outright --+ // rather than loosening the guard -- is caught.+ await user.click(screen.getByLabelText('Scroll right'));++ expect(document.activeElement).toBe(screen.getByLabelText('Scroll left'));+ });++ it('does not move focus on a press that leaves the direction available', async () => {+ const user = userEvent.setup();+ render(+ <Carousel aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ <div>Item 3</div>+ </Carousel>,+ );+ makeScrollable(getScroller(), 600);++ const next = screen.getByLabelText('Scroll right');+ await user.click(next);++ expect(next).toBeEnabled();+ expect(document.activeElement).toBe(next);+ });++ it('does not move focus when hasLoop keeps both buttons enabled', async () => {+ const user = userEvent.setup();+ render(+ <Carousel hasLoop aria-label="Looping">+ <div>Item 1</div>+ <div>Item 2</div>+ </Carousel>,+ );+ makeScrollable(getScroller(), 400);++ const next = screen.getByLabelText('Scroll right');+ await user.click(next);++ expect(next).toBeEnabled();+ expect(document.activeElement).toBe(next);+ });++ it('takes focus without scrolling the receiver into view', async () => {+ const user = userEvent.setup();+ render(+ <Carousel aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ </Carousel>,+ );+ makeScrollable(getScroller(), 400);+ const previous = screen.getByLabelText('Scroll left');+ const focus = vi.spyOn(previous, 'focus');++ await user.click(screen.getByLabelText('Scroll right'));++ // A plain focus() scrolls its element into view, which on the scroll+ // container cancels the scroll the same press started.+ expect(focus).toHaveBeenCalledWith({preventScroll: true});+ });++ it('leaves focus alone when the imperative handle drives the scroll', () => {+ const handle = createRef<CarouselHandle>();+ render(+ <Carousel handleRef={handle} aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ </Carousel>,+ );+ makeScrollable(getScroller(), 400);+ const outside = document.createElement('button');+ document.body.appendChild(outside);+ outside.focus();++ handle.current?.scrollNext();++ expect(document.activeElement).toBe(outside);+ outside.remove();+ });++ it('does not move focus a second time for one transition', async () => {+ const user = userEvent.setup();+ const {rerender} = render(+ <Carousel aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ <div>Item 3</div>+ </Carousel>,+ );+ makeScrollable(getScroller(), 400);+ await user.click(screen.getByLabelText('Scroll right'));++ const previous = screen.getByLabelText('Scroll left');+ expect(document.activeElement).toBe(previous);+ // Park focus outside and re-render: the transition is spent, so nothing+ // may pull focus back in.+ const outside = document.createElement('button');+ document.body.appendChild(outside);+ outside.focus();+ rerender(+ <Carousel aria-label="Gallery">+ <div>Item 1</div>+ <div>Item 2</div>+ <div>Item 3</div>+ </Carousel>,+ );++ expect(document.activeElement).toBe(outside);+ outside.remove();+ });++ it('reflects the scroll container as a theme target carrying its style-driving props', () => {+ render(+ <Carousel gap={2} padding={3} hasSnap aria-label="Gallery">+ <div>Item 1</div>+ </Carousel>,+ );+ const scroller = getScroller();+ expect(scroller).toHaveClass('astryx-carousel-scroller');+ expect(scroller).toHaveAttribute('data-gap', '2');+ expect(scroller).toHaveAttribute('data-padding', '3');+ expect(scroller).toHaveAttribute('data-snap', 'snap');+ expect(scroller).toHaveAttribute('data-edge-fade', 'edge-fade');+ });++ it('omits the opt-out attributes a theme should not see', () => {+ render(+ <Carousel hasEdgeFade={false} aria-label="Gallery">+ <div>Item 1</div>+ </Carousel>,+ );+ const scroller = getScroller();+ expect(scroller).not.toHaveAttribute('data-edge-fade');+ expect(scroller).not.toHaveAttribute('data-snap');+ expect(scroller).not.toHaveAttribute('data-padding');+ });+ });});diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsxindex 0a668d17f5..8c08f1a120 100644--- a/packages/core/src/Carousel/Carousel.tsx+++ b/packages/core/src/Carousel/Carousel.tsx@@ -176,12 +176,6 @@ const styles = stylex.create({},scrollbarWidth: 'none',maskImage: 'none',- transitionProperty: 'mask-image',- transitionDuration: {- default: durationVars['--duration-medium'],- '@media (prefers-reduced-motion: reduce)': '0ms',- },- transitionTimingFunction: easeVars['--ease-standard'],},fadeStart: {maskImage: `linear-gradient(to right, transparent 0%, rgba(0,0,0,0.3) 2px, black ${spacingVars['--spacing-1']})`,@@ -341,6 +335,13 @@ export function Carousel({const t = useTranslator();const ariaLabel = ariaLabelFromProps ?? t('@astryx.carousel.label');const scrollElRef = useRef<HTMLElement | null>(null);+ const startButtonRef = useRef<HTMLButtonElement>(null);+ const endButtonRef = useRef<HTMLButtonElement>(null);+ // Which nav button last held focus, and what the overflow state was on the+ // previous render. Together they are how the Effect below recognises the one+ // transition it is allowed to act on.+ const focusedNavRef = useRef<'start' | 'end' | null>(null);+ const prevCanScrollRef = useRef<{start: boolean; end: boolean} | null>(null);const {scrollRef, overflowStart, overflowEnd, hasOverflow} =useScrollOverflow();@@ -487,6 +488,76 @@ export function Carousel({const canScrollStart = hasLoop && hasOverflow ? true : overflowStart;const canScrollEnd = hasLoop && hasOverflow ? true : overflowEnd;+ // Keep the keyboard user where they are when a nav button disables under+ // them. The browser drops focus off a control it disables, so reaching an+ // edge used to land the user on <body> and cost them their place in the page.+ //+ // This is an Effect on purpose, and the exception is narrow. The thing that+ // disables the button IS this state transition, so it is the only correct+ // trigger: three attempts to predict it from the press -- the position after+ // the scroll, the position before it plus the step, and the settled position+ // reported by `scrollend` -- were each wrong somewhere, under reduced motion,+ // under mandatory scroll-snap, and on a browser that never fires the event.+ // Running after the commit also makes the opposite button a valid receiver,+ // which it is not during the press: at that moment it is still disabled and+ // focus() on a disabled control does nothing. Ruled acceptable by the+ // maintainer, 2026-08-27, on the conditions encoded below: it acts only on+ // the transition that newly disables the focused button, it moves focus and+ // nothing else, and it cannot fire twice for one transition.+ //+ // Which button the person is on is tracked by the buttons' own focus and blur+ // handlers, and the blur has to ignore the one the commit itself causes: a+ // tracker that outlived the person let a later edge -- a swipe, a resize, no+ // press at all -- pull their focus back onto a control they never chose.+ useEffect(() => {+ const previous = prevCanScrollRef.current;+ prevCanScrollRef.current = {start: canScrollStart, end: canScrollEnd};+ const side = focusedNavRef.current;+ if (previous == null || side == null) {+ return;+ }++ // Only the edge that just ran out, and only while it held focus. An edge+ // that was already disabled, or one the user was not on, is not ours.+ const wasEnabled = side === 'start' ? previous.start : previous.end;+ const isEnabled = side === 'start' ? canScrollStart : canScrollEnd;+ if (!wasEnabled || isEnabled) {+ return;+ }++ const pressed =+ side === 'start' ? startButtonRef.current : endButtonRef.current;+ if (pressed == null) {+ return;+ }+ // The browser has already blurred it, so focus reads as the body. Anything+ // else means the user moved on themselves and this is not ours to redirect.+ const active = pressed.ownerDocument.activeElement;+ if (active !== pressed && active !== pressed.ownerDocument.body) {+ return;+ }++ const opposite =+ side === 'start' ? endButtonRef.current : startButtonRef.current;+ // The opposite button is the receiver. It is disabled only when the+ // carousel stopped overflowing entirely, which happens when its content+ // shrinks; the scroll container is then the nearest tab stop still inside+ // the labelled region.+ const receiver =+ opposite != null && !opposite.disabled ? opposite : scrollElRef.current;+ if (receiver == null) {+ return;+ }++ // One move per transition: clearing the tracker first means a re-render or+ // a StrictMode double-invoke re-runs this and returns at the `side == null`+ // guard above. Focusing the receiver sets it again, to the other side.+ focusedNavRef.current = null;+ // preventScroll: a plain focus() scrolls its element into view, which on+ // the scroll container cancels the scroll the press just started.+ receiver.focus({preventScroll: true});+ }, [canScrollStart, canScrollEnd]);+const fadeStyle = hasEdgeFade? (hasLoop && hasOverflow) || (overflowStart && overflowEnd)? styles.fadeBoth@@ -523,12 +594,20 @@ export function Carousel({ref={composedRef}tabIndex={0}onWheel={handleWheel}- {...stylex.props(- styles.scroller,- gapStyles[gap],- padding != null && paddingStyles[padding],- hasSnap && styles.snap,- fadeStyle,+ {...mergeProps(+ themeProps('carousel-scroller', {+ gap,+ padding,+ snap: hasSnap ? 'snap' : null,+ edgeFade: hasEdgeFade ? 'edge-fade' : null,+ }),+ stylex.props(+ styles.scroller,+ gapStyles[gap],+ padding != null && paddingStyles[padding],+ hasSnap && styles.snap,+ fadeStyle,+ ),)}>{slides.map((child, index) => (// APG carousel pattern: each slide container is a group with@@ -560,6 +639,7 @@ export function Carousel({!canScrollStart && styles.buttonHidden,)}><Button+ ref={startButtonRef}icon={<Iconicon="chevronLeft"@@ -572,10 +652,21 @@ export function Carousel({size="sm"isIconOnly// Disabled when there's nothing to scroll toward. Keeps the- // button mounted (stable layout/focus) but removes it from the- // tab order and a11y tree while it's visually hidden, so- // keyboard users don't land on an invisible control.+ // button mounted (stable layout) but removes it from the tab+ // order and a11y tree while it's visually hidden, so keyboard+ // users don't land on an invisible control. The Effect above+ // hands focus to the other button when the state behind this+ // one flips it disabled.isDisabled={!canScrollStart}+ onFocus={() => {+ focusedNavRef.current = 'start';+ }}+ onBlur={event => {+ // A disabled button was blurred by the commit, not the person.+ if (!event.currentTarget.disabled) {+ focusedNavRef.current = null;+ }+ }}onClick={() => scrollBy(-1)}xstyle={styles.buttonRadiusOverride}/>@@ -587,6 +678,7 @@ export function Carousel({!canScrollEnd && styles.buttonHidden,)}><Button+ ref={endButtonRef}icon={<Iconicon="chevronRight"@@ -601,6 +693,15 @@ export function Carousel({// See "Scroll left" — disabled while visually hidden so the// button stays mounted but out of the tab order / a11y tree.isDisabled={!canScrollEnd}+ onFocus={() => {+ focusedNavRef.current = 'end';+ }}+ onBlur={event => {+ // A disabled button was blurred by the commit, not the person.+ if (!event.currentTarget.disabled) {+ focusedNavRef.current = null;+ }+ }}onClick={() => scrollBy(1)}xstyle={styles.buttonRadiusOverride}/>