Skip to content
Shaken UI
Sign in

Carousel

Save

A CSS scroll-snap carousel with previous and next buttons, dots, arrow-key support, and optional autoplay that pauses on hover, focus, and reduced motion.

Category
Data display
Version
0.1.1
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Carousel preview
v0.9

Approval gates

Pause any tool call until a person approves it, with the exact command shown.

v0.8

Trace inspector

Step through every model call and tool result in a run, with timings.

v0.7

Streaming messages

Tokens render as they arrive, with a caret that stops when the run ends.

v0.6

Run graphs

See how sub-agents hand work to each other, and where a run is waiting.

v0.5

Prompt composer

Attach files, pick tools, and send with a shortcut from one field.

Installation

npx @shakenui/cli add carousel

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add carousel --dry-run

Usage

carousel-example.tsx
import { Carousel, CarouselContent, CarouselControls, CarouselDots, CarouselItem, CarouselNext, CarouselPlayToggle, CarouselPrevious } from "@/components/shaken/ui/carousel";

const releases = [
  { version: "v0.9", title: "Approval gates", body: "Pause any tool call until a person approves it, with the exact command shown." },
  { version: "v0.8", title: "Trace inspector", body: "Step through every model call and tool result in a run, with timings." },
  { version: "v0.7", title: "Streaming messages", body: "Tokens render as they arrive, with a caret that stops when the run ends." },
  { version: "v0.6", title: "Run graphs", body: "See how sub-agents hand work to each other, and where a run is waiting." },
  { version: "v0.5", title: "Prompt composer", body: "Attach files, pick tools, and send with a shortcut from one field." },
];

export default function CarouselExample() {
  return (
    <Carousel label="Release highlights" autoplay={6000} className="w-full max-w-2xl">
      <CarouselContent>
        {releases.map((release, i) => (
          <CarouselItem key={release.version} index={i} total={releases.length} className="sm:basis-[calc(50%-0.375rem)]">
            <article className="grid h-full content-start gap-2 rounded-xl border border-zinc-950/10 bg-white p-5 text-zinc-950 dark:border-white/10 dark:bg-black dark:text-white">
              <span className="font-mono text-xs text-zinc-500">{release.version}</span>
              <h3 className="text-base font-semibold">{release.title}</h3>
              <p className="text-sm text-zinc-600 dark:text-zinc-400">{release.body}</p>
            </article>
          </CarouselItem>
        ))}
      </CarouselContent>
      <CarouselControls>
        <CarouselDots className="-ms-1.5" />
        <div className="ms-auto flex items-center gap-1.5">
          <CarouselPlayToggle />
          <CarouselPrevious />
          <CarouselNext />
        </div>
      </CarouselControls>
    </Carousel>
  );
}

API

PropTypeDefaultDescription
Carousel labelstring—Accessible name of the carousel region.
Carousel autoplaynumber | falsefalseAdvances every n milliseconds. Pauses on hover, on focus inside, in a hidden tab, and under reduced motion.
Carousel loopbooleanfalseThe arrows wrap at the ends. Autoplay always wraps.
CarouselContent gapClassNamestring"gap-3"Gap between slides.
CarouselItem index / totalnumber—Position for the "2 of 5" slide label.
CarouselItem classNamestring—Pass a basis class such as sm:basis-1/2 to show several slides.
CarouselPrevious / CarouselNext / CarouselDots / CarouselPlayToggle / CarouselControlsbutton / div props—Controls; dots map to resting positions, not to slides hidden behind a partial view.

Accessibility

  • The root is a section with aria-roledescription="carousel" and its label; each slide is a group with aria-roledescription="slide" and an "n of total" label.
  • Left and Right arrow keys move one stop while focus is anywhere inside, except in text fields.
  • The track is focusable and scrolls natively by touch, trackpad, and wheel; snapping is pure CSS.
  • Autoplay stops while hovered or focused, in a hidden tab, and entirely under reduced motion; CarouselPlayToggle lets anyone pause it.
  • Slide changes are announced politely only when autoplay is not running, and smooth scrolling becomes instant under reduced motion.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/carousel.tsxcarousel
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/carousel/0.1.1.json.

ui/carousel.tsxShow
ui/carousel.tsx
"use client";

import {
  Children,
  type ComponentProps,
  createContext,
  type KeyboardEvent,
  type ReactNode,
  type RefObject,
  useCallback,
  useContext,
  useEffect,
  useRef,
  useState,
} from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

type CarouselContextValue = {
  viewportRef: RefObject<HTMLDivElement | null>;
  /** Scroll offsets the carousel can rest at, one per dot. */
  stops: number[];
  index: number;
  canPrev: boolean;
  canNext: boolean;
  goTo: (stop: number) => void;
  prev: () => void;
  next: () => void;
  /** The user's choice from the play toggle. */
  playing: boolean;
  /** Whether slides are advancing right now (not held by hover or focus). */
  running: boolean;
  autoplay: boolean;
  togglePlaying: () => void;
  register: () => void;
  label: string;
};

const CarouselContext = createContext<CarouselContextValue | null>(null);

function useCarousel(part: string) {
  const context = useContext(CarouselContext);
  if (!context) throw new Error(`${part} must be used inside <Carousel>.`);
  return context;
}

function prefersReducedMotion() {
  return typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}

export interface CarouselProps extends ComponentProps<"section"> {
  /** Accessible name, for example "Release highlights". */
  label: string;
  /** Advances on a timer, in milliseconds. Pauses on hover, on focus, in a hidden tab, and under reduced motion. */
  autoplay?: number | false;
  /** Wraps from the last slide to the first with the arrows. Autoplay always wraps. */
  loop?: boolean;
}

/**
 * A carousel built on CSS scroll snapping, so touch, trackpad, and wheel scrolling feel native.
 * Arrow keys move between slides while focus is inside it. Compose it from `CarouselContent`,
 * `CarouselItem`, `CarouselPrevious`, `CarouselNext`, `CarouselDots`, and `CarouselPlayToggle`.
 */
export function Carousel({ label, autoplay = false, loop = false, className, children, onKeyDown, ...props }: CarouselProps) {
  const viewportRef = useRef<HTMLDivElement>(null);
  const rootRef = useRef<HTMLElement>(null);
  const [stops, setStops] = useState<number[]>([0]);
  const stopsRef = useRef<number[]>([0]);
  const [index, setIndex] = useState(0);
  const [version, setVersion] = useState(0);
  // Playing is the user's choice (the play toggle); paused is the temporary hover/focus hold.
  const [playing, setPlaying] = useState(autoplay !== false);
  const [held, setHeld] = useState(false);
  const [reduced, setReduced] = useState(false);

  const measure = useCallback(() => {
    const viewport = viewportRef.current;
    if (!viewport) return;
    const max = viewport.scrollWidth - viewport.clientWidth;
    const start = viewport.getBoundingClientRect().left - viewport.scrollLeft;
    const items = Array.from(viewport.querySelectorAll<HTMLElement>("[data-slot=carousel-item]"));
    const padStart = Number.parseFloat(getComputedStyle(viewport).scrollPaddingInlineStart) || 0;
    const offsets = items.map((item) => Math.min(max, Math.max(0, Math.round(item.getBoundingClientRect().left - start - padStart))));
    const unique = offsets.filter((offset, i) => i === 0 || offset - offsets[i - 1]! > 2);
    stopsRef.current = unique.length ? unique : [0];
    setStops(stopsRef.current);
  }, []);

  const sync = useCallback(() => {
    const viewport = viewportRef.current;
    if (!viewport) return;
    const current = stopsRef.current;
    const left = viewport.scrollLeft;
    let nearest = 0;
    current.forEach((stop, i) => {
      if (Math.abs(stop - left) < Math.abs(current[nearest]! - left)) nearest = i;
    });
    setIndex(nearest);
  }, []);

  useEffect(() => {
    const viewport = viewportRef.current;
    if (!viewport) return;
    measure();
    sync();
    const observer = new ResizeObserver(() => {
      measure();
      sync();
    });
    observer.observe(viewport);
    let frame = 0;
    const onScroll = () => {
      cancelAnimationFrame(frame);
      frame = requestAnimationFrame(sync);
    };
    viewport.addEventListener("scroll", onScroll, { passive: true });
    return () => {
      observer.disconnect();
      viewport.removeEventListener("scroll", onScroll);
      cancelAnimationFrame(frame);
    };
  }, [measure, sync, version]);

  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);

  const goTo = useCallback(
    (stop: number) => {
      const viewport = viewportRef.current;
      const target = stops[Math.max(0, Math.min(stops.length - 1, stop))];
      if (!viewport || target === undefined) return;
      viewport.scrollTo({ left: target, behavior: prefersReducedMotion() ? "auto" : "smooth" });
    },
    [stops],
  );

  const last = stops.length - 1;
  const prev = useCallback(() => goTo(index === 0 && loop ? last : index - 1), [goTo, index, loop, last]);
  const next = useCallback(() => goTo(index === last && loop ? 0 : index + 1), [goTo, index, loop, last]);

  const running = autoplay !== false && playing && !held && !reduced && last > 0;
  useEffect(() => {
    if (!running) return;
    const timer = setInterval(() => {
      if (document.hidden) return;
      goTo(index >= last ? 0 : index + 1);
    }, autoplay);
    return () => clearInterval(timer);
  }, [running, autoplay, goTo, index, last]);

  function handleKeyDown(event: KeyboardEvent<HTMLElement>) {
    onKeyDown?.(event);
    if (event.defaultPrevented) return;
    const target = event.target as HTMLElement;
    if (target.closest("input, textarea, select, [contenteditable=true]")) return;
    if (event.key === "ArrowLeft") {
      event.preventDefault();
      prev();
    } else if (event.key === "ArrowRight") {
      event.preventDefault();
      next();
    }
  }

  return (
    <CarouselContext.Provider
      value={{
        viewportRef,
        stops,
        index,
        canPrev: loop || index > 0,
        canNext: loop || index < last,
        goTo,
        prev,
        next,
        playing,
        running,
        autoplay: autoplay !== false && !reduced,
        togglePlaying: () => setPlaying((value) => !value),
        register: () => setVersion((value) => value + 1),
        label,
      }}
    >
      <section
        ref={rootRef}
        aria-roledescription="carousel"
        aria-label={label}
        data-slot="carousel"
        data-playing={running || undefined}
        onKeyDown={handleKeyDown}
        onPointerEnter={(event) => event.pointerType === "mouse" && setHeld(true)}
        onPointerLeave={(event) => event.pointerType === "mouse" && setHeld(false)}
        onFocus={() => setHeld(true)}
        onBlur={(event) => {
          if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setHeld(false);
        }}
        className={cx("relative grid min-w-0 gap-3", className)}
        {...props}
      >
        {children}
      </section>
    </CarouselContext.Provider>
  );
}

export interface CarouselContentProps extends ComponentProps<"div"> {
  /** Gap between slides, as a Tailwind gap class. */
  gapClassName?: string;
}

/**
 * The scrolling track. Slides snap to its start edge; the scrollbar is hidden because the
 * arrows, dots, and swipe already show position.
 */
export function CarouselContent({ gapClassName = "gap-3", className, children, ...props }: CarouselContentProps) {
  const { viewportRef, register, running } = useCarousel("CarouselContent");
  const count = Children.count(children);
  useEffect(register, [count]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <div
      ref={viewportRef}
      data-slot="carousel-content"
      // Announce slide changes only when the user caused them, not on every autoplay tick.
      aria-live={running ? "off" : "polite"}
      tabIndex={0}
      className={cx(
        "flex snap-x snap-mandatory overflow-x-auto overscroll-x-contain",
        "[scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
        "rounded-xl outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
        gapClassName,
        className,
      )}
      {...props}
    >
      {children}
    </div>
  );
}

export interface CarouselItemProps extends ComponentProps<"div"> {
  /** Position, used for the "3 of 5" announcement. Set automatically when omitted. */
  index?: number;
  /** Total slides, used with `index`. */
  total?: number;
}

/**
 * One slide. Full width by default; pass a basis class such as `basis-1/2 sm:basis-1/3` to show
 * several at once.
 */
export function CarouselItem({ index, total, className, ...props }: CarouselItemProps) {
  return (
    <div
      role="group"
      aria-roledescription="slide"
      aria-label={index !== undefined && total !== undefined ? `${index + 1} of ${total}` : undefined}
      data-slot="carousel-item"
      className={cx("min-w-0 shrink-0 grow-0 basis-full snap-start", className)}
      {...props}
    />
  );
}

function ArrowButton({ direction, className, ...props }: ComponentProps<"button"> & { direction: "prev" | "next" }) {
  const carousel = useCarousel(direction === "prev" ? "CarouselPrevious" : "CarouselNext");
  const enabled = direction === "prev" ? carousel.canPrev : carousel.canNext;
  return (
    <button
      type="button"
      aria-label={direction === "prev" ? "Previous slide" : "Next slide"}
      disabled={!enabled}
      onClick={direction === "prev" ? carousel.prev : carousel.next}
      className={cx(
        "inline-flex size-8 shrink-0 items-center justify-center rounded-lg border select-none",
        "border-zinc-950/12 bg-white text-zinc-700 hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] hover:text-zinc-950",
        "dark:border-white/15 dark:bg-black dark:text-zinc-300 dark:hover:border-white/25 dark:hover:bg-white/[0.06] dark:hover:text-white",
        "transition-[background-color,border-color,color,scale,opacity] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
        "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
        "disabled:pointer-events-none disabled:opacity-40",
        className,
      )}
      {...props}
    >
      <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4">
        <path
          d={direction === "prev" ? "M10 3.5 5.5 8l4.5 4.5" : "M6 3.5 10.5 8 6 12.5"}
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    </button>
  );
}

/** Scrolls back one stop. Disabled at the start unless the carousel loops. */
export function CarouselPrevious(props: ComponentProps<"button">) {
  return <ArrowButton direction="prev" {...props} />;
}

/** Scrolls forward one stop. Disabled at the end unless the carousel loops. */
export function CarouselNext(props: ComponentProps<"button">) {
  return <ArrowButton direction="next" {...props} />;
}

/** One dot per resting position. The current dot is solid and marked `aria-current`. */
export function CarouselDots({ className, ...props }: ComponentProps<"div">) {
  const { stops, index, goTo } = useCarousel("CarouselDots");
  if (stops.length < 2) return null;
  return (
    <div role="group" aria-label="Choose slide" data-slot="carousel-dots" className={cx("flex items-center", className)} {...props}>
      {stops.map((_, i) => (
        <button
          key={i}
          type="button"
          aria-label={`Go to slide ${i + 1}`}
          aria-current={i === index ? "true" : undefined}
          onClick={() => goTo(i)}
          className="group/dot inline-flex size-6 items-center justify-center rounded-md focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500"
        >
          <span
            aria-hidden="true"
            className={cx(
              "size-1.5 rounded-full transition-[background-color,scale] duration-200 ease-out motion-reduce:transition-none",
              i === index
                ? "scale-125 bg-zinc-950 dark:bg-white"
                : "bg-zinc-950/20 group-hover/dot:bg-zinc-950/40 dark:bg-white/25 dark:group-hover/dot:bg-white/45",
            )}
          />
        </button>
      ))}
    </div>
  );
}

/**
 * Pauses and resumes autoplay, so moving content can always be stopped. Renders nothing when
 * autoplay is off or reduced motion is preferred.
 */
export function CarouselPlayToggle({ className, ...props }: ComponentProps<"button">) {
  const { autoplay, playing, togglePlaying } = useCarousel("CarouselPlayToggle");
  if (!autoplay) return null;
  const showPause = playing;
  return (
    <button
      type="button"
      aria-label={showPause ? "Pause autoplay" : "Start autoplay"}
      onClick={togglePlaying}
      className={cx(
        "inline-flex size-8 items-center justify-center rounded-lg text-zinc-500",
        "transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
        "hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
        "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
        className,
      )}
      {...props}
    >
      <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4">
        {showPause ? (
          <path d="M5.75 3.75v8.5M10.25 3.75v8.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
        ) : (
          <path d="M5.25 3.6v8.8a.5.5 0 0 0 .77.42l6.6-4.4a.5.5 0 0 0 0-.84l-6.6-4.4a.5.5 0 0 0-.77.42Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
        )}
      </svg>
    </button>
  );
}

/** Lays out the arrows, dots, and play toggle in one quiet row. Optional. */
export function CarouselControls({ className, children, ...props }: ComponentProps<"div"> & { children?: ReactNode }) {
  return (
    <div data-slot="carousel-controls" className={cx("flex items-center gap-2", className)} {...props}>
      {children}
    </div>
  );
}