{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"tile-smear","type":"registry:ui","title":"Tile Smear","description":"An image on a grid of tiles that smear along with the cursor and ease back into place.","dependencies":[],"registryDependencies":[],"files":[{"path":"registry/ui/tile-smear.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\nexport interface TileSmearProps {\n  /** Image URL. Remote images need CORS headers (it becomes a WebGL texture). */\n  imageSrc: string;\n  /** Grid cells per side. */\n  grid?: number;\n  /** Radius of cursor influence, as a fraction of the height. */\n  mouseRadius?: number;\n  /** How far cells get dragged by the cursor. */\n  strength?: number;\n  /** Per-frame easing back to rest, 0-1; higher is slower. */\n  relaxation?: number;\n  className?: string;\n}\n\nconst FRAG = `\nprecision highp float;\nuniform vec2 uRes;\nuniform sampler2D uImg;\nuniform sampler2D uGrid;\nuniform vec2 uScale;\nuniform float uReady;\n\n// offsets are packed as 16-bit fixed point in RG (x) and BA (y), range -0.5..0.5\nvec2 offsetAt(vec2 uv) {\n  vec4 g = texture2D(uGrid, uv) * 255.0;\n  return vec2(g.r * 256.0 + g.g, g.b * 256.0 + g.a) / 65535.0 - 0.5;\n}\n\nvoid main() {\n  vec2 uv = gl_FragCoord.xy / uRes;\n  vec2 o = offsetAt(uv);\n  vec2 iuv = (uv - o - 0.5) * uScale + 0.5;\n  vec2 ca = o * 0.03;\n  vec3 col = vec3(\n    texture2D(uImg, iuv + ca).r,\n    texture2D(uImg, iuv).g,\n    texture2D(uImg, iuv - ca).b);\n  col *= 1.0 - 0.25 * length(uv - 0.5);\n  gl_FragColor = vec4(col, 1.0) * uReady;\n}\n`;\n\nconst VERT = \"attribute vec2 p;void main(){gl_Position=vec4(p,0.,1.);}\";\n\ntype Ptr = { x: number; y: number; hover: number };\ntype Uni = (name: string) => WebGLUniformLocation | null;\n\n/** Full-screen shader canvas inside `host`: DPR-capped resize, offscreen pause, reduced motion, eased pointer. */\nfunction runShader(host: HTMLElement, frag: string, speed: () => number, update: (gl: WebGLRenderingContext, u: Uni, pointer: Ptr) => void) {\n  const canvas = document.createElement(\"canvas\");\n  canvas.style.cssText = \"position:absolute;inset:0;width:100%;height:100%;display:block\";\n  const gl = canvas.getContext(\"webgl\", { antialias: false });\n  if (!gl) return null;\n  const prog = gl.createProgram()!;\n  for (const [type, src] of [\n    [gl.VERTEX_SHADER, VERT],\n    [gl.FRAGMENT_SHADER, frag],\n  ] as const) {\n    const sh = gl.createShader(type)!;\n    gl.shaderSource(sh, src);\n    gl.compileShader(sh);\n    if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) console.warn(gl.getShaderInfoLog(sh));\n    gl.attachShader(prog, sh);\n  }\n  gl.bindAttribLocation(prog, 0, \"p\");\n  gl.linkProgram(prog);\n  if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {\n    gl.getExtension(\"WEBGL_lose_context\")?.loseContext();\n    return null;\n  }\n  gl.useProgram(prog);\n  gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n  gl.enableVertexAttribArray(0);\n  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);\n  host.appendChild(canvas);\n\n  const locs = new Map<string, WebGLUniformLocation | null>();\n  const u: Uni = (n) => {\n    if (!locs.has(n)) locs.set(n, gl.getUniformLocation(prog, n));\n    return locs.get(n) ?? null;\n  };\n  const zone = host.parentElement ?? host;\n  const reduced = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n  const ptr: Ptr = { x: 0.5, y: 0.5, hover: 0 };\n  const goal: Ptr = { ...ptr };\n  let raf = 0;\n  let last = 0;\n  let time = 0;\n\n  const draw = () => {\n    gl.uniform2f(u(\"uRes\"), canvas.width, canvas.height);\n    gl.uniform1f(u(\"uTime\"), time);\n    gl.uniform2f(u(\"uMouse\"), ptr.x, ptr.y);\n    gl.uniform1f(u(\"uHover\"), ptr.hover);\n    update(gl, u, goal);\n    gl.drawArrays(gl.TRIANGLES, 0, 3);\n  };\n  const loop = (now: number) => {\n    const dt = Math.min((now - last) / 1000, 0.1);\n    last = now;\n    const k = 1 - Math.exp(-dt * 4);\n    for (const key of [\"x\", \"y\", \"hover\"] as const) ptr[key] += (goal[key] - ptr[key]) * k;\n    time += dt * speed();\n    draw();\n    raf = requestAnimationFrame(loop);\n  };\n  const run = (on: boolean) => {\n    if (on && !raf && !reduced) {\n      last = performance.now();\n      raf = requestAnimationFrame(loop);\n    } else if (!on && raf) {\n      cancelAnimationFrame(raf);\n      raf = 0;\n    }\n  };\n  const resize = () => {\n    const dpr = Math.min(window.devicePixelRatio || 1, 2);\n    canvas.width = Math.max(1, Math.round(host.clientWidth * dpr));\n    canvas.height = Math.max(1, Math.round(host.clientHeight * dpr));\n    gl.viewport(0, 0, canvas.width, canvas.height);\n    draw();\n  };\n  const move = (e: PointerEvent) => {\n    const r = host.getBoundingClientRect();\n    goal.x = (e.clientX - r.left) / r.width;\n    goal.y = 1 - (e.clientY - r.top) / r.height;\n    goal.hover = 1;\n  };\n  const leave = () => {\n    goal.hover = 0;\n  };\n  const ro = new ResizeObserver(resize);\n  const io = new IntersectionObserver(([e]) => run(e.isIntersecting));\n  ro.observe(host);\n  io.observe(host);\n  zone.addEventListener(\"pointermove\", move);\n  zone.addEventListener(\"pointerleave\", leave);\n  return {\n    gl,\n    redraw: () => {\n      if (!raf) draw();\n    },\n    dispose: () => {\n      run(false);\n      ro.disconnect();\n      io.disconnect();\n      zone.removeEventListener(\"pointermove\", move);\n      zone.removeEventListener(\"pointerleave\", leave);\n      gl.getExtension(\"WEBGL_lose_context\")?.loseContext();\n      canvas.remove();\n    },\n  };\n}\n\nexport function TileSmear({\n  imageSrc,\n  grid = 15,\n  mouseRadius = 0.18,\n  strength = 1,\n  relaxation = 0.92,\n  className,\n}: TileSmearProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const opts = useRef({ grid, mouseRadius, strength, relaxation });\n  const api = useRef<ReturnType<typeof runShader>>(null);\n  const image = useRef<{ tex: WebGLTexture; w: number; h: number } | null>(null);\n\n  useEffect(() => {\n    opts.current = { grid, mouseRadius, strength, relaxation };\n    api.current?.redraw();\n  }, [grid, mouseRadius, strength, relaxation]);\n\n  useEffect(() => {\n    let size = 0;\n    let offsets = new Float32Array(0);\n    let bytes = new Uint8Array(0);\n    let gridTex: WebGLTexture | null = null;\n    let prev = { x: 0.5, y: 0.5 };\n    let last = performance.now();\n\n    const r = runShader(\n      ref.current!,\n      FRAG,\n      () => 1,\n      (gl, u, goal) => {\n        const o = opts.current;\n        const now = performance.now();\n        const dt = Math.min((now - last) / 1000, 0.1);\n        last = now;\n        const G = Math.max(2, Math.round(o.grid));\n        if (G !== size) {\n          size = G;\n          offsets = new Float32Array(G * G * 2);\n          bytes = new Uint8Array(G * G * 4);\n        }\n        // drag cells near the cursor along its motion, then ease everything back\n        const vx = goal.x - prev.x;\n        const vy = goal.y - prev.y;\n        prev = { x: goal.x, y: goal.y };\n        const asp = gl.drawingBufferWidth / gl.drawingBufferHeight;\n        const R = Math.max(0.01, o.mouseRadius);\n        const decay = Math.pow(Math.min(Math.max(o.relaxation, 0), 0.999), dt * 60);\n        for (let j = 0; j < G; j++) {\n          for (let i = 0; i < G; i++) {\n            const k = (j * G + i) * 2;\n            const d = Math.hypot(((i + 0.5) / G - goal.x) * asp, (j + 0.5) / G - goal.y);\n            if (goal.hover > 0 && d < R) {\n              const f = (1 - d / R) * o.strength;\n              offsets[k] += vx * f;\n              offsets[k + 1] += vy * f;\n            }\n            for (let c = 0; c < 2; c++) {\n              const v = Math.min(0.5, Math.max(-0.5, offsets[k + c] * decay));\n              offsets[k + c] = v;\n              const q = Math.round((v + 0.5) * 65535);\n              bytes[k * 2 + c * 2] = q >> 8;\n              bytes[k * 2 + c * 2 + 1] = q & 255;\n            }\n          }\n        }\n        gridTex ??= gl.createTexture();\n        gl.activeTexture(gl.TEXTURE1);\n        gl.bindTexture(gl.TEXTURE_2D, gridTex);\n        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);\n        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, G, G, 0, gl.RGBA, gl.UNSIGNED_BYTE, bytes);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n        gl.uniform1i(u(\"uGrid\"), 1);\n\n        const img = image.current;\n        gl.activeTexture(gl.TEXTURE0);\n        gl.bindTexture(gl.TEXTURE_2D, img?.tex ?? null);\n        gl.uniform1i(u(\"uImg\"), 0);\n        gl.uniform1f(u(\"uReady\"), img ? 1 : 0);\n        if (img) {\n          // cover-fit the image\n          const ia = img.w / img.h;\n          gl.uniform2f(u(\"uScale\"), asp > ia ? 1 : asp / ia, asp > ia ? ia / asp : 1);\n        }\n      },\n    );\n    api.current = r;\n    return () => {\n      r?.dispose();\n      api.current = null;\n      image.current = null;\n    };\n  }, []);\n\n  useEffect(() => {\n    const gl = api.current?.gl;\n    if (!gl) return;\n    let cancelled = false;\n    const img = new Image();\n    img.crossOrigin = \"anonymous\";\n    img.onload = () => {\n      if (cancelled || gl.isContextLost()) return;\n      const tex = image.current?.tex ?? gl.createTexture()!;\n      gl.activeTexture(gl.TEXTURE0);\n      gl.bindTexture(gl.TEXTURE_2D, tex);\n      gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n      image.current = { tex, w: img.naturalWidth, h: img.naturalHeight };\n      api.current?.redraw();\n    };\n    img.src = imageSrc;\n    return () => {\n      cancelled = true;\n    };\n  }, [imageSrc]);\n\n  return (\n    <div\n      ref={ref}\n      aria-hidden\n      className={className}\n      style={{ position: \"absolute\", inset: 0, overflow: \"hidden\", pointerEvents: \"none\" }}\n    />\n  );\n}\n"}]}