Skip to content
Pebble Pro is here at $49 one timeSee what’s included ↗
Pebble
ComponentsDocsMCPPricing
⌕ Find a component↗Log in
All components 673

Categories

Core inputs & forms46Buttons & actions33Navigation36Overlays & feedback49Data display33Charts & data viz40Cards & layout43Marketing blocks38App shells & pages37AI interfaces40Text & typography effects33Backgrounds & visual effects38Motion & transitions32Numbers & counters32Media34E-commerce333D & interactive36Themed sets40
Start with the essentials.Installation guide ↗Connect your agent ↗
← All componentsMedia

Carousel

A flat scroll-snap carousel with drag, keyboard, dots with autoplay progress, loop, vertical orientation and responsive slides per view.

Preview

New in the studio

Six pieces, hand picked this week

01 / 01

New

Arc desk lamp

Pebble

$128

4.8

Pour kettle

Pebble

$84

4.6

Best seller

Shelf speaker

Pebble

$219

4.9

Loom chair

Pebble

$340

4.7

Glaze mug

Pebble

$24

4.5

Ceramic planter

Pebble

$46

4.8

“We swapped three tools for one board. Planning went from a day to an hour.
IVInes VargaHead of Ops, Northline
“The handoff notes alone saved our support team 40 tickets a week.
MOMalik OseiSupport lead, Pebble notes
“It feels like the app knows what I am about to do next. In a good way.
PRPriya RamanProduct designer, Pebble

Active users

12,480

+8.2%

Avg. session

6m 42s

+0.4%

Churn

1.9%

−0.3%

Refunds

$1,284

+2.1%

01 / 01

Install

Add the editable source with the shadcn CLI. Your project also needs the shared theme tokens this component uses. Setup and requirements. The Pebble installer is not published yet.

npx shadcn@latest add https://pebbleui.com/r/carousel.json

Props

PropTypeDefaultDescription
orientation"horizontal" | "vertical""horizontal"Scroll axis. Vertical carousels need a height on CarouselContent.
slidesPerViewnumber | { base, sm, md, lg, xl }1Slides in view; the object steps up with the carousel's own width (container queries).
loopbooleanfalsePrevious at the start goes to the end, next at the end rewinds.
autoplaynumber0Milliseconds per slide. Pauses on hover, focus and drag; off under reduced motion. Add CarouselPlayToggle.
gapstring"1rem"CSS length between slides.
defaultIndexnumber0Snap point to start on.
onIndexChange(index: number) => void—Called when the current snap point changes.
setApi(api: CarouselApi) => void—Receives { index, count, canPrev, canNext, prev, next, scrollTo }.
labelstring"Carousel"Accessible name of the carousel region.
Build notes
- Track: `flex` + `overflow-x-auto snap-x snap-mandatory`, items `snap-start`,
  scrollbar hidden. The track has `-m-2 p-2 scroll-p-2` so slide rings and
  shadows are not clipped by the scroller.
- Slide size is pure CSS: the root writes `--pv-base…--pv-xl` and
  `--carousel-gap`; each item picks `--pv` with `@sm:/@md:/@lg:/@xl:` container
  variants and sets `flex-basis: calc((100% - (pv - 1) * gap) / pv)`.
- Snap points are measured, not derived: each item's offset from the first
  item, clamped to the max scroll, deduplicated (within 2px). A
  ResizeObserver re-measures on size changes. The current index is the snap
  point nearest the scroll position, read in one rAF per scroll burst, so
  wheel/touch/focus scrolling keep the dots right.
- Drag-to-scroll only for `pointerType === "mouse"` (touch is native): after
  5px slop it captures the pointer, sets `data-dragging` (which turns off
  snapping and smooth scrolling), writes `scrollLeft` directly, tracks a
  velocity clamped to ±1.5px/ms and on release scrolls to the snap nearest to
  `position + v * 120ms`. A click right after a drag is swallowed in capture.
- Autoplay: one rAF loop accumulates elapsed time only while playing and not
  paused (hover, focus-within, drag), writes the share into
  `--carousel-progress` on the active dot's fill (`scaleX`, no React render)
  and advances at 1. Index changes reset the clock.
- Dot: 12px hit area, the active one widens to 28px (`--motion-base`,
  `ease-move`), its well is `foreground/15` with an inset shade; the fill is
  ink when static, ember when autoplaying.
- Controls are raised round pebbles (`ring-hairline shadow-raised-sm
inset-shadow-highlight`), press drops 1px and scales to 0.96.

<!-- PEBBLE-LICENSE -->
View source

registry/media/carousel/carousel.tsx

"use client";

/* PEBBLE-LICENSE
Built by Pebble. Component: carousel.

First-party license: MIT

The following first-party terms apply only to original Pebble material.

MIT License

Copyright (c) 2026 Praxys Solutions LLC (Pebble)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

THIRD-PARTY NOTICES
These notices apply to identified upstream portions; Pebble terms do not replace or narrow their rights.

Upstream: https://raw.githubusercontent.com/shadcn-ui/ui/main/LICENSE.md
MIT License

Copyright (c) 2023 shadcn

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
END PEBBLE-LICENSE */

import * as React from "react";

import { cn } from "@/lib/utils";

type Orientation = "horizontal" | "vertical";

/** Slides visible at once. A number, or per container width (`@sm` 24rem, `@md` 28rem, `@lg` 32rem, `@xl` 36rem). */
export type SlidesPerView =
  number | { base?: number; sm?: number; md?: number; lg?: number; xl?: number };

export type CarouselApi = {
  /** Index of the current snap point. */
  index: number;
  /** Number of snap points (slides minus the ones already in view at the end). */
  count: number;
  canPrev: boolean;
  canNext: boolean;
  prev: () => void;
  next: () => void;
  scrollTo: (index: number) => void;
};

type CarouselContextValue = CarouselApi & {
  orientation: Orientation;
  loop: boolean;
  trackRef: React.RefObject<HTMLDivElement | null>;
  progressRef: React.RefObject<HTMLSpanElement | null>;
  autoplay: number;
  playing: boolean;
  paused: boolean;
  setPlaying: (playing: boolean) => void;
  onTrackScroll: () => void;
  dragging: boolean;
  setDragging: (dragging: boolean) => void;
  reduce: boolean;
  snaps: number[];
  slideCount: number;
};

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

export function useCarousel() {
  const ctx = React.useContext(CarouselContext);
  if (!ctx) throw new Error("useCarousel must be used inside <Carousel>");
  return ctx;
}

const subscribeReduce = (cb: () => void) => {
  const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
  mq.addEventListener("change", cb);
  return () => mq.removeEventListener("change", cb);
};
const getReduce = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches;

// Pixels a mouse must travel before a press becomes a drag.
const DRAG_SLOP = 5;

function perViewVars(value: SlidesPerView): React.CSSProperties {
  const v = typeof value === "number" ? { base: value } : value;
  const base = v.base ?? 1;
  const sm = v.sm ?? base;
  const md = v.md ?? sm;
  const lg = v.lg ?? md;
  const xl = v.xl ?? lg;
  return {
    "--pv-base": base,
    "--pv-sm": sm,
    "--pv-md": md,
    "--pv-lg": lg,
    "--pv-xl": xl,
  } as React.CSSProperties;
}

export type CarouselProps = Omit<React.ComponentProps<"section">, "onChange"> & {
  /** Scroll axis. Vertical carousels need a height on `CarouselContent`. */
  orientation?: Orientation;
  /** Previous at the first slide goes to the last, next at the last rewinds to the first. */
  loop?: boolean;
  /** Milliseconds per slide. Omit or 0 for no autoplay. Off under reduced motion. */
  autoplay?: number;
  /** Slides in view at once. */
  slidesPerView?: SlidesPerView;
  /** Gap between slides, any CSS length. */
  gap?: string;
  /** Snap point to start on. */
  defaultIndex?: number;
  /** Called when the current snap point changes. */
  onIndexChange?: (index: number) => void;
  /** Receives the imperative API once mounted and on every change. */
  setApi?: (api: CarouselApi) => void;
  /** Accessible name of the region. */
  label?: string;
};

export function Carousel({
  orientation = "horizontal",
  loop = false,
  autoplay = 0,
  slidesPerView = 1,
  gap = "1rem",
  defaultIndex = 0,
  onIndexChange,
  setApi,
  label = "Carousel",
  className,
  style,
  children,
  onKeyDown,
  onPointerEnter,
  onPointerLeave,
  onFocus,
  onBlur,
  ...props
}: CarouselProps) {
  const trackRef = React.useRef<HTMLDivElement>(null);
  const progressRef = React.useRef<HTMLSpanElement>(null);
  const reduce = React.useSyncExternalStore(subscribeReduce, getReduce, () => false);
  const [snaps, setSnaps] = React.useState<number[]>([0]);
  const [slideCount, setSlideCount] = React.useState(0);
  const [index, setIndex] = React.useState(defaultIndex);
  const [dragging, setDragging] = React.useState(false);
  const [hovered, setHovered] = React.useState(false);
  const [focused, setFocused] = React.useState(false);
  const [playing, setPlaying] = React.useState(true);
  const count = snaps.length;
  const auto = autoplay > 0 && !reduce ? autoplay : 0;
  const paused = hovered || focused || dragging;

  const axis = orientation === "horizontal" ? "left" : "top";

  // Snap points: every slide's offset, clamped to the furthest the track can
  // scroll, deduplicated. Slides already in view at the end share one point.
  const measure = React.useCallback(() => {
    const track = trackRef.current;
    if (!track) return;
    const items = Array.from(track.children) as HTMLElement[];
    setSlideCount(items.length);
    const horizontal = orientation === "horizontal";
    const max = horizontal
      ? track.scrollWidth - track.clientWidth
      : track.scrollHeight - track.clientHeight;
    const points: number[] = [];
    // Offsets are measured from the first slide so the track's padding cancels out.
    const origin = items[0] ? (horizontal ? items[0].offsetLeft : items[0].offsetTop) : 0;
    for (const item of items) {
      const offset = Math.min(
        (horizontal ? item.offsetLeft : item.offsetTop) - origin,
        Math.max(max, 0),
      );
      if (!points.length || offset - points[points.length - 1] > 2) points.push(offset);
    }
    setSnaps((prev) =>
      prev.length === points.length && prev.every((p, i) => p === points[i])
        ? prev
        : points.length
          ? points
          : [0],
    );
  }, [orientation]);

  React.useEffect(() => {
    const track = trackRef.current;
    if (!track) return;
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(track);
    for (const child of Array.from(track.children)) ro.observe(child);
    return () => ro.disconnect();
  }, [measure, children]);

  const scrollTo = React.useCallback(
    (target: number) => {
      const track = trackRef.current;
      if (!track) return;
      const i = Math.max(0, Math.min(target, snaps.length - 1));
      track.scrollTo({ [axis]: snaps[i], behavior: reduce ? "auto" : "smooth" });
      setIndex(i);
    },
    [axis, snaps, reduce],
  );

  // Apply the starting index once snaps are known.
  const started = React.useRef(false);
  React.useEffect(() => {
    if (started.current || snaps.length < 2) return;
    started.current = true;
    const track = trackRef.current;
    const i = Math.min(defaultIndex, snaps.length - 1);
    if (track && i > 0) track.scrollTo({ [axis]: snaps[i], behavior: "auto" });
  }, [snaps, defaultIndex, axis]);

  const canPrev = loop ? count > 1 : index > 0;
  const canNext = loop ? count > 1 : index < count - 1;
  const prev = React.useCallback(
    () => scrollTo(index > 0 ? index - 1 : loop ? count - 1 : 0),
    [scrollTo, index, loop, count],
  );
  const next = React.useCallback(
    () => scrollTo(index < count - 1 ? index + 1 : loop ? 0 : index),
    [scrollTo, index, loop, count],
  );

  // The current index follows the scroll position (wheel, touch, keyboard
  // focus scrolling into view), read in one frame per burst of events.
  const frame = React.useRef(0);
  const onTrackScroll = React.useCallback(() => {
    cancelAnimationFrame(frame.current);
    frame.current = requestAnimationFrame(() => {
      const track = trackRef.current;
      if (!track) return;
      const pos = orientation === "horizontal" ? track.scrollLeft : track.scrollTop;
      let best = 0;
      snaps.forEach((p, i) => {
        if (Math.abs(p - pos) < Math.abs(snaps[best] - pos)) best = i;
      });
      setIndex(best);
    });
  }, [orientation, snaps]);
  React.useEffect(() => () => cancelAnimationFrame(frame.current), []);

  const onIndexChangeRef = React.useRef(onIndexChange);
  React.useEffect(() => {
    onIndexChangeRef.current = onIndexChange;
  });
  const firstIndex = React.useRef(true);
  React.useEffect(() => {
    if (firstIndex.current) {
      firstIndex.current = false;
      return;
    }
    onIndexChangeRef.current?.(index);
  }, [index]);

  // Autoplay: one frame loop accumulates time only while playing and not
  // paused, writes the share to `--carousel-progress` on the active dot's
  // fill (no re-render), and advances when it reaches 1. Pausing on hover or
  // focus resumes from the same point.
  // Autoplay always rewinds at the end, even without `loop`.
  const advance = React.useCallback(
    () => scrollTo(index < count - 1 ? index + 1 : 0),
    [scrollTo, index, count],
  );
  const nextRef = React.useRef(advance);
  React.useEffect(() => {
    nextRef.current = advance;
  });
  const elapsed = React.useRef(0);
  React.useEffect(() => {
    elapsed.current = 0;
    progressRef.current?.style.setProperty("--carousel-progress", "0");
  }, [index]);
  React.useEffect(() => {
    if (!auto || !playing || paused || count < 2) return;
    let last = performance.now();
    let raf = requestAnimationFrame(function tick(now) {
      elapsed.current += now - last;
      last = now;
      const share = Math.min(elapsed.current / auto, 1);
      progressRef.current?.style.setProperty("--carousel-progress", String(share));
      if (share >= 1) {
        elapsed.current = 0;
        nextRef.current();
      }
      raf = requestAnimationFrame(tick);
    });
    return () => cancelAnimationFrame(raf);
  }, [auto, playing, paused, count]);

  const api = React.useMemo<CarouselApi>(
    () => ({ index, count, canPrev, canNext, prev, next, scrollTo }),
    [index, count, canPrev, canNext, prev, next, scrollTo],
  );
  React.useEffect(() => {
    setApi?.(api);
  }, [api, setApi]);

  const value = React.useMemo<CarouselContextValue>(
    () => ({
      ...api,
      orientation,
      loop,
      trackRef,
      progressRef,
      autoplay: auto,
      playing,
      paused,
      setPlaying,
      onTrackScroll,
      dragging,
      setDragging,
      reduce,
      snaps,
      slideCount,
    }),
    [
      api,
      orientation,
      loop,
      auto,
      playing,
      paused,
      onTrackScroll,
      dragging,
      reduce,
      snaps,
      slideCount,
    ],
  );

  const prevKey = orientation === "horizontal" ? "ArrowLeft" : "ArrowUp";
  const nextKey = orientation === "horizontal" ? "ArrowRight" : "ArrowDown";

  return (
    <CarouselContext.Provider value={value}>
      <section
        data-slot="carousel"
        data-orientation={orientation}
        aria-roledescription="carousel"
        aria-label={label}
        className={cn("@container relative", className)}
        style={
          { ...perViewVars(slidesPerView), "--carousel-gap": gap, ...style } as React.CSSProperties
        }
        onKeyDown={(event) => {
          onKeyDown?.(event);
          if (event.defaultPrevented) return;
          // Leave arrow keys alone inside fields and sliders within a slide.
          const target = event.target as HTMLElement;
          if (target.closest("input, textarea, select, [role=slider], [contenteditable=true]"))
            return;
          if (event.key === prevKey) {
            event.preventDefault();
            prev();
          } else if (event.key === nextKey) {
            event.preventDefault();
            next();
          } else if (event.key === "Home" && target.closest("[data-slot=carousel-dots]")) {
            event.preventDefault();
            scrollTo(0);
          } else if (event.key === "End" && target.closest("[data-slot=carousel-dots]")) {
            event.preventDefault();
            scrollTo(count - 1);
          }
        }}
        onPointerEnter={(event) => {
          onPointerEnter?.(event);
          if (event.pointerType === "mouse") setHovered(true);
        }}
        onPointerLeave={(event) => {
          onPointerLeave?.(event);
          setHovered(false);
        }}
        onFocus={(event) => {
          onFocus?.(event);
          setFocused(true);
        }}
        onBlur={(event) => {
          onBlur?.(event);
          if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setFocused(false);
        }}
        {...props}
      >
        {children}
        {/* Announce slide changes, but not while autoplay is turning them. */}
        <span className="sr-only" aria-live={auto && playing ? "off" : "polite"} aria-atomic>
          {count > 1 ? `Slide ${index + 1} of ${count}` : ""}
        </span>
      </section>
    </CarouselContext.Provider>
  );
}

export function CarouselContent({ className, children, ...props }: React.ComponentProps<"div">) {
  const { trackRef, orientation, onTrackScroll, setDragging, dragging, reduce, snaps } =
    useCarousel();
  const horizontal = orientation === "horizontal";
  const drag = React.useRef<{
    id: number;
    start: number;
    scroll: number;
    moved: boolean;
    t: number;
    v: number;
  } | null>(null);
  const suppressClick = React.useRef(false);

  return (
    <div
      ref={trackRef}
      data-slot="carousel-content"
      // The track scrolls; it takes focus so keyboard users can scroll it too.
      tabIndex={0}
      role="group"
      aria-label="Slides"
      data-dragging={dragging || undefined}
      onScroll={onTrackScroll}
      onPointerDown={(event) => {
        // Touch and pen scroll natively; only the mouse needs drag-to-scroll.
        if (event.pointerType !== "mouse" || event.button !== 0) return;
        const track = event.currentTarget;
        drag.current = {
          id: event.pointerId,
          start: horizontal ? event.clientX : event.clientY,
          scroll: horizontal ? track.scrollLeft : track.scrollTop,
          moved: false,
          t: event.timeStamp,
          v: 0,
        };
      }}
      onPointerMove={(event) => {
        const d = drag.current;
        if (!d || d.id !== event.pointerId) return;
        const track = event.currentTarget;
        const pos = horizontal ? event.clientX : event.clientY;
        const delta = pos - d.start;
        if (!d.moved) {
          if (Math.abs(delta) < DRAG_SLOP) return;
          d.moved = true;
          track.setPointerCapture(event.pointerId);
          setDragging(true);
        }
        const dt = Math.max(event.timeStamp - d.t, 1);
        const before = horizontal ? track.scrollLeft : track.scrollTop;
        const after = d.scroll - delta;
        // Clamp the throw velocity so a flick carries about one slide, not to the end.
        d.v = Math.max(-1.5, Math.min(1.5, (after - before) / dt));
        d.t = event.timeStamp;
        if (horizontal) track.scrollLeft = after;
        else track.scrollTop = after;
      }}
      onPointerUp={(event) => {
        const d = drag.current;
        drag.current = null;
        if (!d?.moved) return;
        suppressClick.current = true;
        const track = event.currentTarget;
        if (track.hasPointerCapture(event.pointerId)) track.releasePointerCapture(event.pointerId);
        // Settle on the snap nearest to where a short throw would carry it.
        const pos = (horizontal ? track.scrollLeft : track.scrollTop) + d.v * 120;
        let best = 0;
        snaps.forEach((p, i) => {
          if (Math.abs(p - pos) < Math.abs(snaps[best] - pos)) best = i;
        });
        track.scrollTo({
          [horizontal ? "left" : "top"]: snaps[best],
          behavior: reduce ? "auto" : "smooth",
        });
        setDragging(false);
      }}
      onPointerCancel={() => {
        drag.current = null;
        setDragging(false);
      }}
      onClickCapture={(event) => {
        if (!suppressClick.current) return;
        suppressClick.current = false;
        event.preventDefault();
        event.stopPropagation();
      }}
      onDragStart={(event) => event.preventDefault()}
      className={cn(
        "relative flex [scrollbar-width:none] gap-(--carousel-gap) overscroll-contain [&::-webkit-scrollbar]:hidden",
        "data-dragging:cursor-grabbing data-dragging:scroll-auto data-dragging:select-none motion-safe:scroll-smooth",
        horizontal
          ? "snap-x snap-mandatory overflow-x-auto overflow-y-hidden data-dragging:snap-none"
          : "snap-y snap-mandatory flex-col overflow-x-hidden overflow-y-auto data-dragging:snap-none",
        // Room for the slides' rings and shadows inside the clipping track.
        "-m-2 scroll-p-2 p-2",
        "rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring",
        className,
      )}
      {...props}
    >
      {children}
    </div>
  );
}

export function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
  const { slideCount } = useCarousel();
  const ref = React.useRef<HTMLDivElement>(null);
  // "n of total" comes from the slide's place in the track, re-read whenever
  // the carousel re-measures its slides.
  const [position, setPosition] = React.useState<{ n: number; total: number } | null>(null);
  React.useLayoutEffect(() => {
    const el = ref.current;
    const parent = el?.parentElement;
    if (!el || !parent) return;
    const total = parent.children.length;
    const n = Array.prototype.indexOf.call(parent.children, el) + 1;
    setPosition((p) => (p?.n === n && p.total === total ? p : { n, total }));
  }, [slideCount]);
  return (
    <div
      ref={ref}
      data-slot="carousel-item"
      role="group"
      aria-roledescription="slide"
      aria-label={position ? `${position.n} of ${position.total}` : undefined}
      className={cn(
        "min-w-0 shrink-0 grow-0 snap-start",
        // Width (or height) from slides per view and gap, stepping up with the container.
        "[--pv:var(--pv-base)] @sm:[--pv:var(--pv-sm)] @md:[--pv:var(--pv-md)] @lg:[--pv:var(--pv-lg)] @xl:[--pv:var(--pv-xl)]",
        "basis-[calc((100%-(var(--pv)-1)*var(--carousel-gap))/var(--pv))]",
        className,
      )}
      {...props}
    />
  );
}

function Chevron({ dir }: { dir: "prev" | "next" }) {
  return (
    <svg
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth={1.5}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
      className="size-4"
    >
      <path d={dir === "prev" ? "M9.75 3.75 5.5 8l4.25 4.25" : "M6.25 3.75 10.5 8l-4.25 4.25"} />
    </svg>
  );
}

const navButton = cn(
  "inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full bg-card text-foreground",
  "shadow-raised-sm ring-1 inset-shadow-highlight ring-hairline",
  "transition-[background-color,box-shadow,transform,opacity] duration-(--motion-fast) ease-enter",
  "hover:shadow-raised-md active:translate-y-px active:scale-[0.96] active:shadow-raised-xs active:inset-shadow-none",
  "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none",
  "disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none motion-reduce:active:translate-y-0 motion-reduce:active:scale-100",
);

function NavButton({
  side: dir,
  className,
  children,
  onClick,
  ...props
}: React.ComponentProps<"button"> & { side: "prev" | "next" }) {
  const { orientation, canPrev, canNext, prev, next } = useCarousel();
  const can = dir === "prev" ? canPrev : canNext;
  return (
    <button
      type="button"
      data-slot={dir === "prev" ? "carousel-previous" : "carousel-next"}
      aria-label={dir === "prev" ? "Previous slide" : "Next slide"}
      disabled={!can}
      onClick={(event) => {
        onClick?.(event);
        if (!event.defaultPrevented) (dir === "prev" ? prev : next)();
      }}
      className={cn(navButton, orientation === "vertical" && "rotate-90", className)}
      {...props}
    >
      {children ?? <Chevron dir={dir} />}
    </button>
  );
}

export function CarouselPrevious(props: React.ComponentProps<"button">) {
  return <NavButton side="prev" {...props} />;
}

export function CarouselNext(props: React.ComponentProps<"button">) {
  return <NavButton side="next" {...props} />;
}

/** Pause / play control. Rendered only when the carousel autoplays. */
export function CarouselPlayToggle({ className, ...props }: React.ComponentProps<"button">) {
  const { autoplay, playing, setPlaying } = useCarousel();
  if (!autoplay) return null;
  return (
    <button
      type="button"
      data-slot="carousel-play-toggle"
      aria-label={playing ? "Stop slide rotation" : "Start slide rotation"}
      onClick={() => setPlaying(!playing)}
      className={cn(navButton, "size-7", className)}
      {...props}
    >
      <svg viewBox="0 0 16 16" fill="currentColor" aria-hidden className="size-3">
        {playing ? (
          <path d="M4.5 3h2v10h-2zM9.5 3h2v10h-2z" />
        ) : (
          <path d="M5 3.2v9.6a.5.5 0 0 0 .77.42l7.2-4.8a.5.5 0 0 0 0-.84l-7.2-4.8A.5.5 0 0 0 5 3.2" />
        )}
      </svg>
    </button>
  );
}

export function CarouselDots({ className, ...props }: React.ComponentProps<"div">) {
  const { count, index, scrollTo, autoplay, playing, progressRef } = useCarousel();
  if (count < 2) return null;
  return (
    <div
      data-slot="carousel-dots"
      role="group"
      aria-label="Choose slide"
      className={cn("flex items-center justify-center gap-1.5", className)}
      {...props}
    >
      {Array.from({ length: count }, (_, i) => {
        const active = i === index;
        return (
          <button
            key={i}
            type="button"
            aria-label={`Go to slide ${i + 1}`}
            aria-current={active || undefined}
            tabIndex={active ? 0 : -1}
            onClick={() => scrollTo(i)}
            onKeyDown={(event) => {
              // Roving focus: arrows move the slide, focus follows the active dot.
              if (
                ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(
                  event.key,
                )
              ) {
                const group = event.currentTarget.parentElement;
                requestAnimationFrame(() => {
                  const dot = group?.querySelector<HTMLButtonElement>("[aria-current=true]");
                  dot?.focus();
                });
              }
            }}
            className={cn(
              "group/dot relative grid h-6 cursor-pointer place-items-center rounded-full",
              "focus-visible:outline-none",
              "transition-[width] duration-(--motion-base) ease-move motion-reduce:transition-none",
              active ? "w-7" : "w-3",
            )}
          >
            <span
              aria-hidden
              className={cn(
                "relative h-1.5 w-full overflow-hidden rounded-full",
                "transition-colors duration-(--motion-fast)",
                "group-focus-visible/dot:ring-2 group-focus-visible/dot:ring-ring group-focus-visible/dot:ring-offset-2 group-focus-visible/dot:ring-offset-background",
                active
                  ? "bg-foreground/15 shadow-[inset_0_1px_1px_var(--hairline)]"
                  : "bg-foreground/20 group-hover/dot:bg-foreground/40",
              )}
            >
              {active && (
                <span
                  ref={autoplay ? progressRef : undefined}
                  className={cn(
                    "absolute inset-0 origin-left rounded-full",
                    autoplay ? "bg-accent" : "bg-foreground",
                  )}
                  style={
                    autoplay ? { transform: `scaleX(var(--carousel-progress, 0))` } : undefined
                  }
                  data-playing={(autoplay && playing) || undefined}
                />
              )}
            </span>
          </button>
        );
      })}
    </div>
  );
}

/** "3 / 8" counter for the current snap point. */
export function CarouselCounter({ className, ...props }: React.ComponentProps<"p">) {
  const { index, count } = useCarousel();
  return (
    <p
      data-slot="carousel-counter"
      aria-hidden
      className={cn("font-mono text-xs text-muted-foreground tabular-nums", className)}
      {...props}
    >
      <span className="text-foreground">{String(index + 1).padStart(2, "0")}</span> /{" "}
      {String(count).padStart(2, "0")}
    </p>
  );
}
Pebble

Small details.
Better interfaces.

React components to explore, make your own, and build on.

Library

  • Components
  • Installation
  • Pricing

Resources

  • For agents
  • About
  • Support

Legal

  • License
  • Terms
  • Privacy
  • Final sale

Built by Pebble

A product of Praxys Solutions LLC ↗

Pebble Pro is live

$49 one time, lifetime updates ↗