{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"mosaic-glow","type":"registry:ui","title":"MosaicGlow","description":"Canvas mosaic of small tiles on a dark surface where a soft halo follows the cursor with a lag, lighting tiles to random gold intensities that decay into a comet trail, with an additive bloom over the gaps, a glassy per-tile highlight, ambient flicker and an autonomous drift when idle","author":"fancy-ui <https://fancy-ui.rama.app>","categories":["backgrounds"],"registryDependencies":["https://fancy-ui.rama.app/r/internals-dom.json","https://fancy-ui.rama.app/r/utils.json"],"files":[{"path":"react/src/components/mosaic-glow/MosaicGlow.tsx","content":"\"use client\";\n\nimport { forwardRef, useEffect, useRef, useState } from \"react\";\nimport type { HTMLAttributes, ReactNode } from \"react\";\n\nimport { cn } from \"../../utils\";\nimport { useComposedRefs } from \"../../internals/dom/use-composed-refs\";\nimport { useConstant } from \"../../internals/dom/ssr\";\nimport { useElementRef } from \"../../internals/dom/use-element-ref\";\nimport { useLiveRef } from \"../../internals/dom/use-live-ref\";\nimport {\n\tATTACK_TAU,\n\tbuildLut,\n\tclamp01,\n\tcreateGrid,\n\tdriftPoint,\n\tflickerTiles,\n\tlutIndex,\n\tparseRgb,\n\trate,\n\treleaseTau,\n\tsmoothingTau,\n\tupdateTiles,\n\tDEFAULT_COLOR,\n\ttype Halo,\n\ttype MosaicGlowFrame,\n\ttype MosaicGrid,\n} from \"./mosaic-glow-core\";\nimport { startMosaicGlowHdr } from \"./mosaic-glow-hdr\";\n\nexport type MosaicGlowIdle = \"drift\" | \"none\";\n\n/**\n * MosaicGlow — a cursor-lit canvas mosaic.\n *\n * A dark surface tiled with small squares. A soft halo follows the pointer\n * with a slight lag and lights the tiles under it to random intensities;\n * lit tiles fade slowly so the pointer leaves a comet trail. An additive\n * bloom bleeds over the gaps, a glassy highlight sits on every tile, and a\n * scattering of faint tiles stays visible outside the halo. With nobody\n * pointing, the halo drifts on its own.\n */\nexport interface MosaicGlowProps extends Omit<\n\tHTMLAttributes<HTMLDivElement>,\n\t\"color\" | \"children\"\n> {\n\t/** Additional classes on the host */\n\tclassName?: string;\n\t/** Content rendered above the canvas — give the host a height */\n\tchildren?: ReactNode;\n\t/** Tile edge in CSS px */\n\ttileSize?: number;\n\t/** Gap between tiles in CSS px */\n\tgap?: number;\n\t/** Halo / tile colour — hex or rgb() */\n\tcolor?: string;\n\t/** Surface colour behind the tiles — hex or rgb() */\n\tbackground?: string;\n\t/** Halo radius in CSS px */\n\tradius?: number;\n\t/** Overall brightness of lit tiles, 0–1 */\n\tintensity?: number;\n\t/** How long lit tiles linger after the halo moves on, 0–1 */\n\ttrail?: number;\n\t/** Pointer lag, 0 (instant) to 1 (very laggy) */\n\tsmoothing?: number;\n\t/** Spread of per-tile random brightness inside the halo, 0–1 */\n\tnoise?: number;\n\t/** Visibility of the random faint tiles outside the halo, 0–1 */\n\tambient?: number;\n\t/** Slowly re-roll the faint tiles over time */\n\tflicker?: boolean;\n\t/** What the halo does with no pointer: wander on its own or switch off */\n\tidle?: MosaicGlowIdle;\n\t/** Follow the pointer. Off leaves only the idle behaviour. */\n\tinteractive?: boolean;\n\t/** Seed for the per-tile randomness — same seed, same mosaic */\n\tseed?: number;\n\t/**\n\t * On a display that reports HDR, add the light above SDR white in a WebGPU\n\t * layer with extended tone mapping: the hottest tiles peak around 1000\n\t * nits and the halo gets a hot core. Elsewhere the mosaic is unchanged.\n\t */\n\thdr?: boolean;\n}\n\n/** Wait after the pointer leaves before the idle drift takes over (ms). */\nconst IDLE_DELAY_MS = 1500;\n/** Ambient-only frames are drawn at most this often (ms). */\nconst AMBIENT_FRAME_MS = 50;\nconst FLICKER_CHANCE = 0.15;\nconst LUT_SIZE = 64;\n\n/**\n * Everything the frame loop touches and nothing React renders — the counterpart\n * of the Svelte source's plain (non-`$state`) module closure variables. It is\n * one object, created once per instance, so a prop effect and the running loop\n * mutate the same field without either of them re-rendering the component.\n *\n * `reducedMotion` is mirrored here as well as held in React state: the state is\n * what an effect can depend on, the mirror is what the long-lived loop and\n * pointer closures read.\n */\ninterface MosaicMachine {\n\tctx: CanvasRenderingContext2D | null;\n\tglassLayer: HTMLCanvasElement | null;\n\tgrid: MosaicGrid | null;\n\tlut: string[] | null;\n\tdpr: number;\n\tcssW: number;\n\tcssH: number;\n\tw: number;\n\th: number;\n\tpitchDev: number;\n\ttileDev: number;\n\tpx: number;\n\tpy: number;\n\tpointerOver: boolean;\n\tsx: number;\n\tsy: number;\n\tsInit: boolean;\n\thaloFade: number;\n\tdriftT: number;\n\tlastLeaveAt: number;\n\trafId: number | null;\n\tlastTime: number;\n\tlastDraw: number;\n\t/** Something structural changed (size, grid, colours): the next frame must paint. */\n\tdirty: boolean;\n\tvisible: boolean;\n\treducedMotion: boolean;\n\t/** Light-layer callback, called after every painted frame. */\n\tonFrame: ((frame: MosaicGlowFrame) => void) | null;\n}\n\nfunction createMachine(): MosaicMachine {\n\treturn {\n\t\tctx: null,\n\t\tglassLayer: null,\n\t\tgrid: null,\n\t\tlut: null,\n\t\tdpr: 1,\n\t\tcssW: 0,\n\t\tcssH: 0,\n\t\tw: 0,\n\t\th: 0,\n\t\tpitchDev: 20,\n\t\ttileDev: 18,\n\t\tpx: 0,\n\t\tpy: 0,\n\t\tpointerOver: false,\n\t\tsx: 0,\n\t\tsy: 0,\n\t\tsInit: false,\n\t\thaloFade: 0,\n\t\tdriftT: 0,\n\t\tlastLeaveAt: -1,\n\t\trafId: null,\n\t\tlastTime: 0,\n\t\tlastDraw: 0,\n\t\tdirty: true,\n\t\tvisible: true,\n\t\treducedMotion: false,\n\t\tonFrame: null,\n\t};\n}\n\n/**\n * The handful of loop entry points a prop effect needs. They are closures over\n * the live canvas, so they only exist between the mount effect and its cleanup;\n * every caller checks first, which is the React shape of the Svelte source's\n * `if (!ctx) return`.\n */\ninterface MosaicRuntime {\n\tresize: () => void;\n\trequestFrame: () => void;\n\tstopLoop: () => void;\n\tdrawStatic: (halo: Halo | null) => void;\n\tinitialHalo: () => Halo | null;\n}\n\n/** Every prop the loop reads per frame, in its already-clamped form. */\ninterface LiveProps {\n\tcolor: string;\n\tbackground: string;\n\tidle: MosaicGlowIdle;\n\tflicker: boolean;\n\tintensityC: number;\n\ttrailC: number;\n\tsmoothingC: number;\n\tnoiseC: number;\n\tambientC: number;\n\tradiusC: number;\n\ttileC: number;\n\tgapC: number;\n\tseed: number;\n}\n\nexport const MosaicGlow = forwardRef<HTMLDivElement, MosaicGlowProps>(function MosaicGlow(\n\t{\n\t\tclassName,\n\t\tchildren,\n\t\ttileSize = 18,\n\t\tgap = 2,\n\t\tcolor = \"#f2c318\",\n\t\tbackground = \"#0a0a0a\",\n\t\tradius = 170,\n\t\tintensity = 1,\n\t\ttrail = 0.6,\n\t\tsmoothing = 0.15,\n\t\tnoise = 0.7,\n\t\tambient = 0.35,\n\t\tflicker = true,\n\t\tidle = \"drift\",\n\t\tinteractive = true,\n\t\tseed = 1,\n\t\thdr = true,\n\t\tstyle,\n\t\t...restProps\n\t},\n\tforwardedRef\n) {\n\tconst intensityC = clamp01(intensity);\n\tconst trailC = clamp01(trail);\n\tconst smoothingC = clamp01(smoothing);\n\tconst noiseC = clamp01(noise);\n\tconst ambientC = clamp01(ambient);\n\tconst radiusC = Math.max(1, Number.isFinite(radius) ? radius : 170);\n\tconst tileC = Math.max(1, Number.isFinite(tileSize) ? tileSize : 18);\n\tconst gapC = Math.max(0, Number.isFinite(gap) ? gap : 2);\n\n\t// C-1: the nodes, not refs — the setup effect is keyed on them, so it runs\n\t// the moment both exist rather than racing the first commit.\n\tconst [host, hostRef] = useElementRef<HTMLDivElement>();\n\tconst [canvas, canvasRef] = useElementRef<HTMLCanvasElement>();\n\t// C-2: composed above every early return; there are none here, but the\n\t// forwarded ref and the internal one must still be merged in one callback.\n\tconst composedHostRef = useComposedRefs<HTMLDivElement>(forwardedRef, hostRef);\n\n\tconst machine = useConstant(createMachine);\n\tconst runtimeRef = useRef<MosaicRuntime | null>(null);\n\n\t// The Svelte source reads these as `$props()` getters from inside the frame\n\t// loop, which is outside any tracking context: a new colour or intensity\n\t// lands on the next frame and never tears the canvas down.\n\tconst live = useLiveRef<LiveProps>({\n\t\tcolor,\n\t\tbackground,\n\t\tidle,\n\t\tflicker,\n\t\tintensityC,\n\t\ttrailC,\n\t\tsmoothingC,\n\t\tnoiseC,\n\t\tambientC,\n\t\tradiusC,\n\t\ttileC,\n\t\tgapC,\n\t\tseed,\n\t});\n\n\tconst [reducedMotion, setReducedMotion] = useState(false);\n\tconst [hdrCanvas, hdrCanvasRef] = useElementRef<HTMLCanvasElement>();\n\tconst [hdrOn, setHdrOn] = useState(false);\n\t/** Set once the draw runtime exists, so the HDR effect can attach to it. */\n\tconst [engineReady, setEngineReady] = useState(false);\n\n\t// --- mount: context, observers, reduced motion -----------------------------\n\n\tuseEffect(() => {\n\t\tif (!host || !canvas) return;\n\t\tconst hostEl: HTMLDivElement = host;\n\t\tconst canvasEl: HTMLCanvasElement = canvas;\n\t\tconst context = canvasEl.getContext(\"2d\");\n\t\tif (!context) return;\n\t\t// Re-bound with an explicit non-null type: the draw helpers below are\n\t\t// hoisted function declarations, and TypeScript does not carry the null\n\t\t// check above into one.\n\t\tconst ctx: CanvasRenderingContext2D = context;\n\t\tconst m = machine;\n\t\tm.ctx = ctx;\n\n\t\t/** Backing-store scale, capped so dense displays do not blow up the fill rate. */\n\t\tfunction currentDpr() {\n\t\t\treturn Math.min(typeof window !== \"undefined\" ? window.devicePixelRatio || 1 : 1, 2);\n\t\t}\n\n\t\tfunction resize() {\n\t\t\tif (!m.ctx) return;\n\t\t\tconst p = live.current;\n\t\t\tm.cssW = hostEl.clientWidth;\n\t\t\tm.cssH = hostEl.clientHeight;\n\t\t\tm.dpr = currentDpr();\n\t\t\tm.w = Math.max(1, Math.round(m.cssW * m.dpr));\n\t\t\tm.h = Math.max(1, Math.round(m.cssH * m.dpr));\n\t\t\tcanvasEl.width = m.w;\n\t\t\tcanvasEl.height = m.h;\n\t\t\tm.tileDev = Math.max(1, Math.round(p.tileC * m.dpr));\n\t\t\tm.pitchDev = Math.max(m.tileDev, Math.round((p.tileC + p.gapC) * m.dpr));\n\t\t\tconst cols = Math.ceil(m.w / m.pitchDev);\n\t\t\tconst rows = Math.ceil(m.h / m.pitchDev);\n\t\t\tm.grid = createGrid(cols, rows, p.seed, p.noiseC, p.ambientC);\n\t\t\trebuildGlass(cols, rows);\n\t\t\tm.dirty = true;\n\t\t\tif (m.reducedMotion) drawStatic(initialHalo());\n\t\t\telse requestFrame();\n\t\t}\n\n\t\t/** One cached full-size layer with a glassy highlight stamped on every tile. */\n\t\tfunction rebuildGlass(cols: number, rows: number) {\n\t\t\tm.glassLayer = null;\n\t\t\tif (typeof document === \"undefined\") return;\n\t\t\tconst sprite = document.createElement(\"canvas\");\n\t\t\tsprite.width = m.tileDev;\n\t\t\tsprite.height = m.tileDev;\n\t\t\tconst sctx = sprite.getContext(\"2d\");\n\t\t\tif (!sctx) return;\n\t\t\tconst grad = sctx.createRadialGradient(\n\t\t\t\tm.tileDev * 0.35,\n\t\t\t\tm.tileDev * 0.3,\n\t\t\t\t0,\n\t\t\t\tm.tileDev * 0.5,\n\t\t\t\tm.tileDev * 0.5,\n\t\t\t\tm.tileDev * 0.7\n\t\t\t);\n\t\t\tgrad.addColorStop(0, \"rgba(255, 255, 255, 0.22)\");\n\t\t\tgrad.addColorStop(1, \"rgba(255, 255, 255, 0)\");\n\t\t\tsctx.fillStyle = grad;\n\t\t\tsctx.fillRect(0, 0, m.tileDev, m.tileDev);\n\n\t\t\tconst layer = document.createElement(\"canvas\");\n\t\t\tlayer.width = m.w;\n\t\t\tlayer.height = m.h;\n\t\t\tconst lctx = layer.getContext(\"2d\");\n\t\t\tif (!lctx) return;\n\t\t\tfor (let r = 0; r < rows; r++) {\n\t\t\t\tfor (let c = 0; c < cols; c++) {\n\t\t\t\t\tlctx.drawImage(sprite, c * m.pitchDev, r * m.pitchDev);\n\t\t\t\t}\n\t\t\t}\n\t\t\tm.glassLayer = layer;\n\t\t}\n\n\t\tfunction ensureLut(): string[] {\n\t\t\tif (!m.lut) m.lut = buildLut(live.current.background, live.current.color, LUT_SIZE);\n\t\t\treturn m.lut;\n\t\t}\n\n\t\tfunction initialHalo(): Halo | null {\n\t\t\tif (live.current.idle !== \"drift\") return null;\n\t\t\tconst p = driftPoint(0, m.w, m.h);\n\t\t\treturn { x: p.x, y: p.y, r: live.current.radiusC * m.dpr };\n\t\t}\n\n\t\t// --- loop ---------------------------------------------------------------\n\n\t\tfunction requestFrame() {\n\t\t\tif (m.rafId !== null || !m.visible || m.reducedMotion || !m.ctx) return;\n\t\t\tif (typeof requestAnimationFrame !== \"function\") return;\n\t\t\tm.lastTime = 0;\n\t\t\tm.rafId = requestAnimationFrame(tick);\n\t\t}\n\n\t\tfunction stopLoop() {\n\t\t\tif (m.rafId !== null && typeof cancelAnimationFrame === \"function\")\n\t\t\t\tcancelAnimationFrame(m.rafId);\n\t\t\tm.rafId = null;\n\t\t}\n\n\t\tfunction tick(now: number) {\n\t\t\tm.rafId = null;\n\t\t\tconst g = m.grid;\n\t\t\tif (!m.ctx || !g) return;\n\t\t\tconst p = live.current;\n\n\t\t\tconst dt = m.lastTime === 0 ? 1 / 60 : Math.min(0.1, Math.max(0, (now - m.lastTime) / 1000));\n\t\t\tm.lastTime = now;\n\n\t\t\tconst drifting =\n\t\t\t\tp.idle === \"drift\" &&\n\t\t\t\t!m.pointerOver &&\n\t\t\t\t(m.lastLeaveAt < 0 || now - m.lastLeaveAt > IDLE_DELAY_MS);\n\t\t\tlet tx = 0;\n\t\t\tlet ty = 0;\n\t\t\tlet hasTarget = false;\n\t\t\tif (m.pointerOver) {\n\t\t\t\ttx = m.px;\n\t\t\t\tty = m.py;\n\t\t\t\thasTarget = true;\n\t\t\t} else if (drifting) {\n\t\t\t\tm.driftT += dt;\n\t\t\t\tconst point = driftPoint(m.driftT, m.w, m.h);\n\t\t\t\ttx = point.x;\n\t\t\t\tty = point.y;\n\t\t\t\thasTarget = true;\n\t\t\t}\n\n\t\t\tif (hasTarget) {\n\t\t\t\tif (!m.sInit) {\n\t\t\t\t\tm.sx = tx;\n\t\t\t\t\tm.sy = ty;\n\t\t\t\t\tm.sInit = true;\n\t\t\t\t} else {\n\t\t\t\t\tconst tau = drifting\n\t\t\t\t\t\t? Math.max(smoothingTau(p.smoothingC), 0.35)\n\t\t\t\t\t\t: smoothingTau(p.smoothingC);\n\t\t\t\t\tconst k = rate(dt, tau);\n\t\t\t\t\tm.sx += (tx - m.sx) * k;\n\t\t\t\t\tm.sy += (ty - m.sy) * k;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst rel = releaseTau(p.trailC);\n\t\t\tconst fadeTarget = hasTarget ? 1 : 0;\n\t\t\tm.haloFade +=\n\t\t\t\t(fadeTarget - m.haloFade) * rate(dt, fadeTarget > m.haloFade ? ATTACK_TAU : rel);\n\t\t\tif (m.haloFade < 0.005) m.haloFade = 0;\n\n\t\t\tconst halo: Halo | null = hasTarget ? { x: m.sx, y: m.sy, r: p.radiusC * m.dpr } : null;\n\t\t\tconst maxDelta = updateTiles(g, halo, dt, {\n\t\t\t\tpitch: m.pitchDev,\n\t\t\t\ttile: m.tileDev,\n\t\t\t\tattackTau: ATTACK_TAU,\n\t\t\t\treleaseTau: rel,\n\t\t\t});\n\t\t\tif (p.flicker) flickerTiles(g, dt, FLICKER_CHANCE, p.ambientC);\n\n\t\t\tconst active = hasTarget || maxDelta > 0.002 || m.haloFade > 0;\n\t\t\tif (active || m.dirty || now - m.lastDraw >= AMBIENT_FRAME_MS) {\n\t\t\t\tdraw(halo);\n\t\t\t\tm.lastDraw = now;\n\t\t\t\tm.dirty = false;\n\t\t\t}\n\n\t\t\tconst keepGoing = active || p.flicker || (p.idle === \"drift\" && !m.pointerOver);\n\t\t\tif (keepGoing && m.visible && typeof requestAnimationFrame === \"function\") {\n\t\t\t\tm.rafId = requestAnimationFrame(tick);\n\t\t\t}\n\t\t}\n\n\t\t/** Reduced motion: no loop — settle the field instantly and paint once. */\n\t\tfunction drawStatic(halo: Halo | null) {\n\t\t\tconst g = m.grid;\n\t\t\tif (!m.ctx || !g) return;\n\t\t\tupdateTiles(g, halo, 1, {\n\t\t\t\tpitch: m.pitchDev,\n\t\t\t\ttile: m.tileDev,\n\t\t\t\tattackTau: 0,\n\t\t\t\treleaseTau: 0,\n\t\t\t});\n\t\t\tm.haloFade = halo ? 1 : 0;\n\t\t\tif (halo) {\n\t\t\t\tm.sx = halo.x;\n\t\t\t\tm.sy = halo.y;\n\t\t\t}\n\t\t\tdraw(halo);\n\t\t}\n\n\t\tfunction draw(halo: Halo | null) {\n\t\t\tconst c = m.ctx;\n\t\t\tconst g = m.grid;\n\t\t\tif (!c || !g) return;\n\t\t\tconst p = live.current;\n\t\t\tconst table = ensureLut();\n\t\t\tconst { cols, rows, ambient: amb, heat } = g;\n\n\t\t\tc.globalCompositeOperation = \"source-over\";\n\t\t\tc.fillStyle = p.background;\n\t\t\tc.fillRect(0, 0, m.w, m.h);\n\n\t\t\tlet current = -1;\n\t\t\tfor (let r = 0; r < rows; r++) {\n\t\t\t\tconst y = r * m.pitchDev;\n\t\t\t\tfor (let col = 0; col < cols; col++) {\n\t\t\t\t\tconst i = r * cols + col;\n\t\t\t\t\tconst idx = lutIndex(amb[i]!, heat[i]!, p.intensityC, LUT_SIZE);\n\t\t\t\t\tif (idx !== current) {\n\t\t\t\t\t\tc.fillStyle = table[idx]!;\n\t\t\t\t\t\tcurrent = idx;\n\t\t\t\t\t}\n\t\t\t\t\tc.fillRect(col * m.pitchDev, y, m.tileDev, m.tileDev);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (m.glassLayer) {\n\t\t\t\tc.globalCompositeOperation = \"soft-light\";\n\t\t\t\tc.drawImage(m.glassLayer, 0, 0);\n\t\t\t}\n\n\t\t\tif (m.haloFade > 0) {\n\t\t\t\tconst rgb = parseRgb(p.color) ?? DEFAULT_COLOR;\n\t\t\t\tconst r = (halo ? halo.r : p.radiusC * m.dpr) * 1.15;\n\t\t\t\tconst a = p.intensityC * m.haloFade;\n\t\t\t\tconst grad = c.createRadialGradient(m.sx, m.sy, 0, m.sx, m.sy, r);\n\t\t\t\tgrad.addColorStop(0, `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${(0.2 * a).toFixed(3)})`);\n\t\t\t\tgrad.addColorStop(0.45, `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${(0.07 * a).toFixed(3)})`);\n\t\t\t\tgrad.addColorStop(1, `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, 0)`);\n\t\t\t\tc.globalCompositeOperation = \"lighter\";\n\t\t\t\tc.fillStyle = grad;\n\t\t\t\tc.fillRect(m.sx - r, m.sy - r, r * 2, r * 2);\n\t\t\t}\n\n\t\t\tc.globalCompositeOperation = \"source-over\";\n\n\t\t\tif (m.onFrame) {\n\t\t\t\ttry {\n\t\t\t\t\tm.onFrame({\n\t\t\t\t\t\theat: g.heat,\n\t\t\t\t\t\tcols,\n\t\t\t\t\t\trows,\n\t\t\t\t\t\tpitch: m.pitchDev,\n\t\t\t\t\t\ttile: m.tileDev,\n\t\t\t\t\t\twidth: m.w,\n\t\t\t\t\t\theight: m.h,\n\t\t\t\t\t\thalo: {\n\t\t\t\t\t\t\tx: m.sx,\n\t\t\t\t\t\t\ty: m.sy,\n\t\t\t\t\t\t\tr: (halo ? halo.r : p.radiusC * m.dpr) * 1.15,\n\t\t\t\t\t\t\tfade: m.haloFade,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tintensity: p.intensityC,\n\t\t\t\t\t\tcolor: p.color,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tm.onFrame = null;\n\t\t\t\t\tconsole.warn(\"[MosaicGlow] light layer disabled:\", error);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\truntimeRef.current = { resize, requestFrame, stopLoop, drawStatic, initialHalo };\n\t\tsetEngineReady(true);\n\n\t\tlet mq: MediaQueryList | undefined;\n\t\tlet onMq: ((e: MediaQueryListEvent) => void) | undefined;\n\t\tif (typeof window.matchMedia === \"function\") {\n\t\t\tmq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n\t\t\tm.reducedMotion = mq.matches;\n\t\t\tsetReducedMotion(mq.matches);\n\t\t\tonMq = (e) => {\n\t\t\t\tm.reducedMotion = e.matches;\n\t\t\t\tsetReducedMotion(e.matches);\n\t\t\t};\n\t\t\tmq.addEventListener(\"change\", onMq);\n\t\t}\n\n\t\tresize();\n\n\t\tlet ro: ResizeObserver | undefined;\n\t\tif (typeof ResizeObserver !== \"undefined\") {\n\t\t\tro = new ResizeObserver(() => {\n\t\t\t\t// Zoom and display moves can change the pixel ratio at a constant CSS size.\n\t\t\t\tif (\n\t\t\t\t\thostEl.clientWidth === m.cssW &&\n\t\t\t\t\thostEl.clientHeight === m.cssH &&\n\t\t\t\t\tcurrentDpr() === m.dpr\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\tresize();\n\t\t\t});\n\t\t\tro.observe(hostEl);\n\t\t}\n\n\t\tlet io: IntersectionObserver | undefined;\n\t\tif (typeof IntersectionObserver !== \"undefined\") {\n\t\t\tio = new IntersectionObserver(\n\t\t\t\t([entry]) => {\n\t\t\t\t\tif (!entry) return;\n\t\t\t\t\tm.visible = entry.isIntersecting;\n\t\t\t\t\tif (m.visible) requestFrame();\n\t\t\t\t\telse stopLoop();\n\t\t\t\t},\n\t\t\t\t{ rootMargin: \"128px\" }\n\t\t\t);\n\t\t\tio.observe(hostEl);\n\t\t}\n\n\t\treturn () => {\n\t\t\tstopLoop();\n\t\t\tro?.disconnect();\n\t\t\tio?.disconnect();\n\t\t\tif (mq && onMq) mq.removeEventListener(\"change\", onMq);\n\t\t\truntimeRef.current = null;\n\t\t\tsetEngineReady(false);\n\t\t\tm.ctx = null;\n\t\t\tm.grid = null;\n\t\t\tm.glassLayer = null;\n\t\t};\n\t}, [host, canvas, machine, live]);\n\n\t// --- reactivity ------------------------------------------------------------\n\n\t// Structural props rebuild the grid (heat resets — acceptable, it is structural).\n\t// The first run only records dependencies; the mount effect does the initial setup.\n\tconst structuralInit = useRef(false);\n\tuseEffect(() => {\n\t\tif (!structuralInit.current) {\n\t\t\tstructuralInit.current = true;\n\t\t\treturn;\n\t\t}\n\t\truntimeRef.current?.resize();\n\t}, [tileC, gapC, seed, noiseC, ambientC]);\n\n\tuseEffect(() => {\n\t\tmachine.lut = null;\n\t\tmachine.dirty = true;\n\t\tconst runtime = runtimeRef.current;\n\t\tif (!runtime) return;\n\t\tif (machine.reducedMotion)\n\t\t\truntime.drawStatic(\n\t\t\t\tmachine.haloFade > 0\n\t\t\t\t\t? { x: machine.sx, y: machine.sy, r: live.current.radiusC * machine.dpr }\n\t\t\t\t\t: null\n\t\t\t);\n\t\telse runtime.requestFrame();\n\t}, [color, background, machine, live]);\n\n\t// Loop- and paint-affecting props: restart a stopped loop, repaint a static frame.\n\tconst visualInit = useRef(false);\n\tuseEffect(() => {\n\t\tif (!visualInit.current) {\n\t\t\tvisualInit.current = true;\n\t\t\treturn;\n\t\t}\n\t\tconst runtime = runtimeRef.current;\n\t\tif (!runtime) return;\n\t\tmachine.dirty = true;\n\t\tif (machine.reducedMotion)\n\t\t\truntime.drawStatic(\n\t\t\t\tmachine.pointerOver\n\t\t\t\t\t? { x: machine.sx, y: machine.sy, r: radiusC * machine.dpr }\n\t\t\t\t\t: runtime.initialHalo()\n\t\t\t);\n\t\telse runtime.requestFrame();\n\t}, [idle, flicker, radiusC, intensityC, machine]);\n\n\tuseEffect(() => {\n\t\tconst runtime = runtimeRef.current;\n\t\tif (!runtime) return;\n\t\tif (reducedMotion) {\n\t\t\truntime.stopLoop();\n\t\t\truntime.drawStatic(runtime.initialHalo());\n\t\t} else {\n\t\t\truntime.requestFrame();\n\t\t}\n\t}, [reducedMotion]);\n\n\tuseEffect(() => {\n\t\tif (!host || !interactive) return;\n\t\tconst hostEl: HTMLDivElement = host;\n\t\tconst m = machine;\n\n\t\tconst move = (e: PointerEvent) => {\n\t\t\tconst rect = hostEl.getBoundingClientRect();\n\t\t\tm.px = (e.clientX - rect.left) * m.dpr;\n\t\t\tm.py = (e.clientY - rect.top) * m.dpr;\n\t\t\tm.pointerOver = true;\n\t\t\tconst runtime = runtimeRef.current;\n\t\t\tif (!runtime) return;\n\t\t\tif (m.reducedMotion)\n\t\t\t\truntime.drawStatic({ x: m.px, y: m.py, r: live.current.radiusC * m.dpr });\n\t\t\telse runtime.requestFrame();\n\t\t};\n\t\tconst leave = () => {\n\t\t\tm.pointerOver = false;\n\t\t\tm.lastLeaveAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n\t\t\tconst runtime = runtimeRef.current;\n\t\t\tif (!runtime) return;\n\t\t\tif (m.reducedMotion) runtime.drawStatic(runtime.initialHalo());\n\t\t\telse runtime.requestFrame();\n\t\t};\n\n\t\thostEl.addEventListener(\"pointermove\", move, { passive: true });\n\t\thostEl.addEventListener(\"pointerleave\", leave);\n\t\thostEl.addEventListener(\"pointercancel\", leave);\n\t\treturn () => {\n\t\t\thostEl.removeEventListener(\"pointermove\", move);\n\t\t\thostEl.removeEventListener(\"pointerleave\", leave);\n\t\t\thostEl.removeEventListener(\"pointercancel\", leave);\n\t\t\tm.pointerOver = false;\n\t\t};\n\t}, [host, interactive, machine, live]);\n\n\t// HDR light: async WebGPU start; resolves to null off HDR displays.\n\tuseEffect(() => {\n\t\tif (!hdrCanvas || !engineReady) return;\n\t\tconst m = machine;\n\t\tlet cancelled = false;\n\t\tlet stop: (() => void) | null = null;\n\t\tvoid startMosaicGlowHdr(hdrCanvas).then((light) => {\n\t\t\tconst runtime = runtimeRef.current;\n\t\t\tif (!light) return;\n\t\t\tif (cancelled || !runtime) {\n\t\t\t\tlight.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// A light layer attached to a settled or static mosaic needs one frame.\n\t\t\tconst repaint = () => {\n\t\t\t\tm.dirty = true;\n\t\t\t\tif (m.reducedMotion)\n\t\t\t\t\truntime.drawStatic(\n\t\t\t\t\t\tm.haloFade > 0 ? { x: m.sx, y: m.sy, r: live.current.radiusC * m.dpr } : null\n\t\t\t\t\t);\n\t\t\t\telse runtime.requestFrame();\n\t\t\t};\n\t\t\tm.onFrame = (frame) => light.render(frame);\n\t\t\trepaint();\n\t\t\tsetHdrOn(true);\n\t\t\tstop = () => {\n\t\t\t\tm.onFrame = null;\n\t\t\t\tlight.destroy();\n\t\t\t\trepaint();\n\t\t\t\tsetHdrOn(false);\n\t\t\t};\n\t\t});\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t\tstop?.();\n\t\t};\n\t}, [hdrCanvas, engineReady, machine, live]);\n\n\treturn (\n\t\t<div\n\t\t\tref={composedHostRef}\n\t\t\tclassName={cn(\"mosaic-glow relative overflow-hidden\", className)}\n\t\t\tstyle={{ ...style, backgroundColor: background }}\n\t\t\tdata-hdr={hdrOn ? \"\" : undefined}\n\t\t\t{...restProps}\n\t\t>\n\t\t\t<canvas\n\t\t\t\tref={canvasRef}\n\t\t\t\tclassName=\"pointer-events-none absolute inset-0 block h-full w-full\"\n\t\t\t\taria-hidden=\"true\"\n\t\t\t/>\n\t\t\t{hdr ? (\n\t\t\t\t<canvas\n\t\t\t\t\tref={hdrCanvasRef}\n\t\t\t\t\tclassName=\"mosaic-glow__hdr pointer-events-none absolute inset-0 block h-full w-full\"\n\t\t\t\t\taria-hidden=\"true\"\n\t\t\t\t/>\n\t\t\t) : null}\n\t\t\t{children != null ? (\n\t\t\t\t<div className=\"mosaic-glow__content relative z-[1] h-full w-full\">{children}</div>\n\t\t\t) : null}\n\t\t</div>\n\t);\n});\n","type":"registry:ui","target":"@ui/fancy/components/mosaic-glow/MosaicGlow.tsx"},{"path":"react/src/components/mosaic-glow/index.ts","content":"\"use client\";\n\nexport { MosaicGlow } from \"./MosaicGlow\";\nexport type { MosaicGlowProps, MosaicGlowIdle } from \"./MosaicGlow\";\n","type":"registry:ui","target":"@ui/fancy/components/mosaic-glow/index.ts"},{"path":"react/src/components/mosaic-glow/mosaic-glow-core.ts","content":"\"use client\";\n\n/**\n * MosaicGlow core — the framework-free half of the component.\n *\n * First the pure math, unit-testable without a browser: a seeded PRNG, per-tile\n * grid state, the halo falloff curve, the fps-independent heat step, ambient\n * flicker, the colour LUT and the idle drift path. Then `createMosaicGlow`, the\n * engine that owns the canvas, the rAF loop and the pointer listeners. No\n * framework imports, and nothing touches `window` or `document` at module scope,\n * so the file is safe to import on the server.\n *\n * Compiles under `noUncheckedIndexedAccess`, which widens every indexed read\n * to `| undefined`. The `!` assertions below are all in bounds by construction\n * (the loops are driven by the array's own length, the regex groups are\n * guaranteed by a successful match), so they change no behaviour.\n */\n\nexport type Rgb = [number, number, number];\n\n// --- randomness --------------------------------------------------------------\n\n/** Small, fast, seedable PRNG (32-bit state). Same seed → same sequence. */\nexport function mulberry32(seed: number): () => number {\n\tlet a = seed >>> 0;\n\treturn () => {\n\t\ta = (a + 0x6d2b79f5) >>> 0;\n\t\tlet t = a;\n\t\tt = Math.imul(t ^ (t >>> 15), t | 1);\n\t\tt ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n\t\treturn ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n\t};\n}\n\n/** Mix three integers into one uint32 (order-sensitive). */\nfunction hash3(seed: number, a: number, b: number, salt: number): number {\n\tlet h = (seed >>> 0) ^ 0x9e3779b9;\n\th = Math.imul(h ^ (a + 0x7f4a7c15), 0x85ebca6b);\n\th ^= h >>> 13;\n\th = Math.imul(h ^ (b + 0x165667b1), 0xc2b2ae35);\n\th ^= h >>> 16;\n\th = Math.imul(h ^ (salt + 0x27d4eb2f), 0x9e3779b1);\n\th ^= h >>> 15;\n\treturn h >>> 0;\n}\n\n/**\n * Deterministic random in [0, 1) for a tile, keyed by its (col, row) coordinates\n * rather than its linear index so a resize never reshuffles the field.\n */\nexport function tileRandom(seed: number, col: number, row: number, salt: number): number {\n\treturn mulberry32(hash3(seed, col, row, salt))();\n}\n\n// --- grid --------------------------------------------------------------------\n\nexport interface MosaicGrid {\n\tcols: number;\n\trows: number;\n\t/** Per-tile peak response to the halo, in [1 - noise, 1]. */\n\tweight: Float32Array;\n\t/** Current ambient level (LUT space, 0..ambient). */\n\tambient: Float32Array;\n\t/** Flicker eases `ambient` toward this. */\n\tambientTarget: Float32Array;\n\t/** Lit level driven by the halo, 0..1. */\n\theat: Float32Array;\n}\n\n/** Brightest resting tile at `ambient = 1`, in LUT space (keeps them well under the halo colour). */\nexport const AMBIENT_CEILING = 0.4;\n\n/** Cubic skew so most tiles sit near black and only a few read as \"on\". */\nexport function ambientLevel(u: number, ambient: number): number {\n\treturn u * u * u * ambient * AMBIENT_CEILING;\n}\n\nexport function createGrid(\n\tcols: number,\n\trows: number,\n\tseed: number,\n\tnoise: number,\n\tambient: number\n): MosaicGrid {\n\tconst n = Math.max(0, cols * rows);\n\tconst weight = new Float32Array(n);\n\tconst amb = new Float32Array(n);\n\tconst ambientTarget = new Float32Array(n);\n\tconst heat = new Float32Array(n);\n\tfor (let r = 0; r < rows; r++) {\n\t\tfor (let c = 0; c < cols; c++) {\n\t\t\tconst i = r * cols + c;\n\t\t\tweight[i] = 1 - noise * tileRandom(seed, c, r, 1);\n\t\t\tconst a = ambientLevel(tileRandom(seed, c, r, 2), ambient);\n\t\t\tamb[i] = a;\n\t\t\tambientTarget[i] = a;\n\t\t}\n\t}\n\treturn { cols, rows, weight, ambient: amb, ambientTarget, heat };\n}\n\n// --- halo --------------------------------------------------------------------\n\n/**\n * 1 - smoothstep(d): exactly 1 at the centre, exactly 0 at the rim, zero slope\n * at both ends so there is never a visible hard ring.\n */\nexport function falloff(d: number): number {\n\tif (d <= 0) return 1;\n\tif (d >= 1) return 0;\n\tconst s = 1 - d;\n\treturn s * s * (1 + 2 * d);\n}\n\n/** Fraction of the remaining distance to cover after `dt` seconds (exponential approach). */\nexport function rate(dt: number, tau: number): number {\n\tif (tau <= 0) return 1;\n\tif (dt <= 0) return 0;\n\treturn 1 - Math.exp(-dt / tau);\n}\n\nexport interface Halo {\n\t/** Centre, in the same units as tile positions (device px). */\n\tx: number;\n\ty: number;\n\t/** Radius, same units. */\n\tr: number;\n}\n\nexport interface StepParams {\n\t/** Distance between tile origins (device px). */\n\tpitch: number;\n\t/** Tile edge length (device px). */\n\ttile: number;\n\tattackTau: number;\n\treleaseTau: number;\n}\n\n/** Seconds to reach ~63% of the target when lighting up (≈0.34/frame at 60fps). */\nexport const ATTACK_TAU = 0.04;\n\n/**\n * Advance every tile's heat toward its target for this frame.\n * Returns the largest remaining |target - heat| so the caller can stop the loop\n * once the field has settled.\n */\nexport function updateTiles(g: MosaicGrid, halo: Halo | null, dt: number, p: StepParams): number {\n\tconst { cols, rows, weight, heat } = g;\n\tconst kAttack = rate(dt, p.attackTau);\n\tconst kRelease = rate(dt, p.releaseTau);\n\tconst half = p.tile / 2;\n\tlet maxDelta = 0;\n\n\tif (!halo || halo.r <= 0) {\n\t\tfor (let i = 0; i < heat.length; i++) {\n\t\t\tconst h = heat[i]!;\n\t\t\tif (h === 0) continue;\n\t\t\tconst next = h - h * kRelease;\n\t\t\theat[i] = next < 1e-4 ? 0 : next;\n\t\t\tif (next > maxDelta) maxDelta = next;\n\t\t}\n\t\treturn maxDelta;\n\t}\n\n\tconst invR2 = 1 / (halo.r * halo.r);\n\tfor (let r = 0; r < rows; r++) {\n\t\tconst dy = r * p.pitch + half - halo.y;\n\t\tconst dy2 = dy * dy;\n\t\tfor (let c = 0; c < cols; c++) {\n\t\t\tconst i = r * cols + c;\n\t\t\tconst dx = c * p.pitch + half - halo.x;\n\t\t\tconst d2 = (dx * dx + dy2) * invR2;\n\t\t\tconst target = d2 >= 1 ? 0 : falloff(Math.sqrt(d2)) * weight[i]!;\n\t\t\tconst h = heat[i]!;\n\t\t\tconst delta = target - h;\n\t\t\tif (delta === 0) continue;\n\t\t\tconst next = h + delta * (delta > 0 ? kAttack : kRelease);\n\t\t\theat[i] = next < 1e-4 ? 0 : next;\n\t\t\tconst rem = Math.abs(target - heat[i]!);\n\t\t\tif (rem > maxDelta) maxDelta = rem;\n\t\t}\n\t}\n\treturn maxDelta;\n}\n\n/** Slow ambient life: occasionally retarget a tile, then ease toward the target. */\nexport function flickerTiles(\n\tg: MosaicGrid,\n\tdt: number,\n\tchancePerSec: number,\n\tambient: number,\n\trng: () => number = Math.random\n): void {\n\tconst { ambient: amb, ambientTarget } = g;\n\tconst p = chancePerSec * dt;\n\tconst k = rate(dt, 0.4);\n\tfor (let i = 0; i < amb.length; i++) {\n\t\tif (rng() < p) ambientTarget[i] = ambientLevel(rng(), ambient);\n\t\tamb[i] = amb[i]! + (ambientTarget[i]! - amb[i]!) * k;\n\t}\n}\n\n// --- colour ------------------------------------------------------------------\n\n/** Parse `#rgb`, `#rrggbb` or `rgb(r, g, b)`. Returns null on anything else. */\nexport function parseRgb(input: string): Rgb | null {\n\tconst s = input.trim();\n\tconst hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(s);\n\tif (hex) {\n\t\tlet h = hex[1]!;\n\t\tif (h.length === 3) h = h[0]! + h[0]! + h[1]! + h[1]! + h[2]! + h[2]!;\n\t\tconst n = Number.parseInt(h, 16);\n\t\treturn [(n >> 16) & 255, (n >> 8) & 255, n & 255];\n\t}\n\tconst rgb = /^rgba?\\(\\s*(\\d{1,3})\\s*[, ]\\s*(\\d{1,3})\\s*[, ]\\s*(\\d{1,3})/i.exec(s);\n\tif (rgb) {\n\t\treturn [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])].map((v) => Math.min(255, v)) as Rgb;\n\t}\n\treturn null;\n}\n\nexport function mix(a: Rgb, b: Rgb, t: number): Rgb {\n\tconst u = t < 0 ? 0 : t > 1 ? 1 : t;\n\treturn [\n\t\tMath.round(a[0] + (b[0] - a[0]) * u),\n\t\tMath.round(a[1] + (b[1] - a[1]) * u),\n\t\tMath.round(a[2] + (b[2] - a[2]) * u),\n\t];\n}\n\nexport const DEFAULT_COLOR: Rgb = [242, 195, 24];\nexport const DEFAULT_BACKGROUND: Rgb = [10, 10, 10];\n\n/** Level at which the ramp reaches the pure halo colour; above it heads to the peak. */\nexport const LUT_KNEE = 0.55;\n\nfunction rgbString(c: Rgb): string {\n\treturn `rgb(${c[0]}, ${c[1]}, ${c[2]})`;\n}\n\n/**\n * Build the tile colour ramp: a hair above the background at 0, the halo colour\n * at the knee, a near-white tint of the halo colour at 1.\n */\nexport function buildLut(background: string, color: string, size = 64): string[] {\n\tconst bg = parseRgb(background) ?? DEFAULT_BACKGROUND;\n\tconst fg = parseRgb(color) ?? DEFAULT_COLOR;\n\tconst tileBase = mix(bg, fg, 0.05);\n\tconst peak = mix(fg, [255, 255, 255], 0.7);\n\tconst out = new Array<string>(size);\n\tfor (let i = 0; i < size; i++) {\n\t\tconst t = size > 1 ? i / (size - 1) : 0;\n\t\tconst c =\n\t\t\tt <= LUT_KNEE\n\t\t\t\t? mix(tileBase, fg, t / LUT_KNEE)\n\t\t\t\t: mix(fg, peak, (t - LUT_KNEE) / (1 - LUT_KNEE));\n\t\tout[i] = rgbString(c);\n\t}\n\treturn out;\n}\n\nexport function lutIndex(ambient: number, heat: number, intensity: number, size: number): number {\n\tlet level = ambient + heat * intensity;\n\tif (level > 1) level = 1;\n\telse if (level < 0) level = 0;\n\treturn (level * (size - 1)) | 0;\n}\n\n// --- idle drift + prop mapping -----------------------------------------------\n\nconst TWO_PI = Math.PI * 2;\n\n/** Slow Lissajous wander that stays inside the box (periods 9s / 13s). */\nexport function driftPoint(t: number, w: number, h: number): { x: number; y: number } {\n\treturn {\n\t\tx: w * (0.5 + 0.38 * Math.sin((TWO_PI * t) / 9 + 1.3)),\n\t\ty: h * (0.5 + 0.32 * Math.sin((TWO_PI * t) / 13)),\n\t};\n}\n\n/** `trail` 0..1 → release time constant in seconds. */\nexport function releaseTau(trail: number): number {\n\treturn 0.05 + 0.7 * clamp01(trail);\n}\n\n/** `smoothing` 0..1 → pointer lag time constant in seconds (0 = instant). */\nexport function smoothingTau(smoothing: number): number {\n\treturn 0.8 * clamp01(smoothing);\n}\n\nexport function clamp01(v: number): number {\n\tif (!Number.isFinite(v)) return 0;\n\treturn v < 0 ? 0 : v > 1 ? 1 : v;\n}\n\n// --- engine ------------------------------------------------------------------\n//\n// The browser half of the effect: canvas contexts, the rAF loop, the cached\n// glass layer and the pointer listeners. Framework-free on purpose — a wrapper\n// owns markup, a11y, the reduced-motion query and the observers, and feeds this\n// engine through `setOptions` / `resize` / `destroy`.\n\n/** What the halo does with no pointer: wander on its own or switch off. */\nexport type MosaicGlowIdle = \"drift\" | \"none\";\n\n/** Wait after the pointer leaves before the idle drift takes over (ms). */\nexport const IDLE_DELAY_MS = 1500;\n/** Ambient-only frames are drawn at most this often (ms). */\nexport const AMBIENT_FRAME_MS = 50;\n/** Chance per second that a tile re-rolls its resting level. */\nexport const FLICKER_CHANCE = 0.15;\n/** Steps in the tile colour ramp. */\nexport const LUT_SIZE = 64;\n\n/** `tileSize` → tile edge in CSS px. */\nexport function normalizeTileSize(v: number): number {\n\treturn Math.max(1, Number.isFinite(v) ? v : 18);\n}\n\n/** `gap` → gap between tiles in CSS px. */\nexport function normalizeGap(v: number): number {\n\treturn Math.max(0, Number.isFinite(v) ? v : 2);\n}\n\n/** `radius` → halo radius in CSS px. */\nexport function normalizeRadius(v: number): number {\n\treturn Math.max(1, Number.isFinite(v) ? v : 170);\n}\n\nexport interface MosaicGlowElements {\n\t/** Positioned host: measured for the backing store, and the pointer surface. */\n\thost: HTMLElement;\n\t/** Canvas the mosaic is painted on. The engine owns its width/height. */\n\tcanvas: HTMLCanvasElement;\n}\n\n/**\n * Mount-only options. MosaicGlow has none — every prop the wrapper passes is\n * reacted to after mount — so the split is recorded here as \"nothing is frozen\".\n */\nexport type MosaicGlowInitOptions = Record<never, never>;\n\n/**\n * Options the engine reacts to after mount. `setOptions` acts on the keys that\n * are present (an absent or `undefined` key is left alone), grouped by concern\n * exactly as the wrapper's effects are:\n * structural (`tileSize`, `gap`, `seed`, `noise`, `ambient`) rebuilds the grid,\n * colour (`color`, `background`) drops the ramp cache, visual (`idle`,\n * `flicker`, `radius`, `intensity`) repaints, `reducedMotion` swaps the loop for\n * a single static frame, `interactive` attaches or detaches the pointer\n * listeners, `visible` pauses and resumes the loop. `trail` and `smoothing` are\n * read by the next frame and schedule nothing.\n */\nexport interface MosaicGlowLiveOptions {\n\t/** Tile edge in CSS px. */\n\ttileSize?: number;\n\t/** Gap between tiles in CSS px. */\n\tgap?: number;\n\t/** Halo / tile colour — hex or rgb(). */\n\tcolor?: string;\n\t/** Surface colour behind the tiles — hex or rgb(). */\n\tbackground?: string;\n\t/** Halo radius in CSS px. */\n\tradius?: number;\n\t/** Overall brightness of lit tiles, 0–1. */\n\tintensity?: number;\n\t/** How long lit tiles linger after the halo moves on, 0–1. */\n\ttrail?: number;\n\t/** Pointer lag, 0 (instant) to 1 (very laggy). */\n\tsmoothing?: number;\n\t/** Spread of per-tile random brightness inside the halo, 0–1. */\n\tnoise?: number;\n\t/** Visibility of the random faint tiles outside the halo, 0–1. */\n\tambient?: number;\n\t/** Slowly re-roll the faint tiles over time. */\n\tflicker?: boolean;\n\t/** What the halo does with no pointer. */\n\tidle?: MosaicGlowIdle;\n\t/** Follow the pointer. Off leaves only the idle behaviour. */\n\tinteractive?: boolean;\n\t/** Seed for the per-tile randomness — same seed, same mosaic. */\n\tseed?: number;\n\t/** The wrapper's `prefers-reduced-motion` gate: no loop, one settled frame. */\n\treducedMotion?: boolean;\n\t/** The wrapper's visibility gate: false parks the loop. */\n\tvisible?: boolean;\n\t/**\n\t * Called after every painted frame with the light field, for a renderer\n\t * that adds light on top (the HDR layer). `null` removes it. A callback\n\t * that throws is dropped; it never stops the mosaic.\n\t */\n\tonFrame?: ((frame: MosaicGlowFrame) => void) | null;\n}\n\n/** What one painted frame looked like, in device px (the canvas backing store). */\nexport interface MosaicGlowFrame {\n\t/** Per-tile lit level 0..1, row-major; live view, read it synchronously. */\n\theat: Float32Array;\n\tcols: number;\n\trows: number;\n\t/** Distance between tile origins and tile edge. */\n\tpitch: number;\n\ttile: number;\n\t/** Backing-store size. */\n\twidth: number;\n\theight: number;\n\t/** Smoothed halo centre and radius; `fade` 0..1 (0 = no halo). */\n\thalo: { x: number; y: number; r: number; fade: number };\n\t/** 0..1, as passed. */\n\tintensity: number;\n\t/** Tile / halo colour, as passed. */\n\tcolor: string;\n}\n\nexport interface MosaicGlowEngine {\n\tsetOptions(next: Partial<MosaicGlowLiveOptions>): void;\n\t/** Re-measure the host; rebuilds only when the box or the pixel ratio moved. */\n\tresize(): void;\n\tdestroy(): void;\n}\n\n/**\n * Drive a MosaicGlow canvas. Returns null when no 2D context is available\n * (server, jsdom without a stub, a browser that refuses the context) — the\n * caller then simply renders an inert canvas.\n *\n * `random` feeds the ambient flicker only; the per-tile field is seeded through\n * the `seed` option and stays deterministic.\n */\nexport function createMosaicGlow(\n\tel: MosaicGlowElements,\n\toptions: MosaicGlowInitOptions & MosaicGlowLiveOptions = {},\n\trandom: () => number = Math.random\n): MosaicGlowEngine | null {\n\tconst host = el.host;\n\tconst canvas = el.canvas;\n\tif (!host || !canvas) return null;\n\tlet ctx: CanvasRenderingContext2D | null = canvas.getContext(\"2d\");\n\tif (!ctx) return null;\n\n\t// --- options ---------------------------------------------------------------\n\n\tlet tile = normalizeTileSize(options.tileSize ?? 18);\n\tlet gap = normalizeGap(options.gap ?? 2);\n\tlet color = options.color ?? \"#f2c318\";\n\tlet background = options.background ?? \"#0a0a0a\";\n\tlet radius = normalizeRadius(options.radius ?? 170);\n\tlet intensity = clamp01(options.intensity ?? 1);\n\tlet trail = clamp01(options.trail ?? 0.6);\n\tlet smoothing = clamp01(options.smoothing ?? 0.15);\n\tlet noise = clamp01(options.noise ?? 0.7);\n\tlet ambient = clamp01(options.ambient ?? 0.35);\n\tlet flicker = options.flicker ?? true;\n\tlet idle: MosaicGlowIdle = options.idle ?? \"drift\";\n\tlet interactive = options.interactive ?? true;\n\tlet seed = options.seed ?? 1;\n\tlet reducedMotion = options.reducedMotion ?? false;\n\tlet visible = options.visible ?? true;\n\tlet onFrame: ((frame: MosaicGlowFrame) => void) | null = options.onFrame ?? null;\n\n\t// --- frame state (touched every frame, never rendered) ---------------------\n\n\tlet glassLayer: HTMLCanvasElement | null = null;\n\tlet grid: MosaicGrid | null = null;\n\tlet lut: string[] | null = null;\n\tlet dpr = 1;\n\tlet cssW = 0;\n\tlet cssH = 0;\n\tlet w = 0;\n\tlet h = 0;\n\tlet pitchDev = 20;\n\tlet tileDev = 18;\n\n\tlet px = 0;\n\tlet py = 0;\n\tlet pointerOver = false;\n\tlet sx = 0;\n\tlet sy = 0;\n\tlet sInit = false;\n\tlet haloFade = 0;\n\tlet driftT = 0;\n\tlet lastLeaveAt = -1;\n\n\tlet rafId: number | null = null;\n\tlet lastTime = 0;\n\tlet lastDraw = 0;\n\t/** Something structural changed (size, grid, colours): the next frame must paint. */\n\tlet dirty = true;\n\tlet destroyed = false;\n\tlet pointerAttached = false;\n\n\t// --- setup -----------------------------------------------------------------\n\n\t/** Backing-store scale, capped so dense displays do not blow up the fill rate. */\n\tfunction currentDpr(): number {\n\t\treturn Math.min(typeof window !== \"undefined\" ? window.devicePixelRatio || 1 : 1, 2);\n\t}\n\n\t/** Unconditional rebuild: backing store, grid, glass layer, first paint. */\n\tfunction applyResize(): void {\n\t\tif (!ctx) return;\n\t\tcssW = host.clientWidth;\n\t\tcssH = host.clientHeight;\n\t\tdpr = currentDpr();\n\t\tw = Math.max(1, Math.round(cssW * dpr));\n\t\th = Math.max(1, Math.round(cssH * dpr));\n\t\tcanvas.width = w;\n\t\tcanvas.height = h;\n\t\ttileDev = Math.max(1, Math.round(tile * dpr));\n\t\tpitchDev = Math.max(tileDev, Math.round((tile + gap) * dpr));\n\t\tconst cols = Math.ceil(w / pitchDev);\n\t\tconst rows = Math.ceil(h / pitchDev);\n\t\tgrid = createGrid(cols, rows, seed, noise, ambient);\n\t\trebuildGlass(cols, rows);\n\t\tdirty = true;\n\t\tif (reducedMotion) drawStatic(initialHalo());\n\t\telse requestFrame();\n\t}\n\n\t/** One cached full-size layer with a glassy highlight stamped on every tile. */\n\tfunction rebuildGlass(cols: number, rows: number): void {\n\t\tglassLayer = null;\n\t\tif (typeof document === \"undefined\") return;\n\t\tconst sprite = document.createElement(\"canvas\");\n\t\tsprite.width = tileDev;\n\t\tsprite.height = tileDev;\n\t\tconst sctx = sprite.getContext(\"2d\");\n\t\tif (!sctx) return;\n\t\tconst grad = sctx.createRadialGradient(\n\t\t\ttileDev * 0.35,\n\t\t\ttileDev * 0.3,\n\t\t\t0,\n\t\t\ttileDev * 0.5,\n\t\t\ttileDev * 0.5,\n\t\t\ttileDev * 0.7\n\t\t);\n\t\tgrad.addColorStop(0, \"rgba(255, 255, 255, 0.22)\");\n\t\tgrad.addColorStop(1, \"rgba(255, 255, 255, 0)\");\n\t\tsctx.fillStyle = grad;\n\t\tsctx.fillRect(0, 0, tileDev, tileDev);\n\n\t\tconst layer = document.createElement(\"canvas\");\n\t\tlayer.width = w;\n\t\tlayer.height = h;\n\t\tconst lctx = layer.getContext(\"2d\");\n\t\tif (!lctx) return;\n\t\tfor (let r = 0; r < rows; r++) {\n\t\t\tfor (let c = 0; c < cols; c++) {\n\t\t\t\tlctx.drawImage(sprite, c * pitchDev, r * pitchDev);\n\t\t\t}\n\t\t}\n\t\tglassLayer = layer;\n\t}\n\n\tfunction ensureLut(): string[] {\n\t\tif (!lut) lut = buildLut(background, color, LUT_SIZE);\n\t\treturn lut;\n\t}\n\n\tfunction initialHalo(): Halo | null {\n\t\tif (idle !== \"drift\") return null;\n\t\tconst p = driftPoint(0, w, h);\n\t\treturn { x: p.x, y: p.y, r: radius * dpr };\n\t}\n\n\t// --- loop ------------------------------------------------------------------\n\n\tfunction requestFrame(): void {\n\t\tif (rafId !== null || !visible || reducedMotion || !ctx) return;\n\t\tif (typeof requestAnimationFrame !== \"function\") return;\n\t\tlastTime = 0;\n\t\trafId = requestAnimationFrame(tick);\n\t}\n\n\tfunction stopLoop(): void {\n\t\tif (rafId !== null && typeof cancelAnimationFrame === \"function\") cancelAnimationFrame(rafId);\n\t\trafId = null;\n\t}\n\n\tfunction tick(now: number): void {\n\t\trafId = null;\n\t\tif (!ctx || !grid) return;\n\n\t\tconst dt = lastTime === 0 ? 1 / 60 : Math.min(0.1, Math.max(0, (now - lastTime) / 1000));\n\t\tlastTime = now;\n\n\t\tconst drifting =\n\t\t\tidle === \"drift\" && !pointerOver && (lastLeaveAt < 0 || now - lastLeaveAt > IDLE_DELAY_MS);\n\t\tlet tx = 0;\n\t\tlet ty = 0;\n\t\tlet hasTarget = false;\n\t\tif (pointerOver) {\n\t\t\ttx = px;\n\t\t\tty = py;\n\t\t\thasTarget = true;\n\t\t} else if (drifting) {\n\t\t\tdriftT += dt;\n\t\t\tconst p = driftPoint(driftT, w, h);\n\t\t\ttx = p.x;\n\t\t\tty = p.y;\n\t\t\thasTarget = true;\n\t\t}\n\n\t\tif (hasTarget) {\n\t\t\tif (!sInit) {\n\t\t\t\tsx = tx;\n\t\t\t\tsy = ty;\n\t\t\t\tsInit = true;\n\t\t\t} else {\n\t\t\t\tconst tau = drifting ? Math.max(smoothingTau(smoothing), 0.35) : smoothingTau(smoothing);\n\t\t\t\tconst k = rate(dt, tau);\n\t\t\t\tsx += (tx - sx) * k;\n\t\t\t\tsy += (ty - sy) * k;\n\t\t\t}\n\t\t}\n\n\t\tconst rel = releaseTau(trail);\n\t\tconst fadeTarget = hasTarget ? 1 : 0;\n\t\thaloFade += (fadeTarget - haloFade) * rate(dt, fadeTarget > haloFade ? ATTACK_TAU : rel);\n\t\tif (haloFade < 0.005) haloFade = 0;\n\n\t\tconst halo: Halo | null = hasTarget ? { x: sx, y: sy, r: radius * dpr } : null;\n\t\tconst maxDelta = updateTiles(grid, halo, dt, {\n\t\t\tpitch: pitchDev,\n\t\t\ttile: tileDev,\n\t\t\tattackTau: ATTACK_TAU,\n\t\t\treleaseTau: rel,\n\t\t});\n\t\tif (flicker) flickerTiles(grid, dt, FLICKER_CHANCE, ambient, random);\n\n\t\tconst active = hasTarget || maxDelta > 0.002 || haloFade > 0;\n\t\tif (active || dirty || now - lastDraw >= AMBIENT_FRAME_MS) {\n\t\t\tdraw(halo);\n\t\t\tlastDraw = now;\n\t\t\tdirty = false;\n\t\t}\n\n\t\tconst keepGoing = active || flicker || (idle === \"drift\" && !pointerOver);\n\t\tif (keepGoing && visible && typeof requestAnimationFrame === \"function\") {\n\t\t\trafId = requestAnimationFrame(tick);\n\t\t}\n\t}\n\n\t/** Reduced motion: no loop — settle the field instantly and paint once. */\n\tfunction drawStatic(halo: Halo | null): void {\n\t\tif (!ctx || !grid) return;\n\t\tupdateTiles(grid, halo, 1, { pitch: pitchDev, tile: tileDev, attackTau: 0, releaseTau: 0 });\n\t\thaloFade = halo ? 1 : 0;\n\t\tif (halo) {\n\t\t\tsx = halo.x;\n\t\t\tsy = halo.y;\n\t\t}\n\t\tdraw(halo);\n\t}\n\n\tfunction draw(halo: Halo | null): void {\n\t\tconst c = ctx;\n\t\tconst g = grid;\n\t\tif (!c || !g) return;\n\t\tconst table = ensureLut();\n\t\tconst { cols, rows, ambient: amb, heat } = g;\n\n\t\tc.globalCompositeOperation = \"source-over\";\n\t\tc.fillStyle = background;\n\t\tc.fillRect(0, 0, w, h);\n\n\t\tlet current = -1;\n\t\tfor (let r = 0; r < rows; r++) {\n\t\t\tconst y = r * pitchDev;\n\t\t\tfor (let col = 0; col < cols; col++) {\n\t\t\t\tconst i = r * cols + col;\n\t\t\t\t// In bounds by construction: the loops are driven by the grid's own dimensions,\n\t\t\t\t// and `lutIndex` clamps into [0, size - 1].\n\t\t\t\tconst idx = lutIndex(amb[i]!, heat[i]!, intensity, LUT_SIZE);\n\t\t\t\tif (idx !== current) {\n\t\t\t\t\tc.fillStyle = table[idx]!;\n\t\t\t\t\tcurrent = idx;\n\t\t\t\t}\n\t\t\t\tc.fillRect(col * pitchDev, y, tileDev, tileDev);\n\t\t\t}\n\t\t}\n\n\t\tif (glassLayer) {\n\t\t\tc.globalCompositeOperation = \"soft-light\";\n\t\t\tc.drawImage(glassLayer, 0, 0);\n\t\t}\n\n\t\tif (haloFade > 0) {\n\t\t\tconst rgb = parseRgb(color) ?? DEFAULT_COLOR;\n\t\t\tconst r = (halo ? halo.r : radius * dpr) * 1.15;\n\t\t\tconst a = intensity * haloFade;\n\t\t\tconst grad = c.createRadialGradient(sx, sy, 0, sx, sy, r);\n\t\t\tgrad.addColorStop(0, `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${(0.2 * a).toFixed(3)})`);\n\t\t\tgrad.addColorStop(0.45, `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${(0.07 * a).toFixed(3)})`);\n\t\t\tgrad.addColorStop(1, `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, 0)`);\n\t\t\tc.globalCompositeOperation = \"lighter\";\n\t\t\tc.fillStyle = grad;\n\t\t\tc.fillRect(sx - r, sy - r, r * 2, r * 2);\n\t\t}\n\n\t\tc.globalCompositeOperation = \"source-over\";\n\n\t\tif (onFrame) {\n\t\t\ttry {\n\t\t\t\tonFrame({\n\t\t\t\t\theat: g.heat,\n\t\t\t\t\tcols,\n\t\t\t\t\trows,\n\t\t\t\t\tpitch: pitchDev,\n\t\t\t\t\ttile: tileDev,\n\t\t\t\t\twidth: w,\n\t\t\t\t\theight: h,\n\t\t\t\t\thalo: { x: sx, y: sy, r: (halo ? halo.r : radius * dpr) * 1.15, fade: haloFade },\n\t\t\t\t\tintensity,\n\t\t\t\t\tcolor,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tonFrame = null;\n\t\t\t\tconsole.warn(\"[MosaicGlow] light layer disabled:\", error);\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- pointer ---------------------------------------------------------------\n\n\tfunction onMove(e: PointerEvent): void {\n\t\tconst rect = host.getBoundingClientRect();\n\t\tpx = (e.clientX - rect.left) * dpr;\n\t\tpy = (e.clientY - rect.top) * dpr;\n\t\tpointerOver = true;\n\t\tif (reducedMotion) drawStatic({ x: px, y: py, r: radius * dpr });\n\t\telse requestFrame();\n\t}\n\n\tfunction onLeave(): void {\n\t\tpointerOver = false;\n\t\tlastLeaveAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n\t\tif (reducedMotion) drawStatic(initialHalo());\n\t\telse requestFrame();\n\t}\n\n\tfunction syncPointer(): void {\n\t\tconst want = interactive && !destroyed;\n\t\tif (want === pointerAttached) return;\n\t\tif (want) {\n\t\t\thost.addEventListener(\"pointermove\", onMove, { passive: true });\n\t\t\thost.addEventListener(\"pointerleave\", onLeave);\n\t\t\thost.addEventListener(\"pointercancel\", onLeave);\n\t\t} else {\n\t\t\thost.removeEventListener(\"pointermove\", onMove);\n\t\t\thost.removeEventListener(\"pointerleave\", onLeave);\n\t\t\thost.removeEventListener(\"pointercancel\", onLeave);\n\t\t\tpointerOver = false;\n\t\t}\n\t\tpointerAttached = want;\n\t}\n\n\t// --- public surface --------------------------------------------------------\n\n\tfunction setOptions(next: Partial<MosaicGlowLiveOptions>): void {\n\t\tif (destroyed) return;\n\t\tconst structural =\n\t\t\tnext.tileSize !== undefined ||\n\t\t\tnext.gap !== undefined ||\n\t\t\tnext.seed !== undefined ||\n\t\t\tnext.noise !== undefined ||\n\t\t\tnext.ambient !== undefined;\n\t\tconst colour = next.color !== undefined || next.background !== undefined;\n\t\tconst visual =\n\t\t\tnext.idle !== undefined ||\n\t\t\tnext.flicker !== undefined ||\n\t\t\tnext.radius !== undefined ||\n\t\t\tnext.intensity !== undefined;\n\t\tconst motion = next.reducedMotion !== undefined;\n\t\tconst pointer = next.interactive !== undefined;\n\t\tconst visibility = next.visible !== undefined;\n\t\tconst layer = \"onFrame\" in next;\n\t\tif (layer) onFrame = next.onFrame ?? null;\n\n\t\tif (next.tileSize !== undefined) tile = normalizeTileSize(next.tileSize);\n\t\tif (next.gap !== undefined) gap = normalizeGap(next.gap);\n\t\tif (next.seed !== undefined) seed = next.seed;\n\t\tif (next.noise !== undefined) noise = clamp01(next.noise);\n\t\tif (next.ambient !== undefined) ambient = clamp01(next.ambient);\n\t\tif (next.color !== undefined) color = next.color;\n\t\tif (next.background !== undefined) background = next.background;\n\t\tif (next.radius !== undefined) radius = normalizeRadius(next.radius);\n\t\tif (next.intensity !== undefined) intensity = clamp01(next.intensity);\n\t\tif (next.trail !== undefined) trail = clamp01(next.trail);\n\t\tif (next.smoothing !== undefined) smoothing = clamp01(next.smoothing);\n\t\tif (next.flicker !== undefined) flicker = next.flicker;\n\t\tif (next.idle !== undefined) idle = next.idle;\n\t\tif (next.interactive !== undefined) interactive = next.interactive;\n\t\tif (next.reducedMotion !== undefined) reducedMotion = next.reducedMotion;\n\t\tif (next.visible !== undefined) visible = next.visible;\n\n\t\tif (pointer) syncPointer();\n\n\t\t// Structural props rebuild the grid (heat resets — acceptable, it is structural).\n\t\tif (structural) applyResize();\n\n\t\tif (colour) {\n\t\t\tlut = null;\n\t\t\tdirty = true;\n\t\t\tif (reducedMotion) drawStatic(haloFade > 0 ? { x: sx, y: sy, r: radius * dpr } : null);\n\t\t\telse requestFrame();\n\t\t}\n\n\t\t// Loop- and paint-affecting props: restart a stopped loop, repaint a static frame.\n\t\tif (visual) {\n\t\t\tdirty = true;\n\t\t\tif (reducedMotion)\n\t\t\t\tdrawStatic(pointerOver ? { x: sx, y: sy, r: radius * dpr } : initialHalo());\n\t\t\telse requestFrame();\n\t\t}\n\n\t\tif (motion) {\n\t\t\tif (reducedMotion) {\n\t\t\t\tstopLoop();\n\t\t\t\tdrawStatic(initialHalo());\n\t\t\t} else {\n\t\t\t\trequestFrame();\n\t\t\t}\n\t\t}\n\n\t\tif (visibility) {\n\t\t\tif (visible) requestFrame();\n\t\t\telse stopLoop();\n\t\t}\n\n\t\t// A light layer attached to a settled or static mosaic needs one frame.\n\t\tif (layer) {\n\t\t\tdirty = true;\n\t\t\tif (reducedMotion) drawStatic(haloFade > 0 ? { x: sx, y: sy, r: radius * dpr } : null);\n\t\t\telse requestFrame();\n\t\t}\n\t}\n\n\tfunction resize(): void {\n\t\tif (destroyed || !ctx) return;\n\t\t// Zoom and display moves can change the pixel ratio at a constant CSS size.\n\t\tif (host.clientWidth === cssW && host.clientHeight === cssH && currentDpr() === dpr) return;\n\t\tapplyResize();\n\t}\n\n\tfunction destroy(): void {\n\t\tif (destroyed) return;\n\t\tdestroyed = true;\n\t\tstopLoop();\n\t\tsyncPointer();\n\t\tctx = null;\n\t\tgrid = null;\n\t\tglassLayer = null;\n\t\tlut = null;\n\t}\n\n\tapplyResize();\n\tsyncPointer();\n\n\treturn { setOptions, resize, destroy };\n}\n","type":"registry:ui","target":"@ui/fancy/components/mosaic-glow/mosaic-glow-core.ts"},{"path":"react/src/components/mosaic-glow/mosaic-glow-hdr.ts","content":"\"use client\";\n\n/**\n * MosaicGlow HDR light — framework-free, byte-identical in the Svelte, React\n * and Vue trees (see shared-cores.json).\n *\n * The mosaic itself is painted in a 2D canvas, which stops at SDR white. This\n * module lays a WebGPU canvas over it, configured with `rgba16float` +\n * `toneMapping: { mode: \"extended\" }`, and adds only the light ABOVE white:\n * hot tiles inside the halo climb toward {@link MOSAIC_GLOW_HDR_PEAK} (≈1000\n * nits against a 203-nit SDR reference white) and the halo gets a hot core.\n * Resting and ambient tiles get nothing, so the SDR picture is unchanged.\n *\n * It starts only when the browser keeps extended tone mapping AND the display\n * reports `(dynamic-range: high)`; otherwise `startMosaicGlowHdr` resolves to\n * null and the 2D mosaic runs alone. No browser global is touched at import.\n */\n\nimport { DEFAULT_COLOR, parseRgb, type MosaicGlowFrame } from \"./mosaic-glow-core\";\n\n/** SDR white ≈ 203 nits; 1000 nits / 203 ≈ 4.9. */\nexport const MOSAIC_GLOW_HDR_PEAK = 4.9;\n\nexport interface MosaicGlowHdr {\n\t/** Draws the light for one painted mosaic frame. */\n\trender(frame: MosaicGlowFrame): void;\n\tdestroy(): void;\n}\n\nconst FORMAT = \"rgba16float\" as GPUTextureFormat;\n\nconst WGSL = /* wgsl */ `\nstruct Frame {\n\tsize: vec2f,\n\tpitch: f32,\n\ttile: f32,\n\thalo: vec4f,     // x, y, r, fade\n\taccent: vec4f,   // linear rgb, peak\n\tgrid: vec4u,     // cols, rows, -, -\n};\n@group(0) @binding(0) var<uniform> frame: Frame;\n@group(0) @binding(1) var<storage, read> heat: array<f32>;\n\n@vertex\nfn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {\n\tlet p = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));\n\treturn vec4f(p[vi], 0.0, 1.0);\n}\n\n@fragment\nfn fs(@builtin(position) pos: vec4f) -> @location(0) vec4f {\n\tlet p = pos.xy;\n\tlet cell = floor(p / frame.pitch);\n\tlet local = p - cell * frame.pitch;\n\tvar h = 0.0;\n\tif (cell.x >= 0.0 && cell.y >= 0.0 && u32(cell.x) < frame.grid.x && u32(cell.y) < frame.grid.y\n\t\t&& local.x < frame.tile && local.y < frame.tile) {\n\t\th = heat[u32(cell.y) * frame.grid.x + u32(cell.x)];\n\t}\n\tlet peak = frame.accent.w;\n\t// Only the hottest tiles leave SDR: the excess above white ramps in late.\n\tlet hot = smoothstep(0.5, 1.0, h);\n\tlet tileLight = hot * (peak - 1.0);\n\tlet d = distance(p, frame.halo.xy);\n\tlet core = frame.halo.z * 0.22;\n\tlet haloLight = frame.halo.w * 0.9 * exp(-(d * d) / max(core * core, 1.0));\n\tlet v = tileLight + haloLight;\n\tlet colour = mix(frame.accent.rgb, vec3f(1.0), 0.25 * hot);\n\treturn vec4f(colour * v, clamp(v * 0.05, 0.0, 1.0));\n}\n`;\n\nfunction srgbToLinear(c: number): number {\n\tconst s = c / 255;\n\treturn s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);\n}\n\nexport async function startMosaicGlowHdr(canvas: HTMLCanvasElement): Promise<MosaicGlowHdr | null> {\n\ttry {\n\t\tif (typeof navigator === \"undefined\" || typeof window === \"undefined\") return null;\n\t\tconst hdrDisplay =\n\t\t\ttypeof window.matchMedia === \"function\" && window.matchMedia(\"(dynamic-range: high)\").matches;\n\t\tif (!hdrDisplay) return null;\n\t\tconst gpu = (navigator as Navigator & { gpu?: GPU }).gpu;\n\t\tif (!gpu) return null;\n\t\tconst adapter = await gpu.requestAdapter();\n\t\tif (!adapter) return null;\n\t\tconst device = await adapter.requestDevice();\n\t\tconst context = canvas.getContext(\"webgpu\");\n\t\tif (!context) {\n\t\t\tdevice.destroy();\n\t\t\treturn null;\n\t\t}\n\t\tcontext.configure({\n\t\t\tdevice,\n\t\t\tformat: FORMAT,\n\t\t\talphaMode: \"premultiplied\",\n\t\t\tcolorSpace: \"display-p3\",\n\t\t\ttoneMapping: { mode: \"extended\" },\n\t\t} as GPUCanvasConfiguration);\n\t\tlet extended = false;\n\t\ttry {\n\t\t\tconst applied = context.getConfiguration?.() as\n\t\t\t\t| (GPUCanvasConfiguration & { toneMapping?: { mode?: string } })\n\t\t\t\t| null;\n\t\t\textended = applied?.toneMapping?.mode === \"extended\";\n\t\t} catch {\n\t\t\textended = false;\n\t\t}\n\t\tif (!extended) {\n\t\t\tcontext.unconfigure();\n\t\t\tdevice.destroy();\n\t\t\treturn null;\n\t\t}\n\n\t\tconst module = device.createShaderModule({ code: WGSL });\n\t\tconst pipeline = device.createRenderPipeline({\n\t\t\tlayout: \"auto\",\n\t\t\tvertex: { module, entryPoint: \"vs\" },\n\t\t\tfragment: {\n\t\t\t\tmodule,\n\t\t\t\tentryPoint: \"fs\",\n\t\t\t\ttargets: [\n\t\t\t\t\t{\n\t\t\t\t\t\tformat: FORMAT,\n\t\t\t\t\t\tblend: {\n\t\t\t\t\t\t\tcolor: { srcFactor: \"one\", dstFactor: \"one\", operation: \"add\" },\n\t\t\t\t\t\t\talpha: { srcFactor: \"one\", dstFactor: \"one\", operation: \"add\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\tprimitive: { topology: \"triangle-list\" },\n\t\t});\n\t\tconst uniform = device.createBuffer({\n\t\t\tsize: 64,\n\t\t\tusage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n\t\t});\n\t\tconst uniformData = new ArrayBuffer(64);\n\t\tconst f32 = new Float32Array(uniformData);\n\t\tconst u32 = new Uint32Array(uniformData);\n\n\t\tlet heatBuffer: GPUBuffer | null = null;\n\t\tlet heatCapacity = 0;\n\t\tlet scaled = new Float32Array(0);\n\t\tlet bindGroup: GPUBindGroup | null = null;\n\t\tlet colourKey = \"\";\n\t\tlet accent: [number, number, number] = [1, 0.6, 0.1];\n\t\tlet destroyed = false;\n\n\t\tfunction ensureHeat(count: number): void {\n\t\t\tif (heatBuffer && count <= heatCapacity) return;\n\t\t\theatBuffer?.destroy();\n\t\t\theatCapacity = Math.max(count, 64);\n\t\t\theatBuffer = device.createBuffer({\n\t\t\t\tsize: heatCapacity * 4,\n\t\t\t\tusage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,\n\t\t\t});\n\t\t\tscaled = new Float32Array(heatCapacity);\n\t\t\tbindGroup = device.createBindGroup({\n\t\t\t\tlayout: pipeline.getBindGroupLayout(0),\n\t\t\t\tentries: [\n\t\t\t\t\t{ binding: 0, resource: { buffer: uniform } },\n\t\t\t\t\t{ binding: 1, resource: { buffer: heatBuffer } },\n\t\t\t\t],\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\trender(frame) {\n\t\t\t\tif (destroyed || frame.width <= 0 || frame.height <= 0) return;\n\t\t\t\tif (canvas.width !== frame.width) canvas.width = frame.width;\n\t\t\t\tif (canvas.height !== frame.height) canvas.height = frame.height;\n\t\t\t\tif (frame.color !== colourKey) {\n\t\t\t\t\tcolourKey = frame.color;\n\t\t\t\t\tconst rgb = parseRgb(frame.color) ?? DEFAULT_COLOR;\n\t\t\t\t\taccent = [srgbToLinear(rgb[0]), srgbToLinear(rgb[1]), srgbToLinear(rgb[2])];\n\t\t\t\t}\n\t\t\t\tconst count = frame.cols * frame.rows;\n\t\t\t\tensureHeat(count);\n\t\t\t\tfor (let i = 0; i < count; i++) scaled[i] = (frame.heat[i] ?? 0) * frame.intensity;\n\n\t\t\t\tf32[0] = frame.width;\n\t\t\t\tf32[1] = frame.height;\n\t\t\t\tf32[2] = frame.pitch;\n\t\t\t\tf32[3] = frame.tile;\n\t\t\t\tf32[4] = frame.halo.x;\n\t\t\t\tf32[5] = frame.halo.y;\n\t\t\t\tf32[6] = frame.halo.r;\n\t\t\t\tf32[7] = frame.halo.fade * frame.intensity;\n\t\t\t\tf32[8] = accent[0];\n\t\t\t\tf32[9] = accent[1];\n\t\t\t\tf32[10] = accent[2];\n\t\t\t\tf32[11] = MOSAIC_GLOW_HDR_PEAK;\n\t\t\t\tu32[12] = frame.cols;\n\t\t\t\tu32[13] = frame.rows;\n\t\t\t\tdevice.queue.writeBuffer(uniform, 0, uniformData);\n\t\t\t\tif (heatBuffer && count) device.queue.writeBuffer(heatBuffer, 0, scaled, 0, count);\n\n\t\t\t\tconst encoder = device.createCommandEncoder();\n\t\t\t\tconst pass = encoder.beginRenderPass({\n\t\t\t\t\tcolorAttachments: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tview: context.getCurrentTexture().createView(),\n\t\t\t\t\t\t\tclearValue: { r: 0, g: 0, b: 0, a: 0 },\n\t\t\t\t\t\t\tloadOp: \"clear\",\n\t\t\t\t\t\t\tstoreOp: \"store\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t\tif (bindGroup && count) {\n\t\t\t\t\tpass.setPipeline(pipeline);\n\t\t\t\t\tpass.setBindGroup(0, bindGroup);\n\t\t\t\t\tpass.draw(3);\n\t\t\t\t}\n\t\t\t\tpass.end();\n\t\t\t\tdevice.queue.submit([encoder.finish()]);\n\t\t\t},\n\t\t\tdestroy() {\n\t\t\t\tdestroyed = true;\n\t\t\t\ttry {\n\t\t\t\t\tcontext.unconfigure();\n\t\t\t\t} catch {\n\t\t\t\t\t// already gone\n\t\t\t\t}\n\t\t\t\theatBuffer?.destroy();\n\t\t\t\tdevice.destroy();\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n","type":"registry:ui","target":"@ui/fancy/components/mosaic-glow/mosaic-glow-hdr.ts"}],"meta":{"license":"MIT","package":"fancy-ui-react","version":"0.7.0","source":"https://fancy-ui.rama.app/docs/components/mosaic-glow?framework=react"}}