{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "mesh-gradient-avatar",
  "title": "Mesh Gradient Avatar",
  "description": "A default avatar with a unique mesh gradient generated from any seed, like a user ID or email.",
  "dependencies": [
    "@paper-design/shaders-react"
  ],
  "files": [
    {
      "path": "registry/shaders/mesh-gradient-avatar/mesh-gradient-avatar.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { StaticMeshGradient } from \"@paper-design/shaders-react\"\n\nimport { cn } from \"@/lib/utils\"\n\n// Every avatar renders at this size, then gets scaled. Keeping it fixed lets\n// avatars of different sizes share the same cached image.\nconst RENDER_SIZE = 128\n\n// Browsers cap live WebGL contexts per page (around 16), so a long member list\n// can't keep a canvas per avatar. Instead each avatar renders once, is saved\n// as an image, and frees its context. Only a few render at the same time.\nconst MAX_RENDERING = 4\n\nconst cache = new Map<string, string>()\nconst queue: Array<() => void> = []\nlet rendering = 0\n\nfunction acquireSlot() {\n  if (rendering < MAX_RENDERING) {\n    rendering++\n    return Promise.resolve()\n  }\n  return new Promise<void>((resolve) => queue.push(resolve))\n}\n\nfunction releaseSlot() {\n  const next = queue.shift()\n  if (next) next()\n  else rendering--\n}\n\ntype MeshGradientAvatarProps = React.ComponentProps<\"span\"> & {\n  /** Any stable string, like a user ID or email. The same seed always gives the same gradient. */\n  seed: string\n  /** Used as the accessible name. Leave it out for decorative avatars. */\n  name?: string\n  /** Diameter in px. */\n  size?: number\n  /** Override the colors picked from the seed. The shape still follows the seed. */\n  colors?: string[]\n}\n\nfunction MeshGradientAvatar({\n  seed,\n  name,\n  size = 40,\n  colors,\n  className,\n  style,\n  children,\n  ...props\n}: MeshGradientAvatarProps) {\n  const params = getGradient(seed, colors)\n  // Compared by value, so inline color arrays don't trigger a new render.\n  const key = JSON.stringify(params)\n  const [image, setImage] = React.useState<{ key: string; src: string }>()\n  const src = image?.key === key ? image.src : cache.get(key)\n\n  return (\n    <span\n      data-slot=\"mesh-gradient-avatar\"\n      role={name ? \"img\" : undefined}\n      aria-label={name}\n      aria-hidden={name ? undefined : true}\n      className={cn(\n        \"relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full bg-cover\",\n        className\n      )}\n      style={{\n        width: size,\n        height: size,\n        // A plain CSS gradient in the same colors shows until the shader is\n        // ready, and is what the server renders.\n        backgroundImage: src\n          ? `url(${src})`\n          : `linear-gradient(135deg, ${params.colors.join(\", \")})`,\n        ...style,\n      }}\n      {...props}\n    >\n      {!src && (\n        <Snapshot\n          key={key}\n          params={params}\n          scale={size / RENDER_SIZE}\n          onRender={(src) => {\n            cache.set(key, src)\n            setImage({ key, src })\n          }}\n        />\n      )}\n      {children}\n    </span>\n  )\n}\n\nfunction Snapshot({\n  params,\n  scale,\n  onRender,\n}: {\n  params: ReturnType<typeof getGradient>\n  scale: number\n  onRender: (src: string) => void\n}) {\n  const ref = React.useRef<HTMLDivElement>(null)\n  const [ready, setReady] = React.useState(false)\n\n  // Wait for a free slot before mounting the shader.\n  React.useEffect(() => {\n    const element = ref.current\n    let acquired = false\n    let cancelled = false\n\n    acquireSlot().then(() => {\n      if (cancelled) return releaseSlot()\n      acquired = true\n      setReady(true)\n    })\n\n    return () => {\n      cancelled = true\n      if (!acquired) return\n      // Unmounting doesn't free the context until it's garbage collected, so\n      // drop it explicitly before handing the slot to the next avatar.\n      element\n        ?.querySelector(\"canvas\")\n        ?.getContext(\"webgl2\")\n        ?.getExtension(\"WEBGL_lose_context\")\n        ?.loseContext()\n      releaseSlot()\n    }\n  }, [])\n\n  // The shader mounts asynchronously, so poll until its canvas has been sized\n  // and drawn, then save it as an image.\n  React.useEffect(() => {\n    if (!ready) return\n\n    let frame = requestAnimationFrame(function check() {\n      const canvas = ref.current?.querySelector(\"canvas\")\n      if (!canvas?.width) {\n        frame = requestAnimationFrame(check)\n        return\n      }\n      onRender(canvas.toDataURL(\"image/jpeg\", 0.92))\n    })\n\n    return () => cancelAnimationFrame(frame)\n  }, [ready, onRender])\n\n  return (\n    <div\n      ref={ref}\n      aria-hidden\n      className=\"pointer-events-none absolute top-0 left-0 origin-top-left\"\n      style={{\n        width: RENDER_SIZE,\n        height: RENDER_SIZE,\n        // Scale instead of resizing so the canvas always renders at\n        // RENDER_SIZE, whatever size the avatar is shown at.\n        transform: `scale(${scale})`,\n      }}\n    >\n      {ready && (\n        <StaticMeshGradient\n          className=\"size-full\"\n          // Keeps the pixels around after drawing so they can be read back.\n          webGlContextAttributes={{ preserveDrawingBuffer: true }}\n          {...params}\n        />\n      )}\n    </div>\n  )\n}\n\n/** Picks colors and a shape from the seed, so the same seed always matches. */\nfunction getGradient(seed: string, colors?: string[]) {\n  const random = mulberry32(hash(seed))\n  const hue = Math.floor(random() * 360)\n\n  return {\n    // Neighbouring hues only. Opposite hues blend into grey where they meet.\n    colors: colors ?? [\n      `hsl(${hue}, 90%, 58%)`,\n      `hsl(${(hue + 30) % 360}, 95%, 64%)`,\n      `hsl(${(hue + 60) % 360}, 90%, 72%)`,\n      `hsl(${(hue + 100) % 360}, 85%, 62%)`,\n    ],\n    positions: Math.floor(random() * 100),\n    waveX: random(),\n    waveXShift: random(),\n    waveY: random(),\n    waveYShift: random(),\n    rotation: Math.floor(random() * 360),\n    mixing: 0.9,\n    grainMixer: 0,\n    grainOverlay: 0,\n  }\n}\n\n// FNV-1a: turns the seed into a 32-bit number.\nfunction hash(value: string) {\n  let h = 0x811c9dc5\n  for (let i = 0; i < value.length; i++) {\n    h ^= value.charCodeAt(i)\n    h = Math.imul(h, 0x01000193)\n  }\n  return h >>> 0\n}\n\n// A tiny seeded random number generator.\nfunction mulberry32(seed: number) {\n  return () => {\n    seed = (seed + 0x6d2b79f5) | 0\n    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed)\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n  }\n}\n\nexport { MeshGradientAvatar }\n",
      "type": "registry:component"
    }
  ],
  "categories": [
    "components",
    "avatars"
  ],
  "type": "registry:component"
}