# Pour Toggle

> Tip the bowl: a splash falls, and the new theme ripples out from where it lands.

- Category: Buttons
- Tier: Free (MIT)
- Page: https://bowls.dev/components/pour-toggle
- Requires: React 18+, Tailwind CSS 4

## Install

Copy the source below into `components/bowls/pour-toggle.tsx`.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `storageKey` | `string` | `"theme"` | localStorage key that remembers the choice. |
| `attribute` | `string` | `"data-theme"` | Attribute set on <html> to light or dark. |
| `duration` | `number` | `1500` | Length of the splash and ripple, in ms. |
| `size` | `number` | `44` | Button size, in px. |
| `onChange` | `(theme) => void` | — | Called after each switch. |

## Usage

```tsx
"use client";

import { PourToggle } from "@/components/bowls/pour-toggle";

export default function Demo() {
  return (
    <div className="flex h-full w-full flex-col items-center justify-center gap-4">
      <PourToggle size={72} />
      <span className="font-mono text-xs text-[#666] dark:text-[#999]">click to pour · alt-click for system</span>
    </div>
  );
}
```

## Source

`components/bowls/pour-toggle.tsx`

```tsx
"use client";

import { useEffect, useId, useRef, useState } from "react";
import { flushSync } from "react-dom";

type Theme = "light" | "dark";

export type PourToggleProps = {
  /** localStorage key used to remember the choice. */
  storageKey?: string;
  /** Attribute set on <html>: data-theme="light" | "dark". */
  attribute?: string;
  /** Length of the splash and ripple, in ms (the bowl tips for 320 ms first). */
  duration?: number;
  /** Button size, in px. */
  size?: number;
  onChange?: (theme: Theme) => void;
  className?: string;
};

const DARK_QUERY = "(prefers-color-scheme: dark)";
const TIP_MS = 320;
const systemTheme = (): Theme => (window.matchMedia(DARK_QUERY).matches ? "dark" : "light");

function readTheme(attribute: string): Theme {
  const forced = document.documentElement.getAttribute(attribute);
  return forced === "dark" || forced === "light" ? forced : systemTheme();
}

const easeIn = (t: number) => t * t * t;
const easeInOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);

/**
 * Clip-path keyframes for the pour. The bowl empties a tiny splash — one
 * teardrop and two droplets — that falls to the bottom of the page. Where it
 * lands, the new theme spreads out as a ripple with a wobbly water edge until
 * it covers everything. Every frame has the same number of points (shapes are
 * joined by zero-width seams), so the browser can interpolate between them.
 */
function pourKeyframes(lipX: number, lipY: number, w: number, h: number, steps = 90) {
  const RING = 56; // points around the ripple
  const DROP = 14; // points around each drop
  const LEAVE = 0; // the bowl has already tipped; water leaves the lip at once
  const LAND = 0.3; // first drop hits the bottom
  const DROPS = [
    { size: 9, lag: 0 },
    { size: 5, lag: 0.035 },
    { size: 3.5, lag: 0.065 },
  ];
  const frames: string[] = [];

  const impactY = h + 4;
  const pathX = (y: number) => lipX + 16 * (1 - Math.exp(-Math.max(0, y - lipY) / 50));
  const impactX = pathX(impactY);
  const reach = Math.max(Math.hypot(impactX, impactY), Math.hypot(w - impactX, impactY)) + 60;
  const p = (x: number, y: number) => `${x.toFixed(1)}px ${y.toFixed(1)}px`;

  for (let i = 0; i <= steps; i++) {
    const t = i / steps;

    // The ripple: grows from the impact point with a wobbling edge.
    const spread = t <= LAND ? 0 : easeInOut((t - LAND) / (1 - LAND));
    const radius = spread * reach;
    const wobble = radius > 0 ? Math.min(12, radius * 0.08) : 0;
    const ring = Array.from({ length: RING }, (_, k) => {
      const a = (k / RING) * Math.PI * 2;
      const r = radius + wobble * Math.sin(a * 9 + t * 30) + wobble * 0.5 * Math.sin(a * 5 - t * 22);
      return p(impactX + Math.cos(a) * r, impactY + Math.sin(a) * r);
    });

    const pts = [...ring, ring[0]];

    // The drops: each falls with gravity, stretching as it speeds up, and is
    // swallowed when it reaches the bottom.
    for (const d of DROPS) {
      const start = LEAVE + d.lag;
      const end = LAND + d.lag;
      const fall = t <= start ? 0 : Math.min((t - start) / (end - start), 1);
      const alive = t > start && fall < 1;
      const swell = alive ? Math.min((t - start) / 0.04, 1) : 0;
      const s = d.size * swell;
      const cy = lipY + s + (impactY - lipY) * easeIn(fall);
      const cx = pathX(cy);
      const stretch = 1.3 + fall * 1.2;
      for (let k = 0; k <= DROP; k++) {
        const phi = (k / DROP) * Math.PI * 2;
        pts.push(p(cx + s * Math.sin(phi) * Math.sin(phi / 2), cy - s * stretch * Math.cos(phi)));
      }
      pts.push(ring[0]);
    }

    frames.push(`polygon(${pts.join(", ")})`);
  }
  return frames;
}

/**
 * A theme toggle shaped like a bowl, full of the colour you'll switch to.
 * Click it and the bowl tips, the water slides out over the rim, a small
 * splash falls to the bottom of the page and the new theme ripples out from
 * where it lands. The bowl comes back upright, refilled with the other colour.
 * Alt/Option-click goes back to the system setting.
 *
 * Needs your CSS to read `[data-theme]` (see the docs). The splash uses View
 * Transitions; other browsers, and reduced motion, switch instantly.
 * No dependencies besides React.
 */
export function PourToggle({
  storageKey = "theme",
  attribute = "data-theme",
  duration = 1500,
  size = 44,
  onChange,
  className,
}: PourToggleProps) {
  const button = useRef<HTMLButtonElement>(null);
  const bowl = useRef<SVGSVGElement>(null);
  const water = useRef<SVGGElement>(null);
  const clipId = useId();
  const [theme, setTheme] = useState<Theme | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    setTheme(readTheme(attribute));
    const media = window.matchMedia(DARK_QUERY);
    const follow = () => !document.documentElement.hasAttribute(attribute) && setTheme(systemTheme());
    media.addEventListener("change", follow);
    return () => media.removeEventListener("change", follow);
  }, [attribute]);

  const apply = (next: Theme | null) => {
    const root = document.documentElement;
    if (next) root.setAttribute(attribute, next);
    else root.removeAttribute(attribute);
    try {
      if (next) localStorage.setItem(storageKey, next);
      else localStorage.removeItem(storageKey);
    } catch {
      /* private mode: the choice just won't persist */
    }
    const resolved = next ?? systemTheme();
    setTheme(resolved);
    onChange?.(resolved);
  };

  const pour = async (e: React.MouseEvent) => {
    if (busy) return;
    const next: Theme | null = e.altKey ? null : theme === "dark" ? "light" : "dark";
    const calm = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (!document.startViewTransition || calm || !button.current || !bowl.current || !water.current) {
      apply(next);
      return;
    }
    setBusy(true);

    // 1. Tip the bowl and let the water slide out over the rim. This happens
    //    on the live page, so the old snapshot keeps the empty, tipped bowl.
    const tip = bowl.current.animate([{ transform: "rotate(0deg)" }, { transform: "rotate(100deg)" }], {
      duration: TIP_MS,
      easing: "cubic-bezier(.3,.1,.3,1)",
      fill: "forwards",
    });
    const empty = water.current.animate([{ transform: "translateY(0px)" }, { transform: "translateY(-16px)" }], {
      duration: TIP_MS * 0.7,
      delay: TIP_MS * 0.3,
      easing: "ease-in",
      fill: "forwards",
    });
    await tip.finished;

    // 2. Splash and ripple. The new state has the bowl upright and refilled.
    const box = button.current.getBoundingClientRect();
    const rim = size * 0.6 * (14 / 32);
    const lipX = box.left + box.width / 2 + rim * Math.cos((100 * Math.PI) / 180);
    const lipY = box.top + box.height / 2 + rim * Math.sin((100 * Math.PI) / 180);

    const transition = document.startViewTransition(() => {
      tip.cancel();
      empty.cancel();
      flushSync(() => apply(next));
    });
    try {
      await transition.ready;
      document.documentElement.animate(
        { clipPath: pourKeyframes(lipX, lipY, window.innerWidth, window.innerHeight) },
        { duration, easing: "linear", pseudoElement: "::view-transition-new(root)" },
      );
      await transition.finished;
    } finally {
      setBusy(false);
    }
  };

  const label = theme ? `Pour ${theme === "dark" ? "light" : "dark"} mode (Alt-click for system)` : "Toggle theme";

  return (
    <button
      ref={button}
      type="button"
      onClick={pour}
      aria-label={label}
      title={label}
      style={{ width: size, height: size }}
      className={`relative flex shrink-0 items-center justify-center rounded-full border border-current/25 text-[#0a0a0a] transition-colors hover:border-current dark:text-[#f5f5f5] ${className ?? ""}`}
    >
      <svg ref={bowl} viewBox="0 0 32 32" aria-hidden="true" width={size * 0.6} height={size * 0.6} style={{ transformOrigin: "50% 50%" }}>
        <defs>
          <clipPath id={clipId}>
            <path d="M3 16a13 13 0 0 0 26 0z" />
          </clipPath>
        </defs>
        {/* the water: always full, in the colour of the theme you'll switch to */}
        <g clipPath={`url(#${clipId})`}>
          <g ref={water}>
            <path fill="currentColor" d="M0 16.5c4-1.5 8 1.5 12 0s8-1.5 12 0 8 1.5 12 0V36H0z" />
          </g>
        </g>
        <path d="M3 16a13 13 0 0 0 26 0z" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinejoin="round" />
        <path d="M2 16h28" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" />
      </svg>
    </button>
  );
}
```
