"use client"; /** * clay.tsx — a lump of soft pink modelling clay with a debossed label. * Hover and the cursor leaves a dent with a fading trail; click squashes it flat with a fingerprint, then it slowly puffs back. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useImperativeHandle, useRef, useState, type ButtonHTMLAttributes, type MouseEvent, type Ref } from "react"; type Palette = { clay: string; light: string; shadow: string }; type Props = Omit, "children"> & { children?: string; ref?: Ref; palette?: Palette; }; const W = 250; const H = 104; const PAD = 26; const CW = W + PAD * 2; // 302 const CH = H + PAD * 2; // 156 const HW = W / 2; const HH = H / 2; const CAP = HH; // pill end radius const STRAIGHT = HW - CAP; // half length of the flat part const DOME = 24; const EDGE = 34; const SQUASH_Y = 0.68; const SQUASH_MS = 160; const HOLD_END = 900; const RESET_MS = 3300; const SPRING_K = 60; const SPRING_C = 7; const DENT_DEPTH = 8.5; const DENT_SIGMA = 12; const REST_LUMP = 0.8; const RM_RESET_MS = 1900; const DEFAULT_PALETTE: Palette = { clay: "#e49ca3", light: "#f7c4c7", shadow: "#c27482" }; const ACCENT = "#ffb4c2"; const LIGHT: [number, number, number] = (() => { const l = Math.hypot(-0.45, -0.6, 0.66); return [-0.45 / l, -0.6 / l, 0.66 / l]; })(); const FLAT = 0.15 + 0.85 * LIGHT[2]; type Rgb = [number, number, number]; type Print = { x: number; y: number; born: number; rm: boolean; fade: number }; type Dent = { x: number; y: number; d: number }; const clamp = (n: number, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, n)); const hex = (s: string): Rgb => { const m = /^#?([0-9a-f]{6})$/i.exec(s.trim()); const n = m ? parseInt(m[1], 16) : 0xe0a5a4; return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; }; const easeSquash = (t: number) => { // overshoots slightly, like cubic-bezier(.3,1.4,.5,1) const u = clamp(t) - 1; return 1 + 2.4 * u * u * u + 1.4 * u * u; }; const wobble = (th: number) => 0.55 * Math.sin(3 * th + 0.7) + 0.35 * Math.sin(5 * th + 2.0) + 0.3 * Math.sin(8 * th + 4.1); const endBulge = (th: number) => Math.exp(-(1 - Math.abs(Math.cos(th))) * 9); // Local outline of the pill (stadium), with outward normals, used for the lumpy silhouette. const OUTLINE: { x: number; y: number; nx: number; ny: number; th: number }[] = (() => { const pts: { x: number; y: number; nx: number; ny: number; th: number }[] = []; const add = (x: number, y: number, nx: number, ny: number) => pts.push({ x, y, nx, ny, th: Math.atan2(y, x) }); const N = 28; for (let i = 0; i < N; i++) add(-STRAIGHT + (2 * STRAIGHT * i) / N, -CAP, 0, -1); for (let i = 0; i < N; i++) { const a = -Math.PI / 2 + (Math.PI * i) / N; add(STRAIGHT + CAP * Math.cos(a), CAP * Math.sin(a), Math.cos(a), Math.sin(a)); } for (let i = 0; i < N; i++) add(STRAIGHT - (2 * STRAIGHT * i) / N, CAP, 0, 1); for (let i = 0; i < N; i++) { const a = Math.PI / 2 + (Math.PI * i) / N; add(-STRAIGHT + CAP * Math.cos(a), CAP * Math.sin(a), Math.cos(a), Math.sin(a)); } return pts; })(); function buildMask(text: string): { a: Float32Array; size: number; cap: number } { const out = new Float32Array(W * H); const c = document.createElement("canvas"); c.width = W; c.height = H; const g = c.getContext("2d"); if (!g) return { a: out, size: 32, cap: 23 }; const family = 'ui-rounded,"SF Pro Rounded","Nunito","Segoe UI",system-ui,sans-serif'; let size = 32; g.font = `800 ${size}px ${family}`; const label = text.toUpperCase(); const lg = g as CanvasRenderingContext2D & { letterSpacing?: string }; lg.letterSpacing = "2px"; const w = g.measureText(label).width; if (w > 200) { size = Math.max(12, Math.floor((size * 200) / w)); g.font = `800 ${size}px ${family}`; } const cap = g.measureText("H").actualBoundingBoxAscent || size * 0.72; g.fillStyle = "#fff"; g.textAlign = "center"; g.textBaseline = "alphabetic"; g.fillText(label, HW, HH + cap / 2); g.lineJoin = "round"; g.lineWidth = 1.6; g.strokeStyle = "#fff"; g.strokeText(label, HW, HH + cap / 2); const px = g.getImageData(0, 0, W, H).data; const a = new Float32Array(W * H); for (let i = 0; i < W * H; i++) a[i] = px[i * 4 + 3] / 255; // soften with a 3x3 box blur so the walls of the letters have a slope for (let pass = 0; pass < 2; pass++) { const src = pass === 0 ? a : out; const dst = pass === 0 ? out : a; for (let y = 1; y < H - 1; y++) { for (let x = 1; x < W - 1; x++) { const k = y * W + x; dst[k] = (src[k] * 4 + src[k - 1] + src[k + 1] + src[k - W] + src[k + W]) / 8; } } } return { a, size, cap }; } export function ClayButton({ children = "squish", palette = DEFAULT_PALETTE, onClick, className, type = "button", disabled = false, ref, ...rest }: Props) { const btnRef = useRef(null); const wrapRef = useRef(null); const canvasRef = useRef(null); const playRef = useRef<(x: number, y: number, centre: boolean) => void>(() => {}); const [state, setState] = useState<"idle" | "playing">("idle"); useImperativeHandle(ref, () => btnRef.current!, []); const paletteKey = `${palette.clay}|${palette.light}|${palette.shadow}`; useEffect(() => { const btn = btnRef.current; const wrap = wrapRef.current; const canvas = canvasRef.current; if (!btn || !wrap || !canvas) return; const ctx = canvas.getContext("2d"); const off = document.createElement("canvas"); off.width = CW; off.height = CH; const offCtx = off.getContext("2d"); const lab = document.createElement("canvas"); if (!ctx || !offCtx) return; const [kClay, kLight, kShadow] = paletteKey.split("|").map(hex) as [Rgb, Rgb, Rgb]; const kCrease: Rgb = [kShadow[0] * 0.9, kShadow[1] * 0.9, kShadow[2] * 0.9]; const kLabel: Rgb = [kShadow[0] * 0.9, kShadow[1] * 0.78, kShadow[2] * 0.92]; const N = CW * CH; const zBase = new Float32Array(N); const zWork = new Float32Array(N); const mk = new Float32Array(N); const ins = new Uint8Array(N); const grain = new Float32Array(N); const tone = new Float32Array(N); const pk = new Float32Array(N); const img = offCtx.createImageData(CW, CH); const { a: mask, size: labelSize, cap: labelCap } = buildMask(children); const labelText = children.toUpperCase(); const labelFont = `800 ${labelSize}px ui-rounded,"SF Pro Rounded","Nunito","Segoe UI",system-ui,sans-serif`; { // static matte grain: coarse + fine value noise, deterministic let seed = 1234567; const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296); const gw = Math.ceil(CW / 4) + 2; const gh = Math.ceil(CH / 4) + 2; const lat = new Float32Array(gw * gh); for (let i = 0; i < lat.length; i++) lat[i] = rnd() * 2 - 1; const gw2 = Math.ceil(CW / 2.5) + 2, lat2 = new Float32Array(gw2 * (Math.ceil(CH / 2.5) + 2)); for (let i = 0; i < lat2.length; i++) lat2[i] = rnd() * 2 - 1; const gw3 = Math.ceil(CW / 36) + 2, lat3 = new Float32Array(gw3 * (Math.ceil(CH / 36) + 2)); for (let i = 0; i < lat3.length; i++) lat3[i] = rnd() * 2 - 1; const bil = (L: Float32Array, gwv: number, fx: number, fy: number) => { const x0 = Math.floor(fx), y0 = Math.floor(fy), ux = fx - x0, uy = fy - y0, q = y0 * gwv + x0; return (L[q] * (1 - ux) + L[q + 1] * ux) * (1 - uy) + (L[q + gwv] * (1 - ux) + L[q + gwv + 1] * ux) * uy; }; for (let y = 0; y < CH; y++) { for (let x = 0; x < CW; x++) { const fx = x / 4; const fy = y / 4; const x0 = Math.floor(fx); const y0 = Math.floor(fy); const tx = fx - x0; const ty = fy - y0; const a = lat[y0 * gw + x0] * (1 - tx) + lat[y0 * gw + x0 + 1] * tx; const b = lat[(y0 + 1) * gw + x0] * (1 - tx) + lat[(y0 + 1) * gw + x0 + 1] * tx; grain[y * CW + x] = (a * (1 - ty) + b * ty) * 0.55 + bil(lat2, gw2, x / 2.5, y / 2.5) * 0.45; tone[y * CW + x] = bil(lat3, gw3, x / 36, y / 36); } } } // ---- state ---- let dpr = 1; let rect: DOMRect | undefined; let scale = 1; let raf = 0; let last = 0; let visible = true; let hovering = false; let tx = 0; let ty = 0; let phasePlay = false; let t0 = 0; let fromSy = 1; let springOn = false; let sy = 1; let hov = 0; let vy = 0; let prints: Print[] = []; const cur: Dent = { x: 0, y: 0, d: 0 }; let trail: Dent[] = []; let lastTrail = { x: 0, y: 0 }; let baseDirty = true; let timers: number[] = []; const media = window.matchMedia("(prefers-reduced-motion: reduce)"); const allowed = () => !btn.matches(":disabled") && !document.hidden; const printDepth = (p: Print, now: number) => { if (p.rm) return 1.0 * p.fade; const age = now - p.born; const ramp = clamp(age / SQUASH_MS); const decay = age > HOLD_END ? Math.exp(-(age - HOLD_END) / 900) : 1; return 1.5 * ramp * decay * clamp((3250 - age) / 350); }; const computeBase = (now: number) => { const sx = 1 + 0.12 * clamp((1 - sy) / (1 - SQUASH_Y), -0.15, 1); const sq = clamp((1 - sy) / (1 - SQUASH_Y)); const lsx = 1 + 0.04 * sq, lsy = 1 - 0.10 * sq; const zs = Math.pow(clamp(sy, 0.3, 1.2), 0.8); const lump = 1.7 * sq; let strongest = 0; const live: { x: number; y: number; pd: number }[] = []; for (const p of prints) { const pd = printDepth(p, now); if (pd > 0.005) live.push({ x: p.x, y: p.y, pd }); strongest = Math.max(strongest, pd / 1.5); } const bulge = 2.2 * strongest * sq; const labelDepth = Math.max(1.8, 3.0 * sy); const cx = CW / 2; const cy = CH / 2; for (let j = 0; j < CH; j++) { const ly = (j + 0.5 - cy) / sy; const row = j * CW; if (Math.abs(ly) > CAP + 8) { for (let i = 0; i < CW; i++) { zBase[row + i] = 0; ins[row + i] = 0; mk[row + i] = 0; } continue; } for (let i = 0; i < CW; i++) { const k = row + i; const lx = (i + 0.5 - cx) / sx; const ax = Math.abs(lx); const dx = ax > STRAIGHT ? ax - STRAIGHT : 0; let depth = CAP - Math.sqrt(dx * dx + ly * ly); if (depth < -6) { zBase[k] = 0; ins[k] = 0; mk[k] = 0; continue; } if (depth < 18) { const w = clamp(1 - depth / 18), s = w * w * (3 - 2 * w); const th = Math.atan2(ly, lx); depth += ((REST_LUMP + lump) * wobble(th) + bulge * endBulge(th)) * s; } if (depth < -1) { zBase[k] = 0; ins[k] = 0; mk[k] = 0; continue; } ins[k] = 1; let u = (Math.max(depth, 0) + 1.2) / (EDGE + 1.2); if (u > 1) u = 1; let zz = DOME * zs * Math.sqrt(u * (2 - u)); // label deboss let m = 0; if (Math.abs(lx * sx / lsx) < 100 && Math.abs(ly * sy / lsy) < 26) { const mx = (lx * sx) / lsx + HW - 0.5; const my = (ly * sy) / lsy + HH - 0.5; const x0 = Math.floor(mx); const y0 = Math.floor(my); if (x0 >= 0 && y0 >= 0 && x0 < W - 1 && y0 < H - 1) { const fx = mx - x0; const fy = my - y0; const q = y0 * W + x0; m = (mask[q] * (1 - fx) + mask[q + 1] * fx) * (1 - fy) + (mask[q + W] * (1 - fx) + mask[q + W + 1] * fx) * fy; } } mk[k] = m; if (m > 0) zz -= labelDepth * m; // two curved tool smears if (lx > -105 && lx < -40) { const da = Math.abs(ly - (-30 + 0.0016 * (lx + 70) ** 2)), env = Math.sin(Math.PI * (lx + 105) / 65); zz += env * (0.18 * Math.exp(-((da - 2.2) ** 2) / 1.2) - 0.45 * Math.exp(-(da * da) / 2.2)); } if (lx > 30 && lx < 95) { const db = Math.abs(ly - (31 - 0.0012 * (lx - 60) ** 2)), env = Math.sin(Math.PI * (lx - 30) / 65); zz += env * (0.18 * Math.exp(-((db - 2.2) ** 2) / 1.2) - 0.45 * Math.exp(-(db * db) / 2.2)); } let pkv = 0; // fingerprints for (let q = 0; q < live.length; q++) { const p = live[q]; const px = (lx - p.x) * sx; const py = (ly - p.y) * sy; const rs2 = px * px + py * py; if (rs2 > 34 * 34 && rs2 < 118 * 118) { const rs = Math.sqrt(rs2), t2 = Math.atan2(py, px); const w = clamp((rs - 34) / 10) * clamp((118 - rs) / 60) * (p.pd / 1.5); zz -= 0.32 * w * (0.5 + 0.5 * Math.sin(t2 * 23 + 1.7 * Math.sin(t2 * 4))); } if (px > 44 || px < -44 || py > 44 || py < -44) continue; const r2 = px * px + py * py; if (r2 > 44 * 44) continue; const r = Math.sqrt(r2); const f = Math.max(0, 1 - r2 / (38 * 38)); zz -= 2.5 * (p.pd / 1.5) * f * f; const ex = px / 22, ey = py / 27, rr = Math.sqrt(ex * ex + ey * ey); zz += 0.9 * (p.pd / 1.5) * Math.exp(-((r - 33) * (r - 33)) / 16); if (rr < 1) { const e0 = clamp((1 - rr) / 0.3), env = e0 * e0 * (3 - 2 * e0); const th = Math.atan2(ey, ex); const rad = rr * 31 + 2.8 * (th / (2 * Math.PI)) + 1.2 * Math.sin(py * 0.16 + px * 0.05); const ridge = 0.5 + 0.5 * Math.cos((rad * Math.PI * 2) / 2.8); const brk = 0.75 + 0.25 * Math.sin(th * 9 + rr * 17); zz -= p.pd * (0.25 + 0.8 * (1 - ridge) * brk) * env; pkv += (1 - ridge) * brk * env * (p.pd / 1.5); } } pk[k] = pkv; zBase[k] = zz; } } }; const addDent = (z: Float32Array, d: Dent) => { if (d.d < 0.02) return; const sx = 1 + 0.12 * clamp((1 - sy) / (1 - SQUASH_Y), -0.15, 1); const cx = CW / 2; const cy = CH / 2; const i0 = Math.max(0, Math.floor(cx + (d.x - 56) * sx)); const i1 = Math.min(CW - 1, Math.ceil(cx + (d.x + 56) * sx)); const j0 = Math.max(0, Math.floor(cy + (d.y - 56) * sy)); const j1 = Math.min(CH - 1, Math.ceil(cy + (d.y + 56) * sy)); const lip = 0.5 * d.d; for (let j = j0; j <= j1; j++) { const dy = (j + 0.5 - cy) / sy - d.y; for (let i = i0; i <= i1; i++) { const dx = (i + 0.5 - cx) / sx - d.x; const r2 = dx * dx + dy * dy; const r = Math.sqrt(r2); z[j * CW + i] += -d.d * Math.exp(-r2 / (2 * DENT_SIGMA * DENT_SIGMA)) + lip * Math.exp(-((r - 23) * (r - 23)) / 80); } } }; const shade = (z: Float32Array) => { const d = img.data; for (let j = 1; j < CH - 1; j++) { for (let i = 1; i < CW - 1; i++) { const k = j * CW + i; const p = k * 4; if (!ins[k]) { d[p + 3] = 0; continue; } const gx = (z[k + 1] - z[k - 1]) * 0.75; const gy = (z[k + CW] - z[k - CW]) * 0.75; const inv = 1 / Math.sqrt(gx * gx + gy * gy + 1); let ndl = (-gx * LIGHT[0] - gy * LIGHT[1] + LIGHT[2]) * inv; if (ndl < 0) ndl = 0; const v = 0.15 + 0.85 * ndl; let r: number; let g: number; let b: number; if (v >= FLAT) { const t = Math.min(1, ((v - FLAT) / (1 - FLAT)) * 1.25); r = kClay[0] + (kLight[0] - kClay[0]) * t; g = kClay[1] + (kLight[1] - kClay[1]) * t; b = kClay[2] + (kLight[2] - kClay[2]) * t; } else { const s = ((FLAT - v) / FLAT) * 1.15; if (s <= 1) { r = kClay[0] + (kShadow[0] - kClay[0]) * s; g = kClay[1] + (kShadow[1] - kClay[1]) * s; b = kClay[2] + (kShadow[2] - kClay[2]) * s; } else { const t = Math.min(1, s - 1); r = kShadow[0] + (kCrease[0] - kShadow[0]) * t; g = kShadow[1] + (kCrease[1] - kShadow[1]) * t; b = kShadow[2] + (kCrease[2] - kShadow[2]) * t; } } { const yn = (j + 0.5 - CH / 2) / (CAP * sy); const t = clamp((yn - 0.1) / 0.9); const ao = 1 - 0.16 * t * t * (3 - 2 * t); r *= ao; g *= ao; b *= ao; if (z !== zBase) { const cav = zBase[k] - z[k]; if (cav > 0) { const o = 1 - Math.min(0.14, cav * 0.03); r *= o; g *= o; b *= o; } } const lum = (r + g + b) / 3, sat = 1.05 + 0.18 * t * t * (3 - 2 * t); r = lum + (r - lum) * sat; g = lum + (g - lum) * sat; b = lum + (b - lum) * sat; const sh = 0.09 * ndl ** 6; r += (255 - r) * sh; g += (255 - g) * sh; b += (255 - b) * sh; const tl = clamp((-yn - 0.55) / 0.45); r += (kLight[0] - r) * 0.25 * tl; g += (kLight[1] - g) * 0.25 * tl; b += (kLight[2] - b) * 0.25 * tl; } const m = mk[k]; if (m > 0.02) { const f = Math.min(1.25, v / FLAT); const a = Math.min(1, m * 0.20); r += (kLabel[0] * f - r) * a; g += (kLabel[1] * f - g) * a; b += (kLabel[2] * f - b) * a; } const q = pk[k]; if (q > 0.02) { const a = Math.min(0.5, q * 0.5); r += (kLabel[0] - r) * a; g += (kLabel[1] - g) * a; b += (kLabel[2] - b) * a; } const gr = 1 + grain[k] * 0.024; const tn = tone[k]; r *= 1 + 0.022 * tn; b *= 1 - 0.022 * tn; d[p] = r * gr; d[p + 1] = g * gr; d[p + 2] = b * gr; d[p + 3] = 255; } } }; const outline = () => { const sx = 1 + 0.12 * clamp((1 - sy) / (1 - SQUASH_Y), -0.15, 1); const sq = clamp((1 - sy) / (1 - SQUASH_Y)); const lump = 1.7 * sq; let strongest = 0; const now = performance.now(); for (const p of prints) strongest = Math.max(strongest, printDepth(p, now) / 1.5); const bulge = 2.2 * strongest * sq; const path = new Path2D(); OUTLINE.forEach((o, n) => { const off2 = (REST_LUMP + lump) * wobble(o.th) + bulge * endBulge(o.th); const x = CW / 2 + (o.x + o.nx * off2) * sx; const y = CH / 2 + (o.y + o.ny * off2) * sy; if (n === 0) path.moveTo(x, y); else path.lineTo(x, y); }); path.closePath(); return { path, sq }; }; const draw = (now: number) => { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, CW, CH); if (baseDirty) { computeBase(now); baseDirty = false; } let z = zBase; const dents = trail.length || cur.d > 0.02 ? [cur, ...trail] : []; if (dents.length) { zWork.set(zBase); for (const dn of dents) addDent(zWork, dn); z = zWork; } shade(z); offCtx.putImageData(img, 0, 0); const { path, sq } = outline(); ctx.save(); ctx.fillStyle = paletteKey.split("|")[2]; ctx.shadowColor = `rgba(52,18,26,${0.36 + 0.12 * sq})`; ctx.shadowBlur = (16 - 6 * sq) * dpr; ctx.shadowOffsetY = (9 - 4 * sq) * dpr; ctx.fill(path); ctx.shadowColor = `rgba(40,12,20,${0.6 + 0.2 * sq})`; ctx.shadowBlur = (4 - 1 * sq) * dpr; ctx.shadowOffsetY = (2.5 - 1 * sq) * dpr; ctx.fill(path); ctx.restore(); ctx.save(); ctx.clip(path); ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "high"; ctx.drawImage(off, 0, 0, CW, CH); const sqd = clamp((1 - sy) / (1 - SQUASH_Y)), lsx = 1 + 0.04 * sqd, lsy = 1 - 0.10 * sqd; ctx.translate(CW / 2, CH / 2); ctx.scale(lsx, lsy); ctx.drawImage(lab, -HW, -HH, W, H); ctx.restore(); ctx.lineWidth = 0.75; ctx.strokeStyle = "rgba(120,56,66,.16)"; ctx.stroke(path); ctx.save(); ctx.clip(path); ctx.translate(0, 1); const rg = ctx.createLinearGradient(0, CH / 2 - CAP * sy, 0, CH / 2); rg.addColorStop(0, "rgba(255,236,234,.45)"); rg.addColorStop(1, "rgba(255,236,234,0)"); ctx.strokeStyle = rg; ctx.lineWidth = 1.4; ctx.stroke(path); ctx.restore(); }; const buildLabel = () => { lab.width = Math.round(W * dpr); lab.height = Math.round(H * dpr); const g = lab.getContext("2d") as (CanvasRenderingContext2D & { letterSpacing?: string }) | null; if (!g) return; g.setTransform(dpr, 0, 0, dpr, 0, 0); g.font = labelFont; g.letterSpacing = "2px"; g.textAlign = "center"; g.textBaseline = "alphabetic"; const y = HH + labelCap / 2; g.fillStyle = "rgba(255,228,226,.45)"; g.fillText(labelText, HW, y + 0.9); g.fillStyle = "rgba(96,32,50,.55)"; g.fillText(labelText, HW, y - 0.9); g.globalCompositeOperation = "destination-out"; g.fillStyle = "#000"; g.fillText(labelText, HW, y); g.globalCompositeOperation = "source-over"; g.fillStyle = "rgba(140,62,82,.50)"; g.fillText(labelText, HW, y); }; const setup = () => { const r = btn.getBoundingClientRect(); scale = r.width / (btn.offsetWidth || 1) || 1; dpr = Math.min(2, (window.devicePixelRatio || 1) * scale); canvas.width = Math.round(CW * dpr); canvas.height = Math.round(CH * dpr); rect = r; buildLabel(); draw(performance.now()); }; const locate = () => { rect = btn.getBoundingClientRect(); scale = rect.width / (btn.offsetWidth || 1) || 1; }; const toLocal = (cx: number, cy: number) => { if (!rect) locate(); const r = rect!; return { x: (cx - r.left) / scale - HW, y: (cy - r.top) / scale - HH }; }; const endPlay = () => { phasePlay = false; springOn = false; sy = 1 - 0.045 * hov; vy = 0; prints = []; baseDirty = true; setState("idle"); }; const tick = (now: number) => { raf = 0; if (!allowed() || media.matches) return; const dt = last ? Math.min(48, now - last) : 16; last = now; let animating = false; if (phasePlay) { const t = now - t0; if (t >= RESET_MS) { endPlay(); } else { if (t < SQUASH_MS) { sy = fromSy + (SQUASH_Y - fromSy) * easeSquash(t / SQUASH_MS); } else if (t < HOLD_END) { sy = SQUASH_Y - 0.025 * (1 - Math.exp(-(t - SQUASH_MS) / 300)); } else { if (!springOn) { springOn = true; vy = 0; } const steps = Math.max(1, Math.ceil(dt / 4)); const h = dt / steps / 1000; for (let s = 0; s < steps; s++) { vy += (-SPRING_K * (sy - 1) - SPRING_C * vy) * h; sy += vy * h; } if (Math.abs(sy - 1) < 0.0005 && Math.abs(vy) < 0.002) { sy = 1; vy = 0; } } baseDirty = true; animating = true; } } const hovT = hovering && !phasePlay ? 1 : 0, hPrev = hov; hov += (hovT - hov) * (1 - Math.exp(-dt / 120)); if (Math.abs(hovT - hov) < 0.001) hov = hovT; if (!phasePlay && hov !== hPrev) { sy = 1 - 0.045 * hov; baseDirty = true; } // hover dent const pressedRecently = phasePlay && now - t0 < 1500; const target = hovering && !pressedRecently && !phasePlay ? DENT_DEPTH : 0; const kp = 1 - Math.exp(-dt / 60); const kd = 1 - Math.exp(-dt / 55); cur.x += (tx - cur.x) * kp; cur.y += (ty - cur.y) * kp; cur.d += (target - cur.d) * kd; if (cur.d > 0.5 && Math.hypot(cur.x - lastTrail.x, cur.y - lastTrail.y) > 6) { trail.push({ x: cur.x, y: cur.y, d: cur.d * 0.75 }); if (trail.length > 8) trail.shift(); lastTrail = { x: cur.x, y: cur.y }; } const decay = Math.exp(-dt / 700); for (const tr of trail) tr.d *= decay; trail = trail.filter((tr) => tr.d > 0.05); const dentMoving = trail.length > 0 || Math.abs(target - cur.d) > 0.02 || Math.hypot(tx - cur.x, ty - cur.y) > 0.15 || hov !== hovT; if (cur.d < 0.02 && target === 0) cur.d = 0; draw(now); if (animating || dentMoving) raf = requestAnimationFrame(tick); else last = 0; }; const wake = () => { if (!raf && allowed() && !media.matches) raf = requestAnimationFrame(tick); }; const clearTimers = () => { timers.forEach((id) => window.clearTimeout(id)); timers = []; }; const later = (fn: () => void, ms: number) => { timers.push(window.setTimeout(fn, ms)); }; playRef.current = (cx, cy, centre) => { if (!allowed()) return; const lp = centre ? { x: 0, y: 0 } : toLocal(cx, cy); const px = clamp(lp.x * 0.35, -32, 32); const py = clamp(lp.y * 0.3, -6, 6); const now = performance.now(); if (media.matches) { clearTimers(); prints = [{ x: px, y: py, born: now, rm: true, fade: 1 }]; sy = 1; baseDirty = true; draw(now); setState("playing"); later(() => { prints.forEach((p) => (p.fade = 0.5)); baseDirty = true; draw(performance.now()); }, 1600); later(() => { prints.forEach((p) => (p.fade = 0.2)); baseDirty = true; draw(performance.now()); }, 1700); later(() => { prints = []; baseDirty = true; draw(performance.now()); setState("idle"); }, RM_RESET_MS - 100); return; } fromSy = sy; phasePlay = true; t0 = now; springOn = false; vy = 0; prints.push({ x: px, y: py, born: now, rm: false, fade: 1 }); if (prints.length > 2) prints.shift(); setState("playing"); wake(); }; const move = (e: PointerEvent) => { if (!hovering) return; const lp = toLocal(e.clientX, e.clientY); tx = clamp(lp.x, -112, 112); ty = clamp(lp.y, -42, 42); wake(); }; const enter = (e: PointerEvent) => { if (btn.matches(":disabled") || media.matches) return; locate(); hovering = true; const lp = toLocal(e.clientX, e.clientY); tx = clamp(lp.x, -112, 112); ty = clamp(lp.y, -42, 42); if (cur.d < 0.05) { cur.x = tx; cur.y = ty; lastTrail = { x: tx, y: ty }; } wake(); }; const leave = () => { hovering = false; wake(); }; const invalidate = () => { locate(); }; const resize = () => { setup(); }; const onMedia = () => { if (media.matches) { cancelAnimationFrame(raf); raf = 0; endPlay(); cur.d = 0; trail = []; draw(performance.now()); } }; const io = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; wrap.dataset.tbPaused = String(!visible); }); const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(invalidate); const onVis = () => { if (!document.hidden) wake(); }; setup(); io?.observe(wrap); ro?.observe(btn); window.addEventListener("pointermove", move, { passive: true }); window.addEventListener("resize", resize); window.addEventListener("scroll", invalidate, true); btn.addEventListener("pointerenter", enter); btn.addEventListener("pointerleave", leave); document.addEventListener("visibilitychange", onVis); media.addEventListener("change", onMedia); return () => { playRef.current = () => {}; cancelAnimationFrame(raf); clearTimers(); io?.disconnect(); ro?.disconnect(); window.removeEventListener("pointermove", move); window.removeEventListener("resize", resize); window.removeEventListener("scroll", invalidate, true); btn.removeEventListener("pointerenter", enter); btn.removeEventListener("pointerleave", leave); document.removeEventListener("visibilitychange", onVis); media.removeEventListener("change", onMedia); }; }, [disabled, paletteKey, children]); const click = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; const centre = e.detail === 0 || (e.clientX === 0 && e.clientY === 0); playRef.current(e.clientX, e.clientY, centre); }; return ( ); } export default ClayButton; const css = ` .tb-clay-wrap{display:inline-flex;position:relative;vertical-align:middle;width:${W}px;height:${H}px} .tb-clay-btn{position:relative;display:block;box-sizing:border-box;width:${W}px;height:${H}px;padding:0;margin:0;border:0; border-radius:999px;background:transparent;overflow:visible;cursor:pointer;-webkit-tap-highlight-color:transparent; font:800 30px ui-rounded,"SF Pro Rounded","Nunito","Segoe UI",system-ui,sans-serif} .tb-clay-btn:focus-visible{outline:3px solid #c94f6d;outline-offset:6px} .tb-clay-btn:disabled{cursor:default;opacity:.6;filter:saturate(.5)} .tb-clay-canvas{position:absolute;left:-${PAD}px;top:-${PAD}px;width:${CW}px;height:${CH}px;max-width:none;pointer-events:none} .tb-clay-wrap[data-tb-paused=true] *{animation-play-state:paused!important} @media (prefers-reduced-motion:reduce){.tb-clay-wrap *,.tb-clay-wrap *::before,.tb-clay-wrap *::after{animation:none!important;transition:none!important}} `;