{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"level-dial","type":"registry:component","title":"Level dial","description":"A 270° dial for one level in a card: drag it and it follows, and when a preset sets it a crest of light spreads from its centre as the arc sweeps there.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/level-dial.tsx","type":"registry:component","content":"// Hairline UI · level-dial · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport {\n  LightSurface,\n  clamp,\n  easeOutCubic,\n  resolvePalette,\n  useLightHeld,\n  useLightReducedMotion,\n  type LightPalette,\n  type LightPaletteName,\n  type LightSurfaceHandle,\n} from \"./light-surface\";\n\n/* ─────────────────────────────────────────────────────────\n * LEVEL DIAL: a 270° dial for one level, in a card\n *\n *   turn     drag along the arc, or use the arrow keys; the\n *            arc and the figure follow at once\n *   jump     when the value changes from outside (a preset, a\n *            schedule, another device), a crest of light spreads from\n *            the dial's centre; under it the arc sweeps to the\n *            new value and the figure counts there\n *   zones    name ranges of the dial (Late night, Reference);\n *            a zone with a palette colours the arc and keeps\n *            the card's rim lit while the value is in it\n *\n * Reduced motion: jumps land in place, with no light.\n * ───────────────────────────────────────────────────────── */\n\nexport interface LevelZone {\n  /** The zone covers values up to and including this one. */\n  to: number;\n  label: string;\n  /** Colours the arc and lights the rim while the value is in this zone. */\n  palette?: LightPaletteName | LightPalette;\n}\n\nexport interface LevelDialProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"title\" | \"onChange\"> {\n  value: number;\n  onValueChange?: (value: number) => void;\n  min?: number;\n  max?: number;\n  step?: number;\n  /** Set after the figure: \"°\", \"dB\", \"%\". */\n  unit?: string;\n  /** Names the dial for screen readers. */\n  label: string;\n  /** The card's heading. */\n  title?: React.ReactNode;\n  /** Top right of the card: a mode, a badge. */\n  badge?: React.ReactNode;\n  /** A line under the dial. */\n  caption?: React.ReactNode;\n  /** Named ranges, lowest first. */\n  zones?: LevelZone[];\n  /** Your actions, at the foot of the card. */\n  children?: React.ReactNode;\n}\n\nconst START = 135;\nconst SWEEP = 270;\nconst CX = 120;\nconst CY = 120;\nconst R = 84;\n\nconst polar = (deg: number, r = R) => ({ x: CX + r * Math.cos((deg * Math.PI) / 180), y: CY + r * Math.sin((deg * Math.PI) / 180) });\nfunction arc(from: number, to: number) {\n  const a = polar(from);\n  const b = polar(to);\n  return `M ${a.x.toFixed(2)} ${a.y.toFixed(2)} A ${R} ${R} 0 ${to - from > 180 ? 1 : 0} 1 ${b.x.toFixed(2)} ${b.y.toFixed(2)}`;\n}\n\n/** Glides to a new target when asked to, otherwise follows it exactly. */\nfunction useGlide(target: number, glide: boolean, reduced: boolean) {\n  const [anim, setAnim] = React.useState<number | null>(null);\n  const current = React.useRef(target);\n  const raf = React.useRef(0);\n  React.useEffect(() => {\n    cancelAnimationFrame(raf.current);\n    if (!glide || reduced) {\n      current.current = target;\n      raf.current = requestAnimationFrame(() => setAnim(null));\n      return () => cancelAnimationFrame(raf.current);\n    }\n    const from = current.current;\n    if (from === target) return;\n    const start = performance.now();\n    const step = (now: number) => {\n      const k = Math.min(1, (now - start) / 720);\n      current.current = from + (target - from) * easeOutCubic(k);\n      setAnim(k < 1 ? current.current : null);\n      if (k < 1) raf.current = requestAnimationFrame(step);\n    };\n    raf.current = requestAnimationFrame(step);\n    return () => cancelAnimationFrame(raf.current);\n  }, [target, glide, reduced]);\n  return anim ?? target;\n}\n\nexport function LevelDial({\n  value,\n  onValueChange,\n  min = 0,\n  max = 100,\n  step = 1,\n  unit = \"\",\n  label,\n  title,\n  badge,\n  caption,\n  zones,\n  children,\n  className = \"\",\n  ...props\n}: LevelDialProps) {\n  const surface = React.useRef<LightSurfaceHandle>(null);\n  const svg = React.useRef<SVGSVGElement>(null);\n  const reduced = useLightReducedMotion();\n  const [dragging, setDragging] = React.useState(false);\n  // The last value we sent: anything else that arrives was set from outside, and gets the light.\n  const [local, setLocal] = React.useState<number | null>(null);\n  const external = value !== local;\n  const zoneOf = (v: number) => zones?.find((z) => v <= z.to) ?? zones?.[zones.length - 1];\n\n  const landed = useLightHeld(value, external ? `x${value}` : \"local\", surface, () => {\n    if (!external) return null;\n    const card = surface.current?.element();\n    const dial = svg.current;\n    let origin = { x: 0.5, y: 0.44 };\n    if (card && dial) {\n      const c = card.getBoundingClientRect();\n      const d = dial.getBoundingClientRect();\n      origin = { x: (d.left + d.width / 2 - c.left) / c.width, y: (d.top + (d.height * CY) / 218 - c.top) / c.height };\n    }\n    return { direction: \"radial\", origin, palette: zoneOf(value)?.palette ?? \"solar\" };\n  });\n  const shown = clamp(useGlide(landed, external, reduced), min, max);\n  const zone = zoneOf(Math.round(shown));\n  const pal = zone?.palette ? resolvePalette(zone.palette) : null;\n  const angle = START + ((shown - min) / (max - min || 1)) * SWEEP;\n  const thumb = polar(angle);\n  const gradientId = React.useId();\n\n  const send = (v: number) => {\n    const next = clamp(Math.round(v / step) * step, min, max);\n    if (next === value) return;\n    setLocal(next);\n    onValueChange?.(next);\n  };\n\n  const fromPointer = (clientX: number, clientY: number) => {\n    const el = svg.current;\n    if (!el) return;\n    const r = el.getBoundingClientRect();\n    const deg = (Math.atan2(clientY - (r.top + (r.height * CY) / 218), clientX - (r.left + r.width / 2)) * 180) / Math.PI;\n    const around = ((((deg % 360) + 360) % 360) - START + 360) % 360;\n    // Past the ends of the arc, the nearer end wins.\n    const k = around <= SWEEP ? around / SWEEP : around - SWEEP < 360 - around ? 1 : 0;\n    send(min + k * (max - min));\n  };\n\n  const ink = pal ? pal.ink : \"var(--foreground)\";\n  const figure = Math.round(shown);\n\n  return (\n    <LightSurface\n      ref={surface}\n      palette={zone?.palette ?? \"solar\"}\n      direction=\"radial\"\n      lit={!!pal}\n     \n      className={`flex flex-col rounded-[30px] ${className}`}\n      {...props}\n    >\n      <div className=\"flex h-full flex-col px-6 pb-6 pt-6\">\n        {(title || badge) && (\n          <div className=\"flex min-h-7 items-center justify-between gap-3\">\n            <div className=\"text-[15px] font-medium tracking-[-0.01em] text-foreground\">{title}</div>\n            {badge}\n          </div>\n        )}\n        <div className=\"my-1 flex flex-col items-center\">\n          <div\n            role=\"slider\"\n            tabIndex={0}\n            aria-label={label}\n            aria-valuemin={min}\n            aria-valuemax={max}\n            aria-valuenow={value}\n            aria-valuetext={`${value}${unit}${zoneOf(value)?.label ? `, ${zoneOf(value)?.label}` : \"\"}`}\n            onKeyDown={(e) => {\n              const big = Math.max(step, (max - min) / 10);\n              const by: Record<string, number> = { ArrowRight: step, ArrowUp: step, ArrowLeft: -step, ArrowDown: -step, PageUp: big, PageDown: -big };\n              if (e.key in by) send(value + by[e.key]);\n              else if (e.key === \"Home\") send(min);\n              else if (e.key === \"End\") send(max);\n              else return;\n              e.preventDefault();\n            }}\n            className=\"relative flex w-full max-w-[236px] items-center justify-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50\"\n          >\n            <svg\n              ref={svg}\n              viewBox=\"0 0 240 218\"\n              className={`aspect-[240/218] w-full max-w-[236px] touch-none select-none ${dragging ? \"cursor-grabbing\" : \"cursor-grab\"}`}\n              onPointerDown={(e) => {\n                e.currentTarget.setPointerCapture(e.pointerId);\n                setDragging(true);\n                fromPointer(e.clientX, e.clientY);\n              }}\n              onPointerMove={(e) => dragging && fromPointer(e.clientX, e.clientY)}\n              onPointerUp={() => setDragging(false)}\n              onPointerCancel={() => setDragging(false)}\n            >\n              {pal && (\n                <defs>\n                  <linearGradient id={gradientId} x1=\"0%\" y1=\"100%\" x2=\"100%\" y2=\"0%\">\n                    <stop offset=\"0%\" stopColor={pal.ink} />\n                    <stop offset=\"100%\" stopColor={`color-mix(in oklab, ${pal.ink} 45%, white)`} />\n                  </linearGradient>\n                </defs>\n              )}\n              <path d={arc(START, START + SWEEP)} fill=\"none\" stroke=\"color-mix(in oklab, var(--foreground) 11%, transparent)\" strokeWidth=\"7.5\" strokeLinecap=\"round\" />\n              {shown > min && (\n                <path d={arc(START, angle)} fill=\"none\" stroke={pal ? `url(#${gradientId})` : \"var(--foreground)\"} strokeWidth=\"7.5\" strokeLinecap=\"round\" />\n              )}\n              <circle\n                cx={thumb.x}\n                cy={thumb.y}\n                r={dragging ? 7.5 : 5.5}\n                fill=\"var(--card)\"\n                stroke={ink}\n                strokeWidth=\"2.5\"\n                className=\"transition-[r] duration-150 motion-reduce:transition-none\"\n              />\n              <text x=\"62\" y=\"206\" textAnchor=\"middle\" className=\"fill-muted-foreground font-mono text-[12px] tabular-nums\">\n                {min}\n              </text>\n              <text x=\"178\" y=\"206\" textAnchor=\"middle\" className=\"fill-muted-foreground font-mono text-[12px] tabular-nums\">\n                {max}\n              </text>\n            </svg>\n            <div aria-hidden className=\"pointer-events-none absolute inset-0 flex flex-col items-center justify-center pt-1 [container-type:inline-size]\">\n              <div className=\"flex items-baseline gap-0.5\">\n                <span className=\"text-[clamp(34px,15cqi,46px)] font-medium leading-none tracking-[-0.04em] tabular-nums text-foreground\">{figure}</span>\n                {unit && <span className=\"text-[16px] font-medium text-muted-foreground\">{unit}</span>}\n              </div>\n              {zone?.label && (\n                <div\n                  className=\"mt-1.5 text-[13px] font-medium transition-colors duration-300\"\n                  style={{ color: pal ? `color-mix(in oklab, ${pal.ink} 70%, var(--foreground))` : \"var(--muted-foreground)\" }}\n                >\n                  {zone.label}\n                </div>\n              )}\n            </div>\n          </div>\n          {caption && <p className=\"mt-1 text-center text-[13px] tabular-nums text-muted-foreground\">{caption}</p>}\n        </div>\n        {children && <div className=\"mt-auto pt-4\">{children}</div>}\n      </div>\n    </LightSurface>\n  );\n}\n"},{"path":"registry/light-surface.tsx","type":"registry:component","content":"// Hairline UI · level-dial · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\n\n/* ─────────────────────────────────────────────────────────\n * LIGHT SURFACE: the card the light runs through\n *\n *   wave     a band of light crosses the surface: a thin crest\n *            ring from a point (radial), a ribbon scanning left\n *            to right (horizontal), or a wide soft veil drifting\n *            across (diagonal); the content defocuses under it,\n *            your change lands at the peak, and starlight dust\n *            trails behind and fades\n *   charge   while something is held, light gathers toward the\n *            finger and the dust is pulled in; let go and it\n *            relaxes\n *   lit      a surface that's \"on\" keeps its light in the rim:\n *            colour bleeding in from the corners and a fine\n *            prismatic bezel, brighter just after a wave\n *\n * Shared by Status capsule, Hold to start, Level dial and Scene\n * mixer. Dark surfaces add the light; light surfaces get it as\n * colour.\n *\n * Reduced motion: no waves, no charge; changes land at once.\n * ───────────────────────────────────────────────────────── */\n\nexport type LightPaletteName = \"azure\" | \"solar\" | \"prism\" | \"dusk\";\n\nexport interface LightPalette {\n  /** Leading fringe of the wavefront. */\n  outerFringe: string;\n  /** The bright core of the wavefront. */\n  core: string;\n  /** Trailing band of colour. */\n  innerFringe: string;\n  /** The wash behind the wavefront. */\n  ambient: string;\n  /** Dust colours. */\n  sparkle: readonly [string, string, string];\n  /** Rim light, from the corners. */\n  rimPrimary: string;\n  rimSecondary: string;\n  rimAccent: string;\n  /** A solid colour for text and marks that follow the palette. */\n  ink: string;\n  /** How strong the wave is, 0 to 1. */\n  strength: number;\n}\n\nexport const LIGHT_PALETTES: Record<LightPaletteName, LightPalette> = {\n  // A crisp azure scan.\n  azure: {\n    outerFringe: \"rgba(56, 189, 248, 0.94)\",\n    core: \"rgba(240, 249, 255, 0.98)\",\n    innerFringe: \"rgba(37, 99, 235, 0.88)\",\n    ambient: \"rgba(14, 165, 233, 0.38)\",\n    sparkle: [\"#FFFFFF\", \"#BAE6FD\", \"#93C5FD\"],\n    rimPrimary: \"rgba(96, 185, 255, 0.64)\",\n    rimSecondary: \"rgba(59, 130, 246, 0.58)\",\n    rimAccent: \"rgba(186, 230, 253, 0.46)\",\n    ink: \"#3b82f6\",\n    strength: 0.95,\n  },\n  // Warm apricot and rose.\n  solar: {\n    outerFringe: \"rgba(244, 114, 146, 0.68)\",\n    core: \"rgba(255, 250, 234, 0.92)\",\n    innerFringe: \"rgba(251, 166, 92, 0.76)\",\n    ambient: \"rgba(251, 191, 96, 0.36)\",\n    sparkle: [\"#FFFFFF\", \"#FCD9A4\", \"#FBB6C8\"],\n    rimPrimary: \"rgba(251, 178, 102, 0.7)\",\n    rimSecondary: \"rgba(238, 126, 162, 0.62)\",\n    rimAccent: \"rgba(251, 204, 116, 0.54)\",\n    ink: \"#f59e0b\",\n    strength: 0.86,\n  },\n  // Pearl: champagne, rose and sky.\n  prism: {\n    outerFringe: \"rgba(246, 146, 196, 0.72)\",\n    core: \"rgba(255, 250, 236, 0.92)\",\n    innerFringe: \"rgba(96, 195, 248, 0.64)\",\n    ambient: \"rgba(251, 200, 114, 0.36)\",\n    sparkle: [\"#FFFFFF\", \"#FDE6B0\", \"#FFD6E8\"],\n    rimPrimary: \"rgba(250, 204, 116, 0.68)\",\n    rimSecondary: \"rgba(240, 140, 190, 0.66)\",\n    rimAccent: \"rgba(104, 188, 248, 0.5)\",\n    ink: \"#ec4899\",\n    strength: 0.88,\n  },\n  // A soft evening veil: rose and cornflower.\n  dusk: {\n    outerFringe: \"rgba(240, 150, 200, 0.5)\",\n    core: \"rgba(255, 246, 250, 0.7)\",\n    innerFringe: \"rgba(120, 160, 248, 0.48)\",\n    ambient: \"rgba(230, 150, 200, 0.22)\",\n    sparkle: [\"#FFFFFF\", \"#FFE4F0\", \"#D8E4FF\"],\n    rimPrimary: \"rgba(240, 150, 200, 0.6)\",\n    rimSecondary: \"rgba(120, 160, 248, 0.56)\",\n    rimAccent: \"rgba(250, 210, 228, 0.42)\",\n    ink: \"#6b8af6\",\n    strength: 0.64,\n  },\n};\n\nexport type LightDirection = \"radial\" | \"horizontal\" | \"diagonal\";\n/** A point inside the surface, 0 to 1 on each axis. */\nexport type LightPoint = { x: number; y: number };\n\nexport interface LightWaveOptions {\n  origin?: LightPoint;\n  direction?: LightDirection;\n  palette?: LightPaletteName | LightPalette;\n  /** ms; the default suits the direction. */\n  duration?: number;\n  /** Called once, when the content is most out of focus: change your state here. */\n  onMidpoint?: () => void;\n  onComplete?: () => void;\n}\n\nexport interface LightSurfaceHandle {\n  wave: (options?: LightWaveOptions) => void;\n  /** 0 to 1 while something is held; 0 lets the light relax. */\n  charge: (level: number, origin?: LightPoint) => void;\n  /** Whether a wave is crossing right now. */\n  busy: () => boolean;\n  element: () => HTMLDivElement | null;\n}\n\nexport const resolvePalette = (p: LightPaletteName | LightPalette | undefined, fallback: LightPaletteName = \"azure\") =>\n  typeof p === \"object\" ? p : LIGHT_PALETTES[p ?? fallback] ?? LIGHT_PALETTES[fallback];\n\nexport const clamp = (v: number, a: number, b: number) => (v < a ? a : v > b ? b : v);\nexport const easeOutCubic = (t: number) => 1 - (1 - clamp(t, 0, 1)) ** 3;\nexport const easeOutQuart = (t: number) => 1 - (1 - clamp(t, 0, 1)) ** 4;\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nexport const prefersReducedMotion = () => typeof window !== \"undefined\" && window.matchMedia(reducedQuery).matches;\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nexport const useLightReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\n/** Focus, light and dust over a wave's progress (0 to 1): the change lands at 36%, at the deepest defocus. */\nexport function opticsAt(progress: number) {\n  const p = clamp(progress, 0, 1);\n  const swap = 0.36;\n  const focus = p < swap ? Math.sin((p / swap) * (Math.PI / 2)) : p < 0.86 ? Math.cos(((p - swap) / (0.86 - swap)) * (Math.PI / 2)) ** 1.35 : 0;\n  const wave = p < 0.16 ? Math.sin((p / 0.16) * (Math.PI / 2)) : (1 - (p - 0.16) / 0.84) ** 1.9;\n  const dust = p < 0.18 ? p / 0.18 : p < 0.5 ? 1 : (1 - (p - 0.5) / 0.5) ** 1.75;\n  return { blur: focus * 7.8, scale: 1 - focus * 0.01, swapped: p >= swap, wave: clamp(wave, 0, 1), dust: clamp(dust, 0, 1), veil: focus * 0.24 };\n}\n\nlet probe: CanvasRenderingContext2D | null = null;\n/** A light surface has dark text on it, judged from its own text colour (read back from a 1px canvas, so any colour syntax works). */\nexport function isLightSurface(el: Element) {\n  probe ??= document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!probe) return false;\n  probe.clearRect(0, 0, 1, 1);\n  probe.fillStyle = \"#fff\";\n  probe.fillStyle = getComputedStyle(el).color;\n  probe.fillRect(0, 0, 1, 1);\n  const [r, g, b] = probe.getImageData(0, 0, 1, 1).data;\n  return 0.2126 * r + 0.7152 * g + 0.0722 * b < 140;\n}\n\nconst DURATION: Record<LightDirection, number> = { radial: 1400, horizontal: 1180, diagonal: 1360 };\nconst DUST = 195;\n\ntype Dust = { x: number; y: number; size: number; phase: number; twinkle: number; tone: 0 | 1 | 2; star: boolean };\nconst makeDust = (): Dust[] =>\n  Array.from({ length: DUST }, (_, i) => ({\n    x: Math.random(),\n    y: Math.random(),\n    size: 0.5 + Math.random() * 1.15,\n    phase: Math.random() * Math.PI * 2,\n    twinkle: 5 + Math.random() * 8,\n    tone: (i % 3) as 0 | 1 | 2,\n    star: i % 10 === 0,\n  }));\n\n/** On a light surface white light disappears, so the core takes the fringe colour and the dust its coloured tones. */\nconst inkFor = (p: LightPalette, light: boolean): LightPalette =>\n  light ? { ...p, core: p.outerFringe, sparkle: [p.sparkle[2], p.sparkle[1], p.sparkle[2]], strength: p.strength * 0.9 } : p;\n\nfunction starGlint(ctx: CanvasRenderingContext2D, x: number, y: number, arm: number, color: string, alpha: number) {\n  ctx.save();\n  ctx.globalAlpha = alpha;\n  ctx.strokeStyle = color;\n  ctx.lineWidth = 0.7;\n  ctx.beginPath();\n  ctx.moveTo(x - arm, y);\n  ctx.lineTo(x + arm, y);\n  ctx.moveTo(x, y - arm);\n  ctx.lineTo(x, y + arm);\n  ctx.stroke();\n  ctx.restore();\n}\n\ntype Wave = Required<Pick<LightWaveOptions, \"origin\" | \"direction\" | \"duration\">> & {\n  palette: LightPalette;\n  start: number;\n  swapped: boolean;\n  onMidpoint?: () => void;\n  onComplete?: () => void;\n};\n\ntype Settings = { palette: LightPalette; direction: LightDirection; duration: number };\n\nfunction createEngine(get: { root: () => HTMLDivElement | null; content: () => HTMLDivElement | null; veil: () => HTMLDivElement | null; canvas: () => HTMLCanvasElement | null; settings: () => Settings; settle: (on: boolean) => void }) {\n  let raf = 0;\n  let wave: Wave | null = null;\n  let level = 0;\n  let target = 0;\n  let chargeOrigin: LightPoint = { x: 0.5, y: 0.88 };\n  let last = 0;\n  let dust = makeDust();\n  let light = false;\n  let settleTimer = 0;\n  let w = 0;\n  let h = 0;\n  let dpr = 1;\n\n  const measure = () => {\n    const root = get.root();\n    const canvas = get.canvas();\n    if (!root || !canvas) return false;\n    w = root.offsetWidth;\n    h = root.offsetHeight;\n    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    if (canvas.width !== pw) canvas.width = pw;\n    if (canvas.height !== ph) canvas.height = ph;\n    light = isLightSurface(root);\n    return w > 0 && h > 0;\n  };\n\n  const idle = () => {\n    cancelAnimationFrame(raf);\n    raf = 0;\n    const canvas = get.canvas();\n    canvas?.getContext(\"2d\")?.clearRect(0, 0, canvas.width, canvas.height);\n    const content = get.content();\n    if (content) {\n      content.style.filter = \"\";\n      content.style.transform = \"\";\n      content.style.willChange = \"\";\n    }\n    const veil = get.veil();\n    if (veil) veil.style.opacity = \"0\";\n  };\n\n  const frame = (now: number) => {\n    const canvas = get.canvas();\n    const ctx = canvas?.getContext(\"2d\");\n    const content = get.content();\n    if (!canvas || !ctx) return idle();\n    const dt = last ? Math.min(64, now - last) : 16;\n    last = now;\n    // The charge follows the hand up at once and relaxes back down over about 220ms.\n    level = target >= level ? target : Math.max(target, level - dt / 220);\n\n    ctx.save();\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n    ctx.clearRect(0, 0, w, h);\n    ctx.globalCompositeOperation = light ? \"source-over\" : \"lighter\";\n\n    if (level > 0.01 && !wave) drawCharge(ctx, now, content);\n    if (wave) drawWave(ctx, now, wave, content);\n\n    ctx.restore();\n    if (wave || level > 0.005) raf = requestAnimationFrame(frame);\n    else idle();\n  };\n\n  const drawCharge = (ctx: CanvasRenderingContext2D, now: number, content: HTMLDivElement | null) => {\n    const p = inkFor(get.settings().palette, light);\n    const cx = chargeOrigin.x * w;\n    const cy = chargeOrigin.y * h;\n    const lv = clamp(level, 0, 1);\n    // A halo that contracts toward the finger as the charge builds.\n    const ring = Math.hypot(w, h) * 0.54 * (1 - lv * 0.72) + 26;\n    const band = 44 * (0.7 + lv * 0.35);\n    const g = ctx.createRadialGradient(cx, cy, Math.max(0, ring - band), cx, cy, ring + band);\n    g.addColorStop(0, \"rgba(0,0,0,0)\");\n    g.addColorStop(0.32, p.innerFringe);\n    g.addColorStop(0.54, p.core);\n    g.addColorStop(0.76, p.outerFringe);\n    g.addColorStop(1, \"rgba(0,0,0,0)\");\n    ctx.globalAlpha = (0.16 + lv * 0.38) * p.strength;\n    ctx.fillStyle = g;\n    ctx.fillRect(0, 0, w, h);\n    // A soft core under the finger.\n    const coreR = 20 + lv * 72;\n    const cg = ctx.createRadialGradient(cx, cy, 0, cx, cy, coreR);\n    cg.addColorStop(0, p.core);\n    cg.addColorStop(0.5, p.outerFringe);\n    cg.addColorStop(1, \"rgba(0,0,0,0)\");\n    ctx.globalAlpha = 0.16 + lv * 0.42;\n    ctx.fillStyle = cg;\n    ctx.beginPath();\n    ctx.arc(cx, cy, coreR, 0, Math.PI * 2);\n    ctx.fill();\n    // Dust pulled in toward the finger, stars streaking once it's past half.\n    for (const d of dust) {\n      const px = d.x * w;\n      const py = d.y * h;\n      const dx = cx - px;\n      const dy = cy - py;\n      const dist = Math.hypot(dx, dy) || 1;\n      const pull = lv * lv * 0.34;\n      const x = px + dx * pull;\n      const y = py + dy * pull;\n      ctx.globalAlpha = lv * (0.4 + 0.6 * Math.sin(now * 0.011 + d.phase)) * 0.68;\n      ctx.fillStyle = p.sparkle[d.tone];\n      ctx.beginPath();\n      ctx.arc(x, y, d.size * (0.7 + lv * 0.4), 0, Math.PI * 2);\n      ctx.fill();\n      if (lv > 0.5 && d.star) {\n        ctx.strokeStyle = p.sparkle[0];\n        ctx.lineWidth = 0.7;\n        ctx.globalAlpha = (lv - 0.5) * 0.55;\n        ctx.beginPath();\n        ctx.moveTo(x, y);\n        ctx.lineTo(x - (dx / dist) * 7 * lv, y - (dy / dist) * 7 * lv);\n        ctx.stroke();\n      }\n    }\n    if (content) {\n      content.style.willChange = \"transform, filter\";\n      content.style.transform = `scale(${(1 - lv * 0.012).toFixed(4)})`;\n      content.style.filter = `blur(${(lv * 1.1).toFixed(2)}px)`;\n    }\n  };\n\n  const drawWave = (ctx: CanvasRenderingContext2D, now: number, wv: Wave, content: HTMLDivElement | null) => {\n    const raw = clamp((now - wv.start) / wv.duration, 0, 1);\n    const o = opticsAt(raw);\n    if (o.swapped && !wv.swapped) {\n      wv.swapped = true;\n      wv.onMidpoint?.();\n    }\n    if (content) {\n      content.style.willChange = \"transform, filter\";\n      content.style.filter = o.blur > 0.05 ? `blur(${o.blur.toFixed(2)}px)` : \"\";\n      content.style.transform = Math.abs(o.scale - 1) > 0.0005 ? `scale(${o.scale.toFixed(4)})` : \"\";\n    }\n    const veil = get.veil();\n    if (veil) veil.style.opacity = o.veil.toFixed(3);\n    const p = inkFor(wv.palette, light);\n\n    if (wv.direction === \"horizontal\") {\n      // A ribbon of light scanning left to right, catching the top and bottom edges as it passes.\n      const x = -w * 0.14 + easeOutCubic(raw) * w * 1.28;\n      const half = Math.max(46, w * 0.14);\n      const g = ctx.createLinearGradient(x - half * 1.7, 0, x + half * 1.1, 0);\n      g.addColorStop(0, \"rgba(0,0,0,0)\");\n      g.addColorStop(0.28, p.innerFringe);\n      g.addColorStop(0.56, p.core);\n      g.addColorStop(0.76, p.outerFringe);\n      g.addColorStop(1, \"rgba(0,0,0,0)\");\n      ctx.globalAlpha = o.wave * p.strength;\n      ctx.fillStyle = g;\n      ctx.fillRect(0, 0, w, h);\n      for (const [edgeY, top] of [[0, true], [h, false]] as const) {\n        const e = ctx.createRadialGradient(x, edgeY, 2, x, edgeY, half * 1.35);\n        e.addColorStop(0, p.core);\n        e.addColorStop(0.5, p.outerFringe);\n        e.addColorStop(1, \"rgba(0,0,0,0)\");\n        ctx.globalAlpha = o.wave * 0.85;\n        ctx.fillStyle = e;\n        ctx.fillRect(0, top ? 0 : h * 0.5, w, h * 0.5);\n      }\n      for (const d of dust) {\n        const px = d.x * w;\n        const py = d.y * h;\n        const behind = x - px;\n        if (behind <= -22 || behind >= w * 0.95) continue;\n        const fresh = clamp(1 - Math.abs(behind) / (w * 0.65), 0.15, 1);\n        const a = o.dust * fresh * (0.35 + 0.65 * Math.sin(now * 0.01 * d.twinkle * 0.2 + d.phase)) * 0.88;\n        if (a <= 0.02) continue;\n        const sx = px + clamp(behind * 0.04, 0, 12);\n        ctx.globalAlpha = a;\n        ctx.fillStyle = p.sparkle[d.tone];\n        ctx.beginPath();\n        ctx.arc(sx, py, d.size * (0.75 + fresh * 0.45), 0, Math.PI * 2);\n        ctx.fill();\n        if (d.star && a > 0.4) starGlint(ctx, sx, py, d.size * 3, p.sparkle[0], a * 0.78);\n      }\n    } else if (wv.direction === \"diagonal\") {\n      // A wide, soft veil drifting across: no hard band.\n      const e = easeOutQuart(raw);\n      const x = -w * 0.35 + e * w * 1.7;\n      const r = Math.max(w * 0.46, 260);\n      const cy = h * 0.45 + (e - 0.5) * h * 0.18;\n      ctx.save();\n      ctx.translate(x, cy);\n      ctx.scale(1.45, 0.85);\n      const g = ctx.createRadialGradient(0, 0, 0, 0, 0, r);\n      g.addColorStop(0, p.core);\n      g.addColorStop(0.28, p.outerFringe);\n      g.addColorStop(0.58, p.innerFringe);\n      g.addColorStop(0.82, p.ambient);\n      g.addColorStop(1, \"rgba(0,0,0,0)\");\n      ctx.globalAlpha = o.wave * p.strength * 0.78;\n      ctx.fillStyle = g;\n      ctx.beginPath();\n      ctx.arc(0, 0, r, 0, Math.PI * 2);\n      ctx.fill();\n      ctx.restore();\n      for (const d of dust) {\n        const px = d.x * w;\n        const py = d.y * h;\n        const behind = x - px;\n        if (behind <= -r * 0.45) continue;\n        const fresh = clamp(1 - Math.abs(behind) / (w * 0.85), 0.14, 1);\n        const a = o.dust * fresh * (0.3 + 0.7 * Math.sin(now * 0.008 + d.phase)) * 0.58;\n        if (a <= 0.02) continue;\n        ctx.globalAlpha = a;\n        ctx.fillStyle = p.sparkle[d.tone];\n        ctx.beginPath();\n        ctx.arc(px + clamp(behind * 0.02, 0, 10), py, d.size * 0.9, 0, Math.PI * 2);\n        ctx.fill();\n      }\n    } else {\n      // A thin crest of light spreading from a point, a warm wash behind it.\n      const ox = wv.origin.x * w;\n      const oy = wv.origin.y * h;\n      const far = Math.max(Math.hypot(ox, oy), Math.hypot(w - ox, oy), Math.hypot(ox, h - oy), Math.hypot(w - ox, h - oy));\n      const radius = easeOutQuart(raw) * (far * 1.16 + 44);\n      const ring = Math.max(64, far * 0.22);\n      const g = ctx.createRadialGradient(ox, oy, Math.max(0, radius - ring * 0.92), ox, oy, radius + ring * 0.8);\n      g.addColorStop(0, \"rgba(0,0,0,0)\");\n      g.addColorStop(0.22, p.innerFringe);\n      g.addColorStop(0.42, p.ambient);\n      g.addColorStop(0.54, p.core);\n      g.addColorStop(0.7, p.outerFringe);\n      g.addColorStop(0.88, p.ambient);\n      g.addColorStop(1, \"rgba(0,0,0,0)\");\n      ctx.globalAlpha = o.wave * p.strength;\n      ctx.fillStyle = g;\n      ctx.fillRect(0, 0, w, h);\n      const wash = ctx.createRadialGradient(ox, oy, 0, ox, oy, Math.max(10, radius * 0.9));\n      wash.addColorStop(0, \"rgba(0,0,0,0)\");\n      wash.addColorStop(0.66, p.ambient);\n      wash.addColorStop(1, \"rgba(0,0,0,0)\");\n      ctx.globalAlpha = o.wave * 0.44;\n      ctx.fillStyle = wash;\n      ctx.fillRect(0, 0, w, h);\n      for (const d of dust) {\n        const px = d.x * w;\n        const py = d.y * h;\n        const dx = px - ox;\n        const dy = py - oy;\n        const dist = Math.hypot(dx, dy) || 1;\n        const behind = radius - dist;\n        if (behind <= -22) continue;\n        const fresh = clamp(1 - behind / (far * 1.05), 0.14, 1);\n        const a = o.dust * fresh * (0.35 + 0.65 * Math.sin(now * 0.01 + d.phase)) * 0.78;\n        if (a <= 0.02) continue;\n        const drift = clamp(behind * 0.03, 0, 12);\n        const sx = px + (dx / dist) * drift;\n        const sy = py + (dy / dist) * drift;\n        ctx.globalAlpha = a;\n        ctx.fillStyle = p.sparkle[d.tone];\n        ctx.beginPath();\n        ctx.arc(sx, sy, d.size * (0.72 + fresh * 0.45), 0, Math.PI * 2);\n        ctx.fill();\n        if (d.star && a > 0.36) starGlint(ctx, sx, sy, d.size * 3.1, p.sparkle[0], a * 0.75);\n      }\n    }\n\n    if (raw >= 1) {\n      wave = null;\n      wv.onComplete?.();\n    }\n  };\n\n  const run = () => {\n    if (!raf) {\n      last = 0;\n      raf = requestAnimationFrame(frame);\n    }\n  };\n\n  return {\n    wave(options: LightWaveOptions = {}) {\n      const s = get.settings();\n      // A wave still on its way in hands its change over first, so nothing is lost.\n      if (wave && !wave.swapped) {\n        wave.swapped = true;\n        wave.onMidpoint?.();\n      }\n      const previous = wave;\n      wave = null;\n      previous?.onComplete?.();\n      if (prefersReducedMotion() || !measure()) {\n        options.onMidpoint?.();\n        options.onComplete?.();\n        return;\n      }\n      const direction = options.direction ?? s.direction;\n      const duration = options.duration ?? (options.direction ? DURATION[direction] : s.duration);\n      dust = makeDust();\n      target = 0;\n      level = 0;\n      wave = {\n        start: performance.now(),\n        duration,\n        origin: options.origin ?? { x: 0.5, y: 0.88 },\n        direction,\n        palette: resolvePalette(options.palette ?? s.palette),\n        swapped: false,\n        onMidpoint: options.onMidpoint,\n        onComplete: options.onComplete,\n      };\n      // The rim blooms as the wave settles, then breathes out to its resting glow.\n      window.clearTimeout(settleTimer);\n      get.settle(true);\n      settleTimer = window.setTimeout(() => get.settle(false), duration * 0.85);\n      run();\n    },\n    charge(next: number, origin?: LightPoint) {\n      if (prefersReducedMotion()) return;\n      if (origin) chargeOrigin = origin;\n      if (next > 0.005 && !raf && !measure()) return;\n      target = clamp(next, 0, 1);\n      if (target > 0.005 || level > 0.005) run();\n    },\n    busy: () => wave !== null,\n    dispose() {\n      window.clearTimeout(settleTimer);\n      cancelAnimationFrame(raf);\n      raf = 0;\n      wave = null;\n    },\n  };\n}\n\ntype Engine = ReturnType<typeof createEngine>;\n\nconst MASK_EDGE: React.CSSProperties = {\n  WebkitMask: \"linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)\",\n  WebkitMaskComposite: \"xor\",\n  mask: \"linear-gradient(#000 0 0) content-box exclude, linear-gradient(#000 0 0)\",\n};\n\nexport interface LightSurfaceProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  children: React.ReactNode;\n  ref?: React.Ref<LightSurfaceHandle>;\n  /** The light's colours, by name or your own. */\n  palette?: LightPaletteName | LightPalette;\n  /** How waves cross it by default. */\n  direction?: LightDirection;\n  /** Default wave length in ms. */\n  duration?: number;\n  /** Keep the light in the rim: the surface is on. */\n  lit?: boolean;\n  /** A pill keeps its rim light along its long edges. */\n  shape?: \"card\" | \"capsule\";\n  /** What the content dims toward under a wave; a surface with its own dark finish passes its own dark. */\n  veil?: string;\n  /** @deprecated Ignored. Kept so components installed with an earlier copy of this file still compile. */\n  cascadeKey?: string;\n}\n\n/** A card the light runs through. Give it a radius with className; it takes the theme's card colour and border. */\nexport function LightSurface({\n  children,\n  ref,\n  palette = \"azure\",\n  direction = \"radial\",\n  duration,\n  lit = false,\n  shape = \"card\",\n  veil = \"var(--background)\",\n  cascadeKey,\n  className = \"\",\n  onPointerMove,\n  onPointerLeave,\n  ...props\n}: LightSurfaceProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const contentRef = React.useRef<HTMLDivElement>(null);\n  const veilRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const sheenRef = React.useRef<HTMLDivElement>(null);\n  const engineRef = React.useRef<Engine | null>(null);\n  const [settling, setSettling] = React.useState(false);\n  const pal = resolvePalette(palette);\n  const live = React.useRef<Settings>({ palette: pal, direction, duration: duration ?? DURATION[direction] });\n  React.useLayoutEffect(() => {\n    live.current = { palette: pal, direction, duration: duration ?? DURATION[direction] };\n  });\n\n  const engine = React.useCallback(\n    () =>\n      (engineRef.current ??= createEngine({\n        root: () => rootRef.current,\n        content: () => contentRef.current,\n        veil: () => veilRef.current,\n        canvas: () => canvasRef.current,\n        settings: () => live.current,\n        settle: (on: boolean) => setSettling(on),\n      })),\n    [],\n  );\n\n  React.useEffect(\n    () => () => {\n      engineRef.current?.dispose();\n      engineRef.current = null;\n    },\n    [],\n  );\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      wave: (o) => engine().wave(o),\n      charge: (l, o) => engine().charge(l, o),\n      busy: () => engineRef.current?.busy() ?? false,\n      element: () => rootRef.current,\n    }),\n    [engine],\n  );\n\n  void cascadeKey;\n  const capsule = shape === \"capsule\";\n  const rim = !lit ? 0 : capsule || settling ? 0.92 : 0.72;\n  const bezel = !lit ? 0 : capsule ? 0.95 : settling ? 0.96 : 0.84;\n  const card = (a: number) => `color-mix(in oklab, var(--card) ${a}%, transparent)`;\n\n  return (\n    <div\n      ref={rootRef}\n      className={`relative isolate overflow-clip border border-border bg-card text-card-foreground ${className}`}\n      onPointerMove={(e) => {\n        onPointerMove?.(e);\n        const sheen = sheenRef.current;\n        const root = rootRef.current;\n        if (e.pointerType !== \"mouse\" || !sheen || !root) return;\n        const r = root.getBoundingClientRect();\n        sheen.style.background = `radial-gradient(240px circle at ${Math.round(e.clientX - r.left)}px ${Math.round(e.clientY - r.top)}px, color-mix(in oklab, var(--foreground) 24%, transparent), transparent 68%)`;\n        sheen.style.opacity = \"1\";\n      }}\n      onPointerLeave={(e) => {\n        onPointerLeave?.(e);\n        if (sheenRef.current) sheenRef.current.style.opacity = \"0\";\n      }}\n      {...props}\n    >\n      <div aria-hidden className=\"pointer-events-none absolute inset-0 rounded-[inherit]\" style={{ background: \"linear-gradient(180deg, color-mix(in oklab, var(--foreground) 3.5%, transparent) 0%, transparent 26%)\" }} />\n      <div\n        aria-hidden\n        className=\"pointer-events-none absolute inset-0 rounded-[inherit] transition-opacity duration-[1400ms] ease-out\"\n        style={{\n          opacity: rim,\n          background: capsule\n            ? `radial-gradient(62% 38% at 10% 6%, ${pal.rimPrimary}, transparent 68%), radial-gradient(68% 42% at 90% 96%, ${pal.rimSecondary}, transparent 68%), radial-gradient(50% 34% at 92% 8%, ${pal.rimAccent}, transparent 72%)`\n            : `radial-gradient(52% 29% at 8% 4%, ${pal.rimPrimary}, transparent 66%), radial-gradient(54% 31% at 92% 96%, ${pal.rimSecondary}, transparent 67%), radial-gradient(44% 25% at 92% 5%, ${pal.rimAccent}, transparent 69%), radial-gradient(46% 23% at 16% 97%, ${pal.rimSecondary}, transparent 67%)`,\n        }}\n      />\n      <div\n        aria-hidden\n        className=\"pointer-events-none absolute inset-0 rounded-[inherit] transition-opacity duration-[1400ms] ease-out\"\n        style={{\n          opacity: lit ? 1 : 0,\n          background: capsule\n            ? `radial-gradient(76% 68% at 50% 50%, ${card(88)} 0%, ${card(52)} 66%, transparent 100%)`\n            : `radial-gradient(82% 77% at 50% 50%, ${card(96)} 0%, ${card(82)} 70%, ${card(20)} 90%, transparent 100%)`,\n        }}\n      />\n      <div\n        aria-hidden\n        className=\"pointer-events-none absolute inset-0 rounded-[inherit] transition-opacity duration-[1200ms] ease-out\"\n        style={{\n          ...MASK_EDGE,\n          padding: capsule ? 1.5 : 1.25,\n          opacity: bezel,\n          background: `linear-gradient(135deg, ${pal.rimPrimary} 0%, color-mix(in oklab, var(--foreground) 26%, transparent) 28%, color-mix(in oklab, var(--foreground) 6%, transparent) 54%, ${pal.rimSecondary} 100%)`,\n        }}\n      />\n      <div ref={sheenRef} aria-hidden className=\"pointer-events-none absolute inset-0 rounded-[inherit] opacity-0 transition-opacity duration-300\" style={{ ...MASK_EDGE, padding: 1 }} />\n      <div ref={contentRef} className=\"relative z-10 h-full w-full\">\n        {children}\n      </div>\n      <div ref={veilRef} aria-hidden className=\"pointer-events-none absolute inset-0 z-20 rounded-[inherit] opacity-0\" style={{ background: veil }} />\n      <canvas ref={canvasRef} aria-hidden className=\"pointer-events-none absolute inset-0 z-30 size-full rounded-[inherit]\" />\n    </div>\n  );\n}\n\n/**\n * Holds what a component shows until the light covering a change reaches its peak.\n * `next` is what the props say now; `key` changes only for changes worth a wave.\n * Returns what to show.\n */\nexport function useLightHeld<T>(next: T, key: string | number | boolean, surface: React.RefObject<LightSurfaceHandle | null>, wave: () => LightWaveOptions | null) {\n  const [held, setHeld] = React.useState<{ key: typeof key; value: T }>({ key, value: next });\n  const latest = React.useRef({ next, key });\n  React.useLayoutEffect(() => {\n    latest.current = { next, key };\n  });\n  const pending = held.key !== key;\n  React.useEffect(() => {\n    if (!pending) return;\n    const s = surface.current;\n    const options = wave();\n    const land = () => setHeld({ key: latest.current.key, value: latest.current.next });\n    // A light already crossing carries the change; otherwise one is sent for it.\n    if (!s || !options || s.busy()) {\n      const id = requestAnimationFrame(land);\n      return () => cancelAnimationFrame(id);\n    }\n    s.wave({ ...options, onMidpoint: land });\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [pending, key]);\n  return pending ? held.value : next;\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/level-dial. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}