{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "warp-gradient",
  "title": "Warp Gradient",
  "description": "A liquid field of colour carried along by layered noise, from one WebGL2 shader.",
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/use-in-view"
  ],
  "files": [
    {
      "path": "registry/default/ui/warp-gradient.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useMemo, useRef, type ComponentProps, type Ref } from \"react\";\n\nimport { useInView } from \"@/registry/default/hooks/use-in-view\";\nimport { cn } from \"@/registry/default/lib/utils\";\n\nfunction mergeRefs<T>(...refs: (Ref<T> | undefined)[]) {\n  return (node: T | null) => {\n    for (const ref of refs) {\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) ref.current = node;\n    }\n  };\n}\n\nconst MAX_COLORS = 5;\n\nconst VERTEX = `#version 300 es\nin vec2 a_position;\nvoid main() { gl_Position = vec4(a_position, 0.0, 1.0); }`;\n\n// Gradient noise, layered and fed back into itself (domain warping), sets\n// the flow; a simple pattern read through that flow picks the colours.\nconst FRAGMENT = `#version 300 es\nprecision highp float;\nuniform vec2 u_size;\nuniform float u_dpr;\nuniform float u_clock;\nuniform float u_scale;\nuniform float u_turn;\nuniform vec4 u_palette[${MAX_COLORS}];\nuniform int u_count;\nuniform int u_pattern;\nuniform float u_density;\nuniform float u_softness;\nuniform float u_warp;\nuniform float u_turbulence;\nout vec4 outColor;\n\nfloat hash(vec2 cell) {\n  return fract(sin(dot(cell, vec2(41.37, 289.13))) * 17853.217);\n}\n\n// The corner's random slope, followed from the corner to the point.\nfloat lean(vec2 cell, vec2 offset) {\n  float angle = 6.2831853 * hash(cell);\n  return dot(vec2(cos(angle), sin(angle)), offset);\n}\n\n// Gradient noise with quintic fades, roughly -0.7 to 0.7.\nfloat noise(vec2 p) {\n  vec2 cell = floor(p);\n  vec2 f = p - cell;\n  vec2 fade = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);\n  float bottom = mix(lean(cell, f), lean(cell + vec2(1.0, 0.0), f - vec2(1.0, 0.0)), fade.x);\n  float top = mix(lean(cell + vec2(0.0, 1.0), f - vec2(0.0, 1.0)), lean(cell + 1.0, f - 1.0), fade.x);\n  return mix(bottom, top, fade.y);\n}\n\n// Each layer is finer, fainter and turned, so the layers never line up.\nconst mat2 TURN = mat2(0.8776, 0.4794, -0.4794, 0.8776);\n\nfloat layered(vec2 p, int layers) {\n  float sum = 0.0;\n  float weight = 0.55;\n  for (int i = 0; i < 5; i++) {\n    if (i >= layers) break;\n    sum += weight * noise(p);\n    p = TURN * p * 1.97 + vec2(3.7, -1.9);\n    weight *= 0.5;\n  }\n  return sum;\n}\n\nvoid main() {\n  // Pattern space counts CSS pixels from the centre, so the flow keeps its\n  // size on any canvas and any screen density.\n  vec2 p = (gl_FragCoord.xy - 0.5 * u_size) / u_dpr * mix(0.0065, 0.0012, u_scale);\n  float c = cos(u_turn);\n  float s = sin(u_turn);\n  p = mat2(c, s, -s, c) * p;\n\n  float t = 0.15 * u_clock;\n  int layers = 1 + int(u_turbulence * 4.0 + 0.5);\n  vec2 drift = vec2(t, -0.6 * t);\n  // The flow is broader than the pattern, so it bends bands instead of folding them.\n  vec2 q = 0.6 * p;\n  vec2 first = vec2(layered(q + drift, layers), layered(q + vec2(5.3, -2.1) - drift, layers));\n  vec2 second = vec2(\n    layered(q + 1.8 * first + vec2(-4.6, 7.2) + drift.yx, layers),\n    layered(q + 1.8 * first + vec2(8.1, 1.4) - 0.5 * drift, layers)\n  );\n  vec2 w = p + 1.8 * u_warp * second;\n\n  float field;\n  if (u_pattern == 0) {\n    field = 0.5 + 0.5 * sin(3.14159265 * mix(0.5, 3.5, u_density) * w.y);\n  } else if (u_pattern == 1) {\n    float k = mix(1.0, 5.0, u_density);\n    field = 0.5 + 0.5 * sin(k * w.x) * sin(k * w.y);\n  } else {\n    float spread = mix(2.5, 0.1, u_density);\n    field = smoothstep(-spread, spread, w.y);\n  }\n\n  vec4 a = u_palette[0];\n  vec4 color = vec4(a.rgb * a.a, a.a);\n  if (u_count > 1) {\n    float x = clamp(field, 0.0, 1.0) * float(u_count - 1);\n    int i = min(int(x), u_count - 2);\n    float reach = 0.5 * u_softness + fwidth(x);\n    float blend = smoothstep(0.5 - reach, 0.5 + reach, x - float(i));\n    vec4 from = u_palette[i];\n    vec4 to = u_palette[i + 1];\n    color = mix(vec4(from.rgb * from.a, from.a), vec4(to.rgb * to.a, to.a), blend);\n  }\n  // Dither by a fraction of a level so slow gradients do not band.\n  color.rgb += (hash(gl_FragCoord.xy) - 0.5) / 255.0;\n  outColor = color;\n}`;\n\ntype WarpPattern = \"bands\" | \"cells\" | \"split\";\n\ninterface WarpSettings {\n  colors: string[];\n  /** What the colours are laid on: soft bands, a grid of cells, or one divide. */\n  pattern: WarpPattern;\n  /** From 0 to 1: how many bands or cells fit; for \"split\", how sharp the divide is. */\n  density: number;\n  /** From 0 to 1: 0 keeps crisp borders between colours, 1 melts them together. */\n  softness: number;\n  /** From 0 to 1: how far the flow pushes the pattern around. */\n  warp: number;\n  /** From 0 to 1: fine detail in the flow. */\n  turbulence: number;\n  /** From 0 to 1: size of the flow; larger is broader. */\n  scale: number;\n  /** Turn of the whole field, in degrees. */\n  rotation: number;\n  /** Pace of the flow; 0 holds it still. */\n  speed: number;\n}\n\nconst PRESETS = {\n  tide: {\n    colors: [\"#04090f\", \"#1f5f72\", \"#6fb3c2\"],\n    pattern: \"bands\",\n    density: 0.4,\n    softness: 1,\n    warp: 0.8,\n    turbulence: 0.2,\n    scale: 0.6,\n    rotation: -20,\n    speed: 0.5,\n  },\n  brass: {\n    colors: [\"#0b0907\", \"#7a5b2a\", \"#d9b06a\"],\n    pattern: \"split\",\n    density: 0.55,\n    softness: 0.9,\n    warp: 0.8,\n    turbulence: 0.25,\n    scale: 0.6,\n    rotation: 110,\n    speed: 0.5,\n  },\n  abyss: {\n    colors: [\"#020308\", \"#102447\", \"#3a6ea5\", \"#020308\"],\n    pattern: \"bands\",\n    density: 0.3,\n    softness: 1,\n    warp: 0.9,\n    turbulence: 0.2,\n    scale: 0.5,\n    rotation: 0,\n    speed: 0.4,\n  },\n  dusk: {\n    colors: [\"#100a18\", \"#6d63c9\", \"#e07a5f\"],\n    pattern: \"cells\",\n    density: 0.45,\n    softness: 1,\n    warp: 0.7,\n    turbulence: 0.1,\n    scale: 0.5,\n    rotation: 45,\n    speed: 0.5,\n  },\n  fog: {\n    colors: [\"#fafaf9\", \"#e7e5e4\", \"#a8a29e\", \"#fafaf9\"],\n    pattern: \"bands\",\n    density: 0.35,\n    softness: 1,\n    warp: 0.8,\n    turbulence: 0.25,\n    scale: 0.55,\n    rotation: 30,\n    speed: 0.3,\n  },\n} satisfies Record<string, WarpSettings>;\n\n/** Any CSS colour, theme variables included, as 0–1 RGBA. */\nfunction resolveColor(color: string, probe: HTMLElement): [number, number, number, number] {\n  probe.style.color = color;\n  const canvas = document.createElement(\"canvas\");\n  canvas.width = canvas.height = 1;\n  const context = canvas.getContext(\"2d\");\n  if (!context) return [0, 0, 0, 1];\n  context.fillStyle = getComputedStyle(probe).color;\n  context.fillRect(0, 0, 1, 1);\n  const [r = 0, g = 0, b = 0, a = 255] = context.getImageData(0, 0, 1, 1).data;\n  return [r / 255, g / 255, b / 255, a / 255];\n}\n\nfunction compile(gl: WebGL2RenderingContext) {\n  const program = gl.createProgram();\n  for (const [type, source] of [\n    [gl.VERTEX_SHADER, VERTEX],\n    [gl.FRAGMENT_SHADER, FRAGMENT],\n  ] as const) {\n    const shader = gl.createShader(type);\n    if (!shader) return null;\n    gl.shaderSource(shader, source);\n    gl.compileShader(shader);\n    gl.attachShader(program, shader);\n    gl.deleteShader(shader);\n  }\n  gl.linkProgram(program);\n  return gl.getProgramParameter(program, gl.LINK_STATUS) ? program : null;\n}\n\nconst PATTERNS: Record<WarpPattern, number> = { bands: 0, cells: 1, split: 2 };\n\nconst unit = (value: number) => Math.min(Math.max(value, 0), 1);\n\n// Film grain from an SVG noise filter: a few hundred bytes, no image to load.\nconst GRAIN = `url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='180' height='180'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 .5 0 0 0 0 .5 0 0 0 0 .5 0 0 0 1 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23g)'/%3E%3C/svg%3E\")`;\n\ninterface WarpGradientProps extends Omit<ComponentProps<\"div\">, \"children\">, Partial<WarpSettings> {\n  /** A starting point; any setting passed alongside overrides it. */\n  preset?: keyof typeof PRESETS;\n  /** Film grain over the colours, from 0 to 1. */\n  grain?: number;\n}\n\n/**\n * A slow, liquid field of colour: two to five colours laid over bands,\n * cells or a single divide, then carried along by layered noise. It is one\n * WebGL2 fragment shader. Put it inside a positioned element; it fills it.\n * Colours can be theme variables and follow theme switches. It pauses off\n * screen and in background tabs, draws one still frame with\n * `prefers-reduced-motion`, and falls back to a CSS gradient of the same\n * colours where WebGL2 is unavailable.\n *\n * @example\n * <section className=\"relative isolate overflow-hidden rounded-2xl p-12\">\n *   <WarpGradient preset=\"tide\" grain={0.25} />\n *   <h2 className=\"relative text-white\">Into the blue</h2>\n * </section>\n */\nfunction WarpGradient({\n  preset = \"tide\",\n  grain = 0,\n  colors,\n  pattern,\n  density,\n  softness,\n  warp,\n  turbulence,\n  scale,\n  rotation,\n  speed,\n  className,\n  style,\n  ref,\n  ...props\n}: WarpGradientProps) {\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const fallback = useRef<HTMLDivElement>(null);\n  const [observe, inView] = useInView<HTMLDivElement>({ rootMargin: \"100px\" });\n  const mergedRef = useMemo(() => mergeRefs(ref, observe), [ref, observe]);\n\n  const base: WarpSettings = PRESETS[preset] ?? PRESETS.tide;\n  const palette = (colors?.length ? colors : base.colors).slice(0, MAX_COLORS);\n  const paletteKey = palette.join(\"|\");\n  const settings = useRef<WarpSettings>(base);\n  const visible = useRef(false);\n  const wake = useRef<() => void>(() => {});\n  const recolor = useRef<() => void>(() => {});\n\n  useEffect(() => {\n    const element = canvas.current;\n    const gl = element?.getContext(\"webgl2\", { alpha: true, premultipliedAlpha: true });\n    if (!element || !gl) return;\n    const program = compile(gl);\n    if (!program) return;\n    const flat = fallback.current;\n    if (flat) flat.hidden = true;\n\n    const buffer = gl.createBuffer();\n    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n    // One triangle that covers the whole canvas.\n    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n    const position = gl.getAttribLocation(program, \"a_position\");\n    gl.enableVertexAttribArray(position);\n    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);\n    gl.useProgram(program);\n    const names = [\n      \"u_size\",\n      \"u_dpr\",\n      \"u_clock\",\n      \"u_scale\",\n      \"u_turn\",\n      \"u_palette\",\n      \"u_count\",\n      \"u_pattern\",\n      \"u_density\",\n      \"u_softness\",\n      \"u_warp\",\n      \"u_turbulence\",\n    ] as const;\n    const u = Object.fromEntries(\n      names.map((name) => [name, gl.getUniformLocation(program, name)])\n    ) as Record<(typeof names)[number], WebGLUniformLocation | null>;\n\n    const probe = document.createElement(\"span\");\n    probe.style.display = \"none\";\n    element.after(probe);\n    recolor.current = () => {\n      const current = settings.current.colors;\n      const values = new Float32Array(MAX_COLORS * 4);\n      current.forEach((color, index) => values.set(resolveColor(color, probe), index * 4));\n      gl.uniform4fv(u.u_palette, values);\n      gl.uniform1i(u.u_count, Math.max(current.length, 1));\n    };\n\n    let clock = 0;\n    let ratio = 1;\n    const draw = () => {\n      const s = settings.current;\n      gl.uniform2f(u.u_size, element.width, element.height);\n      gl.uniform1f(u.u_dpr, ratio);\n      gl.uniform1f(u.u_clock, clock);\n      gl.uniform1f(u.u_scale, unit(s.scale));\n      gl.uniform1f(u.u_turn, (s.rotation * Math.PI) / 180);\n      gl.uniform1i(u.u_pattern, PATTERNS[s.pattern] ?? 0);\n      gl.uniform1f(u.u_density, unit(s.density));\n      gl.uniform1f(u.u_softness, unit(s.softness));\n      gl.uniform1f(u.u_warp, unit(s.warp));\n      gl.uniform1f(u.u_turbulence, unit(s.turbulence));\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n    };\n\n    const resize = () => {\n      ratio = Math.min(window.devicePixelRatio || 1, 2);\n      element.width = Math.max(1, Math.round(element.clientWidth * ratio));\n      element.height = Math.max(1, Math.round(element.clientHeight * ratio));\n      gl.viewport(0, 0, element.width, element.height);\n      draw();\n    };\n\n    const still = window.matchMedia?.(\"(prefers-reduced-motion: reduce)\");\n    let frame = 0;\n    let last = 0;\n    const loop = (now: number) => {\n      frame = 0;\n      const moving = visible.current && !still?.matches && settings.current.speed !== 0;\n      if (moving && last) clock += ((now - last) / 1000) * settings.current.speed;\n      last = moving ? now : 0;\n      draw();\n      if (moving) frame = requestAnimationFrame(loop);\n    };\n    wake.current = () => {\n      if (!frame) frame = requestAnimationFrame(loop);\n    };\n\n    recolor.current();\n    resize();\n    const resizer = new ResizeObserver(resize);\n    resizer.observe(element);\n    const theme = new MutationObserver(() => {\n      recolor.current();\n      draw();\n    });\n    theme.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: [\"class\", \"style\", \"data-theme\"],\n    });\n    wake.current();\n\n    return () => {\n      cancelAnimationFrame(frame);\n      wake.current = () => {};\n      recolor.current = () => {};\n      resizer.disconnect();\n      theme.disconnect();\n      probe.remove();\n      gl.deleteBuffer(buffer);\n      gl.deleteProgram(program);\n      if (flat) flat.hidden = false;\n    };\n  }, []);\n\n  // Hand the latest settings to the loop and wake it for a fresh frame.\n  useEffect(() => {\n    settings.current = {\n      colors: paletteKey.split(\"|\"),\n      pattern: pattern ?? base.pattern,\n      density: density ?? base.density,\n      softness: softness ?? base.softness,\n      warp: warp ?? base.warp,\n      turbulence: turbulence ?? base.turbulence,\n      scale: scale ?? base.scale,\n      rotation: rotation ?? base.rotation,\n      speed: speed ?? base.speed,\n    };\n    recolor.current();\n    visible.current = inView;\n    wake.current();\n  }, [\n    base,\n    paletteKey,\n    pattern,\n    density,\n    softness,\n    warp,\n    turbulence,\n    scale,\n    rotation,\n    speed,\n    inView,\n  ]);\n\n  return (\n    <div\n      ref={mergedRef}\n      aria-hidden=\"true\"\n      data-slot=\"warp-gradient\"\n      className={cn(\"pointer-events-none absolute inset-0 -z-10 overflow-hidden\", className)}\n      style={style}\n      {...props}\n    >\n      {/* Stands in for the shader where WebGL2 is unavailable. */}\n      <div\n        ref={fallback}\n        data-slot=\"warp-gradient-fallback\"\n        className=\"absolute inset-0\"\n        style={{\n          background: `linear-gradient(${(rotation ?? base.rotation) + 90}deg, ${palette.join(\", \")})`,\n        }}\n      />\n      <canvas ref={canvas} className=\"block size-full\" />\n      {grain > 0 ? (\n        <div\n          data-slot=\"warp-gradient-grain\"\n          className=\"absolute inset-0 mix-blend-overlay\"\n          style={{ backgroundImage: GRAIN, opacity: Math.min(grain, 1) }}\n        />\n      ) : null}\n    </div>\n  );\n}\n\nexport { WarpGradient, type WarpGradientProps };\n",
      "type": "registry:ui"
    }
  ],
  "categories": [
    "background"
  ],
  "type": "registry:ui"
}