{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sticker-avatar",
  "title": "Sticker avatar",
  "author": "Tori Bryan",
  "description": "An avatar cut out like a die-cut sticker, with a paper edge that follows its shape and a status told by shape.",
  "dependencies": [],
  "registryDependencies": [
    "https://fibo.toribryan.com/r/status-dot.json",
    "https://fibo.toribryan.com/r/count.json",
    "utils"
  ],
  "files": [
    {
      "path": "registry/ui/sticker-avatar.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport {\n  StatusDotHostProvider,\n  useStatusDotHost,\n} from \"@/components/ui/status-dot\"\nimport { Count, type CountProps } from \"@/components/ui/count\"\nimport { cn } from \"@/lib/utils\"\n\n/** How the sticker was cut: from the image's own shape, round, or from initials. */\ntype StickerAvatarShape = \"cutout\" | \"round\" | \"initials\"\n\n// Big uploads are scaled down before anything is measured or stamped.\nconst MAX_SOURCE = 512\n\n/** The paper edge for a size: one sixteenth of it, never under 2px. */\nfunction stickerEdge(size: number) {\n  return Math.max(2, Math.round(size / 16))\n}\n\n/*\n * A stable tilt from the name, between about -6.6 and 6.6 degrees, so each\n * person looks hand-placed and stays that way across renders and devices.\n */\nfunction stickerTilt(seed: string) {\n  let hash = 2166136261\n  for (const char of seed) hash = Math.imul(hash ^ char.charCodeAt(0), 16777619)\n  return (((hash >>> 0) % 13) - 6) * 1.1\n}\n\nfunction initials(name: string) {\n  const words = name.trim().split(/\\s+/)\n  const first = words[0]?.[0] ?? \"\"\n  const last = words.length > 1 ? (words[words.length - 1]?.[0] ?? \"\") : \"\"\n  return (first + last).toUpperCase()\n}\n\nclass StickerError extends Error {\n  constructor(readonly reason: \"load\" | \"taint\") {\n    super(reason)\n  }\n}\n\nfunction loadImage(src: string, cors: boolean) {\n  return new Promise<HTMLImageElement>((resolve, reject) => {\n    const img = new Image()\n    if (cors) img.crossOrigin = \"anonymous\"\n    img.onload = () => resolve(img)\n    img.onerror = () => reject(new StickerError(\"load\"))\n    img.src = src\n  })\n}\n\n// Reading pixels needs CORS. A host without it still serves the image, so\n// try again plainly: if that loads, the image is fine but can't be cut.\nasync function loadReadableImage(src: string) {\n  try {\n    return await loadImage(src, true)\n  } catch {\n    await loadImage(src, false)\n    throw new StickerError(\"taint\")\n  }\n}\n\nfunction makeCanvas(width: number, height = width) {\n  const canvas = document.createElement(\"canvas\")\n  canvas.width = width\n  canvas.height = height\n  return canvas\n}\n\n// A cut-out has a mostly clear border. A photo with its background still on\n// has nothing to follow, so it becomes a round sticker instead.\nfunction hasClearBorder(data: Uint8ClampedArray, w: number, h: number) {\n  let clear = 0\n  let total = 0\n  const step = Math.max(1, Math.floor(Math.max(w, h) / 64))\n  const sample = (x: number, y: number) => {\n    total++\n    if ((data[(y * w + x) * 4 + 3] ?? 0) < 16) clear++\n  }\n  for (let x = 0; x < w; x += step) {\n    sample(x, 0)\n    sample(x, h - 1)\n  }\n  for (let y = 0; y < h; y += step) {\n    sample(0, y)\n    sample(w - 1, y)\n  }\n  return clear / total > 0.5\n}\n\nfunction drawnBounds(data: Uint8ClampedArray, w: number, h: number) {\n  let x0 = w\n  let y0 = h\n  let x1 = -1\n  let y1 = -1\n  for (let y = 0; y < h; y++) {\n    for (let x = 0; x < w; x++) {\n      if ((data[(y * w + x) * 4 + 3] ?? 0) <= 12) continue\n      x0 = Math.min(x0, x)\n      y0 = Math.min(y0, y)\n      x1 = Math.max(x1, x)\n      y1 = Math.max(y1, y)\n    }\n  }\n  return x1 < 0 ? null : { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 }\n}\n\ntype BakeOptions = {\n  size: number\n  edge: number\n  color: string\n  cutout: \"auto\" | \"shape\" | \"round\"\n  pixelated: boolean\n}\n\ntype Baked = { url: string; shape: \"cutout\" | \"round\" }\n\n// Each bake holds a data URL, so a long scrolling list of people must not\n// keep every one it has ever shown. A Map iterates in insertion order, so\n// re-inserting on a hit makes the first key the least recently used.\nconst MAX_BAKES = 64\nconst bakes = new Map<string, Promise<Baked>>()\n\n/*\n * Draws the die-cut once, on a canvas, and hands back a plain image. A live\n * SVG filter would rerun on every paint of every row, and is slow in Safari;\n * stamping a silhouette round a circle is smooth at any edge width and costs\n * nothing after the first frame.\n */\nfunction bakeSticker(src: string, options: BakeOptions): Promise<Baked> {\n  const dpr = Math.min(2, window.devicePixelRatio || 1)\n  const key = JSON.stringify([src, options, dpr])\n  const cached = bakes.get(key)\n  if (cached) {\n    bakes.delete(key)\n    bakes.set(key, cached)\n    return cached\n  }\n\n  const job = (async (): Promise<Baked> => {\n    const img = await loadReadableImage(src)\n    const scale = Math.min(\n      1,\n      MAX_SOURCE / Math.max(img.naturalWidth, img.naturalHeight, 1)\n    )\n    const w = Math.max(1, Math.round(img.naturalWidth * scale))\n    const h = Math.max(1, Math.round(img.naturalHeight * scale))\n    const source = makeCanvas(w, h)\n    const sourceCtx = source.getContext(\"2d\")!\n    sourceCtx.imageSmoothingEnabled = !options.pixelated\n    sourceCtx.drawImage(img, 0, 0, w, h)\n    let data: Uint8ClampedArray\n    try {\n      data = sourceCtx.getImageData(0, 0, w, h).data\n    } catch {\n      throw new StickerError(\"taint\")\n    }\n\n    const shape =\n      options.cutout === \"round\" ||\n      (options.cutout === \"auto\" && !hasClearBorder(data, w, h))\n        ? \"round\"\n        : \"cutout\"\n\n    const px = Math.max(1, Math.round(options.size * dpr))\n    const edge = Math.round(options.edge * dpr)\n    const art = makeCanvas(px)\n    const artCtx = art.getContext(\"2d\")!\n    artCtx.imageSmoothingEnabled = !options.pixelated\n    if (shape === \"cutout\") {\n      // Trimmed and centered, so every subject fills its sticker the same way\n      // however much empty space its file has round it.\n      const box = drawnBounds(data, w, h) ?? { x: 0, y: 0, w, h }\n      const fit = px / Math.max(box.w, box.h)\n      artCtx.drawImage(\n        source,\n        box.x,\n        box.y,\n        box.w,\n        box.h,\n        (px - box.w * fit) / 2,\n        (px - box.h * fit) / 2,\n        box.w * fit,\n        box.h * fit\n      )\n    } else {\n      const side = Math.min(w, h)\n      artCtx.beginPath()\n      artCtx.arc(px / 2, px / 2, px / 2, 0, Math.PI * 2)\n      artCtx.clip()\n      artCtx.drawImage(\n        source,\n        (w - side) / 2,\n        (h - side) / 2,\n        side,\n        side,\n        0,\n        0,\n        px,\n        px\n      )\n    }\n\n    const out = makeCanvas(px + edge * 2)\n    const ctx = out.getContext(\"2d\")!\n    if (edge > 0) {\n      const silhouette = makeCanvas(px)\n      const silhouetteCtx = silhouette.getContext(\"2d\")!\n      silhouetteCtx.drawImage(art, 0, 0)\n      silhouetteCtx.globalCompositeOperation = \"source-in\"\n      silhouetteCtx.fillStyle = \"#ffffff\"\n      // Ignored if the browser can't parse the color, leaving white paper.\n      silhouetteCtx.fillStyle = options.color\n      silhouetteCtx.fillRect(0, 0, px, px)\n      const steps = Math.max(24, Math.ceil(edge * 10))\n      for (const radius of [edge, edge / 2]) {\n        for (let i = 0; i < steps; i++) {\n          const angle = (i / steps) * Math.PI * 2\n          ctx.drawImage(\n            silhouette,\n            edge + Math.cos(angle) * radius,\n            edge + Math.sin(angle) * radius\n          )\n        }\n      }\n    }\n    ctx.drawImage(art, edge, edge)\n    return { url: out.toDataURL(\"image/png\"), shape }\n  })()\n\n  bakes.set(key, job)\n  if (bakes.size > MAX_BAKES) bakes.delete(bakes.keys().next().value!)\n  job.catch(() => bakes.delete(key))\n  return job\n}\n\n// A hairline keeps white paper visible on a white page, then the lift\n// shadow. Both are drop-shadows, so they follow the cut, not the box.\nconst PAPER_SHADOW =\n  \"[filter:drop-shadow(0_0_0.5px_var(--ring))_drop-shadow(0_calc(var(--sticker-edge-width)*0.35)_calc(var(--sticker-edge-width)*0.5)_var(--sticker-shadow))] transition-[filter] duration-200\"\nconst PAPER_SHADOW_LIFTED =\n  \"motion-safe:group-hover/sticker-avatar:[filter:drop-shadow(0_0_0.5px_var(--ring))_drop-shadow(0_calc(var(--sticker-edge-width)*1.1)_calc(var(--sticker-edge-width)*1.4)_var(--sticker-shadow))] motion-safe:group-hover/sticker:[filter:drop-shadow(0_0_0.5px_var(--ring))_drop-shadow(0_calc(var(--sticker-edge-width)*1.1)_calc(var(--sticker-edge-width)*1.4)_var(--sticker-shadow))]\"\n\n// A StatusDot child sits on the corner like a second, smaller sticker: it\n// turns against the avatar's tilt and casts the same shadow.\nconst STATUS_PLACEMENT =\n  \"*:data-[slot=status-dot]:absolute *:data-[slot=status-dot]:-right-[6%] *:data-[slot=status-dot]:-bottom-[6%] *:data-[slot=status-dot]:size-[34%] *:data-[slot=status-dot]:min-h-[11px] *:data-[slot=status-dot]:min-w-[11px] *:data-[slot=status-dot]:rotate-[calc(var(--sticker-tilt)*-2)] *:data-[slot=status-dot]:[filter:drop-shadow(0_0_0.5px_var(--ring))_drop-shadow(0_1px_1px_var(--sticker-shadow))]\"\n\ntype StickerAvatarProps = React.ComponentProps<\"span\"> & {\n  /** The person's name. Their accessible name, the seed for the tilt, and the initials when there is no image. */\n  name: string\n  /** Image URL. A transparent cut-out gets a die-cut edge; a photo with a background becomes round. */\n  src?: string\n  /** Width and height in pixels. The edge and tilt are drawn outside this box. */\n  size?: number\n  /** Paper edge in pixels. Defaults to one sixteenth of the size, never under 2px. */\n  edge?: number\n  /** `true` tilts by a stable angle from the name, a number sets degrees, `false` keeps it straight. */\n  tilt?: boolean | number\n  /** Lifts on hover, and when hovering an ancestor with `group/sticker`. */\n  lift?: boolean\n  /** `auto` follows the image's own shape when its border is clear; `shape` or `round` forces one. */\n  cutout?: \"auto\" | \"shape\" | \"round\"\n  /** Keeps hard pixel edges when scaling pixel art. */\n  pixelated?: boolean\n}\n\nfunction StickerAvatar({\n  name,\n  src,\n  size = 40,\n  edge,\n  tilt = true,\n  lift = true,\n  cutout = \"auto\",\n  pixelated = false,\n  className,\n  style,\n  children,\n  ...props\n}: StickerAvatarProps) {\n  const nameId = React.useId()\n  const { labelledBy, host } = useStatusDotHost()\n  const ref = React.useRef<HTMLSpanElement>(null)\n  const edgeWidth = edge ?? stickerEdge(size)\n  const angle =\n    tilt === false ? 0 : typeof tilt === \"number\" ? tilt : stickerTilt(name)\n  const [result, setResult] = React.useState<{\n    src: string\n    baked?: Baked\n    failed?: \"load\" | \"taint\"\n  } | null>(null)\n  const request = React.useRef<string | null>(null)\n\n  // `--sticker-edge` can be overridden on any ancestor, or through `style`,\n  // so it is read after every render: a new value bakes a new sticker, and\n  // the same request is not started twice.\n  React.useEffect(() => {\n    if (!src || !ref.current) {\n      request.current = null\n      return\n    }\n    const color =\n      getComputedStyle(ref.current).getPropertyValue(\"--sticker-edge\").trim() ||\n      \"#ffffff\"\n    const options = { size, edge: edgeWidth, color, cutout, pixelated }\n    const key = JSON.stringify([src, options])\n    if (request.current === key) return\n    request.current = key\n    bakeSticker(src, options).then(\n      (baked) => request.current === key && setResult({ src, baked }),\n      (error: unknown) =>\n        request.current === key &&\n        setResult({\n          src,\n          failed: error instanceof StickerError ? error.reason : \"load\",\n        })\n    )\n  })\n\n  React.useEffect(\n    () => () => {\n      request.current = null\n    },\n    []\n  )\n\n  const settled = src && result?.src === src ? result : null\n  const shape: StickerAvatarShape | \"loading\" = !src\n    ? \"initials\"\n    : !settled\n      ? \"loading\"\n      : settled.baked\n        ? settled.baked.shape\n        : settled.failed === \"taint\"\n          ? \"round\"\n          : \"initials\"\n  return (\n    <>\n      {/* The name lives outside the image so it isn't part of the sticker's\n          own text. The comma keeps name and status apart when read as one. */}\n      <span id={nameId} hidden>\n        {labelledBy ? `${name},` : name}\n      </span>\n      <span\n        ref={ref}\n        role=\"img\"\n        aria-labelledby={labelledBy ? `${nameId} ${labelledBy}` : nameId}\n        data-slot=\"sticker-avatar\"\n        data-shape={shape}\n        className={cn(\n          \"group/sticker-avatar relative inline-block shrink-0 rotate-(--sticker-tilt) align-middle transition-[rotate,translate,scale] duration-200 ease-out\",\n          STATUS_PLACEMENT,\n          lift &&\n            \"motion-safe:group-hover/sticker:-translate-y-0.5 motion-safe:group-hover/sticker:scale-105 motion-safe:group-hover/sticker:rotate-0 motion-safe:hover:-translate-y-0.5 motion-safe:hover:scale-105 motion-safe:hover:rotate-0\",\n          className\n        )}\n        style={\n          {\n            width: size,\n            height: size,\n            \"--sticker-tilt\": `${angle}deg`,\n            \"--sticker-edge-width\": `${edgeWidth}px`,\n            ...style,\n          } as React.CSSProperties\n        }\n        {...props}\n      >\n        {settled?.baked ? (\n          <img\n            data-slot=\"sticker-avatar-image\"\n            src={settled.baked.url}\n            alt=\"\"\n            draggable={false}\n            className={cn(\n              \"pointer-events-none absolute -inset-(--sticker-edge-width) size-[calc(100%+var(--sticker-edge-width)*2)] max-w-none select-none\",\n              PAPER_SHADOW,\n              lift && PAPER_SHADOW_LIFTED\n            )}\n          />\n        ) : shape === \"round\" ? (\n          // The host serves the image without CORS, so its pixels can't be\n          // read or cut. A paper ring in CSS keeps it looking like a sticker.\n          <img\n            data-slot=\"sticker-avatar-image\"\n            src={src}\n            alt=\"\"\n            draggable={false}\n            className={cn(\n              \"pointer-events-none size-full rounded-full object-cover shadow-[0_0_0_var(--sticker-edge-width)_var(--sticker-edge)] select-none\",\n              PAPER_SHADOW,\n              lift && PAPER_SHADOW_LIFTED\n            )}\n          />\n        ) : shape === \"initials\" ? (\n          // The letters are the sticker: a stroke painted under the fill\n          // grows each glyph by the edge width, the same die-cut in CSS.\n          <span\n            data-slot=\"sticker-avatar-fallback\"\n            aria-hidden=\"true\"\n            className={cn(\n              \"flex size-full items-center justify-center leading-none font-bold tracking-tight text-sticker-ink select-none [-webkit-text-stroke:calc(var(--sticker-edge-width)*2)_var(--sticker-edge)] [paint-order:stroke_fill]\",\n              PAPER_SHADOW,\n              lift && PAPER_SHADOW_LIFTED\n            )}\n            style={{ fontSize: size * 0.42 }}\n          >\n            {initials(name)}\n          </span>\n        ) : null}\n        <StatusDotHostProvider host={host}>{children}</StatusDotHostProvider>\n      </span>\n    </>\n  )\n}\n\nfunction StickerAvatarGroup({\n  className,\n  ...props\n}: React.ComponentProps<\"div\">) {\n  return (\n    <div\n      role=\"group\"\n      data-slot=\"sticker-avatar-group\"\n      className={cn(\n        \"flex items-center -space-x-3 *:data-[slot=sticker-avatar]:hover:z-10\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\n\nfunction StickerAvatarCount({\n  count,\n  label = (n) => `${n} more`,\n  size = 40,\n  edge,\n  tilt = true,\n  className,\n  style,\n  ...props\n}: Omit<React.ComponentProps<\"span\">, \"children\"> & {\n  /** How many people are not shown. Rendered as \"+count\". */\n  count: number\n  /** What screen readers hear, for translation. Defaults to \"4 more\". */\n  label?: CountProps[\"label\"]\n  /** Width and height in pixels. Match the stickers beside it. */\n  size?: number\n  /** Paper edge in pixels. Defaults to the same rule as StickerAvatar. */\n  edge?: number\n  /** `true` tilts by a stable angle from the count, a number sets degrees. */\n  tilt?: boolean | number\n}) {\n  const edgeWidth = edge ?? stickerEdge(size)\n  const angle =\n    tilt === false\n      ? 0\n      : typeof tilt === \"number\"\n        ? tilt\n        : stickerTilt(`+${count}`)\n  return (\n    <span\n      data-slot=\"sticker-avatar-count\"\n      className={cn(\n        \"relative inline-flex shrink-0 rotate-(--sticker-tilt) items-center justify-center rounded-full bg-sticker-ink font-semibold text-sticker-edge shadow-[0_0_0_var(--sticker-edge-width)_var(--sticker-edge)] select-none\",\n        PAPER_SHADOW,\n        className\n      )}\n      style={\n        {\n          width: size,\n          height: size,\n          fontSize: size * 0.34,\n          \"--sticker-tilt\": `${angle}deg`,\n          \"--sticker-edge-width\": `${edgeWidth}px`,\n          ...style,\n        } as React.CSSProperties\n      }\n      {...props}\n    >\n      <Count value={count} plus label={label} />\n    </span>\n  )\n}\n\nexport {\n  StickerAvatar,\n  StickerAvatarGroup,\n  StickerAvatarCount,\n  stickerEdge,\n  stickerTilt,\n  type StickerAvatarProps,\n  type StickerAvatarShape,\n}\n",
      "type": "registry:ui"
    }
  ],
  "cssVars": {
    "theme": {
      "color-sticker-edge": "var(--sticker-edge)",
      "color-sticker-ink": "var(--sticker-ink)",
      "color-sticker-shadow": "var(--sticker-shadow)"
    },
    "light": {
      "sticker-edge": "var(--color-white)",
      "sticker-ink": "var(--color-neutral-900)",
      "sticker-shadow": "color-mix(in oklch, var(--color-black) 30%, transparent)"
    },
    "dark": {
      "sticker-edge": "var(--color-white)",
      "sticker-ink": "var(--color-neutral-900)",
      "sticker-shadow": "color-mix(in oklch, var(--color-black) 30%, transparent)"
    }
  },
  "meta": {
    "tier": "special-components",
    "group": "Display",
    "docs": "https://fibo.toribryan.com/?path=/docs/special-components-sticker-avatar--docs"
  },
  "docs": "Docs and live examples: https://fibo.toribryan.com/?path=/docs/special-components-sticker-avatar--docs",
  "categories": [
    "special-components",
    "display"
  ],
  "type": "registry:ui"
}