"use client"; /** * snowglobe.tsx — a snow globe with a little village on a navy plinth. * Hover and a few flakes stir; click to shake it into a blizzard that slowly settles. * * 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 = { glass: string; plinth: string; rim: string; ink: string }; type Props = Omit, "children"> & { children?: ReactNode; ref?: Ref; palette?: Palette; flakes?: number; }; const W = 220; const H = 200; const PAD = 24; const CW = W + 2 * PAD; const CH = H + 2 * PAD; const GR = 75; // globe radius const GX = 110; // globe centre, button coordinates const GY = 61; const OX = GX + PAD - GR; // globe-local origin inside the canvas const OY = GY + PAD - GR; const PLINTH_Y = 136; const DEFAULT_PALETTE: Palette = { glass: "#2f4a66", plinth: "#1f3a5a", rim: "#c08a4a", ink: "#f0ece4" }; const T_SHAKE = 700; const T_END = 4200; const T_CLEAR = 3600; const MAX_FLAKES = 220; 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; }; } // scene geometry in globe-local coordinates (150 x 150) const groundY = (x: number) => 116 + 3 * Math.sin(x * 0.06 + 1); type Roof = { ax: number; ay: number; hw: number; by: number }; const ROOFS: Roof[] = [ { ax: 58, ay: 88, hw: 18, by: 98 }, // chapel nave { ax: 58, ay: 52, hw: 6, by: 70 }, // steeple { ax: 99, ay: 94, hw: 14, by: 104 }, // cottage A { ax: 119, ay: 101, hw: 9, by: 108 }, // cottage B ]; const surf = (x: number) => { let y = groundY(x); for (const r of ROOFS) { const d = Math.abs(x - r.ax); if (d < r.hw) y = Math.min(y, r.ay + (d / r.hw) * (r.by - r.ay)); } return y; }; const WINDOWS: [number, number, number, number][] = [[50, 105, 4, 6], [66, 105, 4, 6], [56, 76, 4, 6], [93, 109, 4, 5], [102, 109, 4, 5], [116, 112, 4, 4]]; function buildScene(dpr: number, glass: string) { const c = document.createElement("canvas"); c.width = Math.round(150 * dpr); c.height = Math.round(150 * dpr); const g = c.getContext("2d"); if (!g) return c; g.setTransform(dpr, 0, 0, dpr, 0, 0); g.save(); g.beginPath(); g.arc(75, 75, 75, 0, 6.2832); g.clip(); const bg = g.createLinearGradient(0, 0, 0, 150); bg.addColorStop(0, "#142a40"); bg.addColorStop(0.5, glass); bg.addColorStop(0.8, "#4a6380"); bg.addColorStop(1, "#6d8198"); g.fillStyle = bg; g.fillRect(0, 0, 150, 150); // stars of haze near the top g.fillStyle = "rgba(255,255,255,.22)"; for (let i = 0; i < 22; i++) { const r = rng(i + 3); g.fillRect(20 + r() * 110, 8 + r() * 40, 1.2, 1.2); } // far range g.fillStyle = "#6f8299"; g.beginPath(); g.moveTo(0,104); g.lineTo(18,90); g.lineTo(40,96); g.lineTo(62,84); g.lineTo(90,94); g.lineTo(112,86); g.lineTo(150,98); g.lineTo(150,118); g.lineTo(0,118); g.fill(); // mountains g.fillStyle = "#8a9bb0"; g.beginPath(); g.moveTo(0, 112); g.lineTo(10, 100); g.lineTo(35, 76); g.lineTo(52, 98); g.lineTo(78, 68); g.lineTo(100, 96); g.lineTo(118, 80); g.lineTo(150, 108); g.lineTo(150, 118); g.lineTo(0, 118); g.fill(); g.fillStyle = "#e9eef4"; for (const [px, py, w] of [[35, 76, 9], [78, 68, 11], [118, 80, 8]] as [number, number, number][]) { g.beginPath(); g.moveTo(px, py); g.lineTo(px - w, py + w * 1.2); g.lineTo(px - w * 0.3, py + w * 0.9); g.lineTo(px, py + w * 1.3); g.lineTo(px + w * 0.4, py + w * 0.9); g.lineTo(px + w, py + w * 1.2); g.closePath(); g.fill(); } const hz = g.createLinearGradient(0,70,0,118); hz.addColorStop(0,"rgba(190,205,225,0)"); hz.addColorStop(1,"rgba(190,205,225,.35)"); g.fillStyle = hz; g.fillRect(0,70,150,48); // ground const gg = g.createLinearGradient(0, 108, 0, 150); gg.addColorStop(0, "#d1cfd0"); gg.addColorStop(1, "#f2f4f7"); g.fillStyle = gg; g.beginPath(); g.moveTo(0, 150); g.lineTo(0, groundY(0)); for (let x = 0; x <= 150; x += 5) g.lineTo(x, groundY(x)); g.lineTo(150, 150); g.closePath(); g.fill(); const pine = (x: number, base: number, h: number, w: number) => { g.fillStyle = "#4a3a2a"; g.fillRect(x - 1, base - 3, 2, 4); for (let t = 0; t < 4; t++) { const ty = base - 3 - (t * h) / 4.4, tw = w * (1 - t * 0.22), th = h / 2.6; g.fillStyle = "#163d30"; g.beginPath(); g.moveTo(x, ty - th); g.lineTo(x - tw / 2, ty); g.lineTo(x + tw / 2, ty); g.fill(); g.fillStyle = "#2d6650"; g.beginPath(); g.moveTo(x, ty - th); g.lineTo(x + tw / 2, ty); g.lineTo(x + tw * 0.05, ty); g.fill(); g.fillStyle = "#f2f4f7"; g.beginPath(); g.moveTo(x, ty - th); g.lineTo(x - tw * 0.2, ty - th * 0.55); g.lineTo(x + tw * 0.22, ty - th * 0.6); g.fill(); g.beginPath(); g.ellipse(x - tw * 0.32, ty - 0.5, tw * 0.15, 1.6, 0, 0, 6.2832); g.fill(); } }; g.globalAlpha = .7; pine(42,113,14,8); pine(76,111,12,7); pine(85,112,16,9); pine(106,113,13,7); pine(140,111,15,8); g.globalAlpha = 1; // stream and bridge g.fillStyle = "#4d7aa3"; g.beginPath(); g.ellipse(75, 135, 24, 4.5, 0, 0, 6.2832); g.fill(); g.strokeStyle = "#8b8f96"; g.lineWidth = 3; g.lineCap = "round"; g.beginPath(); g.moveTo(60, 133); g.quadraticCurveTo(75, 122, 90, 133); g.stroke(); g.strokeStyle = "#e9eef4"; g.lineWidth = 1.2; g.beginPath(); g.moveTo(62, 130); g.quadraticCurveTo(75, 119.5, 88, 130); g.stroke(); g.fillStyle = "rgba(255,184,74,.28)"; for (const [x, y, rx, ry] of [[58, 119, 14, 3], [99, 119, 9, 2.5], [119, 120, 8, 2.2]]) { g.beginPath(); g.ellipse(x, y, rx, ry, 0, 0, 6.2832); g.fill(); } g.fillStyle = "rgba(90,110,140,.35)"; for (const [x, y, rx] of [[20, groundY(20) + 1, 15], [32, groundY(32), 11], [114, groundY(114) - 1, 11], [130, groundY(130) + 1, 16], [58, 118.5, 17], [99, 118.5, 14], [119, 119.5, 10]]) { g.beginPath(); g.ellipse(x, y, rx, 2, 0, 0, 6.2832); g.fill(); } // pines pine(32, groundY(32), 28, 16); pine(114, groundY(114) - 1, 30, 16); pine(20, groundY(20) + 1, 46, 24); pine(130, groundY(130) + 1, 50, 26); // buildings const house = (x0: number, y0: number, w: number, h: number, roof: Roof, wall: string) => { g.fillStyle = wall; g.fillRect(x0, y0, w, h); g.fillStyle = "#c9bca7"; g.fillRect(x0 + w * 0.6, y0, w * 0.4, h); g.fillStyle = "#f2f4f7"; g.beginPath(); g.moveTo(roof.ax, roof.ay); g.lineTo(roof.ax - roof.hw - 2, roof.by); g.lineTo(roof.ax + roof.hw + 2, roof.by); g.closePath(); g.fill(); g.fillStyle = "#d6dce5"; g.beginPath(); g.moveTo(roof.ax, roof.ay); g.lineTo(roof.ax + roof.hw + 2, roof.by); g.lineTo(roof.ax + 2, roof.by); g.closePath(); g.fill(); }; g.fillStyle = "#e7dccb"; g.fillRect(54, 68, 8, 28); g.fillStyle = "#f2f4f7"; g.beginPath(); g.moveTo(58, 52); g.lineTo(52, 70); g.lineTo(64, 70); g.closePath(); g.fill(); g.fillStyle = "#d6dce5"; g.beginPath(); g.moveTo(58, 52); g.lineTo(64, 70); g.lineTo(59, 70); g.closePath(); g.fill(); house(44, 98, 28, 20, ROOFS[0], "#e7dccb"); house(88, 104, 22, 14, ROOFS[2], "#e7dccb"); house(112, 108, 14, 11, ROOFS[3], "#e0d4c0"); g.fillStyle = "#8a4a32"; g.fillRect(104, 90, 3, 6); g.fillStyle = "#6b4a30"; g.fillRect(56, 109, 4, 9); g.fillStyle = "#ffcf7a"; for (const [x, y, w, h] of WINDOWS) g.fillRect(x, y, w, h); // six flakes lying on the ground g.fillStyle = "#fff"; for (const [x, y] of [[26, 127], [48, 131], [72, 142], [98, 128], [121, 133], [84, 138]]) { g.beginPath(); g.arc(x, y, 1.3, 0, 6.2832); g.fill(); } g.restore(); return c; } type Flake = { x: number; y: number; vx: number; vy: number; r: number; seed: number; hover: boolean; landed: number; alpha: number; z: number }; export function SnowGlobeButton({ children = "shake", palette = DEFAULT_PALETTE, flakes: flakeCount = 200, onClick, className, type = "button", disabled = false, ref, ...rest }: Props) { const btnRef = useRef(null); const wrapRef = useRef(null); const canvasRef = useRef(null); const shakeRef = useRef(null); const tiltRef = useRef(null); const arcsRef = useRef(null); const boostRef = useRef(null); const playRef = useRef<() => void>(() => {}); const [playing, setPlaying] = useState(false); const uid = `tb-snowglobe-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; const paletteKey = JSON.stringify(palette); useImperativeHandle(ref, () => btnRef.current!, []); useEffect(() => { const el = btnRef.current; const host = wrapRef.current; const cv = canvasRef.current; const tiltEl = tiltRef.current; if (!el || !host || !cv || !tiltEl) 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(33); const total = Math.min(MAX_FLAKES, flakeCount); let dpr = 1; let scene: HTMLCanvasElement | null = null; let sprite: HTMLCanvasElement | null = null; let spriteBack: HTMLCanvasElement | null = null; let spriteSoft: HTMLCanvasElement | null = null; let raf = 0; let last = 0; let visible = true; let hovering = false; let rect: DOMRect | undefined; let dirty = true; let clickAt = -1; let impulseN = 0; let swirlDir = 1; let nextHoverSpawn = 0; const tilt = { a: 0, v: 0 }; let tiltTarget = 0; const flakes: Flake[] = []; let rmFlakes: [number, number, number][] = []; let rmAlpha = 0; let epoch = 0; 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(); }; const makeSprite = () => { const c = document.createElement("canvas"); c.width = 32; c.height = 32; const g = c.getContext("2d"); if (!g) return c; const gr = g.createRadialGradient(16, 16, 0, 16, 16, 16); gr.addColorStop(0, "rgba(255,255,255,1)"); gr.addColorStop(0.45, "rgba(255,255,255,.9)"); gr.addColorStop(1, "rgba(255,255,255,0)"); g.fillStyle = gr; g.fillRect(0, 0, 32, 32); return c; }; const makeSprite2 = (col: string, soft: boolean) => { const c = document.createElement("canvas"); c.width = 32; c.height = 32; const g = c.getContext("2d"); if (!g) return c; const gr = g.createRadialGradient(16, 16, 0, 16, 16, 16); gr.addColorStop(0, col); gr.addColorStop(soft ? 0.15 : 0.45, col); gr.addColorStop(1, "rgba(255,255,255,0)"); g.fillStyle = gr; g.fillRect(0, 0, 32, 32); return c; }; const setup = () => { const s = el.getBoundingClientRect().width / (el.offsetWidth || 1) || 1; dpr = Math.min(2, (window.devicePixelRatio || 1) * s); cv.width = Math.round(CW * dpr); cv.height = Math.round(CH * dpr); scene = buildScene(dpr, pal.glass); sprite = sprite ?? makeSprite(); spriteBack = spriteBack ?? makeSprite2("#cfdcf0", false); spriteSoft = spriteSoft ?? makeSprite2("#ffffff", true); dirty = true; }; const flakeSize = (hover: boolean) => { if (hover) return { r: 1.1 + R() * 1.1, z: 0.5 }; const z = R(); return { z, r: z > 0.75 ? 0.6 + R() * 0.4 : z >= 0.12 ? 1 + R() : 1.8 + R() * 1.0 }; }; const spawn = (hover: boolean, launch: boolean) => { if (hover && !launch) { const x = 22 + R()*106, y = 18 + R()*92; if (Math.hypot(x-75, y-75) > 66) return; flakes.push({ x, y, vx: (R()-.5)*16, vy: 6 + R()*10, ...flakeSize(true), seed: R()*6.28, hover: true, landed: 0, alpha: 0, z: .5 }); return; } const x = launch ? 14 + R() * 122 : 22 + R() * 106; const y = launch ? surf(x) - R() * R() * 40 : Math.min(surf(x), 148) - R() * 3; const dx = x - 75, dy = y - 75; if (Math.hypot(dx, dy) > (launch ? 68 : 70)) return; flakes.push({ x, y, vx: launch ? (R() - 0.5) * 220 : (R() - 0.5) * 24, vy: launch ? -(50 + R() * 150) : -(10 + R() * 20) * (R() < 0.5 ? 1 : 0.3), ...flakeSize(hover), seed: R() * 6.28, hover, landed: 0, alpha: 1, }); }; const draw = (now: number, hz = 0) => { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, CW, CH); if (!scene || !sprite) return; ctx.save(); ctx.translate(OX, OY); ctx.beginPath(); ctx.arc(75, 75, 74, 0, 6.2832); ctx.clip(); ctx.drawImage(scene, 0, 0, 150, 150); if (hz > 0) { ctx.globalAlpha = 1; const hg = ctx.createRadialGradient(75, 90, 0, 75, 90, 80); hg.addColorStop(0, `rgba(235,242,250,${(0.3 * hz).toFixed(3)})`); hg.addColorStop(1, `rgba(220,232,246,${(0.12 * hz).toFixed(3)})`); ctx.fillStyle = hg; ctx.beginPath(); ctx.arc(75, 75, 74, 0, 6.2832); ctx.fill(); } if (rmAlpha > 0) { ctx.globalAlpha = 0.8 * rmAlpha; for (const [x, y, r] of rmFlakes) ctx.drawImage(sprite, x - r * 1.6, y - r * 1.6, r * 3.2, r * 3.2); } void now; for (const band of [0, 1, 2]) { const streaks: Flake[] = []; for (const f of flakes) { const b = f.hover ? 1 : f.z > 0.75 ? 0 : f.z >= 0.12 ? 1 : 2; if (b !== band) continue; const depth = 1 - 0.3 * clamp((f.y - 60) / 90); if (b === 1 && !f.landed && Math.hypot(f.vx, f.vy) > 90) { streaks.push(f); continue; } const ba = b === 0 ? 0.55 : b === 1 ? 0.9 : 0.38; ctx.globalAlpha = clamp(f.alpha * depth * ba); const d = f.r * 3.2; ctx.drawImage((b === 0 ? spriteBack : b === 2 ? spriteSoft : sprite) ?? sprite, f.x - d / 2, f.y - d / 2, d, d); } if (streaks.length) { ctx.lineCap = "round"; ctx.strokeStyle = "#fff"; for (const f of streaks) { const depth = 1 - 0.3 * clamp((f.y - 60) / 90); ctx.lineWidth = Math.max(0.9, f.r * 0.9); ctx.globalAlpha = clamp(f.alpha * depth * 0.6); ctx.beginPath(); ctx.moveTo(f.x, f.y); ctx.lineTo(f.x - f.vx * 0.012, f.y - f.vy * 0.012); ctx.stroke(); } } } ctx.restore(); ctx.globalAlpha = 1; }; const tick = (now: number) => { raf = 0; if (!canRun()) return; const dt = last ? Math.min(48, now - last) / 1000 : 0.016; last = now; // tilt spring tilt.v += (140 * (tiltTarget - tilt.a) - 16 * tilt.v) * dt; tilt.a += tilt.v * dt; tiltEl.style.transform = `rotate(${tilt.a.toFixed(3)}deg)`; const tilting = Math.abs(tilt.a - tiltTarget) > 0.002 || Math.abs(tilt.v) > 0.01; let t = -1; if (clickAt >= 0) { t = now - clickAt; if (t >= T_END) { clickAt = -1; t = -1; setPlaying(false); } } // sloshing: each change of direction of the shake nudges all flakes sideways if (t >= 0) { while (impulseN < 6 && t >= (impulseN + 1) * 110 + 16) { const s = (impulseN % 2 === 0 ? 1 : -1) * 60; swirlDir = s > 0 ? 1 : -1; for (const f of flakes) if (!f.landed) f.vx += s * (0.5 + f.seed / 6.28); impulseN++; } } // hover keeps a few flakes stirring if (hovering && t < 0 && now >= nextHoverSpawn) { nextHoverSpawn = now + 180; if (flakes.filter((f) => f.hover && !f.landed).length < 28) spawn(true, false); } const tsec = now / 1000; for (let i = flakes.length - 1; i >= 0; i--) { const f = flakes[i]; if (f.landed) { const age = now - f.landed; f.alpha = age < 600 ? 1 - 0.8 * (age / 600) : 0.2 * (1 - clamp((age - 600) / 900)); if (age > 1500) flakes.splice(i, 1); continue; } let drag: number, grav: number; if (f.hover) { f.alpha = Math.min(1, f.alpha + dt*3); drag = 1.2; grav = 14; const dx = f.x - 75, dy = f.y - 75; f.vx += (-dy / 75 * 12 - f.vx) * 0.8 * dt; f.vy += (dx / 75 * 6 - f.vy) * 0.4 * dt; } else { drag = t >= 0 && t < T_SHAKE ? 2.6 : 2.2; grav = 40; f.vx += 18 * Math.sin(tsec * 3 + f.seed) * dt; if (t >= 0 && t < 1600) { const aT = 140 * (1 - t / 1600) * swirlDir; const sx = f.x - 75, sy = f.y - 80, sd = Math.max(8, Math.hypot(sx, sy)); f.vx += -sy / sd * aT * dt; f.vy += sx / sd * aT * dt; } } const k = Math.exp(-drag * dt); f.vx *= k; f.vy = f.vy * k + grav * dt; f.x += f.vx * dt; f.y += f.vy * dt; const dx = f.x - 75, dy = f.y - 75, d = Math.hypot(dx, dy); if (d > 72) { const nx = dx / d, ny = dy / d; f.x = 75 + nx * 72; f.y = 75 + ny * 72; const vn = f.vx * nx + f.vy * ny; if (vn > 0) { f.vx -= 1.3 * vn * nx; f.vy -= 1.3 * vn * ny; } } if (f.vy > 0 && f.y >= surf(f.x) - 0.5) { f.y = surf(f.x) - 0.5; f.landed = now; f.vx = f.vy = 0; } } // click-time fade of everything that is left, so RESET is clean if (t >= T_CLEAR) for (const f of flakes) if (!f.hover) f.alpha = Math.min(f.alpha, 1 - clamp((t - T_CLEAR) / 400)); const hzv = t < 0 ? 0 : t < 150 ? t / 150 : t < 900 ? 1 : Math.max(0, 1 - (t - 900) / 1700); draw(now, hzv); const busy = hovering || clickAt >= 0 || flakes.length > 0 || tilting; if (busy) raf = requestAnimationFrame(tick); else { last = 0; tiltEl.style.transform = ""; } }; const wake = () => { if (!raf && canRun()) { last = 0; raf = requestAnimationFrame(tick); } }; const idle = () => { flakes.length = 0; rmAlpha = 0; tilt.a = tilt.v = 0; tiltEl.style.transform = ""; draw(0); }; const refresh = () => { host.dataset.tbPaused = String(disabled || !visible || document.hidden); if (!canRun()) { cancelAnimationFrame(raf); raf = 0; last = 0; if (rmAlpha === 0) { clickAt = -1; setPlaying(false); idle(); } } 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; tiltTarget = 2 * clamp(((e.clientX - rect.left) / s - W / 2) / (W / 2), -1, 1); wake(); }; const enter = (e: PointerEvent) => { if (e.pointerType === "touch") return; dirty = true; hovering = true; nextHoverSpawn = 0; move(e); if (!rmNow()) for (let i = 0; i < 28; i++) spawn(true, false); wake(); }; const leave = () => { hovering = false; tiltTarget = 0; for (const f of flakes) if (f.hover) f.hover = false; wake(); }; const invalidate = () => { dirty = true; }; const io = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([en]) => { visible = en.isIntersecting; refresh(); }); const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(invalidate); const resize = () => { setup(); draw(0); }; const mediaChange = () => { clearAll(); setPlaying(false); rmAlpha = 0; rmFlakes = []; clickAt = -1; refresh(); idle(); }; playRef.current = () => { if (disabled || el.matches(":disabled")) return; if (rmNow()) { if (rmAlpha > 0) return; setPlaying(true); rmFlakes = Array.from({ length: 80 }, () => { const a = R() * 6.2832, d = Math.sqrt(R()) * 66; return [75 + Math.cos(a) * d, 75 + Math.sin(a) * d * 0.95, 0.8 + R() * 1.2] as [number, number, number]; }); rmAlpha = 1; draw(0); [1400, 1450, 1500, 1550].forEach((ms, i) => later(() => { rmAlpha = 1 - (i + 1) / 4; draw(0); }, ms)); later(() => { rmAlpha = 0; rmFlakes = []; setPlaying(false); draw(0); }, 1620); return; } if (!canRun()) return; const E = "cubic-bezier(.37,0,.63,1)"; const now = performance.now(); // a repeat click re-launches everything, landed flakes included for (const f of flakes) { f.landed = 0; f.alpha = 1; f.hover = false; f.vx = (R() - 0.5) * 220; f.vy = -(50 + R() * 150); } let live = flakes.length; for (let tries = 0; live < total && tries < total * 4; tries++) { const before = flakes.length; spawn(false, true); if (flakes.length > before) live++; } clickAt = now; impulseN = 0; swirlDir = 1; setPlaying(true); anim(shakeRef.current, [ { transform: "translate(0,0) rotate(0deg)", easing: E }, { transform: "translate(-5px,-6px) rotate(-9deg)", offset: 0.16, easing: E }, { transform: "translate(5px,-4px) rotate(8deg)", offset: 0.32, easing: E }, { transform: "translate(-4px,-3px) rotate(-6deg)", offset: 0.48, easing: E }, { transform: "translate(3px,-2px) rotate(4deg)", offset: 0.64, easing: E }, { transform: "translate(-1px,-1px) rotate(-2deg)", offset: 0.8, easing: E }, { transform: "translate(0,0) rotate(0deg)" }, ], { duration: T_SHAKE, easing: "linear" }); anim(shakeRef.current, [{ transform: "scale(1,1)" }, { transform: "scale(1.025,.965)", offset: 0.35 }, { transform: "scale(1,1)" }], { duration: 220, delay: T_SHAKE, easing: "cubic-bezier(.3,1.6,.5,1)" }); anim(arcsRef.current, [{ opacity: 0 }, { opacity: 1, offset: 0.35 }, { opacity: 0 }], { duration: T_SHAKE }); anim(boostRef.current, [{ opacity: 0 }, { opacity: 0.9, offset: 0.2 }, { opacity: 0.9, offset: 0.45 }, { opacity: 0 }], { duration: 1400, delay: 400 }); wake(); }; setup(); draw(0); 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); document.addEventListener("visibilitychange", refresh); media.addEventListener("change", mediaChange); refresh(); return () => { playRef.current = () => {}; cancelAnimationFrame(raf); clearAll(); 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); document.removeEventListener("visibilitychange", refresh); media.removeEventListener("change", mediaChange); }; }, [disabled, paletteKey, flakeCount]); const click = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; playRef.current(); }; const label = typeof children === "string" ? children : ""; const arm = "M0 0V-9M0 -5.5L-2.6 -8M0 -5.5L2.6 -8"; const flake = (x: number, y: number) => ( {[0, 60, 120, 180, 240, 300].map((a) => )} ); const winGlow = ( {WINDOWS.map(([x, y, w, h], i) => ( ))} ); return ( ); } // the plinth colour prop feeds the gradient midpoint function pal(c: string) { return c; } export default SnowGlobeButton; const css = ` .tb-snowglobe-wrap{display:inline-flex;position:relative;vertical-align:middle} .tb-snowglobe-btn{position:relative;display:block;box-sizing:border-box;width:${W}px;height:${H}px;padding:0;border:0;border-radius:36px; background:transparent;overflow:visible;cursor:pointer;-webkit-tap-highlight-color:transparent} .tb-snowglobe-btn:focus-visible{outline:3px solid #5aa0ff;outline-offset:19px} .tb-snowglobe-btn:disabled{cursor:not-allowed} .tb-snowglobe-btn:disabled .tb-snowglobe-shake{opacity:.6;filter:saturate(.5)} .tb-snowglobe-shake,.tb-snowglobe-tilt{position:absolute;inset:0;display:block;transform-origin:${GX}px ${H}px;pointer-events:none} .tb-snowglobe-canvas{position:absolute;left:-${PAD}px;top:-${PAD}px;width:${CW}px;height:${CH}px;max-width:none;pointer-events:none} .tb-snowglobe-art{position:absolute;left:-${PAD}px;top:-${PAD}px;overflow:visible;pointer-events:none;max-width:none;filter:drop-shadow(0 3px 3px rgba(0,0,0,.35))} .tb-snowglobe-flicker{opacity:.88;animation:tb-snowglobe-flick 2.4s ease-in-out infinite alternate} .tb-snowglobe-boost{opacity:0} .tb-snowglobe-arcs{opacity:0} .tb-snowglobe-glowring{opacity:0;transition:opacity 220ms ease-out;filter:drop-shadow(0 0 7px rgba(80,150,255,.8))} .tb-snowglobe-btn:not(:disabled):hover .tb-snowglobe-glowring{opacity:1} .tb-snowglobe-bloom{opacity:0;transition:opacity 220ms ease-out;filter:blur(4px)} .tb-snowglobe-btn:not(:disabled):hover .tb-snowglobe-bloom{opacity:1} .tb-snowglobe-lift{position:absolute;inset:0;display:block;pointer-events:none;transform-origin:${GX}px ${H}px;transition:transform 240ms cubic-bezier(.3,1.4,.5,1)} .tb-snowglobe-btn:not(:disabled):hover .tb-snowglobe-lift{transform:translateY(-3px)} .tb-snowglobe-btn:not(:disabled):active .tb-snowglobe-lift{transform:translateY(1px) scale(1.015,.975);transition-duration:90ms} .tb-snowglobe-btn:not(:disabled):hover .tb-snowglobe-arcs{opacity:.55;transition:opacity 220ms} .tb-snowglobe-floor{position:absolute;left:10px;top:198px;width:200px;height:22px;border-radius:50%;background:radial-gradient(closest-side,rgba(0,0,0,.55),rgba(0,0,0,.25) 55%,transparent);pointer-events:none;transition:transform 240ms,opacity 240ms} .tb-snowglobe-btn:not(:disabled):hover .tb-snowglobe-floor{transform:scaleX(.94);opacity:.8} @keyframes tb-snowglobe-flick{from{opacity:.82}to{opacity:.95}} .tb-snowglobe-wrap[data-tb-paused=true] *{animation-play-state:paused!important} @media (prefers-reduced-motion:reduce){.tb-snowglobe-arcs{opacity:0!important}.tb-snowglobe-lift{transform:none!important}.tb-snowglobe-wrap *,.tb-snowglobe-wrap *::before,.tb-snowglobe-wrap *::after{animation:none!important;transition:none!important}} `;