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 componentsButtons & actions

Theme Toggle

A light, dark and system toggle with a sun-to-moon morph, a segmented three-way variant with a sliding thumb and an optional circular view-transition reveal; it only calls onChange.

Preview

Appearance

light

Revenue

$48.2k

Active

1,284

Churn

2.1%

The toggles only call onChange. Pass reveal for a circular view-transition reveal where the browser supports it.

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/theme-toggle.json

Props

PropTypeDefaultDescription
value"light" | "dark" | "system"—Current theme. Required.
onChange(theme) => void—The only effect: the toggle never changes the document theme itself.
variant"icon" | "segmented""icon"One cycling button, or a three-way radiogroup with a sliding thumb.
includeSystembooleanfalseIcon variant. Add system to the cycle.
revealbooleanfalseCircular view-transition reveal from the control, where supported.
showLabelsbooleanfalseSegmented variant. Text beside the icons.
Build notes
- Glyph (24 px viewBox): core `circle r 4.25 → 8`; a mask with a black disc
  r 6.5 that springs from off-canvas (26, −2) to (16.5, 7.5) to cut the
  crescent; eight ray `line`s from r 7.25 to 9.5 whose end points collapse
  onto their start points in dark, with a 20 ms per-ray stagger on the way
  back to light. The ray group also rotates 45° and fades. Spring stiffness
  300, damping 22.
- System: a monitor with a filled half disc. Icon variant cross-fades sun/moon
  and monitor with a 10 px vertical slide, 200 ms on the enter curve.
- Segmented thumb: `layoutId` per instance, house spring (420/32/0.8).
- Reveal: `document.startViewTransition(() => flushSync(() =>
onChange(next)))`, then on `ready` animates `clip-path: circle()` on
  `::view-transition-new(root)` from 0 to the distance to the farthest
  viewport corner, centred on the control, over 1.6 × `--motion-slow` on
  `--motion-move`. A hoisted `<style precedence>` turns off the default
  cross-fade for the root transition, only when `reveal` is used.
  `flushSync` makes the consumer's state update land inside the transition's
  snapshot.

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

registry/button/theme-toggle/theme-toggle.tsx

"use client";

/* PEBBLE-LICENSE
Built by Pebble. Component: theme-toggle.

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.
END PEBBLE-LICENSE */

import * as React from "react";
import { flushSync } from "react-dom";
import { motion, MotionConfig, useReducedMotion } from "motion/react";

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

export type Theme = "light" | "dark" | "system";

const labels: Record<Theme, string> = { light: "Light", dark: "Dark", system: "System" };

// Our glyph: a sun whose eight rays retract while a shadow disc slides across
// the core, leaving a crescent. One SVG, so light → dark is a morph rather
// than a swap. A mask does the bite so it works on any background.
function SunMoon({ dark }: { dark: boolean }) {
  const id = React.useId();
  const reduce = useReducedMotion();
  const spring = { type: "spring", stiffness: 300, damping: 22, mass: 0.7 } as const;
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      aria-hidden="true"
      className="size-[18px] overflow-visible"
    >
      <mask id={`${id}-bite`}>
        <rect x="-4" y="-4" width="32" height="32" fill="white" />
        <motion.circle
          r="6.5"
          fill="black"
          initial={false}
          animate={dark ? { cx: 16.5, cy: 7.5 } : { cx: 26, cy: -2 }}
          transition={reduce ? { duration: 0 } : spring}
        />
      </mask>
      <motion.circle
        cx="12"
        cy="12"
        fill="currentColor"
        mask={`url(#${id}-bite)`}
        initial={false}
        animate={{ r: dark ? 8 : 4.25 }}
        transition={reduce ? { duration: 0 } : spring}
      />
      <motion.g
        stroke="currentColor"
        strokeWidth="1.75"
        strokeLinecap="round"
        initial={false}
        animate={{ rotate: dark ? 45 : 0, opacity: dark ? 0 : 1 }}
        style={{ originX: "12px", originY: "12px" }}
        transition={reduce ? { duration: 0 } : { duration: 0.32, ease: [0.22, 1, 0.36, 1] }}
      >
        {Array.from({ length: 8 }, (_, i) => {
          const a = (i / 8) * Math.PI * 2;
          const x1 = 12 + Math.cos(a) * 7.25;
          const y1 = 12 + Math.sin(a) * 7.25;
          const x2 = 12 + Math.cos(a) * 9.5;
          const y2 = 12 + Math.sin(a) * 9.5;
          return (
            <motion.line
              key={i}
              x1={x1}
              y1={y1}
              initial={false}
              animate={{
                x2: dark ? x1 : x2,
                y2: dark ? y1 : y2,
              }}
              transition={
                reduce
                  ? { duration: 0 }
                  : { duration: 0.24, ease: [0.22, 1, 0.36, 1], delay: dark ? 0 : 0.12 + i * 0.02 }
              }
            />
          );
        })}
      </motion.g>
    </svg>
  );
}

function Monitor() {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      className="size-[18px]"
    >
      <rect x="3.5" y="4.5" width="17" height="11.5" rx="2" />
      <path d="M9 20h6M12 16v4" />
      {/* Half-lit screen: the system decides. */}
      <path d="M12 7v6.5a3.25 3.25 0 0 0 0-6.5z" fill="currentColor" stroke="none" />
    </svg>
  );
}

/**
 * Runs `apply` inside a view transition that reveals the new theme as a
 * circle growing from `origin`. Falls back to a plain call where view
 * transitions or motion aren't available.
 */
function withReveal(apply: () => void, origin: { x: number; y: number } | null) {
  const doc = typeof document === "undefined" ? null : document;
  const reduce =
    typeof window !== "undefined" &&
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  if (!doc || !origin || reduce || typeof doc.startViewTransition !== "function") {
    apply();
    return;
  }
  const transition = doc.startViewTransition(() => flushSync(apply));
  const radius = Math.hypot(
    Math.max(origin.x, window.innerWidth - origin.x),
    Math.max(origin.y, window.innerHeight - origin.y),
  );
  transition.ready
    .then(() => {
      const styles = getComputedStyle(doc.documentElement);
      doc.documentElement.animate(
        {
          clipPath: [
            `circle(0px at ${origin.x}px ${origin.y}px)`,
            `circle(${radius}px at ${origin.x}px ${origin.y}px)`,
          ],
        },
        {
          duration: (parseFloat(styles.getPropertyValue("--motion-slow")) || 320) * 1.6,
          easing: styles.getPropertyValue("--motion-move") || "ease-in-out",
          pseudoElement: "::view-transition-new(root)",
        },
      );
    })
    .catch(() => {});
}

// With `reveal`, the default cross-fade is switched off so only the circle
// shows. Scoped to the root transition; React 19 hoists and dedupes it.
const REVEAL_CSS =
  "::view-transition-old(root),::view-transition-new(root){animation:none;mix-blend-mode:normal}";

function RevealStyle() {
  return (
    <style href="theme-toggle-reveal" precedence="default">
      {REVEAL_CSS}
    </style>
  );
}

export type ThemeToggleProps = {
  value: Theme;
  /** The only effect: the toggle never touches the document's theme itself. */
  onChange: (theme: Theme) => void;
  /** `icon` cycles on click; `segmented` shows all three options. */
  variant?: "icon" | "segmented";
  /** Icon variant: include "system" in the cycle. */
  includeSystem?: boolean;
  /** Reveal the new theme with a circular view transition from the control. */
  reveal?: boolean;
  /** Segmented: show text labels beside the icons. */
  showLabels?: boolean;
  disabled?: boolean;
  className?: string;
};

export function ThemeToggle({
  value,
  onChange,
  variant = "icon",
  includeSystem = false,
  reveal = false,
  showLabels = false,
  disabled,
  className,
}: ThemeToggleProps) {
  function change(next: Theme, from: Element | null) {
    if (next === value) return;
    if (!reveal) return onChange(next);
    const rect = from?.getBoundingClientRect();
    withReveal(
      () => onChange(next),
      rect ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 } : null,
    );
  }

  if (variant === "segmented") {
    return (
      <MotionConfig reducedMotion="user">
        {reveal && <RevealStyle />}
        <ThemeSegmented
          value={value}
          onSelect={change}
          showLabels={showLabels}
          disabled={disabled}
          className={className}
        />
      </MotionConfig>
    );
  }

  const cycle: Theme[] = includeSystem ? ["light", "dark", "system"] : ["light", "dark"];
  const current = cycle.includes(value) ? value : "light";
  const next = cycle[(cycle.indexOf(current) + 1) % cycle.length];
  return (
    <MotionConfig reducedMotion="user">
      {reveal && <RevealStyle />}
      <button
        type="button"
        data-slot="theme-toggle"
        data-theme-value={value}
        disabled={disabled}
        aria-label={`Theme: ${labels[value]}. Switch to ${labels[next].toLowerCase()}`}
        onClick={(event) => change(next, event.currentTarget)}
        className={cn(
          "relative inline-flex size-9 shrink-0 cursor-pointer items-center justify-center overflow-hidden rounded-md bg-card text-foreground shadow-raised-xs ring-1 inset-shadow-highlight ring-hairline",
          "transition-[background-color,box-shadow,transform] duration-(--motion-fast) ease-enter hover:bg-muted/60 active:scale-[0.94] active:shadow-none active:inset-shadow-none motion-reduce:transition-none motion-reduce:active:scale-100",
          "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-50",
          className,
        )}
      >
        <motion.span
          className="absolute inset-0 flex items-center justify-center"
          initial={false}
          animate={{ opacity: value === "system" ? 0 : 1, y: value === "system" ? -10 : 0 }}
          transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
        >
          <SunMoon dark={value === "dark"} />
        </motion.span>
        <motion.span
          className="absolute inset-0 flex items-center justify-center"
          initial={false}
          animate={{ opacity: value === "system" ? 1 : 0, y: value === "system" ? 0 : 10 }}
          transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
        >
          <Monitor />
        </motion.span>
      </button>
    </MotionConfig>
  );
}

/* ------------------------------------------------------------- Segmented */

const order: Theme[] = ["light", "dark", "system"];

function ThemeSegmented({
  value,
  onSelect,
  showLabels,
  disabled,
  className,
}: {
  value: Theme;
  onSelect: (theme: Theme, from: Element | null) => void;
  showLabels: boolean;
  disabled?: boolean;
  className?: string;
}) {
  const id = React.useId();
  const refs = React.useRef<Record<string, HTMLButtonElement | null>>({});
  return (
    <div
      role="radiogroup"
      aria-label="Theme"
      data-slot="theme-toggle"
      data-variant="segmented"
      aria-disabled={disabled || undefined}
      onKeyDown={(event) => {
        const step =
          event.key === "ArrowRight" || event.key === "ArrowDown"
            ? 1
            : event.key === "ArrowLeft" || event.key === "ArrowUp"
              ? -1
              : 0;
        if (!step || disabled) return;
        event.preventDefault();
        const next = order[(order.indexOf(value) + step + order.length) % order.length];
        refs.current[next]?.focus();
        onSelect(next, refs.current[next]);
      }}
      className={cn(
        "inline-flex items-center gap-0.5 rounded-full bg-muted p-0.5 ring-1 inset-shadow-[0_1px_2px_var(--hairline)] ring-hairline",
        disabled && "pointer-events-none opacity-50",
        className,
      )}
    >
      {order.map((theme) => {
        const checked = theme === value;
        return (
          <button
            key={theme}
            ref={(node) => {
              refs.current[theme] = node;
            }}
            type="button"
            role="radio"
            aria-checked={checked}
            aria-label={showLabels ? undefined : labels[theme]}
            tabIndex={checked ? 0 : -1}
            disabled={disabled}
            onClick={(event) => onSelect(theme, event.currentTarget)}
            className={cn(
              "relative isolate inline-flex h-7 cursor-pointer items-center justify-center gap-1.5 rounded-full text-[13px] font-medium text-muted-foreground transition-colors duration-(--motion-fast) hover:text-foreground motion-reduce:transition-none",
              showLabels ? "px-2.5" : "w-8",
              "aria-checked:text-foreground",
              "focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
              "[&_svg]:size-4",
            )}
          >
            {checked && (
              // The thumb is one raised pebble that slides between options.
              <motion.span
                layoutId={`${id}-thumb`}
                aria-hidden="true"
                transition={{ type: "spring", stiffness: 420, damping: 32, mass: 0.8 }}
                className="absolute inset-0 -z-10 rounded-full bg-card shadow-raised-xs ring-1 inset-shadow-highlight ring-hairline"
              />
            )}
            {theme === "system" ? <Monitor /> : <SunMoon dark={theme === "dark"} />}
            {showLabels && <span>{labels[theme]}</span>}
          </button>
        );
      })}
    </div>
  );
}
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 ↗