"use client"; /** * gumball.tsx — a little red gumball machine with a real pile of candy. * Hover and the balls rattle; click to turn the crank, one rolls out, then the globe tops itself up. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useId, useImperativeHandle, useRef, useState, type ButtonHTMLAttributes, type MouseEvent, type ReactNode, type Ref } from "react"; type Props = Omit, "children"> & { children?: ReactNode; ref?: Ref; colors?: string[]; }; const W = 180; const H = 200; const FW = 300; // floor canvas: body + 120 px to the right const FH = H + 60; const GX = 90; // globe centre in button coordinates const GY = 62; const GR = 54; const SIM = 112; // globe canvas size const SX = GX - SIM / 2; const SY = GY - SIM / 2; const CX = SIM / 2; // sim centre const CY = SIM / 2; const RC = 52; const COUNT = 34; const DEFAULT_COLORS = ["#ff2d2d", "#ffcc1a", "#2fb24a", "#1f7ae0", "#ff8a1a", "#a34be0", "#ff6fb0", "#f4e6c8"]; const CHUTE = { x: 99, y: 126, w: 26, h: 24 }; const CRANK = { x: 64, y: 135 }; const LEDGE_Y = 149; const FLOOR_Y = H + 6; const BALL_R = 11; const T_BALL = 700; const T_SPAWN = 2100; const T_END = 2900; const clamp = (n: number, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, n)); function rng(seed: number) { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } type Ball = { x: number; y: number; vx: number; vy: number; r: number; c: string }; type Floor = { x: number; y: number; vx: number; vy: number; rot: number; c: string; phase: 0 | 1 | 2; hit: number; hitV: number; born: number; fade: number; alpha: number }; export function GumballButton({ children = "twist", colors = DEFAULT_COLORS, onClick, className, type = "button", disabled = false, ref, ...rest }: Props) { const btnRef = useRef(null); const wrapRef = useRef(null); const simRef = useRef(null); const floorRef = useRef(null); const squashRef = useRef(null); const rockRef = useRef(null); const crankRef = useRef(null); const flapRef = useRef(null); const playRef = useRef<() => void>(() => {}); const [playing, setPlaying] = useState(false); const uid = `tb-gumball-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; const colorKey = colors.join("|"); useImperativeHandle(ref, () => btnRef.current!, []); useEffect(() => { const el = btnRef.current; const host = wrapRef.current; const sc = simRef.current; const fc = floorRef.current; if (!el || !host || !sc || !fc) return; const sctx = sc.getContext("2d"); const fctx = fc.getContext("2d"); if (!sctx || !fctx) return; const cols = colorKey.split("|"); const media = window.matchMedia("(prefers-reduced-motion: reduce)"); const R = rng(21); let dpr = 1; let raf = 0; let last = 0; let visible = true; let hovering = false; let asleep = true; let calm = 0; let nextStir = 0; let lastKick = 0; let epoch = 0; let jobs = 0; let lastJob = -1e9; let rmBall = -1; const timers = new Set(); const anims = new Set(); const rmNow = () => media.matches; const canRun = () => !disabled && !el.matches(":disabled") && visible && !document.hidden && !rmNow(); const later = (fn: () => void, ms: number) => { const ep = epoch; const id = window.setTimeout(() => { timers.delete(id); if (ep === epoch) fn(); }, ms); timers.add(id); }; const anim = (target: Element | null, frames: Keyframe[], opts: KeyframeAnimationOptions) => { if (!target) return; const a = target.animate(frames, opts); anims.add(a); a.onfinish = () => anims.delete(a); }; const clearAll = () => { epoch++; timers.forEach((id) => window.clearTimeout(id)); timers.clear(); anims.forEach((a) => a.cancel()); anims.clear(); }; // ---- the pile ---- const balls: Ball[] = []; const addBall = (x: number, y: number, c?: string) => { balls.push({ x, y, vx: 0, vy: 0, r: 6.5 + R() * 2.2, c: c ?? cols[Math.floor(R() * cols.length)] }); }; const resolve = (dt: number) => { const subs = 3; const h = dt / subs; for (let s = 0; s < subs; s++) { for (const b of balls) { b.vy += 1200 * h; const damp = Math.pow(0.98, h * 60); b.vx *= damp; b.vy *= damp; b.x += b.vx * h; b.y += b.vy * h; } for (let pass = 0; pass < 2; pass++) { for (let i = 0; i < balls.length; i++) { const a = balls[i]; for (let j = i + 1; j < balls.length; j++) { const b = balls[j]; const dx = b.x - a.x, dy = b.y - a.y, rr = a.r + b.r; const d2 = dx * dx + dy * dy; if (d2 >= rr * rr || d2 === 0) continue; const d = Math.sqrt(d2), nx = dx / d, ny = dy / d, ov = (rr - d) * 0.5; a.x -= nx * ov; a.y -= ny * ov; b.x += nx * ov; b.y += ny * ov; const vn = (b.vx - a.vx) * nx + (b.vy - a.vy) * ny; if (vn < 0) { const j2 = (-(1 + 0.35) * vn) / 2; a.vx -= j2 * nx; a.vy -= j2 * ny; b.vx += j2 * nx; b.vy += j2 * ny; } } const dx = a.x - CX, dy = a.y - CY, d = Math.hypot(dx, dy), lim = RC - a.r; if (d > lim) { const nx = dx / d, ny = dy / d; a.x = CX + nx * lim; a.y = CY + ny * lim; const vn = a.vx * nx + a.vy * ny; if (vn > 0) { a.vx -= (1 + 0.35) * vn * nx; a.vy -= (1 + 0.35) * vn * ny; } } } } } }; const maxSpeed = () => balls.reduce((m, b) => Math.max(m, Math.hypot(b.vx, b.vy)), 0); for (let i = 0; i < COUNT; i++) { const a = R() * 6.2832, d = Math.sqrt(R()) * (RC - 9); addBall(CX + Math.cos(a) * d * 0.9, CY + 6 + Math.abs(Math.sin(a)) * d * 0.9); } for (let i = 0; i < 360; i++) { resolve(1 / 60); if (i > 40 && maxSpeed() < 3) break; } for (const b of balls) { b.vx = 0; b.vy = 0; } const drawBall = (g: CanvasRenderingContext2D, x: number, y: number, r: number, c: string, rot: number, alpha: number) => { g.save(); g.globalAlpha = alpha; g.fillStyle = c; g.beginPath(); g.arc(x, y, r, 0, 6.2832); g.fill(); if (rot !== 0 || r > 10) { g.save(); g.beginPath(); g.arc(x, y, r, 0, 6.2832); g.clip(); g.translate(x, y); g.rotate(rot); g.strokeStyle = "rgba(255,255,255,.55)"; g.lineWidth = r * 0.28; g.beginPath(); g.moveTo(-r, r * 0.1); g.quadraticCurveTo(0, -r * 0.35, r, r * 0.1); g.stroke(); g.restore(); } const sh = g.createRadialGradient(x - r * 0.35, y - r * 0.45, r * 0.05, x, y, r * 1.05); sh.addColorStop(0, "rgba(255,255,255,.45)"); sh.addColorStop(0.35, "rgba(255,255,255,0)"); sh.addColorStop(0.75, "rgba(0,0,0,.12)"); sh.addColorStop(1, "rgba(0,0,0,.45)"); g.fillStyle = sh; g.beginPath(); g.arc(x, y, r, 0, 6.2832); g.fill(); g.strokeStyle = "rgba(255,255,255,.18)"; g.lineWidth = 1; g.beginPath(); g.arc(x, y, r - 1, 0.2 * Math.PI, 0.7 * Math.PI); g.stroke(); g.fillStyle = "rgba(255,255,255,.25)"; g.beginPath(); g.arc(x - r * 0.38, y - r * 0.42, r * 0.4, 0, 6.2832); g.fill(); g.fillStyle = "rgba(255,255,255,.95)"; g.beginPath(); g.ellipse(x - r * 0.38, y - r * 0.42, r * 0.22, r * 0.15, -0.6, 0, 6.2832); g.fill(); g.restore(); }; const drawSim = () => { sctx.setTransform(dpr, 0, 0, dpr, 0, 0); sctx.clearRect(0, 0, SIM, SIM); sctx.fillStyle = "rgba(0,0,0,.32)"; for (const b of balls) { sctx.beginPath(); sctx.arc(b.x + 0.5, b.y + 1.4, b.r + 0.8, 0, 6.2832); sctx.fill(); } for (const b of balls) drawBall(sctx, b.x, b.y, b.r, b.c, 0, 1); }; // ---- balls that roll out ---- const floor: Floor[] = []; const drawFloor = (now: number) => { fctx.setTransform(dpr, 0, 0, dpr, 0, 0); fctx.clearRect(0, 0, FW, FH); for (const f of floor) { let al = f.alpha; if (f.fade > 0) al *= 1 - clamp((now - f.fade) / 300); if (al <= 0.01) continue; const r = f.fade > 0 ? BALL_R * (1 - 0.3 * clamp((now - f.fade) / 300)) : BALL_R; if (f.phase !== 0) { fctx.fillStyle = `rgba(0,0,0,${0.28 * al * clamp(1 - (FLOOR_Y - BALL_R - f.y) / 120)})`; fctx.beginPath(); fctx.ellipse(f.x, FLOOR_Y + 0.5, r * 0.95, 2.4, 0, 0, 6.2832); fctx.fill(); } if (f.phase === 0 && f.x < CHUTE.x + CHUTE.w + BALL_R) { fctx.save(); fctx.beginPath(); fctx.moveTo(CHUTE.x + 1.25, 150); fctx.lineTo(CHUTE.x + 1.25, 139); fctx.arc(CHUTE.x + 13, 139, 11.75, Math.PI, 0); fctx.lineTo(CHUTE.x + CHUTE.w - 1.25, 150); fctx.closePath(); fctx.rect(CHUTE.x + CHUTE.w, 0, FW, FH); fctx.clip(); fctx.fillStyle = `rgba(0,0,0,${0.35 * al})`; fctx.beginPath(); fctx.ellipse(f.x, f.y + BALL_R - 0.5, 8, 1.8, 0, 0, 6.2832); fctx.fill(); drawBall(fctx, f.x, f.y, r, f.c, f.rot, al); fctx.restore(); } else if (f.phase === 0) { fctx.fillStyle = `rgba(0,0,0,${0.35 * al})`; fctx.beginPath(); fctx.ellipse(f.x, f.y + BALL_R - 0.5, 8, 1.8, 0, 0, 6.2832); fctx.fill(); drawBall(fctx, f.x, f.y, r, f.c, f.rot, al); } else { const age = f.hit ? now - f.hit : 1e9; const q = 0.25 * clamp(f.hitV / 600) * (1 - clamp(age / 110)); if (age < 240 && f.hitV > 150) { const t = age / 240; fctx.strokeStyle = f.c; fctx.globalAlpha = 0.5 * (1 - t) * al; fctx.lineWidth = 1.5; fctx.beginPath(); fctx.ellipse(f.x, FLOOR_Y, 6 + 12 * t, 1.5 + 2 * t, 0, 0, 6.2832); fctx.stroke(); fctx.globalAlpha = 1; } fctx.save(); fctx.translate(f.x, FLOOR_Y); fctx.scale(1 + q, 1 - q); fctx.translate(-f.x, -FLOOR_Y); drawBall(fctx, f.x, f.y, r, f.c, f.rot, al); fctx.restore(); } } }; const updateFloor = (dt: number, now: number) => { const s = dt / 1000; for (let i = floor.length - 1; i >= 0; i--) { const f = floor[i]; f.alpha = clamp((now - f.born) / 80); if (f.fade > 0 && now - f.fade > 300) { floor.splice(i, 1); continue; } if (f.phase === 0) { f.x += f.vx * s; f.y = 139 + clamp((f.x - 126) / 24) * 10; if (f.x >= 176) f.phase = 1; } else if (f.phase === 1) { f.vy += 1800 * s; f.x += f.vx * s; f.y += f.vy * s; if (f.y >= FLOOR_Y - BALL_R) { f.y = FLOOR_Y - BALL_R; if (Math.abs(f.vy) > 40) { f.hit = now; f.hitV = Math.abs(f.vy); f.vy = -f.vy * 0.55; f.vx *= 0.85; } else { f.vy = 0; f.phase = 2; } } } else { f.vx *= Math.exp(-3.5 * s); f.x += f.vx * s; if (Math.abs(f.vx) < 3) f.vx = 0; } f.x = Math.min(f.x, FW - BALL_R - 2); f.rot += (f.vx * s) / BALL_R; } }; const floorBusy = () => floor.some((f) => f.phase !== 2 || f.vx !== 0 || f.fade > 0 || f.alpha < 1); const setup = () => { const scale = el.getBoundingClientRect().width / (el.offsetWidth || 1) || 1; dpr = Math.min(2, (window.devicePixelRatio || 1) * scale); sc.width = Math.round(SIM * dpr); sc.height = Math.round(SIM * dpr); fc.width = Math.round(FW * dpr); fc.height = Math.round(FH * dpr); drawSim(); drawFloor(performance.now()); }; const tick = (now: number) => { raf = 0; if (!canRun()) return; const dt = last ? Math.min(48, now - last) : 16; last = now; if (hovering && now >= nextStir) { nextStir = now + 200; lastKick = now; for (let k = 0; k < 5; k++) { const b = balls[Math.floor(R() * balls.length)]; if (!b) continue; const a = R() * 6.2832, v = 80 + R() * 60; b.vx += Math.cos(a) * v; b.vy += Math.sin(a) * v - 60; } asleep = false; calm = 0; } if (!asleep) { resolve(dt / 1000); if (!hovering && jobs === 0 && (maxSpeed() < 14 ? ++calm > 13 : (calm = 0, now - lastKick > 1200))) { asleep = true; for (const b of balls) { b.vx = 0; b.vy = 0; } } drawSim(); } let fb = false; if (floor.length) { updateFloor(dt, now); drawFloor(now); fb = floorBusy(); } if (hovering || !asleep || fb || jobs > 0) raf = requestAnimationFrame(tick); else { last = 0; drawFloor(now); } }; const wake = () => { asleep = false; calm = 0; if (!raf && canRun()) { last = 0; raf = requestAnimationFrame(tick); } }; const refresh = () => { host.dataset.tbPaused = String(disabled || !visible || document.hidden); if (!canRun()) { cancelAnimationFrame(raf); raf = 0; last = 0; if (!rmNow()) { asleep = true; } } else if (hovering || jobs > 0) wake(); }; const enter = (e: PointerEvent) => { if (e.pointerType === "touch") return; hovering = true; nextStir = performance.now() + 200; lastKick = performance.now(); for (let k = 0; k < 10; k++) { const b = balls[Math.floor(R() * balls.length)]; if (!b) continue; const a = R() * 6.2832, v = 140 + R() * 40; b.vx += Math.cos(a) * v; b.vy += Math.sin(a) * v - 90; } wake(); }; const leave = () => { hovering = false; wake(); }; const io = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([en]) => { visible = en.isIntersecting; refresh(); }); const resize = () => setup(); const mediaChange = () => { clearAll(); jobs = 0; floor.length = 0; setPlaying(false); drawFloor(0); refresh(); }; playRef.current = () => { if (disabled || el.matches(":disabled")) return; if (rmNow()) { if (rmBall >= 0) return; rmBall = 1; setPlaying(true); anim(crankRef.current, [{ transform: "rotate(0deg)" }, { transform: "rotate(180deg)", offset: 0.25 }, { transform: "rotate(180deg)", offset: 0.75 }, { transform: "rotate(0deg)" }], { duration: 400 }); const c = cols[Math.floor(R() * cols.length)]; const draw = (a: number) => { fctx.setTransform(dpr, 0, 0, dpr, 0, 0); fctx.clearRect(0, 0, FW, FH); if (a > 0) { fctx.fillStyle = `rgba(0,0,0,${0.35 * a})`; fctx.beginPath(); fctx.ellipse(150, 159.5, 8, 1.8, 0, 0, 6.2832); fctx.fill(); drawBall(fctx, 150, 149, BALL_R, c, 0, a); } }; [0, 50, 100, 150].forEach((ms, i) => later(() => draw((i + 1) / 4), ms)); [1350, 1400, 1450, 1500].forEach((ms, i) => later(() => draw(1 - (i + 1) / 4), ms)); later(() => { draw(0); rmBall = -1; setPlaying(false); }, 1560); return; } if (!canRun()) return; const now = performance.now(); if (now - lastJob < T_BALL || jobs >= 2) return; // the crank is still turning, or two balls are out lastJob = now; jobs++; setPlaying(true); // crank: two half turns with a detent between them anim(crankRef.current, [ { transform: "rotate(0deg)", easing: "ease-in-out" }, { transform: "rotate(180deg)", offset: 0.5, easing: "ease-in-out" }, { transform: "rotate(360deg)" }, ], { duration: T_BALL }); anim(rockRef.current, [{ transform: "rotate(0deg)" }, { transform: "rotate(-1.6deg)", offset: 0.2 }, { transform: "rotate(1.4deg)", offset: 0.45 }, { transform: "rotate(-1deg)", offset: 0.7 }, { transform: "rotate(0deg)" }], { duration: T_BALL, easing: "ease-in-out" }); // everything shifts toward the outlet lastKick = performance.now(); for (const b of balls) { b.vx += (CX - b.x) * 0.9 + (R() - 0.5) * 60; b.vy += 80 + R() * 60; } wake(); let chosen = cols[0]; later(() => { // pick the ball lowest in the globe let bi = -1, by = -1e9; balls.forEach((b, i) => { if (b.y > by) { by = b.y; bi = i; } }); if (bi >= 0 && balls.length > 12) { chosen = balls[bi].c; balls.splice(bi, 1); } else chosen = cols[Math.floor(R() * cols.length)]; lastKick = performance.now(); asleep = false; calm = 0; wake(); anim(squashRef.current, [{ transform: "scaleY(1)" }, { transform: "scaleY(.955)", offset: 0.35 }, { transform: "scaleY(1.012)", offset: 0.7 }, { transform: "scaleY(1)" }], { duration: 180, easing: "cubic-bezier(.3,.7,.4,1)" }); anim(flapRef.current, [{ transform: "scaleY(1)" }, { transform: "scaleY(.25)", offset: 0.3 }, { transform: "scaleY(.25)", offset: 0.7 }, { transform: "scaleY(1)" }], { duration: 500 }); }, 650); later(() => { const t = performance.now(); floor.push({ x: CHUTE.x + CHUTE.w / 2 - 6, y: 139, vx: 180, vy: 0, rot: 0, c: chosen, phase: 0, hit: 0, hitV: 0, born: t, fade: 0, alpha: 0 }); wake(); }, T_BALL); later(() => { const f = floor.find((q) => q.fade === 0 && q.c === chosen); if (f) f.fade = performance.now(); addBall(CX + (R() - 0.5) * 20, CY - RC + 10, undefined); lastKick = performance.now(); asleep = false; calm = 0; wake(); }, T_SPAWN); later(() => { jobs = Math.max(0, jobs - 1); if (jobs === 0) setPlaying(false); }, T_END); }; setup(); io?.observe(host); window.addEventListener("resize", resize); el.addEventListener("pointerenter", enter); el.addEventListener("pointerleave", leave); document.addEventListener("visibilitychange", refresh); media.addEventListener("change", mediaChange); refresh(); return () => { playRef.current = () => {}; cancelAnimationFrame(raf); clearAll(); io?.disconnect(); window.removeEventListener("resize", resize); el.removeEventListener("pointerenter", enter); el.removeEventListener("pointerleave", leave); document.removeEventListener("visibilitychange", refresh); media.removeEventListener("change", mediaChange); }; }, [disabled, colorKey]); const click = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; playRef.current(); }; const redBody = `url(#${uid}-red)`; return ( ); } export default GumballButton; const css = ` .tb-gumball-wrap{display:inline-flex;position:relative;vertical-align:middle} .tb-gumball-btn{position:relative;display:block;box-sizing:border-box;width:${W}px;height:${H}px;padding:0;border:0;border-radius:24px; background:transparent;overflow:visible;cursor:pointer;-webkit-tap-highlight-color:transparent} .tb-gumball-btn:focus-visible{outline:3px solid #ffcc1a;outline-offset:6px} .tb-gumball-btn:disabled{cursor:not-allowed} .tb-gumball-btn:disabled .tb-gumball-squash{opacity:.6;filter:saturate(.5)} .tb-gumball-squash{position:absolute;inset:0;display:block;transform-origin:50% 100%;pointer-events:none;transition:transform 220ms cubic-bezier(.3,1.4,.5,1)} .tb-gumball-btn:not(:disabled):hover .tb-gumball-squash{transform:translateY(-4px)} .tb-gumball-btn:not(:disabled):hover .tb-gumball-shadow{transform:scale(.88);opacity:.7} .tb-gumball-glint{transition:transform 320ms cubic-bezier(.3,1.3,.5,1)} .tb-gumball-btn:not(:disabled):hover .tb-gumball-glint{transform:translate(3px,-2px)} .tb-gumball-rock{position:absolute;inset:0;display:block;transform-origin:50% 100%} .tb-gumball-layer{position:absolute;left:0;top:0;overflow:visible;pointer-events:none;filter:drop-shadow(0 2px 2px rgba(0,0,0,.28))} .tb-gumball-shadow{position:absolute;left:0;top:0;overflow:visible;pointer-events:none;transform-origin:90px 199px;transition:transform 220ms cubic-bezier(.3,1.4,.5,1),opacity 220ms} .tb-gumball-layer:first-child{filter:none} .tb-gumball-sim{position:absolute;max-width:none;pointer-events:none} .tb-gumball-floor{position:absolute;left:0;top:0;width:${FW}px;height:${FH}px;max-width:none;pointer-events:none} .tb-gumball-crank{transform-origin:${CRANK.x}px ${CRANK.y}px} .tb-gumball-flap{transform-origin:${CHUTE.x + CHUTE.w / 2}px ${CHUTE.y + 1}px} .tb-gumball-btn:not(:disabled):hover .tb-gumball-rock{animation:tb-gumball-in 600ms ease-out,tb-gumball-rock 556ms ease-in-out 600ms infinite alternate} .tb-gumball-btn:not(:disabled):hover .tb-gumball-crank{animation:tb-gumball-invite 900ms cubic-bezier(.4,0,.2,1)} @keyframes tb-gumball-in{0%{transform:rotate(0)}25%{transform:rotate(1.6deg)}50%{transform:rotate(-1.6deg)}75%{transform:rotate(1.2deg)}100%{transform:rotate(-.5deg)}} @keyframes tb-gumball-rock{from{transform:rotate(-.7deg)}to{transform:rotate(.7deg)}} @keyframes tb-gumball-invite{0%,100%{transform:rotate(0)}35%{transform:rotate(32deg)}55%{transform:rotate(26deg)}70%{transform:rotate(30deg)}} .tb-gumball-shake{opacity:0;transition:opacity 160ms ease-out} .tb-gumball-btn:not(:disabled):hover .tb-gumball-shake{opacity:1;animation:tb-gumball-shake 278ms ease-in-out infinite alternate} @keyframes tb-gumball-shake{from{opacity:.35}to{opacity:1}} .tb-gumball-wrap[data-tb-state=playing] .tb-gumball-btn:not(:disabled):hover .tb-gumball-shake{opacity:0;animation:none} .tb-gumball-wrap[data-tb-state=playing] .tb-gumball-btn:not(:disabled):hover .tb-gumball-squash{transform:translateY(0)} .tb-gumball-wrap[data-tb-state=playing] .tb-gumball-btn:not(:disabled):hover .tb-gumball-shadow{transform:scale(1);opacity:1} .tb-gumball-wrap[data-tb-paused=true] *{animation-play-state:paused!important} @media (prefers-reduced-motion:reduce){.tb-gumball-shake{display:none}.tb-gumball-wrap *,.tb-gumball-wrap *::before,.tb-gumball-wrap *::after{animation:none!important;transition:none!important}} `;