Carousel
Swipeable slide carousel driven by one motion value: momentum drag that snaps to slides with rubber-band edges, seamless loop, responsive slidesPerView, dot or thumbnail indicators with a gliding active pill, and autoplay with a progress bar that pauses on hover, focus or hidden tabs.
Preview
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Grow a small control's *hit area* to at least 44×44px (WCAG 2.5.5, Apple
* HIG) on a coarse pointer, without changing what it looks like or the space
* it takes in layout. An invisible `::after` box, centered on the control and
* `max(100%, 2.75rem)` on each axis, catches the taps: a 32px icon button
* reaches 6px past each edge, a wide 40px button only grows vertically, and a
* control already 44px or larger is left as it is. Hit-testing a pseudo
* element lands on its owner, so handlers, focus and `:active` all behave.
*
* Mouse and trackpad rendering is untouched — nothing here applies outside
* `pointer: coarse`. Requirements on the element it goes on:
* - It must be the containing block: add `relative` (and keep it mergeable, so
* a consumer's `absolute` still wins through `cn`).
* - It must not clip itself (`overflow-hidden`), or the overhang is clipped
* away along with its hit area.
* - It must render children: `<input>` and other void elements have no
* `::after`. Put it on the wrapper or label instead.
* - It must not already use `::after` for something visible.
*
* Centered 44px means two 32px buttons with a 4px gap overlap by 8px; the
* later one wins that strip, which still ends well short of the earlier
* button's visual center. Below a ~32px pitch the later neighbour starts
* eating into that center — use `TOUCH_TARGET_Y_CLASS` for such dense rows.
*
* The overhang is real geometry: inside a scroll container it counts as
* scrollable overflow, so a control flush against a scroller's edge can add a
* few pixels of scroll on touch screens. Give such a scroller a little padding
* on that side.
*/
export const TOUCH_TARGET_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-[max(100%,2.75rem)] pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* `TOUCH_TARGET_CLASS` on the vertical axis only, for controls packed tighter
* than ~32px apart in a row (pagination dots, dense swatches), where growing
* sideways would hand most of each control to its neighbour. Same rules.
*/
export const TOUCH_TARGET_Y_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:top-1/2 pointer-coarse:after:h-[max(100%,2.75rem)] pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
Copy the source code
"use client";
// karaui.kamisama-v0.my.id/components/motion/carousel
import { ChevronLeft, ChevronRight, Pause, Play } from "lucide-react";
import {
type AnimationPlaybackControls,
animate,
LayoutGroup,
type MotionValue,
motion,
type PanInfo,
useAnimationFrame,
useMotionValue,
useReducedMotion,
useTransform,
} from "motion/react";
import {
Children,
type KeyboardEvent as ReactKeyboardEvent,
type ReactNode,
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
import { SPRING_LAYOUT, SPRING_PRESS } from "@/lib/ease";
import { TOUCH_GESTURE_CONTENT_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
export type CarouselIndicators = "dots" | "thumbnails" | "none";
export interface CarouselProps {
/** One child per slide. */
children: ReactNode;
/** Controlled index of the first visible slide. */
index?: number;
/** Initial index for uncontrolled use. */
defaultIndex?: number;
onIndexChange?: (index: number) => void;
/** Wrap past either end. Seamless when there are at least `slidesPerView + 2` slides. */
loop?: boolean;
/** Advance automatically; `true` = every 5000ms, or pass the interval in ms. Pauses on hover, focus, drag and hidden tabs; off under reduced motion. */
autoplay?: boolean | number;
/** Slides shown at once: a number, or `{ minContainerWidthPx: count }`, e.g. `{ 0: 1, 480: 2, 768: 3 }`. */
slidesPerView?: number | Record<number, number>;
/** Space between slides in px. */
gap?: number;
indicators?: CarouselIndicators;
/** Thumbnail content per position, for `indicators="thumbnails"`. */
renderThumbnail?: (index: number) => ReactNode;
/** Render previous / next buttons. */
showControls?: boolean;
/** Accessible name of the carousel. */
"aria-label"?: string;
/** Accessible name per slide. */
getSlideLabel?: (index: number, count: number) => string;
className?: string;
slideClassName?: string;
}
const DEFAULT_INTERVAL = 5000;
/** How far ahead a release velocity projects, in seconds (flick momentum). */
const MOMENTUM_TIME = 0.22;
/** Most slides a single flick may travel. */
const MAX_FLING = 3;
/** Past an edge the track gives at most this fraction of a slide (rubber band). */
const EDGE_GIVE = 0.4;
/** Release velocity (px/s) that counts as a flick even over a short distance. */
const FLICK_VELOCITY = 320;
function mod(n: number, m: number) {
return ((n % m) + m) % m;
}
function resolvePerView(
value: CarouselProps["slidesPerView"],
width: number,
): number {
if (typeof value === "number") return Math.max(1, Math.floor(value));
if (!value) return 1;
const points = Object.keys(value)
.map(Number)
.filter(Number.isFinite)
.sort((a, b) => a - b);
let result = points.length > 0 ? value[points[0]] : 1;
for (const point of points) if (width >= point) result = value[point];
return Math.max(1, Math.floor(result));
}
/** Elastic overshoot: grows quickly at first, then asymptotes at EDGE_GIVE. */
function rubber(overshoot: number) {
return EDGE_GIVE * (1 - 1 / (1 + overshoot));
}
export function Carousel({
children,
index: indexProp,
defaultIndex = 0,
onIndexChange,
loop = false,
autoplay = false,
slidesPerView = 1,
gap = 16,
indicators = "dots",
renderThumbnail,
showControls = true,
"aria-label": ariaLabel = "Carousel",
getSlideLabel = (i, n) => `${i + 1} of ${n}`,
className,
slideClassName,
}: CarouselProps) {
const reduce = useReducedMotion() ?? false;
const slides = Children.toArray(children);
const count = slides.length;
const groupId = useId();
const viewportRef = useRef<HTMLDivElement>(null);
// Measured viewport width; 0 on the server, so the first client pass matches.
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
const el = viewportRef.current;
if (!el) return;
const update = () => setWidth(el.clientWidth);
update();
const observer = new ResizeObserver(update);
observer.observe(el);
return () => observer.disconnect();
}, []);
const perView = Math.min(resolvePerView(slidesPerView, width), Math.max(1, count));
// Seamless wrap needs a spare slide on each side of the visible window.
const wrap = loop && count >= perView + 2;
const positions = wrap ? count : Math.max(1, count - perView + 1);
const maxIndex = positions - 1;
const [internal, setInternal] = useState(defaultIndex);
const controlled = indexProp !== undefined;
const raw = controlled ? indexProp : internal;
const current = Math.min(Math.max(0, Math.round(raw)), maxIndex);
const commit = useCallback(
(next: number) => {
if (!controlled) setInternal(next);
onIndexChange?.(next);
},
[controlled, onIndexChange],
);
// `pos` is the track position in slides (fractional mid-drag, unbounded when
// wrapping); `step` is one slide plus gap in px.
const pos = useMotionValue(current);
const step = useMotionValue(0);
const targetRef = useRef(current);
const animationRef = useRef<AnimationPlaybackControls | null>(null);
useLayoutEffect(() => {
step.set(width > 0 ? (width + gap) / perView : 0);
}, [width, gap, perView, step]);
const animateTo = useCallback(
(target: number, velocity = 0) => {
targetRef.current = target;
animationRef.current?.stop();
if (reduce) {
pos.set(wrap ? mod(target, count) : target);
targetRef.current = wrap ? mod(target, count) : target;
return;
}
animationRef.current = animate(pos, target, {
...SPRING_LAYOUT,
velocity,
onComplete: () => {
// Wrapped positions are visually identical, so fold back silently.
if (wrap && targetRef.current === target) {
const folded = mod(target, count);
targetRef.current = folded;
pos.set(folded);
}
},
});
},
[reduce, pos, wrap, count],
);
const goTo = useCallback(
(target: number, velocity = 0) => {
const clamped = wrap ? target : Math.min(Math.max(0, target), maxIndex);
animateTo(clamped, velocity);
const next = wrap ? mod(clamped, count) : clamped;
if (next !== current) commit(next);
},
[wrap, maxIndex, animateTo, count, current, commit],
);
// Follow external index changes (controlled prop, clamping after a resize).
useEffect(() => {
const t = Math.round(targetRef.current);
const settled = wrap ? mod(t, count) : t;
if (settled === current) return;
let target = current;
if (wrap) {
let delta = current - settled;
if (delta > count / 2) delta -= count;
if (delta < -count / 2) delta += count;
target = t + delta;
}
animateTo(target);
}, [current, wrap, count, animateTo]);
const canPrev = loop || current > 0;
const canNext = loop || current < maxIndex;
const next = useCallback(() => {
if (positions <= 1) return;
if (wrap) goTo(Math.round(targetRef.current) + 1);
else goTo(current >= maxIndex ? (loop ? 0 : maxIndex) : current + 1);
}, [positions, wrap, goTo, current, maxIndex, loop]);
const prev = useCallback(() => {
if (positions <= 1) return;
if (wrap) goTo(Math.round(targetRef.current) - 1);
else goTo(current <= 0 ? (loop ? maxIndex : 0) : current - 1);
}, [positions, wrap, goTo, current, maxIndex, loop]);
const jumpTo = useCallback(
(i: number) => {
if (!wrap) return goTo(i);
const base = Math.round(targetRef.current);
let delta = i - mod(base, count);
if (delta > count / 2) delta -= count;
if (delta < -count / 2) delta += count;
goTo(base + delta);
},
[wrap, goTo, count],
);
/* ---- drag (motion pan) ---- */
const dragStart = useRef(0);
const [dragging, setDragging] = useState(false);
const suppressClick = useRef(false);
const onPanStart = () => {
animationRef.current?.stop();
dragStart.current = pos.get();
suppressClick.current = true;
setDragging(true);
};
const onPan = (_: PointerEvent, info: PanInfo) => {
const s = step.get();
if (!s) return;
const rawPos = dragStart.current - info.offset.x / s;
if (wrap) {
pos.set(rawPos);
return;
}
if (rawPos < 0) pos.set(-rubber(-rawPos));
else if (rawPos > maxIndex) pos.set(maxIndex + rubber(rawPos - maxIndex));
else pos.set(rawPos);
};
const onPanEnd = (_: PointerEvent, info: PanInfo) => {
setDragging(false);
// Let the click that ends this drag land first, then re-enable clicks.
setTimeout(() => {
suppressClick.current = false;
}, 0);
const s = step.get();
if (!s) return;
const start = Math.round(dragStart.current);
const v = info.velocity.x;
let target: number;
if (reduce) {
// No momentum: one slide in the drag direction past a small threshold.
const moved = info.offset.x / s;
target = Math.abs(moved) > 0.2 ? start - Math.sign(moved) : start;
} else {
const projected = pos.get() - (v * MOMENTUM_TIME) / s;
target = Math.round(projected);
if (target === start && Math.abs(v) > FLICK_VELOCITY) {
target = start - Math.sign(v);
}
target = Math.min(start + MAX_FLING, Math.max(start - MAX_FLING, target));
}
goTo(target, reduce ? 0 : -v / s);
};
/* ---- autoplay ---- */
const interval =
autoplay === true ? DEFAULT_INTERVAL : autoplay ? Math.max(1000, autoplay) : 0;
const [stopped, setStopped] = useState(false);
const [hovered, setHovered] = useState(false);
const [focused, setFocused] = useState(false);
const [tabHidden, setTabHidden] = useState(false);
const autoplayOn = interval > 0 && !reduce && positions > 1 && !stopped;
const paused = hovered || focused || tabHidden || dragging;
useEffect(() => {
const update = () => setTabHidden(document.visibilityState === "hidden");
update();
document.addEventListener("visibilitychange", update);
return () => document.removeEventListener("visibilitychange", update);
}, []);
const progress = useMotionValue(0);
const elapsed = useRef(0);
const nextRef = useRef(next);
nextRef.current = next;
const runningRef = useRef(false);
runningRef.current = autoplayOn && !paused;
// biome-ignore lint/correctness/useExhaustiveDependencies: restart the timer on every slide change.
useEffect(() => {
elapsed.current = 0;
progress.set(0);
}, [current, autoplayOn, progress]);
useAnimationFrame((_, delta) => {
if (!runningRef.current) return;
elapsed.current += delta;
if (elapsed.current >= interval) {
elapsed.current = 0;
progress.set(0);
nextRef.current();
} else {
progress.set(elapsed.current / interval);
}
});
/* ---- keyboard ---- */
const onKeyDown = (e: ReactKeyboardEvent<HTMLElement>) => {
const target = e.target as HTMLElement;
if (
target.isContentEditable ||
["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName)
)
return;
if (e.key === "ArrowLeft") {
e.preventDefault();
prev();
} else if (e.key === "ArrowRight") {
e.preventDefault();
next();
} else if (e.key === "Home") {
e.preventDefault();
jumpTo(0);
} else if (e.key === "End") {
e.preventDefault();
jumpTo(maxIndex);
}
};
const isVisible = (i: number) => {
const offset = wrap ? mod(i - current + 1, count) - 1 : i - current;
return offset >= 0 && offset < perView;
};
return (
<section
aria-roledescription="carousel"
aria-label={ariaLabel}
onKeyDown={onKeyDown}
onPointerEnter={(e) => {
if (e.pointerType === "mouse") setHovered(true);
}}
onPointerLeave={() => setHovered(false)}
onFocus={() => setFocused(true)}
onBlur={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null))
setFocused(false);
}}
className={cn("relative flex w-full flex-col gap-3", className)}
>
<div className="relative">
<motion.div
ref={viewportRef}
onPanStart={onPanStart}
onPan={onPan}
onPanEnd={onPanEnd}
onClickCapture={(e) => {
if (!suppressClick.current) return;
e.preventDefault();
e.stopPropagation();
}}
className={cn(
"relative overflow-hidden",
// Vertical page scroll stays native; horizontal belongs to the pan.
"touch-pan-y",
TOUCH_GESTURE_CONTENT_CLASS,
dragging ? "cursor-grabbing select-none" : "cursor-grab",
)}
>
<div className="flex items-stretch" style={{ gap }}>
{slides.map((slide, i) => (
<Slide
// biome-ignore lint/suspicious/noArrayIndexKey: slides are positional.
key={i}
index={i}
count={count}
wrap={wrap}
pos={pos}
step={step}
perView={perView}
gap={gap}
visible={isVisible(i)}
label={getSlideLabel(i, count)}
className={slideClassName}
>
{slide}
</Slide>
))}
</div>
</motion.div>
{showControls && positions > 1 ? (
<>
<NavButton
side="prev"
disabled={!canPrev}
onClick={prev}
reduce={reduce}
/>
<NavButton
side="next"
disabled={!canNext}
onClick={next}
reduce={reduce}
/>
</>
) : null}
</div>
{indicators !== "none" && positions > 1 ? (
<div className="flex items-center justify-center gap-2">
{interval > 0 && !reduce ? (
<button
type="button"
onClick={() => setStopped((s) => !s)}
aria-label={stopped ? "Start automatic slide show" : "Stop automatic slide show"}
className="grid size-6 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"
>
{stopped ? <Play className="size-3" /> : <Pause className="size-3" />}
</button>
) : null}
<LayoutGroup id={groupId}>
{indicators === "dots" ? (
<div className="flex items-center">
{Array.from({ length: positions }, (_, i) => {
const active = i === current;
return (
<button
// biome-ignore lint/suspicious/noArrayIndexKey: positions are positional.
key={i}
type="button"
aria-label={`Go to slide ${i + 1}`}
aria-current={active ? "true" : undefined}
onClick={() => jumpTo(i)}
className="group relative grid h-6 w-6 place-items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
>
<span className="size-1.5 rounded-full bg-muted-foreground/40 transition-colors group-hover:bg-muted-foreground/70" />
{active ? (
<motion.span
layoutId="carousel-dot"
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className="absolute inset-x-0.5 top-1/2 h-2 -translate-y-1/2 overflow-hidden rounded-full bg-foreground/25"
>
<ProgressFill
progress={progress}
running={autoplayOn}
className="bg-foreground"
/>
</motion.span>
) : null}
</button>
);
})}
</div>
) : (
<div className="flex max-w-full items-center gap-1.5 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{Array.from({ length: positions }, (_, i) => {
const active = i === current;
return (
<button
// biome-ignore lint/suspicious/noArrayIndexKey: positions are positional.
key={i}
type="button"
aria-label={`Go to slide ${i + 1}`}
aria-current={active ? "true" : undefined}
onClick={() => jumpTo(i)}
className={cn(
"relative h-10 w-14 shrink-0 overflow-hidden rounded-md outline-none transition-opacity focus-visible:ring-2 focus-visible:ring-ring/50",
active ? "opacity-100" : "opacity-55 hover:opacity-90",
)}
>
<span className="pointer-events-none block size-full">
{renderThumbnail?.(i) ?? (
<span className="grid size-full place-items-center bg-muted text-muted-foreground text-xs tabular-nums">
{i + 1}
</span>
)}
</span>
{active ? (
<motion.span
layoutId="carousel-thumb"
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className="pointer-events-none absolute inset-0 overflow-hidden rounded-md ring-2 ring-primary ring-inset"
>
<span className="absolute inset-x-0 bottom-0 h-0.5 bg-primary/30">
<ProgressFill
progress={progress}
running={autoplayOn}
className="bg-primary"
/>
</span>
</motion.span>
) : null}
</button>
);
})}
</div>
)}
</LayoutGroup>
</div>
) : null}
<div aria-live={autoplayOn && !paused ? "off" : "polite"} className="sr-only">
{count > 0 ? `Slide ${current + 1} of ${positions}` : ""}
</div>
</section>
);
}
function Slide({
index,
count,
wrap,
pos,
step,
perView,
gap,
visible,
label,
className,
children,
}: {
index: number;
count: number;
wrap: boolean;
pos: MotionValue<number>;
step: MotionValue<number>;
perView: number;
gap: number;
visible: boolean;
label: string;
className?: string;
children: ReactNode;
}) {
// Each slide sits at its natural flex slot (index * step) and is shifted to
// its slot relative to the track position. When wrapping, the offset is
// folded into [-1, count - 1) so a slide leaving one edge re-enters the other.
const x = useTransform([pos, step], ([p, s]: number[]) => {
let offset = index - p;
if (wrap) offset = mod(offset + 1, count) - 1;
return (offset - index) * s;
});
return (
<motion.div
role="group"
aria-roledescription="slide"
aria-label={label}
inert={!visible}
style={{
x,
width: `calc((100% - ${gap * (perView - 1)}px) / ${perView})`,
}}
className={cn("shrink-0", className)}
>
{children}
</motion.div>
);
}
function ProgressFill({
progress,
running,
className,
}: {
progress: MotionValue<number>;
running: boolean;
className?: string;
}) {
if (!running) return <span className={cn("absolute inset-0", className)} />;
return (
<motion.span
aria-hidden
className={cn("absolute inset-0 origin-left", className)}
style={{ scaleX: progress }}
/>
);
}
function NavButton({
side,
disabled,
onClick,
reduce,
}: {
side: "prev" | "next";
disabled: boolean;
onClick: () => void;
reduce: boolean;
}) {
const isPrev = side === "prev";
const Icon = isPrev ? ChevronLeft : ChevronRight;
return (
<motion.button
type="button"
aria-label={isPrev ? "Previous slide" : "Next slide"}
disabled={disabled}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.9 }}
transition={SPRING_PRESS}
className={cn(
"-translate-y-1/2 absolute top-1/2 grid size-9 place-items-center rounded-full border border-border bg-background/85 text-foreground shadow-sm outline-none backdrop-blur-sm transition-[opacity,background-color] hover:bg-background focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-0",
isPrev ? "left-2" : "right-2",
)}
>
<Icon className="size-4" />
</motion.button>
);
}
@karaui not found? Add it to components.json
{
"registries": {
"@karaui": "https://karaui.kamisama-v0.my.id/r/{name}.json"
}
}@karaui is in shadcn's public registry directory, so the latest CLI needs no setup. On an older CLI, merge this into the existing file once and every @karaui/… install resolves.
API Reference
childrenReactNodeOne child per slide.
—index?numberControlled index of the first visible slide.
—defaultIndex?numberInitial index for uncontrolled use.
0onIndexChange?((index: number) => void)—loop?booleanWrap past either end. Seamless when there are at least `slidesPerView + 2` slides.
falseautoplay?number | booleanAdvance automatically; `true` = every 5000ms, or pass the interval in ms. Pauses on hover, focus, drag and hidden tabs; off under reduced motion.
falseslidesPerView?number | Record<number, number>Slides shown at once: a number, or `{ minContainerWidthPx: count }`, e.g. `{ 0: 1, 480: 2, 768: 3 }`.
1gap?numberSpace between slides in px.
16indicators?"none" | "dots" | "thumbnails"dotsrenderThumbnail?((index: number) => ReactNode)Thumbnail content per position, for `indicators="thumbnails"`.
—showControls?booleanRender previous / next buttons.
truearia-label?stringAccessible name of the carousel.
CarouselgetSlideLabel?((index: number, count: number) => string)Accessible name per slide.
(i, n) => `${i + 1} of ${n}`className?string—slideClassName?string—Updated