"use client"; /** * cookie.tsx — the only cookie banner button you'll enjoy. * Every click takes a bite (where you clicked) and sprays crumbs. Finish it and a fresh one bakes in. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useId, useImperativeHandle, useRef, useState, type ButtonHTMLAttributes, type MouseEvent, type PointerEvent, type Ref, } from "react"; type Props = Omit, "children"> & { /** piped onto the cookie in icing (plain text only) */ children?: string; ref?: Ref; /** how many bites until it's gone */ bites?: number; /** shown for a moment once the cookie is finished */ doneLabel?: string; /** called when the last bite is taken */ onEaten?: () => void; }; const W = 240; const H = 76; const R = 34; // end-cap radius const CX = W / 2; const CY = H / 2; // deterministic noise so server and client render the same cookie 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; }; } /** nearest point on the cookie's rim to (x, y), plus the outward normal there */ function rim(x: number, y: number) { const left = CX - (W / 2 - R - 4); const right = CX + (W / 2 - R - 4); const cx = Math.min(right, Math.max(left, x)); let nx = x - cx; let ny = y - CY; if (cx === x) ny = y < CY ? -1 : 1, nx = 0; const d = Math.hypot(nx, ny) || 1; nx /= d; ny /= d; return { x: cx + nx * R, y: CY + ny * R, nx, ny }; } const SHAPE = (() => { const r = rng(7); const pts: [number, number][] = []; const left = CX - (W / 2 - R - 4); const right = CX + (W / 2 - R - 4); const len = 2 * (right - left) + 2 * Math.PI * R; for (let i = 0; i < 90; i++) { let s = (i / 90) * len; let p: [number, number]; let n: [number, number]; if (s < right - left) p = [left + s, CY - R], n = [0, -1]; else if ((s -= right - left) < Math.PI * R) { const a = -Math.PI / 2 + s / R; p = [right + Math.cos(a) * R, CY + Math.sin(a) * R], n = [Math.cos(a), Math.sin(a)]; } else if ((s -= Math.PI * R) < right - left) p = [right - s, CY + R], n = [0, 1]; else { const a = Math.PI / 2 + (s - (right - left)) / R; p = [left + Math.cos(a) * R, CY + Math.sin(a) * R], n = [Math.cos(a), Math.sin(a)]; } const wob = (r() - 0.5) * 2.6; pts.push([p[0] + n[0] * wob, p[1] + n[1] * wob]); } // smooth closed curve through the points let d = `M${pts[0][0].toFixed(1)} ${pts[0][1].toFixed(1)}`; for (let i = 0; i < pts.length; i++) { const p0 = pts[(i - 1 + pts.length) % pts.length], p1 = pts[i]; const p2 = pts[(i + 1) % pts.length], p3 = pts[(i + 2) % pts.length]; d += `C${(p1[0] + (p2[0] - p0[0]) / 6).toFixed(1)} ${(p1[1] + (p2[1] - p0[1]) / 6).toFixed(1)} ${(p2[0] - (p3[0] - p1[0]) / 6).toFixed(1)} ${(p2[1] - (p3[1] - p1[1]) / 6).toFixed(1)} ${p2[0].toFixed(1)} ${p2[1].toFixed(1)}`; } return `${d}Z`; })(); const CHIPS = (() => { const r = rng(21); const spots = [ [30, 22], [52, 56], [74, 16], [96, 60], [122, 14], [150, 61], [170, 18], [196, 54], [214, 30], [24, 46], [136, 64], [110, 30], [184, 38], ]; return spots.map(([x, y]) => { const n = 7; const s = 3.6 + r() * 2.4; let d = ""; for (let i = 0; i < n; i++) { const a = (i / n) * Math.PI * 2; const rr = s * (0.75 + r() * 0.45); d += `${i ? "L" : "M"}${(x + Math.cos(a) * rr).toFixed(1)} ${(y + Math.sin(a) * rr * 0.85).toFixed(1)}`; } return `${d}Z`; }); })(); const SPECKS = (() => { const r = rng(99); return Array.from({ length: 70 }, () => ({ x: 10 + r() * (W - 20), y: 8 + r() * (H - 16), r: 0.7 + r() * 1.6, light: r() > 0.45, })); })(); // where keyboard bites land, in order const KEY_BITES = [[232, 20], [232, 60], [180, 0], [170, 76], [110, 0], [100, 76], [40, 10], [10, 50]]; type Bite = { id: number; x: number; y: number; r: number; teeth: [number, number][] }; function makeBite(id: number, px: number, py: number): Bite { const e = rim(px, py); const r = 23 + Math.random() * 5; const x = e.x + e.nx * 3; const y = e.y + e.ny * 3; const inward = Math.atan2(-e.ny, -e.nx); const teeth = Array.from({ length: 7 }, (_, i): [number, number] => { const a = inward + ((i - 3) / 3) * 1.25; return [x + Math.cos(a) * r, y + Math.sin(a) * r]; }); return { id, x, y, r, teeth }; } const CRUMB_COLORS = ["#d99a4e", "#c9853d", "#e8b874", "#b8732f", "#4a2a17"]; export function CookieButton({ children = "accept cookies", bites: maxBites = 6, doneLabel = "cookies accepted", onEaten, onClick, onPointerEnter, onPointerLeave, className, type = "button", disabled = false, ref, ...rest }: Props) { const btnRef = useRef(null); useImperativeHandle(ref, () => btnRef.current!, []); const [bites, setBites] = useState([]); const [phase, setPhase] = useState<"cookie" | "gone" | "fresh">("cookie"); const bodyRef = useRef(null); const fxRef = useRef(null); const timers = useRef(new Set()); const nibble = useRef(0); const animations = useRef(new Set()); const biteRef = useRef([]); const finishing = useRef(false); const serial = useRef(0); const visible = useRef(true); const hovering = useRef(false); const liveDisabled = useRef(disabled); liveDisabled.current = disabled; const onEatenRef = useRef(onEaten); onEatenRef.current = onEaten; const phaseRef = useRef(phase); phaseRef.current = phase; const uid = `tbo-${useId().replace(/[^a-zA-Z0-9]/g, "")}`; const later = (fn: () => void, ms: number) => { const id = window.setTimeout(() => { timers.current.delete(id); if (liveDisabled.current || btnRef.current?.matches(":disabled")) return; fn(); }, ms); timers.current.add(id); return id; }; const reduced = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches; const canAnimate = () => !liveDisabled.current && !btnRef.current?.matches(":disabled") && visible.current && !document.hidden && !reduced(); const clearEffects = () => { window.clearInterval(nibble.current); nibble.current = 0; animations.current.forEach((a) => a.cancel()); animations.current.clear(); fxRef.current?.replaceChildren(); }; const animate = (el: HTMLElement, frames: Keyframe[], options: KeyframeAnimationOptions, remove = false) => { const a = el.animate(frames, options); animations.current.add(a); const finish = () => { animations.current.delete(a); if (remove) el.remove(); }; a.finished.then(() => { finish(); a.cancel(); }, finish); }; useEffect(() => { const media = matchMedia("(prefers-reduced-motion: reduce)"); const update = () => { clearEffects(); if (hovering.current && canAnimate()) startNibble(); }; const io = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([entry]) => { visible.current = entry.isIntersecting; update(); }); if (btnRef.current) io?.observe(btnRef.current); document.addEventListener("visibilitychange", update); media.addEventListener("change", update); return () => { io?.disconnect(); document.removeEventListener("visibilitychange", update); media.removeEventListener("change", update); timers.current.forEach((id) => window.clearTimeout(id)); timers.current.clear(); clearEffects(); }; }, []); useEffect(() => { if (!disabled) return; clearEffects(); timers.current.forEach((id) => window.clearTimeout(id)); timers.current.clear(); finishing.current = false; biteRef.current = []; phaseRef.current = "cookie"; setBites([]); setPhase("cookie"); }, [disabled]); /** a crumb flies, bounces once or twice on the "table", rests, then fades */ const crumb = (x: number, y: number, dir: number, power = 1) => { const fx = fxRef.current; if (!fx || !canAnimate() || fx.childElementCount >= 120) return; const el = document.createElement("span"); const size = 2.5 + Math.random() * 5 * power; el.className = "tbo-crumb"; el.style.width = `${size}px`; el.style.height = `${size * (0.7 + Math.random() * 0.5)}px`; el.style.background = CRUMB_COLORS[Math.random() < 0.18 ? 4 : Math.floor(Math.random() * 4)]; el.style.borderRadius = `${30 + Math.random() * 40}% ${30 + Math.random() * 40}% ${30 + Math.random() * 40}% ${30 + Math.random() * 40}%`; fx.append(el); const floor = H + 12 + Math.random() * 6; let px = x, py = y, t = 0; let vx = (dir + (Math.random() - 0.5) * 1.4) * (30 + Math.random() * 80) * power; let vy = -(60 + Math.random() * 190) * power; let rot = 0; const spin = (Math.random() - 0.5) * 900; const frames: Keyframe[] = []; for (let step = 0; step < 240; step++) { if (step % 3 === 0) frames.push({ transform: `translate(${px.toFixed(1)}px,${py.toFixed(1)}px) rotate(${rot.toFixed(0)}deg)` }); const dt = 1 / 60; vy += 1300 * dt; px += vx * dt; py += vy * dt; rot += spin * dt; t += dt; if (py > floor) { py = floor; if (Math.abs(vy) < 90) break; vy *= -0.32; vx *= 0.55; } } const fly = t * 1000; const hold = 900 + Math.random() * 500; const total = fly + hold + 450; const last = frames[frames.length - 1].transform as string; frames.forEach((f, i) => (f.offset = ((i / (frames.length - 1)) * fly) / total)); frames.push({ transform: last, opacity: 1, offset: (fly + hold) / total }, { transform: last, opacity: 0, offset: 1 }); animate(el, frames, { duration: total, fill: "forwards" }, true); }; const bite = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented || phaseRef.current !== "cookie" || finishing.current) return; const r = e.currentTarget.getBoundingClientRect(); const k = W / r.width; const keyboard = e.detail === 0; const [px, py] = keyboard ? KEY_BITES[biteRef.current.length % KEY_BITES.length] : [(e.clientX - r.left) * k, (e.clientY - r.top) * k]; const b = makeBite(++serial.current, px, py); const next = [...biteRef.current, b]; biteRef.current = next; setBites(next); if (canAnimate() && bodyRef.current) { bodyRef.current.getAnimations().forEach((a) => a.cancel()); animate(bodyRef.current, [ { transform: "translate(0,0) scale(1,1)" }, { transform: `translate(${-Math.sign(b.x - CX) * 3}px,1px) scale(1.02,.96)`, offset: 0.3 }, { transform: `translate(${Math.sign(b.x - CX) * 1.5}px,0) scale(.99,1.01)`, offset: 0.65 }, { transform: "translate(0,0) scale(1,1)" }, ], { duration: 220, easing: "ease-out" }, ); const e2 = rim(b.x, b.y); for (let i = 0; i < 12; i++) crumb(e2.x - e2.nx * 4, e2.y - e2.ny * 4, e2.nx * 0.9, 1); } const limit = Number.isFinite(maxBites) ? Math.max(1, Math.floor(maxBites)) : 6; if (next.length < limit) return; finishing.current = true; later(() => { phaseRef.current = "gone"; setPhase("gone"); if (canAnimate()) for (let i = 0; i < 26; i++) crumb(30 + Math.random() * (W - 60), 14 + Math.random() * (H - 28), (Math.random() - 0.5) * 2, 0.8); later(() => { biteRef.current = []; setBites([]); phaseRef.current = "fresh"; setPhase("fresh"); later(() => { phaseRef.current = "cookie"; finishing.current = false; setPhase("cookie"); }, 900); }, 1700); onEatenRef.current?.(); }, 160); }; function startNibble() { window.clearInterval(nibble.current); if (!canAnimate()) return; nibble.current = window.setInterval(() => { if (!canAnimate()) { clearEffects(); return; } if (phaseRef.current === "gone") return; crumb(40 + Math.random() * (W - 80), H - 6, (Math.random() - 0.5) * 0.6, 0.45); }, 380); } const enter = (e: PointerEvent) => { onPointerEnter?.(e); hovering.current = true; if (!e.defaultPrevented) startNibble(); }; const leave = (e: PointerEvent) => { onPointerLeave?.(e); hovering.current = false; window.clearInterval(nibble.current); nibble.current = 0; }; return ( {phase === "gone" ? doneLabel : ""} ); } export default CookieButton; const css = ` .tbo-wrap{display:inline-flex;padding-bottom:20px} .tbo-btn{position:relative;width:240px;height:76px;padding:0;border:0;background:none;cursor:pointer;-webkit-tap-highlight-color:transparent} .tbo-btn:disabled{cursor:not-allowed;opacity:.6} .tbo-btn:focus-visible{outline:2px dashed #b8722e;outline-offset:4px;border-radius:40px} .tbo-lift{position:absolute;inset:0;transition:transform .3s cubic-bezier(.3,1.6,.5,1)} .tbo-btn:not(:disabled):hover .tbo-lift{transform:translateY(-3px) rotate(-1.2deg)} .tbo-btn:not(:disabled):active .tbo-lift{transform:translateY(0) scale(.98)} .tbo-body{position:absolute;inset:0;transition:opacity .25s,transform .25s} .tbo-svg{position:absolute;left:-6px;top:-6px;width:calc(100% + 12px);height:calc(100% + 12px);overflow:visible; filter:drop-shadow(0 10px 12px rgba(120,60,10,.22)) drop-shadow(0 2px 2px rgba(120,60,10,.25))} .tbo-icing{text-anchor:middle;font:700 21px/1 "Segoe Print","Bradley Hand","Chalkboard SE","Comic Sans MS",cursive; fill:#fffaf0;stroke:#fffaf0;stroke-width:1.4;stroke-linejoin:round;paint-order:stroke} .tbo-bite{transform-box:view-box;animation:tbo-chomp .11s cubic-bezier(.2,.9,.3,1.2) both} .tbo-btn[data-phase=gone] .tbo-body{opacity:0;transform:scale(.9)} .tbo-btn[data-phase=fresh] .tbo-body{animation:tbo-bake .8s cubic-bezier(.3,1.4,.5,1) both} .tbo-done{position:absolute;left:50%;top:50%;display:inline-flex;align-items:center;gap:6px;white-space:nowrap; transform:translate(-50%,-50%) scale(.9);opacity:0;pointer-events:none;transition:opacity .25s,transform .35s cubic-bezier(.3,1.6,.5,1); font:650 15px/1 ui-rounded,"SF Pro Rounded","Nunito","Segoe UI",system-ui,sans-serif;color:#8a5a2b} .tbo-done svg{width:18px;height:18px} .tbo-btn[data-phase=gone] .tbo-done{opacity:1;transform:translate(-50%,-50%) scale(1);transition-delay:.25s} .tbo-fx{position:absolute;left:0;top:0;width:0;height:0;pointer-events:none} .tbo-crumb{position:absolute;left:0;top:0;margin:-2px 0 0 -2px;box-shadow:inset -1px -1px 0 rgba(0,0,0,.18)} .tbo-steam{position:absolute;left:50%;bottom:70%;width:120px;height:60px;margin-left:-60px;overflow:visible;pointer-events:none} .tbo-steam path{fill:none;stroke:#cfc6bd;stroke-width:3.5;stroke-linecap:round;stroke-dasharray:90;stroke-dashoffset:90; filter:blur(1.5px);opacity:0;animation:tbo-steam 1.4s ease-out forwards} @keyframes tbo-chomp{from{transform:scale(0)}to{transform:scale(1)}} @keyframes tbo-bake{0%{transform:scale(.6);opacity:0;filter:brightness(1.6) saturate(.4)}55%{transform:scale(1.05);opacity:1}100%{transform:scale(1);filter:none}} @keyframes tbo-steam{0%{stroke-dashoffset:90;opacity:0;transform:translateY(0)}20%{opacity:.8}100%{stroke-dashoffset:0;opacity:0;transform:translateY(-22px)}} .tbo-status{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap} .tbo-btn:disabled *{animation:none!important;transition:none!important} @media (prefers-reduced-motion:reduce){.tbo-lift,.tbo-body,.tbo-done{transition:none}.tbo-btn:not(:disabled):hover .tbo-lift,.tbo-btn:not(:disabled):active .tbo-lift{transform:none}.tbo-bite,.tbo-btn[data-phase=fresh] .tbo-body,.tbo-steam path{animation:none}.tbo-steam{display:none}} `;