{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"portrait-buried-under-sand-in-a-tray-where-the-pointer-drags-a-finger-trail-that-sifts-shut","type":"registry:block","title":"Portrait Buried Under Sand in a Tray Where the Pointer Drags a Finger Trail That Sifts Shut","description":"Cursor effect where a portrait lies under sand in a tray: the pointer ploughs a trail down to the print and the sand sifts shut. Free React and HTML code.","dependencies":["framer-motion"],"files":[{"path":"components/we-inc/portrait-buried-under-sand-in-a-tray-where-the-pointer-drags-a-finger-trail-that-sifts-shut.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\nimport type { PointerEvent as ReactPointerEvent } from \"react\";\nimport { useReducedMotion } from \"framer-motion\";\n\n// The print lying on the glass floor of the tray.\nconst print = {\n  src: \"https://images.pexels.com/photos/9955200/pexels-photo-9955200.jpeg?auto=compress&cs=tinysrgb&w=900\",\n  alt: \"A man in a white beret and white jacket against a blue wall, holding a pink gerbera daisy in front of one eye\",\n};\n\n/** Sand grid across the tray. The picture is drawn far finer than this: the grid only holds how deep the sand lies. */\nconst GW = 128;\nconst GH = 160;\n/** Width of the fingertip, as a share of the tray width. */\nconst FINGER = 0.07;\n/** The steepest wall the sand will hold, as depth per grid cell. Anything steeper collapses at once. */\nconst REPOSE = 0.3;\n/** How quickly the walls of a furrow creep inward, and how quickly grains sift back over bare glass (per second). */\nconst CREEP = 0.55;\nconst LEVEL = 0.011;\n\nconst WALNUT =\n  \"repeating-linear-gradient(91deg, rgba(255,220,180,0.05) 0 1px, rgba(0,0,0,0.07) 1px 3px, rgba(255,220,180,0.02) 3px 7px, rgba(0,0,0,0.04) 7px 12px), linear-gradient(135deg, #7a5333 0%, #4a311d 55%, #36220f 100%)\";\n\nconst VERT = `attribute vec2 a; void main(){ gl_Position = vec4(a, 0.0, 1.0); }`;\n\nconst FRAG = `precision highp float;\nuniform vec2 u_res;\nuniform vec2 u_grid;\nuniform sampler2D u_sand;\nuniform sampler2D u_photo;\nuniform float u_img;\n\nfloat hash(vec2 p){ p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); }\nfloat vnoise(vec2 p){\n  vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f);\n  return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y);\n}\nvec3 bed(vec2 uv){\n  vec2 o = 0.5 / u_grid;\n  return (texture2D(u_sand, uv + o).rgb + texture2D(u_sand, uv - o).rgb + texture2D(u_sand, uv + vec2(o.x, -o.y)).rgb + texture2D(u_sand, uv + vec2(-o.x, o.y)).rgb) * 0.25;\n}\nvec2 cover(vec2 uv){\n  float A = u_res.x / u_res.y;\n  vec2 t = uv;\n  if (u_img > A) t.x = (uv.x - 0.5) * A / u_img + 0.5;\n  else t.y = (uv.y - 0.5) * u_img / A + 0.5;\n  return clamp(t, 0.0, 1.0);\n}\n\nvoid main(){\n  vec2 px = vec2(gl_FragCoord.x, u_res.y - gl_FragCoord.y);\n  vec2 uv = px / u_res;\n  vec3 s = bed(uv);\n  float h = s.r * 2.5;\n  vec2 slope = (s.gb - 0.5) / 1.2;\n\n  // Grains about one screen pixel across, whatever the density of the display.\n  vec2 gp = px / max(1.0, floor(u_res.x / 700.0 + 0.5));\n  float n1 = hash(floor(gp));\n  float n1b = hash(floor(gp) + 19.7);\n  float n2 = hash(floor(gp / 2.0) + 3.1);\n  float mottle = vnoise(gp / 16.0);\n\n  vec2 lamp = normalize(vec2(-0.6, -0.8));\n  vec3 L = normalize(vec3(lamp * 0.92, 0.5));\n\n  // Sand does not end in a line. Where the bed thins it breaks into single grains, and a few are always left behind on the glass.\n  float cov = smoothstep(0.12, 0.48, h + (n2 - 0.5) * 0.36 + (n1 - 0.5) * 0.18);\n  float stray = step(0.9925, hash(floor(gp / 1.5) + 71.3));\n  cov = max(cov, stray * 0.92);\n\n  vec3 n = normalize(vec3(-slope * 3.4 + (vec2(n1, n1b) - 0.5) * 0.6, 1.0));\n  float dif = max(dot(n, L), 0.0);\n  float toward = bed(uv + lamp * 0.011).r * 2.5;\n  float occluded = clamp((toward - h) * 1.3 - 0.05, 0.0, 1.0);\n\n  vec3 grain = mix(vec3(0.80, 0.71, 0.58), vec3(0.60, 0.50, 0.39), n1 * n1);\n  grain = mix(grain, vec3(0.93, 0.88, 0.79), step(0.88, n1b) * 0.6);\n  grain *= 0.92 + 0.16 * mottle;\n  vec3 sand = grain * (0.30 + 1.0 * dif) * (1.0 - 0.5 * occluded);\n  // Flecks of quartz that flash where a slope faces the lamp.\n  sand += vec3(1.0, 0.97, 0.9) * step(0.985, n2) * step(0.5, n1b) * pow(dif, 3.0) * 0.3;\n\n  vec3 photo = texture2D(u_photo, cover(uv)).rgb;\n  // The wall of the furrow nearest the lamp throws its shadow onto the print.\n  photo *= 1.0 - 0.5 * smoothstep(0.15, 0.9, toward) * (1.0 - cov);\n  // A thin film of dust and the faint reflection of the lamp in the glass.\n  photo = photo * 0.93 + 0.035 + 0.05 * smoothstep(0.55, 0.0, abs(uv.x * 0.8 + uv.y - 0.62));\n\n  gl_FragColor = vec4(mix(photo, sand, cov), 1.0);\n}`;\n\nexport default function PortraitBuriedUnderSandInATrayWhereThePointerDragsAFingerTrailThatSiftsShut() {\n  const reduce = useReducedMotion();\n  const well = useRef<HTMLDivElement>(null);\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const photo = useRef<HTMLImageElement>(null);\n  /** The fingertip in tray fractions, where it was a frame ago, and when a person last moved it. */\n  const finger = useRef({ x: 0.5, y: 0.5, px: 0.5, py: 0.5, at: -1e6, moved: false, fresh: true });\n  /** 1 while the sand is brushed off the whole print, and how long the bed is still rushing to its new level. */\n  const bare = useRef({ on: 0, rush: 0 });\n  const [live, setLive] = useState(false);\n  const [cleared, setCleared] = useState(false);\n\n  useEffect(() => {\n    const el = well.current;\n    const cv = canvas.current;\n    const img = photo.current;\n    if (!el || !cv || !img) return;\n    const gl = cv.getContext(\"webgl\", { antialias: false, alpha: false });\n    if (!gl) return;\n\n    const compile = (type: number, source: string) => {\n      const shader = gl.createShader(type)!;\n      gl.shaderSource(shader, source);\n      gl.compileShader(shader);\n      return shader;\n    };\n    const program = gl.createProgram()!;\n    gl.attachShader(program, compile(gl.VERTEX_SHADER, VERT));\n    gl.attachShader(program, compile(gl.FRAGMENT_SHADER, FRAG));\n    gl.linkProgram(program);\n    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return;\n    gl.useProgram(program);\n    gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());\n    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);\n    const at = gl.getAttribLocation(program, \"a\");\n    gl.enableVertexAttribArray(at);\n    gl.vertexAttribPointer(at, 2, gl.FLOAT, false, 0, 0);\n    const u = (name: string) => gl.getUniformLocation(program, name);\n    gl.uniform1i(u(\"u_photo\"), 0);\n    gl.uniform1i(u(\"u_sand\"), 1);\n    gl.uniform2f(u(\"u_grid\"), GW, GH);\n    const texture = (unit: number) => {\n      gl.activeTexture(gl.TEXTURE0 + unit);\n      gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());\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.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n    };\n\n    // Depth of sand in every cell. 1 is the level bed, 0 is bare glass, above 1 is a ridge pushed up beside a furrow.\n    let depth = new Float32Array(GW * GH).fill(1);\n    let spare = new Float32Array(GW * GH);\n    const packed = new Uint8Array(GW * GH * 4);\n    const reach = GW * FINGER;\n\n    /** Press the fingertip down at one spot: scoop out what is under it and bank it up around the edge. */\n    const press = (cx: number, cy: number) => {\n      const out = reach * 1.8;\n      const x0 = Math.max(0, Math.floor(cx - out));\n      const x1 = Math.min(GW - 1, Math.ceil(cx + out));\n      const y0 = Math.max(0, Math.floor(cy - out));\n      const y1 = Math.min(GH - 1, Math.ceil(cy + out));\n      let moved = 0;\n      let room = 0;\n      for (let y = y0; y <= y1; y++) {\n        for (let x = x0; x <= x1; x++) {\n          const i = y * GW + x;\n          const d = Math.hypot(x - cx, y - cy);\n          if (d < reach) {\n            const a = Math.max(0, (d / reach - 0.45) / 0.55);\n            const left = Math.min(depth[i], a * a * (3 - 2 * a) * 1.15);\n            moved += depth[i] - left;\n            depth[i] = left;\n          } else if (d < out) {\n            // Only bank sand onto sand: none of it falls back into the furrow behind the finger.\n            room += Math.sin((Math.PI * (d - reach)) / (out - reach)) * Math.min(1, Math.max(0, (depth[i] - 0.35) / 0.5));\n          }\n        }\n      }\n      if (moved <= 0 || room <= 0) return;\n      const share = (moved * 0.7) / room;\n      for (let y = y0; y <= y1; y++) {\n        for (let x = x0; x <= x1; x++) {\n          const i = y * GW + x;\n          const d = Math.hypot(x - cx, y - cy);\n          if (d >= reach && d < out) {\n            const w = Math.sin((Math.PI * (d - reach)) / (out - reach)) * Math.min(1, Math.max(0, (depth[i] - 0.35) / 0.5));\n            depth[i] = Math.min(2.3, depth[i] + w * share);\n          }\n        }\n      }\n    };\n    const drag = (ax: number, ay: number, bx: number, by: number) => {\n      const steps = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / 1.2));\n      for (let s = 1; s <= steps; s++) press(ax + ((bx - ax) * s) / steps, ay + ((by - ay) * s) / steps);\n    };\n\n    /** Let the bed settle for one tick: walls steeper than sand can hold collapse, the rest creeps, and grains sift back. */\n    const settle = (dt: number, rate: number, level: number) => {\n      const creep = Math.min(0.2, CREEP * dt);\n      const back = Math.min(1, rate * dt);\n      const flow = (d: number) => (d > REPOSE ? (d - REPOSE) * 0.22 : d < -REPOSE ? (d + REPOSE) * 0.22 : 0) + d * creep * 0.25;\n      for (let y = 0; y < GH; y++) {\n        const up = y > 0 ? -GW : 0;\n        const down = y < GH - 1 ? GW : 0;\n        for (let x = 0; x < GW; x++) {\n          const i = y * GW + x;\n          const here = depth[i];\n          const v = here + flow(depth[i + up] - here) + flow(depth[i + down] - here) + flow(depth[x > 0 ? i - 1 : i] - here) + flow(depth[x < GW - 1 ? i + 1 : i] - here);\n          spare[i] = v + (level - v) * back;\n        }\n      }\n      const swap = depth;\n      depth = spare;\n      spare = swap;\n    };\n\n    // With nobody touching it, a slow hand draws one long wandering line.\n    const wander = (t: number): [number, number] => [\n      GW * (0.5 + 0.3 * Math.sin(t * 0.5 + 0.2) + 0.07 * Math.sin(t * 1.31 + 1.0)),\n      GH * (0.47 + 0.33 * Math.sin(t * 0.37 + 1.9) + 0.05 * Math.cos(t * 1.13)),\n    ];\n\n    const draw = () => {\n      for (let y = 0; y < GH; y++) {\n        for (let x = 0; x < GW; x++) {\n          const i = y * GW + x;\n          const sx = (depth[x < GW - 1 ? i + 1 : i] - depth[x > 0 ? i - 1 : i]) * 0.5;\n          const sy = (depth[y < GH - 1 ? i + GW : i] - depth[y > 0 ? i - GW : i]) * 0.5;\n          packed[i * 4] = Math.max(0, Math.min(255, depth[i] * 102));\n          packed[i * 4 + 1] = Math.max(0, Math.min(255, 127.5 + sx * 153));\n          packed[i * 4 + 2] = Math.max(0, Math.min(255, 127.5 + sy * 153));\n          packed[i * 4 + 3] = 255;\n        }\n      }\n      gl.activeTexture(gl.TEXTURE1);\n      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, GW, GH, 0, gl.RGBA, gl.UNSIGNED_BYTE, packed);\n      gl.uniform2f(u(\"u_res\"), cv.width, cv.height);\n      gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n    };\n\n    // It opens with twenty-two seconds of that line already drawn, the oldest end half sifted shut.\n    const LEAD = 22;\n    let lead = wander(-LEAD);\n    for (let t = -LEAD; t < 0; t += 1 / 30) {\n      const next = wander(t);\n      drag(lead[0], lead[1], next[0], next[1]);\n      lead = next;\n      settle(1 / 30, LEVEL, 1);\n    }\n\n    let ready = false;\n    let visible = true;\n    let raf = 0;\n    let last = 0;\n    const started = performance.now();\n\n    const loop = (stamp: number) => {\n      if (ready) {\n        const t = (stamp - started) / 1000;\n        const dt = Math.min(last ? (stamp - last) / 1000 : 0.016, 0.033);\n        last = stamp;\n        const f = finger.current;\n        const b = bare.current;\n        if (f.moved) {\n          const x = f.x * GW;\n          const y = f.y * GH;\n          if (f.fresh) press(x, y);\n          else drag(f.px * GW, f.py * GH, x, y);\n          f.fresh = false;\n          f.px = f.x;\n          f.py = f.y;\n          f.moved = false;\n        }\n        if (reduce) {\n          // No drifting sand: a stroke stays as it was drawn, and the button changes the whole tray at once.\n          if (b.rush > 0) {\n            depth.fill(b.on ? 0 : 1);\n            b.rush = 0;\n          }\n        } else {\n          if (stamp - f.at > 2600 && !b.on) {\n            const next = wander(t);\n            drag(lead[0], lead[1], next[0], next[1]);\n            lead = next;\n          } else lead = wander(t);\n          b.rush = Math.max(0, b.rush - dt);\n          settle(dt, b.rush > 0 ? 2.4 : b.on ? 0.6 : LEVEL, b.on ? 0 : 1);\n        }\n        draw();\n      }\n      raf = visible && !document.hidden && !reduce ? requestAnimationFrame(loop) : 0;\n    };\n    const wake = () => {\n      if (!raf && visible && !document.hidden) {\n        last = 0;\n        raf = requestAnimationFrame(loop);\n      }\n    };\n\n    const resize = () => {\n      const ratio = Math.min(window.devicePixelRatio || 1, 2);\n      cv.width = Math.max(1, Math.round(el.clientWidth * ratio));\n      cv.height = Math.max(1, Math.round(el.clientHeight * ratio));\n      gl.viewport(0, 0, cv.width, cv.height);\n      if (reduce && ready) draw();\n    };\n    const upload = () => {\n      if (ready || !img.complete || !img.naturalWidth) return;\n      try {\n        texture(0);\n        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, img);\n        texture(1);\n        gl.uniform1f(u(\"u_img\"), img.naturalWidth / img.naturalHeight);\n        ready = true;\n        setLive(true);\n        wake();\n      } catch {\n        // The picture could not be read into the shader: the still version underneath stays on show.\n        ready = false;\n      }\n    };\n\n    const ro = new ResizeObserver(resize);\n    ro.observe(el);\n    const io = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      wake();\n    });\n    io.observe(el);\n    document.addEventListener(\"visibilitychange\", wake);\n    img.addEventListener(\"load\", upload);\n    // With motion reduced the loop is not running, so each stroke or button press asks for one redraw.\n    el.addEventListener(\"sand-touched\", wake);\n    resize();\n    upload();\n    wake();\n\n    return () => {\n      cancelAnimationFrame(raf);\n      ro.disconnect();\n      io.disconnect();\n      document.removeEventListener(\"visibilitychange\", wake);\n      img.removeEventListener(\"load\", upload);\n      el.removeEventListener(\"sand-touched\", wake);\n    };\n  }, [reduce]);\n\n  function touch(e: ReactPointerEvent<HTMLDivElement>) {\n    const r = e.currentTarget.getBoundingClientRect();\n    const f = finger.current;\n    const now = performance.now();\n    const x = (e.clientX - r.left) / r.width;\n    const y = (e.clientY - r.top) / r.height;\n    // A press, or a move after a rest, sets the finger down afresh so no line is drawn from where it last was.\n    if (e.type !== \"pointermove\" || now - f.at > 400) {\n      f.fresh = true;\n      f.px = x;\n      f.py = y;\n    }\n    f.x = x;\n    f.y = y;\n    f.at = now;\n    f.moved = true;\n    e.currentTarget.dispatchEvent(new Event(\"sand-touched\"));\n  }\n\n  function toggle() {\n    const next = !cleared;\n    setCleared(next);\n    bare.current = { on: next ? 1 : 0, rush: 1.6 };\n    well.current?.dispatchEvent(new Event(\"sand-touched\"));\n  }\n\n  return (\n    <section className=\"relative isolate flex min-h-[800px] w-full flex-col items-center justify-center overflow-hidden bg-[#14110e] px-4 py-14\">\n      <style>{`\n        .pbs-grain { background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='1.1' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 0.35 0 0 0 0 0.27 0 0 0 0 0.18 0 0 0 0.5 0'/%3E%3C/filter%3E%3Crect width='160' height='160' filter='url(%23n)'/%3E%3C/svg%3E\"); }\n        .pbs-furrow { -webkit-mask: radial-gradient(42% 16% at 46% 30%, transparent 62%, #000 100%); mask: radial-gradient(42% 16% at 46% 30%, transparent 62%, #000 100%); }\n        @media (prefers-reduced-motion: reduce) { .pbs-fade { transition: none; } }\n      `}</style>\n      <div aria-hidden=\"true\" className=\"absolute inset-0 -z-10\" style={{ background: \"radial-gradient(60% 50% at 44% 38%, #2a241e 0%, #14110e 70%)\" }} />\n\n      {/* The tray: a lacquered rim round a shallow well. */}\n      <div className=\"relative w-[min(88vw,470px)] rounded-[22px] bg-[#4a311d] p-[22px] shadow-[inset_0_2px_0_rgba(255,226,190,0.42),inset_2px_0_0_rgba(255,226,190,0.2),inset_0_-4px_6px_rgba(0,0,0,0.6),inset_-3px_0_5px_rgba(0,0,0,0.4),0_0_0_1px_rgba(0,0,0,0.7),0_40px_60px_-20px_rgba(0,0,0,0.9),0_90px_120px_-50px_rgba(0,0,0,0.9)]\" style={{ backgroundImage: WALNUT }}>\n        <div\n          ref={well}\n          onPointerMove={touch}\n          onPointerDown={touch}\n          onPointerEnter={touch}\n          className=\"relative aspect-[4/5] w-full cursor-crosshair touch-pan-y overflow-hidden rounded-[7px] bg-[#b9a585] shadow-[0_1.5px_0_rgba(255,226,190,0.3),1.5px_0_0_rgba(255,226,190,0.14),0_-1px_0_rgba(0,0,0,0.6)]\"\n        >\n          <img ref={photo} src={print.src} alt={print.alt} crossOrigin=\"anonymous\" width={900} height={1350} className=\"absolute inset-0 h-full w-full object-cover\" />\n          {/* The still version: sand with one cleared patch. On show until the shader is ready and whenever WebGL is missing. */}\n          <div aria-hidden=\"true\" className={`pbs-grain pbs-furrow absolute inset-0 bg-[#c9b796] ${cleared ? \"hidden\" : \"\"}`} />\n          <canvas ref={canvas} aria-hidden=\"true\" className={`pbs-fade absolute inset-0 h-full w-full transition-opacity duration-500 ${live ? \"opacity-100\" : \"opacity-0\"}`} />\n          {/* The wall of the well shades the sand along the two edges nearest the lamp. */}\n          <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 rounded-[7px] shadow-[inset_8px_11px_14px_rgba(30,18,6,0.55),inset_2px_3px_3px_rgba(30,18,6,0.5),inset_-1px_-1px_0_rgba(255,255,255,0.16),inset_0_0_0_1px_rgba(0,0,0,0.6)]\" />\n        </div>\n      </div>\n\n      <div className=\"mt-8 flex w-[min(88vw,470px)] items-center justify-between gap-4 px-1 text-[13px]\">\n        <p className=\"text-stone-300\">Draw in the sand.</p>\n        <button\n          type=\"button\"\n          onClick={toggle}\n          aria-pressed={cleared}\n          className=\"min-h-[40px] shrink-0 rounded-full border border-white/15 bg-white/5 px-4 text-[13px] font-medium text-white transition-colors hover:bg-white/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-2 focus-visible:ring-offset-[#14110e]\"\n        >\n          {cleared ? \"Pour the sand back\" : \"Brush the sand off\"}\n        </button>\n      </div>\n    </section>\n  );\n}\n"}]}
