{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"dither-veil","type":"registry:component","title":"Dither veil","description":"A fine 8×8 Bayer privacy shield and secret field for API keys, signing secrets and balances: full-viewport optical veil, lazy on-demand fetch, copy-while-veiled and inherent edge-condensing auto-lock.","author":"Hairline UI","dependencies":["lucide-react"],"files":[{"path":"registry/dither-veil.tsx","type":"registry:component","content":"// Hairline UI · dither-veil · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { Check, Copy, Eye, EyeOff } from \"lucide-react\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  createSpring,\n  interactionIcon,\n  useInteractionActivity,\n  useInteractionReducedMotion,\n  type Spring,\n} from \"./ui-interaction-motion\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * DITHER VEIL & DITHER SECRET: optical 8×8 Bayer privacy layer\n *\n * Two pieces for real production infrastructure:\n *\n *   DitherVeil    an inline <span> primitive for balances, salaries\n *                 and figures inside <h1>, <p> and <td> (0px width shift).\n *                 Scrubbing a pointer parts the fine 8×8 Bayer grain in a\n *                 magnetic circular lens; clicking fires a directional\n *                 shutter sweep that clears to 100% unobstructed ink.\n *\n *   DitherSecret  a complete hairline secret field for API keys, webhook\n *                 signing secrets, env vars and card numbers: a single\n *                 full-viewport optical Bayer pane covers 100% of the value\n *                 slot edge-to-edge up to a hairline divider and Reveal/Copy\n *                 controls. Supports lazy server-side fetching via onReveal()\n *                 with a full-width optical Bayer scan while pending, and\n *                 copies straight to clipboard even while veiled without\n *                 mounting plaintext into the DOM.\n *\n * Inherent auto-relock (no artificial progress bar):\n *   When autoHideMs is set, the secret stays 100% crystal-clear while you\n *   read it; during the final ~2.2 seconds, fine 8×8 Bayer frost condenses\n *   organically inward from both outer edges before locking shut. Moving\n *   your pointer back over the secret pushes the condensing frost back out\n *   and resets the hold window.\n * ───────────────────────────────────────────────────────── */\n\nexport type DitherVeilTone = \"ink\" | \"primary\" | \"spectral\";\n\nexport interface DitherVeilHandle {\n  /** Flash a directional optical Bayer pulse across the element (e.g. emerald lift on copy). */\n  flash: (kind?: \"copy\" | \"error\") => void;\n}\n\nexport interface DitherVeilProps extends Omit<React.HTMLAttributes<HTMLSpanElement>, \"children\"> {\n  ref?: React.Ref<DitherVeilHandle>;\n  /** Sensitive figure, key or inline node. Exact typography and width stay intact. */\n  children: React.ReactNode;\n  /** Controlled revealed state. Omit for uncontrolled click-to-toggle via defaultRevealed. */\n  revealed?: boolean;\n  defaultRevealed?: boolean;\n  onRevealedChange?: (revealed: boolean) => void;\n  /** True while fetching a secret lazily from the server: runs a horizontal optical Bayer scan. */\n  pending?: boolean;\n  /** Fill the full container viewport (used inside DitherSecret) instead of tight inline text bounds. */\n  fill?: boolean;\n  /** Scrubbing a cursor or finger magnetically parts the Bayer grain underneath to peek. */\n  peek?: boolean;\n  /** Radius of the magnetic pointer peek aperture in CSS px (default 34). */\n  peekRadius?: number;\n  /** Clicking or pressing Enter/Space toggles full reveal (default true). */\n  toggleOnClick?: boolean;\n  /** Auto re-veil after this many ms once revealed (0 disables). Grain condenses inherently from the edges before locking. */\n  autoHideMs?: number;\n  /** Immediately re-veil when the window or tab loses focus. */\n  hideOnBlur?: boolean;\n  /** Subtle ambient optical shimmer while veiled (false sleeps completely when pointer is away). */\n  ambient?: boolean;\n  /** Rim & active accent palette: \"ink\" (monochrome hairline, default), \"primary\" (--primary rim), or \"spectral\". */\n  tone?: DitherVeilTone;\n  /** Optical Bayer grain pitch in CSS px (default 1.5). */\n  cellSize?: number;\n  /** Accessible name describing what is masked, e.g. \"Account balance\" or \"Signing secret\". */\n  label?: string;\n  /** Opt-in quiet Web Audio cues on reveal / re-veil (from ui-sounds.ts). */\n  sound?: boolean;\n}\n\ntype Rgb = [number, number, number];\n\n// Recursive 8×8 ordered Bayer threshold matrix (64 tonal steps -> fine halftone grain, never coarse blocks).\nconst BAYER8: Float32Array = (() => {\n  const m = [\n    [0, 32, 8, 40, 2, 34, 10, 42],\n    [48, 16, 56, 24, 50, 18, 58, 26],\n    [12, 44, 4, 36, 14, 46, 6, 38],\n    [60, 28, 52, 20, 62, 30, 54, 22],\n    [3, 35, 11, 43, 1, 33, 9, 41],\n    [51, 19, 59, 27, 49, 17, 57, 25],\n    [15, 47, 7, 39, 13, 45, 5, 37],\n    [63, 31, 55, 23, 61, 29, 53, 21],\n  ];\n  const out = new Float32Array(64);\n  for (let y = 0; y < 8; y++) {\n    for (let x = 0; x < 8; x++) {\n      out[(y << 3) | x] = (m[y][x] + 0.5) / 64;\n    }\n  }\n  return out;\n})();\n\nconst SPECTRAL_STOPS: Rgb[] = [\n  [56, 189, 248],\n  [129, 140, 248],\n  [232, 121, 249],\n  [251, 113, 133],\n  [251, 191, 36],\n  [52, 211, 153],\n];\n\nconst IS_LE = (() => {\n  const b = new ArrayBuffer(4);\n  new Uint32Array(b)[0] = 0x0a0b0c0d;\n  return new Uint8Array(b)[0] === 0x0d;\n})();\n\nfunction packRgba(r: number, g: number, b: number, a: number): number {\n  const ri = r < 0 ? 0 : r > 255 ? 255 : r | 0;\n  const gi = g < 0 ? 0 : g > 255 ? 255 : g | 0;\n  const bi = b < 0 ? 0 : b > 255 ? 255 : b | 0;\n  const ai = a < 0 ? 0 : a > 255 ? 255 : a | 0;\n  return IS_LE ? ((ai << 24) | (bi << 16) | (gi << 8) | ri) >>> 0 : ((ri << 24) | (gi << 16) | (bi << 8) | ai) >>> 0;\n}\n\nconst clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);\nconst clamp01 = (v: number) => (Number.isFinite(v) ? clamp(v, 0, 1) : 0);\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t;\n\nfunction sampleSpectral(pos: number, out: Rgb): Rgb {\n  const n = SPECTRAL_STOPS.length;\n  const w = ((pos % 1) + 1) % 1;\n  const sc = w * n;\n  const i0 = Math.floor(sc) % n;\n  const i1 = (i0 + 1) % n;\n  const f = sc - Math.floor(sc);\n  const a = SPECTRAL_STOPS[i0];\n  const b = SPECTRAL_STOPS[i1];\n  out[0] = a[0] + (b[0] - a[0]) * f;\n  out[1] = a[1] + (b[1] - a[1]) * f;\n  out[2] = a[2] + (b[2] - a[2]) * f;\n  return out;\n}\n\nlet swatchCtx: CanvasRenderingContext2D | null = null;\nfunction cssToRgb(host: Element, cssColor: string, fallback: Rgb): Rgb {\n  const probe = document.createElement(\"span\");\n  probe.style.display = \"none\";\n  probe.style.color = cssColor;\n  host.appendChild(probe);\n  const resolved = getComputedStyle(probe).color;\n  probe.remove();\n  if (/^rgba?\\(/.test(resolved)) {\n    const m = resolved.match(/[\\d.]+/g)?.map(Number);\n    if (m && m.length >= 3) return [m[0], m[1], m[2]];\n  }\n  if (!swatchCtx) {\n    const c = document.createElement(\"canvas\");\n    c.width = 1;\n    c.height = 1;\n    swatchCtx = c.getContext(\"2d\", { willReadFrequently: true });\n  }\n  if (swatchCtx) {\n    swatchCtx.clearRect(0, 0, 1, 1);\n    swatchCtx.fillStyle = \"#808080\";\n    swatchCtx.fillStyle = resolved;\n    swatchCtx.fillRect(0, 0, 1, 1);\n    const d = swatchCtx.getImageData(0, 0, 1, 1).data;\n    return [d[0], d[1], d[2]];\n  }\n  return fallback;\n}\n\nfunction detectLightHost(el: Element | null): boolean {\n  if (!el) return false;\n  const rgb = cssToRgb(el, getComputedStyle(el).color, [240, 240, 240]);\n  return (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) / 255 < 0.52;\n}\n\nconst SHUTTER_SPRING = { stiffness: 175, damping: 24 };\nconst PEEK_SPRING = { stiffness: 260, damping: 26 };\n\nexport function DitherVeil({\n  ref,\n  children,\n  revealed: controlledRevealed,\n  defaultRevealed = false,\n  onRevealedChange,\n  pending = false,\n  fill = false,\n  peek = true,\n  peekRadius = 34,\n  toggleOnClick = true,\n  autoHideMs = 0,\n  hideOnBlur = false,\n  ambient = true,\n  tone = \"ink\",\n  cellSize = 1.5,\n  label,\n  sound = false,\n  className = \"\",\n  onClick,\n  onKeyDown,\n  ...props\n}: DitherVeilProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLSpanElement>();\n  const [ownRevealed, setOwnRevealed] = React.useState(defaultRevealed);\n  const revealed = controlledRevealed ?? ownRevealed;\n\n  const setRevealed = React.useCallback(\n    (next: boolean, playCue = true) => {\n      if (controlledRevealed === undefined) setOwnRevealed(next);\n      onRevealedChange?.(next);\n      if (sound && playCue) playSound(next ? \"unfold\" : \"fold\", 0.35);\n    },\n    [controlledRevealed, onRevealedChange, sound],\n  );\n\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const contentRef = React.useRef<HTMLSpanElement>(null);\n\n  const cfgRef = React.useRef({ revealed, pending, fill, peek, peekRadius, autoHideMs, ambient, tone, cellSize, reduced });\n  React.useLayoutEffect(() => {\n    cfgRef.current = { revealed, pending, fill, peek, peekRadius, autoHideMs, ambient, tone, cellSize, reduced };\n  });\n\n  const relockCbRef = React.useRef<() => void>(() => {});\n  React.useLayoutEffect(() => {\n    relockCbRef.current = () => setRevealed(false);\n  });\n\n  const engineRef = React.useRef<{\n    w: number;\n    h: number;\n    dpr: number;\n    isLight: boolean;\n    ink: Rgb;\n    primary: Rgb;\n    time: number;\n    shutterOriginU: number;\n    shutter: Spring;\n    peekOn: Spring;\n    hoverOn: Spring;\n    ptrX: Spring;\n    ptrY: Spring;\n    hovered: boolean;\n    /** Inherent auto-relock elapsed ms while revealed & not hovered (no external progress bar). */\n    relockElapsed: number;\n    relockFired: boolean;\n    flashKind: \"none\" | \"copy\" | \"error\";\n    flashAge: number;\n    flashLife: number;\n    lastMaskKey: string;\n    refreshTheme: () => void;\n    triggerFlash: (kind: \"copy\" | \"error\") => void;\n    stepAndDraw: (dt: number) => boolean;\n    wake: () => void;\n  } | null>(null);\n\n  const rafRef = React.useRef(0);\n  const runningRef = React.useRef(false);\n  const wakeRef = React.useRef<() => void>(() => {});\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      flash(kind = \"copy\") {\n        engineRef.current?.triggerFlash(kind);\n      },\n    }),\n    [],\n  );\n\n  // Optional window-blur safety lock\n  React.useEffect(() => {\n    if (!revealed || !hideOnBlur) return;\n    const hide = () => setRevealed(false, false);\n    const onVis = () => {\n      if (document.hidden) hide();\n    };\n    window.addEventListener(\"blur\", hide);\n    document.addEventListener(\"visibilitychange\", onVis);\n    return () => {\n      window.removeEventListener(\"blur\", hide);\n      document.removeEventListener(\"visibilitychange\", onVis);\n    };\n  }, [revealed, hideOnBlur, setRevealed]);\n\n  // Core 8×8 Bayer Uint32Array optical veil, magnetic peek, inherent edge condensation & flash sweep\n  React.useEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!root || !canvas || !ctx) return;\n\n    const gridCanvas = document.createElement(\"canvas\");\n    const gridCtx = gridCanvas.getContext(\"2d\");\n    if (!gridCtx) return;\n    let gridImg: ImageData | null = null;\n    let gridU32: Uint32Array | null = null;\n    let gCols = 0;\n    let gRows = 0;\n\n    const ensureGrid = (cols: number, rows: number) => {\n      if (cols === gCols && rows === gRows && gridImg && gridU32) return;\n      gCols = cols;\n      gRows = rows;\n      gridCanvas.width = cols;\n      gridCanvas.height = rows;\n      gridImg = gridCtx.createImageData(cols, rows);\n      gridU32 = new Uint32Array(gridImg.data.buffer);\n    };\n\n    // Every spring frame wakes the canvas loop directly -> makes stalled frames impossible.\n    const wakeOnSpring = () => wakeRef.current();\n    const initRev = cfgRef.current.revealed ? 1 : 0;\n    const shutter = createSpring(initRev, SHUTTER_SPRING, wakeOnSpring, 0.002);\n    const peekOn = createSpring(0, PEEK_SPRING, wakeOnSpring, 0.003);\n    const hoverOn = createSpring(0, PEEK_SPRING, wakeOnSpring, 0.003);\n    const ptrX = createSpring(0, { stiffness: 320, damping: 28 }, wakeOnSpring, 0.2);\n    const ptrY = createSpring(0, { stiffness: 320, damping: 28 }, wakeOnSpring, 0.2);\n    const specRgb: Rgb = [0, 0, 0];\n\n    const eng: NonNullable<typeof engineRef.current> = {\n      w: 0,\n      h: 0,\n      dpr: Math.min(2, window.devicePixelRatio || 1),\n      isLight: false,\n      ink: [164, 170, 182],\n      primary: [48, 93, 222],\n      time: 0.7,\n      shutterOriginU: 0,\n      shutter,\n      peekOn,\n      hoverOn,\n      ptrX,\n      ptrY,\n      hovered: false,\n      relockElapsed: 0,\n      relockFired: false,\n      flashKind: \"none\",\n      flashAge: 0,\n      flashLife: 0.56,\n      lastMaskKey: \"\",\n\n      refreshTheme() {\n        eng.isLight = detectLightHost(root);\n        eng.primary = cssToRgb(root, \"var(--primary)\", [48, 93, 222]);\n        // Refined neutral optical grain (never loud coloured blocks at rest)\n        eng.ink = eng.isLight ? [72, 80, 94] : [168, 174, 186];\n      },\n\n      triggerFlash(kind) {\n        if (cfgRef.current.reduced) return;\n        eng.flashKind = kind;\n        eng.flashAge = 0;\n        eng.flashLife = kind === \"copy\" ? 0.56 : 0.44;\n        // Copying while revealed gently resets the inherent auto-relock hold so it never locks mid-action\n        if (kind === \"copy\") eng.relockElapsed = 0;\n        eng.wake();\n      },\n\n      stepAndDraw(dt: number): boolean {\n        const w = eng.w;\n        const h = eng.h;\n        if (w <= 0 || h <= 0) return false;\n\n        const {\n          revealed: isRev,\n          pending: isPending,\n          fill: isFill,\n          peek: allowPeek,\n          peekRadius: rawR,\n          autoHideMs: hideMs,\n          ambient: isAmb,\n          tone: curTone,\n          cellSize: rawCell,\n          reduced: isRed,\n        } = cfgRef.current;\n\n        const sh = clamp01(eng.shutter.get());\n        const pk = allowPeek && !isRev && !isPending && !isRed ? clamp01(eng.peekOn.get()) : 0;\n        const hv = !allowPeek && !isRev && !isPending && !isRed ? clamp01(eng.hoverOn.get()) : 0;\n        const px = eng.ptrX.get();\n        const py = eng.ptrY.get();\n        const radius = Math.max(18, rawR);\n\n        // Coordinate offset from canvas space to contentRef border-box space:\n        // fill mode: canvas is inset-1 (+4px, +4px) inside contentRef\n        // inline mode: canvas bleeds -inset-x-[5px] -inset-y-[2px] (-5px, -2px) around contentRef\n        const offX = isFill ? 4 : -5;\n        const offY = isFill ? 4 : -2;\n\n        if ((isAmb || isPending) && !isRed) eng.time += dt;\n\n        // Advance active copy/error Bayer flash\n        if (eng.flashKind !== \"none\" && dt > 0) {\n          eng.flashAge += dt;\n          if (eng.flashAge >= eng.flashLife) eng.flashKind = \"none\";\n        }\n\n        // INHERENT AUTO-RELOCK: no bottom progress bar!\n        // Secret stays 100% clear while reading; during the final ~2.2s, fine Bayer frost condenses inward from both edges.\n        // Moving the pointer back over the secret smoothly dissolves the frost back out and holds it open.\n        let condense = 0;\n        if (isRev && hideMs > 0 && sh >= 0.96 && !isRed) {\n          if (eng.hovered) {\n            eng.relockElapsed = Math.max(0, eng.relockElapsed - dt * 2600);\n          } else {\n            eng.relockElapsed += dt * 1000;\n          }\n          const warnWindow = Math.min(2400, hideMs * 0.45);\n          const warnStart = Math.max(400, hideMs - warnWindow);\n          if (eng.relockElapsed > warnStart) {\n            condense = clamp01((eng.relockElapsed - warnStart) / Math.max(1, hideMs - warnStart));\n          }\n          if (eng.relockElapsed >= hideMs && !eng.relockFired) {\n            eng.relockFired = true;\n            eng.shutterOriginU = 0.5;\n            relockCbRef.current();\n          }\n        }\n\n        // 1) Synchronise underlying text visibility / aperture mask (100% crisp ink when revealed, 0 bleed when veiled)\n        const content = contentRef.current;\n        if (content) {\n          let nextKey: string;\n          if (sh >= 0.985) {\n            nextKey = \"full\";\n            if (eng.lastMaskKey !== nextKey) {\n              eng.lastMaskKey = nextKey;\n              content.style.opacity = \"1\";\n              content.style.maskImage = \"none\";\n              content.style.webkitMaskImage = \"none\";\n            }\n          } else if (sh <= 0.01 && pk <= 0.015) {\n            nextKey = \"hidden\";\n            if (eng.lastMaskKey !== nextKey) {\n              eng.lastMaskKey = nextKey;\n              content.style.opacity = \"0\";\n              content.style.maskImage = \"none\";\n              content.style.webkitMaskImage = \"none\";\n            }\n          } else if (sh > 0.01) {\n            // Directional elliptical shutter opening smoothly from click X\n            const oxPx = eng.shutterOriginU * w;\n            const maxDist = Math.max(oxPx, w - oxPx) + 18;\n            const curR = sh * maxDist;\n            const soft = 16;\n            const mx = Math.round(oxPx + offX);\n            nextKey = `sh:${mx}:${Math.round(curR)}`;\n            if (eng.lastMaskKey !== nextKey) {\n              eng.lastMaskKey = nextKey;\n              const grad = `radial-gradient(ellipse ${Math.round(curR * 1.15)}px ${Math.round(h * 2.1)}px at ${mx}px 50%, #000 ${Math.max(0, Math.round(curR - soft))}px, transparent ${Math.round(curR + soft)}px)`;\n              content.style.opacity = \"1\";\n              content.style.maskImage = grad;\n              content.style.webkitMaskImage = grad;\n            }\n          } else {\n            // Magnetic circular peek aperture aligned subpixel-exact with the Bayer canvas\n            const rPx = radius * pk;\n            const inner = Math.max(0, rPx * 0.68);\n            const outer = rPx * 1.04;\n            const mx = Math.round(px + offX);\n            const my = Math.round(py + offY);\n            nextKey = `pk:${mx}:${my}:${Math.round(rPx)}`;\n            if (eng.lastMaskKey !== nextKey) {\n              eng.lastMaskKey = nextKey;\n              const grad = `radial-gradient(circle at ${mx}px ${my}px, #000 ${inner.toFixed(1)}px, transparent ${outer.toFixed(1)}px)`;\n              content.style.opacity = \"1\";\n              content.style.maskImage = grad;\n              content.style.webkitMaskImage = grad;\n            }\n          }\n        }\n\n        // 2) Render optical 8×8 Bayer canvas ONLY when veiled, transitioning, pending, condensing, or flashing\n        ctx.setTransform(eng.dpr, 0, 0, eng.dpr, 0, 0);\n        ctx.clearRect(0, 0, w, h);\n\n        const needsPaint = sh < 0.985 || condense > 0.01 || eng.flashKind !== \"none\" || isPending;\n        if (needsPaint) {\n          const pitch = clamp(rawCell, 1.25, 3.5);\n          const cols = Math.max(1, Math.ceil(w / pitch));\n          const rows = Math.max(1, Math.ceil(h / pitch));\n          ensureGrid(cols, rows);\n          const u32 = gridU32!;\n          u32.fill(0);\n\n          const oxPx = eng.shutterOriginU * w;\n          const maxDist = Math.max(oxPx, w - oxPx) + 18;\n          const shutterR = sh * maxDist;\n          const rPeek = radius * pk;\n          const t = eng.time;\n          const isSpec = curTone === \"spectral\";\n          const isPrim = curTone === \"primary\";\n\n          // Pending fetch scanline sweeps smoothly edge-to-edge\n          const scanU = ((t * 0.92) % 1.32) - 0.16;\n          // Copy / error flash wavefront sweeps left -> right across entire viewport\n          const fk = eng.flashKind !== \"none\" ? eng.flashAge / eng.flashLife : 0;\n          const flashFront = (1 - Math.pow(1 - fk, 2.15)) * 1.18 - 0.06;\n          const flashFade = Math.sin(Math.PI * Math.pow(fk, 0.72));\n\n          const rimAccent: Rgb = isPrim\n            ? eng.isLight\n              ? eng.primary\n              : [96, 165, 250]\n            : eng.isLight\n              ? [37, 99, 235]\n              : [236, 242, 255];\n          const copyRgb: Rgb = eng.isLight ? [5, 150, 105] : [52, 211, 153];\n          const errRgb: Rgb = eng.isLight ? [220, 38, 38] : [248, 113, 113];\n          const paneTintAlpha = eng.isLight ? 11 : 12;\n\n          for (let r = 0; r < rows; r++) {\n            const cy = (r + 0.5) * pitch;\n            const v = cy / h;\n            const vFade = isFill ? Math.min(1, Math.min(v, 1 - v) * 9) : Math.min(1, Math.min(v, 1 - v) * 6.5);\n            const rowOff = r * cols;\n            const bRow = (r & 7) << 3;\n\n            for (let c = 0; c < cols; c++) {\n              const cx = (c + 0.5) * pitch;\n              const u = cx / w;\n              const uFade = isFill ? Math.min(1, Math.min(u, 1 - u) * 26) : Math.min(1, Math.min(u, 1 - u) * 14);\n\n              let density = 0;\n              let rimBoost = 0;\n              let flashBoost = 0;\n              let paneMask = 0;\n\n              // A) Main optical veil (active while veiled or mid-shutter)\n              if (sh < 0.985) {\n                paneMask = 1;\n                // Layered diagonal optical sheen spanning [0.14..0.76] so all 64 Bayer halftone levels breathe\n                // organically like etched frosted glass — never collapsing into a flat 50% checkerboard!\n                const phase = isAmb && !isRed ? t : 0.7;\n                const w1 = Math.sin(u * 5.4 - v * 2.2 + phase * 0.95);\n                const w2 = Math.cos(u * 11.8 + v * 4.6 - phase * 0.55);\n                const w3 = Math.sin((u * 2.6 + v * 1.4) + phase * 0.35);\n                const sheen = 0.43 + 0.19 * w1 + 0.1 * w2 + 0.07 * w3;\n                const edgeK = isFill ? 0.7 + 0.3 * vFade * uFade : 0.5 + 0.5 * vFade * uFade;\n                density = clamp01(sheen * edgeK);\n\n                // While fetching secret from API: crisp horizontal optical scan inside the Bayer grain\n                if (isPending && !isRed) {\n                  const dScan = u - scanU;\n                  const band = Math.exp(-(dScan * dScan) / 0.02);\n                  density = Math.min(0.95, density + band * 0.36);\n                  rimBoost = Math.max(rimBoost, band * 0.95);\n                }\n\n                // Subtle magnetic ferrofluid shimmer on hover when plaintext isn't loaded yet (peek=false)\n                if (hv > 0.015) {\n                  const dist = Math.hypot(cx - px, cy - py);\n                  const swell = Math.exp(-(dist * dist) / (radius * radius * 1.45)) * hv;\n                  density = Math.min(0.92, density + swell * 0.24);\n                  rimBoost = Math.max(rimBoost, swell * 0.58);\n                }\n\n                // Magnetic circular lens parting around pointer when peek is enabled\n                if (pk > 0.015) {\n                  const dist = Math.hypot(cx - px, cy - py);\n                  if (dist < rPeek * 0.72) {\n                    density = 0;\n                    paneMask = 0;\n                  } else if (dist < rPeek * 1.48) {\n                    const k = (dist - rPeek * 0.72) / (rPeek * 0.76);\n                    const ring = Math.exp(-((k - 0.34) ** 2) / 0.048) * pk;\n                    const openK = clamp01(k * 1.25);\n                    density = density * openK + ring * 0.44;\n                    paneMask *= openK;\n                    rimBoost = Math.max(rimBoost, ring);\n                  }\n                }\n\n                // Directional shutter clearing cleanly out from click origin across full viewport\n                if (sh > 0.01) {\n                  const distFromOrigin = Math.abs(cx - oxPx);\n                  const diff = distFromOrigin - shutterR;\n                  if (diff < -10) {\n                    density = 0;\n                    paneMask = 0;\n                  } else if (diff < 24) {\n                    const front = Math.exp(-((diff - 2) ** 2) / 72);\n                    const clearK = clamp01((diff + 10) / 18);\n                    density = density * clearK + front * 0.52;\n                    paneMask *= clearK;\n                    rimBoost = Math.max(rimBoost, front);\n                  }\n                }\n              }\n\n              // B) Inherent edge-condensing Bayer frost during final phase of autoHideMs (NO progress bar!)\n              if (condense > 0.01 && sh >= 0.96) {\n                const edgeDist = Math.min(u, 1 - u) * 2; // 0 at outer left/right viewport edges, 1 at centre\n                const reach = Math.pow(condense, 1.32) * 0.74;\n                const creep = clamp01((reach - edgeDist + 0.14) / 0.24) * condense;\n                const organic = 0.72 + 0.28 * Math.sin(u * 26 + v * 14 + t * 2.2);\n                const frost = creep * organic * 0.64 * (0.58 + 0.42 * vFade);\n                if (frost > density) density = frost;\n                paneMask = Math.max(paneMask, creep * 0.65);\n              }\n\n              // C) Copy emerald lift / error flash wavefront sweeping edge-to-edge across the viewport\n              if (eng.flashKind !== \"none\") {\n                const df = u - flashFront;\n                const lead = Math.exp(-(df * df) / 0.016);\n                const tail = df < 0 ? Math.exp(df / 0.2) * 0.5 : 0;\n                flashBoost = (lead + tail) * flashFade * (0.58 + 0.42 * Math.sin(Math.PI * v));\n                if (flashBoost * 0.76 > density) density = flashBoost * 0.76;\n              }\n\n              const bayer = BAYER8[bRow | (c & 7)];\n              const hit = density > 0.03 ? clamp01((density - bayer + 0.055) / 0.12) : 0;\n\n              if (hit <= 0.02) {\n                // In fill mode, lay a whisper-subtle frosted glass substrate behind the active veiled pane\n                if (isFill && paneMask > 0.02) {\n                  u32[rowOff + c] = packRgba(eng.ink[0], eng.ink[1], eng.ink[2], paneTintAlpha * paneMask);\n                }\n                continue;\n              }\n\n              // Refined neutral optical ink at rest; colour appears strictly with semantic intent (rim, scan, copy, spectral)\n              let cr = eng.ink[0];\n              let cg = eng.ink[1];\n              let cb = eng.ink[2];\n\n              if (isSpec) {\n                sampleSpectral(u * 1.15 + v * 0.25 - t * 0.12, specRgb);\n                const specMix = 0.22 + 0.72 * rimBoost;\n                cr = lerp(cr, specRgb[0], specMix);\n                cg = lerp(cg, specRgb[1], specMix);\n                cb = lerp(cb, specRgb[2], specMix);\n              } else if (rimBoost > 0.04) {\n                const boost = clamp01(rimBoost * 0.88);\n                cr = lerp(cr, rimAccent[0], boost);\n                cg = lerp(cg, rimAccent[1], boost);\n                cb = lerp(cb, rimAccent[2], boost);\n              }\n\n              if (flashBoost > 0.05) {\n                const fRgb = eng.flashKind === \"error\" ? errRgb : copyRgb;\n                const fm = clamp01(flashBoost * 1.1);\n                cr = lerp(cr, fRgb[0], fm);\n                cg = lerp(cg, fRgb[1], fm);\n                cb = lerp(cb, fRgb[2], fm);\n              }\n\n              const baseAlpha = eng.isLight ? 0.66 : 0.74;\n              const alpha = hit * clamp01(baseAlpha + rimBoost * 0.24 + flashBoost * 0.18);\n              u32[rowOff + c] = packRgba(cr, cg, cb, alpha * 255);\n            }\n          }\n\n          gridCtx.putImageData(gridImg!, 0, 0);\n          ctx.save();\n          ctx.imageSmoothingEnabled = false;\n          ctx.drawImage(gridCanvas, 0, 0, cols * pitch, rows * pitch);\n          ctx.restore();\n        }\n\n        // Bulletproof wakeup condition: checks BOTH velocity AND distance to spring target so canvas never stalls mid-transition!\n        const springsPending =\n          Math.abs(eng.shutter.getTarget() - sh) > 0.002 ||\n          Math.abs(eng.peekOn.getTarget() - pk) > 0.002 ||\n          Math.abs(eng.hoverOn.getTarget() - hv) > 0.002 ||\n          Math.abs(eng.shutter.getVelocity()) > 0.004 ||\n          Math.abs(eng.peekOn.getVelocity()) > 0.004 ||\n          Math.abs(eng.hoverOn.getVelocity()) > 0.004 ||\n          Math.abs(eng.ptrX.getVelocity()) > 0.25 ||\n          Math.abs(eng.ptrY.getVelocity()) > 0.25;\n\n        const relockActive = isRev && hideMs > 0 && !isRed && !eng.relockFired;\n        const wantsAmbient = !isRev && sh < 0.985 && (isAmb || isPending) && !isRed;\n        return springsPending || pk > 0.015 || hv > 0.015 || eng.flashKind !== \"none\" || relockActive || wantsAmbient;\n      },\n\n      wake() {\n        wakeRef.current();\n      },\n    };\n\n    engineRef.current = eng;\n\n    const resize = () => {\n      const rect = canvas.getBoundingClientRect();\n      const nw = Math.round(rect.width);\n      const nh = Math.round(rect.height);\n      if (nw <= 0 || nh <= 0) return;\n      const dpr = Math.min(2, window.devicePixelRatio || 1);\n      if (nw !== eng.w || nh !== eng.h || dpr !== eng.dpr) {\n        eng.w = nw;\n        eng.h = nh;\n        eng.dpr = dpr;\n        canvas.width = Math.round(nw * dpr);\n        canvas.height = Math.round(nh * dpr);\n      }\n      eng.refreshTheme();\n      eng.stepAndDraw(0);\n    };\n\n    resize();\n    const ro = new ResizeObserver(resize);\n    ro.observe(canvas);\n\n    const mo = new MutationObserver(() => {\n      eng.refreshTheme();\n      eng.stepAndDraw(0);\n    });\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n\n    return () => {\n      ro.disconnect();\n      mo.disconnect();\n      shutter.stop();\n      peekOn.stop();\n      hoverOn.stop();\n      ptrX.stop();\n      ptrY.stop();\n      engineRef.current = null;\n    };\n  }, [rootRef]);\n\n  React.useEffect(() => {\n    const eng = engineRef.current;\n    if (!eng) return;\n    eng.relockElapsed = 0;\n    eng.relockFired = false;\n    if (reduced) {\n      eng.peekOn.jump(0);\n      eng.hoverOn.jump(0);\n      eng.shutter.jump(revealed ? 1 : 0);\n      eng.stepAndDraw(0);\n      return;\n    }\n    eng.shutter.set(revealed ? 1 : 0);\n    if (revealed) {\n      eng.peekOn.set(0);\n      eng.hoverOn.set(0);\n    }\n    eng.wake();\n  }, [revealed, pending, reduced]);\n\n  // Under reduced motion, still honour autoHideMs via a plain timer (no canvas loop)\n  React.useEffect(() => {\n    if (!reduced || !revealed || autoHideMs <= 0) return;\n    const id = window.setTimeout(() => setRevealed(false), autoHideMs);\n    return () => window.clearTimeout(id);\n  }, [reduced, revealed, autoHideMs, setRevealed]);\n\n  React.useEffect(() => {\n    if (!onScreen || reduced) {\n      if (rafRef.current) {\n        cancelAnimationFrame(rafRef.current);\n        rafRef.current = 0;\n      }\n      runningRef.current = false;\n      if (reduced) engineRef.current?.stepAndDraw(0);\n      return;\n    }\n\n    let last = 0;\n    const tick = (now: number) => {\n      const dt = last ? Math.min(1 / 24, (now - last) / 1000) : 1 / 60;\n      last = now;\n      const eng = engineRef.current;\n      if (!eng) {\n        rafRef.current = 0;\n        runningRef.current = false;\n        return;\n      }\n      if (eng.stepAndDraw(dt)) {\n        rafRef.current = requestAnimationFrame(tick);\n      } else {\n        rafRef.current = 0;\n        runningRef.current = false;\n      }\n    };\n\n    const start = () => {\n      if (runningRef.current) return;\n      runningRef.current = true;\n      last = 0;\n      rafRef.current = requestAnimationFrame(tick);\n    };\n    wakeRef.current = start;\n    start();\n\n    return () => {\n      wakeRef.current = () => {};\n      if (rafRef.current) {\n        cancelAnimationFrame(rafRef.current);\n        rafRef.current = 0;\n      }\n      runningRef.current = false;\n    };\n  }, [onScreen, reduced]);\n\n  const handlePointerMove = (event: React.PointerEvent<HTMLSpanElement>) => {\n    props.onPointerMove?.(event);\n    const eng = engineRef.current;\n    if (!eng) return;\n    eng.hovered = true;\n    if (revealed || pending || reduced) {\n      eng.wake();\n      return;\n    }\n    const rect = canvasRef.current?.getBoundingClientRect();\n    if (!rect || rect.width <= 0) return;\n    const x = event.clientX - rect.left;\n    const y = event.clientY - rect.top;\n    const activeSpring = peek ? eng.peekOn : eng.hoverOn;\n    if (activeSpring.getTarget() === 0) {\n      eng.ptrX.jump(x);\n      eng.ptrY.jump(y);\n    } else {\n      eng.ptrX.set(x);\n      eng.ptrY.set(y);\n    }\n    if (peek) {\n      eng.peekOn.set(1);\n      eng.hoverOn.set(0);\n    } else {\n      eng.hoverOn.set(1);\n      eng.peekOn.set(0);\n    }\n    eng.wake();\n  };\n\n  const handlePointerLeave = (event: React.PointerEvent<HTMLSpanElement>) => {\n    props.onPointerLeave?.(event);\n    const eng = engineRef.current;\n    if (!eng) return;\n    eng.hovered = false;\n    eng.peekOn.set(0);\n    eng.hoverOn.set(0);\n    eng.wake();\n  };\n\n  const handleClick = (event: React.MouseEvent<HTMLSpanElement>) => {\n    // Capture directional shutter origin before delegating (works for both standalone and DitherSecret!)\n    const eng = engineRef.current;\n    const rect = canvasRef.current?.getBoundingClientRect();\n    if (eng && rect && rect.width > 0) {\n      eng.shutterOriginU = clamp01((event.clientX - rect.left) / rect.width);\n    }\n    // Don't accidentally re-veil when the user just drag-selected revealed text\n    if (revealed && typeof window !== \"undefined\" && window.getSelection()?.toString()) {\n      return;\n    }\n    onClick?.(event);\n    if (event.defaultPrevented || !toggleOnClick || pending) return;\n    setRevealed(!revealed);\n  };\n\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLSpanElement>) => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented) return;\n    if (toggleOnClick && !pending && (event.key === \"Enter\" || event.key === \" \")) {\n      event.preventDefault();\n      if (engineRef.current) engineRef.current.shutterOriginU = 0;\n      setRevealed(!revealed);\n    } else if (event.key === \"Escape\" && revealed) {\n      event.preventDefault();\n      if (engineRef.current) engineRef.current.shutterOriginU = 0.5;\n      setRevealed(false);\n    }\n  };\n\n  const accessibleLabel = `${label ? `${label}, ` : \"\"}${pending ? \"fetching\" : revealed ? \"revealed, activate to hide\" : \"hidden, activate to reveal\"}`;\n\n  return (\n    <span\n      ref={rootRef}\n      data-revealed={revealed ? \"true\" : \"false\"}\n      data-pending={pending ? \"true\" : undefined}\n      role={toggleOnClick ? \"button\" : undefined}\n      tabIndex={toggleOnClick ? 0 : undefined}\n      aria-expanded={toggleOnClick ? revealed : undefined}\n      aria-busy={pending || undefined}\n      aria-label={toggleOnClick ? accessibleLabel : label}\n      onClick={handleClick}\n      onKeyDown={handleKeyDown}\n      onPointerMove={handlePointerMove}\n      onPointerLeave={handlePointerLeave}\n      onPointerCancel={handlePointerLeave}\n      className={\n        fill\n          ? `relative grid h-full w-full min-w-0 items-center rounded-[inherit] ${toggleOnClick && !pending ? \"cursor-pointer\" : \"\"} ${\n              revealed ? \"\" : \"select-none\"\n            } ${INTERACTION_FOCUS} ${className}`\n          : `relative inline-grid align-baseline rounded-[7px] ${toggleOnClick && !pending ? \"cursor-pointer\" : \"\"} ${\n              revealed ? \"\" : \"select-none\"\n            } ${INTERACTION_FOCUS} ${className}`\n      }\n      {...props}\n    >\n      {/* Real value: exact typography and width stay intact; opacity/mask driven cleanly by the shutter engine. */}\n      <span\n        ref={contentRef}\n        aria-hidden={!revealed || undefined}\n        className={\n          fill\n            ? \"[grid-area:1/1] flex h-full w-full min-w-0 items-center overflow-x-auto px-3.5 py-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n            : \"[grid-area:1/1] inline-block\"\n        }\n        style={{ opacity: defaultRevealed ? 1 : 0 }}\n      >\n        {children}\n      </span>\n\n      {/* Optical 8×8 Bayer grain shield (strictly transparent once revealed unless inherent condensation or flash is active). */}\n      <canvas\n        ref={canvasRef}\n        aria-hidden=\"true\"\n        className={\n          fill\n            ? \"pointer-events-none absolute inset-1 z-10 h-[calc(100%_-_8px)] w-[calc(100%_-_8px)] rounded-[9px]\"\n            : \"pointer-events-none absolute -inset-x-[5px] -inset-y-[2px] z-10 h-[calc(100%_+_4px)] w-[calc(100%_+_10px)] rounded-[7px]\"\n        }\n      />\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {revealed ? `${label ?? \"Value\"} revealed` : \"\"}\n      </span>\n    </span>\n  );\n}\n\n/* ─────────────────────────────────────────────────────────\n * DITHER SECRET: real-infra hairline secret field (API keys, signing secrets, cards)\n *\n * Built for real production settings screens:\n * - Full-viewport 8×8 Bayer optical pane covers 100% of the secret slot\n *   edge-to-edge (never half-veiled or leaking token length) up to a crisp\n *   1px hairline divider and Reveal/Copy controls\n * - Optional lazy onReveal() promise: plaintext never needs to live in SSR\n *   HTML; clicking Reveal runs a full-width optical Bayer scan before\n *   sweeping open, and clicking Copy while veiled writes straight to the\n *   clipboard without mounting plaintext into the DOM\n * - Inherent edge-condensing auto-relock + Escape / window-blur protection\n * ───────────────────────────────────────────────────────── */\n\nexport interface DitherSecretProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\" | \"onCopy\"> {\n  /** Plaintext secret if already client-side. Omit when fetching lazily via onReveal. */\n  value?: string;\n  /** Fetch plaintext lazily from your backend on reveal or copy (returns the full secret string). */\n  onReveal?: () => Promise<string>;\n  /** Called after the secret is copied to the clipboard. */\n  onCopy?: (secret: string) => void;\n  /** Accessible name (e.g. \"Webhook signing secret\"). */\n  label?: string;\n  /** Auto re-veil after this many ms once revealed (default 8000; 0 disables). Uses inherent Bayer condensation. */\n  autoHideMs?: number;\n  /** Immediately re-veil when the tab loses focus (default true). */\n  hideOnBlur?: boolean;\n  /** Show the built-in Copy button (default true). */\n  copyable?: boolean;\n  /** Allow magnetic cursor peek when client-side value is present (default true). */\n  peek?: boolean;\n  /** Accent rim tone: \"ink\" (default), \"primary\", or \"spectral\". */\n  tone?: DitherVeilTone;\n  /** Opt-in quiet Web Audio cues. */\n  sound?: boolean;\n}\n\nexport function DitherSecret({\n  value,\n  onReveal,\n  onCopy,\n  label = \"Secret\",\n  autoHideMs = 8000,\n  hideOnBlur = true,\n  copyable = true,\n  peek = true,\n  tone = \"primary\",\n  sound = false,\n  className = \"\",\n  ...props\n}: DitherSecretProps) {\n  const reduced = useInteractionReducedMotion();\n  const veilRef = React.useRef<DitherVeilHandle>(null);\n  const [revealed, setRevealed] = React.useState(false);\n  const [pending, setPending] = React.useState(false);\n  const [fetched, setFetched] = React.useState<string | null>(null);\n  const [copied, setCopied] = React.useState(false);\n  const [error, setError] = React.useState<string | null>(null);\n  const mountedRef = React.useRef(true);\n  const copyTimerRef = React.useRef(0);\n\n  React.useEffect(() => {\n    mountedRef.current = true;\n    return () => {\n      mountedRef.current = false;\n      window.clearTimeout(copyTimerRef.current);\n    };\n  }, []);\n\n  const fullPlaintext = fetched ?? value ?? null;\n\n  const resolveSecret = React.useCallback(\n    async (storeInDom: boolean): Promise<string | null> => {\n      if (fullPlaintext) return fullPlaintext;\n      if (!onReveal) return null;\n      setError(null);\n      setPending(true);\n      try {\n        const secret = await onReveal();\n        if (!mountedRef.current) return null;\n        if (storeInDom) setFetched(secret);\n        setPending(false);\n        return secret;\n      } catch (err: unknown) {\n        if (!mountedRef.current) return null;\n        setPending(false);\n        setError(err instanceof Error && err.message ? err.message : \"Could not load secret.\");\n        veilRef.current?.flash(\"error\");\n        if (sound) playSound(\"error\", 0.4);\n        return null;\n      }\n    },\n    [fullPlaintext, onReveal, sound],\n  );\n\n  const handleToggle = React.useCallback(async () => {\n    if (pending) return;\n    if (revealed) {\n      setRevealed(false);\n      if (sound) playSound(\"fold\", 0.35);\n      // Drop lazily fetched plaintext from memory when re-veiled if `onReveal` is the source of truth\n      if (onReveal && !value) {\n        window.setTimeout(() => {\n          if (mountedRef.current) setFetched(null);\n        }, 320);\n      }\n      return;\n    }\n    const secret = await resolveSecret(true);\n    if (!secret || !mountedRef.current) return;\n    setRevealed(true);\n    if (sound) playSound(\"unfold\", 0.35);\n  }, [pending, revealed, resolveSecret, sound, onReveal, value]);\n\n  const handleCopy = React.useCallback(async () => {\n    if (pending) return;\n    // If veiled with lazy onReveal(), copy straight to clipboard without mounting plaintext into the DOM!\n    const secret = await resolveSecret(revealed);\n    if (!secret || !mountedRef.current) return;\n    try {\n      await navigator.clipboard?.writeText(secret);\n    } catch {\n      // Fallback for non-secure preview environments\n    }\n    setCopied(true);\n    veilRef.current?.flash(\"copy\");\n    if (sound) playSound(\"success\", 0.38);\n    onCopy?.(secret);\n    window.clearTimeout(copyTimerRef.current);\n    copyTimerRef.current = window.setTimeout(() => {\n      if (mountedRef.current) setCopied(false);\n    }, 1800);\n  }, [pending, revealed, resolveSecret, sound, onCopy]);\n\n  const canPeek = peek && Boolean(fullPlaintext);\n\n  return (\n    <div className={`flex w-full flex-col ${className}`} {...props}>\n      <div className=\"flex min-h-[44px] w-full items-stretch rounded-[14px] border border-border bg-card text-card-foreground shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)]\">\n        {/* Full-viewport optical secret pane */}\n        <div className=\"relative flex min-w-0 flex-1 items-stretch overflow-hidden rounded-l-[13px]\">\n          <DitherVeil\n            ref={veilRef}\n            fill\n            label={label}\n            revealed={revealed}\n            pending={pending}\n            peek={canPeek}\n            toggleOnClick={false}\n            autoHideMs={autoHideMs}\n            hideOnBlur={hideOnBlur}\n            tone={tone}\n            sound={false}\n            onClick={() => void handleToggle()}\n            onKeyDown={(e) => {\n              if (e.key === \"Enter\" || e.key === \" \") {\n                e.preventDefault();\n                void handleToggle();\n              } else if (e.key === \"Escape\" && revealed) {\n                e.preventDefault();\n                void handleToggle();\n              }\n            }}\n            role=\"button\"\n            tabIndex={0}\n            aria-expanded={revealed}\n            aria-label={`${label}, ${pending ? \"fetching\" : revealed ? \"revealed, activate to hide\" : \"hidden, activate to reveal\"}`}\n            className={pending ? \"\" : \"cursor-pointer\"}\n            onRevealedChange={(next) => {\n              setRevealed(next);\n              if (!next && onReveal && !value) {\n                window.setTimeout(() => {\n                  if (mountedRef.current) setFetched(null);\n                }, 320);\n              }\n            }}\n          >\n            <code className=\"whitespace-nowrap font-mono text-[13.5px] leading-6 tracking-[-0.01em] text-foreground\">\n              {fullPlaintext ?? \"\\u00A0\"}\n            </code>\n          </DitherVeil>\n        </div>\n\n        {/* Crisp 1px hairline instrument divider */}\n        <span aria-hidden=\"true\" className=\"my-2.5 w-px shrink-0 bg-border\" />\n\n        {/* Integrated Reveal/Hide + Copy controls */}\n        <div className=\"flex shrink-0 items-center gap-0.5 px-1.5\">\n          <button\n            type=\"button\"\n            disabled={pending}\n            aria-label={revealed ? `Hide ${label}` : `Reveal ${label}`}\n            aria-pressed={revealed}\n            onClick={() => void handleToggle()}\n            className={`relative flex size-8 cursor-pointer items-center justify-center rounded-[10px] text-muted-foreground hover:bg-accent hover:text-foreground disabled:cursor-default disabled:opacity-45 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n          >\n            <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(!revealed, reduced)}>\n              <Eye className=\"size-[15px]\" strokeWidth={1.9} />\n            </span>\n            <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(revealed, reduced)}>\n              <EyeOff className=\"size-[15px]\" strokeWidth={1.9} />\n            </span>\n          </button>\n\n          {copyable && (\n            <button\n              type=\"button\"\n              disabled={pending}\n              aria-label={copied ? `Copied ${label}` : `Copy ${label}`}\n              onClick={() => void handleCopy()}\n              className={`relative flex size-8 cursor-pointer items-center justify-center rounded-[10px] hover:bg-accent disabled:cursor-default disabled:opacity-45 ${\n                copied ? \"text-emerald-600 dark:text-emerald-400\" : \"text-muted-foreground hover:text-foreground\"\n              } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n            >\n              <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(!copied, reduced)}>\n                <Copy className=\"size-[15px]\" strokeWidth={1.9} />\n              </span>\n              <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(copied, reduced)}>\n                <Check className=\"size-[15px]\" strokeWidth={2.3} />\n              </span>\n            </button>\n          )}\n        </div>\n      </div>\n\n      {/* Inline error fold when lazy onReveal() fails */}\n      <div\n        aria-hidden={!error || undefined}\n        className={`grid ${!error ? \"pointer-events-none\" : \"\"}`}\n        style={{\n          gridTemplateRows: error ? \"1fr\" : \"0fr\",\n          opacity: error ? 1 : 0,\n          transition: reduced ? \"none\" : `grid-template-rows 280ms ${EASE_OUT}, opacity 200ms ${EASE_OUT}`,\n        }}\n      >\n        <div className=\"min-h-0 overflow-hidden\">\n          <p role=\"alert\" className=\"px-1 pt-1.5 text-[12px] leading-5 text-red-600 dark:text-red-400\">\n            {error}\n          </p>\n        </div>\n      </div>\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {copied ? `${label} copied to clipboard` : \"\"}\n      </span>\n    </div>\n  );\n}\n\nexport default DitherVeil;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · dither-veil · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"},{"path":"registry/ui-sounds.ts","type":"registry:component","content":"// Hairline UI · dither-veil · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * UI SOUNDS: small interface sounds, made in code\n *\n * No files and nothing to license: every sound is built from a\n * tone or a burst of noise with the Web Audio API the moment it\n * plays. They're short and quiet, made to sit under an interface,\n * and components only play them when you pass `sound`.\n *\n *   fold     paper creasing: two short crisp bursts\n *   unfold   paper opening: a soft rising sweep\n *   drop     something small landing: a low, soft knock\n *   tick     a light click\n *   pop      a quick bright blip\n *   success  two soft rising notes\n *   error    two low falling notes\n *\n * Browsers only start audio after the visitor has pressed\n * something on the page, so a sound before that stays silent.\n * ───────────────────────────────────────────────────────── */\n\nexport type UiSound = \"fold\" | \"unfold\" | \"drop\" | \"tick\" | \"pop\" | \"success\" | \"error\";\n\nlet context: AudioContext | null = null;\nlet noise: AudioBuffer | null = null;\n\nfunction audio() {\n  if (typeof window === \"undefined\") return null;\n  if (!context) {\n    const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n    if (!Ctx) return null;\n    context = new Ctx();\n  }\n  if (context.state === \"suspended\") void context.resume().catch(() => {});\n  return context;\n}\n\nfunction noiseBuffer(ctx: AudioContext) {\n  if (noise && noise.sampleRate === ctx.sampleRate) return noise;\n  noise = ctx.createBuffer(1, Math.floor(ctx.sampleRate * 0.5), ctx.sampleRate);\n  const data = noise.getChannelData(0);\n  for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n  return noise;\n}\n\n/** A burst of filtered noise. */\nfunction burst(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"bandpass\", from = 2000, to = from, q = 0.9, level = 0.5 }: { type?: BiquadFilterType; from?: number; to?: number; q?: number; level?: number }) {\n  const src = ctx.createBufferSource();\n  src.buffer = noiseBuffer(ctx);\n  const filter = ctx.createBiquadFilter();\n  filter.type = type;\n  filter.Q.value = q;\n  filter.frequency.setValueAtTime(from, at);\n  filter.frequency.exponentialRampToValueAtTime(Math.max(40, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + Math.min(0.012, length / 3));\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  src.connect(filter).connect(gain).connect(out);\n  src.start(at, Math.random() * 0.3, length + 0.02);\n}\n\n/** A tone that glides from one pitch to another. */\nfunction tone(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"sine\", from, to = from, level = 0.4 }: { type?: OscillatorType; from: number; to?: number; level?: number }) {\n  const osc = ctx.createOscillator();\n  osc.type = type;\n  osc.frequency.setValueAtTime(from, at);\n  osc.frequency.exponentialRampToValueAtTime(Math.max(20, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + 0.006);\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  osc.connect(gain).connect(out);\n  osc.start(at);\n  osc.stop(at + length + 0.02);\n}\n\n/** Plays one sound. `volume` is 0 to 1; the default sits quietly under an interface. */\nexport function playSound(name: UiSound, volume = 0.5) {\n  const ctx = audio();\n  if (!ctx) return;\n  const out = ctx.createGain();\n  out.gain.value = Math.max(0, Math.min(1, volume)) * 0.5;\n  out.connect(ctx.destination);\n  const t = ctx.currentTime + 0.005;\n  switch (name) {\n    case \"fold\":\n      burst(ctx, out, t, 0.05, { type: \"highpass\", from: 2600, q: 0.7, level: 0.45 });\n      burst(ctx, out, t + 0.07, 0.07, { type: \"bandpass\", from: 3200, to: 1800, q: 1.2, level: 0.35 });\n      break;\n    case \"unfold\":\n      burst(ctx, out, t, 0.16, { type: \"bandpass\", from: 900, to: 2800, q: 0.8, level: 0.3 });\n      break;\n    case \"drop\":\n      tone(ctx, out, t, 0.12, { from: 180, to: 70, level: 0.55 });\n      burst(ctx, out, t, 0.03, { type: \"lowpass\", from: 1200, q: 0.5, level: 0.2 });\n      break;\n    case \"tick\":\n      tone(ctx, out, t, 0.025, { type: \"triangle\", from: 1900, to: 1500, level: 0.25 });\n      break;\n    case \"pop\":\n      tone(ctx, out, t, 0.06, { from: 620, to: 980, level: 0.3 });\n      break;\n    case \"success\":\n      tone(ctx, out, t, 0.11, { from: 660, level: 0.22 });\n      tone(ctx, out, t + 0.09, 0.16, { from: 990, level: 0.22 });\n      break;\n    case \"error\":\n      tone(ctx, out, t, 0.12, { type: \"triangle\", from: 330, level: 0.25 });\n      tone(ctx, out, t + 0.1, 0.18, { type: \"triangle\", from: 247, level: 0.25 });\n      break;\n  }\n  window.setTimeout(() => out.disconnect(), 600);\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/dither-veil. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}