{
  "schemaVersion": 1,
  "target": "react",
  "name": "image-generation",
  "version": "0.1.0",
  "category": "ai-elements",
  "title": "Image Generation",
  "description": "Prompt in, images out: a grid of placeholders that fill with soft grain and sharpen with progress, images that resolve from blur into focus, a selectable gallery with variations, upscale, and download, and failed tiles with retry.",
  "tags": [
    "ai",
    "agent",
    "image",
    "generation",
    "gallery",
    "text-to-image",
    "progress"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {},
  "registryDependencies": [],
  "docsPath": "/components/image-generation",
  "props": [
    {
      "name": "prompt",
      "type": "string",
      "description": "The request, shown in the header and used as the default alt text."
    },
    {
      "name": "images",
      "type": "{ id, status: \"pending\" | \"generating\" | \"ready\" | \"error\", src?, previewSrc?, progress?, alt?, error? }[]",
      "description": "One entry per image, in order. previewSrc is a partial render that sharpens as progress rises from 0 to 100."
    },
    {
      "name": "count",
      "type": "number",
      "default": "4",
      "description": "How many images the request makes. Missing entries show as queued placeholders."
    },
    {
      "name": "aspectRatio",
      "type": "\"1:1\" | \"4:3\" | \"3:4\" | \"3:2\" | \"2:3\" | \"16:9\" | \"9:16\" | `${number}:${number}`",
      "default": "\"1:1\"",
      "description": "Width to height for every tile."
    },
    {
      "name": "columns",
      "type": "1 | 2 | 3 | 4",
      "description": "Grid columns. Defaults from the count and aspect ratio."
    },
    {
      "name": "model",
      "type": "ReactNode",
      "description": "Model or preset name for the header."
    },
    {
      "name": "selectedId / defaultSelectedId / onSelectedChange",
      "type": "string | null",
      "description": "The selected image, controlled or not."
    },
    {
      "name": "onVariations / onUpscale",
      "type": "(image) => void",
      "description": "Add Variations and Upscale actions for the selected image."
    },
    {
      "name": "onDownload",
      "type": "(image) => void",
      "description": "Replaces the default download, which saves src through a link."
    },
    {
      "name": "onRetry",
      "type": "(image) => void",
      "description": "Adds a retry button to failed tiles."
    }
  ],
  "accessibility": [
    "Finished images form a radio group: Tab reaches the selected image, arrow keys, Home, and End move between finished images and select them, and each is named Image 2 of 4.",
    "Tiles still on their way are progress bars with a value text (Generating, 40% or Queued). The header summary is a polite status region.",
    "A failed tile states the reason in text and its retry button is labelled Retry image 3.",
    "Variations, Upscale, and Download act on the selection and are disabled until one is chosen; on narrow screens they show icons with accessible names.",
    "With reduced motion the grain holds still and images appear without the blur to focus transition."
  ],
  "states": [
    "queued",
    "generating",
    "ready",
    "selected",
    "error"
  ],
  "files": [
    {
      "path": "agent/image-generation.tsx",
      "content": "\"use client\";\n\nimport { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from \"react\";\n\nfunction cx(...classes: Array<string | false | null | undefined>) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\nconst stroke = { fill: \"none\", stroke: \"currentColor\", strokeWidth: 1.5, strokeLinecap: \"round\", strokeLinejoin: \"round\" } as const;\n\nexport type GeneratedImageStatus = \"pending\" | \"generating\" | \"ready\" | \"error\";\nexport type ImageAspectRatio = \"1:1\" | \"4:3\" | \"3:4\" | \"3:2\" | \"2:3\" | \"16:9\" | \"9:16\" | `${number}:${number}`;\n\nexport interface GeneratedImage {\n  id: string;\n  status: GeneratedImageStatus;\n  /** The finished image. */\n  src?: string;\n  /** A partial render while generating. It sharpens as `progress` rises. */\n  previewSrc?: string;\n  /** 0 to 100 while generating. */\n  progress?: number;\n  /** Defaults to the prompt. */\n  alt?: string;\n  /** Why this image failed. */\n  error?: string;\n}\n\nexport interface ImageGenerationProps {\n  prompt: string;\n  /** One entry per image, in order. Missing entries up to `count` show as queued placeholders. */\n  images: GeneratedImage[];\n  /** How many images the request makes. @default 4 */\n  count?: number;\n  /** Width to height, for every tile. @default \"1:1\" */\n  aspectRatio?: ImageAspectRatio;\n  /** Model or preset name for the header. */\n  model?: ReactNode;\n  /** Grid columns. Defaults from the count and aspect ratio. */\n  columns?: 1 | 2 | 3 | 4;\n  /** The selected image. Pass with `onSelectedChange` to control it. */\n  selectedId?: string | null;\n  defaultSelectedId?: string | null;\n  onSelectedChange?: (id: string | null) => void;\n  /** Adds a Variations action for the selected image. */\n  onVariations?: (image: GeneratedImage) => void;\n  /** Adds an Upscale action for the selected image. */\n  onUpscale?: (image: GeneratedImage) => void;\n  /** Replaces the default download, which saves `src` through a link. */\n  onDownload?: (image: GeneratedImage) => void;\n  /** Adds a retry button to failed tiles. */\n  onRetry?: (image: GeneratedImage) => void;\n  className?: string;\n}\n\n// Soft grain as an inline SVG, so tiles need no image requests while they wait.\nconst NOISE = `url(\"data:image/svg+xml;utf8,${encodeURIComponent(\n  `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"180\" height=\"180\"><filter id=\"n\"><feTurbulence type=\"fractalNoise\" baseFrequency=\".8\" numOctaves=\"3\" stitchTiles=\"stitch\"/><feColorMatrix values=\"0 0 0 0 .5 0 0 0 0 .5 0 0 0 0 .5 0 0 0 1.6 -.35\"/></filter><rect width=\"100%\" height=\"100%\" filter=\"url(#n)\"/></svg>`,\n)}\")`;\n\nfunction ratioOf(aspect: ImageAspectRatio) {\n  const [w, h] = aspect.split(\":\").map(Number);\n  return w && h ? w / h : 1;\n}\n\nfunction defaultColumns(count: number, ratio: number) {\n  if (count <= 1) return 1;\n  if (count === 2 || (count === 4 && ratio >= 1)) return 2;\n  if (count === 3) return 3;\n  return count === 4 ? 4 : 3;\n}\n\nconst columnClass: Record<number, string> = {\n  1: \"grid-cols-1\",\n  2: \"grid-cols-2\",\n  3: \"grid-cols-3\",\n  4: \"grid-cols-2 sm:grid-cols-4\",\n};\n\nfunction prefersReducedMotion() {\n  return typeof window !== \"undefined\" && window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n}\n\n/**\n * Text to image: the prompt, then a grid of placeholders that fill with soft grain and sharpen as\n * each image arrives. A finished image resolves from blur into focus. Pick one to get variations,\n * upscale, or download it; a failed tile says why and offers retry.\n */\nexport function ImageGeneration({\n  prompt,\n  images,\n  count: countProp,\n  aspectRatio = \"1:1\",\n  model,\n  columns,\n  selectedId: selectedProp,\n  defaultSelectedId = null,\n  onSelectedChange,\n  onVariations,\n  onUpscale,\n  onDownload,\n  onRetry,\n  className,\n}: ImageGenerationProps) {\n  const count = Math.max(countProp ?? 4, images.length);\n  const tiles: GeneratedImage[] = Array.from({ length: count }, (_, i) => images[i] ?? { id: `queued-${i}`, status: \"pending\" });\n  const ratio = ratioOf(aspectRatio);\n  const cols = columns ?? defaultColumns(count, ratio);\n\n  const [innerSelected, setInnerSelected] = useState<string | null>(defaultSelectedId);\n  const selectedId = selectedProp === undefined ? innerSelected : selectedProp;\n  const select = (id: string | null) => {\n    if (selectedProp === undefined) setInnerSelected(id);\n    onSelectedChange?.(id);\n  };\n  const tileRefs = useRef<Array<HTMLButtonElement | null>>([]);\n\n  const ready = tiles.filter((tile) => tile.status === \"ready\");\n  const failed = tiles.filter((tile) => tile.status === \"error\").length;\n  const working = tiles.some((tile) => tile.status === \"pending\" || tile.status === \"generating\");\n  const overall = Math.round(\n    tiles.reduce((sum, tile) => sum + (tile.status === \"ready\" || tile.status === \"error\" ? 100 : tile.status === \"generating\" ? (tile.progress ?? 0) : 0), 0) / count,\n  );\n  const selected = tiles.find((tile) => tile.id === selectedId && tile.status === \"ready\") ?? null;\n  const selectedIndex = selected ? tiles.indexOf(selected) : -1;\n  const focusIndex = selectedIndex >= 0 ? selectedIndex : tiles.findIndex((tile) => tile.status === \"ready\");\n\n  const summary = working\n    ? `Generating, ${ready.length} of ${count} ready`\n    : failed\n      ? `${ready.length} of ${count} ready, ${failed} failed`\n      : `${count} ${count === 1 ? \"image\" : \"images\"}`;\n\n  function onGridKeyDown(event: KeyboardEvent<HTMLDivElement>) {\n    const current = tileRefs.current.findIndex((el) => el === document.activeElement);\n    if (current < 0) return;\n    const step: Record<string, number> = { ArrowRight: 1, ArrowDown: cols, ArrowLeft: -1, ArrowUp: -cols };\n    let target = -1;\n    if (event.key in step) {\n      const delta = step[event.key]!;\n      for (let i = current + delta; i >= 0 && i < count; i += delta) {\n        if (tiles[i]!.status === \"ready\") {\n          target = i;\n          break;\n        }\n      }\n      // Wrap linearly when a row or column runs out, like a radio group.\n      if (target < 0 && Math.abs(delta) === 1) {\n        const order = delta > 0 ? [...tiles.keys()] : [...tiles.keys()].reverse();\n        target = order.find((i) => tiles[i]!.status === \"ready\" && i !== current) ?? -1;\n      }\n    } else if (event.key === \"Home\") target = tiles.findIndex((tile) => tile.status === \"ready\");\n    else if (event.key === \"End\") target = [...tiles.keys()].reverse().find((i) => tiles[i]!.status === \"ready\") ?? -1;\n    else return;\n    event.preventDefault();\n    if (target >= 0) {\n      tileRefs.current[target]?.focus();\n      select(tiles[target]!.id);\n    }\n  }\n\n  const actionsDisabled = !selected;\n\n  return (\n    <section\n      aria-label=\"Image generation\"\n      className={cx(\n        \"w-full max-w-2xl rounded-xl border border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)]\",\n        \"dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]\",\n        className,\n      )}\n    >\n      <header className=\"px-4 pt-4 pb-3\">\n        <p className=\"text-sm text-pretty text-zinc-950 dark:text-white\">{prompt}</p>\n        <div className=\"mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-zinc-500\">\n          <span role=\"status\" className={cx(working && \"text-zinc-600 dark:text-zinc-400\")}>\n            {summary}\n          </span>\n          {working ? <span className=\"font-mono tabular-nums\">{overall}%</span> : null}\n          <span className=\"font-mono\">{aspectRatio}</span>\n          {model != null ? <span className=\"min-w-0 truncate\">{model}</span> : null}\n        </div>\n      </header>\n\n      <div\n        role=\"radiogroup\"\n        aria-label=\"Generated images\"\n        onKeyDown={onGridKeyDown}\n        className={cx(\"grid gap-2 px-4\", columnClass[cols])}\n      >\n        {tiles.map((tile, index) => (\n          <Tile\n            key={tile.id}\n            tile={tile}\n            index={index}\n            count={count}\n            ratio={ratio}\n            alt={tile.alt ?? prompt}\n            selected={tile.id === selectedId && tile.status === \"ready\"}\n            tabbable={index === focusIndex}\n            onSelect={() => select(tile.id === selectedId ? null : tile.id)}\n            onRetry={onRetry}\n            buttonRef={(el) => {\n              tileRefs.current[index] = el;\n            }}\n          />\n        ))}\n      </div>\n\n      <div className=\"mt-3 flex min-h-12 items-center justify-between gap-3 border-t border-zinc-950/[0.07] px-2 py-2 dark:border-white/[0.08]\">\n        <p className=\"min-w-0 truncate pl-2 text-xs text-zinc-500\">\n          {selected ? `Image ${selectedIndex + 1} selected` : ready.length ? \"Select an image\" : working ? \"Images appear as they finish\" : \"No images to select\"}\n        </p>\n        <div className=\"flex shrink-0 items-center gap-0.5\">\n          {onVariations ? (\n            <Action label=\"Variations\" disabled={actionsDisabled} onClick={() => selected && onVariations(selected)}>\n              <rect x=\"2.75\" y=\"5.25\" width=\"8\" height=\"8\" rx=\"1.5\" />\n              <path d=\"M5.25 2.75h6.5a1.5 1.5 0 0 1 1.5 1.5v6.5\" />\n            </Action>\n          ) : null}\n          {onUpscale ? (\n            <Action label=\"Upscale\" disabled={actionsDisabled} onClick={() => selected && onUpscale(selected)}>\n              <path d=\"M9.5 2.75h3.75V6.5M6.5 13.25H2.75V9.5M13.25 2.75 9 7M2.75 13.25 7 9\" />\n            </Action>\n          ) : null}\n          <Action\n            label=\"Download\"\n            disabled={actionsDisabled || (!onDownload && !selected?.src)}\n            onClick={() => {\n              if (!selected) return;\n              if (onDownload) return onDownload(selected);\n              const link = document.createElement(\"a\");\n              link.href = selected.src!;\n              link.download = `image-${selectedIndex + 1}`;\n              link.click();\n            }}\n          >\n            <path d=\"M8 2.75v7.5m0 0 3-3m-3 3-3-3M3 12.75h10\" />\n          </Action>\n        </div>\n      </div>\n    </section>\n  );\n}\n\nfunction Tile({\n  tile,\n  index,\n  count,\n  ratio,\n  alt,\n  selected,\n  tabbable,\n  onSelect,\n  onRetry,\n  buttonRef,\n}: {\n  tile: GeneratedImage;\n  index: number;\n  count: number;\n  ratio: number;\n  alt: string;\n  selected: boolean;\n  tabbable: boolean;\n  onSelect: () => void;\n  onRetry?: (image: GeneratedImage) => void;\n  buttonRef: (el: HTMLButtonElement | null) => void;\n}) {\n  const src = tile.status === \"ready\" ? (tile.src ?? tile.previewSrc) : tile.status === \"generating\" ? tile.previewSrc : undefined;\n  const [loadedSrc, setLoadedSrc] = useState<string | null>(null);\n  const loaded = src != null && loadedSrc === src;\n  const progress = Math.max(0, Math.min(100, tile.progress ?? 0)) / 100;\n  const grainRef = useRef<HTMLSpanElement>(null);\n  const waiting = tile.status === \"pending\" || tile.status === \"generating\";\n\n  // Grain drifts in small steps while the image is on its way, like film grain. Still under reduced motion.\n  useEffect(() => {\n    const grain = grainRef.current;\n    if (!grain || !waiting || prefersReducedMotion()) return;\n    const animation = grain.animate(\n      [{ transform: \"translate(0,0)\" }, { transform: \"translate(-18%,9%)\" }, { transform: \"translate(7%,-14%)\" }, { transform: \"translate(-9%,-4%)\" }],\n      { duration: 1400, iterations: Infinity, easing: \"steps(7)\" },\n    );\n    return () => animation.cancel();\n  }, [waiting]);\n\n  // Blur falls as progress rises; a ready image lands at zero once its pixels have loaded.\n  const blur = tile.status === \"ready\" ? (loaded ? 0 : 20) : 4 + 22 * (1 - progress);\n  const grain = tile.status === \"pending\" ? 0.5 : tile.status === \"generating\" ? 0.12 + 0.42 * (1 - progress) : 0;\n  const position = `Image ${index + 1} of ${count}`;\n\n  const frame = cx(\n    \"relative isolate block w-full overflow-hidden rounded-lg\",\n    tile.status === \"error\"\n      ? \"border border-red-500/35 bg-red-500/[0.04] dark:bg-red-500/[0.06]\"\n      : \"bg-zinc-950/[0.04] shadow-[inset_0_0_0_1px_rgb(9_9_11/0.07)] dark:bg-white/[0.05] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.08)]\",\n  );\n\n  const layers = (\n    <>\n      {src ? (\n        <img\n          src={src}\n          alt={tile.status === \"ready\" ? alt : \"\"}\n          draggable={false}\n          onLoad={() => setLoadedSrc(src)}\n          className={cx(\n            \"absolute inset-0 size-full object-cover transition-[filter,opacity,scale] duration-500 motion-reduce:transition-none\",\n            ease,\n            loaded ? \"opacity-100\" : \"opacity-0\",\n          )}\n          style={{ filter: blur ? `blur(${blur}px) saturate(${1 - blur / 60})` : undefined, scale: String(1 + blur / 160) }}\n        />\n      ) : null}\n      <span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-0 overflow-hidden transition-opacity duration-500 ease-out motion-reduce:transition-none\"\n        style={{ opacity: grain }}\n      >\n        <span ref={grainRef} className=\"absolute -inset-1/4 opacity-70 dark:opacity-90\" style={{ backgroundImage: NOISE, backgroundSize: \"180px\" }} />\n      </span>\n    </>\n  );\n\n  const percent = Math.round(progress * 100);\n  const isReady = tile.status === \"ready\";\n  const isError = tile.status === \"error\";\n\n  // One frame element for every state, so the image and grain keep their transitions as the tile resolves.\n  return (\n    <div\n      role={isReady ? undefined : isError ? \"group\" : \"progressbar\"}\n      aria-label={isReady ? undefined : isError ? `${position}, failed` : position}\n      aria-valuemin={waiting ? 0 : undefined}\n      aria-valuemax={waiting ? 100 : undefined}\n      aria-valuenow={tile.status === \"generating\" ? percent : undefined}\n      aria-valuetext={waiting ? (tile.status === \"generating\" ? `Generating, ${percent}%` : \"Queued\") : undefined}\n      className={cx(\n        frame,\n        \"outline-offset-2 transition-[outline-color] duration-150 ease-out motion-reduce:transition-none\",\n        selected ? \"outline-2 outline-zinc-950 dark:outline-white\" : \"outline-2 outline-transparent\",\n        \"has-[>button:focus-visible]:outline-2 has-[>button:focus-visible]:outline-solid has-[>button:focus-visible]:outline-offset-[5px] has-[>button:focus-visible]:outline-sky-500\",\n      )}\n      style={{ aspectRatio: ratio }}\n    >\n      {layers}\n\n      {isReady ? (\n        <button\n          ref={buttonRef}\n          type=\"button\"\n          role=\"radio\"\n          aria-checked={selected}\n          aria-label={position}\n          tabIndex={tabbable ? 0 : -1}\n          onClick={onSelect}\n          className={cx(\n            \"group absolute inset-0 cursor-pointer rounded-lg outline-hidden\",\n          )}\n        >\n          <span\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute inset-0 rounded-lg bg-zinc-950/0 transition-colors duration-150 ease-out group-hover:bg-zinc-950/[0.08] group-active:bg-zinc-950/[0.12] motion-reduce:transition-none\"\n          />\n          <span\n            aria-hidden=\"true\"\n            className={cx(\n              \"absolute top-2 left-2 inline-flex size-5 items-center justify-center rounded-full bg-zinc-950 text-white shadow-[0_1px_2px_rgb(0_0_0/0.3)] dark:bg-white dark:text-black\",\n              \"transition-[opacity,scale] duration-200 motion-reduce:transition-none\",\n              ease,\n              selected ? \"scale-100 opacity-100\" : \"scale-90 opacity-0\",\n            )}\n          >\n            <svg viewBox=\"0 0 16 16\" {...stroke} strokeWidth={2} className=\"size-3\">\n              <path d=\"m4 8.25 2.5 2.5 5.5-5.5\" />\n            </svg>\n          </span>\n        </button>\n      ) : null}\n\n      {isError ? (\n        <div className=\"absolute inset-0 flex flex-col items-center justify-center gap-2 p-3 text-center\">\n          <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" {...stroke} className=\"size-4 shrink-0 text-red-600 dark:text-red-400\">\n            <circle cx=\"8\" cy=\"8\" r=\"5.75\" />\n            <path d=\"m6 6 4 4m0-4-4 4\" />\n          </svg>\n          <p className=\"line-clamp-2 text-xs text-red-600 dark:text-red-400\">{tile.error ?? \"Couldn't generate this image\"}</p>\n          {onRetry ? (\n            <button\n              type=\"button\"\n              aria-label={`Retry image ${index + 1}`}\n              onClick={() => onRetry(tile)}\n              className={cx(\n                \"inline-flex h-7 shrink-0 cursor-pointer items-center gap-1.5 rounded-lg border border-zinc-950/12 bg-white px-2.5 text-xs font-medium text-zinc-950\",\n                \"transition-[background-color,border-color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none\",\n                \"hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] dark:border-white/15 dark:bg-black dark:text-white dark:hover:border-white/25 dark:hover:bg-white/[0.06]\",\n                \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n              )}\n            >\n              <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" {...stroke} className=\"size-3.5\">\n                <path d=\"M12.5 8a4.5 4.5 0 1 1-1.32-3.18M12.5 2.75v2.5H10\" />\n              </svg>\n              Retry\n            </button>\n          ) : null}\n        </div>\n      ) : null}\n\n      {waiting ? (\n        <>\n          <span\n            aria-hidden=\"true\"\n            className={cx(\n              \"absolute bottom-2 left-2 rounded-md bg-white/85 px-1.5 py-0.5 font-mono text-[11px] leading-4 text-zinc-600 tabular-nums dark:bg-black/70 dark:text-zinc-300\",\n              \"shadow-[inset_0_0_0_1px_rgb(9_9_11/0.06)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.08)]\",\n            )}\n          >\n            {tile.status === \"generating\" ? `${percent}%` : \"Queued\"}\n          </span>\n          <span aria-hidden=\"true\" className=\"absolute inset-x-0 bottom-0 h-0.5 bg-zinc-950/[0.06] dark:bg-white/[0.08]\">\n            <span\n              className=\"block h-full origin-left bg-zinc-950 transition-transform duration-300 ease-out motion-reduce:transition-none dark:bg-white\"\n              style={{ transform: `scaleX(${tile.status === \"generating\" ? progress : 0})` }}\n            />\n          </span>\n        </>\n      ) : null}\n    </div>\n  );\n}\n\nfunction Action({ label, disabled, onClick, children }: { label: string; disabled: boolean; onClick: () => void; children: ReactNode }) {\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      disabled={disabled}\n      onClick={onClick}\n      className={cx(\n        \"inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg px-2 text-[13px] font-medium text-zinc-600 select-none sm:px-2.5 dark:text-zinc-400\",\n        \"transition-[background-color,color,scale,opacity] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none\",\n        \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n        \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n        \"disabled:pointer-events-none disabled:opacity-40\",\n      )}\n    >\n      <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" {...stroke} className=\"size-4 shrink-0\">\n        {children}\n      </svg>\n      <span className=\"hidden sm:inline\">{label}</span>\n    </button>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { type GeneratedImage, type ImageAspectRatio, ImageGeneration } from \"@/components/shaken/agent/image-generation\";\n\nconst PROMPT = \"A lighthouse on a basalt cliff at dusk, long exposure, calm sea, 35mm film\";\n\n/** Paints one variation of the prompt as an SVG data URI, so the demo needs no network. */\nexport function paintVariation(seed: number, aspect: ImageAspectRatio) {\n  const [w = 1, h = 1] = aspect.split(\":\").map(Number);\n  const width = 800;\n  const height = Math.round((width * h) / w);\n  const palettes = [\n    [\"#0f172a\", \"#7c3aed\", \"#fb923c\", \"#fde68a\"],\n    [\"#020617\", \"#1e3a8a\", \"#f472b6\", \"#fecdd3\"],\n    [\"#111827\", \"#0f766e\", \"#fbbf24\", \"#fef3c7\"],\n    [\"#0c0a09\", \"#9a3412\", \"#fdba74\", \"#ffedd5\"],\n  ];\n  const [top, mid, low, glow] = palettes[seed % palettes.length]!;\n  const horizon = height * (0.58 + ((seed * 7) % 5) * 0.02);\n  const sunX = width * (0.25 + ((seed * 13) % 6) * 0.1);\n  const cliffX = seed % 2 ? width * 0.12 : width * 0.62;\n  const cliffW = width * 0.32;\n  const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" viewBox=\"0 0 ${width} ${height}\">\n<defs>\n<linearGradient id=\"s\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\"><stop offset=\"0\" stop-color=\"${top}\"/><stop offset=\".55\" stop-color=\"${mid}\"/><stop offset=\".9\" stop-color=\"${low}\"/><stop offset=\"1\" stop-color=\"${glow}\"/></linearGradient>\n<linearGradient id=\"w\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\"><stop offset=\"0\" stop-color=\"${low}\" stop-opacity=\".55\"/><stop offset=\"1\" stop-color=\"${top}\"/></linearGradient>\n<radialGradient id=\"g\" cx=\".5\" cy=\".5\" r=\".5\"><stop offset=\"0\" stop-color=\"#fffbeb\"/><stop offset=\".5\" stop-color=\"${glow}\" stop-opacity=\".8\"/><stop offset=\"1\" stop-color=\"${glow}\" stop-opacity=\"0\"/></radialGradient>\n<radialGradient id=\"b\" cx=\".5\" cy=\".5\" r=\".5\"><stop offset=\"0\" stop-color=\"#fffbeb\" stop-opacity=\".9\"/><stop offset=\"1\" stop-color=\"#fffbeb\" stop-opacity=\"0\"/></radialGradient>\n</defs>\n<rect width=\"${width}\" height=\"${height}\" fill=\"url(#s)\"/>\n<circle cx=\"${sunX}\" cy=\"${horizon}\" r=\"${width * 0.16}\" fill=\"url(#g)\"/>\n<rect y=\"${horizon}\" width=\"${width}\" height=\"${height - horizon}\" fill=\"url(#w)\"/>\n<rect x=\"${sunX - width * 0.12}\" y=\"${horizon + 6}\" width=\"${width * 0.24}\" height=\"3\" fill=\"${glow}\" opacity=\".5\"/>\n<rect x=\"${sunX - width * 0.07}\" y=\"${horizon + 18}\" width=\"${width * 0.14}\" height=\"2\" fill=\"${glow}\" opacity=\".35\"/>\n<path d=\"M${cliffX - 20} ${height} L${cliffX} ${horizon - height * 0.06} L${cliffX + cliffW * 0.35} ${horizon - height * 0.1} L${cliffX + cliffW * 0.7} ${horizon - height * 0.04} L${cliffX + cliffW} ${horizon + height * 0.05} L${cliffX + cliffW + 30} ${height} Z\" fill=\"#05050a\"/>\n<rect x=\"${cliffX + cliffW * 0.3}\" y=\"${horizon - height * 0.27}\" width=\"${width * 0.035}\" height=\"${height * 0.17}\" fill=\"#e7e5e4\"/>\n<rect x=\"${cliffX + cliffW * 0.3}\" y=\"${horizon - height * 0.22}\" width=\"${width * 0.035}\" height=\"${height * 0.025}\" fill=\"#b91c1c\"/>\n<circle cx=\"${cliffX + cliffW * 0.3 + width * 0.0175}\" cy=\"${horizon - height * 0.285}\" r=\"${width * 0.09}\" fill=\"url(#b)\"/>\n</svg>`;\n  return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;\n}\n\n/** Fakes a generation run: tiles start at staggered times, report progress, and one fails once. */\nexport function useSimulatedGeneration(count: number, aspect: ImageAspectRatio, failIndex = 2) {\n  const [images, setImages] = useState<GeneratedImage[]>([]);\n  const [run, setRun] = useState(0);\n  const failedOnce = useRef(new Set<number>());\n\n  useEffect(() => {\n    const timers: ReturnType<typeof setTimeout>[] = [];\n    const ids = Array.from({ length: count }, (_, i) => `${run}-${i}`);\n    setImages(ids.map((id) => ({ id, status: \"pending\" })));\n    const update = (i: number, patch: Partial<GeneratedImage>) =>\n      setImages((current) => current.map((image) => (image.id === ids[i] ? { ...image, ...patch } : image)));\n\n    ids.forEach((_, i) => {\n      const src = paintVariation(i + run * count, aspect);\n      let progress = 0;\n      const tick = () => {\n        progress = Math.min(100, progress + 6 + Math.random() * 14);\n        if (i === failIndex && progress > 55 && !failedOnce.current.has(run)) {\n          failedOnce.current.add(run);\n          update(i, { status: \"error\", error: \"The model timed out. Nothing was charged.\" });\n          return;\n        }\n        if (progress >= 100) return update(i, { status: \"ready\", src, progress: 100 });\n        update(i, { status: \"generating\", progress, previewSrc: src });\n        timers.push(setTimeout(tick, 260 + Math.random() * 260));\n      };\n      timers.push(setTimeout(tick, 300 + i * 450));\n    });\n    return () => timers.forEach(clearTimeout);\n  }, [count, aspect, run, failIndex]);\n\n  function retry(image: GeneratedImage) {\n    const i = images.findIndex((item) => item.id === image.id);\n    if (i < 0) return;\n    const src = paintVariation(i + 11 + run * count, aspect);\n    let progress = 0;\n    const tick = () => {\n      progress = Math.min(100, progress + 10 + Math.random() * 16);\n      setImages((current) =>\n        current.map((item) =>\n          item.id === image.id\n            ? progress >= 100\n              ? { ...item, status: \"ready\", src, progress: 100, error: undefined }\n              : { ...item, status: \"generating\", progress, previewSrc: src, error: undefined }\n            : item,\n        ),\n      );\n      if (progress < 100) setTimeout(tick, 280);\n    };\n    tick();\n  }\n\n  return { images, retry, regenerate: () => setRun((value) => value + 1) };\n}\n\nexport default function ImageGenerationExample() {\n  const { images, retry } = useSimulatedGeneration(4, \"3:2\");\n\n  return (\n    <ImageGeneration\n      prompt={PROMPT}\n      images={images}\n      count={4}\n      aspectRatio=\"3:2\"\n      model=\"Studio XL\"\n      onRetry={retry}\n      onVariations={(image) => console.log(\"variations of\", image.id)}\n      onUpscale={(image) => console.log(\"upscale\", image.id)}\n    />\n  );\n}\n"
  }
}
