"use client"; /** * bubble.tsx — a soap-bubble button. * It wobbles toward your cursor like jelly. Click to pop it; a fresh one blows back in. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useRef, useState, useImperativeHandle, type ButtonHTMLAttributes, type Ref, type RefObject, type MouseEvent, type ReactNode, } from "react"; type Props = Omit, "children"> & { children?: ReactNode; ref?: Ref; }; const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); export function BubbleButton({ children = "pop", onClick, className, type = "button", disabled = false, ref, ...rest }: Props) { const [popped, setPopped] = useState(false); const btnRef = useRef(null); useImperativeHandle(ref, () => btnRef.current!, []); const jellyRef = useRef(null); const lifeRef = useRef(null); const labelRef = useRef(null); const fxRef = useRef(null); const busy = useRef(false); const s = useRef({ x: 0, y: 0, k: 0, vx: 0, vy: 0, vk: 0, a: 0 }); const work = useWork(disabled, () => { busy.current = false; setPopped(false); }); // Springy jelly keeps its original spring constants, but sleeps at rest. const wake = usePointerMotion(btnRef, disabled, (r, x, y, hover) => { const dx = x - (r.left + r.width / 2); const dy = y - (r.top + r.height / 2); const sp = s.current; const on = hover && !busy.current; const tx = on ? clamp(dx * 0.1, -10, 10) : 0; const ty = on ? clamp(dy * 0.16, -7, 7) : 0; const tk = on ? 0.06 : 0; if (on) sp.a = (Math.atan2(dy, dx) * 180) / Math.PI; sp.vx = (sp.vx + (tx - sp.x) * 0.08) * 0.84; sp.vy = (sp.vy + (ty - sp.y) * 0.08) * 0.84; sp.vk = (sp.vk + (tk - sp.k) * 0.1) * 0.8; sp.x += sp.vx; sp.y += sp.vy; sp.k += sp.vk; if (jellyRef.current) jellyRef.current.style.transform = `translate(${sp.x.toFixed(2)}px,${sp.y.toFixed(2)}px) rotate(${sp.a.toFixed(1)}deg) scale(${(1 + sp.k).toFixed(4)},${(1 - sp.k * 0.8).toFixed(4)}) rotate(${(-sp.a).toFixed(1)}deg)`; return Math.abs(tx - sp.x) + Math.abs(ty - sp.y) + Math.abs(sp.vx) + Math.abs(sp.vy) < 0.01 && Math.abs(tk - sp.k) + Math.abs(sp.vk) < 0.0001; }); const pop = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; const b = btnRef.current; const life = lifeRef.current; const fx = fxRef.current; if (busy.current || !b || !life || !fx) return; busy.current = true; setPopped(true); wake.current(); if (work.reduced()) { work.later(() => { setPopped(false); busy.current = false; }, 1050); return; } const W = b.offsetWidth; const H = b.offsetHeight; work.animate(life, [{ transform: "scale(1)", opacity: 1 }, { transform: "scale(1.12)", opacity: 0 }], { duration: 80, easing: "ease-out", fill: "forwards" }, ); // a quick flash of the film const ring = document.createElement("span"); ring.className = "tbb-ring"; fx.append(ring); work.animate(ring, [{ transform: "scale(1)", opacity: 0.9 }, { transform: "scale(1.35, 1.6)", opacity: 0 }], { duration: 260, easing: "cubic-bezier(.2,.7,.3,1)", fill: "forwards", }, undefined, true); // droplets thrown off the rim, then gravity for (let i = 0; i < 20; i++) { const t = (i / 20) * Math.PI * 2 + Math.random() * 0.3; const x0 = (Math.cos(t) * W) / 2; const y0 = (Math.sin(t) * H) / 2; const speed = 110 + Math.random() * 170; const vx = Math.cos(t) * speed * 1.3; const vy = Math.sin(t) * speed - 120; const dur = 650 + Math.random() * 450; const size = 5 + Math.random() * 8; const drop = document.createElement("span"); drop.className = "tbb-drop"; drop.style.width = drop.style.height = `${size}px`; drop.style.margin = `${-size / 2}px 0 0 ${-size / 2}px`; fx.append(drop); const frames: Keyframe[] = []; for (let k = 0; k <= 14; k++) { const tt = ((k / 14) * dur) / 1000; frames.push({ transform: `translate(${(x0 + vx * tt).toFixed(1)}px,${(y0 + vy * tt + 450 * tt * tt).toFixed(1)}px) scale(${(1 - (k / 14) * 0.5).toFixed(2)})`, opacity: k < 9 ? 1 : 1 - (k - 9) / 5, }); } work.animate(drop, frames, { duration: dur, fill: "forwards" }, undefined, true); } // the label has nothing to float on anymore const label = labelRef.current?.cloneNode(true) as HTMLElement | undefined; if (label) { label.classList.add("tbb-falling"); fx.append(label); const tilt = Math.random() > 0.5 ? 1 : -1; work.animate(label, [ { transform: "translate(-50%,-50%) rotate(0)", opacity: 1 }, { transform: `translate(-50%,-30%) rotate(${tilt * 4}deg)`, opacity: 1, offset: 0.25 }, { transform: `translate(-50%,160%) rotate(${tilt * 22}deg)`, opacity: 0 }, ], { duration: 750, easing: "cubic-bezier(.5,0,.8,.4)", fill: "forwards" }, undefined, true); } // blow a new one work.later(() => { setPopped(false); work.animate(life, [ { transform: "scale(.04)", opacity: 0 }, { transform: "scale(.06)", opacity: 0.7, offset: 0.06 }, { transform: "scale(1.12, 1.06)", opacity: 1, offset: 0.55 }, { transform: "scale(.95, 1.03)", offset: 0.75 }, { transform: "scale(1.02, .99)", offset: 0.88 }, { transform: "scale(1)", opacity: 1 }, ], { duration: 900, easing: "cubic-bezier(.25,.7,.4,1)" }, () => { busy.current = false; wake.current(); }); }, 1050); }; return ( ); } export default BubbleButton; // 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 - 0 && x <= rect.right + 0 && y >= rect.top - 0 && y <= rect.bottom + 0); 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 = ` .tbb-wrap{position:relative;display:inline-flex;padding-bottom:22px} .tbb-btn{position:relative;width:184px;height:70px;padding:0;border:0;background:none;cursor:pointer;-webkit-tap-highlight-color:transparent; font:600 19px/1 ui-rounded,"SF Pro Rounded","Nunito","Segoe UI",system-ui,sans-serif;letter-spacing:.01em} .tbb-btn:focus-visible{outline:none} .tbb-btn:focus-visible .tbb-life{outline:2px dashed #8fb6ff;outline-offset:6px} .tbb-float{position:absolute;inset:0;animation:tbb-bob 3.4s ease-in-out infinite} .tbb-jelly,.tbb-life{position:absolute;inset:0;border-radius:999px} .tbb-life{overflow:hidden; background:radial-gradient(120% 140% at 30% 20%,rgba(255,255,255,0) 45%,rgba(170,215,255,.16) 72%,rgba(255,160,225,.24) 100%); box-shadow:inset 0 0 0 1.5px rgba(255,255,255,.85),inset 0 0 0 2.5px rgba(150,180,240,.25), inset 7px 9px 18px rgba(110,195,255,.38),inset -9px -9px 18px rgba(255,115,200,.36),inset 0 -12px 22px rgba(255,225,110,.32), 0 10px 30px -12px rgba(110,140,255,.45)} .tbb-swirl{position:absolute;inset:-40%;opacity:.16;filter:blur(8px); background:conic-gradient(from 0deg,#ff9de2,#9ed8ff,#b9ffcb,#fff59e,#ffb38a,#ff9de2);animation:tbb-swirl 7s linear infinite} .tbb-film{position:absolute;inset:0;border-radius:inherit;padding:6px;opacity:.6; background:conic-gradient(from 200deg,#ff9de2,#9ed8ff,#b9ffcb,#fff59e,#ffb38a,#ff9de2); -webkit-mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);-webkit-mask-composite:xor; mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);mask-composite:exclude; filter:blur(3px);animation:tbb-hue 6s linear infinite} .tbb-hi{position:absolute;top:10px;left:22px;width:40px;height:13px;border-radius:50%;background:rgba(255,255,255,.95);filter:blur(1.4px);transform:rotate(-10deg)} .tbb-hi2{position:absolute;top:27px;left:16px;width:7px;height:7px;border-radius:50%;background:rgba(255,255,255,.9);filter:blur(.6px)} .tbb-hi3{position:absolute;right:20px;bottom:9px;width:34px;height:10px;border-radius:50%;border-bottom:2.5px solid rgba(255,255,255,.75);filter:blur(.6px);transform:rotate(-8deg)} .tbb-label{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);white-space:nowrap;color:#4b5680;text-shadow:0 1px 0 rgba(255,255,255,.9)} .tbb-fx{position:absolute;left:50%;top:50%;width:0;height:0;pointer-events:none} .tbb-ring{position:absolute;left:-92px;top:-35px;width:184px;height:70px;border-radius:999px;border:2px solid rgba(150,185,255,.85); box-shadow:0 0 12px rgba(255,150,220,.5)} .tbb-drop{position:absolute;left:0;top:0;border-radius:50%; background:radial-gradient(circle at 34% 30%,#fff 0 18%,rgba(140,190,255,.35) 40%,rgba(255,140,215,.5) 100%); box-shadow:inset 0 0 0 1.5px rgba(120,155,235,.55),inset -1px -2px 3px rgba(255,120,200,.45),0 2px 4px rgba(90,110,180,.22)} .tbb-falling{left:0;top:0} .tbb-shadow{position:absolute;left:50%;bottom:0;width:130px;height:12px;margin-left:-65px;border-radius:50%; background:radial-gradient(closest-side,rgba(70,90,150,.22),transparent);animation:tbb-shadow 3.4s ease-in-out infinite; transition:opacity .25s,width .25s} .tbb-shadow.is-popped{opacity:0} @keyframes tbb-bob{0%,100%{transform:translateY(0) rotate(-.6deg)}50%{transform:translateY(-8px) rotate(.6deg)}} @keyframes tbb-shadow{0%,100%{transform:scale(1)}50%{transform:scale(.82);opacity:.7}} @keyframes tbb-swirl{to{transform:rotate(360deg)}} @keyframes tbb-hue{to{filter:blur(3px) hue-rotate(360deg)}} @media (prefers-reduced-motion:reduce){.tbb-float,.tbb-shadow,.tbb-swirl,.tbb-film{animation:none}} .tbb-btn:disabled{cursor:default;transition:none} .tbb-wrap[data-tb-paused=true] *{animation-play-state:paused!important} .tbb-btn:disabled *{transition:none!important;animation:none!important} @media (prefers-reduced-motion:reduce){.tbb-wrap *, .tbb-wrap *::before, .tbb-wrap *::after{animation:none!important;transition:none!important}} .tbb-btn:disabled .tbb-jelly{transform:none!important} @media (prefers-reduced-motion:reduce){.tbb-jelly{transform:none!important}.tbb-btn[data-popped=true] .tbb-life{opacity:0}} `;