{"slug":"image-generation","name":"Image Generation","description":"A stable generated-image surface that moves from queued work through progressive refinement to a completed result without layout shift.","category":"agents","source_url":"https://beui.dev/r/image-generation/raw","detail_url":"https://beui.dev/r/image-generation","raw_url":"https://beui.dev/r/image-generation/raw","page_url":"https://beui.dev/components/agents/image-generation","markdown_url":"https://beui.dev/components/agents/image-generation.md","published_at":"2026-08-02","updated_at":"2026-11-25","dependencies":["clsx","lucide-react","motion","react","tailwind-merge"],"internal":["@/components/agents/icon-swap","@/components/agents/image-generation","@/lib/ease","@/lib/hooks/use-hover-capable","@/lib/i18n","@/lib/utils"],"install_slugs":["image-generation"],"requires_theme":false,"props":[{"displayName":"ImageGeneration","props":[{"name":"children","type":"ReactNode","required":false,"defaultValue":null,"description":"The completed media. Pass an img, Next Image, canvas, video, or custom preview."},{"name":"status","type":"\"error\" | \"complete\" | \"queued\" | \"generating\" | \"refining\"","required":false,"defaultValue":"generating","description":"Generation stage. Sets the dither overlay, media blur and status line. Default: \"generating\""},{"name":"label","type":"string","required":false,"defaultValue":null,"description":"Accessible description. Defaults to a description derived from prompt."},{"name":"prompt","type":"string","required":false,"defaultValue":null,"description":"The prompt, shown in quotes under the status line."},{"name":"resolution","type":"string","required":false,"defaultValue":"1024 × 1024","description":"Badge in the top right corner. Default: \"1024 × 1024\""},{"name":"aspectRatio","type":"AspectRatio","required":false,"defaultValue":"1 / 1","description":"CSS aspect ratio reserved before generated media is available."},{"name":"size","type":"\"compact\" | \"fluid\"","required":false,"defaultValue":"compact","description":"\"compact\" caps the width at 208px, \"fluid\" fills the container. Default: \"compact\""},{"name":"interactive","type":"boolean","required":false,"defaultValue":"true","description":"Lets the active dither cluster follow fine-pointer movement."},{"name":"statusText","type":"string","required":false,"defaultValue":null,"description":"Replaces the built-in status line text for the current status."},{"name":"showStatus","type":"boolean","required":false,"defaultValue":"true","description":"Shows the status line under the media. Default: true"},{"name":"onRetry","type":"(() => void)","required":false,"defaultValue":null,"description":"Called from the retry button, which shows only when status is \"error\"."},{"name":"labels","type":"Partial<{ queued: string; generating: string; refining: string; complete: string; error: string; labelWithPrompt: string; quotedPrompt: string; retry: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string. `{status}` and `{prompt}` fill `labelWithPrompt`; `{prompt}` fills `quotedPrompt`."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"mediaClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the layer that holds the media."},{"name":"statusClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the status line."}]}],"types":[],"files":[{"path":"components/agents/image-generation.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/image-generation\n\nimport { Check, CircleAlert, RotateCcw } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { useEffect, useRef } from \"react\";\nimport { IconSwap } from \"@/components/agents/icon-swap\";\nimport { EASE_IN_OUT, EASE_OUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ImageGenerationStatus =\n  | \"queued\"\n  | \"generating\"\n  | \"refining\"\n  | \"complete\"\n  | \"error\";\n\nexport interface ImageGenerationProps {\n  /** The completed media. Pass an img, Next Image, canvas, video, or custom preview. */\n  children?: ReactNode;\n  /** Generation stage. Sets the dither overlay, media blur and status line. Default: \"generating\" */\n  status?: ImageGenerationStatus;\n  /** Accessible description. Defaults to a description derived from prompt. */\n  label?: string;\n  /** The prompt, shown in quotes under the status line. */\n  prompt?: string;\n  /** Badge in the top right corner. Default: \"1024 × 1024\" */\n  resolution?: string;\n  /** CSS aspect ratio reserved before generated media is available. */\n  aspectRatio?: CSSProperties[\"aspectRatio\"];\n  /** \"compact\" caps the width at 208px, \"fluid\" fills the container. Default: \"compact\" */\n  size?: \"compact\" | \"fluid\";\n  /** Lets the active dither cluster follow fine-pointer movement. */\n  interactive?: boolean;\n  /** Replaces the built-in status line text for the current status. */\n  statusText?: string;\n  /** Shows the status line under the media. Default: true */\n  showStatus?: boolean;\n  /** Called from the retry button, which shows only when status is \"error\". */\n  onRetry?: () => void;\n  /** Override any built-in string. `{status}` and `{prompt}` fill `labelWithPrompt`; `{prompt}` fills `quotedPrompt`. */\n  labels?: Partial<ImageGenerationMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes merged onto the layer that holds the media. */\n  mediaClassName?: string;\n  /** Classes merged onto the status line. */\n  statusClassName?: string;\n}\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const imageGenerationMessages = {\n  queued: \"Waiting to generate\",\n  generating: \"Generating image\",\n  refining: \"Refining details\",\n  complete: \"Image ready\",\n  error: \"Generation failed\",\n  labelWithPrompt: \"{status}: {prompt}\",\n  quotedPrompt: \"“{prompt}”\",\n  retry: \"Try again\",\n};\n\nexport type ImageGenerationMessages = typeof imageGenerationMessages;\n\nconst MEDIA_STATE: Record<\n  ImageGenerationStatus,\n  { filter: string; opacity: number; scale: number }\n> = {\n  queued: { filter: \"blur(4px) saturate(0.75)\", opacity: 0, scale: 1.02 },\n  generating: { filter: \"blur(3px) saturate(0.85)\", opacity: 0, scale: 1.015 },\n  refining: { filter: \"blur(1.5px) saturate(0.95)\", opacity: 0.62, scale: 1.005 },\n  complete: { filter: \"blur(0px) saturate(1)\", opacity: 1, scale: 1 },\n  error: { filter: \"blur(2px) saturate(0.5)\", opacity: 0.28, scale: 1 },\n};\n\nconst OVERLAY_OPACITY: Record<ImageGenerationStatus, number> = {\n  queued: 1,\n  generating: 1,\n  refining: 0.48,\n  complete: 0,\n  error: 0,\n};\n\nconst DOT_GAP = 10;\nconst TWO_PI = Math.PI * 2;\n\nfunction DitherMark({\n  status,\n  reduce,\n}: {\n  status: ImageGenerationStatus;\n  reduce: boolean;\n}) {\n  if (status === \"complete\") {\n    return <Check aria-hidden=\"true\" className=\"size-3.5\" />;\n  }\n\n  if (status === \"error\") {\n    return <CircleAlert aria-hidden=\"true\" className=\"size-3.5\" />;\n  }\n\n  return (\n    <motion.span\n      aria-hidden=\"true\"\n      animate={reduce ? undefined : { rotate: 360 }}\n      transition={{\n        duration: 2.4,\n        ease: EASE_IN_OUT,\n        repeat: Number.POSITIVE_INFINITY,\n      }}\n      className=\"grid size-3.5 grid-cols-2 place-items-center gap-0.5\"\n    >\n      <span className=\"size-1 rounded-[1px] bg-current\" />\n      <span className=\"size-1 rounded-[1px] bg-current opacity-55\" />\n      <span className=\"size-1 rounded-[1px] bg-current opacity-55\" />\n      <span className=\"size-1 rounded-[1px] bg-current\" />\n    </motion.span>\n  );\n}\n\nfunction DitherField({\n  interactive,\n  reduce,\n  status,\n}: {\n  interactive: boolean;\n  reduce: boolean;\n  status: ImageGenerationStatus;\n}) {\n  const canHover = useHoverCapable();\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    const context = canvas?.getContext(\"2d\");\n    if (!canvas || !context) return;\n\n    let frame = 0;\n    let width = 0;\n    let height = 0;\n    let dotColor = \"currentColor\";\n    const pointer = {\n      x: 0,\n      y: 0,\n      targetX: 0,\n      targetY: 0,\n      inside: false,\n    };\n    const pointerEnabled = interactive && canHover && !reduce;\n\n    const resize = () => {\n      const rect = canvas.getBoundingClientRect();\n      width = rect.width || canvas.clientWidth || 208;\n      height = rect.height || canvas.clientHeight || 208;\n      const dpr = Math.min(window.devicePixelRatio || 1, 2);\n\n      canvas.width = Math.round(width * dpr);\n      canvas.height = Math.round(height * dpr);\n      context.setTransform(dpr, 0, 0, dpr, 0, 0);\n      dotColor = window.getComputedStyle(canvas).color;\n      pointer.x = width / 2;\n      pointer.y = height / 2;\n      pointer.targetX = pointer.x;\n      pointer.targetY = pointer.y;\n      // Sizing the canvas clears it, and reduced motion has no frame loop to repaint.\n      if (reduce) draw(0);\n    };\n\n    const draw = (time: number) => {\n      context.clearRect(0, 0, width, height);\n\n      if (!pointer.inside) {\n        pointer.targetX =\n          width / 2 + (reduce ? 0 : Math.sin(time / 1700) * width * 0.12);\n        pointer.targetY =\n          height / 2 + (reduce ? 0 : Math.cos(time / 2100) * height * 0.1);\n      }\n\n      const follow = reduce ? 1 : pointer.inside ? 0.16 : 0.045;\n      pointer.x += (pointer.targetX - pointer.x) * follow;\n      pointer.y += (pointer.targetY - pointer.y) * follow;\n\n      const radius = Math.min(width, height) * 0.38;\n      const columns = Math.ceil(width / DOT_GAP) + 1;\n      const rows = Math.ceil(height / DOT_GAP) + 1;\n      const offsetX = (width - (columns - 1) * DOT_GAP) / 2;\n      const offsetY = (height - (rows - 1) * DOT_GAP) / 2;\n\n      context.fillStyle = dotColor;\n\n      for (let row = 0; row < rows; row += 1) {\n        for (let column = 0; column < columns; column += 1) {\n          const anchorX = offsetX + column * DOT_GAP;\n          const anchorY = offsetY + row * DOT_GAP;\n          const deltaX = anchorX - pointer.x;\n          const deltaY = anchorY - pointer.y;\n          const distance = Math.hypot(deltaX, deltaY);\n          const proximity = Math.max(0, 1 - distance / radius);\n          const influence = proximity * proximity * (3 - 2 * proximity);\n          const displacement = influence * influence * 9;\n          const directionX = distance > 0 ? deltaX / distance : 0;\n          const directionY = distance > 0 ? deltaY / distance : 0;\n          const x = anchorX + directionX * displacement;\n          const y = anchorY + directionY * displacement;\n          const dotRadius = 0.65 + influence * 0.85;\n\n          context.globalAlpha = 0.17 + influence * 0.72;\n          context.beginPath();\n          context.arc(x, y, dotRadius, 0, TWO_PI);\n          context.fill();\n        }\n      }\n\n      context.globalAlpha = 1;\n      if (!reduce) frame = window.requestAnimationFrame(draw);\n    };\n\n    const handlePointerMove = (event: PointerEvent) => {\n      if (!pointerEnabled) return;\n      const rect = canvas.getBoundingClientRect();\n      pointer.inside = true;\n      pointer.targetX = event.clientX - rect.left;\n      pointer.targetY = event.clientY - rect.top;\n    };\n\n    const handlePointerLeave = () => {\n      pointer.inside = false;\n    };\n\n    const resizeObserver =\n      typeof ResizeObserver === \"undefined\"\n        ? null\n        : new ResizeObserver(resize);\n\n    resize();\n    resizeObserver?.observe(canvas);\n    canvas.addEventListener(\"pointermove\", handlePointerMove, { passive: true });\n    canvas.addEventListener(\"pointerleave\", handlePointerLeave);\n    draw(0);\n\n    return () => {\n      if (frame) window.cancelAnimationFrame(frame);\n      resizeObserver?.disconnect();\n      canvas.removeEventListener(\"pointermove\", handlePointerMove);\n      canvas.removeEventListener(\"pointerleave\", handlePointerLeave);\n    };\n  }, [canHover, interactive, reduce]);\n\n  return (\n    <motion.div\n      aria-hidden=\"true\"\n      initial={false}\n      animate={{ opacity: OVERLAY_OPACITY[status] }}\n      transition={{ duration: reduce ? 0 : 0.4, ease: EASE_OUT }}\n      className=\"absolute inset-0 overflow-hidden bg-muted\"\n    >\n      <canvas\n        ref={canvasRef}\n        className=\"absolute inset-0 size-full text-foreground\"\n      />\n    </motion.div>\n  );\n}\n\nexport function ImageGeneration({\n  children,\n  status = \"generating\",\n  label,\n  prompt,\n  resolution = \"1024 × 1024\",\n  aspectRatio = \"1 / 1\",\n  size = \"compact\",\n  interactive = true,\n  statusText,\n  showStatus = true,\n  onRetry,\n  labels,\n  className,\n  mediaClassName,\n  statusClassName,\n}: ImageGenerationProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"imageGeneration\", imageGenerationMessages, labels);\n  const active =\n    status === \"queued\" || status === \"generating\" || status === \"refining\";\n  const mediaState = MEDIA_STATE[status];\n  const resolvedStatusText = statusText ?? t(status);\n  const resolvedLabel =\n    label ??\n    (prompt\n      ? t(\"labelWithPrompt\", { status: resolvedStatusText, prompt })\n      : resolvedStatusText);\n\n  return (\n    <div\n      data-slot=\"image-generation\"\n      data-state={status}\n      aria-busy={active}\n      className={cn(\"w-full\", className)}\n    >\n      <div\n        className={cn(\n          \"w-full\",\n          size === \"compact\" && \"mx-auto max-w-52\",\n        )}\n      >\n        <div\n          role=\"img\"\n          aria-label={resolvedLabel}\n          style={{ aspectRatio }}\n          className=\"relative isolate w-full overflow-hidden rounded-2xl bg-muted\"\n        >\n          <motion.div\n            aria-hidden={children ? undefined : true}\n            initial={false}\n            animate={\n              reduce\n                ? { opacity: mediaState.opacity }\n                : {\n                    filter: mediaState.filter,\n                    opacity: mediaState.opacity,\n                    scale: mediaState.scale,\n                  }\n            }\n            transition={\n              reduce ? { duration: 0 } : { duration: 0.4, ease: EASE_OUT }\n            }\n            className={cn(\n              \"absolute inset-0 [&>*]:size-full [&>*]:object-cover [&_img]:size-full [&_img]:object-cover\",\n              mediaClassName,\n            )}\n          >\n            {children}\n          </motion.div>\n\n          <AnimatePresence initial={false}>\n            {active ? (\n              <motion.div\n                key=\"dither-field\"\n                initial={{ opacity: 0 }}\n                animate={{ opacity: 1 }}\n                exit={{ opacity: 0 }}\n                transition={{ duration: reduce ? 0 : 0.25, ease: EASE_OUT }}\n                className=\"absolute inset-0\"\n              >\n                <DitherField\n                  interactive={interactive}\n                  reduce={reduce}\n                  status={status}\n                />\n              </motion.div>\n            ) : null}\n          </AnimatePresence>\n\n          {resolution ? (\n            <span className=\"absolute top-2 right-2 z-10 rounded-full bg-background/75 px-2 py-0.5 font-mono text-[11px] tabular-nums text-muted-foreground\">\n              {resolution}\n            </span>\n          ) : null}\n        </div>\n\n        {showStatus || prompt ? (\n          <div className=\"mt-3 text-left\">\n            {showStatus ? (\n              <div\n                aria-live=\"polite\"\n                className={cn(\n                  \"flex min-h-5 items-center gap-2 text-sm font-medium text-foreground\",\n                  status === \"error\" && \"text-destructive\",\n                  statusClassName,\n                )}\n              >\n                <IconSwap id={active ? \"active\" : status}>\n                  <DitherMark status={status} reduce={reduce} />\n                </IconSwap>\n                <AnimatePresence mode=\"popLayout\" initial={false}>\n                  <motion.span\n                    key={resolvedStatusText}\n                    initial={reduce ? false : { opacity: 0, y: 4 }}\n                    animate={{ opacity: 1, y: 0 }}\n                    exit={reduce ? undefined : { opacity: 0, y: -4 }}\n                    transition={{\n                      duration: reduce ? 0 : 0.15,\n                      ease: EASE_OUT,\n                    }}\n                  >\n                    {resolvedStatusText}\n                  </motion.span>\n                </AnimatePresence>\n              </div>\n            ) : null}\n            {prompt ? (\n              <p className=\"mt-0.5 truncate text-xs text-muted-foreground\">\n                {t(\"quotedPrompt\", { prompt })}\n              </p>\n            ) : null}\n          </div>\n        ) : null}\n\n        {status === \"error\" && onRetry ? (\n          <motion.button\n            type=\"button\"\n            onClick={onRetry}\n            whileTap={reduce ? undefined : { scale: 0.96 }}\n            transition={SPRING_PRESS}\n            className=\"mt-3 inline-flex min-h-10 items-center gap-2 rounded-full px-3 text-sm font-medium text-foreground outline-none transition-colors hover:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring\"\n          >\n            <RotateCcw aria-hidden=\"true\" className=\"size-4\" />\n            {t(\"retry\")}\n          </motion.button>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n"},{"path":"components/agents/icon-swap.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { SPRING_SWAP } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface IconSwapProps {\n  /** Changes whenever the icon should change (copy → copied, running → done). */\n  id: string;\n  children: ReactNode;\n  className?: string;\n}\n\n/**\n * Crossfades one status icon into the next with a little scale and a 2px\n * blur, so the change reads as one icon morphing rather than two crossing.\n * Reduced motion keeps the fade and drops the scale.\n */\nexport function IconSwap({ id, children, className }: IconSwapProps) {\n  const reduce = useReducedMotion() ?? false;\n  return (\n    <AnimatePresence mode=\"popLayout\" initial={false}>\n      <motion.span\n        key={id}\n        initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: \"blur(2px)\" }}\n        animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n        exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: \"blur(2px)\" }}\n        transition={reduce ? { duration: 0.12 } : SPRING_SWAP}\n        className={cn(\"grid place-items-center\", className)}\n      >\n        {children}\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/hooks/use-hover-capable.ts","type":"util","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true only on devices that have a true hover (mouse / trackpad).\n * Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere\n * - gate hover-only effects (scale lifts, magnetic pulls) behind this.\n */\nexport function useHoverCapable() {\n  const [canHover, setCanHover] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\" || !window.matchMedia) return;\n    const mq = window.matchMedia(\"(hover: hover) and (pointer: fine)\");\n    const update = () => setCanHover(mq.matches);\n    update();\n    mq.addEventListener?.(\"change\", update);\n    return () => mq.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canHover;\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"components/previews/agents/image-generation.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { RotateCcw } from \"lucide-react\";\nimport { useReducedMotion } from \"motion/react\";\nimport { useEffect, useState } from \"react\";\nimport {\n  ImageGeneration,\n  type ImageGenerationStatus,\n} from \"@/components/agents/image-generation\";\n\nfunction GeneratedArtwork() {\n  return (\n    <svg\n      viewBox=\"0 0 800 600\"\n      aria-hidden=\"true\"\n      className=\"size-full\"\n      preserveAspectRatio=\"xMidYMid slice\"\n    >\n      <defs>\n        <linearGradient id=\"image-sky\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\">\n          <stop offset=\"0\" stopColor=\"#191b33\" />\n          <stop offset=\"0.48\" stopColor=\"#60538d\" />\n          <stop offset=\"1\" stopColor=\"#e59b7b\" />\n        </linearGradient>\n        <linearGradient id=\"image-ground\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n          <stop offset=\"0\" stopColor=\"#314946\" />\n          <stop offset=\"1\" stopColor=\"#101817\" />\n        </linearGradient>\n        <radialGradient id=\"image-glow\">\n          <stop offset=\"0\" stopColor=\"#ffe6b2\" stopOpacity=\"0.95\" />\n          <stop offset=\"1\" stopColor=\"#efb47e\" stopOpacity=\"0\" />\n        </radialGradient>\n      </defs>\n      <rect width=\"800\" height=\"600\" fill=\"url(#image-sky)\" />\n      <circle cx=\"570\" cy=\"210\" r=\"150\" fill=\"url(#image-glow)\" />\n      <circle cx=\"570\" cy=\"210\" r=\"54\" fill=\"#ffe5ad\" />\n      <path\n        d=\"M0 395 120 314l92 54 132-143 116 126 78-66 92 88 170-61v288H0Z\"\n        fill=\"#283d43\"\n        opacity=\"0.9\"\n      />\n      <path\n        d=\"M0 432 118 376l99 73 115-97 107 92 112-52 108 68 141-48v188H0Z\"\n        fill=\"url(#image-ground)\"\n      />\n      <path\n        d=\"M0 505c116-44 190-32 280 6 103 44 212 47 330-7 68-31 126-37 190-28v124H0Z\"\n        fill=\"#13201f\"\n      />\n      <g fill=\"#c9d7c3\" opacity=\"0.65\">\n        <circle cx=\"108\" cy=\"142\" r=\"2\" />\n        <circle cx=\"168\" cy=\"102\" r=\"1.5\" />\n        <circle cx=\"248\" cy=\"154\" r=\"2\" />\n        <circle cx=\"332\" cy=\"84\" r=\"1.5\" />\n        <circle cx=\"414\" cy=\"138\" r=\"2\" />\n      </g>\n    </svg>\n  );\n}\n\nfunction GenerationDemo({ onReplay }: { onReplay: () => void }) {\n  const reduce = useReducedMotion() ?? false;\n  const [status, setStatus] = useState<ImageGenerationStatus>(\n    reduce ? \"complete\" : \"queued\",\n  );\n\n  useEffect(() => {\n    if (reduce) return;\n\n    const timers = [\n      window.setTimeout(() => setStatus(\"generating\"), 500),\n      window.setTimeout(() => setStatus(\"refining\"), 3000),\n      window.setTimeout(() => setStatus(\"complete\"), 5200),\n    ];\n\n    return () => {\n      timers.forEach((timer) => {\n        window.clearTimeout(timer);\n      });\n    };\n  }, [reduce]);\n\n  return (\n    <div className=\"flex w-full flex-col items-center\">\n      <ImageGeneration\n        label=\"A quiet mountain landscape at sunset\"\n        prompt=\"a quiet mountain landscape at sunset\"\n        resolution=\"1024 × 1024\"\n        status={status}\n        onRetry={onReplay}\n      >\n        <GeneratedArtwork />\n      </ImageGeneration>\n      <button\n        type=\"button\"\n        onClick={onReplay}\n        className=\"mt-4 inline-flex min-h-10 items-center gap-2 rounded-full px-3 text-sm font-medium text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n      >\n        <RotateCcw aria-hidden=\"true\" className=\"size-4\" />\n        Replay\n      </button>\n    </div>\n  );\n}\n\nexport function ImageGenerationPreview() {\n  const [run, setRun] = useState(0);\n\n  return (\n    <div className=\"w-full max-w-xl\">\n      <GenerationDemo\n        key={run}\n        onReplay={() => setRun((value) => value + 1)}\n      />\n    </div>\n  );\n}\n"}]}