Tomatoes
Sow indoors 6 weeks before the last frost.
A row or column of slides that scrolls one stop at a time. Use it for step cards, a strip of attachments, or a few cards side by side.
pnpm dlx shadcn@latest add https://sprout.tulipfarm.ai/r/carousel.jsonCopies Carousel and the components it uses (Button) into your app, installs the packages, and adds the styles. Then import it from @/components/ui/carousel. Needs Tailwind CSS 4 and a components.json from shadcn init.
Install the following dependencies:
pnpm add clsx tailwind-merge @hugeicons/core-free-icons @hugeicons/reactAdd Sprout base once per app: the cn() helper and the design tokens.
lib/sprout/classes.tsAdd the components it uses: Button.
Copy and paste the following code into your project.
'use client';
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ComponentProps,
type KeyboardEvent,
type PointerEvent,
type RefCallback,
} from 'react';
import { ChevronLeftIcon } from '@/lib/sprout/icons/chevron-left-icon';
import { ChevronRightIcon } from '@/lib/sprout/icons/chevron-right-icon';
import { cn } from '@/lib/sprout/classes';
import { Button, type ButtonProps } from '@/components/ui/button';
export const carouselOrientationNames = ['horizontal', 'vertical'] as const;
export const carouselAlignNames = ['start', 'center', 'end'] as const;
export type CarouselOrientation = (typeof carouselOrientationNames)[number];
export type CarouselAlign = (typeof carouselAlignNames)[number];
export type CarouselEvent = 'select' | 'reInit';
export interface CarouselOptions {
align?: CarouselAlign | undefined;
dragFree?: boolean | undefined;
loop?: boolean | undefined;
startIndex?: number | undefined;
}
export interface CarouselApi {
scrollPrev(): void;
scrollNext(): void;
scrollTo(index: number): void;
canScrollPrev(): boolean;
canScrollNext(): boolean;
selectedScrollSnap(): number;
scrollSnapList(): number[];
slideNodes(): HTMLElement[];
on(event: CarouselEvent, listener: (api: CarouselApi) => void): CarouselApi;
off(event: CarouselEvent, listener: (api: CarouselApi) => void): CarouselApi;
}
export interface CarouselProps extends ComponentProps<'div'> {
opts?: CarouselOptions | undefined;
orientation?: CarouselOrientation | undefined;
setApi?: ((api: CarouselApi) => void) | undefined;
}
export interface CarouselContextValue {
carouselRef: RefCallback<HTMLDivElement>;
api: CarouselApi;
opts: CarouselOptions | undefined;
orientation: CarouselOrientation;
scrollPrev: () => void;
scrollNext: () => void;
scrollTo: (index: number) => void;
canScrollPrev: boolean;
canScrollNext: boolean;
selectedIndex: number;
snapCount: number;
}
const CarouselContext = createContext<CarouselContextValue | null>(null);
export function useCarousel() {
const context = useContext(CarouselContext);
if (!context) throw new Error('useCarousel must be used within a <Carousel />');
return context;
}
const typing = 'input, textarea, select, [contenteditable="true"]';
const focusable = 'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
interface Geometry {
position: number;
max: number;
snaps: number[];
}
function measure(viewport: HTMLElement, horizontal: boolean, align: CarouselAlign): Geometry {
const position = horizontal ? viewport.scrollLeft : viewport.scrollTop;
const view = horizontal ? viewport.clientWidth : viewport.clientHeight;
const max = Math.max(0, (horizontal ? viewport.scrollWidth : viewport.scrollHeight) - view);
const frame = viewport.getBoundingClientRect();
const slides = Array.from(viewport.firstElementChild?.children ?? []);
const snaps: number[] = [];
for (const slide of slides) {
const box = slide.getBoundingClientRect();
const start = (horizontal ? box.left - frame.left : box.top - frame.top) + position;
const length = horizontal ? box.width : box.height;
const target =
align === 'start' ? start : align === 'center' ? start + length / 2 - view / 2 : start + length - view;
snaps.push(Math.round(Math.min(max, Math.max(0, target))));
}
if (snaps.length) {
snaps[0] = 0;
snaps[snaps.length - 1] = Math.round(max);
}
const unique = snaps.filter((snap, index) => index === 0 || Math.abs(snap - snaps[index - 1]!) > 1);
return { position, max, snaps: unique.length ? unique : [0] };
}
function nearest(snaps: number[], position: number) {
let best = 0;
for (let index = 1; index < snaps.length; index += 1)
if (Math.abs(snaps[index]! - position) < Math.abs(snaps[best]! - position)) best = index;
return best;
}
interface CarouselState {
canScrollPrev: boolean;
canScrollNext: boolean;
selectedIndex: number;
snapCount: number;
viewportFocusable: boolean;
}
const initialState: CarouselState = {
canScrollPrev: false,
canScrollNext: false,
selectedIndex: 0,
snapCount: 0,
viewportFocusable: false,
};
export function Carousel({
orientation = 'horizontal',
opts,
setApi,
className,
children,
onKeyDownCapture,
...props
}: CarouselProps) {
const horizontal = orientation === 'horizontal';
const align = opts?.align ?? 'start';
const loop = opts?.loop ?? false;
const viewport = useRef<HTMLDivElement | null>(null);
const settings = useRef({ horizontal, align, loop });
settings.current = { horizontal, align, loop };
const pending = useRef<{ target: number; timer: number } | null>(null);
const selected = useRef(0);
const listeners = useRef(new Map<CarouselEvent, Set<(api: CarouselApi) => void>>());
const [state, setState] = useState(initialState);
const geometry = useCallback((): Geometry | null => {
const node = viewport.current;
if (!node) return null;
const { horizontal, align } = settings.current;
return measure(node, horizontal, align);
}, []);
const apiRef = useRef<CarouselApi | null>(null);
const emit = useCallback((event: CarouselEvent) => {
const api = apiRef.current;
if (!api) return;
listeners.current.get(event)?.forEach(listener => listener(api));
}, []);
const update = useCallback(() => {
const node = viewport.current;
const shape = geometry();
if (!node || !shape) return;
const { position, max, snaps } = shape;
const target = pending.current?.target;
if (target !== undefined && Math.abs(position - target) <= 1) {
window.clearTimeout(pending.current!.timer);
pending.current = null;
}
const wraps = settings.current.loop && snaps.length > 1;
const next: CarouselState = {
canScrollPrev: wraps || position > 1,
canScrollNext: wraps || position < max - 1,
selectedIndex: nearest(snaps, position),
snapCount: snaps.length,
viewportFocusable: max > 0 && !node.firstElementChild?.querySelector(focusable),
};
const changed = next.selectedIndex !== selected.current;
selected.current = next.selectedIndex;
setState(current =>
current.canScrollPrev === next.canScrollPrev &&
current.canScrollNext === next.canScrollNext &&
current.selectedIndex === next.selectedIndex &&
current.snapCount === next.snapCount &&
current.viewportFocusable === next.viewportFocusable
? current
: next,
);
if (changed) emit('select');
}, [emit, geometry]);
const go = useCallback(
(target: number, instant = false) => {
const node = viewport.current;
if (!node) return;
if (pending.current) window.clearTimeout(pending.current.timer);
pending.current = {
target,
timer: window.setTimeout(() => {
pending.current = null;
update();
}, 700),
};
const key = settings.current.horizontal ? 'left' : 'top';
node.scrollTo({
[key]: target,
...(instant ? { behavior: 'instant' } : {}),
});
update();
},
[update],
);
const scrollTo = useCallback(
(index: number, instant = false) => {
const shape = geometry();
if (!shape) return;
const clamped = Math.min(shape.snaps.length - 1, Math.max(0, index));
go(shape.snaps[clamped]!, instant);
},
[geometry, go],
);
const step = useCallback(
(direction: -1 | 1) => {
const shape = geometry();
if (!shape) return;
const from = pending.current?.target ?? shape.position;
const target =
direction > 0
? shape.snaps.find(snap => snap > from + 1)
: [...shape.snaps].reverse().find(snap => snap < from - 1);
if (target !== undefined) go(target);
else if (settings.current.loop && shape.snaps.length > 1) go(direction > 0 ? 0 : shape.max);
},
[geometry, go],
);
const scrollPrev = useCallback(() => step(-1), [step]);
const scrollNext = useCallback(() => step(1), [step]);
if (!apiRef.current) {
const api: CarouselApi = {
scrollPrev: () => step(-1),
scrollNext: () => step(1),
scrollTo: index => scrollTo(index),
canScrollPrev: () => {
const shape = geometry();
if (!shape) return false;
return (settings.current.loop && shape.snaps.length > 1) || shape.position > 1;
},
canScrollNext: () => {
const shape = geometry();
if (!shape) return false;
return (settings.current.loop && shape.snaps.length > 1) || shape.position < shape.max - 1;
},
selectedScrollSnap: () => selected.current,
scrollSnapList: () => geometry()?.snaps ?? [],
slideNodes: () => Array.from(viewport.current?.firstElementChild?.children ?? []) as HTMLElement[],
on: (event, listener) => {
const set = listeners.current.get(event) ?? new Set();
set.add(listener);
listeners.current.set(event, set);
return api;
},
off: (event, listener) => {
listeners.current.get(event)?.delete(listener);
return api;
},
};
apiRef.current = api;
}
const api = apiRef.current;
const frame = useRef(0);
const scheduleUpdate = useCallback(() => {
if (frame.current) return;
frame.current = requestAnimationFrame(() => {
frame.current = 0;
update();
});
}, [update]);
const startIndex = opts?.startIndex ?? 0;
const started = useRef(false);
const [node, setNode] = useState<HTMLDivElement | null>(null);
const carouselRef = useCallback<RefCallback<HTMLDivElement>>(element => {
viewport.current = element;
setNode(element);
}, []);
useEffect(() => {
if (!node) return;
const reInit = () => {
update();
emit('reInit');
};
if (!started.current) {
started.current = true;
if (startIndex > 0) scrollTo(startIndex, true);
}
update();
const resize = new ResizeObserver(reInit);
resize.observe(node);
const track = node.firstElementChild;
if (track) resize.observe(track);
const mutation = new MutationObserver(() => {
if (track) for (const slide of track.children) resize.observe(slide);
reInit();
});
if (track) {
for (const slide of track.children) resize.observe(slide);
mutation.observe(track, { childList: true, subtree: true });
}
node.addEventListener('scroll', scheduleUpdate, { passive: true });
node.addEventListener('scrollend', update);
return () => {
resize.disconnect();
mutation.disconnect();
node.removeEventListener('scroll', scheduleUpdate);
node.removeEventListener('scrollend', update);
cancelAnimationFrame(frame.current);
frame.current = 0;
};
}, [node, emit, scheduleUpdate, scrollTo, startIndex, update]);
useEffect(() => {
if (!node) return;
update();
emit('reInit');
}, [node, horizontal, align, loop, update, emit]);
useEffect(() => {
if (!setApi) return;
setApi(api);
}, [api, setApi]);
useEffect(
() => () => {
if (pending.current) window.clearTimeout(pending.current.timer);
},
[],
);
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
onKeyDownCapture?.(event);
if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return;
if ((event.target as Element).closest(typing)) return;
const back = event.key === 'ArrowLeft' || (!horizontal && event.key === 'ArrowUp');
const forward = event.key === 'ArrowRight' || (!horizontal && event.key === 'ArrowDown');
if (back || forward) {
event.preventDefault();
step(back ? -1 : 1);
} else if (event.key === 'Home' || event.key === 'End') {
if (!(event.target as Element).closest('[data-slot="carousel-content"]')) return;
event.preventDefault();
scrollTo(event.key === 'Home' ? 0 : Number.MAX_SAFE_INTEGER);
}
};
const value = useMemo<CarouselContextValue>(
() => ({
carouselRef,
api,
opts,
orientation,
scrollPrev,
scrollNext,
scrollTo: (index: number) => scrollTo(index),
canScrollPrev: state.canScrollPrev,
canScrollNext: state.canScrollNext,
selectedIndex: state.selectedIndex,
snapCount: state.snapCount,
}),
[carouselRef, api, opts, orientation, scrollPrev, scrollNext, scrollTo, state],
);
return (
<CarouselContext.Provider value={value}>
<ViewportFocus.Provider value={state.viewportFocusable}>
<div
role="region"
aria-roledescription="carousel"
data-slot="carousel"
data-orientation={orientation}
className={cn('sprout-carousel', className)}
onKeyDownCapture={handleKeyDown}
{...props}
>
{children}
</div>
</ViewportFocus.Provider>
</CarouselContext.Provider>
);
}
const ViewportFocus = createContext(false);
export function CarouselContent({ className, ...props }: ComponentProps<'div'>) {
const { carouselRef, orientation, opts, api } = useCarousel();
const focusableViewport = useContext(ViewportFocus);
const horizontal = orientation === 'horizontal';
const drag = useRef<{
id: number;
start: number;
scroll: number;
moved: boolean;
} | null>(null);
const node = useRef<HTMLDivElement | null>(null);
const ref = useCallback<RefCallback<HTMLDivElement>>(
element => {
node.current = element;
carouselRef(element);
},
[carouselRef],
);
const coordinate = (event: PointerEvent) => (horizontal ? event.clientX : event.clientY);
const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
if (event.pointerType !== 'mouse' || event.button !== 0) return;
if ((event.target as Element).closest(typing)) return;
const viewport = node.current!;
drag.current = {
id: event.pointerId,
start: coordinate(event),
scroll: horizontal ? viewport.scrollLeft : viewport.scrollTop,
moved: false,
};
};
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
const current = drag.current;
if (!current || current.id !== event.pointerId) return;
const delta = coordinate(event) - current.start;
if (!current.moved) {
if (Math.abs(delta) < 5) return;
current.moved = true;
event.currentTarget.setPointerCapture(event.pointerId);
event.currentTarget.setAttribute('data-dragging', '');
}
const viewport = event.currentTarget;
if (horizontal) viewport.scrollLeft = current.scroll - delta;
else viewport.scrollTop = current.scroll - delta;
};
const onPointerEnd = (event: PointerEvent<HTMLDivElement>) => {
const current = drag.current;
if (!current || current.id !== event.pointerId) return;
drag.current = null;
if (!current.moved) return;
const viewport = event.currentTarget;
if (viewport.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
const swallow = (click: MouseEvent) => {
click.preventDefault();
click.stopPropagation();
};
window.addEventListener('click', swallow, { capture: true, once: true });
window.setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
const release = () => {
if (!drag.current) viewport.removeAttribute('data-dragging');
};
if (opts?.dragFree) return release();
const position = horizontal ? viewport.scrollLeft : viewport.scrollTop;
const view = horizontal ? viewport.clientWidth : viewport.clientHeight;
const moved = position - current.scroll;
const snaps = api.scrollSnapList();
const from = nearest(snaps, current.scroll);
const index =
Math.abs(moved) > view * 0.5
? nearest(snaps, position)
: Math.abs(moved) > Math.min(40, view * 0.15)
? from + Math.sign(moved)
: from;
const target = snaps[Math.min(snaps.length - 1, Math.max(0, index))];
if (target === undefined || Math.abs(target - position) < 1) return release();
let timer = 0;
const settle = () => {
window.clearTimeout(timer);
viewport.removeEventListener('scrollend', settle);
release();
};
viewport.addEventListener('scrollend', settle);
timer = window.setTimeout(settle, 700);
const smooth = window.matchMedia('(prefers-reduced-motion: no-preference)').matches;
viewport.scrollTo({
[horizontal ? 'left' : 'top']: target,
behavior: smooth ? 'smooth' : 'instant',
});
};
return (
<div
ref={ref}
data-slot="carousel-content"
data-orientation={orientation}
data-align={opts?.align ?? 'start'}
data-drag-free={opts?.dragFree ? '' : undefined}
tabIndex={focusableViewport ? 0 : undefined}
className="sprout-carousel-content"
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerEnd}
onPointerCancel={onPointerEnd}
onDragStart={event => {
if (drag.current) event.preventDefault();
}}
>
<div data-slot="carousel-track" className={cn('sprout-carousel-track', className)} {...props} />
</div>
);
}
export function CarouselItem({ className, ...props }: ComponentProps<'div'>) {
const { orientation } = useCarousel();
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
data-orientation={orientation}
className={cn('sprout-carousel-item', className)}
{...props}
/>
);
}
export type CarouselButtonProps = Omit<ButtonProps, 'state' | 'pendingLabel'>;
export function CarouselPrevious({
className,
variant = 'secondary',
size = 'icon',
children,
...props
}: CarouselButtonProps) {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
data-slot="carousel-previous"
data-orientation={orientation}
variant={variant}
size={size}
aria-label="Previous slide"
focusableWhenDisabled
className={cn('sprout-carousel-control', 'sprout-carousel-previous', className)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
{children ?? <ChevronLeftIcon aria-hidden="true" />}
</Button>
);
}
export function CarouselNext({
className,
variant = 'secondary',
size = 'icon',
children,
...props
}: CarouselButtonProps) {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
data-slot="carousel-next"
data-orientation={orientation}
variant={variant}
size={size}
aria-label="Next slide"
focusableWhenDisabled
className={cn('sprout-carousel-control', 'sprout-carousel-next', className)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
{children ?? <ChevronRightIcon aria-hidden="true" />}
</Button>
);
}And the files it imports:
lib/sprout/icons/chevron-left-icon.tsxlib/sprout/icons/chevron-right-icon.tsxlib/sprout/icons/create-icon.tsxAdd the styles to your global CSS, after @import "tailwindcss".
@layer components {
.sprout-carousel {
min-width: 0;
position: relative;
}
.sprout-carousel-content {
scrollbar-width: none;
border-radius: var(--sprout-carousel-radius, 0);
outline: none;
min-width: 0;
overflow: auto;
}
.sprout-carousel-content::-webkit-scrollbar {
display: none;
}
.sprout-carousel-content[data-orientation="horizontal"] {
overscroll-behavior-x: contain;
scroll-snap-type: x mandatory;
touch-action: pan-x pinch-zoom;
overflow-y: hidden;
}
.sprout-carousel-content[data-orientation="vertical"] {
overscroll-behavior-y: contain;
scroll-snap-type: y mandatory;
touch-action: pan-y pinch-zoom;
height: 100%;
min-height: 0;
overflow-x: hidden;
}
.sprout-carousel-content[data-drag-free], .sprout-carousel-content[data-dragging] {
scroll-snap-type: none;
}
.sprout-carousel-content[data-dragging] {
cursor: grabbing;
user-select: none;
}
.sprout-carousel-content:focus-visible {
outline: var(--sprout-focus-width) solid var(--sprout-focus-ring);
outline-offset: -1px;
}
.sprout-carousel-track {
gap: var(--sprout-carousel-gap, 16px);
display: flex;
}
.sprout-carousel-content[data-orientation="vertical"] > .sprout-carousel-track {
flex-direction: column;
height: 100%;
}
.sprout-carousel-item {
box-sizing: border-box;
flex: 0 0 var(--sprout-carousel-basis, 100%);
scroll-snap-align: start;
min-width: 0;
min-height: 0;
}
[data-align="center"] > .sprout-carousel-track > .sprout-carousel-item {
scroll-snap-align: center;
}
[data-align="end"] > .sprout-carousel-track > .sprout-carousel-item {
scroll-snap-align: end;
}
.sprout-carousel-control {
box-shadow: var(--sprout-shadow-control);
touch-action: manipulation;
border-radius: 999px;
position: absolute;
}
.sprout-carousel-control[data-orientation="horizontal"] {
margin-block: auto;
inset-block: 0;
}
.sprout-carousel-previous[data-orientation="horizontal"] {
left: calc(-1 * var(--sprout-carousel-control-offset, 48px));
}
.sprout-carousel-next[data-orientation="horizontal"] {
right: calc(-1 * var(--sprout-carousel-control-offset, 48px));
}
.sprout-carousel-control[data-orientation="vertical"] {
left: 50%;
translate: -50%;
rotate: 90deg;
}
.sprout-carousel-previous[data-orientation="vertical"] {
top: calc(-1 * var(--sprout-carousel-control-offset, 48px));
}
.sprout-carousel-next[data-orientation="vertical"] {
bottom: calc(-1 * var(--sprout-carousel-control-offset, 48px));
}
@media (pointer: coarse) {
.sprout-carousel-control.sprout-button-size-icon {
width: 44px;
height: 44px;
}
}
@media (prefers-reduced-motion: no-preference) {
.sprout-carousel-content:not([data-dragging]) {
scroll-behavior: smooth;
}
}
}Import it from @/components/ui/carousel. Update the paths if your @/ alias points elsewhere.
pnpm add @tulipfarm/sprout@import "tailwindcss";
@import "@tulipfarm/sprout/styles.css";The package keeps the source and ships fixes with each release. Import from @tulipfarm/sprout/carousel.
One slide at a time, sideways or up and down. Use the arrows, the arrow keys, a swipe, or drag with a mouse. The arrows turn off at either end.
Slide 1 of 1
Slide 1 of 1
Staged files in one free-scrolling row: chips keep their own width, sit 8px apart, and align to the start. Edge arrows from useCarousel appear on hover or focus and hide at either end.
Set --sprout-carousel-basis to show more than one card. opts.loop wraps at the ends, and setApi drives the dots and the counter.
Sow indoors 6 weeks before the last frost.
Pinch the tips weekly so it grows bushy.
Sow a short row every two weeks.
Thin seedlings to 5 cm once they are 3 cm tall.
Give them a trellis before they start to climb.
Position 1 of 1
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@tulipfarm/sprout/carousel";
<div className="mx-auto w-full max-w-sm px-12">
<Carousel aria-label="Growing steps">
<CarouselContent>
{["Plant", "Water", "Grow"].map((label, index) => (
<CarouselItem key={label}>
<div className="grid h-40 place-items-center rounded-xl border">
{index + 1}. {label}
</div>
</CarouselItem>
))}
</CarouselContent>
<CarouselPrevious />
<CarouselNext />
</Carousel>
</div>The carousel scrolls natively, so touch swipe, trackpads, and focus moving into a hidden slide all work. Slides snap into place unlessopts.dragFree is set. A mouse can drag the slides too.
orientation="vertical" stacks slides in a column. Give the content a height, for example by wrapping it in a flex column with a fixed height. The arrows sit above and below and turn to point up and down.
<div className="mx-auto w-full max-w-xs py-12">
<Carousel orientation="vertical" aria-label="Growing steps">
<div className="flex h-40 flex-col">
<CarouselContent>{/* CarouselItem slides */}</CarouselContent>
</div>
<CarouselPrevious />
<CarouselNext />
</Carousel>
</div>opts.align: start (default),center, or end. Where the current slide lands.opts.dragFree: scroll without snapping. Arrows and keys still step one slide.opts.loop: Next on the last stop goes to the first, and Previous on the first goes to the last.opts.startIndex: the slide shown first.Slides fill the viewport by default. Set CSS tokens on the carousel, or pass a className to CarouselItem:
--sprout-carousel-basis: slide size. auto lets each slide keep its own width, as an attachment row does.calc((100% - 16px) / 2) shows two per view.--sprout-carousel-gap: space between slides. Default 16px.--sprout-carousel-control-offset: how far outside the carousel the arrows sit. Default 48px. Leave that much room around it.function AttachmentArrows() {
const { scrollPrev, scrollNext, canScrollPrev, canScrollNext } = useCarousel();
return (
<>
{canScrollPrev && (
<button type="button" aria-label="Previous attachments" onClick={scrollPrev}>
<ChevronLeft size={12} aria-hidden="true" />
</button>
)}
{canScrollNext && (
<button type="button" aria-label="Next attachments" onClick={scrollNext}>
<ChevronRight size={12} aria-hidden="true" />
</button>
)}
</>
);
}
<Carousel
aria-label="Attached files"
opts={{ align: "start", dragFree: true }}
className="[--sprout-carousel-basis:auto] [--sprout-carousel-gap:8px]"
>
<CarouselContent className="py-1">
{files.map((file) => (
<CarouselItem key={file.id}>
<FileAttachment variant="chip" file={file} />
</CarouselItem>
))}
</CarouselContent>
<AttachmentArrows />
</Carousel>useCarousel() works inside a carousel and returnsscrollPrev, scrollNext, scrollTo,canScrollPrev, canScrollNext,selectedIndex, snapCount,orientation, and api. Use it to draw your own arrows or a counter.
setApi hands the CarouselApi to a parent. It hasscrollPrev(), scrollNext(),scrollTo(index), canScrollPrev(),canScrollNext(), selectedScrollSnap(),scrollSnapList(), slideNodes(), andon/off for the select andreInit events. The carousel does not take Embla plugins.
const [api, setApi] = useState<CarouselApi>();
const [selected, setSelected] = useState(0);
useEffect(() => {
if (!api) return;
const sync = (current: CarouselApi) => setSelected(current.selectedScrollSnap());
api.on("select", sync);
return () => {
api.off("select", sync);
};
}, [api]);
<Carousel setApi={setApi} opts={{ loop: true }} aria-label="Planting guides">
…
</Carousel>CarouselPrevious and CarouselNext areButtons, secondary and icon by default, and take any Button variant and size. They grow to 44px on touch screens.
The carousel is a region witharia-roledescription="carousel", and each slide is agroup with aria-roledescription="slide". Name the carousel with aria-label.
Left and Right step through slides while focus is inside, and Up and Down do the same when it is vertical. Keys typed into fields are left alone. The arrow buttons stay focusable when they turn off at an end, so focus does not jump away. When no slide holds a focusable element, the viewport itself takes focus, and Home and End jump to the first and last slide.
Scrolling animates only when reduced motion is off.