{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"ai-editor","type":"registry:ui","title":"AI Editor","description":"A document an agent edits alongside you.","dependencies":["@base-ui/react","motion"],"registryDependencies":["@kobra/orb","@kobra/streaming-text","@kobra/text-shimmer"],"docs":"Sound: the data-slot attributes on this component are read by the Sound layer, installed separately with `npx shadcn@latest add @kobra/sound`.\nKeep the data-slot and data-sound attributes as written — they are the wiring, not decoration.\nWrap your app once in <SoundEffects> from components/ui/sound.tsx and every Kobra component answers a press.","files":[{"path":"components/ui/ai-editor.tsx","content":"'use client'\n\nimport { useDirection } from '@base-ui/react/direction-provider'\nimport { IconPlaceholder } from '@/components/icon-placeholder'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { AnimatePresence, motion, useReducedMotion } from 'motion/react'\n\nimport { Orb, type OrbVariant } from '@/components/ui/orb'\nimport { StreamingText } from '@/components/ui/streaming-text'\nimport { TextShimmer } from '@/components/ui/text-shimmer'\nimport { cn } from '@/lib/utils'\n\nconst EASE = [0.16, 1, 0.3, 1] as const\n\nconst EXIT = { duration: 0.15, ease: [0.4, 0, 0.2, 1] } as const\n\nconst SETTLE = 250\n\nexport type Format = 'bold' | 'italic' | 'underline' | 'strikethrough' | 'code'\n\nconst FORMATS = [\n  { name: 'Bold', format: 'bold', icon: BoldGlyph },\n  { name: 'Italic', format: 'italic', icon: ItalicGlyph },\n  { name: 'Underline', format: 'underline', icon: UnderlineGlyph },\n  { name: 'Strikethrough', format: 'strikethrough', icon: StrikethroughGlyph },\n  { name: 'Code', format: 'code', icon: CodeGlyph },\n] as const satisfies ReadonlyArray<{ name: string; format: Format; icon: unknown }>\n\nconst ARRIVE_MS: Record<Format, number> = {\n  bold: 220,\n  italic: 220,\n  underline: 260,\n  strikethrough: 260,\n  code: 220,\n}\nconst LEAVE_MS: Record<Format, number> = {\n  bold: 160,\n  italic: 160,\n  underline: 180,\n  strikethrough: 180,\n  code: 160,\n}\n\nconst SHORTCUTS: Partial<Record<string, Format>> = { b: 'bold', i: 'italic', u: 'underline' }\n\nexport function formatForKey(event: {\n  key: string\n  metaKey: boolean\n  ctrlKey: boolean\n  altKey: boolean\n  shiftKey: boolean\n}) {\n  if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return null\n  return SHORTCUTS[event.key.toLowerCase()] ?? null\n}\n\nconst reducedMotion = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches\n\nconst rewrites = new WeakMap<Element, number>()\n\nfunction offsetsOf(root: HTMLElement) {\n  const selection = window.getSelection()\n  if (!selection?.rangeCount) return null\n  const range = selection.getRangeAt(0)\n  if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return null\n  const from = (container: Node, offset: number) => {\n    const span = document.createRange()\n    span.setStart(root, 0)\n    span.setEnd(container, offset)\n    return span.toString().length\n  }\n  return {\n    start: from(range.startContainer, range.startOffset),\n    end: from(range.endContainer, range.endOffset),\n  }\n}\n\nfunction restore(root: HTMLElement, offsets: { start: number; end: number } | null) {\n  if (!offsets) return\n  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)\n  const range = document.createRange()\n  let seen = 0\n  let started = false\n  for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n    const length = (node as Text).length\n    if (!started && offsets.start <= seen + length) {\n      range.setStart(node, offsets.start - seen)\n      started = true\n    }\n    if (started && offsets.end <= seen + length) {\n      range.setEnd(node, offsets.end - seen)\n      const selection = window.getSelection()\n      selection?.removeAllRanges()\n      selection?.addRange(range)\n      return\n    }\n    seen += length\n  }\n}\n\nfunction keepSelection(root: HTMLElement, rebuild: () => void) {\n  const offsets = offsetsOf(root)\n  rebuild()\n  rewrites.set(root, performance.now())\n  restore(root, offsets)\n}\n\nfunction markOf(node: Node, format: Format, root: HTMLElement) {\n  const mark = node.parentElement?.closest<HTMLElement>(\n    `.editor-mark[data-format=\"${format}\"]:not([data-leaving])`,\n  )\n  return mark && root.contains(mark) ? mark : null\n}\n\nfunction splitText(range: Range, root: HTMLElement) {\n  const { startContainer: start, startOffset, endContainer: end, endOffset } = range\n  if (end instanceof Text && endOffset < end.length) end.splitText(endOffset)\n  if (start instanceof Text && startOffset > 0 && startOffset < start.length) {\n    const tail = start.splitText(startOffset)\n    range.setStart(tail, 0)\n    if (end === start) range.setEnd(tail, tail.length)\n  }\n  return textWithin(range, root)\n}\n\nfunction textWithin(range: Range, root: HTMLElement, partly = false) {\n  const nodes: Text[] = []\n  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)\n  for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n    const text = node as Text\n\n    if (!text.length || text.parentElement?.closest('[contenteditable=\"false\"]')) continue\n\n    const inside = partly\n      ? range.intersectsNode(text) &&\n        !(range.startContainer === text && range.startOffset === text.length) &&\n        !(range.endContainer === text && range.endOffset === 0)\n      : range.comparePoint(text, 0) === 0 && range.comparePoint(text, text.length) === 0\n    if (inside) nodes.push(text)\n  }\n  return nodes\n}\n\nexport function formatsOf(range: Range, root: HTMLElement) {\n  const nodes = textWithin(range, root, true)\n  return new Set(\n    FORMATS.map(({ format }) => format).filter(\n      (format) => nodes.length > 0 && nodes.every((node) => markOf(node, format, root)),\n    ),\n  )\n}\n\nfunction unwrap(element: Element) {\n  const parent = element.parentNode\n  if (!parent) return\n  while (element.firstChild) parent.insertBefore(element.firstChild, element)\n  parent.removeChild(element)\n}\n\nfunction textsIn(element: Element) {\n  const texts: Text[] = []\n  const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT)\n  for (let node = walker.nextNode(); node; node = walker.nextNode())\n    if ((node as Text).length) texts.push(node as Text)\n  return texts\n}\n\nfunction markRuns(nodes: Text[], format: Format) {\n  const covered = new Set<Node>(nodes)\n  const units: Node[] = []\n  for (const node of nodes) {\n    let unit: Node = node\n    for (\n      let parent = unit.parentElement;\n      parent?.matches('.editor-mark, .editor-word') &&\n      textsIn(parent).every((text) => covered.has(text));\n      parent = unit.parentElement\n    )\n      unit = parent\n    if (units.at(-1) !== unit) units.push(unit)\n  }\n  const marks: HTMLElement[] = []\n  let run: Node[] = []\n  const close = () => {\n    const first = run[0]\n    if (!first) return\n    const mark = document.createElement('span')\n    mark.className = 'editor-mark'\n    mark.dataset.format = format\n    first.parentNode?.insertBefore(mark, first)\n    for (const unit of run) mark.appendChild(unit)\n    marks.push(mark)\n    run = []\n  }\n  for (const unit of units) {\n    if (run.length && run.at(-1)?.nextSibling !== unit) close()\n    run.push(unit)\n  }\n  close()\n  return marks\n}\n\nfunction isolate(mark: HTMLElement, first: Node, last: Node) {\n  const head = document.createRange()\n  head.setStart(mark, 0)\n  head.setEndBefore(first)\n  if (!head.collapsed) {\n    const piece = mark.cloneNode(false) as HTMLElement\n    piece.appendChild(head.extractContents())\n    if (piece.textContent) mark.parentNode?.insertBefore(piece, mark)\n  }\n  const tail = document.createRange()\n  tail.setStartAfter(last)\n  tail.setEnd(mark, mark.childNodes.length)\n  if (!tail.collapsed) {\n    const piece = mark.cloneNode(false) as HTMLElement\n    piece.appendChild(tail.extractContents())\n    if (piece.textContent) mark.parentNode?.insertBefore(piece, mark.nextSibling)\n  }\n}\n\nfunction slantWords(mark: HTMLElement) {\n  const walker = document.createTreeWalker(mark, NodeFilter.SHOW_TEXT)\n  const texts: Text[] = []\n  for (let node = walker.nextNode(); node; node = walker.nextNode()) texts.push(node as Text)\n  for (const text of texts) {\n    const parts = text.data.split(/(\\s+)/).filter(Boolean)\n    if (parts.length === 1 && /\\s/.test(parts[0] ?? '')) continue\n    const fragment = document.createDocumentFragment()\n    for (const part of parts) {\n      if (/^\\s+$/.test(part)) {\n        fragment.appendChild(document.createTextNode(part))\n        continue\n      }\n      const word = document.createElement('span')\n      word.className = 'editor-word'\n      word.textContent = part\n      fragment.appendChild(word)\n    }\n    text.parentNode?.replaceChild(fragment, text)\n  }\n}\n\nfunction unslantWords(mark: HTMLElement) {\n  for (const word of mark.querySelectorAll('.editor-word')) unwrap(word)\n  mark.normalize()\n}\n\nfunction boldSpacing(mark: HTMLElement) {\n  const text = mark.textContent ?? ''\n  if (!text.length) return 0\n  const probe = document.createElement('span')\n  probe.textContent = text\n  probe.style.cssText = 'position:absolute;visibility:hidden;white-space:pre;font-weight:400'\n  mark.parentNode?.insertBefore(probe, mark.nextSibling)\n  const regular = probe.getBoundingClientRect().width\n  probe.style.fontWeight = '700'\n  const bold = probe.getBoundingClientRect().width\n  probe.parentNode?.removeChild(probe)\n  return (bold - regular) / text.length\n}\n\nfunction drawInTurn(marks: HTMLElement[], format: Format) {\n  if (marks.length < 2 || (format !== 'underline' && format !== 'strikethrough')) return\n  const widths = marks.map((mark) =>\n    [...mark.getClientRects()].reduce((sum, box) => sum + box.width, 0),\n  )\n  const total = widths.reduce((sum, width) => sum + width, 0) || 1\n  let before = 0\n  marks.forEach((mark, index) => {\n    const width = widths[index] ?? 0\n    mark.style.transitionDelay = `${String((ARRIVE_MS[format] * before) / total)}ms`\n    mark.style.transitionDuration = `${String((ARRIVE_MS[format] * width) / total)}ms`\n    mark.style.transitionTimingFunction = 'linear'\n    before += width\n  })\n}\n\nfunction instantly(mark: HTMLElement, instant: boolean) {\n  if (!instant) return\n  mark.dataset.instant = ''\n  window.requestAnimationFrame(() => delete mark.dataset.instant)\n}\n\nfunction inFrame(mark: HTMLElement, ms: number, change: () => void) {\n  if (ms) {\n    window.requestAnimationFrame(() => window.requestAnimationFrame(change))\n    return\n  }\n  change()\n  void mark.offsetWidth\n}\n\nfunction arrive(mark: HTMLElement, format: Format, instant: boolean) {\n  const ms = reducedMotion() || instant ? 0 : ARRIVE_MS[format]\n  instantly(mark, instant)\n  if (format === 'bold')\n    mark.style.setProperty('--editor-bold-spacing', `${String(boldSpacing(mark))}px`)\n  if (format === 'italic') slantWords(mark)\n  void mark.offsetWidth\n  inFrame(mark, ms, () => {\n    mark.dataset.on = ''\n    if (format === 'code') blurSwap(mark, ms, true)\n    window.setTimeout(() => {\n      mark.style.removeProperty('transition-delay')\n      mark.style.removeProperty('transition-duration')\n      mark.style.removeProperty('transition-timing-function')\n    }, ms + 50)\n  })\n}\n\nfunction leave(mark: HTMLElement, format: Format, root: HTMLElement, instant: boolean) {\n  const ms = reducedMotion() || instant ? 0 : LEAVE_MS[format]\n  instantly(mark, instant)\n  mark.dataset.leaving = ''\n  void mark.offsetWidth\n  inFrame(mark, ms, () => {\n    delete mark.dataset.on\n    if (format === 'code') blurSwap(mark, ms, false)\n    window.setTimeout(() => {\n      if (!mark.isConnected) return\n      keepSelection(root, () => {\n        if (format === 'italic') unslantWords(mark)\n        const parent = mark.parentNode\n        unwrap(mark)\n        parent?.normalize()\n      })\n    }, ms + 50)\n  })\n}\n\nfunction blurSwap(mark: HTMLElement, ms: number, mono: boolean) {\n  if (!ms) {\n    if (mono) mark.dataset.mono = ''\n    else delete mark.dataset.mono\n    return\n  }\n  mark.animate(\n    { filter: ['blur(0px)', 'blur(2px)', 'blur(0px)'], opacity: [1, 0.55, 1] },\n    { duration: ms, easing: 'ease-in-out' },\n  )\n  window.setTimeout(() => {\n    if (mono) mark.dataset.mono = ''\n    else delete mark.dataset.mono\n  }, ms / 2)\n}\n\nconst SWAP =\n  'transition-[opacity,filter,translate] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none'\n\nconst OUT = `${SWAP} group-data-ask:pointer-events-none group-data-ask:-translate-x-2 rtl:group-data-ask:translate-x-2 group-data-ask:opacity-0 group-data-ask:blur-[2px]`\n\nconst IN = `pointer-events-none translate-x-2 rtl:-translate-x-2 opacity-0 blur-[2px] delay-100 ${SWAP} group-data-ask:pointer-events-auto group-data-ask:translate-x-0 group-data-ask:opacity-100 group-data-ask:blur-none group-data-sent:pointer-events-none group-data-sent:-translate-x-2 rtl:group-data-sent:translate-x-2 group-data-sent:opacity-0 group-data-sent:blur-[2px] group-data-sent:delay-0`\n\nconst SENT = `pointer-events-none translate-x-2 rtl:-translate-x-2 opacity-0 blur-[2px] delay-100 ${SWAP} group-data-sent:translate-x-0 group-data-sent:opacity-100 group-data-sent:blur-none`\n\nconst SOURCES = ['wikipedia.org', 'reddit.com', 'chatgpt.com']\n\nconst STAGES = {\n  understanding: { label: 'Understanding the context…', orb: 'S3' },\n  gathering: { label: 'Gathering sources…', orb: 'S2' },\n} as const satisfies Record<string, { label: string; orb: OrbVariant }>\n\nconst ANSWER_WORD_MS = 28\n\nexport function formatSelection(root: HTMLElement, format: Format, instant = false) {\n  const selection = window.getSelection()\n  if (!selection?.rangeCount || selection.isCollapsed) return null\n  const range = selection.getRangeAt(0)\n  if (!root.contains(range.commonAncestorContainer)) return null\n  const offsets = offsetsOf(root)\n\n  const nodes = splitText(range, root)\n  const first = nodes[0]\n  const last = nodes.at(-1)\n  if (!first || !last) return null\n  if (nodes.every((node) => markOf(node, format, root))) {\n    const owners = new Map<HTMLElement, Text[]>()\n    for (const node of nodes) {\n      const mark = markOf(node, format, root)\n      if (mark) owners.set(mark, [...(owners.get(mark) ?? []), node])\n    }\n    for (const [mark, inside] of owners) {\n      isolate(mark, inside[0] ?? first, inside.at(-1) ?? last)\n      leave(mark, format, root, instant)\n    }\n  } else {\n    const marks = markRuns(\n      nodes.filter((node) => !markOf(node, format, root)),\n      format,\n    )\n    if (!instant) drawInTurn(marks, format)\n    for (const mark of marks) arrive(mark, format, instant)\n  }\n\n  rewrites.set(root, performance.now())\n  restore(root, offsets)\n  return selection.rangeCount ? formatsOf(selection.getRangeAt(0), root) : null\n}\n\nexport function Editor({\n  title,\n  children,\n  answer,\n  className,\n}: {\n\n  title?: string\n  children: string\n  answer: string\n  className?: string\n}) {\n  const wrap = useRef<HTMLDivElement>(null)\n  const prose = useRef<HTMLDivElement>(null)\n  const dragging = useRef(false)\n\n  const asking = useRef(false)\n\n  const [at, setAt] = useState<{ x: number; y: number } | null>(null)\n  const [askMode, setAskMode] = useState(false)\n  const [formats, setFormats] = useState<ReadonlySet<Format>>(new Set())\n\n  const applyFormat = useCallback((format: Format, instant = false) => {\n    const root = prose.current\n    const next = root ? formatSelection(root, format, instant) : null\n    if (next) setFormats(next)\n  }, [])\n\n  const enterAskMode = useCallback(() => {\n\n    const selection = window.getSelection()\n    if (selection && !selection.isCollapsed && 'highlights' in CSS) {\n      CSS.highlights.set('editor-ask', new Highlight(selection.getRangeAt(0).cloneRange()))\n    }\n    asking.current = true\n    setAskMode(true)\n  }, [])\n\n  useEffect(() => {\n    let timer = 0\n\n    const show = () => {\n      const selection = window.getSelection()\n      const proseEl = prose.current\n      const wrapEl = wrap.current\n      if (\n        !selection ||\n        selection.isCollapsed ||\n        !proseEl ||\n        !wrapEl ||\n        !proseEl.contains(selection.anchorNode) ||\n        !proseEl.contains(selection.focusNode)\n      ) {\n        setAt(null)\n        return\n      }\n      const box = selection.getRangeAt(0).getBoundingClientRect()\n      const origin = wrapEl.getBoundingClientRect()\n      setAt({ x: box.left + box.width / 2 - origin.left, y: box.top - origin.top })\n      setFormats(formatsOf(selection.getRangeAt(0), proseEl))\n    }\n\n    const onSelectionChange = () => {\n      const proseEl = prose.current\n      if (asking.current || (proseEl && performance.now() - (rewrites.get(proseEl) ?? 0) < 100))\n        return\n      window.clearTimeout(timer)\n      setAt(null)\n      if (!dragging.current) timer = window.setTimeout(show, SETTLE)\n    }\n\n    const onPointerDown = (event: PointerEvent) => {\n      if ((event.target as Element).closest('[data-editor-toolbar]')) return\n      if ('highlights' in CSS) CSS.highlights.delete('editor-ask')\n      asking.current = false\n      setAskMode(false)\n      dragging.current = true\n      window.clearTimeout(timer)\n      setAt(null)\n    }\n\n    const onPointerUp = (event: PointerEvent) => {\n\n      if (asking.current || (event.target as Element).closest('[data-editor-toolbar]')) return\n      dragging.current = false\n      show()\n    }\n\n    document.addEventListener('selectionchange', onSelectionChange)\n    document.addEventListener('pointerdown', onPointerDown)\n    document.addEventListener('pointerup', onPointerUp)\n\n    document.addEventListener('pointercancel', onPointerUp)\n    return () => {\n      window.clearTimeout(timer)\n      document.removeEventListener('selectionchange', onSelectionChange)\n      document.removeEventListener('pointerdown', onPointerDown)\n      document.removeEventListener('pointerup', onPointerUp)\n      document.removeEventListener('pointercancel', onPointerUp)\n    }\n  }, [])\n\n  return (\n    <div ref={wrap} className={cn('relative', className)}>\n\n      <div\n        ref={prose}\n        contentEditable\n        suppressContentEditableWarning\n        spellCheck={false}\n        role=\"textbox\"\n        aria-multiline=\"true\"\n        aria-label={title ?? 'Document'}\n\n        dir=\"auto\"\n\n        onKeyDown={(event) => {\n          if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return\n          const format = SHORTCUTS[event.key.toLowerCase()]\n          if (!format) return\n          event.preventDefault()\n          applyFormat(format, true)\n        }}\n        className=\"outline-none\"\n      >\n        {title ? <h3 className=\"text-2xl font-semibold tracking-tight\">{title}</h3> : null}\n\n        <p className={cn('text-sm leading-relaxed text-muted-foreground', title && 'mt-4')}>\n          {children}\n        </p>\n      </div>\n\n      <AnimatePresence>\n        {at && (\n          <motion.div\n            key=\"toolbar\"\n            className=\"absolute z-50\"\n            style={{ left: at.x, top: at.y }}\n            initial={{ opacity: 0, scale: 0.96, y: 6, filter: 'blur(4px)' }}\n            animate={{ opacity: 1, scale: 1, y: 0, filter: 'blur(0px)' }}\n            exit={{ opacity: 0, scale: 0.99, y: 2, transition: EXIT }}\n            transition={{ duration: 0.25, ease: EASE }}\n          >\n\n            <div className=\"absolute bottom-1.5 left-0 -translate-x-1/2\">\n              <SelectionToolbar\n                askMode={askMode}\n                answer={answer}\n                onAsk={enterAskMode}\n                formats={formats}\n                onFormat={(format) => applyFormat(format)}\n              />\n            </div>\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </div>\n  )\n}\n\nexport function SelectionToolbar({\n  askMode,\n  answer = '',\n  sources = SOURCES,\n  onAsk,\n  formats,\n  onFormat,\n}: {\n  askMode: boolean\n  answer?: string\n\n  sources?: readonly string[]\n  onAsk: () => void\n\n  formats: ReadonlySet<Format>\n  onFormat: (format: Format) => void\n}) {\n  const input = useRef<HTMLInputElement>(null)\n  const panel = useRef<HTMLDivElement>(null)\n  const reduceMotion = useReducedMotion() ?? false\n  const side = useDirection() === 'rtl' ? -1 : 1\n\n  const [query, setQuery] = useState<string | null>(null)\n  const [stage, setStage] = useState<keyof typeof STAGES>('understanding')\n  const [answering, setAnswering] = useState(false)\n  const [shown, setShown] = useState(0)\n  const [height, setHeight] = useState(0)\n\n  const words = answer.split(' ')\n\n  useEffect(() => {\n    const element = panel.current\n    if (!element) return\n    const observer = new ResizeObserver(() => setHeight(element.offsetHeight))\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [])\n\n  useEffect(() => {\n    if (!query) return\n    const found = window.setTimeout(() => setStage('gathering'), 2000)\n    const reply = window.setTimeout(() => setAnswering(true), 4200)\n    return () => {\n      window.clearTimeout(found)\n      window.clearTimeout(reply)\n    }\n  }, [query])\n\n  useEffect(() => {\n    if (!answering || shown >= words.length) return\n    const timer = window.setTimeout(() => setShown((count) => count + 1), ANSWER_WORD_MS)\n    return () => window.clearTimeout(timer)\n  }, [answering, shown, words.length])\n\n  const submit = () => {\n    const value = input.current?.value.trim()\n    if (!value || query) return\n    setQuery(value)\n    input.current?.blur()\n  }\n\n  return (\n    <div\n      role=\"toolbar\"\n      aria-label=\"Selection\"\n      data-editor-toolbar\n      data-ask={askMode ? '' : undefined}\n      data-sent={query ? '' : undefined}\n\n      onMouseDown={(event) => {\n        if ((event.target as HTMLElement).tagName !== 'INPUT') event.preventDefault()\n      }}\n      className=\"group flex origin-bottom scale-90 flex-col overflow-hidden rounded-[22px] border border-border bg-popover whitespace-nowrap text-muted-foreground shadow-lg\"\n    >\n      <div className=\"relative flex items-center gap-1 p-1.5\">\n        <button\n          type=\"button\"\n          onClick={() => {\n            if (askMode) return\n\n            onAsk()\n            input.current?.focus({ preventScroll: true })\n          }}\n          className=\"flex h-8 shrink-0 items-center gap-1.5 rounded-full ps-1.5 pe-2.5 text-sm font-medium text-foreground hover:bg-accent group-data-ask:hover:bg-transparent\"\n        >\n          <span data-stirring={askMode || undefined} className=\"editor-orb size-5 shrink-0\" />\n          <span className={OUT}>Ask AI</span>\n        </button>\n\n        <div className={cn('mx-1 h-5 w-px shrink-0 bg-border', OUT)} />\n\n        {FORMATS.map(({ name, format, icon: Icon }) => (\n          <button\n            key={name}\n            type=\"button\"\n            aria-label={name}\n            aria-pressed={formats.has(format)}\n            onClick={() => onFormat(format)}\n            className={cn(\n              'flex size-8 shrink-0 items-center justify-center rounded-full hover:bg-accent aria-pressed:bg-accent aria-pressed:text-foreground',\n              OUT,\n            )}\n          >\n            <Icon className=\"size-[1.125rem]\" stroke={1.8} />\n          </button>\n        ))}\n\n        <div className={cn('absolute inset-y-1.5 start-10 end-1.5 flex items-center gap-1', IN)}>\n          <input\n            ref={input}\n            type=\"text\"\n            dir=\"auto\"\n            aria-label=\"Ask about the selection\"\n            placeholder=\"Ask anything…\"\n            onKeyDown={(event) => event.key === 'Enter' && submit()}\n            className=\"h-8 min-w-0 flex-1 bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground\"\n          />\n          <button\n            type=\"button\"\n            aria-label=\"Send\"\n            onClick={submit}\n            className=\"flex size-8 shrink-0 items-center justify-center rounded-full bg-foreground text-background\"\n          >\n            <IconPlaceholder tabler=\"IconArrowRight\" lucide=\"ArrowRight\" hugeicons=\"ArrowRight01Icon\" phosphor=\"ArrowRightIcon\" remixicon=\"RiArrowRightLine\" className=\"size-4 rtl:-scale-x-100\" />\n          </button>\n        </div>\n\n        <div\n          className={cn(\n            'absolute inset-y-1.5 start-10 end-3 flex items-center overflow-hidden text-sm font-medium text-foreground',\n            SENT,\n          )}\n        >\n          <span dir=\"auto\" className=\"truncate\">\n            {query}\n          </span>\n        </div>\n      </div>\n\n      <motion.div\n        initial={{ height: 0 }}\n        animate={{ height }}\n        transition={reduceMotion ? { duration: 0 } : { duration: 0.3, ease: EASE }}\n        className=\"overflow-hidden\"\n      >\n        <div ref={panel} className=\"relative\">\n          <AnimatePresence mode=\"popLayout\">\n            {query && !answering && (\n              <motion.div\n                key=\"loading\"\n                initial={{ opacity: 0, y: 4, filter: 'blur(2px)' }}\n                animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }}\n                exit={{ opacity: 0, y: -4, filter: 'blur(4px)' }}\n                transition={{ duration: 0.25, ease: EASE }}\n\n                className=\"flex items-center gap-1 border-t border-border bg-muted/50 px-3 py-2.5\"\n              >\n                <Orb\n                  key={STAGES[stage].orb}\n                  variant={STAGES[stage].orb}\n                  label={STAGES[stage].label}\n                  className=\"shrink-0 text-muted-foreground\"\n                />\n\n                <AnimatePresence mode=\"wait\" initial={false}>\n                  <motion.span\n                    key={stage}\n                    initial={{ opacity: 0, y: 6, filter: 'blur(2px)' }}\n                    animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }}\n                    exit={{ opacity: 0, y: -6, filter: 'blur(2px)' }}\n                    transition={{ duration: 0.15, ease: EASE }}\n                    className=\"inline-block text-sm\"\n                  >\n                    <TextShimmer duration={1.5}>{STAGES[stage].label}</TextShimmer>\n                  </motion.span>\n                </AnimatePresence>\n\n                <div className=\"ms-auto flex items-center ps-2\">\n                  {stage === 'gathering' &&\n                    sources.map((domain, index) => (\n                      <motion.img\n                        key={domain}\n                        src={`https://www.google.com/s2/favicons?domain=${domain}&sz=64`}\n                        alt={domain}\n\n                        initial={{ opacity: 0, x: 10 * side, scale: 0.4 }}\n                        animate={{ opacity: 1, x: 0, scale: 1 }}\n                        transition={{ delay: index * 0.08, duration: 0.35, ease: EASE }}\n                        className=\"-ms-2 size-5 rounded-full bg-background ring-2 ring-popover first:ms-0\"\n                      />\n                    ))}\n                </div>\n              </motion.div>\n            )}\n\n            {answering && (\n              <motion.div\n                key=\"answer\"\n                initial={{ opacity: 0 }}\n                animate={{ opacity: 1 }}\n                transition={{ duration: 0.2, ease: EASE }}\n\n                className=\"min-h-[41px] border-t border-border bg-muted/50 px-3.5 py-3\"\n              >\n                <p\n                  dir=\"auto\"\n                  className=\"max-w-xs text-[15px] leading-relaxed whitespace-normal text-foreground\"\n                >\n                  <StreamingText>{words.slice(0, shown).join(' ')}</StreamingText>\n                </p>\n              </motion.div>\n            )}\n          </AnimatePresence>\n        </div>\n      </motion.div>\n    </div>\n  )\n}\n\ntype PlaceholderGlyphProps = Omit<\n  import('react').ComponentPropsWithoutRef<'svg'>,\n  'stroke' | 'strokeWidth' | 'children'\n> & {\n  stroke?: number\n  size?: number\n}\n\nfunction BoldGlyph({ stroke = 2, ...props }: PlaceholderGlyphProps) {\n  return <IconPlaceholder tabler=\"IconBold\" lucide=\"Bold\" hugeicons=\"TextBoldIcon\" phosphor=\"TextBIcon\" remixicon=\"RiBold\" strokeWidth={stroke} {...props} />\n}\n\nfunction CodeGlyph({ stroke = 2, ...props }: PlaceholderGlyphProps) {\n  return <IconPlaceholder tabler=\"IconCode\" lucide=\"CodeIcon\" hugeicons=\"CodeIcon\" phosphor=\"CodeIcon\" remixicon=\"RiCodeLine\" strokeWidth={stroke} {...props} />\n}\n\nfunction ItalicGlyph({ stroke = 2, ...props }: PlaceholderGlyphProps) {\n  return <IconPlaceholder tabler=\"IconItalic\" lucide=\"Italic\" hugeicons=\"TextItalicIcon\" phosphor=\"TextItalicIcon\" remixicon=\"RiItalic\" strokeWidth={stroke} {...props} />\n}\n\nfunction StrikethroughGlyph({ stroke = 2, ...props }: PlaceholderGlyphProps) {\n  return <IconPlaceholder tabler=\"IconStrikethrough\" lucide=\"Strikethrough\" hugeicons=\"TextStrikethroughIcon\" phosphor=\"TextStrikethroughIcon\" remixicon=\"RiStrikethrough\" strokeWidth={stroke} {...props} />\n}\n\nfunction UnderlineGlyph({ stroke = 2, ...props }: PlaceholderGlyphProps) {\n  return <IconPlaceholder tabler=\"IconUnderline\" lucide=\"Underline\" hugeicons=\"TextUnderlineIcon\" phosphor=\"TextUnderlineIcon\" remixicon=\"RiUnderline\" strokeWidth={stroke} {...props} />\n}\n","type":"registry:ui","target":"components/ui/ai-editor.tsx"}],"css":{".editor-orb":{"border-radius":"9999px","background":"radial-gradient(60% 60% at 30% 28%, oklch(0.88 0.11 225), transparent 70%), radial-gradient(65% 65% at 72% 68%, oklch(0.62 0.22 288), transparent 70%), linear-gradient(oklch(0.62 0.19 258), oklch(0.72 0.15 238))"},".editor-orb[data-stirring]":{"animation":"editor-orb-stir 2.4s linear infinite"},"@keyframes editor-orb-stir":{"to":{"rotate":"1turn"}},"@media (prefers-reduced-motion: reduce)":{".editor-orb[data-stirring]":{"animation":"none"},".editor-mark, .editor-word":{"transition":"none"}},".editor-mark":{"--editor-ease":"cubic-bezier(0.23, 1, 0.32, 1)","transition-property":"background-size, background-color, padding, letter-spacing, -webkit-text-stroke-color","transition-duration":"220ms","transition-timing-function":"var(--editor-ease)"},".editor-mark[data-leaving]":{"transition-duration":"160ms"},".editor-mark[data-format='underline'], .editor-mark[data-format='strikethrough']":{"background-image":"linear-gradient(currentColor, currentColor)","background-repeat":"no-repeat","background-size":"0% 1px","transition-duration":"260ms"},".editor-mark[data-format='underline'][data-leaving], .editor-mark[data-format='strikethrough'][data-leaving]":{"transition-duration":"180ms"},".editor-mark[data-format='underline']":{"background-position":"0 92%"},".editor-mark[data-format='strikethrough']":{"background-position":"0 58%"},".editor-mark[data-format='underline']:dir(rtl), .editor-mark[data-format='strikethrough']:dir(rtl)":{"background-position-x":"100%"},".editor-mark[data-format='underline'][data-on], .editor-mark[data-format='strikethrough'][data-on]":{"background-size":"100% 1px"},".editor-mark[data-format='bold']":{"letter-spacing":"0","-webkit-text-stroke":"0.03em transparent"},".editor-mark[data-format='bold'][data-on]":{"letter-spacing":"var(--editor-bold-spacing, 0)","-webkit-text-stroke-color":"currentColor"},".editor-word":{"display":"inline-block","transform-origin":"0 78%","transition":"transform 220ms var(--editor-ease)"},".editor-mark[data-leaving] .editor-word":{"transition-duration":"160ms"},".editor-mark[data-format='italic'][data-on] .editor-word":{"transform":"skewX(-12deg)"},".editor-mark[data-format='code']":{"border-radius":"0.3em","-webkit-box-decoration-break":"clone","box-decoration-break":"clone"},".editor-mark[data-format='code'][data-on]":{"background-color":"color-mix(in oklab, currentColor 14%, transparent)","padding-inline":"0.3em"},".editor-mark[data-format='code'][data-mono]":{"font-family":"var(--font-mono)"},".editor-mark[data-instant], .editor-mark[data-instant] .editor-word":{"transition":"none"}}}