Skip to content

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

TypeScript

feat(carousel): add hasLoop wrap-around and handleRef imperative control (#4629)

freddymetac0cec5fc69a7
diff --git a/.changeset/carousel-loop-handle.md b/.changeset/carousel-loop-handle.md
new file mode 100644
index 0000000000..eec69285bd
--- /dev/null
+++ b/.changeset/carousel-loop-handle.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Carousel: add `hasLoop` for wrap-around scrolling (next at the end returns to the start, prev at the start jumps to the end; navigation buttons stay active at both edges) and a `handleRef` imperative handle (`CarouselHandle`) exposing `scrollNext`, `scrollPrev`, `scrollTo(index)`, `canScrollNext()`, and `canScrollPrev()` for programmatic control.
+@freddymeta
diff --git a/apps/storybook/stories/Carousel.stories.tsx b/apps/storybook/stories/Carousel.stories.tsx
index 16dd73bce9..12efada07d 100644
--- a/apps/storybook/stories/Carousel.stories.tsx
+++ b/apps/storybook/stories/Carousel.stories.tsx
@@ -1,11 +1,13 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {useState} from 'react';
+import {useRef, useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import * as stylex from '@stylexjs/stylex';
import {Carousel} from '@astryxdesign/core/Carousel';
+import type {CarouselHandle} from '@astryxdesign/core/Carousel';
import {Thumbnail} from '@astryxdesign/core/Thumbnail';
import {Card} from '@astryxdesign/core/Card';
+import {Button} from '@astryxdesign/core/Button';
import {
colorVars,
spacingVars,
@@ -81,6 +83,14 @@ const meta: Meta<typeof Carousel> = {
control: 'boolean',
description: 'Show navigation buttons on hover',
},
+ hasEdgeFade: {
+ control: 'boolean',
+ description: 'Show gradient edge-fade mask on overflow',
+ },
+ hasLoop: {
+ control: 'boolean',
+ description: 'Wrap-around scrolling (next at end → start)',
+ },
hasSnap: {
control: 'boolean',
description: 'Enable scroll-snap',
@@ -285,3 +295,73 @@ export const ColorSwatches: Story = {
);
},
};
+
+export const Loop: Story = {
+ name: 'Loop (Wrap-Around)',
+ render: () => (
+ <div {...stylex.props(styles.constrainedWidth)}>
+ <p {...stylex.props(styles.label)}>
+ Next at the end wraps to the start — buttons stay active at both edges
+ </p>
+ <Carousel gap={1} hasLoop hasSnap aria-label="Looping gallery">
+ {IMAGES.map(img => (
+ <Thumbnail
+ key={img.id}
+ src={img.src}
+ alt={img.label}
+ label={img.label}
+ />
+ ))}
+ </Carousel>
+ </div>
+ ),
+};
+
+export const ImperativeControl: Story = {
+ name: 'Imperative Control (handleRef)',
+ render: function ImperativeControlStory() {
+ const carouselRef = useRef<CarouselHandle>(null);
+ return (
+ <div {...stylex.props(styles.constrainedWidth)}>
+ <p {...stylex.props(styles.label)}>
+ External buttons driving the carousel through handleRef
+ </p>
+ <Carousel
+ handleRef={carouselRef}
+ gap={1}
+ hasSnap
+ hasButtons={false}
+ aria-label="Externally controlled gallery">
+ {IMAGES.map(img => (
+ <Thumbnail
+ key={img.id}
+ src={img.src}
+ alt={img.label}
+ label={img.label}
+ />
+ ))}
+ </Carousel>
+ <div style={{display: 'flex', gap: 8, marginTop: 12}}>
+ <Button
+ label="Previous"
+ variant="secondary"
+ size="sm"
+ onClick={() => carouselRef.current?.scrollPrev()}
+ />
+ <Button
+ label="Next"
+ variant="secondary"
+ size="sm"
+ onClick={() => carouselRef.current?.scrollNext()}
+ />
+ <Button
+ label="Jump to first"
+ variant="ghost"
+ size="sm"
+ onClick={() => carouselRef.current?.scrollTo(0)}
+ />
+ </div>
+ </div>
+ );
+ },
+};
diff --git a/packages/core/src/Carousel/Carousel.doc.mjs b/packages/core/src/Carousel/Carousel.doc.mjs
index 16db6fb64b..29eb79a63e 100644
--- a/packages/core/src/Carousel/Carousel.doc.mjs
+++ b/packages/core/src/Carousel/Carousel.doc.mjs
@@ -12,6 +12,7 @@ export const docs = {
'Carousel scrolls a row of items horizontally when they overflow the available width. Use it for card grids, image galleries, product lists, or any set of items that should be browsable without taking up the full page.',
bestPractices: [
{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: '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.'},
@@ -31,10 +32,12 @@ export const docs = {
{name: 'gap', type: "0 | 0.5 | 1 | 1.5 | 2 | 3 | 4", description: 'Gap between items using the spacing token scale.', default: '1'},
{name: 'hasButtons', type: 'boolean', description: 'Show prev/next navigation buttons when content is scrollable.', default: 'true'},
{name: 'hasEdgeFade', type: 'boolean', description: 'Show a gradient edge-fade mask when content overflows, signalling that more items exist off-screen.', default: 'true'},
+ {name: 'hasLoop', type: 'boolean', description: 'Wrap-around scrolling: next at the end scrolls to the start, prev at the start scrolls to the end. Buttons stay visible at both edges. Only engages when content overflows.', default: 'false'},
{name: 'hasSnap', type: 'boolean', description: 'Enable scroll-snap so each child snaps to the start edge.', default: 'false'},
{name: 'padding', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Inline padding inside the scroll container, with matching scroll-padding so snap points align to the content edge.'},
{name: 'aria-label', type: 'string', description: 'Accessible label for the carousel region.', default: "\'Carousel\'"},
{name: 'ref', type: 'React.Ref<HTMLDivElement>', description: 'Ref forwarded to the root element.'},
+ {name: 'handleRef', type: 'React.Ref<CarouselHandle>', description: 'Imperative handle exposing scrollNext(), scrollPrev(), scrollTo(index), canScrollNext(), and canScrollPrev() for programmatic scroll control.'},
{name: 'xstyle', type: 'StyleXStyles', description: 'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value.'},
{name: 'className', type: 'string', description: 'CSS class name for the root element. Prefer xstyle for styling.'},
{name: 'style', type: 'CSSProperties', description: 'Inline styles for the root element. Prefer xstyle.'},
@@ -75,9 +78,11 @@ export const docsZh = {
gap: '使用间距令牌比例的项目间距。',
hasButtons: '内容可滚动时显示上一个/下一个导航按钮。',
hasEdgeFade: '内容溢出时显示渐变边缘遮罩,提示屏幕外还有更多项目。',
+ hasLoop: '环绕滚动:在末尾按"下一个"回到开头,在开头按"上一个"跳到末尾。按钮在两端始终可见。仅在内容溢出时生效。',
hasSnap: '启用滚动吸附,使每个子元素吸附到起始边缘。',
padding: '滚动容器内的内联内边距,并设置匹配的 scroll-padding,使吸附点与内容边缘对齐。',
'aria-label': '轮播区域的无障碍标签。',
+ handleRef: '命令式句柄,暴露 scrollNext()、scrollPrev()、scrollTo(index)、canScrollNext() 和 canScrollPrev() 以进行编程式滚动控制。',
},
};
@@ -102,9 +107,11 @@ export const docsDense = {
gap: 'item spacing via spacing token scale',
hasButtons: 'prev/next buttons when content is scrollable',
hasEdgeFade: 'gradient edge-fade mask on overflow',
+ hasLoop: 'wrap-around: next at end -> start, prev at start -> end; buttons stay visible; only when overflowing',
hasSnap: 'scroll-snap; children snap to start edge',
padding: 'inline padding; scroll-padding keeps snap points on content edge',
'aria-label': 'accessible label for carousel region',
+ handleRef: 'imperative handle: scrollNext/scrollPrev/scrollTo(index)/canScrollNext/canScrollPrev',
'data-testid': 'test selector for automated testing frameworks',
},
};
diff --git a/packages/core/src/Carousel/Carousel.test.tsx b/packages/core/src/Carousel/Carousel.test.tsx
index e4fe08680c..3c0a368e35 100644
--- a/packages/core/src/Carousel/Carousel.test.tsx
+++ b/packages/core/src/Carousel/Carousel.test.tsx
@@ -1,8 +1,9 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect, vi} from 'vitest';
+import {createRef} from 'react';
import {render, screen, fireEvent} from '@testing-library/react';
-import {Carousel} from './Carousel';
+import {Carousel, type CarouselHandle} from './Carousel';
// Mock ResizeObserver (not available in jsdom)
class MockResizeObserver {
@@ -259,4 +260,234 @@ describe('Carousel', () => {
expect(scrollBy).not.toHaveBeenCalled();
});
});
+
+ describe('hasLoop', () => {
+ // jsdom doesn't lay out elements, so we fake an overflowing scroll
+ // container, force it to rest at an edge, and capture scrollBy calls.
+ function getScroller() {
+ const region = screen.getByRole('region');
+ return region.firstElementChild as HTMLElement;
+ }
+
+ function makeOverflowing(el: HTMLElement, scrollLeft: number) {
+ Object.defineProperty(el, 'scrollWidth', {
+ value: 500,
+ configurable: true,
+ });
+ Object.defineProperty(el, 'clientWidth', {
+ value: 200,
+ configurable: true,
+ });
+ Object.defineProperty(el, 'scrollLeft', {
+ value: scrollLeft,
+ writable: true,
+ configurable: true,
+ });
+ // Drive the overflow hook's scroll listener so overflowStart/End settle.
+ fireEvent.scroll(el);
+ }
+
+ it('keeps both navigation buttons enabled at the edges when looping', () => {
+ render(
+ <Carousel hasLoop aria-label="Looping">
+ <div>Item 1</div>
+ <div>Item 2</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+ // At the start edge: without loop the left button would be disabled.
+ makeOverflowing(scroller, 0);
+
+ expect(screen.getByLabelText('Scroll left')).toBeEnabled();
+ expect(screen.getByLabelText('Scroll right')).toBeEnabled();
+ });
+
+ it('wraps to the start when pressing next at the end', () => {
+ render(
+ <Carousel hasLoop aria-label="Looping">
+ <div>Item 1</div>
+ <div>Item 2</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+ // At the end edge (scrolled fully right): overflowEnd is false.
+ makeOverflowing(scroller, 300);
+ const scrollBy = vi.fn();
+ scroller.scrollBy = scrollBy;
+
+ fireEvent.click(screen.getByLabelText('Scroll right'));
+
+ // Overshoots toward the start by the full scroll width; the browser
+ // clamps to scrollLeft 0.
+ expect(scrollBy).toHaveBeenCalledWith({
+ left: -500,
+ behavior: 'smooth',
+ });
+ });
+
+ it('wraps to the end when pressing prev at the start', () => {
+ render(
+ <Carousel hasLoop aria-label="Looping">
+ <div>Item 1</div>
+ <div>Item 2</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+ makeOverflowing(scroller, 0);
+ const scrollBy = vi.fn();
+ scroller.scrollBy = scrollBy;
+
+ fireEvent.click(screen.getByLabelText('Scroll left'));
+
+ // Overshoots toward the end by the full scroll width.
+ expect(scrollBy).toHaveBeenCalledWith({
+ left: 500,
+ behavior: 'smooth',
+ });
+ });
+
+ it('does not wrap when content fits without overflowing', () => {
+ render(
+ <Carousel hasLoop aria-label="Looping">
+ <div>Only item</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+ Object.defineProperty(scroller, 'scrollWidth', {
+ value: 200,
+ configurable: true,
+ });
+ Object.defineProperty(scroller, 'clientWidth', {
+ value: 200,
+ configurable: true,
+ });
+ Object.defineProperty(scroller, 'scrollLeft', {
+ value: 0,
+ writable: true,
+ configurable: true,
+ });
+ fireEvent.scroll(scroller);
+ const scrollBy = vi.fn();
+ scroller.scrollBy = scrollBy;
+
+ // Buttons are hidden/disabled with no overflow; invoking scroll is a
+ // no-op wrap-wise — a normal (non-wrap) scrollBy still runs, but there
+ // is nothing to wrap to, so the overshoot branch must not fire.
+ fireEvent.click(screen.getByLabelText('Scroll right'));
+
+ // Either not called (button disabled) or called with a normal delta —
+ // never the full-scrollWidth overshoot.
+ if (scrollBy.mock.calls.length > 0) {
+ expect(scrollBy).not.toHaveBeenCalledWith(
+ expect.objectContaining({left: 500}),
+ );
+ expect(scrollBy).not.toHaveBeenCalledWith(
+ expect.objectContaining({left: -500}),
+ );
+ }
+ });
+ });
+
+ describe('handleRef', () => {
+ function getScroller() {
+ const region = screen.getByRole('region');
+ return region.firstElementChild as HTMLElement;
+ }
+
+ function makeOverflowing(el: HTMLElement, scrollLeft: number) {
+ Object.defineProperty(el, 'scrollWidth', {
+ value: 500,
+ configurable: true,
+ });
+ Object.defineProperty(el, 'clientWidth', {
+ value: 200,
+ configurable: true,
+ });
+ Object.defineProperty(el, 'scrollLeft', {
+ value: scrollLeft,
+ writable: true,
+ configurable: true,
+ });
+ fireEvent.scroll(el);
+ }
+
+ it('exposes scrollNext/scrollPrev that drive the scroll container', () => {
+ const handle = createRef<CarouselHandle>();
+ render(
+ <Carousel handleRef={handle} aria-label="Handle">
+ <div>Item 1</div>
+ <div>Item 2</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+ makeOverflowing(scroller, 100);
+ const scrollBy = vi.fn();
+ scroller.scrollBy = scrollBy;
+
+ handle.current?.scrollNext();
+ expect(scrollBy).toHaveBeenCalledTimes(1);
+ expect(scrollBy.mock.calls[0][0].left).toBeGreaterThan(0);
+
+ handle.current?.scrollPrev();
+ expect(scrollBy).toHaveBeenCalledTimes(2);
+ expect(scrollBy.mock.calls[1][0].left).toBeLessThan(0);
+ });
+
+ it('reports canScrollNext/canScrollPrev from live overflow state', () => {
+ const handle = createRef<CarouselHandle>();
+ render(
+ <Carousel handleRef={handle} aria-label="Handle">
+ <div>Item 1</div>
+ <div>Item 2</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+
+ // At the start: can scroll toward the end, not the start.
+ makeOverflowing(scroller, 0);
+ expect(handle.current?.canScrollPrev()).toBe(false);
+ expect(handle.current?.canScrollNext()).toBe(true);
+
+ // Scroll into the middle: both directions available.
+ makeOverflowing(scroller, 150);
+ expect(handle.current?.canScrollPrev()).toBe(true);
+ expect(handle.current?.canScrollNext()).toBe(true);
+ });
+
+ it('reports both directions scrollable under hasLoop when overflowing', () => {
+ const handle = createRef<CarouselHandle>();
+ render(
+ <Carousel handleRef={handle} hasLoop aria-label="Handle">
+ <div>Item 1</div>
+ <div>Item 2</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+ // Rest at the start edge — normally canScrollPrev would be false.
+ makeOverflowing(scroller, 0);
+
+ expect(handle.current?.canScrollPrev()).toBe(true);
+ expect(handle.current?.canScrollNext()).toBe(true);
+ });
+
+ it('scrollTo scrolls the container and clamps out-of-range indices', () => {
+ const handle = createRef<CarouselHandle>();
+ render(
+ <Carousel handleRef={handle} aria-label="Handle">
+ <div>Item 1</div>
+ <div>Item 2</div>
+ <div>Item 3</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+ const scrollBy = vi.fn();
+ scroller.scrollBy = scrollBy;
+
+ // Out-of-range index is clamped to the last item — no throw, one call.
+ expect(() => handle.current?.scrollTo(99)).not.toThrow();
+ expect(scrollBy).toHaveBeenCalledTimes(1);
+ // Uses scrollBy (contained to the carousel), never scrollIntoView.
+ expect(scrollBy.mock.calls[0][0]).toHaveProperty('left');
+ });
+ });
});
diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsx
index 3041fc857e..b100810e66 100644
--- a/packages/core/src/Carousel/Carousel.tsx
+++ b/packages/core/src/Carousel/Carousel.tsx
@@ -9,7 +9,9 @@
* @position Horizontal scroll container with fade-edge overflow indication,
* optional prev/next buttons on the top layer, scroll-snap, a 1px
* visual bleed allowance for child selection indicators, and Shift + wheel
- * mapping so mouse users can scroll horizontally. Exposes APG
+ * mapping so mouse users can scroll horizontally. Supports optional
+ * wrap-around looping and an imperative handle (handleRef) for programmatic
+ * 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".
@@ -25,6 +27,7 @@ import {
useRef,
useCallback,
useEffect,
+ useImperativeHandle,
Children,
isValidElement,
} from 'react';
@@ -48,8 +51,48 @@ import type {SpacingStep} from '../utils/types';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
+/**
+ * Imperative control surface for the Carousel, accessed via the `handleRef`
+ * prop. Methods drive the same native-scroll machinery as the built-in
+ * buttons, so they respect RTL, reduced-motion, and `hasLoop`.
+ */
+export interface CarouselHandle {
+ /**
+ * Scroll forward by roughly one viewport. With `hasLoop`, wraps to the
+ * start once the end is reached.
+ */
+ scrollNext(): void;
+ /**
+ * Scroll backward by roughly one viewport. With `hasLoop`, wraps to the
+ * end once the start is reached.
+ */
+ scrollPrev(): void;
+ /**
+ * Scroll the item at the given 0-based index to the start edge. The index
+ * is clamped to the item range, and only the carousel scrolls — the page
+ * position is left untouched.
+ */
+ scrollTo(index: number): void;
+ /**
+ * Whether there is scrollable content past the trailing edge. With
+ * `hasLoop`, returns true whenever the content overflows, since wrapping
+ * is always available. Reads live state — safe to call in an event handler.
+ */
+ canScrollNext(): boolean;
+ /**
+ * Whether there is scrollable content past the leading edge. With
+ * `hasLoop`, returns true whenever the content overflows. Reads live state.
+ */
+ canScrollPrev(): boolean;
+}
+
export interface CarouselProps extends BaseProps<HTMLDivElement> {
ref?: React.Ref<HTMLDivElement>;
+ /**
+ * Imperative handle for programmatic scroll control. Exposes scrollNext,
+ * scrollPrev, scrollTo, and the canScrollNext/canScrollPrev queries.
+ */
+ handleRef?: React.Ref<CarouselHandle>;
/** Carousel items — rendered in a horizontal scroll container. */
children: ReactNode;
/**
@@ -69,6 +112,16 @@ export interface CarouselProps extends BaseProps<HTMLDivElement> {
* @default true
*/
hasEdgeFade?: boolean;
+ /**
+ * Enable wrap-around scrolling. When the content overflows, pressing Next
+ * at the end scrolls back to the start, and Prev at the start scrolls to
+ * the end — for both the built-in buttons and the imperative handle. The
+ * navigation buttons stay visible at both edges instead of hiding, since a
+ * scroll is always available. Has no effect when the content fits without
+ * overflowing.
+ * @default false
+ */
+ hasLoop?: boolean;
/**
* Enable scroll-snap on items. Each direct child snaps to the start edge.
* @default false
@@ -269,10 +322,12 @@ const paddingStyles = stylex.create({
*/
export function Carousel({
ref,
+ handleRef,
children,
gap = 1,
hasButtons = true,
hasEdgeFade = true,
+ hasLoop = false,
hasSnap = false,
padding,
'aria-label': ariaLabelFromProps,
@@ -285,7 +340,8 @@ export function Carousel({
const t = useTranslator();
const ariaLabel = ariaLabelFromProps ?? t('@astryx.carousel.label');
const scrollElRef = useRef<HTMLElement | null>(null);
- const {scrollRef, overflowStart, overflowEnd} = useScrollOverflow();
+ const {scrollRef, overflowStart, overflowEnd, hasOverflow} =
+ useScrollOverflow();
// Children.toArray drops null/undefined/boolean children and assigns
// stable keys, so slide numbering ("Slide N of M") matches what actually
@@ -338,33 +394,100 @@ export function Carousel({
el.scrollBy({left: event.deltaY, behavior: 'auto'});
}, []);
- const scrollBy = useCallback((direction: -1 | 1) => {
+ const scrollBy = useCallback(
+ (direction: -1 | 1) => {
+ const el = scrollElRef.current;
+ if (!el) {
+ return;
+ }
+ // Respect the user's reduced-motion preference — mirrors the CSS
+ // scroll-behavior override so button-driven scrolling doesn't animate
+ // for users who opted out of motion.
+ const prefersReducedMotion =
+ typeof window !== 'undefined' &&
+ typeof window.matchMedia === 'function' &&
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ const behavior = prefersReducedMotion ? 'auto' : 'smooth';
+ // Under RTL the scroll axis is inverted (start is scrollLeft 0, the end
+ // is negative), so flip the physical delta sign.
+ const rtlSign = isRtlElement(el) ? -1 : 1;
+
+ // Wrap-around: when looping over overflowing content, a press that would
+ // run past an edge jumps to the opposite edge instead. Overshoot by the
+ // full scroll width in the opposite logical direction and let the browser
+ // clamp to the far edge — this reuses the same RTL sign convention as a
+ // normal scroll, so it stays direction-correct without special-casing.
+ if (hasLoop && hasOverflow) {
+ const atEnd = direction === 1 && !overflowEnd;
+ const atStart = direction === -1 && !overflowStart;
+ if (atEnd || atStart) {
+ el.scrollBy({left: rtlSign * -direction * el.scrollWidth, behavior});
+ return;
+ }
+ }
+
+ const firstChild = el.firstElementChild as HTMLElement | null;
+ const itemWidth = firstChild ? firstChild.offsetWidth : 0;
+ const amount = el.clientWidth - itemWidth * 0.5;
+ el.scrollBy({
+ // `direction` is the logical intent (-1 = toward content start, +1 =
+ // toward content end).
+ left: rtlSign * direction * Math.max(amount, itemWidth),
+ behavior,
+ });
+ },
+ [hasLoop, hasOverflow, overflowStart, overflowEnd],
+ );
+
+ const scrollToIndex = useCallback((index: number) => {
const el = scrollElRef.current;
- if (!el) {
+ const items = el?.children;
+ if (!el || !items || items.length === 0) {
return;
}
- const firstChild = el.firstElementChild as HTMLElement | null;
- const itemWidth = firstChild ? firstChild.offsetWidth : 0;
- const amount = el.clientWidth - itemWidth * 0.5;
- // Respect the user's reduced-motion preference — mirrors the CSS
- // scroll-behavior override so button-driven scrolling doesn't animate
- // for users who opted out of motion.
+ const clamped = Math.max(0, Math.min(index, items.length - 1));
+ const target = items[clamped] as HTMLElement;
const prefersReducedMotion =
typeof window !== 'undefined' &&
typeof window.matchMedia === 'function' &&
window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ // Bring the item to the start edge by scrolling the container by the
+ // measured gap between the item and the container edge. Using scrollBy
+ // (not scrollIntoView) keeps the scroll contained to the carousel and
+ // never moves ancestors or the page. In RTL the start edge is the right
+ // edge, so align the trailing edges instead of the leading ones.
+ const containerRect = el.getBoundingClientRect();
+ const itemRect = target.getBoundingClientRect();
+ const delta = isRtlElement(el)
+ ? itemRect.right - containerRect.right
+ : itemRect.left - containerRect.left;
el.scrollBy({
- // `direction` is the logical intent (-1 = toward content start, +1 =
- // toward content end). Under RTL the scroll axis is inverted (start is
- // scrollLeft 0, the end is negative), so flip the physical delta sign.
- left:
- (isRtlElement(el) ? -1 : 1) * direction * Math.max(amount, itemWidth),
+ left: delta,
behavior: prefersReducedMotion ? 'auto' : 'smooth',
});
}, []);
+ useImperativeHandle(
+ handleRef,
+ () => ({
+ scrollNext: () => scrollBy(1),
+ scrollPrev: () => scrollBy(-1),
+ scrollTo: (index: number) => scrollToIndex(index),
+ // With loop, either direction is reachable whenever the content
+ // overflows; otherwise reflect the live per-edge overflow state.
+ canScrollNext: () => (hasLoop ? hasOverflow : overflowEnd),
+ canScrollPrev: () => (hasLoop ? hasOverflow : overflowStart),
+ }),
+ [scrollBy, scrollToIndex, hasLoop, hasOverflow, overflowStart, overflowEnd],
+ );
+
+ // With loop, the buttons stay reachable at both edges as long as there's
+ // something to scroll; without loop they follow the per-edge overflow state.
+ const canScrollStart = hasLoop && hasOverflow ? true : overflowStart;
+ const canScrollEnd = hasLoop && hasOverflow ? true : overflowEnd;
+
const fadeStyle = hasEdgeFade
- ? overflowStart && overflowEnd
+ ? (hasLoop && hasOverflow) || (overflowStart && overflowEnd)
? styles.fadeBoth
: overflowStart
? styles.fadeStart
@@ -433,7 +556,7 @@ export function Carousel({
{...stylex.props(
styles.buttonPill,
styles.buttonPillStart,
- !overflowStart && styles.buttonHidden,
+ !canScrollStart && styles.buttonHidden,
)}>
<Button
icon={
@@ -449,7 +572,7 @@ export function Carousel({
// 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.
- isDisabled={!overflowStart}
+ isDisabled={!canScrollStart}
onClick={() => scrollBy(-1)}
xstyle={styles.buttonRadiusOverride}
/>
@@ -458,7 +581,7 @@ export function Carousel({
{...stylex.props(
styles.buttonPill,
styles.buttonPillEnd,
- !overflowEnd && styles.buttonHidden,
+ !canScrollEnd && styles.buttonHidden,
)}>
<Button
icon={
@@ -472,7 +595,7 @@ export function Carousel({
isIconOnly
// See "Scroll left" — disabled while visually hidden so the
// button stays mounted but out of the tab order / a11y tree.
- isDisabled={!overflowEnd}
+ isDisabled={!canScrollEnd}
onClick={() => scrollBy(1)}
xstyle={styles.buttonRadiusOverride}
/>
diff --git a/packages/core/src/Carousel/index.ts b/packages/core/src/Carousel/index.ts
index c60c6e0a77..ec2b0fe6ed 100644
--- a/packages/core/src/Carousel/index.ts
+++ b/packages/core/src/Carousel/index.ts
@@ -10,4 +10,4 @@
*/
export {Carousel} from './Carousel';
-export type {CarouselProps} from './Carousel';
+export type {CarouselProps, CarouselHandle} from './Carousel';