An open source design system that's fully customizable and agent ready
TypeScript
feat(Carousel): add XDSCarousel horizontal scroll container (#1292)
Cindy Zhang193f2bd30c76
diff --git a/apps/storybook/stories/Carousel.stories.tsx b/apps/storybook/stories/Carousel.stories.tsxnew file mode 100644index 0000000000..50dbac3a62--- /dev/null+++ b/apps/storybook/stories/Carousel.stories.tsx@@ -0,0 +1,285 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import * as stylex from '@stylexjs/stylex';+import {XDSCarousel} from '@xds/core/Carousel';+import {XDSThumbnail} from '@xds/core/Thumbnail';+import {XDSCard} from '@xds/core/Card';+import {+ colorVars,+ spacingVars,+ typographyVars,+ radiusVars,+} from '@xds/core/theme/tokens.stylex';++const styles = stylex.create({+ pageWrapper: {+ backgroundColor: colorVars['--color-background-body'],+ padding: spacingVars['--spacing-6'],+ fontFamily: typographyVars['--font-family-body'],+ },+ constrainedWidth: {+ maxWidth: 400,+ },+ card: {+ width: 160,+ flexShrink: 0,+ },+ cardInner: {+ padding: spacingVars['--spacing-3'],+ },+ cardTitle: {+ margin: 0,+ fontSize: 14,+ fontWeight: 600,+ color: colorVars['--color-text-primary'],+ fontFamily: typographyVars['--font-family-body'],+ },+ cardDesc: {+ margin: 0,+ fontSize: 12,+ color: colorVars['--color-text-secondary'],+ fontFamily: typographyVars['--font-family-body'],+ },+ colorSwatch: {+ width: 80,+ height: 80,+ borderRadius: radiusVars['--radius-element'],+ flexShrink: 0,+ },+ label: {+ fontSize: 12,+ color: colorVars['--color-text-secondary'],+ marginBottom: spacingVars['--spacing-2'],+ fontFamily: typographyVars['--font-family-body'],+ },+});++const IMAGES = [+ {id: 1, src: 'https://picsum.photos/id/1042/200/200', label: 'dark.jpg'},+ {id: 2, src: 'https://picsum.photos/id/1043/200/200', label: 'light.jpg'},+ {id: 3, src: 'https://picsum.photos/id/1044/200/200', label: 'warm.jpg'},+ {id: 4, src: 'https://picsum.photos/id/1047/200/200', label: 'mixed.jpg'},+ {id: 5, src: 'https://picsum.photos/id/1050/200/200', label: 'nature.jpg'},+ {id: 6, src: 'https://picsum.photos/id/1055/200/200', label: 'city.jpg'},+ {id: 7, src: 'https://picsum.photos/id/1060/200/200', label: 'ocean.jpg'},+ {id: 8, src: 'https://picsum.photos/id/1069/200/200', label: 'forest.jpg'},+];++const meta: Meta<typeof XDSCarousel> = {+ title: 'Core/XDSCarousel',+ component: XDSCarousel,+ tags: ['autodocs'],+ argTypes: {+ gap: {+ control: {type: 'select'},+ options: [0, 0.5, 1, 1.5, 2, 3, 4],+ description: 'Gap between items',+ },+ hasButtons: {+ control: 'boolean',+ description: 'Show navigation buttons on hover',+ },+ hasSnap: {+ control: 'boolean',+ description: 'Enable scroll-snap',+ },+ },+ decorators: [+ Story => (+ <div {...stylex.props(styles.pageWrapper)}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof XDSCarousel>;++export const Default: Story = {+ render: () => (+ <div {...stylex.props(styles.constrainedWidth)}>+ <p {...stylex.props(styles.label)}>Scroll or hover for arrows →</p>+ <XDSCarousel gap={1} aria-label="Photo thumbnails">+ {IMAGES.map(img => (+ <XDSThumbnail+ key={img.id}+ src={img.src}+ alt={img.label}+ label={img.label}+ />+ ))}+ </XDSCarousel>+ </div>+ ),+};++export const WithRemove: Story = {+ name: 'Thumbnails with Remove',+ render: function WithRemoveStory() {+ const [items, setItems] = useState(IMAGES);+ return (+ <div {...stylex.props(styles.constrainedWidth)}>+ <p {...stylex.props(styles.label)}>{items.length} attachments</p>+ <XDSCarousel gap={1} aria-label="Attached files">+ {items.map(img => (+ <XDSThumbnail+ key={img.id}+ src={img.src}+ alt={img.label}+ label={img.label}+ onRemove={() =>+ setItems(prev => prev.filter(i => i.id !== img.id))+ }+ />+ ))}+ </XDSCarousel>+ {items.length === 0 && (+ <p {...stylex.props(styles.label)}>+ All removed. <button onClick={() => setItems(IMAGES)}>Reset</button>+ </p>+ )}+ </div>+ );+ },+};++export const FewItems: Story = {+ name: 'Few Items (No Overflow)',+ render: () => (+ <div {...stylex.props(styles.constrainedWidth)}>+ <p {...stylex.props(styles.label)}>No overflow — no fade, no buttons</p>+ <XDSCarousel gap={1} aria-label="Small gallery">+ {IMAGES.slice(0, 3).map(img => (+ <XDSThumbnail+ key={img.id}+ src={img.src}+ alt={img.label}+ label={img.label}+ />+ ))}+ </XDSCarousel>+ </div>+ ),+};++export const Cards: Story = {+ name: 'Card Content',+ render: () => {+ const cards = [+ {id: 1, title: 'Design System', desc: 'Component library'},+ {id: 2, title: 'Documentation', desc: 'API reference'},+ {id: 3, title: 'Storybook', desc: 'Visual testing'},+ {id: 4, title: 'Theme Config', desc: 'Token overrides'},+ {id: 5, title: 'CLI Tools', desc: 'Code generation'},+ {id: 6, title: 'Accessibility', desc: 'ARIA patterns'},+ ];+ return (+ <div style={{maxWidth: 500}}>+ <p {...stylex.props(styles.label)}>Cards in a carousel</p>+ <XDSCarousel gap={2} hasSnap aria-label="Feature cards">+ {cards.map(card => (+ <XDSCard key={card.id} xstyle={styles.card}>+ <div {...stylex.props(styles.cardInner)}>+ <p {...stylex.props(styles.cardTitle)}>{card.title}</p>+ <p {...stylex.props(styles.cardDesc)}>{card.desc}</p>+ </div>+ </XDSCard>+ ))}+ </XDSCarousel>+ </div>+ );+ },+};++export const NoButtons: Story = {+ name: 'Without Buttons',+ render: () => (+ <div {...stylex.props(styles.constrainedWidth)}>+ <p {...stylex.props(styles.label)}>Scroll only — no arrow buttons</p>+ <XDSCarousel gap={1} hasButtons={false} aria-label="Scroll-only gallery">+ {IMAGES.map(img => (+ <XDSThumbnail+ key={img.id}+ src={img.src}+ alt={img.label}+ label={img.label}+ />+ ))}+ </XDSCarousel>+ </div>+ ),+};++export const WithSnap: Story = {+ name: 'Scroll Snap',+ render: () => (+ <div {...stylex.props(styles.constrainedWidth)}>+ <p {...stylex.props(styles.label)}>Snaps to items on scroll</p>+ <XDSCarousel gap={2} hasSnap aria-label="Snapping gallery">+ {IMAGES.map(img => (+ <XDSThumbnail+ key={img.id}+ src={img.src}+ alt={img.label}+ label={img.label}+ />+ ))}+ </XDSCarousel>+ </div>+ ),+};++export const LargeGap: Story = {+ name: 'Large Gap',+ render: () => (+ <div {...stylex.props(styles.constrainedWidth)}>+ <p {...stylex.props(styles.label)}>gap=4 (16px)</p>+ <XDSCarousel gap={4} aria-label="Spaced gallery">+ {IMAGES.map(img => (+ <XDSThumbnail+ key={img.id}+ src={img.src}+ alt={img.label}+ label={img.label}+ />+ ))}+ </XDSCarousel>+ </div>+ ),+};++export const ColorSwatches: Story = {+ name: 'Custom Content (Swatches)',+ render: () => {+ const colors = [+ '#e74c3c',+ '#e67e22',+ '#f1c40f',+ '#2ecc71',+ '#1abc9c',+ '#3498db',+ '#9b59b6',+ '#34495e',+ '#e84393',+ '#00cec9',+ '#6c5ce7',+ '#fdcb6e',+ ];+ return (+ <div style={{maxWidth: 360}}>+ <p {...stylex.props(styles.label)}>Any content works as children</p>+ <XDSCarousel gap={1.5} aria-label="Color swatches">+ {colors.map(color => (+ <div+ key={color}+ {...stylex.props(styles.colorSwatch)}+ style={{backgroundColor: color}}+ title={color}+ />+ ))}+ </XDSCarousel>+ </div>+ );+ },+};diff --git a/packages/core/package.json b/packages/core/package.jsonindex 867d9504be..993a32eef9 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -88,6 +88,12 @@"import": "./dist/Card/index.mjs","require": "./dist/Card/index.js"},+ "./Carousel": {+ "source": "./src/Carousel/index.ts",+ "types": "./dist/Carousel/index.d.ts",+ "import": "./dist/Carousel/index.mjs",+ "require": "./dist/Carousel/index.js"+ },"./Center": {"source": "./src/Center/index.ts","types": "./dist/Center/index.d.ts",diff --git a/packages/core/src/Carousel/XDSCarousel.test.tsx b/packages/core/src/Carousel/XDSCarousel.test.tsxnew file mode 100644index 0000000000..06ab6a2fea--- /dev/null+++ b/packages/core/src/Carousel/XDSCarousel.test.tsx@@ -0,0 +1,57 @@+import {describe, it, expect, vi} from 'vitest';+import {render, screen} from '@testing-library/react';+import {XDSCarousel} from './XDSCarousel';++// Mock ResizeObserver (not available in jsdom)+class MockResizeObserver {+ callback: ResizeObserverCallback;+ constructor(callback: ResizeObserverCallback) {+ this.callback = callback;+ }+ observe() {}+ unobserve() {}+ disconnect() {}+}+vi.stubGlobal('ResizeObserver', MockResizeObserver);++describe('XDSCarousel', () => {+ it('renders children', () => {+ render(+ <XDSCarousel aria-label="Test carousel">+ <div data-testid="item-1">Item 1</div>+ <div data-testid="item-2">Item 2</div>+ </XDSCarousel>,+ );+ expect(screen.getByTestId('item-1')).toBeInTheDocument();+ expect(screen.getByTestId('item-2')).toBeInTheDocument();+ });++ it('has carousel ARIA attributes', () => {+ render(+ <XDSCarousel aria-label="Photos">+ <div>Item</div>+ </XDSCarousel>,+ );+ const region = screen.getByRole('region', {name: 'Photos'});+ expect(region).toHaveAttribute('aria-roledescription', 'carousel');+ });++ it('applies data-testid', () => {+ render(+ <XDSCarousel data-testid="my-carousel">+ <div>Item</div>+ </XDSCarousel>,+ );+ expect(screen.getByTestId('my-carousel')).toBeInTheDocument();+ });++ it('has correct xds class name', () => {+ render(+ <XDSCarousel data-testid="cls-test">+ <div>Item</div>+ </XDSCarousel>,+ );+ const el = screen.getByTestId('cls-test');+ expect(el.className).toContain('xds-carousel');+ });+});diff --git a/packages/core/src/Carousel/XDSCarousel.tsx b/packages/core/src/Carousel/XDSCarousel.tsxnew file mode 100644index 0000000000..00b2c39fe3--- /dev/null+++ b/packages/core/src/Carousel/XDSCarousel.tsx@@ -0,0 +1,339 @@+'use client';++/**+ * @file XDSCarousel.tsx+ * @input Uses React, StyleX, useScrollOverflow, useXDSLayer, XDSButton, XDSIcon, theme tokens+ * @output Exports XDSCarousel component+ * @position Horizontal scroll container with fade-edge overflow indication,+ * optional prev/next buttons on the top layer, and scroll-snap.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Carousel/index.ts (exports)+ * - /apps/storybook/stories/Carousel.stories.tsx+ */++import {type ReactNode, useRef, useCallback, useEffect, Children} from 'react';+import type {StyleXStyles} from '@stylexjs/stylex';+import * as stylex from '@stylexjs/stylex';+import {+ spacingVars,+ colorVars,+ shadowVars,+ radiusVars,+ durationVars,+ easeVars,+} from '../theme/tokens.stylex';+import {XDSButton} from '../Button';+import {XDSIcon} from '../Icon';+import {useXDSLayer} from '../Layer';+import {useScrollOverflow} from '../hooks/useScrollOverflow';+import type {XDSBaseProps} from '../XDSBaseProps';+import {xdsClassName, mergeProps} from '../utils';+import {carouselScope} from './carousel.markers.stylex';++export interface XDSCarouselProps extends XDSBaseProps<HTMLDivElement> {+ ref?: React.Ref<HTMLDivElement>;+ /** Carousel items — rendered in a horizontal scroll container. */+ children: ReactNode;+ /**+ * Gap between items using spacing scale tokens.+ * @default 1+ */+ gap?: 0 | 0.5 | 1 | 1.5 | 2 | 3 | 4;+ /**+ * Show prev/next navigation buttons on hover (desktop only).+ * @default true+ */+ hasButtons?: boolean;+ /**+ * Enable scroll-snap on items. Each direct child snaps to the start edge.+ * @default false+ */+ hasSnap?: boolean;+ /**+ * Accessible label for the carousel region.+ * @default 'Carousel'+ */+ 'aria-label'?: string;++ xstyle?: StyleXStyles;+ className?: string;+ style?: React.CSSProperties;+ 'data-testid'?: string;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ root: {+ position: 'relative',+ display: 'flex',+ alignItems: 'center',+ },+ scroller: {+ display: 'flex',+ alignItems: 'center',+ overflowX: 'auto',+ overflowY: 'hidden',+ overscrollBehaviorX: 'contain',+ scrollBehavior: {+ default: 'smooth',+ '@media (prefers-reduced-motion: reduce)': 'auto',+ },+ 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']})`,+ },+ fadeEnd: {+ maskImage: `linear-gradient(to left, transparent 0%, rgba(0,0,0,0.3) 2px, black ${spacingVars['--spacing-1']})`,+ },+ fadeBoth: {+ maskImage: `linear-gradient(to right, transparent 0%, rgba(0,0,0,0.3) 2px, black ${spacingVars['--spacing-1']}, black calc(100% - ${spacingVars['--spacing-1']}), rgba(0,0,0,0.3) calc(100% - 2px), transparent 100%)`,+ },+ snap: {+ scrollSnapType: 'x mandatory',+ },+ item: {+ scrollSnapAlign: 'start',+ display: 'flex',+ flexShrink: 0,+ // Entry: 0% = item just touching edge, ~15% = item half in view, ~30% = fully in view+ // Exit mirrors in reverse. Scale down only while partially out of view.+ animationName: stylex.keyframes({+ '0%': {transform: 'scale(0.85)'},+ '15%': {transform: 'scale(1)'},+ '85%': {transform: 'scale(1)'},+ '100%': {transform: 'scale(0.85)'},+ }),+ animationTimeline: 'view(inline)',+ animationRange: 'cover',+ animationFillMode: 'both',+ animationDuration: {+ default: null,+ '@media (prefers-reduced-motion: reduce)': '0ms',+ },+ },+ // Overlay on top layer — covers the carousel anchor area+ buttonOverlay: {+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ pointerEvents: 'none',+ },+ buttonPill: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: colorVars['--color-background-popover'],+ borderRadius: radiusVars['--radius-full'],+ boxShadow: shadowVars['--shadow-med'],+ pointerEvents: 'auto',+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', carouselScope)]: {+ '@media (hover: hover)': 1,+ },+ },+ transitionProperty: 'opacity',+ transitionDuration: durationVars['--duration-fast'],+ transitionTimingFunction: easeVars['--ease-standard'],+ },+ buttonPillStart: {+ transform: 'translateX(-50%)',+ },+ buttonPillEnd: {+ transform: 'translateX(50%)',+ },+ buttonHidden: {+ opacity: 0,+ pointerEvents: 'none' as const,+ },+ buttonRadiusOverride: {+ '--button-radius': radiusVars['--radius-full'],+ } as Record<string, string>,+});++const gapStyles = stylex.create({+ 0: {gap: spacingVars['--spacing-0']},+ 0.5: {gap: spacingVars['--spacing-0-5']},+ 1: {gap: spacingVars['--spacing-1']},+ 1.5: {gap: spacingVars['--spacing-1-5']},+ 2: {gap: spacingVars['--spacing-2']},+ 3: {gap: spacingVars['--spacing-3']},+ 4: {gap: spacingVars['--spacing-4']},+});++// =============================================================================+// Component+// =============================================================================++/**+ * Horizontal scroll container with fade-edge overflow indication and+ * optional navigation buttons.+ *+ * Wraps any content in a scrollable row. When content overflows, gradient+ * fades appear at the edges to signal more items exist. On desktop, hover+ * reveals prev/next buttons rendered on the top layer via XDSLayer so they+ * escape any parent overflow clipping.+ *+ * @example+ * ```+ * <XDSCarousel gap={1}>+ * <XDSThumbnail src="/a.jpg" alt="A" />+ * <XDSThumbnail src="/b.jpg" alt="B" />+ * <XDSThumbnail src="/c.jpg" alt="C" />+ * </XDSCarousel>+ * ```+ */+export function XDSCarousel({+ ref,+ children,+ gap = 1,+ hasButtons = true,+ hasSnap = false,+ 'aria-label': ariaLabel = 'Carousel',+ xstyle,+ className,+ style,+ 'data-testid': testId,+ ...htmlProps+}: XDSCarouselProps) {+ const scrollElRef = useRef<HTMLElement | null>(null);+ const {scrollRef, overflowStart, overflowEnd} = useScrollOverflow();++ const layer = useXDSLayer({+ mode: 'context',+ lightDismiss: false,+ });++ useEffect(() => {+ if (hasButtons) {+ layer.show();+ } else {+ layer.hide();+ }+ }, [hasButtons, layer]);++ const composedRef = useCallback(+ (el: HTMLDivElement | null) => {+ scrollElRef.current = el;+ scrollRef(el);+ },+ [scrollRef],+ );++ const scrollBy = useCallback((direction: -1 | 1) => {+ const el = scrollElRef.current;+ if (!el) return;+ const firstChild = el.firstElementChild as HTMLElement | null;+ const itemWidth = firstChild ? firstChild.offsetWidth : 0;+ const amount = el.clientWidth - itemWidth * 0.5;+ el.scrollBy({+ left: direction * Math.max(amount, itemWidth),+ behavior: 'smooth',+ });+ }, []);++ const fadeStyle =+ overflowStart && overflowEnd+ ? styles.fadeBoth+ : overflowStart+ ? styles.fadeStart+ : overflowEnd+ ? styles.fadeEnd+ : null;++ return (+ <div+ ref={(el: HTMLDivElement | null) => {+ if (typeof ref === 'function') ref(el);+ else if (ref)+ (ref as React.MutableRefObject<HTMLDivElement | null>).current = el;+ if (layer.ref) layer.ref(el as HTMLElement | null);+ }}+ data-testid={testId}+ role="region"+ aria-label={ariaLabel}+ aria-roledescription="carousel"+ {...mergeProps(+ xdsClassName('carousel'),+ stylex.props(styles.root, carouselScope, xstyle),+ className,+ style,+ )}+ {...htmlProps}>+ <div+ ref={composedRef}+ {...stylex.props(+ styles.scroller,+ gapStyles[gap],+ hasSnap && styles.snap,+ fadeStyle,+ )}>+ {Children.map(children, child => (+ <div {...stylex.props(styles.item)}>{child}</div>+ ))}+ </div>++ {layer.render(+ <>+ <div+ {...stylex.props(+ styles.buttonPill,+ styles.buttonPillStart,+ !overflowStart && styles.buttonHidden,+ )}>+ <XDSButton+ icon={<XDSIcon icon="chevronLeft" size="xsm" />}+ label="Scroll left"+ variant="ghost"+ size="sm"+ isIconOnly+ onClick={() => scrollBy(-1)}+ xstyle={styles.buttonRadiusOverride}+ />+ </div>+ <div+ {...stylex.props(+ styles.buttonPill,+ styles.buttonPillEnd,+ !overflowEnd && styles.buttonHidden,+ )}>+ <XDSButton+ icon={<XDSIcon icon="chevronRight" size="xsm" />}+ label="Scroll right"+ variant="ghost"+ size="sm"+ isIconOnly+ onClick={() => scrollBy(1)}+ xstyle={styles.buttonRadiusOverride}+ />+ </div>+ </>,+ {+ placement: 'below',+ alignment: 'center',+ style: {+ // Override anchor positioning to cover the anchor instead of below it+ positionArea: 'center',+ width: 'anchor-size(width)',+ height: 'anchor-size(height)',+ } as React.CSSProperties,+ xstyle: styles.buttonOverlay,+ },+ )}+ </div>+ );+}++XDSCarousel.displayName = 'XDSCarousel';diff --git a/packages/core/src/Carousel/carousel.markers.stylex.ts b/packages/core/src/Carousel/carousel.markers.stylex.tsnew file mode 100644index 0000000000..fc304140b5--- /dev/null+++ b/packages/core/src/Carousel/carousel.markers.stylex.ts@@ -0,0 +1,8 @@+import * as stylex from '@stylexjs/stylex';++/**+ * Scoped marker for Carousel ancestor selectors.+ * Prevents hover styles from leaking from parent containers.+ */+export const carouselScope: ReturnType<typeof stylex.defineMarker> =+ stylex.defineMarker();diff --git a/packages/core/src/Carousel/index.ts b/packages/core/src/Carousel/index.tsnew file mode 100644index 0000000000..7d1c445832--- /dev/null+++ b/packages/core/src/Carousel/index.ts@@ -0,0 +1,9 @@+/**+ * @file index.ts+ * @input XDSCarousel component+ * @output Re-exports XDSCarousel and its props type+ * @position Public entry point for the Carousel module+ */++export {XDSCarousel} from './XDSCarousel';+export type {XDSCarouselProps} from './XDSCarousel';diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 335a8ba6e9..49c8d54b01 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -23,6 +23,9 @@ export {useMediaQuery} from './useMediaQuery';export {useOverflow} from './useOverflow';export type {UseOverflowOptions, UseOverflowReturn} from './useOverflow';+export {useScrollOverflow} from './useScrollOverflow';+export type {ScrollOverflowState} from './useScrollOverflow';+export {useScrollLock} from './useScrollLock';export {useEntryAnimation} from './useEntryAnimation';diff --git a/packages/core/src/hooks/useScrollOverflow.ts b/packages/core/src/hooks/useScrollOverflow.tsnew file mode 100644index 0000000000..898cedb993--- /dev/null+++ b/packages/core/src/hooks/useScrollOverflow.ts@@ -0,0 +1,109 @@+'use client';++/**+ * @file useScrollOverflow.ts+ * @input Uses React useRef, useState, useCallback, useEffect+ * @output Exports useScrollOverflow hook for tracking scroll position edges+ * @position Core hook; used by XDSCarousel for fade-edge and button state+ *+ * Observes a scroll container and reports whether content overflows at the+ * start, end, or both edges. Updates on scroll and resize.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/index.ts+ */++import {useState, useCallback, useEffect, useRef} from 'react';++export interface ScrollOverflowState {+ /** Content overflows the start (left in LTR, right in RTL) */+ overflowStart: boolean;+ /** Content overflows the end (right in LTR, left in RTL) */+ overflowEnd: boolean;+ /** Whether the container has any overflow at all */+ hasOverflow: boolean;+}++/**+ * 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.+ *+ * @example+ * ```+ * const { scrollRef, overflowStart, overflowEnd } = useScrollOverflow();+ * <div ref={scrollRef} style={{ overflowX: 'auto' }}>...</div>+ * ```+ */+export function useScrollOverflow() {+ const elRef = useRef<HTMLElement | null>(null);+ const observerRef = useRef<ResizeObserver | null>(null);++ const [state, setState] = useState<ScrollOverflowState>({+ overflowStart: false,+ overflowEnd: false,+ hasOverflow: false,+ });++ const measure = useCallback(() => {+ const el = elRef.current;+ if (!el) return;++ const tolerance = 1;+ const {scrollLeft, scrollWidth, clientWidth} = el;+ const maxScroll = scrollWidth - clientWidth;++ const overflowStart = Math.abs(scrollLeft) > tolerance;+ const overflowEnd = Math.abs(scrollLeft) < maxScroll - tolerance;+ const hasOverflow = scrollWidth > clientWidth + tolerance;++ setState(prev => {+ if (+ prev.overflowStart === overflowStart &&+ prev.overflowEnd === overflowEnd &&+ prev.hasOverflow === hasOverflow+ ) {+ return prev;+ }+ return {overflowStart, overflowEnd, hasOverflow};+ });+ }, []);++ const scrollRef = useCallback(+ (el: HTMLElement | null) => {+ if (observerRef.current) {+ observerRef.current.disconnect();+ observerRef.current = null;+ }+ if (elRef.current) {+ elRef.current.removeEventListener('scroll', measure);+ }++ elRef.current = el;++ if (el) {+ el.addEventListener('scroll', measure, {passive: true});++ const ro = new ResizeObserver(measure);+ ro.observe(el);+ observerRef.current = ro;++ measure();+ }+ },+ [measure],+ );++ useEffect(() => {+ return () => {+ if (observerRef.current) observerRef.current.disconnect();+ if (elRef.current) elRef.current.removeEventListener('scroll', measure);+ };+ }, [measure]);++ return {+ scrollRef,+ ...state,+ };+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex c96b7209a7..c2814f5b54 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -21,6 +21,7 @@ export * from './Banner';export * from './Breadcrumbs';export * from './Button';export * from './Card';+export * from './Carousel';export * from './Calendar';export * from './Center';export * from './CodeBlock';