{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-side-panel",
  "title": "AI side panel",
  "description": "An AI assistant docked beside the page — a header with History and Close, a removable chip saying what it is looking at, a short thread, and the small composer, on one soft top-to-bottom AI wash.",
  "registryDependencies": [
    "sheet",
    "button",
    "https://www.quilldesignsystem.com/r/icon.json",
    "https://www.quilldesignsystem.com/r/ai-mark.json",
    "https://www.quilldesignsystem.com/r/prompt-composer.json",
    "https://www.quilldesignsystem.com/r/ai-message.json",
    "https://www.quilldesignsystem.com/r/ai-thinking.json",
    "https://www.quilldesignsystem.com/r/citations.json",
    "https://www.quilldesignsystem.com/r/suggested-prompts.json"
  ],
  "files": [
    {
      "path": "registry/blocks/ai-side-panel.tsx",
      "content": "'use client'\n\nimport * as React from 'react'\nimport { Sheet, SheetClose, SheetContent, SheetTrigger } from '@/components/ui/sheet'\nimport { Button } from '@/components/ui/button'\nimport { Icon } from '@/components/ui/icon'\nimport { AiMark } from '@/components/ui/ai-mark'\nimport { PromptComposer } from '@/components/ui/prompt-composer'\nimport { AiMessage, UserMessage } from '@/components/ui/ai-message'\nimport { AiThinking } from '@/components/ui/ai-thinking'\nimport { Citation, type Source } from '@/components/ui/citations'\nimport { SuggestedPrompts } from '@/components/ui/suggested-prompts'\nimport { cn } from '@/lib/utils'\n\nconst SOURCE: Source = { title: 'Changelog: new pricing page', label: 'changelog', detail: 'example.com/changelog', snippet: 'Shipped 9 September: annual plans shown first.', kind: 'web' }\n\ntype Turn = { id: number; ask: string; reply: 'working' | 'stopped' }\n\n// One close icon, shared: the Sheet's Close reuses this.\nconst closeIcon = (size?: number) => <Icon name=\"close\" size={size} />\n\n// The thread has to move this many px before the fade appears: its top padding. Less than that and nothing has gone\n// under the header yet, so a trackpad nudge would only fade the scope chip where it sits.\nconst THREAD_FADE_AFTER = 4\n\n// React draws nothing for these, so a prop holding one is \"nothing passed\": `text && <List />` with an empty string.\nconst drawsNothing = (node: React.ReactNode) => node === undefined || node === null || typeof node === 'boolean' || node === ''\n\n// The Sheet's own element, for the panel inside AiSidePanel: the one thing outside itself the panel may send focus to.\nconst SheetElement = React.createContext<React.RefObject<HTMLElement | null> | null>(null)\n\n// A device whose main pointer is a finger. Why that decides where focus goes is told once, at the Sheet below.\nconst onTouchScreen = () => window.matchMedia('(pointer: coarse)').matches\n\nexport type AiPanelProps = {\n  title?: string\n  /** What the assistant can see: \"Q3 report\". Pass a string or null to control it; leave it out and the panel keeps its own. */\n  scope?: string | null\n  /** Called when the chip's remove button is pressed. A scope you control needs this, or the chip has no remove button. */\n  onScopeRemove?: () => void\n  /** History only calls this; the panel has no past-chats view of its own. Left out, the History button is not drawn. */\n  onHistory?: () => void\n  /** A close control for the header. AiSidePanel passes the Sheet's own. */\n  close?: React.ReactNode\n  /** The message box, for a wrapper that sends focus there. AiSidePanel passes its own, to open with the cursor in the box. */\n  composerRef?: React.RefObject<HTMLTextAreaElement | null>\n  onSubmit?: (value: string) => void\n  /** Your own conversation: UserMessage, AiMessage and cards, each turn a direct child. Passing anything but undefined replaces the sample conversation: no sample messages, no sample follow-up, and sending adds nothing by itself (add the turn in onSubmit). Unlike body, null, false and an empty list count as passed here: they are your thread with nothing in it yet, so only undefined shows the sample. Replies in a panel should pass hideName: the header already says who is answering. */\n  children?: React.ReactNode\n  /** With your own conversation: 'working' while a reply is being written, which shows Stop. Not read while the sample is shown. */\n  status?: 'idle' | 'working'\n  /** With your own conversation: called when Stop is pressed. The cursor goes back to the message box either way. */\n  onStop?: () => void\n  /** The message box's text. Pass a string to control it (and clear it yourself after onSubmit); leave it out and the panel keeps its own. */\n  value?: string\n  onValueChange?: (value: string) => void\n  /** Shown in place of the thread (the scope chip and the messages) for as long as it is passed: your list of past chats while History is open, for example. The header and the composer stay. Anything React draws nothing for (undefined, null, true, false, an empty string) means \"no body\", so `open ? <List /> : null` and `open && <List />` both work, and the thread is back where it was. */\n  body?: React.ReactNode\n  className?: string\n}\n\n/** The assistant panel on its own (header, scope chip, thread and composer on one AI wash), for a layout that gives it its own column. */\nexport function AiPanel({\n  title = 'Assistant', scope, onScopeRemove, onHistory, close, composerRef: givenComposerRef, onSubmit = () => {},\n  children, status = 'idle', onStop, value: givenValue, onValueChange, body, className,\n}: AiPanelProps) {\n  const titleId = React.useId()\n  const [ownScope, setOwnScope] = React.useState<string | null>('Q3 report')\n  const currentScope = scope === undefined ? ownScope : scope\n  // A scope the app controls, with nothing to call, cannot be removed: no dead button.\n  const removable = scope === undefined || Boolean(onScopeRemove)\n  const [ownValue, setOwnValue] = React.useState('')\n  const value = givenValue === undefined ? ownValue : givenValue\n  const setValue = (next: string) => {\n    if (givenValue === undefined) setOwnValue(next)\n    onValueChange?.(next)\n  }\n  const [turns, setTurns] = React.useState<Turn[]>([])\n  // The app's own conversation, or (left out) the sample one, which this panel keeps going with pretend replies.\n  const ownsThread = children !== undefined\n  const turnCount = ownsThread ? React.Children.count(children) : turns.length\n  // Anything React draws nothing for is \"no body\", so `open ? <List /> : null` and `open && <List />` both show the thread while closed.\n  const hasBody = !drawsNothing(body)\n  const ownComposerRef = React.useRef<HTMLTextAreaElement>(null)\n  const composerRef = givenComposerRef ?? ownComposerRef\n  const scrollerRef = React.useRef<HTMLDivElement>(null)\n  const working = ownsThread ? status === 'working' : turns.at(-1)?.reply === 'working'\n  // Whether a message has been scrolled under the header: only then is there something to fade.\n  const [scrolled, setScrolled] = React.useState(false)\n\n  // A new turn is added at the bottom of a thread that may already be scrolled; keep the newest in view.\n  // An app's thread also opens on its newest turn, and comes back to it when the app starts writing a reply.\n  // Where the thread was when something else took its place; while that shows, \"the newest\" is remembered instead.\n  const threadTop = React.useRef(0)\n  const showsBody = React.useRef(hasBody)\n  const toNewest = React.useCallback(() => {\n    const scroller = scrollerRef.current\n    if (!scroller) return\n    if (showsBody.current) threadTop.current = Number.MAX_SAFE_INTEGER\n    else scroller.scrollTop = scroller.scrollHeight\n  }, [])\n  React.useEffect(() => {\n    if (turnCount > 0) toNewest()\n  }, [turnCount, toNewest])\n  const writing = ownsThread && working\n  React.useEffect(() => {\n    if (writing) toNewest()\n  }, [writing, toNewest])\n  // `body` takes the thread's place in the same scrolling area: it starts at its own top, and the thread returns to\n  // where it was. If the cursor was on something in the body, that is gone now; it lands in the message box, or on a\n  // touch screen on the panel itself: the Sheet's own element, or drawn inline this section, which is made focusable\n  // until focus leaves it again. Never an element of the app's.\n  const panelRef = React.useRef<HTMLElement>(null)\n  const sheet = React.useContext(SheetElement)\n  React.useLayoutEffect(() => {\n    const scroller = scrollerRef.current\n    if (!scroller || showsBody.current === hasBody) return\n    showsBody.current = hasBody\n    scroller.scrollTop = hasBody ? 0 : threadTop.current\n    const active = document.activeElement\n    if (hasBody || (active !== null && active !== document.body)) return\n    if (!onTouchScreen()) return composerRef.current?.focus()\n    if (sheet?.current) return sheet.current.focus()\n    const section = panelRef.current\n    if (!section) return\n    if (!section.hasAttribute('tabindex')) {\n      section.tabIndex = -1\n      section.addEventListener('blur', () => section.removeAttribute('tabindex'), { once: true })\n    }\n    section.focus()\n  }, [hasBody, composerRef, sheet])\n\n  const removeScope = () => {\n    if (scope === undefined) setOwnScope(null)\n    onScopeRemove?.()\n    // The button that was pressed is about to unmount; without this keyboard focus falls to the page.\n    composerRef.current?.focus()\n  }\n\n  return (\n    // One wash on the panel itself, top to bottom, behind all three parts: a band on the header alone reads as a hard edge.\n    <section ref={panelRef} aria-labelledby={titleId} className={cn('ai-wash grid min-h-0 grid-rows-[auto_minmax(0,1fr)_auto] bg-popover text-sm text-popover-foreground', className)}>\n      {/* min-h-12 = a 28px button plus the padding, so the header keeps its height with or without History and Close. */}\n      <div className=\"flex min-h-12 items-center gap-2 py-2.5 pr-2.5 pl-3.5\">\n        <AiMark size=\"icon-lg\" />\n        {/* A paragraph, not a heading: headings take the serif display preset. */}\n        <p id={titleId} className=\"min-w-0 flex-1 truncate font-semibold text-foreground\">{title}</p>\n        {onHistory ? <Button type=\"button\" variant=\"ghost\" size=\"icon-sm\" aria-label=\"History\" onClick={onHistory}><Icon name=\"history\" /></Button> : null}\n        {close}\n      </div>\n      {/* The inner block is pushed to the bottom with an auto margin, which (unlike aligning the content to the end)\n          keeps the top reachable when the thread grows past the panel and scrolls. */}\n      {/* Messages scrolled under the header fade out through a mask: it has no colour of its own, so the wash shows\n          through in every theme, and it is not an element, so it takes no presses. The fade is as deep as a reply's\n          avatar. scroll-pt keeps a control reached by keyboard below it, where its focus ring is drawn in full.\n          relative: kit pieces placed in the thread keep absolutely positioned boxes for screen readers, which must\n          take their place from the thread to scroll with it instead of hanging below the panel. */}\n      <div ref={scrollerRef} data-slot=\"thread\"\n        onScroll={(event) => {\n          setScrolled(event.currentTarget.scrollTop > THREAD_FADE_AFTER)\n          if (!hasBody) threadTop.current = event.currentTarget.scrollTop\n        }}\n        className={cn('relative flex min-h-0 scroll-pt-8 flex-col overflow-y-auto px-3.5 pt-1 pb-2.5', scrolled && '[mask-image:linear-gradient(to_bottom,transparent,black_1.75rem)]')}>\n        {/* Kept on the page (hidden) while something else is shown, so cards in the thread keep what was typed in them. */}\n        <div hidden={hasBody || undefined} className=\"mt-auto grid min-w-0 gap-3\">\n          {currentScope ? (\n            // border-input, not the divider line: the chip has to read as a shape on the wash in the dark themes.\n            <span data-slot=\"scope-chip\" className={cn('inline-flex h-7 w-fit max-w-full items-center gap-1.5 rounded-full border border-input bg-background pl-2 text-xs text-ink-soft', removable ? 'pr-1' : 'pr-2.5')}>\n              <Icon name=\"description\" className=\"size-icon-xs\" />\n              <span className=\"truncate\">{`Looking at: ${currentScope}`}</span>\n              {removable ? (\n                <button type=\"button\" aria-label={`Stop looking at ${currentScope}`} onClick={removeScope}\n                  className=\"grid size-5 shrink-0 place-items-center rounded-full hover:bg-muted hover:text-foreground outline-hidden focus-visible:ring-3 focus-visible:ring-ring/50\">\n                  {closeIcon(12)}\n                </button>\n              ) : null}\n            </span>\n          ) : null}\n          {/* A log is a polite live region, so each new turn is read out. */}\n          <div role=\"log\" aria-label=\"Messages\" className=\"grid min-w-0 gap-3\">\n            {ownsThread ? children : (\n              <>\n                <UserMessage>{\"What's the one thing to fix?\"}</UserMessage>\n                {/* hideName on every reply: the header already says who is answering. */}\n                <AiMessage hideName>\n                  <p>The September dip. It started the day the new pricing page shipped<Citation source={SOURCE} />.</p>\n                </AiMessage>\n                {turns.length === 0 ? (\n                  <SuggestedPrompts layout=\"list\" label=\"Follow-ups\"\n                    suggestions={[{ label: 'Draft a fix for the pricing page' }]}\n                    onPick={(prompt) => { setValue(prompt); composerRef.current?.focus() }} />\n                ) : null}\n                {turns.map((turn) => (\n                  <React.Fragment key={turn.id}>\n                    <UserMessage>{turn.ask}</UserMessage>\n                    {turn.reply === 'working'\n                      ? <AiMessage hideName streaming thinking={<AiThinking status=\"working\" activity=\"Reading the page\" />} />\n                      : <AiMessage hideName stopped />}\n                  </React.Fragment>\n                ))}\n              </>\n            )}\n          </div>\n        </div>\n        {hasBody ? <div data-slot=\"panel-body\" className=\"min-w-0\">{body}</div> : null}\n      </div>\n      <div className=\"px-3 pt-2 pb-3\">\n        <PromptComposer\n          ref={composerRef}\n          size=\"sm\"\n          value={value}\n          onValueChange={setValue}\n          status={working ? 'working' : 'idle'}\n          onStop={() => {\n            if (ownsThread) onStop?.()\n            else setTurns((all) => all.map((turn, index) => (index === all.length - 1 ? { ...turn, reply: 'stopped' } : turn)))\n            // Stop unmounts as the composer goes idle; without this keyboard focus falls to the page.\n            composerRef.current?.focus()\n          }}\n          onSubmit={(text) => {\n            onSubmit(text)\n            if (!ownsThread) setTurns((all) => [...all, { id: all.length + 1, ask: text, reply: 'working' }])\n            // A value the app controls is the app's to clear.\n            if (givenValue === undefined) setOwnValue('')\n          }}\n          placeholder={currentScope ? 'Ask about this' : 'Ask anything'}\n        />\n      </div>\n    </section>\n  )\n}\n\nexport type AiSidePanelProps = Omit<AiPanelProps, 'close' | 'className' | 'composerRef'> & {\n  /** Controlled when passed; leave it out to let the panel keep its own. */\n  open?: boolean\n  defaultOpen?: boolean\n  onOpenChange?: (open: boolean) => void\n  /** The element that opens the panel, usually a Button. */\n  trigger?: React.ReactElement\n  side?: 'left' | 'right'\n  className?: string\n}\n\n/** An AI assistant docked beside the page — a header with History and Close, a removable chip saying what it is looking at, a short thread, and the small composer, on one soft top-to-bottom AI wash. */\nexport function AiSidePanel({ open, defaultOpen = false, onOpenChange, trigger, side = 'right', title = 'Assistant', className, ...panel }: AiSidePanelProps) {\n  const [ownOpen, setOwnOpen] = React.useState(defaultOpen)\n  const isOpen = open === undefined ? ownOpen : open\n  const setOpen = (next: boolean) => {\n    if (open === undefined) setOwnOpen(next)\n    onOpenChange?.(next)\n  }\n  const composerRef = React.useRef<HTMLTextAreaElement>(null)\n  const sheetRef = React.useRef<HTMLDivElement>(null)\n  return (\n    <Sheet open={isOpen} onOpenChange={(next) => setOpen(next)}>\n      {trigger ? <SheetTrigger render={trigger} /> : null}\n      {/* The panel's header holds the one Close, so the Sheet's corner button is off. gap-0 and p-0 hand the whole\n          sheet to the panel, so its wash runs edge to edge. w-full replaces the stock three-quarter width, so on a\n          phone the panel takes the whole screen; from sm up the stock max-w-sm still caps it at the same 24rem.\n          People open the assistant to ask it something, so focus starts in the message box, not on the header's first\n          button. On a touch screen focus goes to the panel itself, as the Sheet does on its own: focusing a text box\n          there would throw the on-screen keyboard over half the panel before anything has been read. The Sheet only\n          knows a touch from its own trigger; opened by the app (the open prop) it reports nothing, so the device's\n          pointer decides instead. */}\n      <SheetContent ref={sheetRef} side={side} showCloseButton={false} aria-label={title}\n        initialFocus={(openedBy) => {\n          const onTouch = openedBy ? openedBy === 'touch' : onTouchScreen()\n          return onTouch ? sheetRef.current : composerRef.current\n        }}\n        className={cn('gap-0 p-0 data-[side=left]:w-full data-[side=right]:w-full', className)}>\n        <SheetElement.Provider value={sheetRef}>\n        <AiPanel\n          {...panel}\n          title={title}\n          composerRef={composerRef}\n          className=\"min-h-0 flex-1\"\n          close={(\n            <SheetClose render={<Button type=\"button\" variant=\"ghost\" size=\"icon-sm\" />}>\n              {closeIcon()}\n              <span className=\"sr-only\">Close</span>\n            </SheetClose>\n          )}\n        />\n        </SheetElement.Provider>\n      </SheetContent>\n    </Sheet>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/quill/ai-side-panel.tsx"
    }
  ],
  "meta": {
    "intent": [
      "ai"
    ],
    "use_when": "People are working on a page (a report, a record, a document) and should be able to ask the AI about it without leaving.",
    "not_for": "the conversation is the whole page, not a helper beside other work → ai-chat; the side panel holds an ordinary form or details, not an AI assistant → sheet; the AI suggests one edit to selected text and no conversation is needed → ai-popover"
  },
  "docs": "An AI assistant docked beside the page — a header with History and Close, a removable chip saying what it is looking at, a short thread, and the small composer, on one soft top-to-bottom AI wash. Do: Keep the \"Looking at\" chip so people know what the assistant can read, and let them remove it. Don't: Send the page to the AI without saying so, or pin a scope people cannot drop. Do: Let the one wash run from the top of the panel to the bottom, behind the header, the thread and the composer. Don't: Give the header its own gradient band or add a second wash — a band reads as a hard edge. Do: Wire History to your own list of past chats with onHistory; the conversation-history block is that list, and passing it as body shows it in the panel itself, in place of the thread, until you stop passing it (anything React draws nothing for shows the thread: undefined, null, true, false, an empty string; so open ? list : null and open && list both work). History only calls onHistory, and with it left out the button is not drawn. Don't: Ship a History button that does nothing, or put the list among the messages — it is not a turn of the conversation. Do: Use the small composer and the list layout for suggestions; the panel is narrow. Don't: Put the large composer or starter cards in the panel — they belong to the AI home page. Do: Pass your conversation as children and drive the composer with status, onStop and onSubmit. The conversation shown without children is sample content. For a conversation with nothing in it yet pass null, false or an empty list: unlike body, anything but undefined counts as passed here, and only undefined shows the sample. Don't: Ship the sample conversation, or edit the block to hard-code yours — the block is overwritten on update. Do: Keep the composer's gradient edge on the washed panel here. It is on purpose, even though the general rule puts the edge on page-background surfaces. Don't: Take it as a reason to put the edge on other tinted surfaces. Use ai-chat when the conversation is the whole page, not a helper beside other work. Use sheet when the side panel holds an ordinary form or details, not an AI assistant. Use ai-popover when the AI suggests one edit to selected text and no conversation is needed.",
  "categories": [
    "ai"
  ],
  "type": "registry:block"
}