{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"snowfall","type":"registry:component","title":"Snowfall","description":"Snow that settles on whatever you wrap: it caps your logo, packs into the gaps between its shapes, and a tap knocks it off.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/snowfall.tsx","type":"registry:component","content":"// Hairline UI · snowfall · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { createSpring, useInteractionActivity, useInteractionReducedMotion, type Spring } from \"./ui-interaction-motion\";\nimport { createSnowRenderer, type SnowRenderer } from \"./snowfall-gl\";\nimport { readShape, snowLayout, SnowSim } from \"./snowfall-sim\";\n\n/* ─────────────────────────────────────────────────────────\n * SNOWFALL: snow that settles on whatever you wrap\n *\n *   falling    flakes drift down at three depths around the\n *              element: far ones pass behind it, near ones blur\n *              past in front\n *   settling   snow caps every top edge, rounding off at the\n *              ends; in a logo made of shapes on a plate, the\n *              narrow gaps between them fill from the bottom up\n *   dressed    once it is covered the snowfall thins out and\n *              stops; nothing moves until the next one\n *   shaken     a tap knocks the element: the snow pops up with\n *              it, breaks into clumps and falls away, then it\n *              snows again\n *\n * Inline SVG is read shape by shape, an <img> by its alpha,\n * anything else by its box and corner radius.\n *\n * Reduced motion: the element appears already dressed in snow,\n * with no flakes and no shake.\n * ───────────────────────────────────────────────────────── */\n\nexport interface SnowfallProps extends Omit<React.HTMLAttributes<HTMLSpanElement>, \"children\"> {\n  /** What the snow settles on: an inline SVG logo, an image, a button, a card. One element. */\n  children: React.ReactNode;\n  /** Whether snow is falling. Turn it off and the flakes in the air finish their fall; settled snow stays. */\n  snowing?: boolean;\n  /** How heavily it snows, 0.25 to 2. */\n  intensity?: number;\n  /** Keep a light snowfall going once the element is dressed, instead of stopping. */\n  keepFalling?: boolean;\n  /** Knock the snow off when the element is pressed (pointer, Enter or Space). */\n  shake?: boolean;\n  /** Called when a snowfall has dressed the element and everything is still. */\n  onSettled?: () => void;\n}\n\ntype Geo = { x: number; y: number; w: number; h: number; dpr: number };\n\ntype Engine = {\n  sim: SnowSim | null;\n  renderer: SnowRenderer | null;\n  raf: number;\n  last: number;\n  light: boolean;\n  frame: (now: number) => void;\n  paint: () => void;\n  wake: () => void;\n};\n\nconst round = (v: number) => Math.round(v * 2) / 2;\n\n/** Whether the page behind is light, judged from the text colour (dark text, light page). Works for any colour syntax. */\nfunction isLightPage(el: Element) {\n  const probe = document.createElement(\"canvas\");\n  probe.width = probe.height = 1;\n  const ctx = probe.getContext(\"2d\", { willReadFrequently: true });\n  if (!ctx) return true;\n  ctx.fillStyle = getComputedStyle(el).color;\n  ctx.fillRect(0, 0, 1, 1);\n  const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data;\n  return 0.2126 * r + 0.7152 * g + 0.0722 * b < 140;\n}\n\nexport function Snowfall({\n  children,\n  snowing = true,\n  intensity = 1,\n  keepFalling = false,\n  shake = true,\n  onSettled,\n  className = \"\",\n  onPointerDown,\n  onKeyDown,\n  ...props\n}: SnowfallProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: host, active } = useInteractionActivity<HTMLSpanElement>();\n  const layer = React.useRef<HTMLSpanElement>(null);\n  const canvas = React.useRef<HTMLCanvasElement>(null);\n  const jolt = React.useRef<Spring | null>(null);\n  const [geo, setGeo] = React.useState<Geo | null>(null);\n  const layout = React.useMemo(() => (geo ? snowLayout(geo.w, geo.h, geo.dpr) : null), [geo]);\n  const live = React.useRef({ active, reduced, snowing, intensity, keepFalling, onSettled, dpr: 1, cw: 0, ch: 0 });\n  const engine = React.useRef<Engine | null>(null);\n\n  React.useEffect(() => {\n    live.current = { ...live.current, active, reduced, snowing, intensity: Math.min(2, Math.max(0.25, intensity)), keepFalling, onSettled };\n  });\n\n  // The renderer, the frame loop and the shake spring live as long as the component.\n  React.useEffect(() => {\n    const el = canvas.current;\n    const hostEl = host.current;\n    if (!el || !hostEl) return;\n    const e: Engine = {\n      sim: null,\n      renderer: createSnowRenderer(el),\n      raf: 0,\n      last: 0,\n      light: isLightPage(hostEl),\n      frame: () => {},\n      paint: () => {},\n      wake: () => {},\n    };\n    const draw = (time: number, upload: boolean) => {\n      const { sim, renderer } = e;\n      if (!sim || !renderer) return;\n      const L = live.current;\n      renderer.draw({\n        view: upload || sim.viewDirty ? sim.view : null,\n        clumps: upload || sim.viewDirty ? sim.clumpView : null,\n        instances: sim.instances,\n        count: sim.instanceCount,\n        width: L.cw,\n        height: L.ch,\n        dpr: L.dpr,\n        light: e.light,\n        time,\n      });\n      sim.viewDirty = false;\n    };\n    e.frame = (now) => {\n      const { sim } = e;\n      const L = live.current;\n      if (!sim || !e.renderer) {\n        e.raf = 0;\n        return;\n      }\n      const dt = e.last ? Math.min(0.05, (now - e.last) / 1000) : 1 / 60;\n      e.last = now;\n      sim.snowing = L.snowing;\n      sim.intensity = L.intensity;\n      sim.keepFalling = L.keepFalling;\n      const moving = sim.step(dt);\n      draw(now / 1000, false);\n      if (sim.takeSettled()) L.onSettled?.();\n      if (moving && L.active && !L.reduced) e.raf = requestAnimationFrame(e.frame);\n      else {\n        e.raf = 0;\n        e.last = 0;\n      }\n    };\n    e.paint = () => {\n      if (!e.raf) draw(performance.now() / 1000, true);\n    };\n    e.wake = () => {\n      const L = live.current;\n      if (e.raf || !e.sim || !e.renderer || !L.active || L.reduced) return;\n      e.last = 0;\n      e.raf = requestAnimationFrame(e.frame);\n    };\n    engine.current = e;\n\n    const lost = (event: Event) => {\n      event.preventDefault();\n      cancelAnimationFrame(e.raf);\n      e.raf = 0;\n      e.renderer = null;\n    };\n    el.addEventListener(\"webglcontextlost\", lost);\n    const theme = new MutationObserver(() => {\n      const light = isLightPage(hostEl);\n      if (light === e.light) return;\n      e.light = light;\n      e.paint();\n    });\n    theme.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n\n    const spring = createSpring(\n      0,\n      { stiffness: 560, damping: 15 },\n      () => {\n        if (layer.current) layer.current.style.translate = `0 ${spring.get().toFixed(2)}px`;\n      },\n      0.02,\n    );\n    jolt.current = spring;\n\n    return () => {\n      cancelAnimationFrame(e.raf);\n      e.raf = 0;\n      el.removeEventListener(\"webglcontextlost\", lost);\n      theme.disconnect();\n      spring.stop();\n      e.renderer?.dispose();\n      e.renderer = null;\n      e.sim = null;\n      engine.current = null;\n    };\n  }, [host]);\n\n  // Measure the wrapped element; the canvas reaches past it on every side for the snowfall.\n  React.useEffect(() => {\n    const hostEl = host.current;\n    const layerEl = layer.current;\n    if (!hostEl || !layerEl) return;\n    const target = layerEl.firstElementChild ?? layerEl;\n    const measure = () => {\n      const hr = hostEl.getBoundingClientRect();\n      const tr = target.getBoundingClientRect();\n      const lift = jolt.current?.get() ?? 0;\n      const next: Geo = { x: round(tr.left - hr.left), y: round(tr.top - hr.top - lift), w: round(tr.width), h: round(tr.height), dpr: Math.min(2, window.devicePixelRatio || 1) };\n      if (next.w < 4 || next.h < 4) return;\n      setGeo((p) => (p && p.x === next.x && p.y === next.y && p.w === next.w && p.h === next.h && p.dpr === next.dpr ? p : next));\n    };\n    const observer = new ResizeObserver(measure);\n    observer.observe(hostEl);\n    observer.observe(target);\n    return () => observer.disconnect();\n  }, [host]);\n\n  // Read the shape and start a snowfall whenever the element's size changes.\n  React.useEffect(() => {\n    const e = engine.current;\n    const layerEl = layer.current;\n    if (!layout || !geo || !e || !e.renderer || !layerEl) return;\n    let cancelled = false;\n    const target = layerEl.firstElementChild ?? layerEl;\n    readShape(target, layout)\n      // Building the simulation is the other half of the work; give the page a frame in between.\n      .then((shape) => new Promise<typeof shape>((resolve) => setTimeout(() => resolve(shape), 0)))\n      .then((shape) => {\n        if (cancelled || !e.renderer) return;\n        const L = live.current;\n        L.dpr = geo.dpr;\n        L.cw = layout.cw;\n        L.ch = layout.ch;\n        const sim = new SnowSim(shape, layout);\n        sim.snowing = L.snowing;\n        sim.intensity = L.intensity;\n        sim.keepFalling = L.keepFalling;\n        e.renderer.setGrid(layout.gw, layout.gh);\n        e.renderer.setMask(sim.mask, layout.gw * layout.k, layout.gh * layout.k);\n        e.sim = sim;\n        if (reduced) {\n          sim.fillStatic(true);\n          e.paint();\n        } else {\n          if (L.snowing) sim.prewarm();\n          e.paint();\n          e.wake();\n        }\n      })\n      .catch(() => {});\n    return () => {\n      cancelled = true;\n      cancelAnimationFrame(e.raf);\n      e.raf = 0;\n      e.sim = null;\n    };\n  }, [layout, geo, reduced]);\n\n  // Snow again, or more or less of it, when the props change or it comes back into view.\n  React.useEffect(() => {\n    engine.current?.wake();\n  }, [active, snowing, intensity, keepFalling]);\n\n  const knock = () => {\n    const e = engine.current;\n    if (!shake || reduced || !e?.sim || !layout) return;\n    e.sim.shake();\n    jolt.current?.push(-layout.s * 0.55);\n    e.wake();\n  };\n\n  return (\n    <span\n      ref={host}\n      className={`relative inline-block align-top ${shake && !reduced ? \"cursor-pointer\" : \"\"} ${className}`}\n      onPointerDown={(event) => {\n        onPointerDown?.(event);\n        if (event.button === 0 && !event.defaultPrevented) knock();\n      }}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        if ((event.key === \"Enter\" || event.key === \" \") && !event.repeat && !event.defaultPrevented) knock();\n      }}\n      {...props}\n    >\n      {/* A flex box, so an inline <svg> child sits without the line box's gap under it. */}\n      <span ref={layer} className=\"flex\">\n        {children}\n      </span>\n      <canvas\n        ref={canvas}\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute\"\n        style={layout && geo ? { left: geo.x - layout.box.x, top: geo.y - layout.box.y, width: layout.cw, height: layout.ch } : { display: \"none\" }}\n      />\n    </span>\n  );\n}\n"},{"path":"registry/snowfall-sim.ts","type":"registry:component","content":"// Hairline UI · snowfall · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * SNOWFALL engine: where snow can rest on a shape, and the snow\n *\n *   reading   the wrapped logo is drawn once with every shape in\n *             a flat colour of its own, so each pixel says which\n *             shape is on top; a shape that sits inside another\n *             stands one level in front of it (tiles on a plate)\n *   resting   snow caps the top edge of every level and packs\n *             into narrow gaps between raised shapes, filling\n *             them from the bottom up like a channel\n *   falling   flakes at three depths: far ones pass behind the\n *             logo, near ones blur past in front, the middle\n *             ones land; a full cap sheds from its ends\n *   shaking   the settled snow breaks into clumps that pop up\n *             with the logo and fall away\n *\n * Everything here is in CSS pixels of the canvas, which covers\n * the element plus room above and around it for the snowfall.\n * ───────────────────────────────────────────────────────── */\n\nexport type Box = { x: number; y: number; w: number; h: number };\n\nexport type SnowLayout = {\n  /** Size scale: the geometric mean of the element's sides, in CSS px. */\n  s: number;\n  /** Grid cell size in CSS px. */\n  cell: number;\n  /** Mask pixels per grid cell, along each side. */\n  k: number;\n  gw: number;\n  gh: number;\n  /** Canvas size in CSS px: exactly gw * cell by gh * cell. */\n  cw: number;\n  ch: number;\n  /** Where the element sits in the canvas. */\n  box: Box;\n};\n\nconst clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);\n\n/* Tuning. Lengths are fractions of s, the element's size. */\nconst CELLS = 110; // grid cells across s\nconst CAP_BASE = 0.055; // cap height on the base level (a plate, a wordmark, a button)\nconst CAP_RAISED = 0.032; // cap height on shapes that stand on another\nconst GROOVE = 0.075; // gaps between raised shapes up to this wide catch snow\nconst SPEED = 0.42; // fall speed of the middle flakes, s per second\nconst GRAVITY = 2.3; // for clumps, s per second squared\nconst FLOW = 5; // cells of snow per second that a deposit settles in at\nconst MASS_GROOVE = 30; // cells of snow one grain packs into a gap\nconst MASS_CAP = 3.6; // cells of snow one grain adds to a cap\nconst FULL = 0.93; // share of the room that counts as dressed\nconst MAX_FLAKES = 900;\nconst MAX_CLUMPS = 1600;\n\nconst BACK = 0;\nconst MID = 1;\nconst FRONT = 2;\n\n/** Where the canvas sits and how fine the grid is, for an element of this size. */\nexport function snowLayout(w: number, h: number, dpr: number): SnowLayout {\n  const s = Math.sqrt(Math.max(1, w) * Math.max(1, h));\n  const cell = clamp(s / CELLS, 0.5, 8);\n  const side = clamp(s * 0.35, 24, 180);\n  const top = clamp(s * 0.55, 36, 260);\n  const bottom = clamp(s * 0.3, 20, 140);\n  const gw = Math.ceil((w + side * 2) / cell);\n  const gh = Math.ceil((h + top + bottom) / cell);\n  let k = clamp(Math.ceil((cell * dpr) / 1.7), 1, 5);\n  while (k > 1 && gw * gh * k * k > 1_400_000) k--;\n  return { s, cell, k, gw, gh, cw: gw * cell, ch: gh * cell, box: { x: side, y: top, w, h } };\n}\n\n/* ── Reading the shape ─────────────────────────────────── */\n\nexport type ShapeMap = {\n  /** One entry per mask pixel: -1 where nothing is drawn, else how many levels in front of the back the shape stands. */\n  level: Int8Array;\n  maxLevel: number;\n};\n\nconst SHAPES = \"path,rect,circle,ellipse,polygon,polyline,line,text,use\";\nconst NONRENDER = \"defs,symbol,clipPath,mask,pattern,marker\";\n\nconst idColor = (id: number) => `rgb(${((id & 31) << 3) | 4},${((id >> 5) << 3) | 4},128)`;\n\nfunction colorAlpha(color: string) {\n  const m = /rgba?\\(([^)]+)\\)/.exec(color);\n  if (!m) return color === \"transparent\" ? 0 : 1;\n  const parts = m[1].split(/[\\s,/]+/).filter(Boolean);\n  if (parts.length < 4) return 1;\n  const a = parseFloat(parts[3]);\n  return parts[3].endsWith(\"%\") ? a / 100 : a;\n}\n\nfunction paintAlpha(paint: string, doc: Document) {\n  if (!paint || paint === \"none\") return 0;\n  const url = /url\\([\"']?#([^\"')]+)[\"']?\\)/.exec(paint);\n  if (!url) return colorAlpha(paint);\n  const grad = doc.getElementById(url[1]);\n  const stops = grad ? grad.querySelectorAll(\"stop\") : null;\n  if (!stops || !stops.length) return 1;\n  let max = 0;\n  stops.forEach((stop) => {\n    const cs = getComputedStyle(stop);\n    max = Math.max(max, (parseFloat(cs.stopOpacity) || 0) * colorAlpha(cs.stopColor));\n  });\n  return max;\n}\n\nfunction opacityChain(el: Element, root: Element) {\n  let o = 1;\n  for (let node: Element | null = el; node; node = node.parentElement) {\n    o *= parseFloat(getComputedStyle(node).opacity) || 0;\n    if (node === root) break;\n  }\n  return o;\n}\n\n/** Draw the SVG with each visible shape in its own flat colour. Returns how many shapes it drew. */\nasync function drawSvgIds(ctx: CanvasRenderingContext2D, svg: SVGSVGElement, x: number, y: number, w: number, h: number, box: Box) {\n  const clone = svg.cloneNode(true) as SVGSVGElement;\n  const live = Array.from(svg.querySelectorAll(SHAPES));\n  const copies = Array.from(clone.querySelectorAll(SHAPES)) as SVGElement[];\n  let id = 0;\n  live.forEach((el, i) => {\n    const copy = copies[i];\n    if (!copy || el.closest(NONRENDER)) return;\n    const hide = () => copy.setAttribute(\"display\", \"none\");\n    if (el.closest('[data-snow=\"ignore\"]')) return hide();\n    const cs = getComputedStyle(el);\n    if (cs.display === \"none\" || cs.visibility === \"hidden\") return hide();\n    const o = opacityChain(el, svg);\n    const fill = o * (parseFloat(cs.fillOpacity) || 0) * paintAlpha(cs.fill, el.ownerDocument) >= 0.5;\n    const stroke = (parseFloat(cs.strokeWidth) || 0) > 0 && o * (parseFloat(cs.strokeOpacity) || 0) * paintAlpha(cs.stroke, el.ownerDocument) >= 0.5;\n    if (!fill && !stroke) return hide();\n    if (id >= 1023) return hide();\n    const color = idColor(++id);\n    copy.style.setProperty(\"fill\", fill ? color : \"none\", \"important\");\n    copy.style.setProperty(\"stroke\", stroke ? color : \"none\", \"important\");\n  });\n  if (!id) return 0;\n  clone.querySelectorAll(\"*\").forEach((node) => {\n    const style = (node as SVGElement).style;\n    if (!style) return;\n    style.setProperty(\"opacity\", \"1\", \"important\");\n    style.setProperty(\"fill-opacity\", \"1\", \"important\");\n    style.setProperty(\"stroke-opacity\", \"1\", \"important\");\n    style.setProperty(\"filter\", \"none\", \"important\");\n  });\n  if (!clone.getAttribute(\"viewBox\")) clone.setAttribute(\"viewBox\", `0 0 ${box.w} ${box.h}`);\n  clone.removeAttribute(\"class\");\n  clone.removeAttribute(\"style\");\n  clone.setAttribute(\"xmlns\", \"http://www.w3.org/2000/svg\");\n  clone.setAttribute(\"width\", String(w));\n  clone.setAttribute(\"height\", String(h));\n  clone.style.setProperty(\"shape-rendering\", \"crispEdges\");\n  const img = new Image();\n  img.src = \"data:image/svg+xml;charset=utf-8,\" + encodeURIComponent(new XMLSerializer().serializeToString(clone));\n  await img.decode();\n  ctx.drawImage(img, x, y, w, h);\n  return id;\n}\n\nfunction drawBox(ctx: CanvasRenderingContext2D, el: Element, x: number, y: number, w: number, h: number, scale: number) {\n  const cs = getComputedStyle(el);\n  const r = (v: string) => {\n    const n = parseFloat(v) || 0;\n    return Math.min(v.trim().endsWith(\"%\") ? (n / 100) * Math.min(w, h) : n * scale, w / 2, h / 2);\n  };\n  ctx.fillStyle = idColor(1);\n  ctx.beginPath();\n  ctx.roundRect(x, y, w, h, [r(cs.borderTopLeftRadius), r(cs.borderTopRightRadius), r(cs.borderBottomRightRadius), r(cs.borderBottomLeftRadius)]);\n  ctx.fill();\n}\n\n/**\n * Read the element into a level map at mask resolution. An inline SVG is read shape by shape; an image by its alpha;\n * anything else by its border box and radius.\n */\nexport async function readShape(target: Element, layout: SnowLayout): Promise<ShapeMap> {\n  const { k, gw, gh, cell, box } = layout;\n  const w = gw * k;\n  const h = gh * k;\n  const px = k / cell;\n  const canvas = document.createElement(\"canvas\");\n  canvas.width = w;\n  canvas.height = h;\n  const ctx = canvas.getContext(\"2d\", { willReadFrequently: true });\n  if (!ctx) throw new Error(\"no 2d context\");\n  ctx.imageSmoothingEnabled = false;\n  const bx = box.x * px;\n  const by = box.y * px;\n  const bw = box.w * px;\n  const bh = box.h * px;\n  let count = 0;\n  let alphaOnly = false;\n  let data: Uint8ClampedArray | null = null;\n  try {\n    if (target instanceof SVGSVGElement) count = await drawSvgIds(ctx, target, bx, by, bw, bh, box);\n    else if (target instanceof HTMLImageElement && target.complete && target.naturalWidth) {\n      ctx.drawImage(target, bx, by, bw, bh);\n      count = 1;\n      alphaOnly = true;\n    }\n    if (count) data = ctx.getImageData(0, 0, w, h).data;\n  } catch {\n    count = 0;\n  }\n  if (!count || !data) {\n    ctx.clearRect(0, 0, w, h);\n    drawBox(ctx, target, bx, by, bw, bh, px);\n    count = 1;\n    alphaOnly = true;\n    data = ctx.getImageData(0, 0, w, h).data;\n  }\n\n  const n = count;\n  const ids = new Uint16Array(w * h);\n  for (let i = 0, p = 0; i < ids.length; i++, p += 4) {\n    if (data[p + 3] < 128) continue;\n    const id = alphaOnly ? 1 : ((data[p] >> 3) & 31) | (((data[p + 1] >> 3) & 31) << 5);\n    ids[i] = id >= 1 && id <= n ? id : 0;\n  }\n\n  // A shape stands on whatever earlier shape most of its outline touches; one that mostly touches nothing is at the back.\n  const levels = new Int8Array(n + 1);\n  if (n > 1 && n <= 300) {\n    const stride = n + 1;\n    const votes = new Int32Array(stride * stride);\n    const vote = (a: number, b: number) => {\n      if (a && (b === 0 || b < a)) votes[a * stride + b]++;\n    };\n    for (let y = 0; y < h; y++) {\n      for (let x = 0; x < w; x++) {\n        const i = y * w + x;\n        const a = ids[i];\n        if (x + 1 < w && ids[i + 1] !== a) {\n          vote(a, ids[i + 1]);\n          vote(ids[i + 1], a);\n        }\n        if (y + 1 < h && ids[i + w] !== a) {\n          vote(a, ids[i + w]);\n          vote(ids[i + w], a);\n        }\n      }\n    }\n    for (let e = 1; e <= n; e++) {\n      const none = votes[e * stride];\n      let best = 0;\n      let bestCount = 0;\n      for (let f = 1; f < e; f++) {\n        const c = votes[e * stride + f];\n        if (c > bestCount) {\n          bestCount = c;\n          best = f;\n        }\n      }\n      levels[e] = best && bestCount > none ? Math.min(3, levels[best] + 1) : 0;\n    }\n  }\n  const level = new Int8Array(w * h);\n  let maxLevel = 0;\n  for (let i = 0; i < level.length; i++) {\n    const id = ids[i];\n    const l = id ? levels[id] : -1;\n    level[i] = l;\n    if (l > maxLevel) maxLevel = l;\n  }\n  return { level, maxLevel };\n}\n\n/* ── Blur for the mask's shading ──────────────────────── */\n\nfunction boxBlur(src: Float32Array, w: number, h: number, r: number) {\n  const tmp = new Float32Array(src.length);\n  const out = new Float32Array(src.length);\n  const span = r * 2 + 1;\n  for (let y = 0; y < h; y++) {\n    const row = y * w;\n    let sum = 0;\n    for (let x = -r; x <= r; x++) sum += src[row + clamp(x, 0, w - 1)];\n    for (let x = 0; x < w; x++) {\n      tmp[row + x] = sum / span;\n      sum += src[row + Math.min(w - 1, x + r + 1)] - src[row + Math.max(0, x - r)];\n    }\n  }\n  for (let x = 0; x < w; x++) {\n    let sum = 0;\n    for (let y = -r; y <= r; y++) sum += tmp[clamp(y, 0, h - 1) * w + x];\n    for (let y = 0; y < h; y++) {\n      out[y * w + x] = sum / span;\n      sum += tmp[Math.min(h - 1, y + r + 1) * w + x] - tmp[Math.max(0, y - r) * w + x];\n    }\n  }\n  return out;\n}\n\n/** Grow (keep = 1) or shrink (keep = 0) a mask by a square of radius r, one axis at a time. */\nfunction morph(src: Uint8Array, w: number, h: number, r: number, keep: 0 | 1) {\n  const tmp = new Uint8Array(src.length);\n  const out = new Uint8Array(src.length);\n  for (let y = 0; y < h; y++) {\n    for (let x = 0; x < w; x++) {\n      let v = 1 - keep;\n      for (let i = Math.max(0, x - r); i <= Math.min(w - 1, x + r); i++) {\n        if (src[y * w + i] === keep) {\n          v = keep;\n          break;\n        }\n      }\n      tmp[y * w + x] = v;\n    }\n  }\n  for (let x = 0; x < w; x++) {\n    for (let y = 0; y < h; y++) {\n      let v = 1 - keep;\n      for (let i = Math.max(0, y - r); i <= Math.min(h - 1, y + r); i++) {\n        if (tmp[i * w + x] === keep) {\n          v = keep;\n          break;\n        }\n      }\n      out[y * w + x] = v;\n    }\n  }\n  return out;\n}\n\n/* ── The simulation ───────────────────────────────────── */\n\ntype Run = { x0: number; y0: number; x1: number; y1: number; shed0: number; shed1: number };\n\nexport class SnowSim {\n  readonly layout: SnowLayout;\n  readonly bands: number;\n  /** Mask for the renderer, RGBA at gw * k by gh * k: where snow may show, how shaded it is there, and where the shape is. */\n  readonly mask: Uint8Array;\n  /** Settled snow for the renderer, one byte per cell; the shape's mask clips it. */\n  readonly view: Uint8Array;\n  /** Snow in the air after a shake, one byte per cell; nothing clips it, since it falls in front. */\n  readonly clumpView: Uint8Array;\n  /** Flakes for the renderer: x, y, radius, alpha, softness, behind-the-logo, per flake. */\n  readonly instances: Float32Array;\n  instanceCount = 0;\n  viewDirty = true;\n\n  snowing = true;\n  intensity = 1;\n  keepFalling = false;\n\n  private readonly cells: number;\n  private readonly lev: Int8Array;\n  private readonly groove: Uint8Array;\n  private readonly runOf: Int32Array[];\n  private readonly hmax: Float32Array[];\n  private readonly runs: Run[] = [];\n  private readonly d: Float32Array;\n  private readonly pend: Float32Array;\n  private readonly owner: Int8Array;\n  private readonly inPend: Uint8Array;\n  private pendList: number[] = [];\n  private readonly edgeCells: Int32Array;\n  private readonly edgeNbrs: Int32Array;\n  private readonly capacity: number;\n\n  // flakes\n  private n = 0;\n  private readonly fx = new Float32Array(MAX_FLAKES);\n  private readonly fy = new Float32Array(MAX_FLAKES);\n  private readonly fvx = new Float32Array(MAX_FLAKES);\n  private readonly fvy = new Float32Array(MAX_FLAKES);\n  private readonly fterm = new Float32Array(MAX_FLAKES);\n  private readonly fr = new Float32Array(MAX_FLAKES);\n  private readonly fa = new Float32Array(MAX_FLAKES);\n  private readonly fsoft = new Float32Array(MAX_FLAKES);\n  private readonly fph = new Float32Array(MAX_FLAKES);\n  private readonly ffreq = new Float32Array(MAX_FLAKES);\n  private readonly famp = new Float32Array(MAX_FLAKES);\n  private readonly fmass = new Float32Array(MAX_FLAKES);\n  private readonly fkind = new Int8Array(MAX_FLAKES);\n  private readonly fband = new Int8Array(MAX_FLAKES);\n\n  // clumps\n  private cn = 0;\n  private readonly cx = new Float32Array(MAX_CLUMPS);\n  private readonly cy = new Float32Array(MAX_CLUMPS);\n  private readonly cvx = new Float32Array(MAX_CLUMPS);\n  private readonly cvy = new Float32Array(MAX_CLUMPS);\n  private readonly cr = new Float32Array(MAX_CLUMPS);\n  private readonly cage = new Float32Array(MAX_CLUMPS);\n  private readonly cax = new Float32Array(MAX_CLUMPS);\n  private readonly cay = new Float32Array(MAX_CLUMPS);\n\n  private time = 0;\n  private acc = 0;\n  private ramp = 0;\n  private pause = 0;\n  private full = false;\n  private snowTime = 0;\n  private checkTimer = 0;\n  private armed = false;\n  private clumpsShown = false;\n  private stampId = 0;\n  private readonly stamp: Int32Array;\n  private readonly queue: Int32Array;\n  private readonly u: number;\n  private readonly v0: number;\n  private readonly rate: number;\n\n  constructor(shape: ShapeMap, layout: SnowLayout) {\n    this.layout = layout;\n    const { gw, gh, k, s, cell } = layout;\n    const cells = gw * gh;\n    this.cells = cells;\n    this.bands = shape.maxLevel + 1;\n    this.d = new Float32Array(cells);\n    this.pend = new Float32Array(cells);\n    this.owner = new Int8Array(cells).fill(-1);\n    this.inPend = new Uint8Array(cells);\n    this.view = new Uint8Array(cells);\n    this.clumpView = new Uint8Array(cells);\n    this.stamp = new Int32Array(cells);\n    this.queue = new Int32Array(Math.min(cells, 20000));\n    this.instances = new Float32Array(MAX_FLAKES * 6);\n\n    // Levels per cell, read at the middle of each cell.\n    const mw = gw * k;\n    const lev = new Int8Array(cells);\n    const half = k >> 1;\n    for (let y = 0; y < gh; y++) for (let x = 0; x < gw; x++) lev[y * gw + x] = shape.level[(y * k + half) * mw + x * k + half];\n    this.lev = lev;\n\n    // Gaps between shapes of one level, over the level behind them, catch snow: the cells a closing of those shapes fills\n    // in (grown by half the widest gap, then shrunk back), so the joins where gaps meet count too.\n    const reach = Math.max(1, Math.round((GROOVE * CELLS) / 2));\n    const groove = new Uint8Array(cells);\n    for (let b = 1; b < this.bands; b++) {\n      const wall = new Uint8Array(cells);\n      for (let c = 0; c < cells; c++) wall[c] = lev[c] >= b ? 1 : 0;\n      const closed = morph(morph(wall, gw, gh, reach, 1), gw, gh, reach, 0);\n      for (let c = 0; c < cells; c++) if (!wall[c] && closed[c] && lev[c] === b - 1) groove[c] = b + 1;\n    }\n    this.groove = groove;\n\n    // Top edges of each level, joined into runs that can carry a cap; caps round off towards a run's ends.\n    this.runOf = [];\n    this.hmax = [];\n    for (let b = 0; b < this.bands; b++) {\n      const runOf = new Int32Array(cells).fill(-1);\n      const hmax = new Float32Array(cells);\n      const cap = ((b === 0 ? CAP_BASE : CAP_RAISED) * s) / cell;\n      const isLedge = (c: number) => lev[c] >= b && (c < gw || lev[c - gw] < b);\n      const stack: number[] = [];\n      for (let c0 = 0; c0 < cells; c0++) {\n        if (runOf[c0] >= 0 || !isLedge(c0)) continue;\n        const id = this.runs.length;\n        const members: number[] = [];\n        const run: Run = { x0: Infinity, y0: 0, x1: -Infinity, y1: 0, shed0: 0, shed1: 0 };\n        runOf[c0] = id;\n        stack.push(c0);\n        while (stack.length) {\n          const c = stack.pop() as number;\n          members.push(c);\n          const x = c % gw;\n          const y = (c - x) / gw;\n          if (x < run.x0 || (x === run.x0 && y > run.y0)) {\n            run.x0 = x;\n            run.y0 = y;\n          }\n          if (x > run.x1 || (x === run.x1 && y > run.y1)) {\n            run.x1 = x;\n            run.y1 = y;\n          }\n          for (let dy = -1; dy <= 1; dy++) {\n            for (let dx = -1; dx <= 1; dx++) {\n              const nx = x + dx;\n              const ny = y + dy;\n              if ((!dx && !dy) || nx < 0 || ny < 0 || nx >= gw || ny >= gh) continue;\n              const nc = ny * gw + nx;\n              if (runOf[nc] < 0 && isLedge(nc)) {\n                runOf[nc] = id;\n                stack.push(nc);\n              }\n            }\n          }\n        }\n        for (const c of members) {\n          const x = c % gw;\n          const dx = Math.min(x - run.x0, run.x1 - x);\n          hmax[c] = cap * Math.sqrt(Math.min(1, (dx + 0.6) / (cap * 1.15)));\n        }\n        this.runs.push(run);\n      }\n      this.runOf.push(runOf);\n      this.hmax.push(hmax);\n    }\n\n    // The frontmost shapes hide the snow; their cells next to snow borrow its value so it meets them cleanly.\n    const front = this.bands - 1;\n    const edges: number[] = [];\n    const nbrs: number[] = [];\n    for (let y = 0; y < gh; y++) {\n      for (let x = 0; x < gw; x++) {\n        const c = y * gw + x;\n        if (lev[c] !== front) continue;\n        const list = [x > 0 ? c - 1 : -1, x < gw - 1 ? c + 1 : -1, y > 0 ? c - gw : -1, y < gh - 1 ? c + gw : -1].map((nc) => (nc >= 0 && lev[nc] < front ? nc : -1));\n        if (list.every((nc) => nc < 0)) continue;\n        edges.push(c);\n        nbrs.push(...list);\n      }\n    }\n    this.edgeCells = Int32Array.from(edges);\n    this.edgeNbrs = Int32Array.from(nbrs);\n\n    this.mask = this.buildMask(shape);\n    this.capacity = Math.max(1, this.fillStatic(false));\n\n    this.u = clamp(s / CELLS, 1.05, 5);\n    this.v0 = clamp(SPEED * s, 46, 190);\n    // One flake in the air for about every 420 square pixels of sky, so a small logo gets a light fall, not a blizzard.\n    const count = clamp((layout.cw * layout.ch) / 420, 10, 320);\n    this.rate = count / (layout.ch / this.v0);\n  }\n\n  private buildMask(shape: ShapeMap) {\n    const { gw, gh, k } = this.layout;\n    const w = gw * k;\n    const h = gh * k;\n    const L = shape.level;\n    const front = this.bands - 1;\n    const out = new Uint8Array(w * h * 4);\n    const shade = new Float32Array(w * h);\n    const radius = Math.max(1, Math.round(k * 1.3));\n    for (let m = -1; m < front; m++) {\n      let any = false;\n      const src = new Float32Array(w * h);\n      for (let i = 0; i < src.length; i++) {\n        if (L[i] > m) src[i] = 1;\n        if (L[i] === m) any = true;\n      }\n      if (!any) continue;\n      const blurred = boxBlur(boxBlur(src, w, h, radius), w, h, radius);\n      for (let i = 0; i < src.length; i++) if (L[i] === m) shade[i] = blurred[i];\n    }\n    for (let i = 0, p = 0; i < L.length; i++, p += 4) {\n      const l = L[i];\n      out[p] = l < front ? 255 : 0;\n      out[p + 1] = l < front ? Math.round(clamp(shade[i] * 1.6, 0, 1) * 255) : 0;\n      out[p + 2] = l >= 0 ? 255 : 0;\n      out[p + 3] = 255;\n    }\n    return out;\n  }\n\n  /** Dress the shape fully at once (reduced motion), or just count how many cells that takes. */\n  fillStatic(apply: boolean) {\n    const { gw } = this.layout;\n    const t = new Float32Array(this.cells);\n    const own = new Int8Array(this.cells).fill(-1);\n    for (let c = 0; c < this.cells; c++) {\n      const g = this.groove[c];\n      if (g) {\n        t[c] = 1;\n        own[c] = g - 1;\n      }\n    }\n    for (let b = 0; b < this.bands; b++) {\n      const runOf = this.runOf[b];\n      const hmax = this.hmax[b];\n      for (let c = 0; c < this.cells; c++) {\n        if (runOf[c] < 0) continue;\n        const h = hmax[c];\n        for (let r = 1; r <= Math.ceil(h); r++) {\n          const cc = c - r * gw;\n          if (cc < 0 || this.lev[cc] >= b) break;\n          t[cc] = Math.max(t[cc], clamp(h - r + 1, 0, 1));\n          if (own[cc] < 0) own[cc] = b;\n        }\n      }\n    }\n    let count = 0;\n    for (let c = 0; c < this.cells; c++) if (t[c] >= 0.5) count++;\n    if (apply) {\n      this.d.set(t);\n      this.owner.set(own);\n      this.n = 0;\n      this.cn = 0;\n      this.full = true;\n      this.viewDirty = true;\n      this.buildView();\n    }\n    return count;\n  }\n\n  /* ── Cells ── */\n\n  private filled(c: number, band: number) {\n    return this.owner[c] === band && this.d[c] + this.pend[c] >= 0.5;\n  }\n\n  private blocked(c: number, band: number) {\n    return this.lev[c] >= band || this.filled(c, band);\n  }\n\n  private supported(c: number, band: number, inGroove: boolean) {\n    const below = c + this.layout.gw;\n    if (below >= this.cells) return true;\n    if (this.lev[below] >= band || this.filled(below, band)) return true;\n    return inGroove && this.groove[below] !== band + 1;\n  }\n\n  private addPend(c: number, amount: number, band: number) {\n    this.pend[c] += amount;\n    this.owner[c] = band;\n    if (!this.inPend[c]) {\n      this.inPend[c] = 1;\n      this.pendList.push(c);\n    }\n  }\n\n  /** Height of the snow column standing on a ledge if this cell were filled, or -1 when the cell is not over one. */\n  private capHeight(c: number, band: number) {\n    const { gw } = this.layout;\n    const limit = Math.ceil(((CAP_BASE * this.layout.s) / this.layout.cell) * 1.2) + 3;\n    let rows = 1;\n    let cc = c + gw;\n    while (cc < this.cells && rows <= limit) {\n      if (this.lev[cc] >= band) return this.runOf[band][cc] >= 0 && rows <= this.hmax[band][cc] + 0.5 ? rows : -1;\n      if (!this.filled(cc, band)) return -1;\n      rows++;\n      cc += gw;\n    }\n    return -1;\n  }\n\n  /** Spread a grain's snow along one row from where it landed; returns what did not fit. */\n  private spreadRow(x0: number, row: number, mass: number, band: number, inGroove: boolean, reach: number) {\n    const { gw } = this.layout;\n    const base = row * gw;\n    const ok = (x: number) => {\n      if (x < 0 || x >= gw) return false;\n      const c = base + x;\n      if (this.lev[c] >= band) return false;\n      if (inGroove ? this.groove[c] !== band + 1 : this.capHeight(c, band) < 0) return false;\n      if (this.owner[c] >= 0 && this.owner[c] !== band && this.d[c] + this.pend[c] > 0.05) return false;\n      return this.supported(c, band, inGroove);\n    };\n    if (!ok(x0)) return mass;\n    let left = x0;\n    let right = x0;\n    const take = (x: number) => {\n      const c = base + x;\n      const room = 1 - this.d[c] - this.pend[c];\n      if (room <= 0.001) return;\n      const t = Math.min(room, mass);\n      this.addPend(c, t, band);\n      mass -= t;\n    };\n    take(x0);\n    for (let i = 1; i <= reach && mass > 0.001; i++) {\n      const goLeft = left === x0 - i + 1 && ok(x0 - i);\n      const goRight = right === x0 + i - 1 && ok(x0 + i);\n      if (!goLeft && !goRight) break;\n      if (goLeft) {\n        left = x0 - i;\n        take(left);\n      }\n      if (goRight && mass > 0.001) {\n        right = x0 + i;\n        take(right);\n      }\n    }\n    return mass;\n  }\n\n  private deposit(gx: number, gy: number, band: number, mass: number) {\n    const { gw } = this.layout;\n    this.armed = true;\n    if (this.groove[gy * gw + gx] === band + 1) {\n      this.pour(gx, gy, band, mass * MASS_GROOVE);\n      return;\n    }\n    let left = mass * MASS_CAP;\n    for (let row = gy; row >= 0 && row > gy - 4 && left > 0.001; row--) left = this.spreadRow(gx, row, left, band, false, 1);\n  }\n\n  /** Snow in a gap settles like a liquid: into the lowest open cells it can reach, so the level rises evenly. */\n  private pour(gx: number, gy: number, band: number, mass: number) {\n    const { gw, gh } = this.layout;\n    const tag = band + 1;\n    const span = Math.round(GROOVE * CELLS) * 4;\n    const stamp = ++this.stampId;\n    const queue = this.queue;\n    const room = (c: number) => 1 - this.d[c] - this.pend[c];\n    let head = 0;\n    let tail = 0;\n    const start = gy * gw + gx;\n    queue[tail++] = start;\n    this.stamp[start] = stamp;\n    while (head < tail && tail < queue.length - 4) {\n      const c = queue[head++];\n      const x = c % gw;\n      const y = (c - x) / gw;\n      const next = [x > 0 ? c - 1 : -1, x < gw - 1 ? c + 1 : -1, y < gh - 1 ? c + gw : -1, y > gy ? c - gw : -1];\n      for (const n of next) {\n        if (n < 0 || this.stamp[n] === stamp) continue;\n        const nx = n % gw;\n        if (Math.abs(nx - gx) > span || this.groove[n] !== tag || this.lev[n] >= band || room(n) <= 0.02) continue;\n        this.stamp[n] = stamp;\n        queue[tail++] = n;\n      }\n    }\n    // Lowest first, counting cells further from where the grain fell as a little higher, so the snow mounds slightly\n    // where it lands instead of lying dead flat. The mound stays under one row, so a row always fills before the one\n    // above it and no pocket is left under an overhang (the bar of an H).\n    const found = Array.from(queue.subarray(0, tail));\n    const level = (c: number) => ((c / gw) | 0) - Math.min(0.85, Math.abs((c % gw) - gx) * 0.3);\n    found.sort((a, b) => level(b) - level(a));\n    for (const c of found) {\n      const r = room(c);\n      if (r <= 0.001) continue;\n      const t = Math.min(r, mass);\n      this.addPend(c, t, band);\n      mass -= t;\n      if (mass <= 0.001) break;\n    }\n  }\n\n  /* ── Flakes ── */\n\n  private addFlake(kind: number, x: number, y: number, band: number) {\n    if (this.n >= MAX_FLAKES) return -1;\n    const i = this.n++;\n    const { u, v0 } = this;\n    const s = this.layout.s;\n    this.fkind[i] = kind;\n    this.fband[i] = band;\n    this.fx[i] = x;\n    this.fy[i] = y;\n    this.fvx[i] = 0;\n    this.fph[i] = Math.random() * Math.PI * 2;\n    this.ffreq[i] = Math.PI * 2 * (0.22 + Math.random() * 0.32);\n    this.fmass[i] = 1;\n    if (kind === BACK) {\n      this.fr[i] = Math.max(0.7, u * (0.5 + Math.random() * 0.32));\n      this.fterm[i] = v0 * (0.52 + Math.random() * 0.14);\n      this.fa[i] = 0.42 + Math.random() * 0.2;\n      this.fsoft[i] = 0.25;\n      this.famp[i] = s * 0.02 * (0.5 + Math.random());\n    } else if (kind === FRONT) {\n      this.fr[i] = u * (2.5 + Math.random() * 1.9);\n      this.fterm[i] = v0 * (1.45 + Math.random() * 0.35);\n      this.fa[i] = 0.32 + Math.random() * 0.2;\n      this.fsoft[i] = 1;\n      this.famp[i] = s * 0.05 * (0.5 + Math.random());\n    } else {\n      this.fr[i] = Math.max(0.9, u * (0.85 + Math.random() * 0.65));\n      this.fterm[i] = v0 * (0.86 + Math.random() * 0.3);\n      this.fa[i] = 0.92;\n      this.fsoft[i] = 0.12;\n      this.famp[i] = s * 0.035 * (0.4 + Math.random());\n    }\n    this.fvy[i] = this.fterm[i];\n    return i;\n  }\n\n  private spawn(y: number) {\n    const roll = Math.random();\n    const x = Math.random() * this.layout.cw;\n    if (roll < 0.22) return this.addFlake(BACK, x, y, -1);\n    if (roll < 0.3) return this.addFlake(FRONT, x, y, -1);\n    // Raised shapes catch more: weight each band by how far forward it stands.\n    let total = 0;\n    for (let b = 0; b < this.bands; b++) total += b === 0 ? 1.2 : 2.4;\n    let pick = Math.random() * total;\n    let band = 0;\n    for (let b = 0; b < this.bands; b++) {\n      pick -= b === 0 ? 1.2 : 2.4;\n      if (pick <= 0) {\n        band = b;\n        break;\n      }\n    }\n    return this.addFlake(MID, x, y, band);\n  }\n\n  /** Fill the sky above the element so the first flakes land almost at once. */\n  prewarm() {\n    const top = this.layout.box.y * 0.95;\n    const count = Math.round(this.rate * (top / this.v0) * this.intensity);\n    for (let i = 0; i < count; i++) this.spawn(Math.random() * top);\n    this.ramp = 1;\n  }\n\n  private removeFlake(i: number) {\n    const last = --this.n;\n    if (i === last) return;\n    this.fx[i] = this.fx[last];\n    this.fy[i] = this.fy[last];\n    this.fvx[i] = this.fvx[last];\n    this.fvy[i] = this.fvy[last];\n    this.fterm[i] = this.fterm[last];\n    this.fr[i] = this.fr[last];\n    this.fa[i] = this.fa[last];\n    this.fsoft[i] = this.fsoft[last];\n    this.fph[i] = this.fph[last];\n    this.ffreq[i] = this.ffreq[last];\n    this.famp[i] = this.famp[last];\n    this.fmass[i] = this.fmass[last];\n    this.fkind[i] = this.fkind[last];\n    this.fband[i] = this.fband[last];\n  }\n\n  private shed(runId: number, gx: number, band: number, mass: number) {\n    const run = this.runs[runId];\n    let side = gx - run.x0 < run.x1 - gx ? 0 : 1;\n    if (Math.random() < 0.25) side = 1 - side;\n    if (side === 0) run.shed0 += mass;\n    else run.shed1 += mass;\n    const stock = side === 0 ? run.shed0 : run.shed1;\n    if (stock < 2) return;\n    if (side === 0) run.shed0 = 0;\n    else run.shed1 = 0;\n    const { gw, cell } = this.layout;\n    const ex = side === 0 ? run.x0 - 1 : run.x1 + 1;\n    const ey = side === 0 ? run.y0 : run.y1;\n    const top = ey - Math.ceil(this.hmax[band][ey * gw + (side === 0 ? run.x0 : run.x1)]) - 1;\n    if (ex < 0 || ex >= gw || top < 0 || this.lev[top * gw + ex] >= band) return;\n    const i = this.addFlake(MID, (ex + 0.5) * cell, (top + 0.5) * cell, band);\n    if (i < 0) return;\n    this.fmass[i] = stock;\n    this.fr[i] *= 1.35;\n    this.fvy[i] = this.fterm[i] * 0.3;\n    this.fvx[i] = (side === 0 ? -1 : 1) * this.v0 * 0.18;\n  }\n\n  /** A grain that rolled off an edge falls on from there. */\n  private drop(gx: number, gy: number, band: number, mass: number) {\n    const { cell } = this.layout;\n    const i = this.addFlake(MID, (gx + 0.5) * cell, (gy + 0.5) * cell, band);\n    if (i < 0) return;\n    this.fmass[i] = mass;\n    this.fvy[i] = this.fterm[i] * 0.25;\n    this.famp[i] *= 0.3;\n  }\n\n  /** Where a grain comes to rest on a cap or in a gap. */\n  private land(i: number, gx: number, gy: number) {\n    const { gw } = this.layout;\n    const band = this.fband[i];\n    let y = gy;\n    while (y >= 0 && this.blocked(y * gw + gx, band)) y--;\n    if (y < 0) return;\n    if (this.groove[y * gw + gx] === band + 1) {\n      this.deposit(gx, y, band, this.fmass[i]);\n      return;\n    }\n    // On a cap the grain rolls down whichever side is lower, and off an edge it drops on as a flake.\n    for (let step = 0; step < 12 && Math.random() > 0.12; step++) {\n      const first = Math.random() < 0.5 ? -1 : 1;\n      let moved = false;\n      for (const dir of [first, -first]) {\n        const nx = gx + dir;\n        const ny = y + 1;\n        if (nx < 0 || nx >= gw || ny >= this.layout.gh) continue;\n        const side = y * gw + nx;\n        const down = ny * gw + nx;\n        if (this.blocked(side, band) || this.blocked(down, band)) continue;\n        if (this.groove[down] === band + 1 || !this.supported(down, band, false)) {\n          this.drop(nx, ny, band, this.fmass[i]);\n          return;\n        }\n        gx = nx;\n        y = ny;\n        moved = true;\n        break;\n      }\n      if (!moved) break;\n    }\n    const c = y * gw + gx;\n    // Find the ledge under the snow.\n    let cc = c + gw;\n    let rows = 1;\n    const limit = Math.ceil(((CAP_BASE * this.layout.s) / this.layout.cell) * 1.2) + 3;\n    while (cc < this.cells && rows <= limit && this.lev[cc] < band) {\n      if (!this.filled(cc, band)) return;\n      cc += gw;\n      rows++;\n    }\n    if (cc >= this.cells || this.lev[cc] < band) return;\n    const runId = this.runOf[band][cc];\n    if (runId < 0) return;\n    if (rows <= this.hmax[band][cc] + 0.5) this.deposit(gx, y, band, this.fmass[i]);\n    else this.shed(runId, gx, band, this.fmass[i]);\n  }\n\n  private stepFlakes(dt: number) {\n    const { gw, gh, cell, cw, ch } = this.layout;\n    const wind = this.v0 * (0.06 * Math.sin(this.time * 0.21) + 0.035 * Math.sin(this.time * 0.67 + 1.3));\n    const relax = Math.min(1, 2.6 * dt);\n    for (let i = this.n - 1; i >= 0; i--) {\n      const kind = this.fkind[i];\n      const ph = this.fph[i] + this.ffreq[i] * dt;\n      this.fph[i] = ph;\n      this.fvy[i] += (this.fterm[i] - this.fvy[i]) * relax;\n      this.fvx[i] *= 1 - relax;\n      const depth = kind === BACK ? 0.55 : kind === FRONT ? 1.5 : 1;\n      const vx = wind * depth + this.famp[i] * this.ffreq[i] * Math.cos(ph) + this.fvx[i];\n      const x = this.fx[i];\n      const y = this.fy[i];\n      let nx = x + vx * dt;\n      const ny = y + this.fvy[i] * dt;\n      if (kind === MID) {\n        const band = this.fband[i];\n        const cgx = Math.floor(x / cell);\n        const cgy = Math.floor(y / cell);\n        const ngx = Math.floor(nx / cell);\n        const ngy = Math.floor(ny / cell);\n        if (cgy >= 0 && cgy < gh && ngx >= 0 && ngx < gw && ngx !== cgx && this.blocked(cgy * gw + ngx, band)) nx = x;\n        const gx = Math.floor(nx / cell);\n        if (ngy >= 0 && ngy < gh && gx >= 0 && gx < gw) {\n          const c = ngy * gw + gx;\n          if (this.blocked(c, band)) {\n            this.land(i, gx, Math.max(0, cgy));\n            this.removeFlake(i);\n            continue;\n          }\n          if (this.groove[c] === band + 1 && this.supported(c, band, true)) {\n            this.land(i, gx, ngy);\n            this.removeFlake(i);\n            continue;\n          }\n        }\n      }\n      const r = this.fr[i];\n      if (ny - r > ch || nx < -r * 4 || nx > cw + r * 4) {\n        this.removeFlake(i);\n        continue;\n      }\n      this.fx[i] = nx;\n      this.fy[i] = ny;\n    }\n  }\n\n  /* ── Clumps ── */\n\n  /** Knock the snow off: it breaks into clumps that pop up with the element and fall away. */\n  shake(power = 1) {\n    const { gw, gh, cell, s, box } = this.layout;\n    const mid = box.x + box.w / 2;\n    // Clumps of about three cells across, so the snow breaks into pieces rather than dust.\n    for (let y = 0; y < gh - 2; y += 3) {\n      for (let x = 0; x < gw - 2; x += 3) {\n        let m = 0;\n        for (let dy = 0; dy < 3; dy++) for (let dx = 0; dx < 3; dx++) m += this.d[(y + dy) * gw + x + dx] + this.pend[(y + dy) * gw + x + dx];\n        if (m < 1.1 || this.cn >= MAX_CLUMPS) continue;\n        const j = this.cn++;\n        const px = (x + 1.5) * cell;\n        this.cx[j] = px;\n        this.cy[j] = (y + 1.5) * cell;\n        this.cr[j] = cell * Math.sqrt(m) * 0.82;\n        this.cage[j] = 0;\n        // The snow lifts as one piece with the element, then each clump drifts its own way as it falls.\n        this.cvx[j] = ((Math.random() - 0.5) * 0.08 + ((px - mid) / s) * 0.22) * s * power;\n        this.cvy[j] = -s * (0.44 + Math.random() * 0.05) * power;\n        this.cax[j] = (Math.random() - 0.5) * 0.9 * s;\n        this.cay[j] = (Math.random() - 0.3) * 0.9 * s;\n      }\n    }\n    this.d.fill(0);\n    this.pend.fill(0);\n    this.owner.fill(-1);\n    this.inPend.fill(0);\n    this.pendList = [];\n    for (const run of this.runs) run.shed0 = run.shed1 = 0;\n    this.full = false;\n    this.snowTime = 0;\n    this.pause = 0.7;\n    this.armed = true;\n    this.viewDirty = true;\n  }\n\n  private stepClumps(dt: number) {\n    if (!this.cn) {\n      if (this.clumpsShown) {\n        this.clumpsShown = false;\n        this.viewDirty = true;\n      }\n      return;\n    }\n    this.clumpsShown = true;\n    const g = GRAVITY * this.layout.s;\n    const { ch } = this.layout;\n    for (let j = this.cn - 1; j >= 0; j--) {\n      const age = (this.cage[j] += dt);\n      if (age < 0) continue;\n      this.cvy[j] += g * dt;\n      if (age > 0.18) {\n        this.cvx[j] += this.cax[j] * dt;\n        this.cvy[j] += this.cay[j] * dt;\n      }\n      this.cx[j] += this.cvx[j] * dt;\n      this.cy[j] += this.cvy[j] * dt;\n      // Powder breaks off as it falls.\n      if (age > 0.08 && this.cr[j] > this.layout.cell * 1.6 && Math.random() < dt * 0.9) {\n        const i = this.addFlake(FRONT, this.cx[j], this.cy[j], -1);\n        if (i >= 0) {\n          this.fr[i] = this.u * (0.7 + Math.random() * 0.8);\n          this.fa[i] = 0.75;\n          this.fsoft[i] = 0.5;\n          this.fvy[i] = this.cvy[j] * 0.5;\n          this.fvx[i] = this.cvx[j] * 0.6 + (Math.random() - 0.5) * this.v0 * 0.6;\n          this.fterm[i] = this.v0 * (0.7 + Math.random() * 0.4);\n        }\n      }\n      const r = this.cr[j] * Math.max(0.55, 1 - 0.35 * age);\n      if (this.cy[j] - r > ch) {\n        const last = --this.cn;\n        this.cx[j] = this.cx[last];\n        this.cy[j] = this.cy[last];\n        this.cvx[j] = this.cvx[last];\n        this.cvy[j] = this.cvy[last];\n        this.cr[j] = this.cr[last];\n        this.cage[j] = this.cage[last];\n        this.cax[j] = this.cax[last];\n        this.cay[j] = this.cay[last];\n      }\n    }\n    this.viewDirty = true;\n  }\n\n  /* ── Frame ── */\n\n  private flow(dt: number) {\n    if (!this.pendList.length) return;\n    const step = FLOW * dt;\n    let w = 0;\n    for (let i = 0; i < this.pendList.length; i++) {\n      const c = this.pendList[i];\n      const t = Math.min(this.pend[c], step);\n      this.pend[c] -= t;\n      this.d[c] = Math.min(1, this.d[c] + t);\n      if (this.pend[c] > 1e-4) this.pendList[w++] = c;\n      else {\n        this.pend[c] = 0;\n        this.inPend[c] = 0;\n      }\n    }\n    this.pendList.length = w;\n    this.viewDirty = true;\n  }\n\n  private checkFull(dt: number) {\n    if (this.full || !this.snowing) return;\n    this.snowTime += dt;\n    this.checkTimer += dt;\n    if (this.checkTimer < 0.4) return;\n    this.checkTimer = 0;\n    let count = 0;\n    for (let c = 0; c < this.cells; c++) if (this.d[c] >= 0.5) count++;\n    if (count >= this.capacity * FULL || this.snowTime > 40) this.full = true;\n  }\n\n  private buildView() {\n    const v = this.view;\n    const d = this.d;\n    for (let c = 0; c < this.cells; c++) v[c] = d[c] >= 1 ? 255 : (d[c] * 255) | 0;\n    const edges = this.edgeCells;\n    const nb = this.edgeNbrs;\n    for (let e = 0; e < edges.length; e++) {\n      let m = 0;\n      for (let j = e * 4; j < e * 4 + 4; j++) {\n        const nc = nb[j];\n        if (nc >= 0 && v[nc] > m) m = v[nc];\n      }\n      v[edges[e]] = m;\n    }\n    const cv = this.clumpView;\n    cv.fill(0);\n    if (this.cn) {\n      const { gw, gh, cell } = this.layout;\n      for (let j = 0; j < this.cn; j++) {\n        if (this.cage[j] < 0) continue;\n        const rc = (this.cr[j] * Math.max(0.55, 1 - 0.35 * this.cage[j])) / cell + 0.5;\n        const px = this.cx[j] / cell - 0.5;\n        const py = this.cy[j] / cell - 0.5;\n        const x0 = Math.max(0, Math.floor(px - rc));\n        const x1 = Math.min(gw - 1, Math.ceil(px + rc));\n        const y0 = Math.max(0, Math.floor(py - rc));\n        const y1 = Math.min(gh - 1, Math.ceil(py + rc));\n        const r2 = rc * rc;\n        for (let y = y0; y <= y1; y++) {\n          for (let x = x0; x <= x1; x++) {\n            const dd = ((x - px) * (x - px) + (y - py) * (y - py)) / r2;\n            if (dd >= 1) continue;\n            const val = Math.min(255, (1.3 * (1 - dd) * 255) | 0);\n            const c = y * gw + x;\n            if (val > cv[c]) cv[c] = val;\n          }\n        }\n      }\n    }\n  }\n\n  private writeInstances() {\n    const out = this.instances;\n    let p = 0;\n    for (let i = 0; i < this.n; i++) {\n      out[p++] = this.fx[i];\n      out[p++] = this.fy[i];\n      out[p++] = this.fr[i];\n      out[p++] = this.fa[i];\n      out[p++] = this.fsoft[i];\n      out[p++] = this.fkind[i] === BACK ? 1 : 0;\n    }\n    this.instanceCount = this.n;\n  }\n\n  /** Advance by dt seconds. Returns whether anything is still moving or about to. */\n  step(dt: number) {\n    this.time += dt;\n    const target = this.pause > 0 || !this.snowing ? 0 : this.full ? (this.keepFalling ? 0.35 : 0) : 1;\n    this.pause = Math.max(0, this.pause - dt);\n    this.ramp += (target - this.ramp) * Math.min(1, (target > this.ramp ? 1.6 : 0.7) * dt);\n    if (target === 0 && this.ramp < 0.02) this.ramp = 0;\n    this.acc += this.rate * this.intensity * this.ramp * dt;\n    while (this.acc >= 1) {\n      this.acc -= 1;\n      this.spawn(-this.u * 6);\n    }\n    this.stepFlakes(dt);\n    this.stepClumps(dt);\n    this.flow(dt);\n    this.checkFull(dt);\n    if (this.viewDirty) {\n      this.buildView();\n    }\n    this.writeInstances();\n    return this.moving();\n  }\n\n  moving() {\n    return this.n > 0 || this.cn > 0 || this.pendList.length > 0 || this.ramp > 0 || this.pause > 0 || (this.snowing && (!this.full || this.keepFalling));\n  }\n\n  /** True once after a snowfall has finished and everything is still. */\n  takeSettled() {\n    if (!this.armed || this.moving()) return false;\n    this.armed = false;\n    return true;\n  }\n}\n"},{"path":"registry/snowfall-gl.ts","type":"registry:component","content":"// Hairline UI · snowfall · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * SNOWFALL renderer (WebGL 2)\n *\n *   snow     the settled snow is a coarse field of cells drawn\n *            smooth (a cubic B-spline through the cells, cut at\n *            half), clipped by a fine mask of the shape so it\n *            meets every edge cleanly; lit from above, shaded\n *            where it faces down and where it packs against a\n *            wall, with a fine grain and a few slow glints\n *   flakes   one quad per flake: small crisp ones, large soft\n *            ones close to the eye, far ones hidden by the logo\n *\n * On light pages the snow and flakes get a cool rim, since\n * white on white has no edge of its own.\n * ───────────────────────────────────────────────────────── */\n\nexport interface SnowFrame {\n  /** Settled snow cells, one byte each, or null when unchanged. */\n  view: Uint8Array | null;\n  /** Snow in the air after a shake, same grid; uploaded with view. */\n  clumps: Uint8Array | null;\n  instances: Float32Array;\n  count: number;\n  /** Canvas size in CSS px. */\n  width: number;\n  height: number;\n  dpr: number;\n  light: boolean;\n  time: number;\n}\n\nexport interface SnowRenderer {\n  setMask(data: Uint8Array, width: number, height: number): void;\n  setGrid(width: number, height: number): void;\n  draw(frame: SnowFrame): void;\n  dispose(): void;\n}\n\nconst VERT_FIELD = `#version 300 es\nin vec2 aPos;\nout vec2 vUv;\nvoid main() {\n  vUv = vec2(aPos.x * 0.5 + 0.5, 0.5 - aPos.y * 0.5);\n  gl_Position = vec4(aPos, 0.0, 1.0);\n}`;\n\nconst FRAG_FIELD = `#version 300 es\nprecision highp float;\nin vec2 vUv;\nuniform sampler2D uD;\nuniform sampler2D uC;\nuniform sampler2D uM;\nuniform vec2 uGrid;\nuniform float uLight;\nuniform float uTime;\nuniform float uDpr;\nout vec4 o;\n\nconst float TH = 0.42;\n\nvec4 cubicW(float v) {\n  vec4 n = vec4(1.0, 2.0, 3.0, 4.0) - v;\n  vec4 s = n * n * n;\n  float x = s.x;\n  float y = s.y - 4.0 * s.x;\n  float z = s.z - 4.0 * s.y + 6.0 * s.x;\n  float w = 6.0 - x - y - z;\n  return vec4(x, y, z, w) * (1.0 / 6.0);\n}\n\nfloat field(sampler2D tex, vec2 uv) {\n  vec2 inv = 1.0 / uGrid;\n  vec2 tc = uv * uGrid - 0.5;\n  vec2 f = fract(tc);\n  tc -= f;\n  vec4 xc = cubicW(f.x);\n  vec4 yc = cubicW(f.y);\n  vec4 c = tc.xxyy + vec2(-0.5, 1.5).xyxy;\n  vec4 s = vec4(xc.xz + xc.yw, yc.xz + yc.yw);\n  vec4 off = (c + vec4(xc.yw, yc.yw) / s) * inv.xxyy;\n  float s0 = texture(tex, off.xz).r;\n  float s1 = texture(tex, off.yz).r;\n  float s2 = texture(tex, off.xw).r;\n  float s3 = texture(tex, off.yw).r;\n  float sx = s.x / (s.x + s.y);\n  float sy = s.z / (s.z + s.w);\n  return mix(mix(s3, s2, sx), mix(s1, s0, sx), sy);\n}\n\nfloat hash(vec2 p) {\n  p = fract(p * vec2(123.34, 456.21));\n  p += dot(p, p + 45.32);\n  return fract(p.x * p.y);\n}\n\nvoid main() {\n  vec4 m = texture(uM, vUv);\n  float allowed = smoothstep(0.3, 0.7, m.r);\n  float ds = field(uD, vUv);\n  float dc = field(uC, vUv);\n  float aas = max(fwidth(ds) * 0.85, 0.002);\n  float aac = max(fwidth(dc) * 0.85, 0.002);\n  float as_ = smoothstep(TH - aas, TH + aas, ds) * allowed;\n  float ac = smoothstep(TH - aac, TH + aac, dc);\n  bool air = ac > as_;\n  float d = air ? dc : ds;\n  float aa = air ? aac : aas;\n  float a = max(as_, ac);\n  if (a < 0.002) { o = vec4(0.0); return; }\n  vec2 g = vec2(dFdx(d), dFdy(d));\n  float gl = length(g);\n  vec2 nrm = gl > 1e-6 ? -g / gl : vec2(0.0, 1.0);\n  float edge = 1.0 - smoothstep(TH, TH + 0.3, d);\n  float up = clamp(nrm.y, 0.0, 1.0);\n  float down = clamp(-nrm.y, 0.0, 1.0);\n  vec3 body = vec3(0.93, 0.952, 0.988);\n  vec3 cool = vec3(0.64, 0.72, 0.87);\n  vec3 col = body;\n  col = mix(col, vec3(1.0), edge * up * 0.9);\n  col = mix(col, cool, edge * down * 0.5);\n  col = mix(col, cool, smoothstep(0.12, 0.9, m.g) * 0.4 * (air ? 0.0 : 1.0));\n  vec2 fc = gl_FragCoord.xy;\n  col *= 0.982 + 0.036 * hash(floor(fc / (1.2 * uDpr)));\n  float h = hash(floor(fc / (1.7 * uDpr)) + 31.7);\n  float glint = step(0.9955, h) * (0.5 + 0.5 * sin(uTime * 1.6 + h * 91.0));\n  col = mix(col, vec3(1.0), glint * (1.0 - down * edge));\n  float rim = (1.0 - smoothstep(TH + aa, TH + aa + 0.1, d)) * uLight;\n  col = mix(col, cool * 0.9, rim * 0.55);\n  o = vec4(col * a, a);\n}`;\n\nconst VERT_FLAKE = `#version 300 es\nin vec2 aCorner;\nin vec4 aA;\nin vec2 aB;\nuniform vec2 uView;\nuniform vec3 uFade;\nout vec2 vLocal;\nout float vR;\nout float vAlpha;\nout float vSoft;\nout float vOcc;\nout vec2 vUv;\nvoid main() {\n  float pad = 1.0 + aA.z * aB.x * 0.4;\n  vec2 local = aCorner * (aA.z + pad);\n  vec2 p = aA.xy + local;\n  vLocal = local;\n  vR = aA.z;\n  vSoft = aB.x;\n  vOcc = aB.y;\n  float fade = smoothstep(0.0, uFade.x, aA.y) * (1.0 - smoothstep(uView.y - uFade.y, uView.y, aA.y))\n    * smoothstep(0.0, uFade.z, aA.x) * smoothstep(0.0, uFade.z, uView.x - aA.x);\n  vAlpha = aA.w * fade;\n  vUv = p / uView;\n  gl_Position = vec4(vUv.x * 2.0 - 1.0, 1.0 - vUv.y * 2.0, 0.0, 1.0);\n}`;\n\nconst FRAG_FLAKE = `#version 300 es\nprecision highp float;\nin vec2 vLocal;\nin float vR;\nin float vAlpha;\nin float vSoft;\nin float vOcc;\nin vec2 vUv;\nuniform sampler2D uM;\nuniform float uLight;\nuniform float uDpr;\nout vec4 o;\nvoid main() {\n  float dist = length(vLocal);\n  float aa = 0.7 / uDpr;\n  float inner = vR * (1.0 - vSoft * 0.9);\n  float a = 1.0 - smoothstep(inner - aa, vR + aa, dist);\n  a *= vAlpha;\n  if (vOcc > 0.5) a *= 1.0 - texture(uM, vUv).b;\n  if (a < 0.003) discard;\n  // On light pages a flake is a pale cool dot with a slightly deeper edge; a rim alone would read as a ring on small flakes.\n  float edgeTint = smoothstep(vR * 0.2, vR, dist);\n  vec3 col = mix(vec3(1.0), vec3(0.6, 0.68, 0.82), uLight * (0.42 + 0.3 * edgeTint) * (1.0 - vSoft * 0.5));\n  o = vec4(col * a, a);\n}`;\n\nfunction compile(gl: WebGL2RenderingContext, vert: string, frag: string) {\n  const program = gl.createProgram();\n  if (!program) throw new Error(\"program\");\n  for (const [type, src] of [\n    [gl.VERTEX_SHADER, vert],\n    [gl.FRAGMENT_SHADER, frag],\n  ] as const) {\n    const shader = gl.createShader(type);\n    if (!shader) throw new Error(\"shader\");\n    gl.shaderSource(shader, src);\n    gl.compileShader(shader);\n    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(shader) ?? \"shader\");\n    gl.attachShader(program, shader);\n  }\n  gl.linkProgram(program);\n  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program) ?? \"link\");\n  return program;\n}\n\nfunction texture(gl: WebGL2RenderingContext) {\n  const t = gl.createTexture();\n  gl.bindTexture(gl.TEXTURE_2D, t);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n  return t;\n}\n\n/** Returns null when WebGL 2 is not available; the element then shows as it is. */\nexport function createSnowRenderer(canvas: HTMLCanvasElement): SnowRenderer | null {\n  const gl = canvas.getContext(\"webgl2\", { premultipliedAlpha: true, alpha: true, antialias: false, depth: false, stencil: false });\n  if (!gl) return null;\n  let fieldProgram: WebGLProgram;\n  let flakeProgram: WebGLProgram;\n  try {\n    fieldProgram = compile(gl, VERT_FIELD, FRAG_FIELD);\n    flakeProgram = compile(gl, VERT_FLAKE, FRAG_FLAKE);\n  } catch {\n    return null;\n  }\n  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);\n\n  const fu = (name: string) => gl.getUniformLocation(fieldProgram, name);\n  const pu = (name: string) => gl.getUniformLocation(flakeProgram, name);\n  const field = { d: fu(\"uD\"), c: fu(\"uC\"), m: fu(\"uM\"), grid: fu(\"uGrid\"), light: fu(\"uLight\"), time: fu(\"uTime\"), dpr: fu(\"uDpr\") };\n  const flake = { view: pu(\"uView\"), fade: pu(\"uFade\"), m: pu(\"uM\"), light: pu(\"uLight\"), dpr: pu(\"uDpr\") };\n\n  const fieldVao = gl.createVertexArray();\n  gl.bindVertexArray(fieldVao);\n  const tri = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, tri);\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n  const aPos = gl.getAttribLocation(fieldProgram, \"aPos\");\n  gl.enableVertexAttribArray(aPos);\n  gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);\n\n  const flakeVao = gl.createVertexArray();\n  gl.bindVertexArray(flakeVao);\n  const quad = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, quad);\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);\n  const aCorner = gl.getAttribLocation(flakeProgram, \"aCorner\");\n  gl.enableVertexAttribArray(aCorner);\n  gl.vertexAttribPointer(aCorner, 2, gl.FLOAT, false, 0, 0);\n  const inst = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, inst);\n  let instCapacity = 0;\n  const aA = gl.getAttribLocation(flakeProgram, \"aA\");\n  const aB = gl.getAttribLocation(flakeProgram, \"aB\");\n  gl.enableVertexAttribArray(aA);\n  gl.vertexAttribPointer(aA, 4, gl.FLOAT, false, 24, 0);\n  gl.vertexAttribDivisor(aA, 1);\n  gl.enableVertexAttribArray(aB);\n  gl.vertexAttribPointer(aB, 2, gl.FLOAT, false, 24, 16);\n  gl.vertexAttribDivisor(aB, 1);\n  gl.bindVertexArray(null);\n\n  const dTex = texture(gl);\n  const cTex = texture(gl);\n  const mTex = texture(gl);\n  let grid: [number, number] = [1, 1];\n  let hasMask = false;\n\n  return {\n    setMask(data, width, height) {\n      gl.bindTexture(gl.TEXTURE_2D, mTex);\n      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);\n      hasMask = true;\n    },\n    setGrid(width, height) {\n      grid = [width, height];\n      for (const t of [dTex, cTex]) {\n        gl.bindTexture(gl.TEXTURE_2D, t);\n        gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, new Uint8Array(width * height));\n      }\n    },\n    draw(frame) {\n      const w = Math.max(1, Math.round(frame.width * frame.dpr));\n      const h = Math.max(1, Math.round(frame.height * frame.dpr));\n      if (canvas.width !== w || canvas.height !== h) {\n        canvas.width = w;\n        canvas.height = h;\n      }\n      gl.viewport(0, 0, w, h);\n      gl.clearColor(0, 0, 0, 0);\n      gl.clear(gl.COLOR_BUFFER_BIT);\n      if (!hasMask) return;\n      gl.enable(gl.BLEND);\n      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n\n      if (frame.view) {\n        gl.bindTexture(gl.TEXTURE_2D, dTex);\n        gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, grid[0], grid[1], gl.RED, gl.UNSIGNED_BYTE, frame.view);\n      }\n      if (frame.clumps) {\n        gl.bindTexture(gl.TEXTURE_2D, cTex);\n        gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, grid[0], grid[1], gl.RED, gl.UNSIGNED_BYTE, frame.clumps);\n      }\n      gl.activeTexture(gl.TEXTURE0);\n      gl.bindTexture(gl.TEXTURE_2D, dTex);\n      gl.activeTexture(gl.TEXTURE1);\n      gl.bindTexture(gl.TEXTURE_2D, mTex);\n      gl.activeTexture(gl.TEXTURE2);\n      gl.bindTexture(gl.TEXTURE_2D, cTex);\n\n      gl.useProgram(fieldProgram);\n      gl.uniform1i(field.d, 0);\n      gl.uniform1i(field.m, 1);\n      gl.uniform1i(field.c, 2);\n      gl.uniform2f(field.grid, grid[0], grid[1]);\n      gl.uniform1f(field.light, frame.light ? 1 : 0);\n      gl.uniform1f(field.time, frame.time);\n      gl.uniform1f(field.dpr, frame.dpr);\n      gl.bindVertexArray(fieldVao);\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n\n      if (frame.count) {\n        gl.useProgram(flakeProgram);\n        gl.uniform1i(flake.m, 1);\n        gl.uniform2f(flake.view, frame.width, frame.height);\n        gl.uniform3f(flake.fade, frame.height * 0.08, frame.height * 0.14, frame.width * 0.09);\n        gl.uniform1f(flake.light, frame.light ? 1 : 0);\n        gl.uniform1f(flake.dpr, frame.dpr);\n        gl.bindVertexArray(flakeVao);\n        gl.bindBuffer(gl.ARRAY_BUFFER, inst);\n        const bytes = frame.count * 24;\n        if (bytes > instCapacity) {\n          instCapacity = frame.instances.byteLength;\n          gl.bufferData(gl.ARRAY_BUFFER, instCapacity, gl.DYNAMIC_DRAW);\n        }\n        gl.bufferSubData(gl.ARRAY_BUFFER, 0, frame.instances, 0, frame.count * 6);\n        gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, frame.count);\n      }\n      gl.bindVertexArray(null);\n      gl.activeTexture(gl.TEXTURE0);\n    },\n    dispose() {\n      gl.deleteTexture(dTex);\n      gl.deleteTexture(cTex);\n      gl.deleteTexture(mTex);\n      gl.deleteBuffer(tri);\n      gl.deleteBuffer(quad);\n      gl.deleteBuffer(inst);\n      gl.deleteVertexArray(fieldVao);\n      gl.deleteVertexArray(flakeVao);\n      gl.deleteProgram(fieldProgram);\n      gl.deleteProgram(flakeProgram);\n    },\n  };\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · snowfall · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/snowfall. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}