"use client"; /** * balloon.tsx — a tight rubber balloon on a string. * Hover and it swells; click and it bangs into shreds and confetti, then a new one blows up from the knot. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useImperativeHandle, useRef, type ButtonHTMLAttributes, type MouseEvent, type Ref } from "react"; type Palette = { cycle: string[] }; type Props = Omit, "children"> & { children?: string; ref?: Ref; palette?: Palette; }; const W = 240; const H = 84; const PX = 120; // overflow layer: sides, top, bottom const PT = 160; const PB = 150; const CW = W + PX * 2; const CH = H + PT + PB; const FLOOR = H + PB - 4; const DEFAULT_PALETTE: Palette = { cycle: ["#d90f0e", "#1f7ae0", "#f4c21c", "#29b35a"] }; const CONFETTI = ["#ffd23f", "#3ec1ff", "#ff5fa2", "#7ce07a", "#ffffff", "#ff8a1f"]; const FONT = `800 34px ui-rounded,"SF Pro Rounded","Nunito","Segoe UI",system-ui,sans-serif`; const A = W / 2; const B = H / 2; const NPTS = 24; const N_EXP = 2.6; const KNOT = { x: -72, y: 38 }; // in balloon space (centre origin) const ROPE_N = 13; const SEG = 110 / (ROPE_N - 1); const POP_END = 2600; const TOTAL = 2900; const HOVER_S = { x: 1.18, y: 1.34 }; const clamp = (n: number, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, n)); const rnd = (a: number, b: number) => a + Math.random() * (b - a); const hex = (c: string): [number, number, number] => { const h = c.length === 4 ? `#${c[1]}${c[1]}${c[2]}${c[2]}${c[3]}${c[3]}` : c; return [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)]; }; const mixh = (a: string, b: string, t: number) => { const x = hex(a), y = hex(b); return "#" + x.map((v, i) => Math.round(v + (y[i] - v) * t).toString(16).padStart(2, "0")).join(""); }; const rgba = (c: string, a: number) => { const [r, g, b] = hex(c); return `rgba(${r},${g},${b},${a})`; }; const mixc = (a: string, b: string, t: number) => { const x = hex(a), y = hex(b); return `rgb(${Math.round(x[0] + (y[0] - x[0]) * t)},${Math.round(x[1] + (y[1] - x[1]) * t)},${Math.round(x[2] + (y[2] - x[2]) * t)})`; }; const sgnPow = (v: number, p: number) => Math.sign(v) * Math.pow(Math.abs(v), p); // balloon outline in its own space (before wobble), with the pinched tip at the knot const BASE_PTS: { x: number; y: number; w: number }[] = (() => { const pts: { th: number; x: number; y: number; w: number }[] = []; for (let i = 0; i < NPTS; i++) { const th = (i / NPTS) * Math.PI * 2; pts.push({ th, x: A * sgnPow(Math.cos(th), 2 / N_EXP), y: B * sgnPow(Math.sin(th), 2 / N_EXP), w: 1 }); } pts.push({ th: 2.17, x: KNOT.x, y: KNOT.y + 9, w: 0 }); pts.sort((p, q) => p.th - q.th); const tip = KNOT; return pts.map((p) => { if (p.w === 0) return p; const d = Math.hypot(p.x - tip.x, p.y - tip.y); const k = 0.38 * Math.exp(-((d / 40) ** 2)); return { th: p.th, x: p.x + (tip.x - p.x) * k, y: p.y + (tip.y + 9 - p.y) * k, w: 1 }; }); })(); type Shred = { x: number; y: number; vx: number; vy: number; rot: number; spin: number; fl: number; fs: number; age: number; life: number; poly: number[]; rx: number; ry: number; landed: boolean }; type Conf = { x: number; y: number; vx: number; vy: number; rot: number; spin: number; fl: number; fs: number; age: number; life: number; w: number; h: number; round: boolean; col: string; back: string; landed: boolean }; type Node = { x: number; y: number; px: number; py: number }; export function BalloonButton({ children = "pop", palette = DEFAULT_PALETTE, onClick, className, type = "button", disabled = false, ref, ...rest }: Props) { const btnRef = useRef(null); const wrapRef = useRef(null); const canvasRef = useRef(null); const play = useRef<() => void>(() => {}); const pal = useRef(palette); pal.current = palette; const label = useRef(children); label.current = children; useImperativeHandle(ref, () => btnRef.current!, []); useEffect(() => { const el = btnRef.current; const host = wrapRef.current; const cv = canvasRef.current; if (!el || !host || !cv) return; const ctx = cv.getContext("2d"); if (!ctx) return; let raf = 0; let last = 0; let visible = true; let hovering = false; let colorIdx = 0; let began = 0; let popped = false; let nextDone = false; let flashAt = -1e9; let burstSx = 1, burstSy = 1, burstRot = 0; let pressAt = 0; let popAt = 48; let burstCx = A; let burstCy = B; // balloon spring state let sx = 1, sy = 1, vx = 0, vy = 0; let grow = 1, gv = 0; // regrow scale let fade = 1; // reduced-motion fade let epoch = 0; const timers = new Set(); const media = window.matchMedia("(prefers-reduced-motion: reduce)"); const allowed = () => !disabled && visible && !document.hidden && !media.matches; const shreds: Shred[] = []; const confetti: Conf[] = []; const rope: Node[] = []; let pinned = true; let pinFrom = { x: 0, y: 0 }; let pinT = -1; let knotPos = { x: 0, y: 0 }; let knotAng = 0; const colors = () => pal.current.cycle.length ? pal.current.cycle : DEFAULT_PALETTE.cycle; const baseColor = () => colors()[colorIdx % colors().length]; const sOff = (i: number) => Math.sin((i / (ROPE_N - 1)) * Math.PI * 1.6) * 7 * (i / (ROPE_N - 1)); const setup = () => { const scale = el.getBoundingClientRect().width / (el.offsetWidth || 1) || 1; const dpr = Math.min(2, (window.devicePixelRatio || 1) * scale); cv.width = Math.round(CW * dpr); cv.height = Math.round(CH * dpr); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); }; const initRope = (ax: number, ay: number) => { rope.length = 0; for (let i = 0; i < ROPE_N; i++) { const x = ax + sOff(i); const y = ay + i * SEG; rope.push({ x, y, px: x, py: y }); } }; // balloon transform: world = centre + R(rot) * (s * p) const cx0 = A; const cy0 = B; let bob = 0; let rot = 0; const toWorld = (px: number, py: number, scx: number, scy: number) => { const x = px * scx, y = py * scy; const c = Math.cos(rot), s = Math.sin(rot); return { x: cx0 + x * c - y * s, y: cy0 + bob + x * s + y * c }; }; const kPoint = (scx: number, scy: number, ox: number, oy: number) => { // knot with an origin shift (regrow scales about the knot) const w = toWorld(KNOT.x, KNOT.y + 9, scx, scy); return { x: w.x + ox, y: w.y + oy }; }; const smoothPath = (pts: { x: number; y: number }[]) => { const n = pts.length; ctx.beginPath(); ctx.moveTo(pts[0].x, pts[0].y); for (let i = 0; i < n; i++) { const p0 = pts[(i - 1 + n) % n], p1 = pts[i], p2 = pts[(i + 1) % n], p3 = pts[(i + 2) % n]; ctx.bezierCurveTo(p1.x + (p2.x - p0.x) / 6, p1.y + (p2.y - p0.y) / 6, p2.x - (p3.x - p1.x) / 6, p2.y - (p3.y - p1.y) / 6, p2.x, p2.y); } ctx.closePath(); }; const drawBalloon = (now: number, scx: number, scy: number, hvAmt: number, lit: number, pull: number, alpha: number) => { const bcol = baseColor(); const base = mixh(bcol, "#ffffff", clamp(hvAmt * 0.1 + lit * 0.18)); const deep = mixh(bcol, "#000000", 0.55); const wob = 1.5 * hvAmt; const pts = BASE_PTS.map((p) => { if (p.th === 2.17) return { x: p.x, y: p.y }; const k = Math.hypot(p.x - KNOT.x, p.y - KNOT.y); let nx = p.x, ny = p.y; const l = Math.hypot(p.x, p.y) || 1; nx += (p.x / l) * wob * Math.sin(p.th * 3 + now * 0.012); ny += (p.y / l) * wob * Math.sin(p.th * 3 + now * 0.012); if (pull > 0 && k < 20) { nx += (KNOT.x - nx) * 0.2 * pull; ny += (KNOT.y - ny) * 0.2 * pull; } return { x: nx, y: ny }; }); ctx.save(); ctx.globalAlpha = alpha; ctx.translate(cx0, cy0 + bob); ctx.rotate(rot); ctx.scale(scx, scy); smoothPath(pts); ctx.fillStyle = base; ctx.fill(); ctx.save(); ctx.clip(); const FR = [-A - 6, -B - 6, 2 * A + 12, 2 * B + 12] as const; const rimLight = mixh(base, "#ffffff", 0.38); let g: CanvasGradient = ctx.createLinearGradient(0, -B, 0, B); g.addColorStop(0, rgba("#ffffff", 0.3)); g.addColorStop(0.2, rgba("#ffffff", 0.1)); g.addColorStop(0.48, rgba("#000000", 0)); g.addColorStop(0.8, rgba(deep, 0.42)); g.addColorStop(0.93, rgba(deep, 0.62)); g.addColorStop(1, rgba(rimLight, 0.55)); ctx.fillStyle = g; ctx.fillRect(...FR); g = ctx.createLinearGradient(-A, 0, A, 0); g.addColorStop(0, rgba(deep, 0.65)); g.addColorStop(0.13, rgba(deep, 0)); g.addColorStop(0.87, rgba(deep, 0)); g.addColorStop(1, rgba(deep, 0.75)); ctx.fillStyle = g; ctx.fillRect(...FR); const warm = mixh(base, "#ff4a3a", 0.5); ctx.save(); ctx.scale(1, 0.38); g = ctx.createRadialGradient(0, (B * 0.3) / 0.38, 0, 0, (B * 0.3) / 0.38, A * 0.78); g.addColorStop(0, rgba(warm, 0.4)); g.addColorStop(1, rgba(warm, 0)); ctx.fillStyle = g; ctx.fillRect(-A, -B / 0.38, 2 * A, (2 * B) / 0.38); ctx.restore(); // gather creases at the neck const cr = 1 - 0.6 * hvAmt; ctx.lineWidth = 1; g = ctx.createRadialGradient(KNOT.x + 4, KNOT.y - 4, 0, KNOT.x + 4, KNOT.y - 4, 20); g.addColorStop(0, rgba(deep, 0.42 * cr)); g.addColorStop(1, rgba(deep, 0)); ctx.fillStyle = g; ctx.fillRect(KNOT.x - 16, KNOT.y - 24, 40, 40); for (const [o, len, tilt] of [[-5, 8, -0.15], [-1.5, 12, 0.15], [2, 11, 0.42], [5.5, 7, 0.7]]) { const bx = KNOT.x + o, by = KNOT.y - 1, a = -Math.PI / 2 + tilt; const tx = bx + Math.cos(a) * len, ty = by + Math.sin(a) * len; const mx = (bx + tx) / 2, my = (by + ty) / 2, nx = -Math.sin(a), ny = Math.cos(a); const wedge = (dx: number, dy: number, k: number) => { ctx.beginPath(); ctx.moveTo(bx - nx * 1.2 + dx, by - ny * 1.2 + dy); ctx.quadraticCurveTo(mx + nx * 1.8 + dx, my + ny * 1.8 + dy, bx + (tx - bx) * k + dx, by + (ty - by) * k + dy); ctx.quadraticCurveTo(mx + nx * 0.2 + dx, my + ny * 0.2 + dy, bx + nx * 1.2 + dx, by + ny * 1.2 + dy); ctx.closePath(); ctx.fill(); }; ctx.fillStyle = rgba(deep, 0.22 * cr); wedge(0, 0, 1); } // printed label stretches with the rubber (x scale capped at 1.12) ctx.save(); ctx.scale(Math.min(scx, 1.12) / scx, 1); ctx.font = FONT; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.letterSpacing = "0.5px"; const txt = label.current.toUpperCase(); ctx.fillStyle = rgba(deep, 0.55); ctx.fillText(txt, 0, 1.6); const lg = ctx.createLinearGradient(0, -17, 0, 17); lg.addColorStop(0, "#ffffff"); lg.addColorStop(0.55, "#fff7f5"); lg.addColorStop(1, mixh("#ffffff", base, 0.24)); ctx.fillStyle = lg; ctx.fillText(txt, 0, 0.4); ctx.globalAlpha = alpha * 0.35; ctx.fillStyle = "#ffffff"; ctx.fillText(txt, 0, -0.4); ctx.globalAlpha = alpha; ctx.restore(); // speculars (thin out as the rubber stretches), over the print const hl = 0.9 * (1 - 0.25 * hvAmt); ctx.beginPath(); ctx.moveTo(-A * 0.52, -B * 0.5); ctx.quadraticCurveTo(0, -B * 0.82, A * 0.6, -B * 0.52); ctx.quadraticCurveTo(0, -B * 0.58, -A * 0.52, -B * 0.5); ctx.closePath(); g = ctx.createLinearGradient(-A * 0.52, 0, A * 0.6, 0); g.addColorStop(0, "rgba(255,240,235,0)"); g.addColorStop(0.12, `rgba(255,240,235,${hl})`); g.addColorStop(0.55, `rgba(255,240,235,${hl * 0.8})`); g.addColorStop(1, "rgba(255,240,235,0)"); ctx.fillStyle = g; ctx.fill(); ctx.save(); ctx.translate(4, -B * 0.56); ctx.scale(1, 12 / (A * 0.7)); g = ctx.createRadialGradient(0, 0, 0, 0, 0, A * 0.7); g.addColorStop(0, `rgba(255,240,235,${0.16 * hl})`); g.addColorStop(0.6, `rgba(255,240,235,${0.06 * hl})`); g.addColorStop(1, "rgba(255,240,235,0)"); ctx.fillStyle = g; ctx.fillRect(-A * 0.7, -A * 0.7, A * 1.4, A * 1.4); ctx.restore(); ctx.save(); ctx.translate(-A * 0.70, -B * 0.36); ctx.rotate(-0.45); ctx.scale(1.7, 1); g = ctx.createRadialGradient(0, 0, 0, 0, 0, 7); g.addColorStop(0, "rgba(255,250,248,.98)"); g.addColorStop(0.35, "rgba(255,240,235,.7)"); g.addColorStop(1, "rgba(255,235,230,0)"); ctx.fillStyle = g; ctx.fillRect(-8, -8, 16, 16); ctx.restore(); ctx.save(); ctx.translate(A * 0.84, -B * 0.30); ctx.rotate(0.35); ctx.scale(0.38, 1); g = ctx.createRadialGradient(0, 0, 0, 0, 0, 16); g.addColorStop(0, "rgba(255,235,230,.38)"); g.addColorStop(1, "rgba(255,235,230,0)"); ctx.fillStyle = g; ctx.fillRect(-16, -16, 32, 32); ctx.restore(); ctx.save(); ctx.translate(A * 0.08, B * 0.74); ctx.scale(1, 6 / (A * 0.45)); g = ctx.createRadialGradient(0, 0, 0, 0, 0, A * 0.45); g.addColorStop(0, rgba(mixh(base, "#ffffff", 0.45), 0.22)); g.addColorStop(1, rgba(mixh(base, "#ffffff", 0.45), 0)); ctx.fillStyle = g; ctx.fillRect(-A * 0.45, -A * 0.45, A * 0.9, A * 0.9); ctx.restore(); ctx.restore(); smoothPath(pts); ctx.lineWidth = 1.1 / Math.min(scx, scy); ctx.strokeStyle = rgba(deep, 0.55); ctx.stroke(); ctx.restore(); }; const drawKnot = (x: number, y: number, ang: number, a: number, torn: boolean) => { ctx.save(); ctx.globalAlpha = a; ctx.translate(x, y); ctx.rotate(ang); ctx.scale(1.3, 1.3); const bc = baseColor(); const base = bc, light = mixh(bc, "#ffffff", 0.22), deep = mixh(bc, "#000000", 0.55); if (torn) { ctx.beginPath(); ctx.moveTo(-3, -6); ctx.lineTo(-7.5, -13); ctx.lineTo(-4, -11.5); ctx.lineTo(-2, -16.5); ctx.lineTo(0.8, -12); ctx.lineTo(4, -15.5); ctx.lineTo(5, -10.5); ctx.lineTo(8.5, -12.5); ctx.lineTo(3, -6); ctx.closePath(); const tg = ctx.createLinearGradient(-7.5, 0, 8.5, 0); tg.addColorStop(0, light); tg.addColorStop(0.5, base); tg.addColorStop(1, deep); ctx.fillStyle = tg; ctx.fill(); ctx.strokeStyle = rgba(deep, 0.6); ctx.lineWidth = 0.6; ctx.stroke(); } ctx.fillStyle = mixh(base, "#000000", 0.3); ctx.beginPath(); ctx.roundRect(-3, -7, 6, 6, 2); ctx.fill(); ctx.lineCap = "round"; for (const yy of [-4.6, -2.6]) { ctx.strokeStyle = "#a8916a"; ctx.lineWidth = 0.7; ctx.beginPath(); ctx.moveTo(-3.5, yy + 0.8); ctx.lineTo(3.5, yy + 1.6); ctx.stroke(); ctx.strokeStyle = "#d8c29a"; ctx.lineWidth = 1.4; ctx.beginPath(); ctx.moveTo(-3.5, yy); ctx.lineTo(3.5, yy + 0.8); ctx.stroke(); } const fg = ctx.createLinearGradient(-8.5, 0, 8.5, 0); fg.addColorStop(0, light); fg.addColorStop(0.45, base); fg.addColorStop(1, deep); ctx.fillStyle = fg; ctx.beginPath(); ctx.moveTo(-2.5, -1); ctx.quadraticCurveTo(-9, 3, -8.5, 8); ctx.lineTo(-5, 6.6); ctx.lineTo(-2, 8.8); ctx.lineTo(1, 6.9); ctx.lineTo(4.5, 8.8); ctx.lineTo(8.5, 7.4); ctx.quadraticCurveTo(8.5, 3, 2.5, -1); ctx.closePath(); ctx.fill(); ctx.strokeStyle = rgba(deep, 0.6); ctx.lineWidth = 0.6; ctx.stroke(); ctx.save(); ctx.translate(-4, 3); ctx.rotate(0.5); ctx.fillStyle = "rgba(255,235,230,.55)"; ctx.beginPath(); ctx.ellipse(0, 0, 1.6, 2.6, 0, 0, Math.PI * 2); ctx.fill(); ctx.restore(); ctx.strokeStyle = mixh(base, "#000000", 0.7); ctx.lineWidth = 0.8; ctx.beginPath(); ctx.moveTo(-1, 0); ctx.lineTo(-5, 7); ctx.moveTo(0.5, 0); ctx.lineTo(0, 7.6); ctx.moveTo(1.5, 0); ctx.lineTo(5, 7); ctx.stroke(); ctx.restore(); }; const drawRope = (a: number) => { ctx.save(); ctx.globalAlpha = a; ctx.lineCap = "round"; ctx.lineJoin = "round"; const trace = () => { ctx.beginPath(); ctx.moveTo(rope[0].x, rope[0].y); for (let i = 1; i < rope.length - 1; i++) { const mx = (rope[i].x + rope[i + 1].x) / 2, my = (rope[i].y + rope[i + 1].y) / 2; ctx.quadraticCurveTo(rope[i].x, rope[i].y, mx, my); } const l = rope[rope.length - 1]; ctx.lineTo(l.x, l.y); }; trace(); ctx.strokeStyle = "#d8c29a"; ctx.lineWidth = 2.6; ctx.stroke(); trace(); ctx.strokeStyle = "#a8916a"; ctx.lineWidth = 2.6; ctx.setLineDash([1.6, 3.6]); ctx.stroke(); ctx.setLineDash([]); ctx.restore(); }; const drawShred = (s: Shred, a: number) => { const c0 = baseColor(); const light = mixh(c0, "#ffffff", 0.35), deep = mixh(c0, "#000000", 0.45), inside = mixh(c0, "#000000", 0.28); const front = Math.cos(s.fl) > 0; ctx.save(); ctx.globalAlpha = a; ctx.translate(s.x, s.y); ctx.rotate(s.rot); ctx.scale(Math.cos(s.fl) * 0.85 + (Math.cos(s.fl) < 0 ? -0.15 : 0.15), 1); if (s.rx > 20) ctx.scale(1, 0.78 + 0.22 * Math.sin(s.fl * 0.7)); const P = s.poly, n = P.length / 2; const mx = (i: number) => (P[i * 2] + P[((i + 1) % n) * 2]) / 2; const my = (i: number) => (P[i * 2 + 1] + P[((i + 1) % n) * 2 + 1]) / 2; ctx.beginPath(); ctx.moveTo(mx(n - 1), my(n - 1)); for (let i = 0; i < n; i++) ctx.quadraticCurveTo(P[i * 2], P[i * 2 + 1], mx(i), my(i)); ctx.closePath(); if (front) { const g = ctx.createLinearGradient(0, -s.ry, 0, s.ry); g.addColorStop(0, light); g.addColorStop(0.45, c0); g.addColorStop(1, deep); ctx.fillStyle = g; } else ctx.fillStyle = inside; ctx.fill(); if (front) { ctx.lineCap = "round"; ctx.strokeStyle = "rgba(255,235,230,.6)"; ctx.lineWidth = 1.1; ctx.beginPath(); ctx.moveTo(-s.rx * 0.55, -s.ry * 0.05); ctx.quadraticCurveTo(0, -s.ry * 0.75, s.rx * 0.5, -s.ry * 0.15); ctx.stroke(); ctx.strokeStyle = rgba(deep, 0.5); ctx.lineWidth = 0.9; ctx.beginPath(); ctx.moveTo(-s.rx * 0.3, s.ry * 0.35); ctx.quadraticCurveTo(s.rx * 0.1, s.ry * 0.05, s.rx * 0.45, s.ry * 0.4); ctx.stroke(); if (s.rx > 20) { ctx.strokeStyle = rgba(deep, 0.45); ctx.lineWidth = 1.1; ctx.beginPath(); ctx.moveTo(-s.rx * 0.6, -s.ry * 0.35); ctx.quadraticCurveTo(-s.rx * 0.1, s.ry * 0.1, s.rx * 0.25, -s.ry * 0.45); ctx.stroke(); } } ctx.restore(); }; const burst = (now: number) => { popped = true; nextDone = false; pressAt = 0; grow = 0.05; gv = 0; flashAt = now; burstSx = sx; burstSy = sy; burstRot = rot; const bc = toWorld(0, 0, sx, sy); burstCx = bc.x; burstCy = bc.y; for (let i = 0; i < 22; i++) { const big = i < 7; const rx = big ? rnd(22, 34) : rnd(7, 12); const ry = rx * (big ? rnd(0.42, 0.65) : rnd(0.32, 0.5)); const np = big ? 10 : 8; const poly: number[] = []; for (let k = 0; k < np; k++) { const a = (k / np) * Math.PI * 2 + rnd(-0.18, 0.18); const j = k % 2 ? rnd(0.55, 0.8) : rnd(0.95, 1.15); poly.push(Math.cos(a) * rx * j, Math.sin(a) * ry * j); } const th = rnd(0, Math.PI * 2); const w = toWorld(A * 0.92 * Math.cos(th), B * 0.92 * Math.sin(th), sx, sy); const ang = Math.atan2(Math.sin(th) / B, Math.cos(th) / A) + rnd(-0.45, 0.45); const sp = big ? rnd(200, 360) : rnd(340, 760); const spin = big ? rnd(-5, 5) : rnd(-13, 13); shreds.push({ x: w.x, y: w.y, vx: Math.cos(ang) * sp, vy: Math.sin(ang) * sp - (big ? 170 : 90), rot: rnd(0, 6), spin, fl: rnd(0, 6), fs: big ? rnd(4, 8) : rnd(8, 16), age: 0, life: 1600, poly, rx, ry, landed: false }); } for (let i = 0; i < 90; i++) { const a = rnd(0, Math.PI * 2); const u = Math.sqrt(Math.random()); const hero = Math.random() < 0.14; const sp = rnd(280, 660) * (0.6 + 0.4 * u) * (hero ? 0.75 : 1); const round = hero || Math.random() < 0.4; const col = CONFETTI[Math.floor(Math.random() * CONFETTI.length)]; const cw = hero ? rnd(7, 10) : rnd(3, 6); confetti.push({ x: bc.x + A * sx * 0.5 * u * Math.cos(a), y: bc.y + B * sy * 0.5 * u * Math.sin(a), vx: Math.cos(a) * sp, vy: Math.sin(a) * sp - 130, rot: rnd(0, 6), spin: rnd(-10, 10), fl: rnd(0, 6), fs: rnd(8, 18), age: 0, life: 1600, w: cw, h: round ? 0 : rnd(3, 6), round, col, back: mixh(col, "#000000", 0.3), landed: false }); } pinned = false; const n0 = rope[0]; n0.px = n0.x + 150 * 0.016; n0.py = n0.y + 170 * 0.016; // verlet: previous position sets the up-left impulse }; const stepRope = (dt: number, now: number, t: number) => { const h = Math.min(dt, 32) / 1000; const g = 600; const n = rope.length; // anchor if (pinned || pinT >= 0) { let k = kPoint(sx, sy, 0, 0); if (pinT >= 0) { const e = clamp((t - pinT) / 600); const ee = e * e * (3 - 2 * e); const rest = kPoint(1, 1, 0, 0); k = { x: pinFrom.x + (rest.x - pinFrom.x) * ee, y: pinFrom.y + (rest.y - pinFrom.y) * ee }; if (e >= 1) { pinT = -1; pinned = true; } } rope[0].x = rope[0].px = k.x; rope[0].y = rope[0].py = k.y; knotPos = k; } for (let i = pinned || pinT >= 0 ? 1 : 0; i < n; i++) { const p = rope[i]; const vxp = (p.x - p.px) * 0.985; const vyp = (p.y - p.py) * 0.985; p.px = p.x; p.py = p.y; p.x += vxp; p.y += vyp + g * h * h; if (pinned || pinT >= 0) { // weak spring back to the S-curve hang const tx = rope[0].x + sOff(i); p.x += (tx - p.x) * 0.04; } } for (let it = 0; it < 4; it++) { for (let i = 0; i < n - 1; i++) { const a = rope[i], b = rope[i + 1]; const dx = b.x - a.x, dy = b.y - a.y; const d = Math.hypot(dx, dy) || 1; const diff = (d - SEG) / d; const aFixed = i === 0 && (pinned || pinT >= 0); if (aFixed) { b.x -= dx * diff; b.y -= dy * diff; } else { a.x += dx * diff * 0.5; a.y += dy * diff * 0.5; b.x -= dx * diff * 0.5; b.y -= dy * diff * 0.5; } } if (!(pinned || pinT >= 0)) for (const p of rope) if (p.y > FLOOR) { p.y = FLOOR; p.px = p.x - (p.x - p.px) * 0.3; } } if (!(pinned || pinT >= 0)) knotPos = { x: rope[0].x, y: rope[0].y }; knotAng = Math.atan2(rope[1].y - rope[0].y, rope[1].x - rope[0].x) - Math.PI / 2; void now; }; const paintParticles = (dt: number) => { const h = dt / 1000; for (let i = shreds.length - 1; i >= 0; i--) { const s = shreds[i]; s.age += dt; if (s.age > s.life) { shreds.splice(i, 1); continue; } if (!s.landed) { const dr = Math.exp(-(s.rx > 20 ? 3.4 : 2.5) * h); s.vx *= dr; s.vy = s.vy * dr + 700 * h; s.x += s.vx * h; s.y += s.vy * h; s.rot += s.spin * h; s.fl += s.fs * h; if (s.y > FLOOR) { s.y = FLOOR; s.landed = true; } } const a = s.age < 900 ? 1 : 1 - (s.age - 900) / (s.life - 900); drawShred(s, a); } for (let i = confetti.length - 1; i >= 0; i--) { const c = confetti[i]; c.age += dt; if (c.age > c.life) { confetti.splice(i, 1); continue; } if (!c.landed) { const dr = Math.exp(-1.8 * h); c.vx *= dr; c.vy = c.vy * dr + 500 * h; c.x += c.vx * h; c.y += c.vy * h; c.rot += c.spin * h; c.fl += c.fs * h; if (c.y > FLOOR) { c.y = FLOOR; c.landed = true; } } const a = c.age < 900 ? 1 : 1 - (c.age - 900) / (c.life - 900); ctx.globalAlpha = a; const v = Math.hypot(c.vx, c.vy); if (!c.landed && v > 300) { ctx.strokeStyle = c.col; ctx.globalAlpha = a * 0.35; ctx.lineWidth = Math.max(1, c.w * 0.5); ctx.lineCap = "round"; ctx.beginPath(); ctx.moveTo(c.x, c.y); ctx.lineTo(c.x - c.vx * 0.014, c.y - c.vy * 0.014); ctx.stroke(); ctx.globalAlpha = a; } ctx.fillStyle = Math.cos(c.fl) < 0 ? c.back : c.col; ctx.save(); ctx.translate(c.x, c.y); ctx.rotate(c.rot); if (c.round) { ctx.scale(Math.abs(Math.cos(c.fl)) + 0.15, 1); ctx.beginPath(); ctx.arc(0, 0, c.w / 2, 0, Math.PI * 2); ctx.fill(); } else { ctx.scale(1, Math.abs(Math.cos(c.fl)) + 0.15); ctx.fillRect(-c.w / 2, -c.h / 2, c.w, c.h); } ctx.restore(); } ctx.globalAlpha = 1; }; const frame = (now: number, dt: number) => { const t = began ? now - began : 0; const ambient = allowed(); bob = ambient ? 2 * Math.sin((2 * Math.PI * now) / 3200) : 0; rot = ambient ? ((0.6 * Math.PI) / 180) * Math.sin((2 * Math.PI * now) / 4100) : 0; // inflate spring (k 180, c 14) let tx = hovering && !began ? HOVER_S.x : 1; let ty = hovering && !began ? HOVER_S.y : 1; if (began && !popped) { tx = (hovering ? HOVER_S.x : 1) * 1.06; ty = (hovering ? HOVER_S.y : 1) * 1.06; } else if (pressAt && !began) { tx = (hovering ? HOVER_S.x : 1) * 1.05; ty = (hovering ? HOVER_S.y : 1) * 1.07; } const sub = Math.max(1, Math.ceil(dt / 4)); const hh = dt / sub / 1000; for (let i = 0; i < sub; i++) { vx += (-180 * (sx - tx) - 14 * vx) * hh; sx += vx * hh; vy += (-180 * (sy - ty) - 14 * vy) * hh; sy += vy * hh; if (began && t >= 1600) { gv += (-140 * (grow - 1) - 12 * gv) * hh; grow += gv * hh; } } if (began) { if (!popped && t >= popAt) burst(now); if (popped && t >= 1500 && pinT < 0 && !pinned) { pinFrom = { x: rope[0].x, y: rope[0].y }; pinT = t; } if (popped && t >= 1600 && !nextDone) { nextDone = true; colorIdx++; } if (t >= TOTAL) { began = 0; popped = false; grow = 1; gv = 0; sx = sy = 1; vx = vy = 0; host.dataset.tbState = "idle"; shreds.length = confetti.length = 0; } } const hvAmt = clamp((sx - 1) / (HOVER_S.x - 1)); stepRope(dt, now, t); ctx.clearRect(0, 0, CW, CH); ctx.save(); ctx.translate(PX, PT); // floor shadow if (!popped) { ctx.save(); ctx.translate(A, FLOOR + 2); ctx.scale(1, 0.1); const r = 78 * sx; const sg = ctx.createRadialGradient(0, 0, 0, 0, 0, r); const k = 0.3 - bob * 0.03; sg.addColorStop(0, `rgba(0,0,0,${k})`); sg.addColorStop(0.6, `rgba(0,0,0,${k * 0.4})`); sg.addColorStop(1, "rgba(0,0,0,0)"); ctx.fillStyle = sg; ctx.fillRect(-r, -r, r * 2, r * 2); ctx.restore(); } drawRope(1); if (!popped) { const press = pressAt && !began ? clamp((now - pressAt) / 70) : 0; const pull = began ? (t < popAt ? 1 : 0) : press; const lit = began ? clamp(t / popAt) : press; drawBalloon(now, sx, sy, hvAmt, lit, pull, fade); const kp = kPoint(sx, sy, 0, 0); drawKnot(kp.x, kp.y + 4, rot, 1, false); } else { if (t >= 1500) { // new balloon grows out of the knot const sc = clamp(grow, 0.02, 1.2); const kRest = kPoint(1, 1, 0, 0); const ox = (cx0 - kRest.x) * 0; // origin handled below void ox; ctx.save(); const kx = rope[0].x, ky = rope[0].y; ctx.translate(kx, ky); ctx.scale(sc, sc); ctx.translate(-kRest.x, -kRest.y); if (t >= 1600) drawBalloon(now, 1, 1, 0, 0, 0, clamp((t - 1600) / 150)); ctx.restore(); } drawKnot(knotPos.x, knotPos.y + 4, knotAng, 1, t < 1600); paintParticles(dt); const fl = clamp((now - flashAt) / 110); if (fl < 1) { const e = 1 - (1 - fl) ** 3; const tint = mixh(baseColor(), "#ffffff", 0.55); ctx.save(); ctx.globalCompositeOperation = "destination-over"; ctx.globalAlpha = (1 - fl) ** 2; ctx.translate(burstCx, burstCy); ctx.rotate(burstRot); ctx.scale(A * burstSx * (0.85 + 0.45 * e), B * burstSy * (0.85 + 0.45 * e)); const g = ctx.createRadialGradient(0, 0, 0, 0, 0, 1); g.addColorStop(0, rgba(tint, 0.55)); g.addColorStop(0.55, rgba(baseColor(), 0.22)); g.addColorStop(1, rgba(baseColor(), 0)); ctx.fillStyle = g; ctx.beginPath(); ctx.arc(0, 0, 1, 0, Math.PI * 2); ctx.fill(); ctx.restore(); } } ctx.restore(); }; const tick = (now: number) => { raf = 0; if (!allowed()) return; const dt = last ? Math.min(48, now - last) : 16; last = now; frame(now, dt); raf = requestAnimationFrame(tick); }; const wake = () => { if (!raf && allowed()) raf = requestAnimationFrame(tick); }; const later = (fn: () => void, ms: number) => { const my = epoch; const id = window.setTimeout(() => { timers.delete(id); if (my === epoch) fn(); }, ms); timers.add(id); }; const clearTimers = () => { epoch++; timers.forEach((id) => window.clearTimeout(id)); timers.clear(); }; const sync = () => { cancelAnimationFrame(raf); raf = 0; last = 0; clearTimers(); began = 0; popped = false; grow = 1; gv = 0; sx = sy = 1; vx = vy = 0; fade = 1; pinned = true; pinT = -1; pressAt = 0; shreds.length = confetti.length = 0; host.dataset.tbPaused = String(disabled || !visible || document.hidden); host.dataset.tbState = "idle"; hovering = allowed() && el.matches(":hover"); bob = 0; rot = 0; const k = kPoint(1, 1, 0, 0); initRope(k.x, k.y); knotPos = k; frame(performance.now(), 16); wake(); }; play.current = () => { if (disabled || began) return; if (media.matches) { if (fade < 1) return; host.dataset.tbState = "playing"; fade = 0; frame(performance.now(), 16); later(() => { colorIdx++; fade = 1; frame(performance.now(), 16); host.dataset.tbState = "idle"; }, 520); return; } if (!allowed()) return; began = performance.now(); popAt = pressAt && began - pressAt > 40 ? 12 : 48; popped = false; host.dataset.tbState = "playing"; wake(); }; const down = (e: PointerEvent) => { if (e.button !== 0 || !allowed() || began) return; pressAt = performance.now(); wake(); later(() => { if (!began) pressAt = 0; }, 300); }; const cancelPress = () => { if (!began) pressAt = 0; }; const enter = () => { if (!allowed()) return; hovering = true; wake(); }; const leave = () => { hovering = false; cancelPress(); wake(); }; const io = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([en]) => { visible = en.isIntersecting; sync(); }); const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => { setup(); frame(performance.now(), 16); }); setup(); io?.observe(host); ro?.observe(el); el.addEventListener("pointerenter", enter); el.addEventListener("pointerleave", leave); el.addEventListener("pointerdown", down); el.addEventListener("pointercancel", cancelPress); document.addEventListener("visibilitychange", sync); media.addEventListener("change", sync); sync(); return () => { play.current = () => {}; cancelAnimationFrame(raf); clearTimers(); io?.disconnect(); ro?.disconnect(); el.removeEventListener("pointerenter", enter); el.removeEventListener("pointerleave", leave); el.removeEventListener("pointerdown", down); el.removeEventListener("pointercancel", cancelPress); document.removeEventListener("visibilitychange", sync); media.removeEventListener("change", sync); }; }, [disabled]); const click = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; play.current(); }; return ( ); } export default BalloonButton; const css = ` .tb-balloon-wrap{display:inline-flex;position:relative;vertical-align:middle;width:${W}px;height:${H}px} .tb-balloon-btn{position:relative;display:block;box-sizing:border-box;width:${W}px;height:${H}px;padding:0;border:0;border-radius:${H / 2}px; background:transparent;cursor:pointer;overflow:visible;-webkit-tap-highlight-color:transparent} .tb-balloon-btn:focus-visible{outline:3px solid #ff5045;outline-offset:6px} .tb-balloon-btn:disabled{cursor:default;opacity:.6;filter:saturate(.5)} .tb-balloon-canvas{position:absolute;left:-${PX}px;top:-${PT}px;width:${CW}px;height:${CH}px;max-width:none;pointer-events:none} .tb-balloon-wrap[data-tb-paused=true] *{animation-play-state:paused!important} @media (prefers-reduced-motion:reduce){.tb-balloon-wrap *,.tb-balloon-wrap *::before,.tb-balloon-wrap *::after{animation:none!important;transition:none!important}} `;