"use client"; /** * critter.tsx — something lives behind this button. * Hover and it peeks over the edge, eyes following your cursor. Click to boop it. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useId, useRef, useState, useImperativeHandle, type ButtonHTMLAttributes, type Ref, type RefObject, type MouseEvent, type ReactNode, } from "react"; type Props = Omit, "children"> & { children?: ReactNode; ref?: Ref; /** fur color */ fur?: string; }; const EYES = [ { x: 37, y: 46 }, { x: 63, y: 46 }, ]; const HEART = ''; export function CritterButton({ children = "boop", fur = "#ff8a65", onClick, className, type = "button", disabled = false, ref, style, ...rest }: Props) { const btnRef = useRef(null); useImperativeHandle(ref, () => btnRef.current!, []); const [happy, setHappy] = useState(false); const leanRef = useRef(null); const squishRef = useRef(null); const heartsRef = useRef(null); const pupils = useRef<(SVGGElement | null)[]>([]); const look = useRef(EYES.map(() => ({ x: 0, y: 0 }))); const lean = useRef(0); const work = useWork(disabled, () => setHappy(false)); const happyTimer = useRef(0); const uid = `tbk-${useId()}`; // Cache the resting creature anchor; its own lean must not move the target. usePointerMotion(btnRef, disabled, (r, x, y, hover, scale) => { const near = Math.hypot(x - r.left - r.width / 2, y - r.top) < 400; const left = r.left + r.width / 2 - 48 * scale; const top = r.bottom - (hover ? 124 : 70) * scale; let error = 0; EYES.forEach((eye, i) => { const dx = x - (left + eye.x * 0.96 * scale); const dy = y - (top + eye.y * (88 / 92) * scale); const d = Math.hypot(dx, dy) || 1; const m = near ? Math.min(4.2, d / 25) : 0; const tx = (dx / d) * m, ty = (dy / d) * m; const p = look.current[i]; p.x += (tx - p.x) * 0.25; p.y += (ty - p.y) * 0.25; error += Math.abs(tx - p.x) + Math.abs(ty - p.y); pupils.current[i]?.setAttribute("transform", `translate(${p.x.toFixed(2)} ${p.y.toFixed(2)})`); }); const target = near ? Math.max(-9, Math.min(9, (x - r.left - r.width / 2) * 0.05)) : 0; lean.current += (target - lean.current) * 0.1; if (leanRef.current) leanRef.current.style.transform = `rotate(${lean.current.toFixed(2)}deg)`; return error + Math.abs(target - lean.current) < 0.01; }); const boop = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; setHappy(true); work.cancel(happyTimer.current); happyTimer.current = work.later(() => setHappy(false), 1100); if (work.reduced()) return; work.animate(squishRef.current, [ { transform: "scale(1,1)" }, { transform: "scale(1.16,.8)", offset: 0.2 }, { transform: "scale(.94,1.1)", offset: 0.45 }, { transform: "scale(1.03,.97)", offset: 0.7 }, { transform: "scale(1,1)" }, ], { duration: 650, easing: "ease-out" }, ); const layer = heartsRef.current; if (!layer) return; layer.querySelectorAll(".tbk-heart").forEach((el) => { el.getAnimations().forEach((a) => a.cancel()); el.remove(); }); [-1, 1, 0].forEach((side, i) => { const h = document.createElement("span"); h.className = "tbk-heart"; h.innerHTML = HEART; h.style.width = h.style.height = `${[14, 12, 18][i]}px`; layer.append(h); const drift = side * (14 + Math.random() * 10); work.animate(h, [ { transform: "translate(-50%,0) scale(.2) rotate(0deg)", opacity: 0 }, { transform: `translate(calc(-50% + ${drift * 0.5}px),-26px) scale(1) rotate(${side * 8}deg)`, opacity: 1, offset: 0.3 }, { transform: `translate(calc(-50% + ${drift}px),-74px) scale(.8) rotate(${side * -6}deg)`, opacity: 0 }, ], { duration: 1100, delay: i * 110, easing: "cubic-bezier(.2,.7,.4,1)", fill: "both" }, undefined, true); }); }; return ( ); } export default CritterButton; // Each file stays copyable: all animation ownership lives with this instance. function useWork(disabled: boolean, reset: () => void) { const state = useRef({ epoch: 0, active: false, timers: new Set(), animations: new Map() }); const resetRef = useRef(reset); resetRef.current = reset; useEffect(() => { const s = state.current; const clear = () => { s.epoch++; s.timers.forEach((id) => window.clearTimeout(id)); s.timers.clear(); s.animations.forEach(({ el, remove }, a) => { a.cancel(); if (remove) el.remove(); }); s.animations.clear(); }; s.active = !disabled; if (disabled) resetRef.current(); const media = window.matchMedia("(prefers-reduced-motion: reduce)"); const change = () => { clear(); resetRef.current(); }; media.addEventListener("change", change); return () => { s.active = false; clear(); media.removeEventListener("change", change); }; }, [disabled]); const later = (done: () => void, ms: number) => { const s = state.current; const epoch = s.epoch; const id = window.setTimeout(() => { s.timers.delete(id); if (s.active && s.epoch === epoch) done(); }, ms); s.timers.add(id); return id; }; const animate = (el: Element | null, frames: Keyframe[], timing: KeyframeAnimationOptions, done?: () => void, remove = false) => { const s = state.current; if (!s.active) return; s.animations.forEach((entry, a) => { if (entry.el === el) { a.cancel(); s.animations.delete(a); } }); if (!el) { done?.(); return; } const epoch = s.epoch; const a = el.animate(frames, timing); s.animations.set(a, { el, remove }); const finish = () => { if (remove) { el.remove(); a.cancel(); } if (remove || done || (timing.fill !== "forwards" && timing.fill !== "both")) s.animations.delete(a); }; a.finished.then(() => { finish(); if (s.active && s.epoch === epoch) done?.(); if (done) a.cancel(); }, () => { if (remove) el.remove(); s.animations.delete(a); }); }; const cancelAnimations = (el: Element) => { state.current.animations.forEach((entry, a) => { if (entry.el === el) { a.cancel(); if (entry.remove) el.remove(); state.current.animations.delete(a); } }); }; return { later, animate, cancelAnimations, cancel: (id: number) => { window.clearTimeout(id); state.current.timers.delete(id); }, reduced: () => window.matchMedia("(prefers-reduced-motion: reduce)").matches, }; } // Cache geometry until layout changes; stop the spring once it settles. function usePointerMotion( ref: RefObject, disabled: boolean, step: (r: DOMRect, x: number, y: number, hover: boolean, scale: number) => boolean, ) { const stepRef = useRef(step); stepRef.current = step; const wake = useRef(() => {}); useEffect(() => { const button = ref.current; const wrap = button?.parentElement; if (!button || !wrap) return; let raf = 0, dirty = true, visible = true, hover = button.matches(":hover"); let x = -1e4, y = -1e4, scale = 1, wasNear = false; let rect: DOMRect | undefined; const media = window.matchMedia("(prefers-reduced-motion: reduce)"); const allowed = () => !disabled && !button.matches(":disabled") && visible && !document.hidden && !media.matches; const tick = () => { raf = 0; if (!allowed()) return; if (dirty) { rect = button.getBoundingClientRect(); scale = rect.width / (button.offsetWidth || 1); dirty = false; } if (!stepRef.current(rect!, x, y, hover, scale)) raf = requestAnimationFrame(tick); }; const start = () => { if (!raf && allowed()) raf = requestAnimationFrame(tick); }; wake.current = start; const pause = () => { wrap.dataset.tbPaused = String(disabled || !visible || document.hidden); if (!allowed()) { cancelAnimationFrame(raf); raf = 0; } else { dirty = true; start(); } }; const invalidate = () => { dirty = true; start(); }; const move = (e: PointerEvent) => { x = e.clientX; y = e.clientY; const near = hover || !rect || (x >= rect.left - 400 && x <= rect.right + 400 && y >= rect.top - 400 && y <= rect.bottom + 400); if (near || wasNear) start(); wasNear = near; }; const enter = (e: PointerEvent) => { hover = true; dirty = true; move(e); }; const leave = () => { hover = false; start(); }; const gone = () => { x = y = -1e4; hover = false; start(); }; const observer = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; pause(); }); observer?.observe(wrap); const resize = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(invalidate); resize?.observe(button); window.addEventListener("pointermove", move, { passive: true }); window.addEventListener("resize", invalidate); window.addEventListener("scroll", invalidate, true); document.documentElement.addEventListener("pointerleave", gone); document.addEventListener("visibilitychange", pause); button.addEventListener("pointerenter", enter); button.addEventListener("pointerleave", leave); button.addEventListener("transitionend", invalidate); media.addEventListener("change", pause); pause(); return () => { wake.current = () => {}; cancelAnimationFrame(raf); observer?.disconnect(); resize?.disconnect(); window.removeEventListener("pointermove", move); window.removeEventListener("resize", invalidate); window.removeEventListener("scroll", invalidate, true); document.documentElement.removeEventListener("pointerleave", gone); document.removeEventListener("visibilitychange", pause); button.removeEventListener("pointerenter", enter); button.removeEventListener("pointerleave", leave); button.removeEventListener("transitionend", invalidate); media.removeEventListener("change", pause); }; }, [disabled, ref]); return wake; } const css = ` .tbk-wrap{display:inline-flex;padding-top:70px} .tbk-btn{position:relative;width:180px;height:58px;padding:0;border:0;background:none;cursor:pointer;isolation:isolate;-webkit-tap-highlight-color:transparent; font:700 18px/1 ui-rounded,"SF Pro Rounded","Nunito","Segoe UI",system-ui,sans-serif;letter-spacing:.02em;color:#fff} .tbk-btn:focus-visible{outline:none} .tbk-btn:focus-visible .tbk-face{outline:3px solid #ffb199;outline-offset:3px} .tbk-peek{position:absolute;left:50%;bottom:20px;width:140px;height:130px;margin-left:-70px;overflow:hidden;z-index:0;pointer-events:none} .tbk-rise{position:absolute;left:50%;bottom:16px;width:96px;height:88px;margin-left:-48px;transform:translateY(54px); transition:transform .22s cubic-bezier(.5,0,.9,.5)} .tbk-btn:enabled:hover .tbk-rise,.tbk-btn:focus-visible .tbk-rise{transform:translateY(0);transition:transform .5s cubic-bezier(.3,1.5,.55,1)} .tbk-lean,.tbk-squish{position:absolute;inset:0;transform-origin:50% 100%} .tbk-critter{width:100%;height:100%;overflow:visible;pointer-events:auto} .tbk-antenna path{fill:none;stroke:var(--tbk-fur);stroke-width:3.2;stroke-linecap:round;filter:brightness(.88)} .tbk-antenna circle{fill:#ffd166} .tbk-antenna{transform-box:fill-box;animation:tbk-sway 2.6s ease-in-out infinite} .tbk-antenna-l{transform-origin:100% 100%} .tbk-antenna-r{transform-origin:0 100%;animation-delay:-1.3s} .tbk-btn:enabled:hover .tbk-antenna{animation-duration:.7s} .tbk-eye{transform-box:fill-box;transform-origin:center;animation:tbk-blink 4.2s infinite} .tbk-happy-eye{fill:none;stroke:#24202e;stroke-width:3;stroke-linecap:round;opacity:0} .tbk-cheek{fill:#ff5c8a;opacity:0;transition:opacity .2s} .tbk-mouth{fill:none;stroke:#5a2a1e;stroke-width:2.4;stroke-linecap:round} .tbk-mouth-open{fill:#7a2c22;opacity:0} .tbk-btn[data-happy=true] .tbk-eye{opacity:0} .tbk-btn[data-happy=true] .tbk-happy-eye,.tbk-btn[data-happy=true] .tbk-mouth-open{opacity:1} .tbk-btn[data-happy=true] .tbk-mouth{opacity:0} .tbk-btn[data-happy=true] .tbk-cheek{opacity:.55} .tbk-hearts{position:absolute;left:50%;top:-56px;width:0;height:0;z-index:3;pointer-events:none} .tbk-heart{position:absolute;left:0;top:0;color:#ff5c8a;filter:drop-shadow(0 2px 2px rgba(255,92,138,.3))} .tbk-face{position:absolute;inset:0;z-index:1;display:flex;align-items:center;justify-content:center;border-radius:16px; background:linear-gradient(180deg,#3d3854,#2b2740); box-shadow:inset 0 1px 0 rgba(255,255,255,.14),0 5px 0 #1b1828,0 14px 22px -8px rgba(27,24,40,.55); transition:transform .12s,box-shadow .12s} .tbk-btn:enabled:active .tbk-face{transform:translateY(4px);box-shadow:inset 0 1px 0 rgba(255,255,255,.14),0 1px 0 #1b1828,0 6px 12px -6px rgba(27,24,40,.5)} .tbk-paw{position:absolute;top:-7px;width:22px;height:14px;border-radius:10px 10px 7px 7px;background:var(--tbk-fur); box-shadow:inset 0 -2px 0 rgba(0,0,0,.12),0 2px 3px rgba(0,0,0,.18);opacity:0;transform:translateY(10px) scale(.5); transition:opacity .12s,transform .18s ease-in} .tbk-paw::after{content:"";position:absolute;left:5px;right:5px;bottom:1px;height:6px; background:linear-gradient(90deg,transparent 3px,rgba(90,30,15,.35) 3px 4.5px,transparent 4.5px 7.5px,rgba(90,30,15,.35) 7.5px 9px,transparent 9px)} .tbk-paw-l{left:44px} .tbk-paw-r{right:44px} .tbk-btn:enabled:hover .tbk-paw,.tbk-btn:focus-visible .tbk-paw{opacity:1;transform:none;transition:opacity .1s .18s,transform .35s .18s cubic-bezier(.3,1.6,.5,1)} @keyframes tbk-sway{0%,100%{transform:rotate(-6deg)}50%{transform:rotate(6deg)}} @keyframes tbk-blink{0%,92%,100%{transform:scaleY(1)}95%{transform:scaleY(.1)}} @media (prefers-reduced-motion:reduce){.tbk-antenna,.tbk-eye{animation:none}} .tbk-btn:disabled{cursor:default;transition:none} .tbk-wrap[data-tb-paused=true] *{animation-play-state:paused!important} .tbk-btn:disabled *{transition:none!important;animation:none!important} @media (prefers-reduced-motion:reduce){.tbk-wrap *, .tbk-wrap *::before, .tbk-wrap *::after{animation:none!important;transition:none!important}} .tbk-btn:disabled .tbk-lean{transform:none!important} @media (prefers-reduced-motion:reduce){.tbk-lean{transform:none!important}} `;