{"slug":"artifact-panel","category":"messages","job":"ask","added":"2026-11-08T13:50Z","title":"Artifact Panel","description":"A side panel beside the chat for a document or app the model made — opened from a card in the message, with Preview and Code tabs, a version stepper fed by follow-ups, and Copy.","url":"https://ai-patterns.app/patterns/messages/artifact-panel","markdown":"https://ai-patterns.app/patterns/messages/artifact-panel.md","json":"https://ai-patterns.app/api/patterns/messages/artifact-panel","seenIn":[{"team":"Claude","source":"https://support.claude.com/en/articles/9487310-what-are-artifacts-and-how-do-i-use-them"},{"team":"chatgpt","source":"https://help.openai.com/en/articles/9930697-what-is-the-canvas-feature-in-chatgpt-and-how-do-i-use-it"},{"team":"Google Gemini","source":"https://blog.google/products/gemini/gemini-collaboration-features/"}],"spec":"# Artifact Panel\n\n## Summary\nA side panel that opens beside the chat to hold a substantial thing the model made — a document, a component, a diagram — so it can be read, versioned, copied and revised without scrolling the transcript. The message that produced it keeps a compact card that opens the panel; follow-up turns write new versions into the same panel instead of pasting the whole thing again.\n\n## When to use\n- The output is something people will keep and reuse (a plan, a page of code, an HTML app, a diagram), not an answer to read once.\n- The output is long enough that showing it inline would push the conversation off screen — roughly more than a screen of text or a dozen lines of code.\n- People will iterate on it over several turns (\"make it shorter\", \"add a pricing section\") and need to compare versions.\n- The output renders into something other than text (a live preview of a component, a chart), where a preview and its source are both useful.\n\n## When not to use\n- Short answers, snippets or a few lines of code — keep them inline. A panel for a three-line reply is a detour.\n- Content the user is meant to read in the flow of the conversation (an explanation, a summary). Put it in the message.\n- When the product already has a document or editor surface. Write into that surface directly instead of a second, parallel one.\n- When the screen is too narrow for two columns and the artifact is not the main point — an inline expandable block costs less than covering the chat.\n\n## Anatomy\n- Artifact card: in the message that created the artifact — a type icon, the title, the type and version (\"Document · v2\") and an open affordance. One card per version-producing message, so the transcript shows where each version came from.\n- Panel: beside the chat on wide screens, covering it on narrow ones.\n- Header: the title, a one-line note on what this version changed, a version stepper (\"v2/2\"), Copy and Close.\n- View tabs: Preview and Code, shown only when the artifact has source behind its rendering.\n- Body: the rendered artifact or its source, scrolling on its own.\n- Writing state: a thin indeterminate bar and a dimmed body while a new version is being written.\n\n## Behavior\n- The panel opens automatically when the model starts writing an artifact, and on demand from any card. Opening an older message's card shows that message's version.\n- A follow-up that changes the artifact adds a new version and switches the panel to it. Earlier versions stay reachable from the stepper; nothing is overwritten.\n- While a new version is written, the previous one stays visible but dimmed, so the user never looks at an empty panel. Don't let them edit a version that is being replaced.\n- Side by side from about 42rem of container width; below that the panel covers the chat and Close returns to it. Size the split by the container, not the viewport, so the pattern also works inside a narrow pane.\n- Escape and Close collapse the panel and return focus to the card that opened it. The chat column keeps its scroll position.\n- Copy copies the current version's source, and confirms in place (\"Copied\") for a moment.\n\n## Content guidelines\n- Titles name the thing, not the request: \"Q3 beta launch plan\", not \"Here's your plan\".\n- Version notes say what changed in a few words (\"Shorter, one screen\", \"Added pricing\"), not \"Updated version\".\n- The message that carries the card says what the artifact is or what changed in a sentence. Don't repeat the artifact's content in the message.\n- Type labels are concrete (\"Document\", \"React\", \"HTML\", \"Diagram\"), never \"Artifact\".\n\n## Accessibility\n- The card is a real button with `aria-expanded` reflecting whether its panel is open.\n- The panel is a labelled `aside` (named by its title). On open, focus moves to the title; on close, it returns to the opening card.\n- Preview and Code use the tabs pattern: `role=\"tablist\"`, `aria-selected` on each tab, and a labelled `tabpanel`.\n- The version label and the \"Writing a new version…\" note sit in polite live regions so version changes are announced; the body is `aria-busy` while writing.\n- Icon-only buttons (previous, next, copy, close) carry accessible names. Respect `prefers-reduced-motion`: fade the panel in instead of sliding it.\n\n## Related patterns\n- **Code Preview Block** — Use it instead for a short snippet that should stay inline in the message.\n- **Diff Tabs** — Use it as well when the artifact is code and people need to see what changed between versions.\n- **Selection Actions** — Use it inside the panel so people can select a passage and ask for a change to just that part.\n- **Conversation Branches** — Use it instead when people want alternative replies to one prompt, not successive versions of one thing.\n","code":"\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { Check, ChevronLeft, ChevronRight, Code2, Copy, FileText, LayoutPanelLeft, X } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport interface ArtifactVersion {\n  id: string;\n  /** What changed in this version, e.g. \"Shorter, one page\". Shown under the title. */\n  note?: string;\n  /** The rendered artifact for the Preview tab. */\n  preview: React.ReactNode;\n  /** Source for the Code tab and for Copy. Omit to hide the tab. */\n  source?: string;\n}\n\nexport interface Artifact {\n  id: string;\n  title: string;\n  /** A short type label: \"Document\", \"React\", \"HTML\", \"Diagram\"… */\n  kind: string;\n  versions: ArtifactVersion[];\n}\n\n/* ------------------------------------------------------------------ */\n/* Inline card: the artifact's place in the transcript                 */\n/* ------------------------------------------------------------------ */\n\nexport interface ArtifactCardProps {\n  artifact: Artifact;\n  /** Index of the version this message produced. */\n  version?: number;\n  open?: boolean;\n  /** Still being written. The card stays clickable so people can watch it fill. */\n  generating?: boolean;\n  onOpen: () => void;\n  className?: string;\n}\n\nexport const ArtifactCard = React.forwardRef<HTMLButtonElement, ArtifactCardProps>(function ArtifactCard(\n  { artifact, version = artifact.versions.length - 1, open, generating, onOpen, className },\n  ref\n) {\n  const Icon = artifact.versions[version]?.source && artifact.kind !== \"Document\" ? Code2 : FileText;\n  return (\n    <button\n      ref={ref}\n      type=\"button\"\n      onClick={onOpen}\n      aria-expanded={open}\n      className={cn(\n        \"group flex w-full max-w-xs items-center gap-3 rounded-xl border bg-card p-2 pr-3 text-left transition-colors hover:bg-accent/60\",\n        open && \"border-foreground/30 bg-accent/40\",\n        className\n      )}\n    >\n      <span className=\"flex size-10 shrink-0 items-center justify-center rounded-lg text-muted-foreground bg-muted\">\n        <Icon className=\"size-4\" aria-hidden />\n      </span>\n      <span className=\"min-w-0 flex-1\">\n        <span className=\"block truncate text-sm font-medium\">{artifact.title}</span>\n        <span className=\"block text-xs text-muted-foreground\">\n          {generating ? \"Writing…\" : `${artifact.kind} · v${version + 1}`}\n        </span>\n      </span>\n      <span className=\"shrink-0 text-xs font-medium text-muted-foreground group-hover:text-foreground\">\n        {open ? \"Viewing\" : \"View\"}\n      </span>\n    </button>\n  );\n});\n\n/* ------------------------------------------------------------------ */\n/* Split layout: chat beside the panel, or the panel over the chat     */\n/* ------------------------------------------------------------------ */\n\nexport interface ArtifactSplitProps {\n  open: boolean;\n  chat: React.ReactNode;\n  panel: React.ReactNode;\n  className?: string;\n}\n\n/**\n * Side by side when the container is at least 42rem wide; below that the\n * panel covers the chat, because two cramped columns serve neither.\n */\nexport function ArtifactSplit({ open, chat, panel, className }: ArtifactSplitProps) {\n  return (\n    <div className={cn(\"@container relative flex h-full w-full overflow-hidden\", className)}>\n      <div className={cn(\"flex min-w-0 flex-1 flex-col\", open && \"@max-2xl:invisible\")}>{chat}</div>\n      <AnimatePresence initial={false}>{open && panel}</AnimatePresence>\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------ */\n/* The panel                                                           */\n/* ------------------------------------------------------------------ */\n\nexport interface ArtifactPanelProps {\n  artifact: Artifact;\n  version: number;\n  onVersionChange: (index: number) => void;\n  onClose: () => void;\n  /** The model is writing a new version right now. */\n  generating?: boolean;\n  className?: string;\n}\n\nexport function ArtifactPanel({\n  artifact,\n  version,\n  onVersionChange,\n  onClose,\n  generating,\n  className,\n}: ArtifactPanelProps) {\n  const reduce = useReducedMotion();\n  const [tab, setTab] = React.useState<\"preview\" | \"code\">(\"preview\");\n  const [copied, setCopied] = React.useState(false);\n  const headingRef = React.useRef<HTMLHeadingElement>(null);\n  const id = React.useId();\n\n  const current = artifact.versions[version];\n  const count = artifact.versions.length;\n  const hasSource = Boolean(current?.source);\n  const activeTab = hasSource ? tab : \"preview\";\n\n  // Move focus into the panel when it opens so keyboard and screen-reader\n  // users land on the thing they asked to see. Whoever opened it gets focus\n  // back on close (see the demo's card ref).\n  React.useEffect(() => {\n    headingRef.current?.focus();\n  }, []);\n\n  React.useEffect(() => {\n    if (!copied) return;\n    const t = setTimeout(() => setCopied(false), 1500);\n    return () => clearTimeout(t);\n  }, [copied]);\n\n  async function copy() {\n    const text = current?.source ?? \"\";\n    try {\n      await navigator.clipboard.writeText(text);\n      setCopied(true);\n    } catch {\n      // Clipboard can be blocked (iframes, permissions); fail quietly.\n    }\n  }\n\n  return (\n    <motion.aside\n      aria-labelledby={`${id}-title`}\n      onKeyDown={(e) => {\n        if (e.key === \"Escape\") {\n          e.stopPropagation();\n          onClose();\n        }\n      }}\n      initial={reduce ? { opacity: 0 } : { opacity: 0, x: 24 }}\n      animate={{ opacity: 1, x: 0 }}\n      exit={reduce ? { opacity: 0 } : { opacity: 0, x: 24 }}\n      transition={{ duration: 0.2, ease: \"easeOut\" }}\n      className={cn(\n        \"absolute inset-0 z-10 flex flex-col bg-background @2xl:static @2xl:w-[58%] @2xl:shrink-0 @2xl:border-l\",\n        className\n      )}\n    >\n      <header className=\"flex items-center gap-2 border-b px-3 py-2\">\n        <div className=\"min-w-0 flex-1\">\n          <h3\n            ref={headingRef}\n            id={`${id}-title`}\n            tabIndex={-1}\n            className=\"truncate text-sm font-medium outline-none\"\n          >\n            {artifact.title}\n          </h3>\n          <p className=\"truncate text-xs text-muted-foreground\" aria-live=\"polite\">\n            {generating ? \"Writing a new version…\" : current?.note ?? artifact.kind}\n          </p>\n        </div>\n\n        {count > 1 && (\n          <div className=\"flex items-center rounded-lg border text-xs\" role=\"group\" aria-label=\"Version\">\n            <IconBtn\n              label=\"Previous version\"\n              disabled={version === 0}\n              onClick={() => onVersionChange(version - 1)}\n            >\n              <ChevronLeft className=\"size-3.5\" aria-hidden />\n            </IconBtn>\n            <span className=\"px-1 tabular-nums text-muted-foreground\" aria-live=\"polite\">\n              v{version + 1}\n              <span className=\"sr-only\"> of {count}</span>\n              <span aria-hidden>/{count}</span>\n            </span>\n            <IconBtn\n              label=\"Next version\"\n              disabled={version === count - 1}\n              onClick={() => onVersionChange(version + 1)}\n            >\n              <ChevronRight className=\"size-3.5\" aria-hidden />\n            </IconBtn>\n          </div>\n        )}\n\n        {hasSource && (\n          <IconBtn label={copied ? \"Copied\" : \"Copy\"} onClick={copy} className=\"rounded-lg\">\n            {copied ? <Check className=\"size-3.5\" aria-hidden /> : <Copy className=\"size-3.5\" aria-hidden />}\n          </IconBtn>\n        )}\n        <IconBtn label=\"Close panel\" onClick={onClose} className=\"rounded-lg\">\n          <X className=\"size-4\" aria-hidden />\n        </IconBtn>\n      </header>\n\n      {hasSource && (\n        <div role=\"tablist\" aria-label=\"View\" className=\"flex gap-1 border-b px-3 py-1.5\">\n          {([\"preview\", \"code\"] as const).map((t) => (\n            <button\n              key={t}\n              type=\"button\"\n              role=\"tab\"\n              id={`${id}-tab-${t}`}\n              aria-selected={activeTab === t}\n              aria-controls={`${id}-body`}\n              onClick={() => setTab(t)}\n              className={cn(\n                \"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground\",\n                activeTab === t && \"bg-accent text-foreground\"\n              )}\n            >\n              {t === \"preview\" ? (\n                <LayoutPanelLeft className=\"size-3.5\" aria-hidden />\n              ) : (\n                <Code2 className=\"size-3.5\" aria-hidden />\n              )}\n              {t === \"preview\" ? \"Preview\" : \"Code\"}\n            </button>\n          ))}\n        </div>\n      )}\n\n      <div\n        id={`${id}-body`}\n        role={hasSource ? \"tabpanel\" : undefined}\n        aria-labelledby={hasSource ? `${id}-tab-${activeTab}` : undefined}\n        aria-busy={generating || undefined}\n        tabIndex={0}\n        className=\"relative min-h-0 flex-1 overflow-auto outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset\"\n      >\n        <AnimatePresence mode=\"wait\" initial={false}>\n          <motion.div\n            key={`${current?.id}-${activeTab}`}\n            initial={{ opacity: 0 }}\n            animate={{ opacity: generating ? 0.45 : 1 }}\n            exit={{ opacity: 0 }}\n            transition={{ duration: 0.15 }}\n          >\n            {activeTab === \"code\" ? (\n              <pre className=\"p-4 font-mono text-xs leading-relaxed whitespace-pre-wrap text-muted-foreground\">\n                {current?.source}\n              </pre>\n            ) : (\n              <div className=\"p-5\">{current?.preview}</div>\n            )}\n          </motion.div>\n        </AnimatePresence>\n        {generating && (\n          <div className=\"pointer-events-none absolute inset-x-0 top-0 h-0.5 overflow-hidden bg-muted\">\n            <motion.div\n              className=\"h-full w-1/3 bg-foreground/40\"\n              animate={reduce ? undefined : { x: [\"-100%\", \"300%\"] }}\n              transition={{ duration: 1.2, repeat: Infinity, ease: \"easeInOut\" }}\n            />\n          </div>\n        )}\n      </div>\n    </motion.aside>\n  );\n}\n\nfunction IconBtn({\n  label,\n  onClick,\n  disabled,\n  className,\n  children,\n}: {\n  label: string;\n  onClick: () => void;\n  disabled?: boolean;\n  className?: string;\n  children: React.ReactNode;\n}) {\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      title={label}\n      onClick={onClick}\n      disabled={disabled}\n      className={cn(\n        \"flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-40\",\n        className\n      )}\n    >\n      {children}\n    </button>\n  );\n}\n","dependencies":["lucide-react","motion"],"localImports":["@/lib/utils"]}