{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"afterglow","type":"registry:component","title":"Afterglow","description":"Light runs through a card the moment something works: it rises from the button you pressed, the old content dissolves into the new behind it, and what changed catches the light.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/afterglow.tsx","type":"registry:component","content":"// Hairline UI · afterglow · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { createAfterglowRenderer, type AfterglowRenderer, type RGB } from \"./afterglow-gl\";\n\n/* ─────────────────────────────────────────────────────────\n * AFTERGLOW: light runs through an element when something worked\n *\n *   rise     the light comes out of the control you pressed and\n *            spreads across the element: a horizon rising\n *            through a card, a streak along a pill, a ring\n *            from the middle of a round tile\n *   change   your update runs at once, under an exact copy of\n *            the old content; the light dissolves that copy\n *            grain by grain just behind its bright line, so each\n *            old line turns into the new one in its own place as\n *            the light passes, and what didn't change never moves\n *   glint    as the content clears, only the text that changed\n *            catches the light, rippling out from your press\n *   afterglow  the edge keeps an iridescent glow a moment,\n *            the far side last, and fades\n *\n * One call: ref.play(update). The app keeps its own state, its\n * own buttons and its own API.\n *\n * Reduced motion: the update runs at once, with no light.\n * ───────────────────────────────────────────────────────── */\n\nexport type AfterglowOrigin = \"press\" | \"center\" | \"top\" | \"bottom\" | \"left\" | \"right\" | { x: number; y: number };\n\nexport interface AfterglowHandle {\n  /**\n   * Runs the light. `update` is called once, straight away, under a copy of the old content\n   * that the light then dissolves: set your new state there and it appears where the light passes.\n   * Resolves when the light has gone.\n   */\n  play: (update?: () => void, options?: { origin?: AfterglowOrigin }) => Promise<void>;\n}\n\nexport interface AfterglowProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  /** One element: a card, a pill, a tile, a row. The light takes its shape and corner radius. */\n  children: React.ReactNode;\n  ref?: React.Ref<AfterglowHandle>;\n  /** Where the light starts. \"press\" is the control last pressed inside, else the focused one, else the bottom edge. */\n  origin?: AfterglowOrigin;\n  /** Warm light ahead of the front, the fringe, the clear light behind it. Any CSS colours. */\n  colors?: readonly [string, string, string];\n  /** Let the text that changed catch the light as the content clears. */\n  glint?: boolean;\n  /** Called when the light has gone. */\n  onFinish?: () => void;\n}\n\nconst FRONT = 1100;\nconst TOTAL = 2000;\nconst PEAK_BLUR = 4;\nconst BLUR_IN = 240;\nconst BLUR_OUT = 700;\n/** The dissolve runs this far behind the bright line, and takes this much of the band to finish (both × band). */\nconst LAG = 0.22;\nconst DEPTH = 0.6;\nconst GLINT = 820;\nconst PRESS_MEMORY = 15000;\nconst DEFAULT_COLORS = [\"#ffb347\", \"#ff4f8b\", \"#3d8bff\"] as const;\nconst PRESSABLE = 'button, a, input, select, textarea, label, summary, [role=\"button\"], [role=\"switch\"], [role=\"checkbox\"], [role=\"tab\"], [role=\"menuitem\"]';\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\nconst clamp = (v: number, a: number, b: number) => (v < a ? a : v > b ? b : v);\nconst easeIn = (t: number) => t * t;\nconst easeOut = (t: number) => 1 - (1 - t) ** 3;\n\nlet probe: CanvasRenderingContext2D | null = null;\n/** Any CSS colour as 0–1 RGB, read back from a 1px canvas. */\nfunction toRgb(color: string, fallback: RGB): RGB {\n  probe ??= document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!probe) return fallback;\n  probe.clearRect(0, 0, 1, 1);\n  probe.fillStyle = \"#000\";\n  probe.fillStyle = color;\n  probe.fillRect(0, 0, 1, 1);\n  const [r, g, b, a] = probe.getImageData(0, 0, 1, 1).data;\n  return a === 0 ? fallback : [r / 255, g / 255, b / 255];\n}\n\n/** A light surface has dark text on it. Judged from the element's own text colour, so a dark card on a light page counts as dark. */\nfunction isLightSurface(el: Element) {\n  const [r, g, b] = toRgb(getComputedStyle(el).color, [0, 0, 0]);\n  return 0.2126 * r + 0.7152 * g + 0.0722 * b < 0.55;\n}\n\nfunction parseRadius(value: string, w: number, h: number) {\n  const first = value.trim().split(/\\s+/)[0] ?? \"0\";\n  const n = parseFloat(first) || 0;\n  return clamp(first.endsWith(\"%\") ? (n / 100) * Math.min(w, h) : n, 0, Math.min(w, h) / 2);\n}\n\nlet grain: string | null = null;\n/** A 64px tile of random alpha: the grain the old content dissolves through. Made once, on first use. */\nfunction grainTile() {\n  if (grain !== null) return grain;\n  const size = 64;\n  const c = document.createElement(\"canvas\");\n  c.width = c.height = size;\n  const ctx = c.getContext(\"2d\");\n  if (!ctx) return (grain = \"\");\n  const img = ctx.createImageData(size, size);\n  for (let i = 0; i < size * size; i++) img.data[i * 4 + 3] = Math.round(Math.random() ** 0.55 * 255);\n  ctx.putImageData(img, 0, 0);\n  return (grain = c.toDataURL());\n}\n\n/** A still copy of the element as it is, laid exactly over it: inert, unnamed, hidden from assistive tech. */\nfunction makeGhost(el: HTMLElement) {\n  const ghost = el.cloneNode(true) as HTMLElement;\n  for (const n of [ghost, ...Array.from(ghost.querySelectorAll<HTMLElement>(\"[id], [name]\"))]) {\n    n.removeAttribute(\"id\");\n    n.removeAttribute(\"name\");\n  }\n  const from = el.querySelectorAll(\"canvas\");\n  ghost.querySelectorAll(\"canvas\").forEach((c, i) => {\n    try {\n      c.getContext(\"2d\")?.drawImage(from[i], 0, 0);\n    } catch {}\n  });\n  ghost.setAttribute(\"aria-hidden\", \"true\");\n  ghost.inert = true;\n  Object.assign(ghost.style, {\n    position: \"absolute\",\n    left: `${el.offsetLeft}px`,\n    top: `${el.offsetTop}px`,\n    width: `${el.offsetWidth}px`,\n    height: `${el.offsetHeight}px`,\n    minWidth: \"0\",\n    maxWidth: \"none\",\n    margin: \"0\",\n    zIndex: \"5\",\n    pointerEvents: \"none\",\n    transition: \"none\",\n  });\n  return ghost;\n}\n\ntype Leaf = { el: HTMLElement; text: string };\n\n/** Every element that holds only text, keyed by its path from the root, skipping hidden and screen-reader-only text. */\nfunction readLeaves(root: HTMLElement) {\n  const out = new Map<string, Leaf>();\n  const walk = (el: Element, path: string) => {\n    if (!(el instanceof HTMLElement) || el.getAttribute(\"aria-hidden\") === \"true\") return;\n    const kids = el.children;\n    if (kids.length === 0) {\n      const text = el.textContent?.trim();\n      if (text && el.offsetWidth > 1 && el.offsetHeight > 1) out.set(path, { el, text });\n      return;\n    }\n    for (let i = 0; i < kids.length; i++) walk(kids[i], `${path}/${i}${kids[i].tagName}`);\n  };\n  walk(root, \"\");\n  return out;\n}\n\n/** A band of the light's colours runs through the letters once, in the direction the light travelled. */\nfunction glintText(el: HTMLElement, delay: number, rightward: boolean, light: boolean, colors: readonly [string, string, string]) {\n  if (getComputedStyle(el).backgroundImage !== \"none\") return;\n  const [warm, mid, cool] = colors;\n  const stops = light ? [cool, mid, warm] : [cool, \"#fff\", warm, mid];\n  const band = (rightward ? stops : [...stops].reverse()).map((c, i, all) => `${c} ${Math.round(36 + (i * 26) / Math.max(1, all.length - 1))}%`);\n  const s = el.style;\n  const saved = [s.backgroundImage, s.backgroundSize, s.backgroundRepeat, s.backgroundClip, s.webkitBackgroundClip, s.webkitTextFillColor];\n  s.backgroundImage = `linear-gradient(100deg, currentColor 0 30%, ${band.join(\", \")}, currentColor 68% 100%)`;\n  s.backgroundSize = \"300% 100%\";\n  s.backgroundRepeat = \"no-repeat\";\n  s.backgroundClip = \"text\";\n  s.webkitBackgroundClip = \"text\";\n  s.webkitTextFillColor = \"transparent\";\n  const [from, to] = rightward ? [\"100% 0\", \"0% 0\"] : [\"0% 0\", \"100% 0\"];\n  const a = el.animate([{ backgroundPosition: from }, { backgroundPosition: to }], { duration: GLINT, delay, easing: \"cubic-bezier(0.45, 0, 0.2, 1)\", fill: \"both\" });\n  const restore = () => {\n    a.cancel();\n    [s.backgroundImage, s.backgroundSize, s.backgroundRepeat, s.backgroundClip, s.webkitBackgroundClip, s.webkitTextFillColor] = saved;\n  };\n  a.onfinish = restore;\n  return restore;\n}\n\ntype Settings = { origin: AfterglowOrigin; colors: readonly [string, string, string]; glint: boolean; onFinish?: () => void; reduced: boolean };\n\ntype Run = {\n  el: HTMLElement;\n  start: number;\n  w: number;\n  h: number;\n  pw: number;\n  ph: number;\n  radius: number;\n  light: boolean;\n  cx: number;\n  cy: number;\n  r0: number;\n  rmax: number;\n  band: number;\n  seed: number;\n  rgb: [RGB, RGB, RGB];\n  ghost: HTMLElement | null;\n  far: number;\n  blur: number;\n  before: Map<string, Leaf> | null;\n  mutated: boolean;\n  observer: MutationObserver | null;\n  resolve: () => void;\n};\n\ntype Press = { el: Element | null; x: number; y: number; at: number };\n\nfunction createEngine(getRoot: () => HTMLDivElement | null, getSettings: () => Settings) {\n  let renderer: AfterglowRenderer | null | undefined;\n  let canvas: HTMLCanvasElement | null = null;\n  let raf = 0;\n  let warmTimer = 0;\n  let run: Run | null = null;\n  let press: Press | null = null;\n  const styled = new Map<HTMLElement, [string, string, string]>();\n  const glints = new Set<() => void>();\n\n  /** The wrapped element: the first child that isn't our canvas. */\n  const subject = () => {\n    const root = getRoot();\n    if (!root) return null;\n    for (const c of Array.from(root.children)) if (c instanceof HTMLElement && c !== canvas) return c;\n    return null;\n  };\n\n  const dropCanvas = () => {\n    renderer?.dispose();\n    canvas?.remove();\n    canvas = null;\n  };\n\n  /** The canvas is ours, not React's: a context that was lost or released can't come back on the same canvas. */\n  const ensureRenderer = () => {\n    if (renderer && !renderer.lost()) return renderer;\n    if (renderer === null) return null;\n    const root = getRoot();\n    if (!root) return null;\n    dropCanvas();\n    canvas = document.createElement(\"canvas\");\n    canvas.setAttribute(\"aria-hidden\", \"true\");\n    Object.assign(canvas.style, { position: \"absolute\", left: \"0\", top: \"0\", zIndex: \"10\", pointerEvents: \"none\", display: \"none\" });\n    root.appendChild(canvas);\n    renderer = createAfterglowRenderer(canvas);\n    if (!renderer) dropCanvas();\n    return renderer;\n  };\n\n  /** Blur and dim what's inside the element and its ghost, not their boxes: the card's edge stays crisp. */\n  const writeBlur = (els: (HTMLElement | null)[], blur: number) => {\n    const targets = els.flatMap((el) => (!el ? [] : el.children.length ? Array.from(el.children) : [el]));\n    const on = blur > 0.05;\n    for (const k of targets) {\n      if (!(k instanceof HTMLElement)) continue;\n      let saved = styled.get(k);\n      if (!saved) {\n        saved = [k.style.filter, k.style.opacity, k.style.willChange];\n        styled.set(k, saved);\n        k.style.willChange = \"filter, opacity\";\n      }\n      k.style.filter = on ? `blur(${blur.toFixed(2)}px)` : saved[0];\n      k.style.opacity = on ? String(1 - 0.22 * (blur / PEAK_BLUR)) : saved[1];\n    }\n  };\n\n  const restoreStyles = () => {\n    for (const [k, [filter, opacity, willChange]] of styled) {\n      k.style.filter = filter;\n      k.style.opacity = opacity;\n      k.style.willChange = willChange;\n    }\n    styled.clear();\n  };\n\n  const resolveOrigin = (kind: AfterglowOrigin, el: HTMLElement, w: number, h: number) => {\n    if (typeof kind === \"object\") return { x: clamp(kind.x, 0, 1) * w, y: clamp(kind.y, 0, 1) * h };\n    if (kind === \"center\") return { x: w / 2, y: h / 2 };\n    if (kind === \"top\") return { x: w / 2, y: 0 };\n    if (kind === \"bottom\") return { x: w / 2, y: h };\n    if (kind === \"left\") return { x: 0, y: h / 2 };\n    if (kind === \"right\") return { x: w, y: h / 2 };\n    const box = el.getBoundingClientRect();\n    const sx = box.width / w || 1;\n    const sy = box.height / h || 1;\n    const centreOf = (t: Element) => {\n      const r = t.getBoundingClientRect();\n      return { x: (r.left + r.width / 2 - box.left) / sx, y: (r.top + r.height / 2 - box.top) / sy, big: r.width * r.height > 0.4 * box.width * box.height };\n    };\n    if (press && performance.now() - press.at < PRESS_MEMORY) {\n      // Out of the control you pressed; from the exact point when the whole element is the control.\n      if (press.el?.isConnected && el.contains(press.el)) {\n        const c = centreOf(press.el);\n        if (!c.big) return c;\n      }\n      return { x: press.x, y: press.y };\n    }\n    const active = document.activeElement;\n    if (active && active !== el && el.contains(active)) return centreOf(active);\n    return { x: w / 2, y: h };\n  };\n\n  const finish = (interrupted: boolean) => {\n    const r = run;\n    if (!r) return;\n    run = null;\n    cancelAnimationFrame(raf);\n    raf = 0;\n    r.ghost?.remove();\n    r.observer?.disconnect();\n    restoreStyles();\n    renderer?.clear();\n    if (canvas) canvas.style.display = \"none\";\n    r.resolve();\n    if (!interrupted) getSettings().onFinish?.();\n  };\n\n  /** Radius of the front after t ms, and when it reaches distance d (the same curve as the shader). */\n  const frontAt = (r: Run, t: number) => r.r0 + (r.rmax - r.r0) * easeOut(clamp(t / FRONT, 0, 1));\n  const reachesAt = (r: Run, d: number) => (1 - Math.cbrt(1 - clamp((d - r.r0) / Math.max(1, r.rmax - r.r0), 0, 1))) * FRONT;\n\n  const glintChanges = (r: Run, t: number) => {\n    const before = r.before;\n    r.before = null;\n    r.observer?.disconnect();\n    r.observer = null;\n    if (!before) return;\n    const box = r.el.getBoundingClientRect();\n    const sx = box.width / r.w || 1;\n    const sy = box.height / r.h || 1;\n    const changed: { el: HTMLElement; dist: number; dx: number }[] = [];\n    for (const [key, leaf] of readLeaves(r.el)) {\n      if (before.get(key)?.text === leaf.text) continue;\n      const b = leaf.el.getBoundingClientRect();\n      const x = (b.left + b.width / 2 - box.left) / sx - r.cx;\n      const y = (b.top + b.height / 2 - box.top) / sy - r.cy;\n      changed.push({ el: leaf.el, dist: Math.hypot(x, y), dx: x });\n    }\n    if (!changed.length) return;\n    const { colors } = getSettings();\n    for (const c of changed.slice(0, 16)) {\n      // Each new value catches the light as soon as the dissolve has finished over it.\n      const delay = Math.max(40, reachesAt(r, c.dist + (LAG + DEPTH) * r.band) - t + 60);\n      const stop = glintText(c.el, delay, c.dx >= 0, r.light, colors);\n      if (stop) {\n        glints.add(stop);\n        window.setTimeout(() => glints.delete(stop), delay + GLINT + 50);\n      }\n    }\n  };\n\n  const frame = (now: number) => {\n    const r = run;\n    if (!r) return;\n    const t = Math.max(0, now - r.start);\n    if (r.before && (r.mutated ? t >= 32 : t >= 300)) glintChanges(r, t);\n    r.blur = t < BLUR_IN ? PEAK_BLUR * easeIn(t / BLUR_IN) : PEAK_BLUR * (1 - easeOut(Math.min(1, (t - BLUR_IN) / BLUR_OUT)));\n    // The old content dissolves just behind the bright line: solid ahead of it, grain fading to nothing\n    // over the next stretch, gone where the light has passed.\n    if (r.ghost) {\n      const edge = frontAt(r, t) - LAG * r.band;\n      const inner = edge - DEPTH * r.band;\n      if (inner > r.far) {\n        r.ghost.remove();\n        r.ghost = null;\n      } else {\n        const at = `circle at ${r.cx.toFixed(1)}px ${r.cy.toFixed(1)}px`;\n        const solid = `radial-gradient(${at}, transparent ${Math.max(0, edge).toFixed(1)}px, #000 ${Math.max(0.5, edge + 0.5).toFixed(1)}px)`;\n        const fade = `radial-gradient(${at}, transparent ${Math.max(0, inner).toFixed(1)}px, #000 ${Math.max(0.5, edge).toFixed(1)}px)`;\n        const tile = grainTile();\n        const st = r.ghost.style;\n        st.maskImage = st.webkitMaskImage = tile ? `${solid}, url(${tile}), ${fade}` : `${solid}, ${fade}`;\n        st.maskSize = st.webkitMaskSize = tile ? \"100% 100%, 64px 64px, 100% 100%\" : \"100% 100%, 100% 100%\";\n        st.maskRepeat = st.webkitMaskRepeat = tile ? \"no-repeat, repeat, no-repeat\" : \"no-repeat, no-repeat\";\n        st.maskComposite = tile ? \"add, intersect, add\" : \"add, add\";\n        st.setProperty(\"-webkit-mask-composite\", tile ? \"source-over, source-in, source-over\" : \"source-over, source-over\");\n      }\n    }\n    writeBlur([r.el, r.ghost], r.blur);\n    renderer?.draw({\n      width: r.w,\n      height: r.h,\n      pixelWidth: r.pw,\n      pixelHeight: r.ph,\n      radius: r.radius,\n      cx: r.cx,\n      cy: r.cy,\n      r0: r.r0,\n      rmax: r.rmax,\n      band: r.band,\n      time: t,\n      front: FRONT,\n      total: TOTAL,\n      light: r.light,\n      warm: r.rgb[0],\n      mid: r.rgb[1],\n      cool: r.rgb[2],\n      seed: r.seed,\n    });\n    if (t >= TOTAL) return finish(false);\n    raf = requestAnimationFrame(frame);\n  };\n\n  /** Compile the light ahead of time, when a hand comes near, so the first frame doesn't wait for it. */\n  const warm = () => {\n    if (renderer !== undefined || warmTimer || getSettings().reduced) return;\n    warmTimer = window.setTimeout(() => {\n      warmTimer = 0;\n      ensureRenderer();\n    }, 0);\n  };\n\n  return {\n    warm,\n    notePress(target: EventTarget | null, clientX: number, clientY: number) {\n      const el = subject();\n      if (!el || !(target instanceof Element)) return;\n      const box = el.getBoundingClientRect();\n      const control = target.closest(PRESSABLE);\n      press = {\n        el: control && el.contains(control) ? control : target,\n        x: (clientX - box.left) * (el.offsetWidth / (box.width || 1)),\n        y: (clientY - box.top) * (el.offsetHeight / (box.height || 1)),\n        at: performance.now(),\n      };\n      warm();\n    },\n    notePressedKey(target: EventTarget | null) {\n      const el = subject();\n      if (!el || !(target instanceof Element) || !el.contains(target)) return;\n      const box = el.getBoundingClientRect();\n      const r = target.getBoundingClientRect();\n      press = { el: target, x: r.left + r.width / 2 - box.left, y: r.top + r.height / 2 - box.top, at: performance.now() };\n      warm();\n    },\n    play(update?: () => void, options?: { origin?: AfterglowOrigin }) {\n      finish(true);\n      const s = getSettings();\n      const el = subject();\n      const w = el?.offsetWidth ?? 0;\n      const h = el?.offsetHeight ?? 0;\n      if (!el || s.reduced || !w || !h) {\n        update?.();\n        return Promise.resolve();\n      }\n      const cs = getComputedStyle(el);\n      const o = resolveOrigin(options?.origin ?? s.origin, el, w, h);\n      // The wave's centre sits behind the press point, away from the middle, so the front leaves the\n      // control as a gentle arc: a horizon in a card, a streak in a pill, a ring from the centre.\n      const short = Math.min(w, h);\n      const dx = o.x - w / 2;\n      const dy = o.y - h / 2;\n      const len = Math.hypot(dx, dy);\n      const push = len < short * 0.12 ? 0 : short * 0.45 + Math.max(w, h) * 0.08;\n      const cx = o.x + (len ? dx / len : 0) * push;\n      const cy = o.y + (len ? dy / len : 0) * push;\n      const band = clamp(short * (push ? 0.5 : 0.36), 36, 170);\n      const far = Math.max(Math.hypot(cx, cy), Math.hypot(cx - w, cy), Math.hypot(cx, cy - h), Math.hypot(cx - w, cy - h));\n      const dpr = Math.min(2, window.devicePixelRatio || 1);\n      const pw = Math.max(1, Math.round(w * dpr));\n      const ph = Math.max(1, Math.round(h * dpr));\n      const light = isLightSurface(el);\n      if (ensureRenderer() && canvas) {\n        if (canvas.width !== pw) canvas.width = pw;\n        if (canvas.height !== ph) canvas.height = ph;\n        Object.assign(canvas.style, {\n          display: \"block\",\n          left: `${el.offsetLeft}px`,\n          top: `${el.offsetTop}px`,\n          width: `${w}px`,\n          height: `${h}px`,\n          borderRadius: cs.borderRadius,\n          mixBlendMode: light ? \"normal\" : \"screen\",\n        });\n      }\n      const [warm, mid, cool] = s.colors;\n      const before = s.glint ? readLeaves(el) : null;\n      // The old content, frozen, over the new: nothing visibly changes until the light dissolves it.\n      const ghost = update ? makeGhost(el) : null;\n      if (ghost) el.after(ghost);\n      update?.();\n      return new Promise<void>((resolve) => {\n        run = {\n          el,\n          start: performance.now(),\n          w,\n          h,\n          pw,\n          ph,\n          radius: parseRadius(cs.borderTopLeftRadius, w, h),\n          light,\n          cx,\n          cy,\n          r0: push,\n          rmax: far + band * 1.4,\n          far,\n          band,\n          seed: Math.random() * 97,\n          rgb: [toRgb(warm, [1, 0.7, 0.28]), toRgb(mid, [1, 0.31, 0.55]), toRgb(cool, [0.24, 0.55, 1])],\n          ghost,\n          blur: 0,\n          before,\n          mutated: false,\n          observer: null,\n          resolve,\n        };\n        if (before) {\n          const r = run;\n          r.observer = new MutationObserver(() => {\n            r.mutated = true;\n            writeBlur([r.el, r.ghost], r.blur);\n          });\n          r.observer.observe(el, { childList: true, subtree: true, characterData: true });\n        }\n        raf = requestAnimationFrame(frame);\n      });\n    },\n    dispose() {\n      finish(true);\n      window.clearTimeout(warmTimer);\n      warmTimer = 0;\n      for (const stop of glints) stop();\n      glints.clear();\n      dropCanvas();\n      renderer = undefined;\n    },\n  };\n}\n\ntype Engine = ReturnType<typeof createEngine>;\n\nexport function Afterglow({\n  children,\n  ref,\n  origin = \"press\",\n  colors = DEFAULT_COLORS,\n  glint = true,\n  onFinish,\n  className = \"\",\n  onPointerDownCapture,\n  onPointerEnter,\n  onKeyDownCapture,\n  ...props\n}: AfterglowProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const reduced = useReducedMotion();\n  const settings = React.useRef<Settings>({ origin, colors, glint, onFinish, reduced });\n  const engineRef = React.useRef<Engine | null>(null);\n\n  React.useLayoutEffect(() => {\n    settings.current = { origin, colors, glint, onFinish, reduced };\n  });\n\n  const engine = React.useCallback(\n    () => (engineRef.current ??= createEngine(() => rootRef.current, () => settings.current)),\n    [],\n  );\n\n  React.useEffect(\n    () => () => {\n      engineRef.current?.dispose();\n      engineRef.current = null;\n    },\n    [],\n  );\n\n  React.useImperativeHandle(ref, () => ({ play: (update, options) => engine().play(update, options) }), [engine]);\n\n  return (\n    <div\n      ref={rootRef}\n      className={`relative isolate ${className}`}\n      onPointerEnter={(e) => {\n        onPointerEnter?.(e);\n        if (e.pointerType === \"mouse\") engine().warm();\n      }}\n      onPointerDownCapture={(e) => {\n        onPointerDownCapture?.(e);\n        engine().notePress(e.target, e.clientX, e.clientY);\n      }}\n      onKeyDownCapture={(e) => {\n        onKeyDownCapture?.(e);\n        if (e.key === \"Enter\" || e.key === \" \") engine().notePressedKey(e.target);\n      }}\n      {...props}\n    >\n      {children}\n    </div>\n  );\n}\n"},{"path":"registry/afterglow-gl.ts","type":"registry:component","content":"// Hairline UI · afterglow · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * AFTERGLOW renderer (WebGL 2)\n *\n * One full-screen triangle; everything is worked out per pixel\n * from the time and the distance to the centre of the wave:\n *\n *   front    a thin white-hot line, warm light running ahead\n *            of it with a rose fringe, clear blue behind\n *   wake     the air it passed through keeps a little light,\n *            and fine dust twinkles in it, then both fade\n *   rim      the edge of the element lights up as the front\n *            reaches it and holds an iridescent glow a moment\n *\n * Each pixel knows when the front passed it (the reach curve\n * inverted), so the wake and the rim fade in the order the\n * light went through, and the far corner glows last.\n *\n * Dark surfaces add the light (the canvas is screened over the\n * element); light surfaces get it as colour, since white light\n * on white has nothing to show.\n * ───────────────────────────────────────────────────────── */\n\nexport type RGB = readonly [number, number, number];\n\nexport interface GlowFrame {\n  /** Element size in CSS px. */\n  width: number;\n  height: number;\n  /** Canvas size in device px. */\n  pixelWidth: number;\n  pixelHeight: number;\n  /** Corner radius in CSS px. */\n  radius: number;\n  /** Centre of the wave and its radius at the start and the end, CSS px. */\n  cx: number;\n  cy: number;\n  r0: number;\n  rmax: number;\n  /** Width of the band of light, CSS px. */\n  band: number;\n  /** ms since the start, how long the front takes, how long it all takes. */\n  time: number;\n  front: number;\n  total: number;\n  light: boolean;\n  warm: RGB;\n  mid: RGB;\n  cool: RGB;\n  seed: number;\n}\n\nexport interface AfterglowRenderer {\n  draw(frame: GlowFrame): void;\n  clear(): void;\n  lost(): boolean;\n  dispose(): void;\n}\n\nconst VERT = `#version 300 es\nvoid main() {\n  vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));\n  gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);\n}`;\n\nconst FRAG = `#version 300 es\nprecision highp float;\nuniform vec2 uSize;\nuniform vec2 uPix;\nuniform float uRadius;\nuniform vec2 uCenter;\nuniform float uR0;\nuniform float uRmax;\nuniform float uBand;\nuniform float uTime;\nuniform float uFront;\nuniform float uTotal;\nuniform float uLight;\nuniform float uSeed;\nuniform vec3 uWarm;\nuniform vec3 uMid;\nuniform vec3 uCool;\nout vec4 o;\n\nfloat hash(vec2 p) {\n  vec3 q = fract(vec3(p.xyx) * 0.1031);\n  q += dot(q, q.yzx + 33.33);\n  return fract((q.x + q.y) * q.z);\n}\n\nfloat vnoise(vec2 p) {\n  vec2 i = floor(p);\n  vec2 f = fract(p);\n  f = f * f * (3.0 - 2.0 * f);\n  float a = hash(i + uSeed);\n  float b = hash(i + vec2(1.0, 0.0) + uSeed);\n  float c = hash(i + vec2(0.0, 1.0) + uSeed);\n  float d = hash(i + vec2(1.0, 1.0) + uSeed);\n  return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);\n}\n\nfloat sdBox(vec2 p, vec2 b, float r) {\n  vec2 q = abs(p) - b + r;\n  return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;\n}\n\n// How far the front has got (0 to 1) after a share k of its time: fast out, long slow tail.\nfloat reach(float k) {\n  float c = clamp(k, 0.0, 1.0);\n  return 1.0 - (1.0 - c) * (1.0 - c) * (1.0 - c);\n}\n\n// When the front got to distance d, in ms (reach inverted).\nfloat passedAt(float d) {\n  float k = clamp((d - uR0) / max(uRmax - uR0, 1.0), 0.0, 1.0);\n  return (1.0 - pow(1.0 - k, 1.0 / 3.0)) * uFront;\n}\n\nvoid main() {\n  vec2 p = vec2(gl_FragCoord.x, uPix.y - gl_FragCoord.y) * (uSize / uPix);\n  vec2 rel = p - uCenter;\n  float d = length(rel);\n  vec2 dir = rel / max(d, 0.001);\n  float t = uTime;\n  float u = t / uFront;\n\n  // The front, with a slow wobble along it so it's never a drawn circle.\n  float R = uR0 + (uRmax - uR0) * reach(u);\n  // The wobble grows with the ring, so a small ring near its start stays round.\n  float wob = (vnoise(dir * 2.2 + vec2(t * 0.0005, 3.1)) - 0.5) * min(uBand * 0.34, R * 0.14 + 1.0);\n  float s = R + wob - d;\n  float x = s / uBand;\n  float env = smoothstep(0.0, 0.06, u) * (1.0 - smoothstep(0.42, 1.0, u));\n  float rays = 0.78 + 0.44 * vnoise(dir * 9.0 + vec2(1.7, t * 0.0008));\n\n  // Ahead: gold close to the front, a faint rose fringe further out.\n  float ahead = x < 0.0 ? exp(x / 0.24) : 0.0;\n  float fringe = x < 0.0 ? exp(-pow((x + 0.42) / 0.22, 2.0)) : 0.0;\n  // The front: a thin white-hot line.\n  float core = exp(-pow(s / (uBand * 0.022 + 0.9), 2.0));\n  // Behind: a narrow band of clear sky, then dark.\n  float sky = x > 0.0 ? exp(-pow((x - 0.12) / 0.13, 2.0)) : 0.0;\n  float dusk = x > 0.0 ? exp(-pow((x - 0.45) / 0.35, 2.0)) : 0.0;\n\n  bool light = uLight > 0.5;\n  vec3 hot = light ? mix(uWarm, uMid, 0.4) : vec3(1.0, 0.97, 0.92);\n  vec3 col = (uWarm * ahead * 0.95 + uMid * fringe * 0.22) * rays\n    + hot * core * 1.15\n    + (uCool * sky * 0.8 + uCool * dusk * 0.1) * mix(1.0, rays, 0.5);\n  col *= env;\n\n  // The wake: what the light passed through holds a little of it.\n  float age = t - passedAt(d - wob);\n  float behind = step(0.0, s);\n  float haze = behind * exp(-max(age, 0.0) / 320.0);\n  col += mix(uCool, uMid, 0.3) * haze * 0.06;\n\n  // Dust in the wake, sparse and uneven, twinkling, brightest close behind the front.\n  float cell = 6.0;\n  vec2 c = floor(p / cell);\n  vec2 sp = (c + 0.2 + 0.6 * vec2(hash(c + 11.3), hash(c + 27.9))) * cell;\n  float rad = 0.28 + 0.5 * pow(hash(c + 3.7), 2.0);\n  float star = step(0.83, hash(c * 1.37 + 4.1)) * (1.0 - smoothstep(rad * 0.4, rad + 0.5, length(p - sp))) * (0.35 + 0.65 * hash(c + 6.4));\n  float tw = 0.45 + 0.55 * sin(t * (0.006 + 0.01 * hash(c + 8.8)) + 6.2832 * hash(c + 1.1));\n  float dust = behind * exp(-max(age, 0.0) / 560.0) * smoothstep(0.0, 0.05, x) * (0.4 + sky * 0.8 + dusk * 0.5);\n  vec3 dustCol = light ? mix(uCool, uMid, step(0.5, hash(c + 5.5))) : vec3(1.0);\n  col += dustCol * star * tw * dust;\n\n  // The rim lights as the front reaches it and keeps an iridescent glow for a moment.\n  vec2 hs = uSize * 0.5;\n  float e = max(-sdBox(p - hs, hs, uRadius), 0.0);\n  float lit = smoothstep(-0.6, 0.0, x) * exp(-max(age, 0.0) / 820.0);\n  float h = 0.5 + 0.5 * sin(atan(p.y - hs.y, p.x - hs.x) + t * 0.0016);\n  vec3 rimCol = h < 0.5 ? mix(uWarm, uMid, h * 2.0) : mix(uMid, uCool, h * 2.0 - 1.0);\n  col += rimCol * (exp(-e / 1.1) * 0.85 + exp(-e / 16.0) * 0.22) * lit;\n\n  col *= 1.0 - smoothstep(uTotal - 520.0, uTotal, t);\n  col = max(col, 0.0);\n  float peak = max(col.r, max(col.g, col.b));\n  if (light) {\n    float a = clamp(peak, 0.0, 1.0) * 0.74;\n    o = vec4(peak > 0.0001 ? col / peak * a : vec3(0.0), a);\n  } else {\n    col = col / (1.0 + col * 0.3);\n    o = vec4(min(col, 1.0), clamp(max(col.r, max(col.g, col.b)), 0.0, 1.0));\n  }\n}`;\n\nconst UNIFORMS = [\"uSize\", \"uPix\", \"uRadius\", \"uCenter\", \"uR0\", \"uRmax\", \"uBand\", \"uTime\", \"uFront\", \"uTotal\", \"uLight\", \"uSeed\", \"uWarm\", \"uMid\", \"uCool\"] as const;\ntype UniformName = (typeof UNIFORMS)[number];\n\nfunction compile(gl: WebGL2RenderingContext, type: number, source: string) {\n  const shader = gl.createShader(type);\n  if (!shader) return null;\n  gl.shaderSource(shader, source);\n  gl.compileShader(shader);\n  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n    gl.deleteShader(shader);\n    return null;\n  }\n  return shader;\n}\n\n/** A renderer on this canvas, or null where WebGL 2 isn't available (the element still blurs and glints). */\nexport function createAfterglowRenderer(canvas: HTMLCanvasElement): AfterglowRenderer | null {\n  const gl = canvas.getContext(\"webgl2\", { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, preserveDrawingBuffer: false });\n  if (!gl) return null;\n  const vs = compile(gl, gl.VERTEX_SHADER, VERT);\n  const fs = compile(gl, gl.FRAGMENT_SHADER, FRAG);\n  const program = gl.createProgram();\n  if (!vs || !fs || !program) return null;\n  gl.attachShader(program, vs);\n  gl.attachShader(program, fs);\n  gl.linkProgram(program);\n  gl.deleteShader(vs);\n  gl.deleteShader(fs);\n  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n    gl.deleteProgram(program);\n    return null;\n  }\n  const loc = Object.fromEntries(UNIFORMS.map((name) => [name, gl.getUniformLocation(program, name)])) as Record<UniformName, WebGLUniformLocation | null>;\n\n  return {\n    draw(f) {\n      if (gl.isContextLost()) return;\n      gl.viewport(0, 0, f.pixelWidth, f.pixelHeight);\n      gl.useProgram(program);\n      gl.uniform2f(loc.uSize, f.width, f.height);\n      gl.uniform2f(loc.uPix, f.pixelWidth, f.pixelHeight);\n      gl.uniform1f(loc.uRadius, f.radius);\n      gl.uniform2f(loc.uCenter, f.cx, f.cy);\n      gl.uniform1f(loc.uR0, f.r0);\n      gl.uniform1f(loc.uRmax, f.rmax);\n      gl.uniform1f(loc.uBand, f.band);\n      gl.uniform1f(loc.uTime, f.time);\n      gl.uniform1f(loc.uFront, f.front);\n      gl.uniform1f(loc.uTotal, f.total);\n      gl.uniform1f(loc.uLight, f.light ? 1 : 0);\n      gl.uniform1f(loc.uSeed, f.seed);\n      gl.uniform3f(loc.uWarm, f.warm[0], f.warm[1], f.warm[2]);\n      gl.uniform3f(loc.uMid, f.mid[0], f.mid[1], f.mid[2]);\n      gl.uniform3f(loc.uCool, f.cool[0], f.cool[1], f.cool[2]);\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n    },\n    clear() {\n      if (gl.isContextLost()) return;\n      gl.clearColor(0, 0, 0, 0);\n      gl.clear(gl.COLOR_BUFFER_BIT);\n    },\n    lost: () => gl.isContextLost(),\n    dispose() {\n      gl.deleteProgram(program);\n      gl.getExtension(\"WEBGL_lose_context\")?.loseContext();\n    },\n  };\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/afterglow. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}