{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "fluid-shader",
  "title": "Fluid Shader",
  "description": "A flowing, glossy WebGL fluid background with configurable colours, speed and complexity.",
  "dependencies": [
    "motion"
  ],
  "files": [
    {
      "path": "packages/fluid-shader/fluid-shader.tsx",
      "content": "\"use client\";\r\n\r\nimport { MotionConfigContext } from \"motion/react\";\r\nimport React, { useEffect, useRef, useSyncExternalStore, useContext } from \"react\";\r\nimport { cn } from \"@/lib/utils\";\r\n\r\n/**\r\n * \"user\" (the default) follows a surrounding <MotionConfig reducedMotion>,\r\n * then the visitor's \"reduce motion\" device setting. \"always\" and \"never\"\r\n * force the calm or the full version.\r\n */\r\nexport type ReducedMotion = \"user\" | \"always\" | \"never\";\r\n\r\nconst REDUCED_MOTION_QUERY = \"(prefers-reduced-motion: reduce)\";\r\n\r\nfunction subscribeToReducedMotion(onChange: () => void) {\r\n  const query = window.matchMedia(REDUCED_MOTION_QUERY);\r\n  query.addEventListener(\"change\", onChange);\r\n  return () => query.removeEventListener(\"change\", onChange);\r\n}\r\n\r\n// The prop wins, then MotionConfig, then the device setting. The device is\r\n// read as \"no\" while server rendering, so hydration always matches.\r\nfunction useShouldReduceMotion(mode: ReducedMotion = \"user\") {\r\n  const device = useSyncExternalStore(\r\n    subscribeToReducedMotion,\r\n    () => window.matchMedia(REDUCED_MOTION_QUERY).matches,\r\n    () => false,\r\n  );\r\n  const config = useContext(MotionConfigContext).reducedMotion;\r\n  if (mode !== \"user\") return mode === \"always\";\r\n  if (config === \"always\" || config === \"never\") return config === \"always\";\r\n  return device;\r\n}\r\n\r\n\r\n/**\r\n * Calls onChange(true) while `element` is on screen (or within 200px of it)\r\n * and the tab is showing, and onChange(false) otherwise, so an animation\r\n * loop can sleep while nobody can see it. Returns a function that stops\r\n * watching.\r\n */\r\nfunction watchVisibility(element: Element, onChange: (visible: boolean) => void) {\r\n  let onScreen = true;\r\n  let last: boolean | null = null;\r\n  const update = () => {\r\n    const visible = onScreen && document.visibilityState === \"visible\";\r\n    if (visible !== last) onChange((last = visible));\r\n  };\r\n  const observer =\r\n    typeof IntersectionObserver !== \"undefined\"\r\n      ? new IntersectionObserver(\r\n          ([entry]) => {\r\n            onScreen = entry.isIntersecting;\r\n            update();\r\n          },\r\n          { rootMargin: \"200px\" },\r\n        )\r\n      : null;\r\n  observer?.observe(element);\r\n  document.addEventListener(\"visibilitychange\", update);\r\n  update();\r\n  return () => {\r\n    observer?.disconnect();\r\n    document.removeEventListener(\"visibilitychange\", update);\r\n  };\r\n}\r\n\r\ninterface FluidShaderProps extends Omit<React.ComponentProps<\"div\">, \"color\"> {\r\n  /**\r\n   * Main colour of the flow, as any CSS colour, including a theme variable.\r\n   * @default \"#16a5fe\"\r\n   */\r\n  color?: string;\r\n  /**\r\n   * Second colour of the flow, blended with color. It also tints the rim light.\r\n   * @default \"#47a6ff\"\r\n   */\r\n  accentColor?: string;\r\n  /**\r\n   * Colour the flow fades into at its edges, as any CSS colour. The default matches your\r\n   * theme's page background; set it to the section's colour when it sits on another.\r\n   * @default \"var(--background)\"\r\n   */\r\n  backgroundColor?: string;\r\n  /** How fast the surface moves. 0 freezes it. */\r\n  speed?: number;\r\n  /** How much the flow folds into itself. 0 is smooth; above 1 gets busy. */\r\n  complexity?: number;\r\n  /** Zoom of the pattern. Higher values show smaller, more frequent waves. */\r\n  scale?: number;\r\n  /** Depth of the surface relief. 0 is flat; around 1 to 3 catches the light like liquid. */\r\n  elevation?: number;\r\n  /** Sharpness of the highlight. Higher values give a smaller, glossier glint. */\r\n  glossiness?: number;\r\n  /** Classes for the wrapper. Give it a size: the canvas fills it. */\r\n  className?: string;\r\n  /**\r\n   * \"user\" follows a surrounding MotionConfig, then the visitor's reduce-motion setting.\r\n   * \"always\" and \"never\" force the calm or the full version.\r\n   */\r\n  reducedMotion?: ReducedMotion;\r\n}\r\n\r\ninterface UniformLocations {\r\n  res: WebGLUniformLocation | null;\r\n  time: WebGLUniformLocation | null;\r\n  c1: WebGLUniformLocation | null;\r\n  c2: WebGLUniformLocation | null;\r\n  bg: WebGLUniformLocation | null;\r\n  speed: WebGLUniformLocation | null;\r\n  comp: WebGLUniformLocation | null;\r\n  scale: WebGLUniformLocation | null;\r\n  elev: WebGLUniformLocation | null;\r\n  gloss: WebGLUniformLocation | null;\r\n}\r\n\r\nlet colorProbe: CanvasRenderingContext2D | null | undefined;\r\n\r\n/** Any CSS colour the browser understands, as 0-1 channels for WebGL, by painting one pixel. */\r\nfunction toVec3(css: string): [number, number, number] {\r\n  if (colorProbe === undefined) {\r\n    colorProbe = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\r\n  }\r\n  if (!colorProbe || !css) return [1, 1, 1];\r\n  colorProbe.clearRect(0, 0, 1, 1);\r\n  colorProbe.fillStyle = \"#ffffff\";\r\n  colorProbe.fillStyle = css;\r\n  colorProbe.fillRect(0, 0, 1, 1);\r\n  const [r, g, b] = colorProbe.getImageData(0, 0, 1, 1).data;\r\n  return [r / 255, g / 255, b / 255];\r\n}\r\n\r\nconst FluidShader = ({\r\n  color = \"#16a5fe\",\r\n  accentColor = \"#47a6ff\",\r\n  backgroundColor = \"var(--background)\",\r\n  speed = 0.6,\r\n  complexity = 0.8,\r\n  scale = 2.2,\r\n  elevation = 0,\r\n  glossiness = 53,\r\n  className,\r\n  reducedMotion = \"user\",\r\n  ...props\r\n}: FluidShaderProps) => {\r\n  const canvasRef = useRef<HTMLCanvasElement>(null);\r\n  // Hidden spans that resolve the three colours, which may be CSS variables.\r\n  const colorRefs = useRef<(HTMLSpanElement | null)[]>([]);\r\n  const paletteRef = useRef<{ key: string; vec: [number, number, number][] } | null>(null);\r\n  const animationRef = useRef<number>(0);\r\n  const glRef = useRef<WebGLRenderingContext | null>(null);\r\n  const programRef = useRef<WebGLProgram | null>(null);\r\n  // Reduced motion paints one still frame (repainted on resize) instead of a loop.\r\n  const reduce = useShouldReduceMotion(reducedMotion);\r\n\r\n  // The frame loop reads the latest props from here, so a new colour array on\r\n  // each parent render no longer tears down and recompiles the WebGL program.\r\n  const settings = { speed, complexity, scale, elevation, glossiness };\r\n  const settingsRef = useRef(settings);\r\n  const repaintRef = useRef<() => void>(() => {});\r\n  useEffect(() => {\r\n    settingsRef.current = settings;\r\n    // A still (reduced-motion) frame has no loop to pick changes up.\r\n    repaintRef.current();\r\n  });\r\n\r\n  useEffect(() => {\r\n    const canvas = canvasRef.current;\r\n    if (!canvas) return;\r\n\r\n    const gl =\r\n      canvas.getContext(\"webgl\", { antialias: true }) ||\r\n      (canvas.getContext(\"experimental-webgl\") as WebGLRenderingContext);\r\n    if (!gl) return;\r\n\r\n    glRef.current = gl;\r\n\r\n    // Vertex shader\r\n    const vs =\r\n      \"attribute vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }\";\r\n\r\n    // Fragment shader\r\n    const fs = `\r\n    precision highp float;\r\n    uniform vec2 u_resolution; uniform float u_time;\r\n    uniform vec3 u_color1; uniform vec3 u_color2; uniform vec3 u_bg;\r\n    uniform float u_speed; uniform float u_complexity; uniform float u_scale;\r\n    uniform float u_elevation; uniform float u_glossiness;\r\n\r\n    vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }\r\n    vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }\r\n    vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }\r\n    vec4 permute(vec4 x) { return mod289(((x*34.0)+1.0)*x); }\r\n\r\n    float snoise(vec3 v) {\r\n      const vec2 C = vec2(1.0/6.0, 1.0/3.0); const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\r\n      vec3 i = floor(v + dot(v, C.yyy)); vec3 x0 = v - i + dot(i, C.xxx);\r\n      vec3 g = step(x0.yzx, x0.xyz); vec3 l = 1.0 - g;\r\n      vec3 i1 = min( g.xyz, l.zxy ); vec3 i2 = max( g.xyz, l.zxy );\r\n      vec3 x1 = x0 - i1 + C.xxx; vec3 x2 = x0 - i2 + C.yyy; vec3 x3 = x0 - D.yyy;\r\n      i = mod289(i);\r\n      vec4 p = permute( permute( permute( i.z + vec4(0.0, i1.z, i2.z, 1.0 )) + i.y + vec4(0.0, i1.y, i2.y, 1.0 )) + i.x + vec4(0.0, i1.x, i2.x, 1.0 ));\r\n      float n_ = 0.142857142857; vec3 ns = n_ * D.wyz - D.xzx;\r\n      vec4 j = p - 49.0 * floor(p * ns.z * ns.z);\r\n      vec4 x_ = floor(j * ns.z); vec4 y_ = floor(j - 7.0 * x_);\r\n      vec4 x = x_ *ns.x + ns.yyyy; vec4 y = y_ *ns.x + ns.yyyy;\r\n      vec4 h = 1.0 - abs(x) - abs(y); vec4 b0 = vec4( x.xy, y.xy ); vec4 b1 = vec4( x.zw, y.zw );\r\n      vec4 s0 = floor(b0)*2.0 + 1.0; vec4 s1 = floor(b1)*2.0 + 1.0; vec4 sh = -step(h, vec4(0.0));\r\n      vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy; vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww;\r\n      vec3 p0 = vec3(a0.xy,h.x); vec3 p1 = vec3(a0.zw,h.y); vec3 p2 = vec3(a1.xy,h.z); vec3 p3 = vec3(a1.zw,h.w);\r\n      vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\r\n      p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;\r\n      vec4 m = max(0.5 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\r\n      m = m * m; return 105.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3) ) );\r\n    }\r\n\r\n    float surface(vec2 p) {\r\n        vec3 p3 = vec3(p * u_scale, u_time * u_speed * 0.15);\r\n        float n1 = snoise(p3);\r\n        float n2 = snoise(p3 + vec3(4.1, 2.3, u_time * 0.1) + n1 * u_complexity);\r\n        float n3 = snoise(p3 + vec3(1.2, 5.7, -u_time * 0.1) + n2 * u_complexity);\r\n        return n3;\r\n    }\r\n\r\n    float random(vec2 st) { return fract(sin(dot(st.xy, vec2(12.9898,78.233))) * 43758.5453123); }\r\n\r\n    void main() {\r\n        vec2 uv = gl_FragCoord.xy / u_resolution.xy;\r\n        vec2 p = uv - 0.5;\r\n        p.x *= u_resolution.x / u_resolution.y;\r\n        \r\n        // Topography mapping\r\n        float h = surface(p);\r\n        \r\n        // Calculate 3D Normals\r\n        float eps = 0.01;\r\n        float dx = (surface(p + vec2(eps, 0.0)) - surface(p - vec2(eps, 0.0))) / (2.0 * eps);\r\n        float dy = (surface(p + vec2(0.0, eps)) - surface(p - vec2(0.0, eps))) / (2.0 * eps);\r\n        vec3 normal = normalize(vec3(-dx * u_elevation, -dy * u_elevation, 1.0));\r\n        \r\n        // Lighting Setup\r\n        vec3 lightDir = normalize(vec3(0.5, 0.8, 1.2));\r\n        vec3 viewDir = normalize(vec3(0.0, 0.0, 1.0));\r\n        vec3 halfVector = normalize(lightDir + viewDir);\r\n        \r\n        float diff = max(dot(normal, lightDir), 0.0);\r\n        float spec = pow(max(dot(normal, halfVector), 0.0), u_glossiness);\r\n        float fresnel = pow(1.0 - max(dot(normal, viewDir), 0.0), 3.0);\r\n        \r\n        // Base Color & SSS Fake\r\n        float mixVal = smoothstep(-0.6, 0.6, h);\r\n        vec3 baseColor = mix(u_color1, u_color2, mixVal);\r\n        \r\n        float sss = smoothstep(-0.8, 0.8, h) * 0.3;\r\n        vec3 litColor = baseColor * (diff * 0.6 + 0.4 + sss);\r\n        \r\n        // Specular & Rim\r\n        litColor += vec3(1.0) * spec * 0.4;\r\n        litColor += u_color2 * fresnel * 0.4;\r\n        \r\n        // Inner Ambient Occlusion\r\n        float ao = smoothstep(-0.8, 0.2, h);\r\n        litColor -= (1.0 - ao) * 0.15;\r\n        \r\n        // Masking & Drop Shadow\r\n        float dist = length(p);\r\n        float mask = smoothstep(0.48, 0.15, dist + h * 0.15);\r\n        float shadowMask = smoothstep(0.55, 0.2, length(p - vec2(0.03, -0.06)) + h * 0.1);\r\n        vec3 bgShadowed = mix(u_bg, mix(u_bg, vec3(0.0), 1.0), shadowMask * 0.15);\r\n        \r\n        vec3 finalCol = mix(bgShadowed, litColor, mask);\r\n        \r\n        // Dithering for buttery smooth gradients\r\n        finalCol += (random(uv) - 0.5) * 0.012;\r\n        \r\n        gl_FragColor = vec4(finalCol, 1.0);\r\n    }`;\r\n\r\n    const createShader = (type: number, src: string): WebGLShader | null => {\r\n      const s = gl.createShader(type);\r\n      if (!s) return null;\r\n      gl.shaderSource(s, src);\r\n      gl.compileShader(s);\r\n\r\n      // Check for compilation errors\r\n      if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {\r\n        console.error(\"Shader compilation error:\", gl.getShaderInfoLog(s));\r\n        gl.deleteShader(s);\r\n        return null;\r\n      }\r\n\r\n      return s;\r\n    };\r\n\r\n    const prog = gl.createProgram();\r\n    if (!prog) return;\r\n\r\n    programRef.current = prog;\r\n\r\n    const vsShader = createShader(gl.VERTEX_SHADER, vs);\r\n    const fsShader = createShader(gl.FRAGMENT_SHADER, fs);\r\n\r\n    if (!vsShader || !fsShader) {\r\n      console.error(\"Failed to create shaders\");\r\n      return;\r\n    }\r\n\r\n    gl.attachShader(prog, vsShader);\r\n    gl.attachShader(prog, fsShader);\r\n    gl.linkProgram(prog);\r\n\r\n    // Check for linking errors\r\n    if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {\r\n      console.error(\"Program linking error:\", gl.getProgramInfoLog(prog));\r\n      return;\r\n    }\r\n\r\n    gl.useProgram(prog);\r\n\r\n    // Set up geometry\r\n    const buffer = gl.createBuffer();\r\n    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\r\n    gl.bufferData(\r\n      gl.ARRAY_BUFFER,\r\n      new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),\r\n      gl.STATIC_DRAW,\r\n    );\r\n\r\n    const pos = gl.getAttribLocation(prog, \"p\");\r\n    gl.enableVertexAttribArray(pos);\r\n    gl.vertexAttribPointer(pos, 2, gl.FLOAT, false, 0, 0);\r\n\r\n    // Get uniform locations\r\n    const loc: UniformLocations = {\r\n      res: gl.getUniformLocation(prog, \"u_resolution\"),\r\n      time: gl.getUniformLocation(prog, \"u_time\"),\r\n      c1: gl.getUniformLocation(prog, \"u_color1\"),\r\n      c2: gl.getUniformLocation(prog, \"u_color2\"),\r\n      bg: gl.getUniformLocation(prog, \"u_bg\"),\r\n      speed: gl.getUniformLocation(prog, \"u_speed\"),\r\n      comp: gl.getUniformLocation(prog, \"u_complexity\"),\r\n      scale: gl.getUniformLocation(prog, \"u_scale\"),\r\n      elev: gl.getUniformLocation(prog, \"u_elevation\"),\r\n      gloss: gl.getUniformLocation(prog, \"u_glossiness\"),\r\n    };\r\n\r\n    // Resize handler\r\n    // Render at the canvas's own CSS size so it works inside any container.\r\n    const resize = () => {\r\n      const dpr = Math.min(window.devicePixelRatio || 1, 2);\r\n      const w = canvas.clientWidth || window.innerWidth;\r\n      const h = canvas.clientHeight || window.innerHeight;\r\n      canvas.width = Math.max(1, Math.round(w * dpr));\r\n      canvas.height = Math.max(1, Math.round(h * dpr));\r\n      gl.viewport(0, 0, canvas.width, canvas.height);\r\n      // Resizing clears the canvas, so a still frame has to be painted again.\r\n      repaintRef.current();\r\n    };\r\n\r\n    const paintOnce = () => {\r\n      cancelAnimationFrame(animationRef.current);\r\n      animationRef.current = requestAnimationFrame(() => draw());\r\n    };\r\n    repaintRef.current = reduce ? paintOnce : () => {};\r\n\r\n    window.addEventListener(\"resize\", resize);\r\n    const observer = typeof ResizeObserver !== \"undefined\" ? new ResizeObserver(resize) : null;\r\n    observer?.observe(canvas);\r\n    resize();\r\n\r\n    // Time only advances while frames are drawn, so after sleeping off-screen\r\n    // the surface carries on from where it stopped instead of jumping ahead.\r\n    let elapsed = 0;\r\n    let last = performance.now();\r\n\r\n    // Animation loop\r\n    const draw = () => {\r\n      if (!gl || !prog) return;\r\n      const { speed, complexity, scale, elevation, glossiness } = settingsRef.current;\r\n      const now = performance.now();\r\n      elapsed += Math.min(0.1, (now - last) / 1000);\r\n      last = now;\r\n\r\n      // Read the colours back every frame, so a theme change shows at once.\r\n      // getComputedStyle is cheap, and they are only re-parsed when they change.\r\n      const css = colorRefs.current.map((el) => (el ? getComputedStyle(el).color : \"\"));\r\n      const key = css.join(\"|\");\r\n      if (paletteRef.current?.key !== key) {\r\n        paletteRef.current = { key, vec: css.map(toVec3) };\r\n      }\r\n      const [color1, color2, background] = paletteRef.current.vec;\r\n\r\n      // Update uniforms\r\n      if (loc.res) gl.uniform2f(loc.res, canvas.width, canvas.height);\r\n      if (loc.time)\r\n        gl.uniform1f(loc.time, reduce ? 0 : elapsed);\r\n      if (loc.c1) gl.uniform3fv(loc.c1, color1);\r\n      if (loc.c2) gl.uniform3fv(loc.c2, color2);\r\n      if (loc.bg) gl.uniform3fv(loc.bg, background);\r\n      if (loc.speed) gl.uniform1f(loc.speed, speed);\r\n      if (loc.comp) gl.uniform1f(loc.comp, complexity);\r\n      if (loc.scale) gl.uniform1f(loc.scale, scale);\r\n      if (loc.elev) gl.uniform1f(loc.elev, elevation);\r\n      if (loc.gloss) gl.uniform1f(loc.gloss, glossiness);\r\n\r\n      gl.drawArrays(gl.TRIANGLES, 0, 6);\r\n\r\n      if (!reduce) animationRef.current = requestAnimationFrame(draw);\r\n    };\r\n\r\n    draw();\r\n\r\n    // A still frame repaints when the theme changes (a class or attribute on\r\n    // <html>), since there is no loop to pick up the new colours.\r\n    const themeObserver =\r\n      reduce && typeof MutationObserver !== \"undefined\" ? new MutationObserver(paintOnce) : null;\r\n    themeObserver?.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\r\n\r\n    // The loop runs only while the canvas can be seen: scrolled away or in a\r\n    // hidden tab it stops drawing. A reduced-motion still frame has no loop.\r\n    const stopWatching = reduce\r\n      ? () => {}\r\n      : watchVisibility(canvas, (visible) => {\r\n          cancelAnimationFrame(animationRef.current);\r\n          animationRef.current = 0;\r\n          if (visible) {\r\n            last = performance.now();\r\n            animationRef.current = requestAnimationFrame(draw);\r\n          }\r\n        });\r\n\r\n    // Cleanup\r\n    return () => {\r\n      stopWatching();\r\n      themeObserver?.disconnect();\r\n      repaintRef.current = () => {};\r\n      window.removeEventListener(\"resize\", resize);\r\n      observer?.disconnect();\r\n      if (animationRef.current) {\r\n        cancelAnimationFrame(animationRef.current);\r\n      }\r\n\r\n      if (gl && prog) {\r\n        // Clean up WebGL resources\r\n        gl.deleteShader(vsShader);\r\n        gl.deleteShader(fsShader);\r\n        gl.deleteProgram(prog);\r\n        gl.deleteBuffer(buffer);\r\n      }\r\n    };\r\n  }, [reduce]);\r\n\r\n  return (\r\n    <div className={cn(\"relative\", className)} {...props}>\r\n      <canvas ref={canvasRef} aria-hidden=\"true\" className=\"absolute inset-0 block size-full\" />\r\n      {[color, accentColor, backgroundColor].map((c, i) => (\r\n        <span\r\n          key={i}\r\n          ref={(el) => {\r\n            colorRefs.current[i] = el;\r\n          }}\r\n          hidden\r\n          style={{ color: c }}\r\n        />\r\n      ))}\r\n    </div>\r\n  );\r\n};\r\n\r\nexport default FluidShader;\r\n",
      "type": "registry:component",
      "target": "components/satori-ui/fluid-shader.tsx"
    }
  ],
  "meta": {
    "usage": "<FluidShader className=\"h-[480px] w-full\" />"
  },
  "type": "registry:component"
}