"use client"; /** * fur.tsx — a button you can pet. * Stroke it and the fur parts and stays combed for a while. Click and it puffs up like a startled cat. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useImperativeHandle, useRef, type ButtonHTMLAttributes, type MouseEvent, type Ref, } from "react"; type Palette = { skin: string; shadow: string; ink: string; fur: string[] }; type Props = Omit, "children"> & { /** pressed into the fur (plain text only) */ children?: string; ref?: Ref; palette?: Palette; }; const PINK: Palette = { skin: "#e58aae", shadow: "#c9668f", ink: "#b9487a", fur: ["#f6b3cc", "#f9c3d7", "#f2a3c1", "#fcd6e4"], }; const W = 220; const H = 72; const PAD = 32; // fur sticks out past the edges (and puffs further) const SPACING = 2.9; const FONT = `800 25px ui-rounded, "SF Pro Rounded", "Nunito", "Segoe UI", system-ui, sans-serif`; type Strand = { x: number; y: number; len: number; curl: number; tone: number; text: boolean; rx: number; ry: number; // resting direction cx: number; cy: number; // where it's been combed to ux: number; uy: number; // where it points right now l: number; lt: number; // length multiplier, and its target }; /** distance outside the pill (negative inside) and the outward normal */ function pill(x: number, y: number) { const r = H / 2; const qx = Math.min(W - r, Math.max(r, x)); const dx = x - qx, dy = y - r; const d = Math.hypot(dx, dy) || 1e-6; return { d: d - r, nx: dx / d, ny: dy / d }; } function grow(label: string): Strand[] { // where the letters are, so those strands can be clipped short const mask = document.createElement("canvas"); mask.width = W; mask.height = H; const m = mask.getContext("2d", { willReadFrequently: true })!; m.font = FONT; m.textAlign = "center"; m.textBaseline = "middle"; m.fillText(label, W / 2, H / 2 + 1); const alpha = m.getImageData(0, 0, W, H).data; const inText = (x: number, y: number) => { const ix = Math.round(x), iy = Math.round(y); return ix >= 0 && iy >= 0 && ix < W && iy < H && alpha[(iy * W + ix) * 4 + 3] > 90; }; const out: Strand[] = []; for (let y = 1; y < H; y += SPACING * 0.87) { for (let x = 1; x < W; x += SPACING) { const px = x + (Math.random() - 0.5) * SPACING * 0.9; const py = y + (Math.random() - 0.5) * SPACING * 0.9; const p = pill(px, py); if (p.d > -1.5) continue; // fur lies down-and-right, and fans outward near the rim so the silhouette is fuzzy let a = 1.75 + (Math.random() - 0.5) * 0.7; let rx = Math.cos(a), ry = Math.sin(a); const edge = Math.max(0, 1 + p.d / 10); rx += p.nx * edge * 1.6; ry += p.ny * edge * 1.6; a = Math.hypot(rx, ry); rx /= a; ry /= a; const text = inText(px, py); out.push({ x: px, y: py, len: (text ? 4 : 8.5) + Math.random() * (text ? 2 : 5), curl: (Math.random() - 0.5) * 2.6, tone: Math.floor(Math.random() * 4), text, rx, ry, cx: rx, cy: ry, ux: rx, uy: ry, l: 1, lt: 1, }); } } return out.sort((a, b) => a.y - b.y); } export function FurButton({ children = "pet me", palette = PINK, onClick, className, type = "button", disabled = false, ref, ...rest }: Props) { const btnRef = useRef(null); useImperativeHandle(ref, () => btnRef.current!, []); const canvasRef = useRef(null); const bodyRef = useRef(null); const bodyAnimation = useRef(null); const api = useRef({ puff: () => {} }); const paletteRef = useRef(palette); paletteRef.current = palette; const paletteKey = JSON.stringify(palette); useEffect(() => { const canvas = canvasRef.current; const button = btnRef.current; if (!canvas || !button) return; const ctx = canvas.getContext("2d")!; const label = children; const strands = grow(label); let textAlpha = 0.9; const tones = [0, 1, 2].map((t) => strands.filter((s) => Math.min(s.tone, 2) === t && !s.text)); const tips = strands.filter((s, i) => i % 3 === 0 && !s.text); const lettering = strands.filter((s) => s.text); let raf = 0; let timer = 0; let relax = 0.025; let visible = true, previous = 0, disturbed = 0; let scale = 1; let rect = button.getBoundingClientRect(); let last = { x: 0, y: 0, t: 0 }; const reduced = window.matchMedia("(prefers-reduced-motion: reduce)"); const size = () => { rect = button.getBoundingClientRect(); scale = rect.width / W; // handles CSS zoom and transforms // Cap backing resolution; refresh it on resize and DPR changes. const dpr = Math.max(0.5, Math.min(2, (window.devicePixelRatio || 1) * scale)); canvas.width = Math.round((W + PAD * 2) * dpr); canvas.height = Math.round((H + PAD * 2) * dpr); ctx.setTransform(dpr, 0, 0, dpr, PAD * dpr, PAD * dpr); draw(); }; const draw = () => { const pal = paletteRef.current; ctx.clearRect(-PAD, -PAD, W + PAD * 2, H + PAD * 2); ctx.beginPath(); ctx.roundRect(1, 1, W - 2, H - 2, H / 2); ctx.fillStyle = pal.skin; ctx.fill(); ctx.lineCap = "round"; // straight segments: hair this short doesn't need curves, and lines are far cheaper to stroke const path = (list: Strand[], dx: number, dy: number, from = 0) => { ctx.beginPath(); let count = 0; for (const s of list) { // Small paths avoid expensive rasterization of thousands of overlapping subpaths. if (count++ === 16) { ctx.stroke(); ctx.beginPath(); count = 1; } const len = s.len * s.l; const ex = s.x + s.ux * len - s.uy * s.curl * 0.6, ey = s.y + s.uy * len + s.ux * s.curl * 0.6; ctx.moveTo(s.x + (ex - s.x) * from + dx, s.y + (ey - s.y) * from + dy); ctx.lineTo(ex + dx, ey + dy); } }; // depth: a dark under-pass, the fur in three tones, then a few light tips ctx.strokeStyle = pal.shadow; ctx.globalAlpha = 0.65; ctx.lineWidth = 1.25; path(strands, 0.45, 0.7); ctx.stroke(); ctx.globalAlpha = 1; ctx.lineWidth = 0.85; tones.forEach((list, tone) => { ctx.strokeStyle = pal.fur[[0, 1, 3][tone] % pal.fur.length]; path(list, 0, 0); ctx.stroke(); }); ctx.strokeStyle = "rgba(255,255,255,.5)"; ctx.lineWidth = 0.6; path(tips, 0, 0, 0.5); ctx.stroke(); // the label is pressed into the fur: flat ink, then short fuzz over it ctx.font = FONT; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.globalAlpha = textAlpha; ctx.fillStyle = pal.ink; ctx.fillText(label, W / 2, H / 2 + 1); ctx.strokeStyle = pal.shadow; ctx.lineWidth = 0.9; path(lettering, 0, 0); ctx.stroke(); ctx.globalAlpha = 1; }; const allowed = () => !disabled && !button.matches(":disabled") && visible && !document.hidden && !reduced.matches; const step = (now: number) => { raf = 0; if (!allowed()) { reset(); return; } const dt = Math.min(3, Math.max(0.25, (now - (previous || now - 16.67)) / 16.67)); previous = now; const decay = 1 - Math.pow(1 - relax, dt); const follow = 1 - Math.pow(0.72, dt); let moving = false; for (const s of strands) { s.cx += (s.rx - s.cx) * decay; s.cy += (s.ry - s.cy) * decay; const nx = s.ux + (s.cx - s.ux) * follow; const ny = s.uy + (s.cy - s.uy) * follow; const n = Math.hypot(nx, ny) || 1; s.ux = nx / n; s.uy = ny / n; s.l += (s.lt - s.l) * (1 - Math.pow(0.82, dt)); // Stop below a tenth of a CSS pixel at the tip, rather than summing tiny // errors over 2,000 strands. A stroke has a bounded three-second tail. const error = s.len * (Math.abs(s.rx - s.ux) + Math.abs(s.ry - s.uy) + Math.abs(s.lt - s.l)); if (error > 0.1 && now - disturbed < 3000) moving = true; else { s.cx = s.ux = s.rx; s.cy = s.uy = s.ry; s.l = s.lt; } } draw(); if (moving) raf = requestAnimationFrame(step); else previous = 0; }; const wake = () => { if (!raf && allowed()) raf = requestAnimationFrame(step); }; const reset = () => { cancelAnimationFrame(raf); raf = 0; previous = 0; window.clearTimeout(timer); bodyAnimation.current?.cancel(); textAlpha = 0.9; for (const s of strands) { s.cx = s.ux = s.rx; s.cy = s.uy = s.ry; s.l = s.lt = 1; } draw(); }; const move = (e: PointerEvent) => { if (!allowed()) return; const x = (e.clientX - rect.left) / scale; const y = (e.clientY - rect.top) / scale; const t = e.timeStamp; const dt = Math.max(8, t - last.t) / 1000; const vx = (x - last.x) / dt, vy = (y - last.y) / dt; last = { x, y, t }; const speed = Math.hypot(vx, vy); if (speed < 25 || pill(x, y).d > 18 || dt > 0.2) return; const radius = 17; for (const s of strands) { const dx = s.x - x, dy = s.y - y; const d = Math.hypot(dx, dy); if (d > radius) continue; const f = 1 - d / radius; // comb along the stroke, and part the fur right under the cursor const away = d < 7 ? 1.4 : 0.35; let px = vx / speed + (dx / (d || 1)) * away; let py = vy / speed + (dy / (d || 1)) * away; const n = Math.hypot(px, py) || 1; px /= n; py /= n; s.cx += (px - s.cx) * Math.min(1, f * 0.9); s.cy += (py - s.cy) * Math.min(1, f * 0.9); } relax = 0.025; disturbed = performance.now(); wake(); }; api.current.puff = () => { if (!allowed()) return; disturbed = performance.now(); for (const s of strands) { let ox = s.x - W / 2, oy = (s.y - H / 2) * 2.4; const n = Math.hypot(ox, oy) || 1; ox = ox / n + (Math.random() - 0.5) * 0.9; oy = oy / n + (Math.random() - 0.5) * 0.9; const m = Math.hypot(ox, oy) || 1; s.cx = ox / m; s.cy = oy / m; s.lt = s.text ? 1.25 : 1.55 + Math.random() * 0.35; } relax = 0.035; textAlpha = 0.35; window.clearTimeout(timer); timer = window.setTimeout(() => { for (const s of strands) s.lt = 1; relax = 0.025; disturbed = performance.now(); textAlpha = 0.9; wake(); }, 420); // it never quite goes back the same: leave a cowlick somewhere near the top const cx = 40 + Math.random() * (W - 80), cy = 12; for (const s of strands) { const dx = s.x - cx, dy = s.y - cy, d = Math.hypot(dx, dy); if (d > 13) continue; const a = Math.atan2(dy, dx) + 1.9; const k = 1 - d / 13; let rx = s.rx * (1 - k) + Math.cos(a) * k, ry = s.ry * (1 - k) + Math.sin(a) * k - 0.6 * k; const n = Math.hypot(rx, ry) || 1; rx /= n; ry /= n; s.rx = rx; s.ry = ry; } wake(); }; const geometry = () => { const next = button.getBoundingClientRect(); const nextScale = next.width / W || 1; if (Math.abs(nextScale - scale) > 0.001) size(); else rect = next; }; 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(); const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(size); ro?.observe(button); window.addEventListener("pointermove", move, { passive: true }); window.addEventListener("scroll", geometry, true); window.addEventListener("resize", size); button.addEventListener("pointerenter", geometry); document.addEventListener("visibilitychange", visibility); reduced.addEventListener("change", visibility); return () => { reset(); io?.disconnect(); dprQuery.removeEventListener("change", watchDpr); ro?.disconnect(); window.removeEventListener("pointermove", move); window.removeEventListener("scroll", geometry, true); window.removeEventListener("resize", size); button.removeEventListener("pointerenter", geometry); document.removeEventListener("visibilitychange", visibility); reduced.removeEventListener("change", visibility); api.current.puff = () => {}; }; }, [children, disabled, paletteKey]); const click = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; api.current.puff(); if (!window.matchMedia("(prefers-reduced-motion: reduce)").matches) { bodyAnimation.current?.cancel(); bodyAnimation.current = bodyRef.current?.animate( [ { transform: "scale(1,1)" }, { transform: "scale(1.1,.86) translateY(3px)", offset: 0.18 }, { transform: "scale(.96,1.07) translateY(-4px)", offset: 0.42 }, { transform: "scale(1.02,.98)", offset: 0.7 }, { transform: "scale(1,1)" }, ], { duration: 620, easing: "ease-out" }, ) ?? null; } }; return ( ); } export default FurButton; const css = ` .tbf-wrap{display:inline-flex} .tbf-btn{position:relative;width:${W}px;height:${H}px;padding:0;border:0;background:none;cursor:pointer;-webkit-tap-highlight-color:transparent; border-radius:${H / 2}px} .tbf-btn:disabled{cursor:not-allowed;opacity:.6;filter:saturate(.5)} .tbf-btn:focus-visible{outline:3px solid #f2a3c1;outline-offset:${PAD - 2}px} .tbf-body{position:absolute;inset:0;transform-origin:50% 100%} .tbf-canvas{position:absolute;left:${-PAD}px;top:${-PAD}px;width:calc(100% + ${PAD * 2}px);height:calc(100% + ${PAD * 2}px)} .tbf-shadow{position:absolute;left:6%;right:6%;bottom:-14px;height:26px;border-radius:50%;pointer-events:none; background:radial-gradient(closest-side,rgba(200,90,140,.32),rgba(200,90,140,0))} `;