{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-popover",
  "title": "AI popover",
  "description": "An AI suggestion beside the text it is about — what the AI did, the suggested text on a soft AI wash, then Discard, Try again and Replace.",
  "registryDependencies": [
    "button",
    "popover",
    "https://www.quilldesignsystem.com/r/ai-mark.json"
  ],
  "files": [
    {
      "path": "registry/lib/ai-popover.tsx",
      "content": "'use client'\n\nimport * as React from 'react'\nimport { Button } from '@/components/ui/button'\nimport { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@/components/ui/popover'\nimport { AiMark } from '@/components/ui/ai-mark'\nimport { cn } from '@/lib/utils'\n\n/** Anything that can say where it is on screen: a DOM Range, an element, or an object of your own with getBoundingClientRect. */\nexport type AiPopoverAnchor = { getBoundingClientRect: () => DOMRect }\n\nexport type AiPopoverProps = {\n  /** The text or control the suggestion is about: a <mark> around the selected text, or a Button. The popover opens from it and sits beside it. Optional once `anchor` is passed. */\n  children?: React.ReactElement\n  /** What the popover sits beside when there is no element to wrap: the selection in an editor (a Range), or for a <textarea> an object whose getBoundingClientRect returns the box you worked out. Nothing is pressed to open it, so drive `open` yourself. With `children` as well, children still opens it and `anchor` only says where it sits. Its box is asked for on every frame while the popover is open, to follow the text as it moves: keep getBoundingClientRect cheap. Render the popover just after the editor: Tab past its last button closes it and goes to the next Tab stop after where it is rendered. An anchor inside a scaled ancestor is followed at its size on screen. Not supported: a rotated, skewed or mirrored ancestor (the popover then sits near the anchor, not on it), and an anchor with no size inside a scaled ancestor (it is placed approximately). */\n  anchor?: AiPopoverAnchor | null\n  /** With `anchor`: where the cursor goes when the popover closes (the editor). Left out, it goes back to `children`, or to whatever had it when the popover opened. */\n  returnFocus?: React.RefObject<HTMLElement | null>\n  /** What the AI did: \"Rewrite: shorter\". */\n  title: string\n  /** The suggested text. Leave it out while the AI is still writing. */\n  suggestion?: React.ReactNode\n  /** The AI is writing: shows the shimmering label and switches off Replace, Insert below and Try again. */\n  working?: boolean\n  workingLabel?: string\n  /** Controlled when passed; leave it out to let the popover keep its own. */\n  open?: boolean\n  defaultOpen?: boolean\n  onOpenChange?: (open: boolean) => void\n  onReplace: () => void\n  replaceLabel?: string\n  /** Shows \"Insert below\". */\n  onInsertBelow?: () => void\n  /** Shows \"Try again\". */\n  onRetry?: () => void\n  /** Called when Discard is pressed (not on Escape or an outside press). */\n  onDiscard?: () => void\n  side?: 'top' | 'bottom' | 'left' | 'right'\n  align?: 'start' | 'center' | 'end'\n  className?: string\n}\n\n// '', whitespace, null and false are all \"no suggestion yet\".\nconst isShown = (node: React.ReactNode) =>\n  node !== undefined && node !== null && node !== false && !(typeof node === 'string' && node.trim() === '')\n\n// Mounts with the popover, so its \"just after mount\" is just after the popover opens. The region is in the popover\n// from its first paint, empty: a live region that arrives already filled is announced unreliably.\nfunction WritingStatus({ working, label }: { working: boolean; label: string }) {\n  const [announcing, setAnnouncing] = React.useState(false)\n  React.useEffect(() => {\n    const timer = window.setTimeout(() => setAnnouncing(true), 100)\n    return () => window.clearTimeout(timer)\n  }, [])\n  // \"Suggestion ready\" is only news if the person waited for it in this popover.\n  const [wasWorking, setWasWorking] = React.useState(working)\n  if (working && !wasWorking) setWasWorking(true)\n  return <div role=\"status\" className=\"sr-only\">{!announcing ? '' : working ? label : wasWorking ? 'Suggestion ready' : ''}</div>\n}\n\n// The first of these that is still on the page and can take the cursor.\nconst firstOnPage = (...candidates: Array<HTMLElement | null | undefined>) =>\n  candidates.find((element) => element && element.isConnected && element !== document.body) ?? null\n\ntype Box = { left: number; top: number; width: number; height: number }\nconst sameBox = (one: Box, other: Box) =>\n  Math.abs(one.left - other.left) < 0.05 && Math.abs(one.top - other.top) < 0.05 && Math.abs(one.width - other.width) < 0.05 && Math.abs(one.height - other.height) < 0.05\n\nconst write = (spot: HTMLElement, css: { x: number; y: number; width: number; height: number }) => {\n  spot.style.left = `${css.x}px`\n  spot.style.top = `${css.y}px`\n  spot.style.width = `${css.width}px`\n  spot.style.height = `${css.height}px`\n}\n\n// A stand-in that is still off its anchor after this many writes is not going to get there (two is the most a\n// supported case takes).\nconst MAX_WRITES = 6\n\n// What Tab can land on: links, enabled form controls and buttons, and anything given a place in the Tab order.\nconst TAB_STOPS = 'a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\"-1\"])'\n\n// Anchor mode. The stock PopoverContent places the popover beside its trigger and takes no other anchor, so the\n// selection gets a stand-in: an empty box kept exactly over it, which is the popover's trigger in name only. It takes\n// no presses (they reach the text underneath), is not a Tab stop and is hidden from screen readers.\nfunction AnchorSpot({ id, anchor, open, onFocus }: { id: string; anchor: AiPopoverAnchor; open: boolean; onFocus: () => void }) {\n  // Typed as the stock trigger types it; the element is the <span> below.\n  const ref = React.useRef<HTMLButtonElement>(null)\n  // What was last written to the stand-in, in its own CSS pixels, and how many screen pixels one of those is.\n  const written = React.useRef({ x: 0, y: 0, width: 0, height: 0, scaleX: 1, scaleY: 1 })\n  // The last box the anchor gave that was a real one: its numbers (an app may hand out one rect and write over it),\n  // and the anchor they came from (a new anchor that cannot be measured is not put at the old one's place: the\n  // stand-in simply stays where it last was).\n  const lastGood = React.useRef<{ from: AiPopoverAnchor; box: Box } | null>(null)\n  // The box last aimed at: how far off the stand-in was then, the scale that write went by, and how many writes it\n  // has had. And the box given up on. Correcting only goes on while it helps; where it cannot (see below) the\n  // stand-in is left alone until the anchor moves.\n  const aim = React.useRef<{ box: Box; miss: number; scaleX: number; scaleY: number; writes: number; best: { miss: number; x: number; y: number; width: number; height: number } } | null>(null)\n  const gaveUpOn = React.useRef<Box | null>(null)\n  const reported = React.useRef(false)\n  const place = React.useCallback(() => {\n    const spot = ref.current\n    if (!spot) return\n    // An app's own getBoundingClientRect can throw, and a Range whose text was redrawn reports an empty box at the\n    // window's corner. Neither is a place to go to: the last real box is kept.\n    if (lastGood.current?.from !== anchor) lastGood.current = null\n    try {\n      const box = anchor.getBoundingClientRect()\n      if (box.width !== 0 || box.height !== 0 || box.left !== 0 || box.top !== 0) {\n        lastGood.current = { from: anchor, box: { left: box.left, top: box.top, width: box.width, height: box.height } }\n      }\n    } catch (error) {\n      // Dev-only, once for each popover: in production the popover staying put is the right failure for an app's\n      // users, and saying nothing is the wrong one for its developers.\n      if (process.env.NODE_ENV !== 'production' && !reported.current) {\n        reported.current = true\n        console.error(\n          '[quill] <AiPopover anchor> threw from getBoundingClientRect, so the popover stays where it last was. ' +\n            'Return a box, or pass anchor={null} while there is nothing to sit beside.',\n          error\n        )\n      }\n    }\n    const want = lastGood.current?.box\n    if (!want) return\n    if (gaveUpOn.current && sameBox(gaveUpOn.current, want)) return\n    gaveUpOn.current = null\n    const css = written.current\n    // Twice at most: the first pass may only learn the scale (nothing had a size yet to measure it by).\n    for (let pass = 0; pass < 2; pass += 1) {\n      const landed = spot.getBoundingClientRect()\n      const off = [want.left - landed.left, want.top - landed.top, want.width - landed.width, want.height - landed.height]\n      const miss = Math.max(...off.map(Math.abs))\n      // Already there (the usual answer): nothing is written, so nothing is laid out again.\n      if (miss < 0.05) {\n        aim.current = null\n        return\n      }\n      // A fixed box is measured from the window, unless an ancestor is transformed: then from that ancestor, and in\n      // its pixels. Under scale(2) one CSS pixel is two on screen, so the miss (read in screen pixels) is divided by\n      // the scale before it is taken out, and so is the size. The scale is what the box measures over what was\n      // written.\n      if (css.width > 0 && landed.width > 0) css.scaleX = landed.width / css.width\n      if (css.height > 0 && landed.height > 0) css.scaleY = landed.height / css.height\n      // One axis with nothing to measure (a caret has no width) goes by the other.\n      const scaleX = css.width > 0 ? css.scaleX : css.scaleY\n      const scaleY = css.height > 0 ? css.scaleY : css.scaleX\n      // Aimed at this same box before. If the last write brought it no nearer and there is nothing new to go by (the\n      // same scale as then), or it has been written MAX_WRITES times and is still off, correcting is not working,\n      // and more of it would only keep the stand-in moving (or send it off the screen). It stays where it is. This\n      // is what happens inside a rotated, skewed or mirrored ancestor, where an upright box cannot be laid over the\n      // anchor, and for an anchor with no size inside a scaled one, where there is nothing to tell the scale by.\n      const before = aim.current && sameBox(aim.current.box, want) ? aim.current : null\n      const nothingNew = before !== null && Math.abs(before.scaleX - scaleX) < 0.001 && Math.abs(before.scaleY - scaleY) < 0.001\n      if (before && ((nothingNew && miss >= before.miss - 0.01) || before.writes >= MAX_WRITES)) {\n        // Left at the nearest it got, which may be where it started: a mirrored ancestor sends each correction the\n        // wrong way, and the last one written would be the farthest off.\n        if (before.best.miss < miss - 0.01) write(spot, Object.assign(css, { x: before.best.x, y: before.best.y, width: before.best.width, height: before.best.height }))\n        gaveUpOn.current = want\n        aim.current = null\n        return\n      }\n      const best = before && before.best.miss <= miss ? before.best : { miss, x: css.x, y: css.y, width: css.width, height: css.height }\n      const next = { x: css.x + off[0] / scaleX, y: css.y + off[1] / scaleY, width: want.width / scaleX, height: want.height / scaleY }\n      // Never a value that is not a number: what was written is forgotten, and the stand-in stays as it is.\n      if (!Object.values(next).every(Number.isFinite)) {\n        written.current = { x: 0, y: 0, width: 0, height: 0, scaleX: 1, scaleY: 1 }\n        gaveUpOn.current = want\n        aim.current = null\n        return\n      }\n      aim.current = { box: want, miss, scaleX, scaleY, writes: (before?.writes ?? 0) + 1, best }\n      write(spot, Object.assign(css, next))\n    }\n  }, [anchor])\n  // After every render while open (the anchor may be a new one), and before the popover works out its own place.\n  React.useLayoutEffect(() => {\n    if (open) place()\n  })\n  // Then on every frame while open. A selection moves when its box scrolls, when the window is resized and when the\n  // page around it changes height, and only the first two say so; asking each frame catches all three. The stock\n  // positioner notices the stand-in move and follows.\n  React.useEffect(() => {\n    if (!open) return\n    let frame = window.requestAnimationFrame(function follow() {\n      place()\n      frame = window.requestAnimationFrame(follow)\n    })\n    return () => window.cancelAnimationFrame(frame)\n  }, [open, place])\n  return <PopoverTrigger ref={ref} id={id} nativeButton={false} tabIndex={-1} aria-hidden onFocus={onFocus} render={<span data-slot=\"popover-anchor\" className=\"pointer-events-none fixed top-0 left-0\" />} />\n}\n\n/** An AI suggestion beside the text it is about — what the AI did, the suggested text on a soft AI wash, then Discard, Try again and Replace. */\nexport function AiPopover({\n  children, title, suggestion, working = false, workingLabel = 'Writing',\n  open, defaultOpen = false, onOpenChange, onReplace, replaceLabel = 'Replace',\n  onInsertBelow, onRetry, onDiscard, side = 'bottom', align = 'start', className, anchor, returnFocus,\n}: AiPopoverProps) {\n  const [ownOpen, setOwnOpen] = React.useState(defaultOpen)\n  // With neither a trigger nor an anchor there is nothing to sit beside, so nothing is shown.\n  const anchored = anchor !== undefined && anchor !== null\n  const isOpen = (open === undefined ? ownOpen : open) && (anchored || children !== undefined)\n  const setOpen = (next: boolean) => {\n    if (open === undefined) setOwnOpen(next)\n    onOpenChange?.(next)\n  }\n  const popupRef = React.useRef<HTMLDivElement>(null)\n  const ready = !working && isShown(suggestion)\n  // The middle of the popover scrolls when the suggestion is taller than the space left on screen. It holds nothing\n  // a keyboard can land on, so while it overflows (and only then) it is a Tab stop itself; some browsers do not make\n  // a scroller focusable on their own. The overflow is measured, and remembered against the element it was measured\n  // on, so a popover that opens again starts as \"fits\" instead of with the last one's answer.\n  const [scrollArea, setScrollArea] = React.useState<HTMLDivElement | null>(null)\n  const [overflowing, setOverflowing] = React.useState<HTMLDivElement | null>(null)\n  const scrolls = scrollArea !== null && overflowing === scrollArea\n  React.useEffect(() => {\n    if (!scrollArea || typeof ResizeObserver === 'undefined') return\n    // Fires once on observe, then whenever the area (the window changed) or what is in it (the suggestion changed) resizes.\n    const observer = new ResizeObserver(() => {\n      const overflows = scrollArea.scrollHeight > scrollArea.clientHeight\n      // The area is about to stop being focusable; keep a keyboard user inside the popover rather than on the page.\n      if (!overflows && document.activeElement === scrollArea) popupRef.current?.focus()\n      setOverflowing(overflows ? scrollArea : null)\n    })\n    observer.observe(scrollArea)\n    for (const child of Array.from(scrollArea.children)) observer.observe(child)\n    return () => observer.disconnect()\n    // working and ready swap the area's children, which have to be observed afresh.\n  }, [scrollArea, working, ready])\n  // A Button or a <button> is a native button. Highlighted text (a <mark>, a <span>) is not, and the trigger has to\n  // be told so it adds the button role, a Tab stop and Enter / Space.\n  const nativeButton = children === undefined || typeof children.type !== 'string' || children.type === 'button'\n  // Anchor mode: the stand-in is the trigger the popover is placed by, and must never end up holding the cursor.\n  // Closing sends the cursor to returnFocus, else to the trigger (children), else to what had it on opening.\n  const spotId = React.useId()\n  const popupId = React.useId()\n  const triggerRef = React.useRef<HTMLButtonElement>(null)\n  const opener = React.useRef<HTMLElement | null>(null)\n\n  return (\n    // triggerId says which trigger the popover is placed by: the stand-in while there is an anchor; null leaves it to\n    // the popover, which goes by the trigger that was pressed.\n    <Popover open={isOpen} triggerId={anchored ? spotId : null}\n      onOpenChange={(next, details) => {\n        // Placed by the stand-in, the popover takes a press on the real trigger while open as a request to move to\n        // it, not to close. A second press on the trigger closes, as it does without an anchor.\n        if (anchored && next && isOpen && details.reason === 'trigger-press') return setOpen(false)\n        setOpen(next)\n      }}>\n      {/* The stand-in is the trigger the popover belongs to, so the real one is told here what a trigger is told:\n          whether the popover is open and which it is. Tab from it, while open, goes in to the popover's first stop,\n          as it does from a trigger the popover is placed by. */}\n      {children ? (\n        // Highlighted text gets a Tab stop here, so it needs Quill's focus ring, not the browser's.\n        <PopoverTrigger render={children} nativeButton={nativeButton} className={nativeButton ? undefined : 'outline-hidden focus-visible:ring-3 focus-visible:ring-ring/50'} {...(anchored ? {\n          ref: triggerRef,\n          'aria-expanded': isOpen,\n          'aria-controls': isOpen ? popupId : undefined,\n          onKeyDown: (event: React.KeyboardEvent) => {\n            if (!isOpen || event.key !== 'Tab' || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return\n            const first = popupRef.current?.querySelector<HTMLElement>(TAB_STOPS)\n            if (!first) return\n            event.preventDefault()\n            first.focus()\n          },\n        } : undefined)} />\n      ) : null}\n      {/* Shift+Tab out of the popover's start goes to its trigger. Here that is the stand-in, so it passes the cursor\n          on: to the real trigger when there is one, as a wrapped anchor would have it; with no trigger there is\n          nothing to step back to, and the cursor stays in the popover, on the dialog. */}\n      {anchored ? <AnchorSpot id={spotId} anchor={anchor} open={isOpen} onFocus={() => (firstOnPage(triggerRef.current) ?? popupRef.current)?.focus()} /> : null}\n      {/* The wash is a background image over the popover's own fill, so the stock surface colour stays. Focus opens on\n          the dialog itself, not on Discard: someone holding Enter to open it would otherwise discard on the key repeat. */}\n      <PopoverContent ref={popupRef} side={side} align={align}\n        // With an anchor, what has the cursor as the popover opens is remembered, to hand it back on closing.\n        // Asked a second time with the cursor already inside (a double render), the first answer stands.\n        initialFocus={anchored ? () => {\n          const active = document.activeElement\n          if (!popupRef.current?.contains(active)) opener.current = active instanceof HTMLElement ? active : null\n          return popupRef.current\n        } : popupRef}\n        {...(anchored ? { id: popupId } : undefined)}\n        finalFocus={anchored ? () => firstOnPage(returnFocus?.current, triggerRef.current, opener.current) ?? false : undefined}\n        className={cn('ai-wash w-card max-w-[calc(100vw-2rem)] max-h-(--available-height) gap-0 overflow-hidden p-0 focus-visible:ring-3 focus-visible:ring-ring/50', className)}>\n        <div className=\"flex shrink-0 items-center gap-2 px-3.5 pt-3 pb-1\">\n          <AiMark size=\"icon-lg\" />\n          {/* A paragraph, not the default h2: headings take the serif display preset. */}\n          <PopoverTitle render={<p />} className=\"min-w-0 flex-1 text-sm font-semibold text-foreground\">{title}</PopoverTitle>\n        </div>\n        {/* The popup is capped to the space the positioner has left. The header and the buttons stay put; only this\n            middle part scrolls, so Replace is never pushed off a short screen. While it overflows it is a named Tab\n            stop, so the arrow and Page keys scroll it. Its ring is an outline drawn just inside it: the popover clips\n            anything outside, and an outline is painted over the text scrolling past. */}\n        <div ref={setScrollArea} data-focus-inset=\"\" {...(scrolls ? { tabIndex: 0, role: 'group', 'aria-label': 'Suggested text' } : {})}\n          className=\"grid min-h-0 grid-cols-[minmax(0,1fr)] gap-2.5 overflow-y-auto px-3.5 pt-1.5 focus-visible:outline-3 focus-visible:-outline-offset-3 focus-visible:outline-ring/50\">\n          <WritingStatus working={working} label={workingLabel} />\n          {working ? (\n            <div className=\"grid gap-1.5\">\n              <span aria-hidden data-slot=\"writing-label\" className=\"ai-shimmer w-fit text-sm font-semibold\">{workingLabel}</span>\n              <span aria-hidden className=\"ai-line\" />\n            </div>\n          ) : ready ? (\n            // The divider line, not the control line: the tile is read-only content, told apart from the popover by\n            // its fill. The control line is kept for things people press or type in.\n            <div data-slot=\"suggestion\" className=\"rounded-lg border border-border bg-background px-3 py-2 text-sm leading-reading [overflow-wrap:anywhere] text-foreground\">{suggestion}</div>\n          ) : null}\n        </div>\n        <div className=\"flex shrink-0 flex-wrap items-center gap-1.5 px-3.5 pt-2.5 pb-3.5\">\n          <Button type=\"button\" variant=\"ghost\" onClick={() => { onDiscard?.(); setOpen(false) }}>Discard</Button>\n          <span className=\"flex-1\" />\n          {/* Pressing Try again disables it while the AI writes, and the suggestion is swapped for the shimmer; focus\n              moves to the dialog first so it never falls to the page. */}\n          {onRetry ? <Button type=\"button\" variant=\"outline\" disabled={working} onClick={() => { popupRef.current?.focus(); onRetry() }}>Try again</Button> : null}\n          {onInsertBelow ? <Button type=\"button\" variant=\"outline\" disabled={!ready} onClick={() => { onInsertBelow(); setOpen(false) }}>Insert below</Button> : null}\n          {/* Plain solid ink: accepting an AI suggestion is an ordinary decision. */}\n          <Button type=\"button\" disabled={!ready} onClick={() => { onReplace(); setOpen(false) }}>{replaceLabel}</Button>\n        </div>\n      </PopoverContent>\n    </Popover>\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/ui/ai-popover.tsx"
    }
  ],
  "docs": "An AI suggestion beside the text it is about — what the AI did, the suggested text on a soft AI wash, then Discard, Try again and Replace. Do: Leave Replace as the plain solid button; the wash and the mark already say this came from AI. Don't: Put the AI gradient on Replace or on the suggested text — accepting has to feel like any other decision. Do: Wrap the selected text as the popover's anchor so it stays highlighted underneath for comparison. In a text box or an editor, where the selection cannot be wrapped, pass it as anchor instead and leave the text as it is. Don't: Cover or remove the original before the person has chosen. Do: Title the popover with the action and its flavour: \"Rewrite: shorter\". Don't: Title it \"AI\" or \"Suggestion\" — people should know what was asked without remembering it. Do: Leave the suggestion tile on the soft divider line (border-border). It is read-only content, told apart from the popover by its fill. Don't: Outline it with the control line (border-input) — that line marks things people press or type in. Use popover when the overlay holds an ordinary form or filter, not an AI suggestion. Use ai-message when the AI answers in a conversation rather than suggesting an edit to text on the page.",
  "type": "registry:ui"
}