Particle Toggle

A switch with no solid shapes in it. The track and the thumb are both grids of tiny square particles, a couple of pixels apart, rendered with three.js. Toggle it and the thumb comes apart: the particles on its leading edge leave first, the swarm stretches and scatters a little in flight, then settles back into a circle on the other side. The track lights up behind it as it goes. Use Full screen to see it large.

Particles that look like pixels

Each particle is a gl_PointSize square, snapped to the device pixel grid in the vertex shader, so it renders as a crisp block rather than a soft dot. The lattice spacing is rounded to whole device pixels too, and each particle is about three quarters of the spacing, which leaves a one-pixel gap on retina screens. Because positions snap, motion steps from pixel to pixel, which is what makes the swarm read as pixels moving and not as blurred dots.

The thumb is a swarm

Every thumb particle has its own spring toward its place in the circle, with a slightly different stiffness. On toggle, each one waits a few milliseconds depending on how far forward it sits, and gets a small random vertical kick. Those three things are enough to turn a circle sliding across into something that pours across and reassembles. The springs are a little underdamped, so the circle lands with a small settle.

The track follows the thumb

The track doesn't switch colour on its own timer. Each frame it reads where the swarm's centre is and lights every particle the thumb has passed, with a soft edge, so the fill moves exactly with the thumb, including when the thumb overshoots. A ring of particles around the thumb is hidden, which keeps the thumb readable when the track is lit in the same colour.

Small details

  • Pointer. Particles within about 14px of the cursor lean away from it and spring back when it leaves. It's mouse-only and decorative.
  • Press. Holding the switch stretches the thumb sideways, the particle version of a button pressing in.
  • Idle. The animation loop runs only while something is moving, so a resting switch costs nothing.
  • Theme. Colours come from CSS custom properties. They are read through the browser's colour parser, so oklch and color-mix work, and re-read when the theme changes.
  • Reduced motion. The thumb jumps to its new side and the pointer effect is off.

Accessibility

It's a real <button role="switch"> with aria-checked, so Space and Enter toggle it and a <label htmlFor> works. The canvas is aria-hidden. If WebGL isn't available, a plain CSS switch is drawn in its place.

Every toggle owns a WebGL context, and browsers cap those at around 16 per page, so this suits a few hero switches, not a long settings list.

Usage

Size it with a class. Colours are --particle-on (the accent, foreground by default), --particle-off, and --particle-thumb. pitch sets the particle spacing in CSS pixels.

<ParticleToggle
  aria-label="Dark mode"
  className="h-10 w-18 [--particle-on:var(--color-emerald-500)]"
  defaultChecked
  onCheckedChange={(on) => console.log(on)}
/>
components/blocks/controls/particle-toggle.tsx
"use client";

import { useReducedMotion } from "motion/react";
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ComponentPropsWithoutRef } from "react";
import {
  BufferAttribute,
  BufferGeometry,
  NormalBlending,
  OrthographicCamera,
  Points,
  Scene,
  ShaderMaterial,
  WebGLRenderer,
} from "three";

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

export type ParticleToggleProps = Omit<
  ComponentPropsWithoutRef<"button">,
  "onChange" | "children" | "value"
> & {
  checked?: boolean;
  defaultChecked?: boolean;
  onCheckedChange?: (checked: boolean) => void;
  /** Distance between particles in CSS pixels. Each particle is about ¾ of this. */
  pitch?: number;
};

/**
 * A toggle switch drawn entirely as a grid of pixel-sized particles. The
 * thumb is a swarm that flies to the other side on toggle, the track fills
 * behind it, and nearby particles lean away from the pointer.
 *
 * Size it with `className` (default `h-10 w-18`). Colours come from CSS
 * custom properties, so they follow the theme:
 * `--particle-thumb`, `--particle-on` (the accent, defaults to foreground)
 * and `--particle-off`.
 */
export function ParticleToggle({
  checked: checkedProp,
  defaultChecked = false,
  onCheckedChange,
  pitch = 2,
  className,
  disabled,
  onClick,
  onPointerMove,
  onPointerLeave,
  onPointerDown,
  onPointerUp,
  onPointerCancel,
  ...props
}: ParticleToggleProps) {
  const [inner, setInner] = useState(defaultChecked);
  const checked = checkedProp ?? inner;
  const reduced = useReducedMotion() ?? false;

  const rootRef = useRef<HTMLButtonElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const probeRef = useRef<HTMLSpanElement>(null);
  const fieldRef = useRef<Field | null>(null);

  // Latest values for the field without rebuilding it.
  const checkedRef = useRef(checked);
  const reducedRef = useRef(reduced);
  useLayoutEffect(() => {
    checkedRef.current = checked;
    reducedRef.current = reduced;
  });

  useEffect(() => {
    const root = rootRef.current;
    const canvas = canvasRef.current;
    const probe = probeRef.current;
    if (!root || !canvas || !probe) return;

    let field: Field;
    try {
      field = createField(canvas, probe, pitch, checkedRef.current, () => reducedRef.current);
    } catch {
      // No WebGL: show the CSS fallback instead.
      root.dataset.fallback = "";
      return;
    }
    fieldRef.current = field;

    const resize = () => field.resize(root.clientWidth, root.clientHeight);
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(root);

    // Re-read the colours when the theme flips.
    const mo = new MutationObserver(() => field.readColors());
    mo.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "data-theme"] });
    const mq = window.matchMedia("(prefers-color-scheme: dark)");
    const onScheme = () => field.readColors();
    mq.addEventListener("change", onScheme);

    return () => {
      ro.disconnect();
      mo.disconnect();
      mq.removeEventListener("change", onScheme);
      field.dispose();
      fieldRef.current = null;
    };
  }, [pitch]);

  useEffect(() => {
    fieldRef.current?.setChecked(checked);
  }, [checked]);

  useEffect(() => {
    fieldRef.current?.readColors();
  }, [className, disabled]);

  const local = useCallback((e: React.PointerEvent) => {
    const r = e.currentTarget.getBoundingClientRect();
    return [e.clientX - r.left, e.clientY - r.top] as const;
  }, []);

  return (
    <button
      ref={rootRef}
      type="button"
      role="switch"
      aria-checked={checked}
      disabled={disabled}
      data-slot="particle-toggle"
      data-state={checked ? "on" : "off"}
      className={cn(
        "group/particle relative inline-block h-10 w-18 shrink-0 touch-manipulation rounded-full outline-none select-none",
        "[--particle-off:color-mix(in_oklab,var(--muted-foreground)_32%,transparent)] [--particle-on:var(--foreground)] [--particle-thumb:var(--foreground)]",
        "focus-visible:ring-[1.5px] focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",
        "disabled:pointer-events-none disabled:opacity-50",
        className
      )}
      onClick={(e) => {
        onClick?.(e);
        if (e.defaultPrevented) return;
        const next = !checked;
        if (checkedProp === undefined) setInner(next);
        onCheckedChange?.(next);
      }}
      onPointerMove={(e) => {
        onPointerMove?.(e);
        if (e.pointerType === "mouse") fieldRef.current?.setPointer(...local(e));
      }}
      onPointerLeave={(e) => {
        onPointerLeave?.(e);
        fieldRef.current?.setPointer(null);
        fieldRef.current?.setPressed(false);
      }}
      onPointerDown={(e) => {
        onPointerDown?.(e);
        fieldRef.current?.setPressed(true);
      }}
      onPointerUp={(e) => {
        onPointerUp?.(e);
        fieldRef.current?.setPressed(false);
      }}
      onPointerCancel={(e) => {
        onPointerCancel?.(e);
        fieldRef.current?.setPressed(false);
      }}
      {...props}
    >
      <canvas ref={canvasRef} aria-hidden className="pointer-events-none absolute inset-0 size-full" />
      <span ref={probeRef} hidden />
      <Fallback checked={checked} />
    </button>
  );
}

/** Plain CSS switch for browsers without WebGL. */
function Fallback({ checked }: { checked: boolean }) {
  return (
    <span
      aria-hidden
      className={cn(
        "absolute inset-0 hidden rounded-full transition-colors group-data-fallback/particle:block",
        checked ? "bg-(--particle-on)" : "bg-(--particle-off)"
      )}
    >
      <span
        className={cn(
          "absolute top-1 bottom-1 aspect-square rounded-full bg-(--particle-thumb) transition-[left] ease-snappy",
          checked ? "left-[calc(100%-0.25rem)] -translate-x-full" : "left-1",
          checked && "ring-2 ring-background"
        )}
      />
    </span>
  );
}

/* -------------------------------------------------------------------------- */
/*                                  The field                                 */
/* -------------------------------------------------------------------------- */

type Field = {
  resize: (w: number, h: number) => void;
  setChecked: (checked: boolean) => void;
  setPointer: (x: number | null, y?: number) => void;
  setPressed: (pressed: boolean) => void;
  readColors: () => void;
  dispose: () => void;
};

type RGBA = [number, number, number, number];

const VERTEX = /* glsl */ `
  attribute vec4 aColor;
  uniform float uDpr;
  uniform float uSize;
  varying vec4 vColor;
  void main() {
    // Snap to the device pixel grid so every particle is a crisp square.
    vec2 p = floor(position.xy * uDpr + 0.5) + mod(uSize, 2.0) * 0.5;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(p / uDpr, 0.0, 1.0);
    gl_PointSize = uSize;
    vColor = aColor;
  }
`;

const FRAGMENT = /* glsl */ `
  varying vec4 vColor;
  void main() {
    if (vColor.a < 0.004) discard;
    gl_FragColor = vColor;
  }
`;

/** Pointer influence radius and push, in CSS px. */
const REPEL_RADIUS = 14;
const REPEL_PUSH = 2.5;
/** How much the thumb stretches while pressed. */
const PRESS_STRETCH = 1.18;

function createField(
  canvas: HTMLCanvasElement,
  probe: HTMLSpanElement,
  pitchCss: number,
  initialChecked: boolean,
  isReduced: () => boolean
): Field {
  const renderer = new WebGLRenderer({ canvas, alpha: true, antialias: false, premultipliedAlpha: true });
  renderer.setClearColor(0x000000, 0);

  const scene = new Scene();
  const camera = new OrthographicCamera(0, 1, 0, 1, -1, 1);
  const material = new ShaderMaterial({
    vertexShader: VERTEX,
    fragmentShader: FRAGMENT,
    uniforms: { uDpr: { value: 1 }, uSize: { value: 1 } },
    transparent: true,
    depthTest: false,
    depthWrite: false,
    blending: NormalBlending,
  });
  const geometry = new BufferGeometry();
  const points = new Points(geometry, material);
  points.frustumCulled = false;
  scene.add(points);

  // Colours, read from CSS.
  const colorCanvas = document.createElement("canvas");
  colorCanvas.width = colorCanvas.height = 1;
  const colorCtx = colorCanvas.getContext("2d", { willReadFrequently: true })!;
  let cOff: RGBA = [0.5, 0.5, 0.5, 0.3];
  let cOn: RGBA = [0, 0, 0, 1];
  let cThumb: RGBA = [0, 0, 0, 1];

  // Layout.
  let W = 0;
  let H = 0;
  let pitch = pitchCss;
  let thumbR = 0;
  let offX = 0;
  let onX = 0;
  let midY = 0;

  // Particles: track first, then thumb.
  let trackCount = 0;
  let count = 0;
  let home = new Float32Array(0); // track: absolute; thumb: offset from thumb centre
  let pos = new Float32Array(0);
  let vel = new Float32Array(0);
  let stiff = new Float32Array(0);
  let delay = new Float32Array(0); // seconds left before a thumb particle sets off
  let rowLag = new Float32Array(0); // extra delay shared by a thumb row
  // Lattice occupancy, so the track can carve a gap around each thumb particle.
  let cols = 0;
  let rows = 0;
  let occupied = new Uint8Array(0);
  let trackCell = new Int32Array(0);
  let posAttr: BufferAttribute | null = null;
  let colorAttr: BufferAttribute | null = null;

  let checked = initialChecked;
  let pointer: [number, number] | null = null;
  let pressed = false;
  let press = 1; // animated stretch
  let raf = 0;
  let last = 0;
  let disposed = false;

  const snap = (v: number) => (Math.round(v / pitch - 0.5) + 0.5) * pitch;
  const thumbX = () => (checked ? onX : offX);

  function readColors() {
    const read = (prop: string, fallback: RGBA): RGBA => {
      probe.style.color = `var(${prop})`;
      const css = getComputedStyle(probe).color;
      if (!css) return fallback;
      colorCtx.clearRect(0, 0, 1, 1);
      colorCtx.fillStyle = "#000";
      colorCtx.fillStyle = css;
      colorCtx.fillRect(0, 0, 1, 1);
      const [r, g, b, a] = colorCtx.getImageData(0, 0, 1, 1).data;
      return a === 0 ? [0, 0, 0, 0] : [r / 255, g / 255, b / 255, a / 255];
    };
    cOff = read("--particle-off", cOff);
    cOn = read("--particle-on", cOn);
    cThumb = read("--particle-thumb", cThumb);
    wake();
  }

  function resize(w: number, h: number) {
    if (w === W && h === H) return;
    W = w;
    H = h;
    const dpr = Math.min(window.devicePixelRatio || 1, 3);
    renderer.setPixelRatio(dpr);
    renderer.setSize(w, h, false);
    camera.right = w;
    camera.bottom = h;
    camera.updateProjectionMatrix();

    // Keep the lattice on whole device pixels so the grid stays even.
    const pitchPx = Math.max(2, Math.round(pitchCss * dpr));
    pitch = pitchPx / dpr;
    material.uniforms.uDpr.value = dpr;
    material.uniforms.uSize.value = Math.max(1, Math.floor(pitchPx * 0.75));

    const pad = Math.max(pitch * 2, h * 0.12);
    thumbR = h / 2 - pad;
    midY = snap(h / 2);
    offX = snap(h / 2);
    onX = snap(w - h / 2);

    // Track: every lattice point inside the pill.
    const track: number[] = [];
    const r = h / 2;
    for (let y = pitch / 2; y < h; y += pitch) {
      for (let x = pitch / 2; x < w; x += pitch) {
        const cx = Math.min(Math.max(x, r), w - r);
        if (Math.hypot(x - cx, y - r) <= r - pitch * 0.35) track.push(x, y);
      }
    }
    // Thumb: lattice offsets inside the circle.
    // Rows share their randomness, so the swarm streaks like scanlines instead
    // of dissolving into noise.
    const thumb: number[] = [];
    const thumbStiff: number[] = [];
    const thumbLag: number[] = [];
    const steps = Math.ceil(thumbR / pitch);
    for (let j = -steps; j <= steps; j++) {
      const rowStiff = 0.8 + Math.random() * 0.4;
      const lag = Math.random() * 0.05;
      for (let i = -steps; i <= steps; i++) {
        if (Math.hypot(i * pitch, j * pitch) > thumbR) continue;
        thumb.push(i * pitch, j * pitch);
        thumbStiff.push(rowStiff + (Math.random() - 0.5) * 0.08);
        thumbLag.push(lag);
      }
    }

    trackCount = track.length / 2;
    count = trackCount + thumb.length / 2;
    home = new Float32Array([...track, ...thumb]);
    pos = new Float32Array(count * 3);
    vel = new Float32Array(count * 2);
    stiff = new Float32Array(count);
    delay = new Float32Array(count);
    rowLag = new Float32Array(count);
    cols = Math.ceil(w / pitch);
    rows = Math.ceil(h / pitch);
    occupied = new Uint8Array(cols * rows);
    trackCell = new Int32Array(trackCount);
    for (let i = 0; i < count; i++) {
      const [tx, ty] = target(i);
      pos[i * 3] = tx;
      pos[i * 3 + 1] = ty;
      if (i < trackCount) {
        stiff[i] = 0.85 + Math.random() * 0.3;
        trackCell[i] = Math.floor(tx / pitch) + Math.floor(ty / pitch) * cols;
      } else {
        stiff[i] = thumbStiff[i - trackCount];
        rowLag[i] = thumbLag[i - trackCount];
      }
    }
    posAttr = new BufferAttribute(pos, 3);
    colorAttr = new BufferAttribute(new Float32Array(count * 4), 4);
    geometry.setAttribute("position", posAttr);
    geometry.setAttribute("aColor", colorAttr);
    geometry.setDrawRange(0, count);
    wake();
  }

  /** Where particle i wants to be right now. */
  function target(i: number): [number, number] {
    let x: number;
    let y: number;
    if (i < trackCount) {
      x = home[i * 2];
      y = home[i * 2 + 1];
    } else {
      x = thumbX() + home[i * 2] * press;
      y = midY + home[i * 2 + 1] / Math.sqrt(press);
    }
    if (pointer && !isReduced()) {
      const dx = x - pointer[0];
      const dy = y - pointer[1];
      const d = Math.hypot(dx, dy);
      if (d < REPEL_RADIUS && d > 0.001) {
        const f = (1 - d / REPEL_RADIUS) ** 2 * REPEL_PUSH;
        x += (dx / d) * f;
        y += (dy / d) * f;
      }
    }
    return [x, y];
  }

  function setChecked(next: boolean) {
    if (next === checked) return;
    checked = next;
    if (count === 0) return;
    if (isReduced()) {
      for (let i = trackCount; i < count; i++) {
        const [tx, ty] = target(i);
        pos[i * 3] = tx;
        pos[i * 3 + 1] = ty;
        vel[i * 2] = vel[i * 2 + 1] = 0;
        delay[i] = 0;
      }
    } else {
      // Leading edge leaves first, rows lag by their own amount, and a small
      // vertical kick roughs up the edges in flight.
      const dir = next ? 1 : -1;
      for (let i = trackCount; i < count; i++) {
        const lead = (dir * home[i * 2]) / Math.max(thumbR, 1); // 1 = front, -1 = back
        delay[i] = (1 - lead) * 0.03 + rowLag[i] + Math.random() * 0.008;
        vel[i * 2 + 1] += (Math.random() - 0.5) * 14;
      }
    }
    wake();
  }

  function setPointer(x: number | null, y?: number) {
    pointer = x === null || y === undefined ? null : [x, y];
    wake();
  }

  function setPressed(p: boolean) {
    pressed = p;
    wake();
  }

  function wake() {
    if (disposed || raf) return;
    last = performance.now();
    raf = requestAnimationFrame(frame);
  }

  function frame(now: number) {
    raf = 0;
    const dt = Math.min((now - last) / 1000, 1 / 30);
    last = now;
    const reduced = isReduced();

    // Press stretch eases toward its goal.
    const pressGoal = pressed && !reduced ? PRESS_STRETCH : 1;
    press += (pressGoal - press) * (1 - Math.exp(-dt * 22));
    if (Math.abs(pressGoal - press) < 0.001) press = pressGoal;

    let moving = press !== pressGoal;
    let sumX = 0;
    for (let i = 0; i < count; i++) {
      const isThumb = i >= trackCount;
      if (isThumb && delay[i] > 0) {
        delay[i] -= dt;
        moving = true;
        sumX += pos[i * 3];
        continue;
      }
      const [tx, ty] = target(i);
      const px = pos[i * 3];
      const py = pos[i * 3 + 1];
      if (reduced) {
        pos[i * 3] = tx;
        pos[i * 3 + 1] = ty;
      } else {
        const k = (isThumb ? 420 : 300) * stiff[i];
        const c = 2 * Math.sqrt(k) * (isThumb ? 0.62 : 0.8);
        let vx = vel[i * 2] + (k * (tx - px) - c * vel[i * 2]) * dt;
        let vy = vel[i * 2 + 1] + (k * (ty - py) - c * vel[i * 2 + 1]) * dt;
        let nx = px + vx * dt;
        let ny = py + vy * dt;
        if (Math.abs(tx - nx) < 0.01 && Math.abs(ty - ny) < 0.01 && Math.abs(vx) < 0.5 && Math.abs(vy) < 0.5) {
          nx = tx;
          ny = ty;
          vx = vy = 0;
        } else {
          moving = true;
        }
        vel[i * 2] = vx;
        vel[i * 2 + 1] = vy;
        pos[i * 3] = nx;
        pos[i * 3 + 1] = ny;
      }
      if (isThumb) sumX += pos[i * 3];
    }

    paint(sumX / Math.max(count - trackCount, 1));
    renderer.render(scene, camera);
    if (moving) raf = requestAnimationFrame(frame);
  }

  /** Colour every particle from where the thumb swarm is right now. */
  function paint(centroidX: number) {
    if (!colorAttr || !posAttr) return;
    const col = colorAttr.array as Float32Array;
    const span = Math.max(onX - offX, 1);
    const p = (centroidX - offX) / span; // 0 = off, 1 = on
    // Mark every lattice cell within two steps of a thumb particle.
    occupied.fill(0);
    for (let i = trackCount; i < count; i++) {
      const cx = Math.round(pos[i * 3] / pitch - 0.5);
      const cy = Math.round(pos[i * 3 + 1] / pitch - 0.5);
      for (let dy = -2; dy <= 2; dy++) {
        const y = cy + dy;
        if (y < 0 || y >= rows) continue;
        for (let dx = -2; dx <= 2; dx++) {
          const x = cx + dx;
          if (x < 0 || x >= cols || dx * dx + dy * dy > 4) continue;
          occupied[x + y * cols] = 1;
        }
      }
    }
    for (let i = 0; i < count; i++) {
      let c: RGBA;
      let a: number;
      if (i < trackCount) {
        // The fill follows the thumb: lit where the thumb has passed.
        const u = clamp01((home[i * 2] - offX) / span);
        const lit = smoothstep(u - 0.12, u + 0.12, p * 1.24 - 0.12);
        c = [
          cOff[0] + (cOn[0] - cOff[0]) * lit,
          cOff[1] + (cOn[1] - cOff[1]) * lit,
          cOff[2] + (cOn[2] - cOff[2]) * lit,
          cOff[3] + (cOn[3] - cOff[3]) * lit,
        ];
        // A gap around the thumb keeps it readable against a lit track.
        a = occupied[trackCell[i]] ? 0 : c[3];
      } else {
        c = cThumb;
        a = cThumb[3];
      }
      col[i * 4] = c[0];
      col[i * 4 + 1] = c[1];
      col[i * 4 + 2] = c[2];
      col[i * 4 + 3] = a;
    }
    colorAttr.needsUpdate = true;
    posAttr.needsUpdate = true;
  }

  function dispose() {
    disposed = true;
    cancelAnimationFrame(raf);
    geometry.dispose();
    material.dispose();
    renderer.dispose();
  }

  readColors();

  return {
    resize,
    setChecked,
    setPointer,
    setPressed,
    readColors,
    dispose,
  };
}

function clamp01(v: number) {
  return v < 0 ? 0 : v > 1 ? 1 : v;
}

function smoothstep(a: number, b: number, v: number) {
  const t = clamp01((v - a) / (b - a));
  return t * t * (3 - 2 * t);
}

Search concepts

Search for a command to run...