"use client"; /** * cloud.tsx — a soft, squeezable cumulus with a label pill. * Hover and it drizzles on an invisible floor; click for a flash of lightning and a rainbow, then the sky clears. * * 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 Palette = { cloud: string[]; drops: string; rainbow: string[] }; type Props = Omit, "children"> & { children?: ReactNode; ref?: Ref; palette?: Palette; }; const W = 250; const H = 130; const PL = 130; // canvas padding left/right const PT = 190; const PB = 170; const CW = W + 2 * PL; const CH = H + PT + PB; const DEFAULT_PALETTE: Palette = { cloud: ["#f3f3f7", "#e9e8ec", "#b4b3b7"], drops: "rgba(130,190,230,.75)", rainbow: ["#ff4a3d", "#ff9a2e", "#ffd84a", "#4fd36a", "#3b8cff", "#8a5bff"], }; const FLOOR = H + 82; // virtual floor, button coordinates const GRAVITY = 650; const TERMINAL = 300; const RB_CX = 195; const RB_CY = 20; const RB_R = 95; const BAND = 10; const T_RB = 250; // rainbow starts const T_RB_GROW = 650; const T_FADE = 2100; const T_END = 2800; const EXT = 800; const CIRCLES: [number, number, number][] = [ [40, 94, 36], [80, 72, 44], [125, 58, 58], [170, 70, 46], [212, 94, 38], [95, 98, 32], [160, 98, 32], ]; const mix = (hex: string, to: string, k: number) => { const f = (h: string) => { const v = h.replace("#", ""); const x = v.length === 3 ? v.split("").map((c) => c + c).join("") : v; return [0, 2, 4].map((i) => parseInt(x.slice(i, i + 2), 16) || 0); }; const a = f(hex), b = f(to); return `rgb(${a.map((c, i) => Math.round(c + (b[i] - c) * k)).join(",")})`; }; const clamp = (n: number, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, n)); const easeOut = (n: number) => 1 - Math.pow(1 - clamp(n), 3); const rb = (n: number) => { const u = clamp(n) - 1; return 1 + 2.4 * u * u * u + 1.4 * u * u; }; 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; }; } const PUFFS: [number, number, number][] = (() => { const r = rng(11); const out: [number, number, number][] = []; const per = 34; CIRCLES.forEach(([cx, cy, cr], ci) => { for (let k = 0; k < per && out.length < 120; k++) { const a = (k / per) * Math.PI * 2 + r() * 0.25; const x = cx + Math.cos(a) * (cr + 0.5), y = cy + Math.sin(a) * (cr + 0.5); if (y > H - 4) continue; if (CIRCLES.some(([ox, oy, or], oi) => oi !== ci && Math.hypot(x - ox, y - oy) < or - 2)) continue; out.push([x, y, 3 + r() * 3.5]); } }); return out; })(); const FIBERS: [number, number, number][] = (() => { const r = rng(29); const out: [number, number, number][] = []; const per = 46; CIRCLES.forEach(([cx, cy, cr], ci) => { for (let k = 0; k < per && out.length < 200; k++) { const a = (k / per) * Math.PI * 2 + r() * 0.25; const off = cr + 2.5 + r() * 1.5, rr = 1.4 + r() * 1.6; const x = cx + Math.cos(a) * off, y = cy + Math.sin(a) * off; if (y > H - 6) continue; if (CIRCLES.some(([ox, oy, or], oi) => oi !== ci && Math.hypot(x - ox, y - oy) < or - 1)) continue; out.push([x, y, rr]); } }); return out; })(); const BOLT: [number, number][] = ([[8, 0], [-10, 38], [0, 38], [-14, 90], [16, 30], [4, 30], [16, 0]] as [number, number][]).map(([x, y]) => [x * 1.25, y * 1.1] as [number, number]); type Drop = { x: number; y: number; vx: number; vy: number; floor: number }; type Splash = { x: number; y: number; vx: number; vy: number; age: number; r: number }; type Ripple = { x: number; age: number }; export function CloudButton({ children = "rain", 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 squashRef = useRef(null); const shadeRef = useRef(null); const glowRef = useRef(null); const wetRef = useRef(null); const floorRef = useRef(null); const grainRef = useRef(null); const playRef = useRef<() => void>(() => {}); const [playing, setPlaying] = useState(false); const uid = `tb-cloud-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; const paletteKey = JSON.stringify(palette); useImperativeHandle(ref, () => btnRef.current!, []); useEffect(() => { let dead = false; let grainUrl = ""; const el = btnRef.current; const host = wrapRef.current; const cv = canvasRef.current; const sq = squashRef.current; if (!el || !host || !cv || !sq) return; const ctx = cv.getContext("2d"); if (!ctx) return; const pal: Palette = JSON.parse(paletteKey); const media = window.matchMedia("(prefers-reduced-motion: reduce)"); const R = rng(5); let dpr = 1; try { const gc = document.createElement("canvas"); gc.width = gc.height = 192; const gx = gc.getContext("2d"); if (gx) { const GR = rng(23); const id = gx.createImageData(192, 192); for (let i = 0; i < id.data.length; i += 4) { const v = GR() < 0.5 ? 90 : 255; id.data[i] = id.data[i + 1] = id.data[i + 2] = v; id.data[i + 3] = 44; } gx.putImageData(id, 0, 0); const sc2 = document.createElement("canvas"); sc2.width = sc2.height = 48; const sx = sc2.getContext("2d"); if (sx) { const id2 = sx.createImageData(48, 48); for (let i = 0; i < id2.data.length; i += 4) { const v = GR() < 0.5 ? 90 : 255; id2.data[i] = id2.data[i + 1] = id2.data[i + 2] = v; id2.data[i + 3] = 255; } sx.putImageData(id2, 0, 0); gx.imageSmoothingEnabled = true; gx.globalAlpha = 0.5; gx.drawImage(sc2, 0, 0, 192, 192); } gc.toBlob((b) => { if (!b || dead) return; grainUrl = URL.createObjectURL(b); grainRef.current?.setAttribute("href", grainUrl); }); } } catch { /* grain is optional */ } let raf = 0; let last = 0; let visible = true; let hovering = false; let slant = 0; let rect: DOMRect | undefined; let dirty = true; let clickAt = -1; let ext = 0; let lightAt = -1e9; let sheenAt = -1e9; let bolts: [number, number][][] = []; let sparks: [number, number, number][][] = []; let emit = 0; let dark = 0; let pending: { at: number; n: number }[] = []; let sprites: HTMLCanvasElement[] = []; let bandGrad: CanvasGradient[] = []; let spines: [number, number][][] = []; let boltX: number[] = []; const sqx = { v: 0, a: 0 }; // squash spring, value in "scale delta" const sqy = { v: 0, a: 0 }; const lift = { v: 0, a: 0 }; let squashUntil = 0; let pressing = false; const drops: Drop[] = []; const splashes: Splash[] = []; const ripples: Ripple[] = []; let rmShow = 0; // reduced motion rainbow alpha let rmOn = false; let epoch = 0; const timers = 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 clearTimers = () => { epoch++; timers.forEach((id) => window.clearTimeout(id)); timers.clear(); }; const setup = () => { const scale = el.getBoundingClientRect().width / (el.offsetWidth || 1) || 1; dpr = Math.min(2, (window.devicePixelRatio || 1) * scale); cv.width = Math.round(CW * dpr); cv.height = Math.round(CH * dpr); dirty = true; bandGrad = pal.rainbow.map((c, i) => { const r = RB_R - BAND / 2 - i * BAND; const g = ctx.createRadialGradient(RB_CX, RB_CY, r - BAND / 2, RB_CX, RB_CY, r + BAND / 2); g.addColorStop(0, mix(c, "#000000", 0.28)); g.addColorStop(0.38, c); g.addColorStop(0.7, mix(c, "#ffffff", 0.42)); g.addColorStop(0.86, c); g.addColorStop(1, mix(c, "#000000", 0.12)); return g; }); sprites = [15, 18, 22].map((len) => { const c = document.createElement("canvas"); const cw = 24, chh = len + 12; c.width = Math.ceil(cw * dpr); c.height = Math.ceil(chh * dpr); const g = c.getContext("2d"); if (!g) return c; g.scale(dpr, dpr); g.translate(cw / 2, chh / 2); const h = len / 2, w = 6; g.beginPath(); g.moveTo(0, -h); g.bezierCurveTo(w * 0.3, -h * 0.3, w, h * 0.1, w, h * 0.45); g.bezierCurveTo(w, h * 0.95, -w, h * 0.95, -w, h * 0.45); g.bezierCurveTo(-w, h * 0.1, -w * 0.3, -h * 0.3, 0, -h); const gr = g.createLinearGradient(0, -h, 0, h); gr.addColorStop(0, "rgba(190,235,255,.10)"); gr.addColorStop(0.6, "rgba(120,200,255,.22)"); gr.addColorStop(1, "rgba(90,175,245,.45)"); g.fillStyle = gr; g.fill(); g.shadowBlur = 6; g.shadowColor = "rgba(90,200,255,.8)"; g.strokeStyle = "rgba(150,225,255,.95)"; g.lineWidth = 1.1; g.stroke(); g.shadowBlur = 0; g.shadowColor = "transparent"; g.strokeStyle = "rgba(225,250,255,.9)"; g.lineWidth = 1.2; g.beginPath(); g.arc(0, h * 0.45, w - 1.8, 0.15 * Math.PI, 0.85 * Math.PI); g.stroke(); g.fillStyle = "#fff"; g.beginPath(); g.ellipse(-2.2, h * 0.05, 1.4, 3.2, 0.3, 0, 6.2832); g.fill(); g.fillStyle = "rgba(255,255,255,.7)"; g.beginPath(); g.arc(-2.2, h * 0.5, 0.9, 0, 6.2832); g.fill(); return c; }); }; const spawn = (x: number, y: number, v0: number) => { if (drops.length > 140) return; drops.push({ x, y, vx: 0, vy: v0, floor: FLOOR + (R() - 0.5) * 16 }); }; const clearBolt = (x: number) => { const bx = boltX[0] ?? 125; return Math.abs(x - bx) < 22 ? x + (x < bx ? -26 : 26) : x; }; const burst = () => { const x = clearBolt(125 + (R() + R() - 1) * 95); spawn(x, 110 + R() * 22, 60 + R() * 200); }; const drawDrop = (d: Drop) => { const sp = Math.hypot(d.vx, d.vy); const bi = Math.min(2, Math.floor(clamp(sp / TERMINAL) * 3)); const spr = sprites[bi]; if (!spr) return; const len = [15, 18, 22][bi]; ctx.save(); ctx.translate(d.x, d.y); ctx.rotate(Math.atan2(-d.vx, d.vy)); ctx.drawImage(spr, -12, -(len + 12) / 2, 24, len + 12); ctx.restore(); }; const bandAlpha = (i: number, t: number, e: number) => 1 - clamp((t - (T_FADE + e) - i * 40) / 400); const rainbow = (t: number, e: number, forceFull: boolean, alpha: number) => { const p = forceFull ? 1 : easeOut((t - T_RB) / T_RB_GROW); if (p <= 0) return; ctx.save(); if (p > 0.15) { ctx.lineCap = "butt"; ctx.globalAlpha = 0.08 * alpha * (forceFull ? 1 : bandAlpha(0, t, e)); ctx.lineWidth = 6 * BAND + 4; ctx.strokeStyle = "#fff"; ctx.beginPath(); ctx.arc(RB_CX, RB_CY, RB_R - 3 * BAND, Math.PI, Math.PI + Math.PI * p); ctx.stroke(); } ctx.lineCap = "round"; for (let i = 0; i < pal.rainbow.length; i++) { const al = (forceFull ? 1 : bandAlpha(i, t, e)) * alpha * 0.9; if (al <= 0.003) continue; const r = RB_R - BAND / 2 - i * BAND; const a1 = Math.PI + Math.PI * p; ctx.globalAlpha = al; ctx.lineWidth = BAND + 0.8; ctx.strokeStyle = bandGrad[i] ?? pal.rainbow[i]; ctx.beginPath(); ctx.arc(RB_CX, RB_CY, r, Math.PI, a1); ctx.stroke(); } // sheen travelling along the arc const sh = forceFull ? -1 : (t - (sheenAt > 0 ? 0 : 0)) && 0; void sh; ctx.restore(); }; const farPuff = (scale: number, alpha: number) => { if (scale <= 0.01 || alpha <= 0) return; const mid = RB_R - 3 * BAND; const px = RB_CX + mid, py = RB_CY + 4; ctx.save(); ctx.globalAlpha = alpha; ctx.translate(px, py); ctx.scale(scale * 1.3, scale * 1.3); const parts: [number, number, number][] = [[0, 3, 12], [-10, 6, 8], [10, 5, 9], [3, -7, 10], [-6, -3, 8], [12, -4, 7], [-13, 0, 6], [6, 9, 7]]; parts.forEach(([x, y, r], pi) => { const g = ctx.createRadialGradient(x - r * 0.12, y - r * 0.2, r * 0.2, x, y, r); g.addColorStop(0, "#fff"); g.addColorStop(0.6, pal.cloud[0]); g.addColorStop(0.88, "#e9e8ee"); g.addColorStop(1, "#dcdbe2"); ctx.fillStyle = g; if (pi === 0) { ctx.shadowBlur = 6; ctx.shadowColor = "rgba(0,0,0,.22)"; ctx.shadowOffsetY = 2; } ctx.beginPath(); ctx.arc(x, y, r, 0, 6.2832); ctx.fill(); ctx.shadowBlur = 0; ctx.shadowColor = "transparent"; ctx.shadowOffsetY = 0; }); ctx.restore(); }; const flicker = (tl: number) => { if (tl < 0) return 0; if (tl < 60) return 1; if (tl < 100) return 0; if (tl < 190) return 1; if (tl < 390) return 1 - (tl - 190) / 200; return 0; }; const render = (now: number, t: number) => { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, CW, CH); ctx.translate(PL, PT); const e = ext; if (rmOn) { rainbow(0, 0, true, rmShow); farPuff(1, rmShow * 0.9); } else if (t >= T_RB) { rainbow(t, e, false, 1); // sheen pass const ts = now - sheenAt; if (ts >= 0 && ts < 300) { const a = Math.PI + Math.PI * (ts / 300); ctx.save(); ctx.globalAlpha = 0.3 * Math.sin(Math.PI * (ts / 300)); ctx.lineWidth = RB_R - 53; ctx.strokeStyle = "#fff"; ctx.beginPath(); ctx.arc(RB_CX, RB_CY, (RB_R + 53) / 2, a - 0.12, a + 0.12); ctx.stroke(); ctx.restore(); } const pop = rb((t - 700) / 200); const shrink = 1 - clamp((t - (T_FADE + e)) / 400); farPuff(pop * shrink, 1); } if (dark > 0.01) { ctx.save(); ctx.translate(125, 134); ctx.scale(1, 0.24); const ug = ctx.createRadialGradient(0, 0, 0, 0, 0, 100); ug.addColorStop(0, `rgba(120,200,255,${0.42 * dark})`); ug.addColorStop(1, "rgba(120,200,255,0)"); ctx.fillStyle = ug; ctx.beginPath(); ctx.arc(0, 0, 100, 0, 6.2832); ctx.fill(); ctx.restore(); } for (const d of drops) drawDrop(d); ctx.strokeStyle = "rgba(185,228,255,.85)"; for (const r of ripples) { ctx.globalAlpha = 0.16 * (1 - clamp(r.age / 300)); ctx.fillStyle = "rgb(130,190,230)"; ctx.beginPath(); ctx.ellipse(r.x, FLOOR, 6, 1.6, 0, 0, 6.2832); ctx.fill(); for (let q = 0; q < 2; q++) { const k = (r.age - q * 70) / 300; if (k < 0 || k > 1) continue; const sc = q ? 0.7 : 1; ctx.globalAlpha = 0.85 * (1 - k); ctx.lineWidth = 1; ctx.beginPath(); ctx.ellipse(r.x, FLOOR, (3 + 7 * k) * sc, (1.2 + 2 * k) * sc, 0, 0, 6.2832); ctx.stroke(); } } ctx.globalAlpha = 1; ctx.fillStyle = "rgba(150,205,240,.85)"; ctx.beginPath(); for (const s of splashes) { const rr = s.r * (1 - s.age / 300); ctx.moveTo(s.x + rr, s.y); ctx.arc(s.x, s.y, rr, 0, 6.2832); } ctx.fill(); ctx.fillStyle = "rgba(255,255,255,.8)"; ctx.beginPath(); for (const s of splashes) { const rr = 0.6 * (1 - s.age / 300); ctx.moveTo(s.x + rr, s.y); ctx.arc(s.x, s.y, rr, 0, 6.2832); } ctx.fill(); // lightning const tl = now - lightAt; const inten = flicker(tl); if (inten > 0.01 && bolts.length) { const bi = tl < 100 ? 0 : 1; const bolt = bolts[bi]; const ox = boltX[bi] ?? W / 2; ctx.save(); ctx.globalAlpha = inten; ctx.globalCompositeOperation = "lighter"; const bg = ctx.createRadialGradient(ox, 122, 0, ox, 122, 70); bg.addColorStop(0, `rgba(255,214,110,${0.4 * inten})`); bg.addColorStop(1, "rgba(255,214,110,0)"); ctx.fillStyle = bg; ctx.fillRect(ox - 70, 52, 140, 140); const bl = ctx.createRadialGradient(ox, 165, 0, ox, 165, 78); bl.addColorStop(0, `rgba(255,190,60,${0.45 * inten})`); bl.addColorStop(0.45, `rgba(255,150,40,${0.18 * inten})`); bl.addColorStop(1, "rgba(255,150,40,0)"); ctx.fillStyle = bl; ctx.fillRect(ox - 78, 87, 156, 156); ctx.globalCompositeOperation = "source-over"; const lg = ctx.createLinearGradient(0, 116, 0, 230); lg.addColorStop(0, "#fff8d6"); lg.addColorStop(0.4, "#ffd84a"); lg.addColorStop(1, "#ffaa1e"); const path = () => { ctx.beginPath(); bolt.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.closePath(); }; ctx.fillStyle = lg; ctx.shadowBlur = 26; ctx.shadowColor = "rgba(255,186,40,.85)"; path(); ctx.fill(); ctx.shadowBlur = 8; ctx.shadowColor = "rgba(255,236,150,.95)"; path(); ctx.fill(); ctx.shadowBlur = 0; const sp = spines[bi]; if (sp) { ctx.globalCompositeOperation = "lighter"; ctx.lineJoin = ctx.lineCap = "round"; const line = (w: number, c: string) => { ctx.lineWidth = w; ctx.strokeStyle = c; ctx.beginPath(); sp.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.stroke(); }; line(3.2, "rgba(255,236,170,.55)"); line(1.6, "rgba(255,255,245,.95)"); ctx.globalCompositeOperation = "source-over"; } ctx.lineJoin = "round"; ctx.strokeStyle = "#ffe27a"; ctx.lineWidth = 2.2; ctx.lineCap = "round"; ctx.beginPath(); for (const [x, y, a] of sparks[bi]) { ctx.moveTo(x, y); ctx.lineTo(x + Math.cos(a) * 10, y + Math.sin(a) * 10); } ctx.stroke(); ctx.restore(); } glowRef.current?.style.setProperty("opacity", String(inten)); }; const frame = (now: number) => { raf = 0; if (!canRun()) return; const dt = last ? Math.min(48, now - last) : 16; last = now; const sec = dt / 1000; const t = clickAt >= 0 ? now - clickAt : -1; // click timeline end if (clickAt >= 0 && t >= T_END + ext) { clickAt = -1; ext = 0; setPlaying(false); } const clicking = clickAt >= 0; // emission const rate = (hovering ? 13 : 0) + 0; let r = rate; if (clicking) r = Math.max(rate, t < T_RB + 650 ? 10 : t < T_FADE + ext ? 4 : 0); emit += r * sec; while (emit >= 1) { emit -= 1; let ex = 25 + R() * 200; if (now - lightAt < 450) ex = clearBolt(ex); spawn(ex, 118 + R() * 8, 120); } while (pending.length && now >= pending[0].at) { const pq = pending.shift()!; for (let i = 0; i < pq.n; i++) burst(); } // drops for (let i = drops.length - 1; i >= 0; i--) { const d = drops[i]; d.vy = Math.min(TERMINAL, d.vy + GRAVITY * sec); d.vx = d.vy * slant; d.x += d.vx * sec; d.y += d.vy * sec; if (d.y >= d.floor) { for (let k = 0; k < 3; k++) { const dir = k - 1 + (R() - 0.5) * 0.6; splashes.push({ x: d.x, y: FLOOR, vx: dir * (60 + R() * 60), vy: -(60 + R() * 60), age: 0, r: 1.2 + R() * 0.8 }); } if (ripples.length < 30) ripples.push({ x: d.x, age: 0 }); drops.splice(i, 1); } } for (let i = splashes.length - 1; i >= 0; i--) { const s = splashes[i]; s.age += dt; s.vy += GRAVITY * 0.6 * sec; s.x += s.vx * sec; s.y += s.vy * sec; if (s.age > 220 || s.y > FLOOR + 2) splashes.splice(i, 1); } for (let i = ripples.length - 1; i >= 0; i--) { ripples[i].age += dt; if (ripples[i].age > 370) ripples.splice(i, 1); } // squash springs back to a hover or rest target if (!hovering) pressing = false; const ty = hovering || clicking ? -0.02 : 0; const step = (s: { v: number; a: number }, target: number, k = 300, d = 18) => { s.v += (k * (target - s.a) - d * s.v) * sec; s.a += s.v * sec; if (Math.abs(s.a - target) < 0.0008 && Math.abs(s.v) < 0.02) { s.a = target; s.v = 0; } }; if (now < squashUntil) { step(sqx, 0.06, 1800, 70); step(sqy, -0.1, 1800, 70); } else if (pressing) { step(sqx, 0.025, 900, 45); step(sqy, -0.045, 900, 45); } else { step(sqx, 0); step(sqy, ty); } const lt = hovering || clicking ? -4 : 0; step(lift, lt, 300, 18); const sMoving = now < squashUntil || sqx.a !== 0 || sqy.a !== ty || sqx.v !== 0 || sqy.v !== 0 || lift.a !== lt || lift.v !== 0; if (floorRef.current) { floorRef.current.style.transform = `scale(${(1 + lift.a * 0.02).toFixed(3)})`; floorRef.current.style.opacity = String(1 + lift.a * 0.04); } sq.style.transform = `translateY(${lift.a.toFixed(2)}px) scale(${(1 + sqx.a).toFixed(4)},${(1 + sqy.a).toFixed(4)})`; // cloud darkening const dTarget = hovering || (clicking && t < T_END + ext) ? 1 : 0; dark += (dTarget - dark) * (1 - Math.exp(-dt / 120)); if (Math.abs(dTarget - dark) < 0.004) dark = dTarget; shadeRef.current?.style.setProperty("opacity", String(dark * 0.5 * (1 - 0.85 * flicker(now - lightAt)))); wetRef.current?.style.setProperty("opacity", String(dark * 0.8 * (1 - flicker(now - lightAt)))); render(now, t); const lightning = now - lightAt < 400; if (hovering || clicking || drops.length || splashes.length || ripples.length || sMoving || pending.length > 0 || dark !== dTarget || lightning) raf = requestAnimationFrame(frame); else { last = 0; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, CW, CH); sq.style.transform = ""; if (floorRef.current) { floorRef.current.style.transform = ""; floorRef.current.style.opacity = ""; } } }; const wake = () => { if (!raf && canRun()) { last = 0; raf = requestAnimationFrame(frame); } }; const reset = () => { cancelAnimationFrame(raf); raf = 0; last = 0; drops.length = splashes.length = ripples.length = 0; pending = []; sqx.a = sqx.v = sqy.a = sqy.v = lift.a = lift.v = 0; squashUntil = 0; pressing = false; dark = 0; clickAt = -1; ext = 0; lightAt = -1e9; shadeRef.current?.style.setProperty("opacity", "0"); wetRef.current?.style.setProperty("opacity", "0"); if (floorRef.current) { floorRef.current.style.transform = ""; floorRef.current.style.opacity = ""; } glowRef.current?.style.setProperty("opacity", "0"); sq.style.transform = ""; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, CW, CH); }; const refresh = () => { host.dataset.tbPaused = String(disabled || !visible || document.hidden); if (!canRun()) { if (!rmOn) { reset(); setPlaying(false); } } else wake(); }; const move = (e: PointerEvent) => { if (e.pointerType === "touch") return; if (dirty || !rect) { rect = el.getBoundingClientRect(); dirty = false; } const s = rect.width / (el.offsetWidth || 1) || 1; const x = (e.clientX - rect.left) / s; slant = -Math.tan((8 * Math.PI) / 180) * clamp((x - W / 2) / (W / 2), -1, 1); }; const enter = (e: PointerEvent) => { if (e.pointerType === "touch") return; dirty = true; hovering = true; move(e); wake(); }; const down = () => { if (disabled) return; pressing = true; wake(); }; const up = () => { pressing = false; wake(); }; const leave = () => { hovering = false; pressing = false; slant = 0; wake(); }; const invalidate = () => { dirty = true; }; const resize = () => { setup(); }; const io = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([en]) => { visible = en.isIntersecting; refresh(); }); const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(invalidate); const mediaChange = () => { clearTimers(); rmOn = false; rmShow = 0; setPlaying(false); reset(); refresh(); }; const makeBolts = () => { bolts = []; sparks = []; boltX = []; spines = []; for (let k = 0; k < 2; k++) { const ox = W / 2 + (R() - 0.5) * 40, flip = R() < 0.5 ? -1 : 1, sc = 0.9 + R() * 0.2; boltX.push(ox); bolts.push(BOLT.map(([x, y]) => [ox + flip * x * sc + (R() - 0.5) * 3, 110 + y * sc])); spines.push(([[12, 0], [-3, 35], [8, 33], [-14, 90]] as [number, number][]).map(([x, y]) => [ox + flip * x * 1.25 * sc, 110 + y * 1.1 * sc] as [number, number])); sparks.push(Array.from({ length: 8 }, (_, i) => { const a = (i / 8) * 6.2832 + R() * 0.5; return [ox + Math.cos(a) * (40 + R() * 22), 165 + Math.sin(a) * (34 + R() * 20), a] as [number, number, number]; })); } }; playRef.current = () => { if (disabled || el.matches(":disabled")) return; if (rmNow()) { if (rmOn) return; rmOn = true; setPlaying(true); const draw = (a: number) => { rmShow = a; render(performance.now(), -1); }; [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(() => { rmOn = false; rmShow = 0; setPlaying(false); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, CW, CH); }, 1560); return; } if (!canRun()) return; const now = performance.now(); const t = clickAt >= 0 ? now - clickAt : -1; if (clickAt < 0 || t >= T_FADE + ext) { clickAt = now; ext = 0; setPlaying(true); } else { if (ext === 0) ext = EXT; sheenAt = now; } squashUntil = now + 90; if (now - lightAt > 700) { makeBolts(); lightAt = now + 60; } for (let i = 0; i < 5; i++) burst(); pending = [40, 80, 120].map((ms) => ({ at: now + ms, n: 3 })); if (clickAt === now) sheenAt = now + 900; wake(); }; setup(); io?.observe(host); ro?.observe(el); window.addEventListener("resize", resize); window.addEventListener("scroll", invalidate, true); el.addEventListener("pointerenter", enter); el.addEventListener("pointermove", move); el.addEventListener("pointerleave", leave); el.addEventListener("pointerdown", down); el.addEventListener("pointerup", up); el.addEventListener("pointercancel", up); document.addEventListener("visibilitychange", refresh); media.addEventListener("change", mediaChange); refresh(); return () => { dead = true; if (grainUrl) URL.revokeObjectURL(grainUrl); playRef.current = () => {}; cancelAnimationFrame(raf); clearTimers(); io?.disconnect(); ro?.disconnect(); window.removeEventListener("resize", resize); window.removeEventListener("scroll", invalidate, true); el.removeEventListener("pointerenter", enter); el.removeEventListener("pointermove", move); el.removeEventListener("pointerleave", leave); el.removeEventListener("pointerdown", down); el.removeEventListener("pointerup", up); el.removeEventListener("pointercancel", up); document.removeEventListener("visibilitychange", refresh); media.removeEventListener("change", mediaChange); }; }, [disabled, paletteKey]); const click = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; playRef.current(); }; const [c0, c1, c2] = palette.cloud; const shape = ( {CIRCLES.map(([x, y, r], i) => )} {PUFFS.map(([x, y, r], i) => )} ); return ( ); } export default CloudButton; const css = ` .tb-cloud-wrap{display:inline-flex;position:relative;vertical-align:middle} .tb-cloud-btn{position:relative;display:block;box-sizing:border-box;width:${W}px;height:${H}px;padding:0;border:0; background:none;-webkit-appearance:none;appearance:none;overflow:visible;cursor:pointer;-webkit-tap-highlight-color:transparent;color:#464850} .tb-cloud-btn:focus-visible{outline:3px solid #6fb4ff;outline-offset:16px;border-radius:82px} .tb-cloud-btn:disabled{cursor:not-allowed} .tb-cloud-btn:disabled .tb-cloud-drift{opacity:.6;filter:saturate(.5);animation:none} .tb-cloud-canvas{position:absolute;left:-${PL}px;top:-${PT}px;width:${CW}px;height:${CH}px;max-width:none;pointer-events:none} .tb-cloud-drift{position:absolute;inset:0;display:block;pointer-events:none;animation:tb-cloud-drift 6s ease-in-out infinite} .tb-cloud-squash{position:absolute;inset:0;display:block;transform-origin:50% 100%;will-change:transform} .tb-cloud-art{position:absolute;left:0;top:0;overflow:visible} .tb-cloud-floor{position:absolute;left:22px;top:118px;width:206px;height:26px;border-radius:50%;pointer-events:none;background:radial-gradient(closest-side,rgba(6,8,16,.42),rgba(6,8,16,0))} .tb-cloud-glow,.tb-cloud-shade{opacity:0} .tb-cloud-puffs-a,.tb-cloud-puffs-b,.tb-cloud-puffs-c{transform-box:fill-box;transform-origin:center;animation:tb-cloud-breathe 5s ease-in-out infinite alternate} .tb-cloud-puffs-b{animation-duration:6.3s;animation-delay:-2.1s} .tb-cloud-puffs-c{animation-duration:7.6s;animation-delay:-4.4s} .tb-cloud-pill{position:absolute;left:65px;top:52px;width:120px;height:44px;box-sizing:border-box;display:flex;align-items:center;justify-content:center; border-radius:22px;background:linear-gradient(180deg,#ffffff 0%,#f4f3f1 45%,#dcdbe0 100%); box-shadow:inset 0 1.5px 0 #fff,inset 0 -2px 3px rgba(110,112,130,.30),0 0 0 1px rgba(140,142,160,.32),0 2px 3px rgba(40,44,60,.30),0 7px 14px -5px rgba(40,44,60,.45)} .tb-cloud-label{font:800 24px/1 ui-rounded,"SF Pro Rounded","Nunito","Segoe UI",system-ui,sans-serif;text-transform:uppercase;letter-spacing:.07em;font-size:23px;padding-top:1px; color:#353844;text-shadow:0 1px 0 rgba(255,255,255,.95),0 -0.5px 0 rgba(20,22,30,.30)} @keyframes tb-cloud-drift{0%,100%{transform:translateX(-2px)}50%{transform:translateX(2px)}} @keyframes tb-cloud-breathe{from{transform:scale(.985)}to{transform:scale(1.015)}} .tb-cloud-wrap[data-tb-paused=true] *{animation-play-state:paused!important} @media (prefers-reduced-motion:reduce){.tb-cloud-wrap *,.tb-cloud-wrap *::before,.tb-cloud-wrap *::after{animation:none!important;transition:none!important}} `;