"use client"; /** * sand.tsx — a terracotta button made of sand. * Hover and grains trickle off the bottom. Click and the whole thing pours into a pile, then rebuilds itself. * Note: the pile spills ~90px below the button, outside its layout box. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useImperativeHandle, useRef, type ButtonHTMLAttributes, type MouseEvent, type Ref, } from "react"; type Props = Omit, "children"> & { /** engraved into the block (plain text only) */ children?: string; ref?: Ref; /** top and bottom colors of the block */ colors?: [string, string]; }; const W = 220; const H = 64; const C = 2; // one grain = 2x2 css px const SIDE = 90; // room for the pile to spread const BELOW = 92; const GW = (W + SIDE * 2) / C; const GH = (H + BELOW) / C; const FONT = `700 22px ui-rounded, "SF Pro Rounded", "Nunito", "Segoe UI", system-ui, sans-serif`; function rng(seed: number) { return () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } /** paints the block itself; the grains are sampled from this, so it's the single source of truth */ function paint(ctx: CanvasRenderingContext2D, label: string, [top, bottom]: [string, string]) { const r = rng(5); ctx.save(); ctx.beginPath(); ctx.roundRect(0, 5, W, H - 5, 14); ctx.fillStyle = "#86391d"; ctx.fill(); ctx.beginPath(); ctx.roundRect(0, 0, W, H - 6, 14); const g = ctx.createLinearGradient(0, 0, 0, H - 6); g.addColorStop(0, top); g.addColorStop(1, bottom); ctx.fillStyle = g; ctx.fill(); ctx.clip(); for (let i = 0; i < 220; i++) { ctx.fillStyle = r() > 0.5 ? "rgba(255,225,190,.28)" : "rgba(90,30,10,.22)"; ctx.fillRect(r() * W, r() * H, 1 + r() * 1.4, 1 + r() * 1.4); } ctx.fillStyle = "rgba(255,255,255,.18)"; ctx.fillRect(0, 0, W, 2); ctx.restore(); ctx.font = FONT; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = "rgba(255,214,180,.4)"; ctx.fillText(label, W / 2, (H - 6) / 2 + 2); ctx.fillStyle = "#6e2a12"; ctx.fillText(label, W / 2, (H - 6) / 2 + 1); } export function SandButton({ children = "dissolve", colors = ["#dc7c4e", "#b9573a"], onClick, onPointerEnter, onPointerLeave, className, type = "button", disabled = false, ref, ...rest }: Props) { const btnRef = useRef(null); useImperativeHandle(ref, () => btnRef.current!, []); const canvasRef = useRef(null); const api = useRef({ pour: () => {}, hover: (_on: boolean) => {} }); const colorsRef = useRef(colors); colorsRef.current = colors; useEffect(() => { const canvas = canvasRef.current; const button = btnRef.current; if (!canvas || !button) return; const ctx = canvas.getContext("2d")!; const reduced = window.matchMedia("(prefers-reduced-motion: reduce)"); // crisp copy of the block, redrawn at the right resolution on resize/zoom const still = document.createElement("canvas"); // tiny buffer: one pixel per grain const tiny = document.createElement("canvas"); tiny.width = GW; tiny.height = GH; const tctx = tiny.getContext("2d")!; const img = tctx.createImageData(GW, GH); const px = new Uint32Array(img.data.buffer); // grains const sample = document.createElement("canvas"); sample.width = W / C; sample.height = H / C; const sctx = sample.getContext("2d", { willReadFrequently: true })!; sctx.scale(1 / C, 1 / C); paint(sctx, children, colorsRef.current); const data = sctx.getImageData(0, 0, W / C, H / C).data; const hx: number[] = [], hy: number[] = [], col: number[] = []; const jitter = rng(11); for (let j = 0; j < H / C; j++) { for (let i = 0; i < W / C; i++) { const k = (j * (W / C) + i) * 4; if (data[k + 3] < 140) continue; const f = 0.88 + jitter() * 0.24; const cl = (v: number) => Math.min(255, Math.round(v * f)); hx.push(i + SIDE / C); hy.push(j); col.push((255 << 24) | (cl(data[k + 2]) << 16) | (cl(data[k + 1]) << 8) | cl(data[k])); } } const N = hx.length; const gx = new Float32Array(N), gy = new Float32Array(N); const vy = new Float32Array(N), acc = new Float32Array(N); const release = new Float32Array(N), start = new Float32Array(N); const sx = new Float32Array(N), sy = new Float32Array(N); const state = new Uint8Array(N); // 0 home, 1 sand, 2 flying home const grid = new Int32Array(GW * GH); const rowHead = new Int32Array(GH), nextGrain = new Int32Array(N); let phase: "idle" | "pour" | "rest" | "build" = "idle"; let t0 = 0, raf = 0, timer = 0, quiet = 0, hovering = false, fade = 1; let visible = true, previous = 0, elapsed = 0; const dust: { x: number; y: number; v: number; c: number; life: number }[] = []; const size = () => { const rect = button.getBoundingClientRect(); const scale = rect.width / W || 1; const dpr = Math.max(0.5, Math.min(2, (window.devicePixelRatio || 1) * scale)); canvas.width = Math.round((W + SIDE * 2) * dpr); canvas.height = Math.round((H + BELOW) * dpr); still.width = Math.round(W * dpr); still.height = Math.round(H * dpr); const s = still.getContext("2d")!; s.setTransform(dpr, 0, 0, dpr, 0, 0); paint(s, children, colorsRef.current); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.imageSmoothingEnabled = false; draw(); }; const draw = () => { ctx.clearRect(0, 0, W + SIDE * 2, H + BELOW); if (phase === "idle" || fade < 1) { ctx.globalAlpha = phase === "idle" ? fade : 1 - fade; ctx.drawImage(still, SIDE, 0, W, H); ctx.globalAlpha = 1; } if (phase !== "idle" || fade < 1) { px.fill(0); for (let i = 0; i < N; i++) { const x = Math.round(gx[i]), y = Math.round(gy[i]); if (x >= 0 && y >= 0 && x < GW && y < GH) px[y * GW + x] = col[i]; } tctx.putImageData(img, 0, 0); ctx.globalAlpha = phase === "idle" ? 1 - fade : 1; ctx.drawImage(tiny, 0, 0, W + SIDE * 2, H + BELOW); ctx.globalAlpha = 1; } for (const d of dust) { ctx.globalAlpha = Math.min(1, d.life); ctx.fillStyle = `#${(d.c & 0xffffff).toString(16).padStart(6, "0").replace(/(..)(..)(..)/, "$3$2$1")}`; ctx.fillRect(d.x, d.y, C, C); } ctx.globalAlpha = 1; }; const fall = (i: number) => { const x = gx[i] | 0, y = gy[i] | 0; if (y >= GH - 1) return false; const here = y * GW + x; const down = here + GW; const go = (to: number, nx: number, ny: number) => { grid[here] = 0; grid[to] = i + 1; gx[i] = nx; gy[i] = ny; return true; }; if (!grid[down]) return go(down, x, y + 1); const dir = Math.random() < 0.5 ? -1 : 1; for (const d of [dir, -dir]) { const nx = x + d; if (nx < 0 || nx >= GW) continue; if (!grid[down + d]) return go(down + d, nx, y + 1); } // let it slide a little further so the pile is low and wide for (const d of [dir, -dir]) { const nx = x + d * 2; if (nx < 0 || nx >= GW || grid[here + d]) continue; if (!grid[down + d * 2] && Math.random() < 0.6) return go(down + d * 2, nx, y + 1); } return false; }; const step = (now: number) => { raf = 0; if (!allowed()) { reset(); return; } const dt = Math.min(50, now - (previous || now - 16.67)); previous = now; const t = now - t0; let busy = (hovering && phase === "idle") || dust.length > 0; if (phase === "pour") { for (let i = 0; i < N; i++) if (state[i] === 0 && t >= release[i]) { state[i] = 1; vy[i] = 0.3; acc[i] = 0; } let moved = 0; elapsed += dt; let ticks = 0; while (elapsed >= 1000 / 60) { elapsed -= 1000 / 60; ticks++; for (let sub = 0; sub < 3; sub++) { // Bucket only live grains by row. Visit each exactly once, bottom-up, // without sweeping the mostly empty 200x78 grid three times. rowHead.fill(-1); for (let i = 0; i < N; i++) { if (state[i] !== 1) continue; const y = gy[i] | 0; nextGrain[i] = rowHead[y]; rowHead[y] = i; } for (let y = GH - 2; y >= 0; y--) { for (let i = rowHead[y]; i !== -1; i = nextGrain[i]) { vy[i] = Math.min(vy[i] + 0.06, 2.2); acc[i] += vy[i]; while (acc[i] >= 1) { acc[i] -= 1; if (fall(i)) moved++; else { vy[i] = 0.3; acc[i] = 0; break; } } } } } } // A short quiet window starts the return promptly after the pile settles. if (ticks) quiet = moved < 90 * ticks ? quiet + ticks * 1000 / 60 : 0; if ((quiet > 100 && t > 900) || t > 2100) { phase = "rest"; timer = window.setTimeout(build, 220); } busy = true; } else if (phase === "build") { let done = 0; for (let i = 0; i < N; i++) { const p = Math.min(1, Math.max(0, (t - release[i]) / 520)); if (p >= 1) { gx[i] = hx[i]; gy[i] = hy[i]; done++; continue; } const e = 1 - Math.pow(1 - p, 3); gx[i] = sx[i] + (hx[i] - sx[i]) * e; // arc up and over, like it's being poured back in reverse gy[i] = sy[i] + (hy[i] - sy[i]) * e - Math.sin(Math.PI * p) * start[i]; } if (done === N) { phase = "idle"; fade = 0; } busy = true; } if (phase === "idle" && fade < 1) { fade = Math.min(1, fade + dt / 210); busy = true; } // decorative trickle while hovering if (hovering && phase === "idle" && Math.random() < 1 - Math.pow(0.45, dt / 16.67)) { const i = Math.floor(Math.random() * N); dust.push({ x: SIDE + (hx[i] - SIDE / C) * C, y: H - 7, v: 0.4, c: col[i], life: 2.4 }); } for (let k = dust.length - 1; k >= 0; k--) { const d = dust[k]; d.v = Math.min(d.v + 0.35 * dt / 16.67, 7); d.y = Math.min(d.y + d.v * dt / 16.67, H + BELOW - C); if (d.y >= H + BELOW - C) d.life -= 0.04 * dt / 16.67; if (d.life <= 0) dust.splice(k, 1); } button.dataset.phase = phase; draw(); if (busy) raf = requestAnimationFrame(step); else previous = 0; }; const allowed = () => !disabled && !button.matches(":disabled") && visible && !document.hidden && !reduced.matches; const wake = () => { if (!raf && allowed()) raf = requestAnimationFrame(step); }; function build() { timer = 0; if (!allowed()) return; phase = "build"; t0 = performance.now(); for (let i = 0; i < N; i++) { state[i] = 2; sx[i] = gx[i]; sy[i] = gy[i]; // bottom rows of the block come back first, so it rebuilds upward release[i] = ((H / C - hy[i]) / (H / C)) * 650 + Math.random() * 160; start[i] = 4 + Math.random() * 10; } grid.fill(0); wake(); } api.current.pour = () => { if (phase !== "idle" || !allowed()) return; elapsed = 0; previous = 0; phase = "pour"; t0 = performance.now(); quiet = 0; fade = 1; grid.fill(0); for (let i = 0; i < N; i++) { gx[i] = hx[i]; gy[i] = hy[i]; state[i] = 0; grid[hy[i] * GW + hx[i]] = i + 1; // the bottom goes first, like the block is draining through the floor release[i] = ((H / C - 1 - hy[i]) / (H / C)) * 700 + Math.random() * 140; } wake(); }; api.current.hover = (on) => { hovering = on && allowed(); if (hovering) { size(); wake(); } }; const reset = () => { cancelAnimationFrame(raf); raf = 0; previous = 0; window.clearTimeout(timer); timer = 0; phase = "idle"; fade = 1; hovering = false; dust.length = 0; button.dataset.phase = phase; draw(); }; const visibility = () => { if (!allowed()) reset(); }; const io = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; visibility(); }); io?.observe(button); let dprQuery: MediaQueryList; const watchDpr = () => { dprQuery?.removeEventListener("change", watchDpr); size(); dprQuery = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`); dprQuery.addEventListener("change", watchDpr); }; watchDpr(); window.addEventListener("resize", size); document.addEventListener("visibilitychange", visibility); reduced.addEventListener("change", visibility); const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(size); ro?.observe(button); return () => { reset(); io?.disconnect(); dprQuery.removeEventListener("change", watchDpr); window.removeEventListener("resize", size); document.removeEventListener("visibilitychange", visibility); reduced.removeEventListener("change", visibility); ro?.disconnect(); api.current = { pour: () => {}, hover: () => {} }; }; }, [children, disabled, colors[0], colors[1]]); useEffect(() => { if (disabled) api.current.hover(false); }, [disabled]); const click = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (!e.defaultPrevented) api.current.pour(); }; return ( ); } export default SandButton; const css = ` .tbd-wrap{display:inline-flex} .tbd-btn{position:relative;width:${W}px;height:${H}px;padding:0;border:0;background:none;cursor:pointer;border-radius:14px;-webkit-tap-highlight-color:transparent; transition:transform .25s cubic-bezier(.3,1.6,.5,1)} .tbd-btn:not(:disabled):hover{transform:translateY(-1px)} .tbd-btn:disabled{cursor:not-allowed;opacity:.6;filter:saturate(.5)} .tbd-btn:focus-visible{outline:3px solid #dc7c4e;outline-offset:4px} .tbd-canvas{position:absolute;left:${-SIDE}px;top:0;width:${W + SIDE * 2}px;height:${H + BELOW}px;pointer-events:none} .tbd-shadow,.tbd-pile-shadow{position:absolute;pointer-events:none;height:20px;border-radius:50%;background:radial-gradient(closest-side,rgba(120,50,20,.2),transparent)} .tbd-shadow{left:0;right:0;top:54px} .tbd-btn[data-phase=pour] .tbd-shadow,.tbd-btn[data-phase=rest] .tbd-shadow,.tbd-btn[data-phase=build] .tbd-shadow{opacity:0} .tbd-pile-shadow{left:-65px;right:-65px;top:146px;opacity:0} .tbd-btn[data-phase=rest] .tbd-pile-shadow,.tbd-btn[data-phase=pour] .tbd-pile-shadow,.tbd-btn[data-phase=build] .tbd-pile-shadow{opacity:1} @media(prefers-reduced-motion:reduce){.tbd-btn{transition:none}.tbd-btn:not(:disabled):hover{transform:none}} `;