{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "halftone-tide",
  "title": "Halftone Tide",
  "type": "registry:component",
  "description": "Print-style halftone dots swelling like a tide",
  "dependencies": [],
  "files": [
    {
      "path": "src/kavyn/halftone-tide.tsx",
      "type": "registry:component",
      "target": "@components/kavyn/halftone-tide.tsx",
      "content": "'use client'\n\nimport ShaderBackground, { type ShaderBackgroundProps } from './shader-bg'\n\nconst FRAG = `\nuniform float uCell;\nvoid main(){\n  float s=uCell*uPx/uScale;\n  mat2 rot=mat2(.7071,-.7071,.7071,.7071);\n  vec2 q=rot*(gl_FragCoord.xy-.5*uRes)/s;vec2 id=floor(q+.5);vec2 o=q-id;\n  vec2 c=((id*s)*rot)/uRes.y;float t=uTime*.25;\n  float tide=.5+.5*sin(c.x*2.6+c.y*1.7+t+2.2*fbm(c*1.2+vec2(t*.2,0.)));\n  tide=tide*.75+.25*fbm(c*2.5-t*.1);\n  tide=smoothstep(.12,.88,tide);\n  tide+=uMouse.w*.5*exp(-7.*dot(c-pointer(),c-pointer()));\n  float r=.46*sqrt(clamp(tide,0.,1.));\n  float aa=1./s;\n  float dotv=smoothstep(r+aa,r-aa,length(o))*step(.04,r);\n  paint(dotv*.45*smoothstep(1.5,.2,length(c)),tide);\n}\n`\n\nexport interface HalftoneTideProps extends ShaderBackgroundProps {\n  /** Distance between dots, in CSS pixels. */\n  cell?: number\n}\n\n// Print-style halftone dots on a 45 degree screen, swelling and thinning like a tide. They gather under the pointer.\n// Ink and paper come from your theme (--tx on --bg), so it works in light and dark. Pass `color` to tint it.\nexport default function HalftoneTide({ cell = 14, color = '', color2 = '', speed = 1, intensity = 1, scale = 1, interactive = true, allowSoftware = true, className = '', style, children }: HalftoneTideProps) {\n  return (\n    <ShaderBackground frag={FRAG} uniforms={{ uCell: cell }} color={color} color2={color2} speed={speed} intensity={intensity} scale={scale} interactive={interactive} allowSoftware={allowSoftware} className={className} style={style}>\n      {children}\n    </ShaderBackground>\n  )\n}\n"
    },
    {
      "path": "src/kavyn/shader-bg.tsx",
      "type": "registry:component",
      "target": "@components/kavyn/shader-bg.tsx",
      "content": "'use client'\n\nimport { useEffect, useRef, type CSSProperties, type ReactNode } from 'react'\n\n// Shared runner for the shader backgrounds.\n//\n// It draws one full-screen triangle with your fragment shader and takes care of the parts\n// that make a shader safe to ship behind real content:\n//   - theme: reads --bg and --tx from your CSS, so every background is ink-on-paper in light\n//     mode and light-on-black in dark mode, and redraws when the theme class flips\n//   - quality: renders at device resolution (capped at 2x) and steps down if frames run slow\n//   - banding: every shader ends in a tiny dither, so dark gradients stay smooth on 8-bit screens\n//   - manners: pauses off screen and in hidden tabs, draws one still frame for reduced motion\n//   - any machine: uses the GPU when it can; on software-only WebGL (common on Linux, VMs, remote\n//     desktops) it draws a still frame and animates, at lower resolution and 30fps, only while the\n//     pointer is over it; if even that is too slow it holds the still frame.\n//   - page load: a background compiles only once it nears the screen, one at a time in idle moments,\n//     so a page full of them never freezes. Only with no WebGL at all does the CSS fallback stay, and the console says why.\n\nexport type RGB = [number, number, number]\n\nexport interface ShaderBackgroundProps {\n  /** Ink colour as a hex string. Defaults to your theme's text colour (--tx). */\n  color?: string\n  /** Second ink colour, blended in where the shader has depth. Defaults to `color`. */\n  color2?: string\n  /** Time multiplier. 0 freezes the frame. */\n  speed?: number\n  /** How strongly the pattern shows, 0 to 2. */\n  intensity?: number\n  /** Zoom of the pattern. Above 1 is finer, below 1 is larger. */\n  scale?: number\n  /** React to the pointer. */\n  interactive?: boolean\n  /** Run when WebGL is software-only (no GPU), at reduced resolution and 30fps. Set false to show the CSS fallback there instead. */\n  allowSoftware?: boolean\n  className?: string\n  style?: CSSProperties\n  children?: ReactNode\n}\n\ninterface FrameProps extends ShaderBackgroundProps {\n  frag: string\n  /** Extra float uniforms for this shader. */\n  uniforms?: Record<string, number>\n}\n\nconst VERT = 'attribute vec2 p;void main(){gl_Position=vec4(p,0.,1.);}'\n\n// Uniforms and helpers every shader gets.\n//   uRes    canvas size in pixels          uTime   seconds, already scaled by `speed`\n//   uMouse  xy = pointer (0..1, smoothed), z = 1 while pressed, w = 0..1 hover presence\n//   uBg     page background                uA, uB  ink colours\n//   uAmp    intensity                      uScale  pattern zoom\n//   uPx     canvas pixels per CSS pixel, for line widths and dot sizes that stay the same on any screen\nconst HEAD = `\n#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\nuniform vec2 uRes;uniform float uTime;uniform vec4 uMouse;\nuniform vec3 uBg;uniform vec3 uA;uniform vec3 uB;uniform float uAmp;uniform float uScale;uniform float uPx;\nfloat hash(vec2 p){vec3 q=fract(vec3(p.xyx)*.1031);q+=dot(q,q.yzx+33.33);return fract((q.x+q.y)*q.z);}\nvec2 hash2(vec2 p){vec3 q=fract(vec3(p.xyx)*vec3(.1031,.1030,.0973));q+=dot(q,q.yzx+33.33);return fract((q.xx+q.yz)*q.zy);}\nfloat noise(vec2 p){\n  vec2 i=floor(p),f=fract(p);vec2 u=f*f*f*(f*(f*6.-15.)+10.);\n  float a=dot(hash2(i)*2.-1.,f),b=dot(hash2(i+vec2(1.,0.))*2.-1.,f-vec2(1.,0.));\n  float c=dot(hash2(i+vec2(0.,1.))*2.-1.,f-vec2(0.,1.)),d=dot(hash2(i+vec2(1.,1.))*2.-1.,f-vec2(1.,1.));\n  return clamp(mix(mix(a,b,u.x),mix(c,d,u.x),u.y)*.75+.5,0.,1.);\n}\nfloat fbm(vec2 p){float v=0.,a=.5;mat2 r=mat2(.8,-.6,.6,.8);for(int i=0;i<5;i++){v+=a*noise(p);p=r*p*2.03+11.7;a*=.5;}return v;}\nvec2 centered(){return (gl_FragCoord.xy-.5*uRes)/uRes.y;}\nvec2 pointer(){return (uMouse.xy-.5)*vec2(uRes.x/uRes.y,1.);}\n// v = how much ink (0..1), k = blend from the first ink colour to the second.\nvoid paint(float v,float k){\n  vec3 c=mix(uBg,mix(uA,uB,clamp(k,0.,1.)),clamp(v*uAmp,0.,1.));\n  c+=(hash(gl_FragCoord.xy+fract(uTime)*61.)-.5)/160.;\n  gl_FragColor=vec4(c,1.);\n}\n`\n\nexport function hexToRgb(hex: string | undefined, fallback: RGB): RGB {\n  const s = typeof hex === 'string' ? hex.trim().replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i, '#$1$1$2$2$3$3') : ''\n  const m = s.match(/^#?([0-9a-f]{6})$/i)\n  if (!m) return fallback\n  const n = parseInt(m[1], 16)\n  return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]\n}\n\nconst readToken = (el: Element, name: string, fallback: RGB): RGB => hexToRgb(getComputedStyle(el).getPropertyValue(name), fallback)\n\nconst num = (v: unknown, fallback: number) => (typeof v === 'number' && Number.isFinite(v) ? v : fallback)\n\n// Each problem is reported once per page, not once per background.\nconst told = new Set<string>()\nconst tell = (key: string, msg: string, level: 'info' | 'warn' = 'info') => {\n  if (told.has(key)) return\n  told.add(key)\n  try { console[level](`[kavynui] ${msg}`) } catch { /* no console */ }\n}\n\n// Setup is queued: one background compiles its shader per idle moment, so a page with many of them\n// never freezes while they all compile at once (on software WebGL a compile can take 100ms+).\nconst queue: Array<() => void> = []\nlet pumping = false\nconst later = (fn: () => void) => (typeof requestIdleCallback === 'function' ? requestIdleCallback(fn, { timeout: 250 }) : setTimeout(fn, 16))\nconst pump = () => {\n  const job = queue.shift()\n  if (!job) { pumping = false; return }\n  try { job() } finally { later(pump) }\n}\nconst enqueue = (job: () => void) => {\n  queue.push(job)\n  if (!pumping) { pumping = true; later(pump) }\n  return () => { const i = queue.indexOf(job); if (i >= 0) queue.splice(i, 1) }\n}\n\n// On software WebGL a background animates only while the pointer is over it; otherwise it holds a still\n// frame, so a page of them costs nothing at rest. On a GPU they all animate as usual.\nlet softOwner: object | null = null\nconst softWakers = new Set<() => void>()\nconst releaseSoft = (me: object) => {\n  if (softOwner !== me) return\n  softOwner = null\n  for (const wake of softWakers) wake()\n}\n\nconst CTX: WebGLContextAttributes = { antialias: false, alpha: false, depth: false, stencil: false, powerPreference: 'low-power' }\nconst getGL = (canvas: HTMLCanvasElement, attrs: WebGLContextAttributes) => {\n  try { return canvas.getContext('webgl', attrs) as WebGLRenderingContext | null } catch { return null }\n}\n\n/** Wraps your content in a box with a live shader behind it. Each background file is this plus one fragment shader. */\nexport default function ShaderBackground({ frag, uniforms, color, color2, speed = 1, intensity = 1, scale = 1, interactive = true, allowSoftware = true, className = '', style, children }: FrameProps) {\n  const host = useRef<HTMLDivElement>(null)\n  // Props are read every frame from this ref, so changing them never rebuilds the GL program.\n  const live = useRef({ uniforms, color, color2, speed, intensity, scale, interactive })\n  live.current = { uniforms, color, color2, speed, intensity, scale, interactive }\n\n  useEffect(() => {\n    const el = host.current\n    if (!el || typeof window === 'undefined') return\n    // Nothing is compiled until the background comes near the screen, then setup waits its turn in the queue.\n    let dispose: (() => void) | void = undefined\n    let cancel = () => {}\n    const begin = () => { cancel = enqueue(() => { dispose = setup(el) }) }\n    let near: IntersectionObserver | null = null\n    if (typeof IntersectionObserver === 'undefined') begin()\n    else {\n      near = new IntersectionObserver(([e]) => { if (e?.isIntersecting) { near?.disconnect(); near = null; begin() } }, { rootMargin: '300px' })\n      near.observe(el)\n    }\n    return () => { near?.disconnect(); cancel(); if (dispose) dispose() }\n\n    function setup(el: HTMLDivElement): (() => void) | void {\n    const canvas = document.createElement('canvas')\n    canvas.setAttribute('aria-hidden', 'true')\n    canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;display:block;opacity:0;transition:opacity .7s ease'\n    // GPU first. If the browser only offers software WebGL, use it at reduced cost rather than show nothing.\n    let soft = false\n    let gl = getGL(canvas, { ...CTX, failIfMajorPerformanceCaveat: true })\n    if (!gl) {\n      if (allowSoftware) { gl = getGL(canvas, CTX); soft = !!gl }\n      if (!gl) {\n        tell('nogl', allowSoftware\n          ? 'WebGL is not available in this browser, so shader backgrounds show their CSS fallback.'\n          : 'Only software WebGL is available and allowSoftware is false, so shader backgrounds show their CSS fallback.')\n        return\n      }\n      tell('soft', 'No GPU WebGL here (hardware acceleration off or the GPU is blocklisted). Shader backgrounds show a still frame and animate only under the pointer, at reduced resolution.')\n    }\n    const g = gl\n    const compile = (type: number, src: string) => {\n      const s = g.createShader(type)\n      if (!s) return null\n      g.shaderSource(s, src); g.compileShader(s)\n      if (!g.getShaderParameter(s, g.COMPILE_STATUS)) {\n        tell(`compile:${src.length}`, `A shader failed to compile on this GPU, showing the CSS fallback. Driver says: ${g.getShaderInfoLog(s) || 'no details'}`, 'warn')\n        g.deleteShader(s); return null\n      }\n      return s\n    }\n    const vs = compile(g.VERTEX_SHADER, VERT), fs = compile(g.FRAGMENT_SHADER, HEAD + frag)\n    const prog = vs && fs ? g.createProgram() : null\n    if (!prog || !vs || !fs) return\n    g.attachShader(prog, vs); g.attachShader(prog, fs); g.linkProgram(prog)\n    if (!g.getProgramParameter(prog, g.LINK_STATUS)) {\n      tell(`link:${frag.length}`, `A shader failed to link, showing the CSS fallback. Driver says: ${g.getProgramInfoLog(prog) || 'no details'}`, 'warn')\n      return\n    }\n    g.useProgram(prog)\n    const buf = g.createBuffer()\n    g.bindBuffer(g.ARRAY_BUFFER, buf)\n    g.bufferData(g.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), g.STATIC_DRAW)\n    const at = g.getAttribLocation(prog, 'p')\n    g.enableVertexAttribArray(at); g.vertexAttribPointer(at, 2, g.FLOAT, false, 0, 0)\n    const locs: Record<string, WebGLUniformLocation | null> = {}\n    const U = (name: string) => (name in locs ? locs[name] : (locs[name] = g.getUniformLocation(prog, name)))\n    el.prepend(canvas)\n\n    // Theme: ink and paper come from the page's own tokens, and follow a theme switch.\n    let bg: RGB = [0, 0, 0], fg: RGB = [0.96, 0.96, 0.97]\n    const readTheme = () => { bg = readToken(el, '--bg', [0, 0, 0]); fg = readToken(el, '--tx', bg[0] + bg[1] + bg[2] > 1.5 ? [0.11, 0.11, 0.12] : [0.96, 0.96, 0.97]) }\n    readTheme()\n\n    const mouse = { x: 0.5, y: 0.5, tx: 0.5, ty: 0.5, down: 0, in: 0, tin: 0 }\n    const onMove = (e: PointerEvent) => {\n      const r = el.getBoundingClientRect()\n      if (!r.width || !r.height) return\n      mouse.tx = (e.clientX - r.left) / r.width; mouse.ty = 1 - (e.clientY - r.top) / r.height; mouse.tin = 1\n    }\n    const onLeave = () => { mouse.tin = 0 }\n    const onDown = () => { mouse.down = 1 }\n    const onUp = () => { mouse.down = 0 }\n    el.addEventListener('pointermove', onMove)\n    el.addEventListener('pointerleave', onLeave)\n    el.addEventListener('pointerdown', onDown)\n    window.addEventListener('pointerup', onUp)\n\n    const reduce = !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n    let raf = 0, visible = true, lost = false, shown = false, time = 0, prev = performance.now()\n    // Adaptive quality: start at device resolution (half of 1x on software), step down while frames run slow.\n    // On the floor and still slow: stop animating and keep the last frame, so the page stays responsive.\n    const MIN_Q = soft ? 0.2 : 0.4\n    let q = soft ? 0.5 : 1, slow = 0, frames = 0, still = false, lastDraw = 0\n    const draw = (now: number) => {\n      if (lost || g.isContextLost()) return\n      const p = live.current\n      const dpr = Math.min(soft ? 1 : 2, window.devicePixelRatio || 1) * q\n      const w = Math.max(1, Math.round(el.clientWidth * dpr)), h = Math.max(1, Math.round(el.clientHeight * dpr))\n      if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h }\n      g.viewport(0, 0, w, h)\n      const dt = Math.max(0, (now - prev) / 1000)\n      time += Math.min(0.1, dt) * num(p.speed, 1)\n      prev = now\n      if (shown && dt < 0.5) {\n        frames++\n        if (dt > (soft ? 1 / 22 : 1 / 45)) slow++\n        if (frames >= 40) {\n          if (slow > 16) {\n            if (q > MIN_Q) q = Math.max(MIN_Q, q * 0.8)\n            else { still = true; tell('still', 'This device is too slow to animate shader backgrounds, so they hold a still frame.') }\n          }\n          frames = 0; slow = 0\n        }\n      }\n      const on = p.interactive !== false\n      mouse.x += ((on ? mouse.tx : 0.5) - mouse.x) * 0.07; mouse.y += ((on ? mouse.ty : 0.5) - mouse.y) * 0.07\n      mouse.in += ((on ? mouse.tin : 0) - mouse.in) * 0.06\n      const a = hexToRgb(p.color, fg), b = hexToRgb(p.color2, a)\n      g.uniform2f(U('uRes'), w, h); g.uniform1f(U('uPx'), dpr)\n      g.uniform1f(U('uTime'), reduce ? 14 : time + 14)\n      g.uniform4f(U('uMouse'), mouse.x, mouse.y, on ? mouse.down : 0, mouse.in)\n      g.uniform3f(U('uBg'), bg[0], bg[1], bg[2]); g.uniform3f(U('uA'), a[0], a[1], a[2]); g.uniform3f(U('uB'), b[0], b[1], b[2])\n      g.uniform1f(U('uAmp'), Math.min(2, Math.max(0, num(p.intensity, 1)))); g.uniform1f(U('uScale'), Math.max(0.05, num(p.scale, 1)))\n      for (const [name, v] of Object.entries(p.uniforms || {})) { const l = U(name); if (l) g.uniform1f(l, num(v, 0)) }\n      g.drawArrays(g.TRIANGLES, 0, 3)\n      if (!shown) { shown = true; canvas.style.opacity = '1' }\n    }\n    const me = {}\n    const mayAnimate = () => !soft || softOwner === me\n    const loop = (now: number) => {\n      raf = 0\n      // Software rendering is capped at 30fps: half the CPU for a difference few people see.\n      if (!soft || now - lastDraw >= 31 || !shown) { lastDraw = now; draw(now) }\n      if (!reduce && !still && visible && !document.hidden && mayAnimate()) raf = requestAnimationFrame(loop)\n    }\n    const start = () => { if (!raf && !lost) { prev = performance.now(); raf = requestAnimationFrame(loop) } }\n    const onEnter = () => { if (soft && softOwner !== me) { softOwner = me; start() } }\n    const onExit = () => releaseSoft(me)\n    if (soft) { softWakers.add(start); el.addEventListener('pointerenter', onEnter); el.addEventListener('pointerleave', onExit) }\n    const io = typeof IntersectionObserver !== 'undefined' ? new IntersectionObserver(([e]) => { visible = !!e?.isIntersecting; if (visible) start(); else releaseSoft(me) }) : null\n    io?.observe(el)\n    const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => start()) : null\n    ro?.observe(el)\n    const mo = typeof MutationObserver !== 'undefined' ? new MutationObserver(() => { readTheme(); start() }) : null\n    mo?.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] })\n    const onVis = () => { if (!document.hidden) start() }\n    document.addEventListener('visibilitychange', onVis)\n    const onLost = (e: Event) => { e.preventDefault(); lost = true; cancelAnimationFrame(raf); canvas.style.opacity = '0' }\n    canvas.addEventListener('webglcontextlost', onLost)\n    start()\n\n    return () => {\n      cancelAnimationFrame(raf)\n      softWakers.delete(start); el.removeEventListener('pointerenter', onEnter); el.removeEventListener('pointerleave', onExit); releaseSoft(me)\n      io?.disconnect(); ro?.disconnect(); mo?.disconnect()\n      document.removeEventListener('visibilitychange', onVis)\n      el.removeEventListener('pointermove', onMove)\n      el.removeEventListener('pointerleave', onLeave)\n      el.removeEventListener('pointerdown', onDown)\n      window.removeEventListener('pointerup', onUp)\n      canvas.removeEventListener('webglcontextlost', onLost)\n      try {\n        g.deleteBuffer(buf); g.deleteProgram(prog); g.deleteShader(vs); g.deleteShader(fs)\n        g.getExtension('WEBGL_lose_context')?.loseContext()\n      } catch { /* already gone */ }\n      canvas.remove()\n    }\n    }\n  }, [frag, allowSoftware])\n\n  // The CSS layer under the canvas: what visitors see before the GPU frame fades in, and all they see without WebGL.\n  const ink = color || 'var(--tx)'\n  const fallback = `radial-gradient(120% 90% at 50% 110%, color-mix(in srgb, ${ink} 16%, transparent), transparent 70%)`\n  return (\n    <div ref={host} className={`relative isolate h-full min-h-72 w-full overflow-hidden bg-bg ${className}`} style={{ backgroundImage: fallback, ...style }}>\n      <div className=\"relative z-10 grid h-full min-h-72 place-items-center p-6\">{children}</div>\n    </div>\n  )\n}\n"
    }
  ],
  "cssVars": {
    "theme": {
      "color-bg": "var(--bg)",
      "color-panel": "var(--panel)",
      "color-panel2": "var(--panel2)",
      "color-line": "var(--line)",
      "color-line2": "var(--line2)",
      "color-tx": "var(--tx)",
      "color-mute": "var(--mute)",
      "color-faint": "var(--faint)",
      "color-acc": "var(--acc)",
      "color-acc-fg": "var(--acc-fg)"
    },
    "light": {
      "bg": "#ffffff",
      "panel": "#f5f5f7",
      "panel2": "#e8e8ed",
      "line": "#e5e5ea",
      "line2": "#d2d2d7",
      "tx": "#1d1d1f",
      "mute": "#6e6e73",
      "faint": "#a1a1a6",
      "acc": "#1d1d1f",
      "acc-fg": "#ffffff"
    },
    "dark": {
      "bg": "#000000",
      "panel": "#141416",
      "panel2": "#1f1f22",
      "line": "#262628",
      "line2": "#3a3a3d",
      "tx": "#f5f5f7",
      "mute": "#a1a1a6",
      "faint": "#6e6e73",
      "acc": "#f5f5f7",
      "acc-fg": "#000000"
    }
  },
  "css": {
    ".light": {
      "--bg": "#ffffff",
      "--panel": "#f5f5f7",
      "--panel2": "#e8e8ed",
      "--line": "#e5e5ea",
      "--line2": "#d2d2d7",
      "--tx": "#1d1d1f",
      "--mute": "#6e6e73",
      "--faint": "#a1a1a6",
      "--acc": "#1d1d1f",
      "--acc-fg": "#ffffff"
    }
  }
}
