{
  "schemaVersion": 1,
  "target": "react",
  "name": "selection-actions",
  "version": "0.1.0",
  "category": "ai-elements",
  "title": "Selection Actions",
  "description": "A floating AI toolbar for selected text in a passage: Rewrite, Shorten, Explain, or a typed edit, with the rewrite resolving in place for Keep or Discard.",
  "tags": [
    "ai",
    "agent",
    "selection",
    "rewrite",
    "toolbar",
    "editor",
    "inline",
    "text"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "motion": "^14.14.0"
  },
  "registryDependencies": [],
  "docsPath": "/components/selection-actions",
  "props": [
    {
      "name": "defaultValue / value",
      "type": "string",
      "description": "The passage. Blank lines separate paragraphs. Pass value with onValueChange to control it."
    },
    {
      "name": "onValueChange",
      "type": "(value: string) => void",
      "description": "Called with the new passage when the user keeps a rewrite."
    },
    {
      "name": "onRun",
      "type": "(request) => string | Promise<string>",
      "description": "Returns the rewrite or note. The request has action, prompt, text, value, start, end, and an AbortSignal for Stop."
    },
    {
      "name": "actions",
      "type": "SelectionAction[]",
      "default": "Rewrite, Shorten, Explain",
      "description": "Toolbar buttons: { id, label, icon?, kind?: \"replace\" | \"note\", pending? }. A note action shows its answer under the toolbar instead of editing."
    },
    {
      "name": "allowPrompt",
      "type": "boolean",
      "default": "true",
      "description": "Adds an Ask button that turns the toolbar into a field for a typed edit."
    },
    {
      "name": "defaultSelection",
      "type": "{ start, end }",
      "description": "Opens the toolbar on this range at first, as if the user had selected it."
    },
    {
      "name": "paragraphClassName",
      "type": "string",
      "description": "Classes for each paragraph."
    }
  ],
  "accessibility": [
    "The toolbar is role=\"toolbar\" named \"Edit selection\", placed right after the passage in the DOM, so Tab moves from a selection into it; Left and Right arrows move between its buttons.",
    "Choosing an action keeps the selected range drawn as a highlight, since the native selection goes away when focus moves.",
    "When the toolbar is used from the keyboard, focus follows each state: Stop while working, then Keep, then back to the first action after Discard.",
    "Escape stops a running request, discards a proposal under review, or closes the toolbar. A polite status region announces working, ready, kept, and discarded.",
    "The custom edit field has a visually hidden label, \"Describe the edit\".",
    "Selecting text needs a pointer or caret browsing; the toolbar itself is fully keyboard operable.",
    "With reduced motion the toolbar moves and resizes instantly, the working spinner is still, and the rewrite appears without the word-by-word blur."
  ],
  "states": [
    "hidden",
    "idle",
    "prompt",
    "working",
    "review",
    "note",
    "error"
  ],
  "files": [
    {
      "path": "agent/selection-actions.tsx",
      "content": "\"use client\";\n\nimport { motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type KeyboardEvent,\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\nconst quint = [0.23, 1, 0.32, 1] as const;\n\nexport interface SelectionAction {\n  id: string;\n  label: string;\n  icon?: ReactNode;\n  /** replace rewrites the selection in place for Keep or Discard; note shows the answer under the toolbar. @default \"replace\" */\n  kind?: \"replace\" | \"note\";\n  /** What the toolbar says while it runs, e.g. \"Shortening\". Defaults to \"Working\". */\n  pending?: string;\n}\n\nexport interface SelectionRequest {\n  /** The action picked, or null for a typed request. */\n  action: SelectionAction | null;\n  /** The typed request, for a custom edit. */\n  prompt?: string;\n  /** The selected text. */\n  text: string;\n  /** The whole passage, for context. */\n  value: string;\n  start: number;\n  end: number;\n  /** Aborted when the user presses Stop or closes the toolbar. */\n  signal: AbortSignal;\n}\n\nexport interface SelectionRange {\n  start: number;\n  end: number;\n}\n\nexport interface SelectionActionsProps extends Omit<ComponentProps<\"div\">, \"children\" | \"defaultValue\" | \"onChange\"> {\n  /** The passage. Blank lines separate paragraphs. Pass with `onValueChange` to control it. */\n  value?: string;\n  defaultValue?: string;\n  /** Called when the user keeps a rewrite. */\n  onValueChange?: (value: string) => void;\n  /** Returns the rewrite (or the note) for a request. May be async. */\n  onRun: (request: SelectionRequest) => string | Promise<string>;\n  /** The buttons in the toolbar. Defaults to Rewrite, Shorten, and Explain. */\n  actions?: SelectionAction[];\n  /** Adds an Ask button that turns the toolbar into a field for a custom edit. @default true */\n  allowPrompt?: boolean;\n  /** Opens the toolbar on this range at first, as if the user had selected it. */\n  defaultSelection?: SelectionRange;\n  /** Classes for each paragraph. */\n  paragraphClassName?: string;\n}\n\ntype Phase = \"idle\" | \"prompt\" | \"working\" | \"review\" | \"note\" | \"error\";\n\nconst defaultActions: SelectionAction[] = [\n  { id: \"rewrite\", label: \"Rewrite\", pending: \"Rewriting\", icon: <RewriteIcon /> },\n  { id: \"shorten\", label: \"Shorten\", pending: \"Shortening\", icon: <ShortenIcon /> },\n  { id: \"explain\", label: \"Explain\", pending: \"Reading\", kind: \"note\", icon: <ExplainIcon /> },\n];\n\ninterface Paragraph {\n  start: number;\n  text: string;\n}\n\nfunction paragraphs(text: string): Paragraph[] {\n  const out: Paragraph[] = [];\n  const pattern = /\\n{2,}/g;\n  let last = 0;\n  let match: RegExpExecArray | null;\n  while ((match = pattern.exec(text))) {\n    out.push({ start: last, text: text.slice(last, match.index) });\n    last = match.index + match[0].length;\n  }\n  out.push({ start: last, text: text.slice(last) });\n  return out;\n}\n\n/**\n * A floating AI toolbar for text the user selects inside a passage: Rewrite, Shorten, Explain, or a\n * typed request. It follows the selection, morphs between its idle, working and Keep or Discard\n * states as one object, and the rewrite resolves in place out of a soft blur.\n */\nexport function SelectionActions({\n  value: valueProp,\n  defaultValue = \"\",\n  onValueChange,\n  onRun,\n  actions = defaultActions,\n  allowPrompt = true,\n  defaultSelection,\n  paragraphClassName,\n  className,\n  ...props\n}: SelectionActionsProps) {\n  const id = useId();\n  const reduce = useReducedMotion();\n  const [inner, setInner] = useState(defaultValue);\n  const value = valueProp ?? inner;\n  const [range, setRange] = useState<SelectionRange | null>(defaultSelection ?? null);\n  // Frozen: the range is drawn as a highlight in the text, because focus has moved to the toolbar.\n  const [frozen, setFrozen] = useState(Boolean(defaultSelection));\n  const [phase, setPhase] = useState<Phase>(\"idle\");\n  const [result, setResult] = useState(\"\");\n  const [prompt, setPrompt] = useState(\"\");\n  const [pendingLabel, setPendingLabel] = useState(\"Working\");\n  const [kept, setKept] = useState<SelectionRange | null>(null);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const [position, setPosition] = useState<{ x: number; y: number; above: boolean } | null>(null);\n  const [size, setSize] = useState<{ width: number; height: number } | null>(null);\n\n  const rootRef = useRef<HTMLDivElement>(null);\n  const textRef = useRef<HTMLDivElement>(null);\n  const barRef = useRef<HTMLDivElement>(null);\n  const barInnerRef = useRef<HTMLDivElement>(null);\n  const controller = useRef<AbortController | null>(null);\n  const lastRequest = useRef<{ action: SelectionAction | null; prompt?: string } | null>(null);\n  const shown = useRef(false);\n  // True while the user drives the toolbar from the keyboard, so focus follows each state change.\n  const keyboard = useRef(false);\n\n  const locked = phase === \"working\" || phase === \"review\" || phase === \"note\";\n  const open = range !== null && range.end > range.start;\n  // Read by the selection listener, which must not act on a stale render.\n  const state = useRef({ locked, frozen, value });\n  state.current = { locked, frozen, value };\n\n  const close = useCallback(() => {\n    controller.current?.abort();\n    controller.current = null;\n    setRange(null);\n    setFrozen(false);\n    setPhase(\"idle\");\n    setPrompt(\"\");\n    setResult(\"\");\n  }, []);\n\n  // Read the user's selection into text offsets while the toolbar is not busy.\n  useEffect(() => {\n    let frame = 0;\n    const read = () => {\n      frame = 0;\n      const root = textRef.current;\n      const bar = barRef.current;\n      const { locked, frozen, value } = state.current;\n      if (!root || locked) return;\n      if (bar?.contains(document.activeElement)) return;\n      const selection = document.getSelection();\n      if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {\n        if (!frozen) setRange(null);\n        return;\n      }\n      const dom = selection.getRangeAt(0);\n      if (!root.contains(dom.startContainer) || !root.contains(dom.endContainer)) {\n        if (!frozen) setRange(null);\n        return;\n      }\n      const start = offsetOf(dom.startContainer, dom.startOffset);\n      const end = offsetOf(dom.endContainer, dom.endOffset);\n      if (start == null || end == null || end <= start) return;\n      // Trim surrounding whitespace so a double-clicked word does not carry its space.\n      const text = value.slice(start, end);\n      const lead = text.length - text.trimStart().length;\n      const trail = text.length - text.trimEnd().length;\n      if (end - trail <= start + lead) return;\n      setFrozen(false);\n      setPhase(\"idle\");\n      setRange({ start: start + lead, end: end - trail });\n    };\n    const onChange = () => {\n      if (!frame) frame = requestAnimationFrame(read);\n    };\n    document.addEventListener(\"selectionchange\", onChange);\n    return () => {\n      document.removeEventListener(\"selectionchange\", onChange);\n      if (frame) cancelAnimationFrame(frame);\n    };\n  }, []);\n\n  // Click outside closes an idle toolbar; Escape anywhere closes it.\n  useEffect(() => {\n    if (!open) return;\n    const onPointer = (event: PointerEvent) => {\n      if (locked) return;\n      if (rootRef.current?.contains(event.target as Node)) return;\n      close();\n    };\n    const onKey = (event: globalThis.KeyboardEvent) => {\n      if (event.key !== \"Escape\" || event.defaultPrevented) return;\n      if (phase === \"working\") {\n        controller.current?.abort();\n        setPhase(\"idle\");\n        return;\n      }\n      if (phase === \"review\") return discard();\n      document.getSelection()?.removeAllRanges();\n      close();\n    };\n    document.addEventListener(\"pointerdown\", onPointer);\n    document.addEventListener(\"keydown\", onKey);\n    return () => {\n      document.removeEventListener(\"pointerdown\", onPointer);\n      document.removeEventListener(\"keydown\", onKey);\n    };\n  });\n\n  // Fade the \"kept\" tint away.\n  useEffect(() => {\n    if (!kept) return;\n    const timer = setTimeout(() => setKept(null), 1200);\n    return () => clearTimeout(timer);\n  }, [kept]);\n\n  // Size of the bar's content, so the bar can ease between widths instead of jumping.\n  useLayoutEffect(() => {\n    const el = barInnerRef.current;\n    if (!el) return;\n    const measure = () => setSize({ width: el.offsetWidth, height: el.offsetHeight });\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [open]);\n\n  // Place the bar centred under the selection, or above it when there is no room below.\n  const place = useCallback(() => {\n    const root = rootRef.current;\n    const text = textRef.current;\n    if (!root || !text || !open) return;\n    let rects: DOMRect[] = [];\n    const marks = text.querySelectorAll<HTMLElement>(\"[data-range]\");\n    if (marks.length) {\n      marks.forEach((mark) => rects.push(...Array.from(mark.getClientRects())));\n    } else {\n      const selection = document.getSelection();\n      if (selection && selection.rangeCount) rects = Array.from(selection.getRangeAt(0).getClientRects());\n    }\n    rects = rects.filter((rect) => rect.width > 0 && rect.height > 0);\n    if (!rects.length) return;\n    const box = root.getBoundingClientRect();\n    const first = rects[0]!;\n    const last = rects[rects.length - 1]!;\n    const left = Math.min(...rects.map((rect) => rect.left));\n    const right = Math.max(...rects.map((rect) => rect.right));\n    const width = size?.width ?? 0;\n    const height = size?.height ?? 36;\n    const center = (left + right) / 2 - box.left;\n    const x = Math.max(0, Math.min(box.width - width, center - width / 2));\n    const below = last.bottom - box.top + 8;\n    const roomBelow = window.innerHeight - (last.bottom + 8 + height) > 8;\n    const above = !roomBelow && first.top - height - 8 > 8;\n    const y = above ? first.top - box.top - 8 - height : below;\n    setPosition((current) => (current && current.x === x && current.y === y && current.above === above ? current : { x, y, above }));\n  }, [open, size]);\n\n  useLayoutEffect(() => {\n    if (!open) {\n      setPosition(null);\n      shown.current = false;\n      return;\n    }\n    place();\n  });\n\n  useEffect(() => {\n    if (!open) return;\n    window.addEventListener(\"resize\", place);\n    window.addEventListener(\"scroll\", place, true);\n    return () => {\n      window.removeEventListener(\"resize\", place);\n      window.removeEventListener(\"scroll\", place, true);\n    };\n  }, [open, place]);\n\n  // Draw the range as a highlight and drop the native selection, which re-rendering would break.\n  function freeze() {\n    if (frozen || !range) return;\n    state.current.frozen = true;\n    setFrozen(true);\n    document.getSelection()?.removeAllRanges();\n  }\n\n  // Moves focus to the new state's main button, but only for someone already working in the toolbar.\n  function focusPrimary() {\n    if (!keyboard.current) return;\n    requestAnimationFrame(() => barRef.current?.querySelector<HTMLElement>(\"[data-primary]\")?.focus({ preventScroll: true }));\n  }\n\n  async function run(action: SelectionAction | null, typed?: string) {\n    if (!range) return;\n    keyboard.current = Boolean(barRef.current?.contains(document.activeElement));\n    freeze();\n    document.getSelection()?.removeAllRanges();\n    controller.current?.abort();\n    const abort = new AbortController();\n    controller.current = abort;\n    lastRequest.current = { action, prompt: typed };\n    const label = action?.pending ?? \"Working\";\n    setPendingLabel(label);\n    setPhase(\"working\");\n    setAnnouncement(`${label}…`);\n    focusPrimary();\n    try {\n      const output = await onRun({\n        action,\n        prompt: typed,\n        text: value.slice(range.start, range.end),\n        value,\n        start: range.start,\n        end: range.end,\n        signal: abort.signal,\n      });\n      if (abort.signal.aborted) return;\n      setResult(output);\n      const note = action?.kind === \"note\";\n      setPhase(note ? \"note\" : \"review\");\n      setAnnouncement(note ? output : \"Rewrite ready. Keep or discard it.\");\n      focusPrimary();\n    } catch {\n      if (abort.signal.aborted) return;\n      setPhase(\"error\");\n      setAnnouncement(\"That did not work. Try again.\");\n      focusPrimary();\n    }\n  }\n\n  function keep() {\n    if (!range) return;\n    const next = value.slice(0, range.start) + result + value.slice(range.end);\n    if (valueProp === undefined) setInner(next);\n    onValueChange?.(next);\n    setKept({ start: range.start, end: range.start + result.length });\n    setAnnouncement(\"Change kept.\");\n    close();\n  }\n\n  function discard() {\n    keyboard.current = Boolean(barRef.current?.contains(document.activeElement));\n    setResult(\"\");\n    setPhase(\"idle\");\n    setAnnouncement(\"Change discarded.\");\n    focusPrimary();\n  }\n\n  function retry() {\n    const request = lastRequest.current;\n    if (request) void run(request.action, request.prompt);\n  }\n\n  function onBarKeyDown(event: KeyboardEvent<HTMLDivElement>) {\n    if (event.key !== \"ArrowRight\" && event.key !== \"ArrowLeft\") return;\n    if ((event.target as HTMLElement).tagName === \"INPUT\") return;\n    const buttons = Array.from(barRef.current?.querySelectorAll<HTMLElement>(\"button:not(:disabled)\") ?? []);\n    const index = buttons.indexOf(event.target as HTMLElement);\n    if (index === -1) return;\n    event.preventDefault();\n    buttons[(index + (event.key === \"ArrowRight\" ? 1 : -1) + buttons.length) % buttons.length]?.focus();\n  }\n\n  // What the text shows: the proposal stands in for the range while it is under review.\n  const reviewing = phase === \"review\" && range !== null;\n  const display = reviewing ? value.slice(0, range.start) + result + value.slice(range.end) : value;\n  const highlight: SelectionRange | null = reviewing\n    ? { start: range.start, end: range.start + result.length }\n    : frozen && range\n      ? range\n      : kept;\n  const highlightKind = reviewing ? \"proposal\" : frozen && range ? \"selection\" : \"kept\";\n\n  // Words of the proposal get a running index so they resolve one after another across paragraphs.\n  let wordIndex = 0;\n\n  const enterTransition = reduce\n    ? { duration: 0 }\n    : shown.current\n      ? { type: \"spring\" as const, duration: 0.42, bounce: 0 }\n      : { duration: 0 };\n  if (position) shown.current = true;\n\n  return (\n    <div ref={rootRef} className={cx(\"@container relative\", className)} {...props}>\n      <div\n        ref={textRef}\n        id={`${id}-text`}\n        onPointerDown={() => {\n          // Starting a new selection: drop the drawn highlight first so the browser selects plain text.\n          if (frozen && !locked) {\n            state.current.frozen = false;\n            setFrozen(false);\n            setRange(null);\n            setPhase(\"idle\");\n          }\n        }}\n        className=\"grid gap-3 text-sm leading-relaxed text-zinc-700 dark:text-zinc-300\"\n      >\n        {paragraphs(display).map((paragraph) => {\n          const pEnd = paragraph.start + paragraph.text.length;\n          const parts: ReactNode[] = [];\n          if (highlight && highlight.start < pEnd && highlight.end > paragraph.start) {\n            const from = Math.max(highlight.start, paragraph.start) - paragraph.start;\n            const to = Math.min(highlight.end, pEnd) - paragraph.start;\n            const middle = paragraph.text.slice(from, to);\n            parts.push(paragraph.text.slice(0, from));\n            if (highlightKind === \"proposal\") {\n              const tokens = middle.split(/(\\s+)/);\n              parts.push(\n                <span key=\"range\" data-range=\"\" className=\"rounded-[3px] bg-zinc-950/[0.05] box-decoration-clone text-zinc-950 dark:bg-white/[0.08] dark:text-white\">\n                  {tokens.map((token, index) =>\n                    /^\\s+$/.test(token) || token === \"\" ? (\n                      token\n                    ) : (\n                      <span\n                        key={index}\n                        style={reduce ? undefined : { transitionDelay: `${Math.min(wordIndex++ * 32, 640)}ms` }}\n                        className={cx(\n                          \"inline-block whitespace-pre\",\n                          \"transition-[opacity,filter,translate] duration-500\",\n                          ease,\n                          \"starting:translate-y-[3px] starting:opacity-0 starting:blur-[6px] motion-reduce:transition-none\",\n                        )}\n                      >\n                        {token}\n                      </span>\n                    ),\n                  )}\n                </span>,\n              );\n            } else {\n              parts.push(\n                <mark\n                  key={`range-${highlightKind}`}\n                  data-range={highlightKind === \"selection\" ? \"\" : undefined}\n                  className={cx(\n                    \"rounded-[3px] box-decoration-clone text-inherit\",\n                    highlightKind === \"selection\"\n                      ? \"bg-sky-500/20 dark:bg-sky-400/25\"\n                      : `bg-transparent transition-[background-color] duration-1000 ${ease} starting:bg-zinc-950/[0.08] motion-reduce:transition-none dark:starting:bg-white/[0.12]`,\n                  )}\n                >\n                  {middle}\n                </mark>,\n              );\n            }\n            parts.push(paragraph.text.slice(to));\n          } else {\n            parts.push(paragraph.text);\n          }\n          return (\n            <p key={paragraph.start} data-start={paragraph.start} className={cx(\"whitespace-pre-wrap\", paragraphClassName)}>\n              {parts}\n            </p>\n          );\n        })}\n      </div>\n\n      {open ? (\n        <motion.div\n          ref={barRef}\n          role=\"toolbar\"\n          aria-label=\"Edit selection\"\n          aria-controls={`${id}-text`}\n          onKeyDown={onBarKeyDown}\n          onMouseDown={(event) => {\n            // Buttons act without taking focus from the text; the field still takes it.\n            if ((event.target as HTMLElement).tagName !== \"INPUT\") event.preventDefault();\n            freeze();\n          }}\n          onFocus={freeze}\n          initial={false}\n          animate={{\n            x: position?.x ?? 0,\n            y: position?.y ?? 0,\n            width: size?.width ?? \"auto\",\n            height: size?.height ?? \"auto\",\n          }}\n          transition={{\n            x: enterTransition,\n            y: enterTransition,\n            width: reduce ? { duration: 0 } : { duration: 0.32, ease: quint },\n            height: reduce ? { duration: 0 } : { duration: 0.32, ease: quint },\n          }}\n          style={{ visibility: position ? \"visible\" : \"hidden\" }}\n          className=\"absolute top-0 left-0 z-10\"\n        >\n          <div\n            className={cx(\n              \"size-full overflow-hidden rounded-xl border border-zinc-950/10 bg-white text-zinc-950\",\n              \"has-[input:focus]:border-sky-500/60 dark:has-[input:focus]:border-sky-400/60\",\n              \"shadow-[0_12px_32px_-8px_rgb(0_0_0/0.18),0_1px_2px_rgb(0_0_0/0.05)]\",\n              \"dark:border-white/15 dark:bg-black dark:text-white dark:shadow-[0_16px_48px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]\",\n              position?.above ? \"origin-bottom\" : \"origin-top\",\n              `transition-[opacity,scale,translate] duration-200 ${ease} motion-reduce:transition-none`,\n              \"starting:scale-[0.96] starting:opacity-0\",\n              position?.above ? \"starting:translate-y-1\" : \"starting:-translate-y-1\",\n            )}\n          >\n            <div ref={barInnerRef} className=\"w-max max-w-[min(22rem,calc(100vw-2rem))]\">\n              <div\n                key={phase}\n                className={cx(\n                  \"flex items-center gap-0.5 p-1\",\n                  `transition-[opacity,filter] duration-200 ${ease} starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none`,\n                  phase === \"note\" && \"flex-col items-stretch gap-0 p-0\",\n                )}\n              >\n                {phase === \"idle\" ? (\n                  <>\n                    {actions.map((action, index) => (\n                      <button key={action.id} type=\"button\" data-primary={index === 0 ? \"\" : undefined} onClick={() => void run(action)} className={barButton}>\n                        {action.icon ? <span aria-hidden=\"true\" className={iconSlot}>{action.icon}</span> : null}\n                        {action.label}\n                      </button>\n                    ))}\n                    {allowPrompt ? (\n                      <>\n                        <span aria-hidden=\"true\" className=\"mx-0.5 h-4 w-px bg-zinc-950/10 dark:bg-white/15\" />\n                        <button\n                          type=\"button\"\n                          onClick={() => {\n                            setPhase(\"prompt\");\n                            requestAnimationFrame(() => barRef.current?.querySelector(\"input\")?.focus());\n                          }}\n                          className={barButton}\n                        >\n                          <span aria-hidden=\"true\" className={iconSlot}>\n                            <AskIcon />\n                          </span>\n                          Ask\n                        </button>\n                      </>\n                    ) : null}\n                  </>\n                ) : phase === \"prompt\" ? (\n                  <form\n                    className=\"flex items-center gap-1\"\n                    onSubmit={(event) => {\n                      event.preventDefault();\n                      if (prompt.trim()) void run(null, prompt.trim());\n                    }}\n                  >\n                    <label htmlFor={`${id}-prompt`} className=\"sr-only\">\n                      Describe the edit\n                    </label>\n                    <input\n                      id={`${id}-prompt`}\n                      value={prompt}\n                      onChange={(event) => setPrompt(event.target.value)}\n                      onKeyDown={(event) => {\n                        if (event.key === \"Escape\") {\n                          event.preventDefault();\n                          setPhase(\"idle\");\n                          requestAnimationFrame(() => barRef.current?.querySelector<HTMLElement>(\"button\")?.focus());\n                        }\n                      }}\n                      placeholder=\"Make it more direct\"\n                      autoComplete=\"off\"\n                      className=\"h-7 w-56 max-w-[calc(100vw-7rem)] bg-transparent px-2 text-sm text-zinc-950 placeholder:text-zinc-500 focus:outline-none dark:text-white\"\n                    />\n                    <button type=\"submit\" aria-label=\"Run edit\" disabled={!prompt.trim()} className={cx(barButton, \"w-7 px-0\")}>\n                      <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-4\">\n                        <path d=\"M8 12.5v-9m0 0L4.5 7M8 3.5 11.5 7\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n                      </svg>\n                    </button>\n                  </form>\n                ) : phase === \"working\" ? (\n                  <>\n                    <span className=\"flex h-7 items-center gap-2 pr-1 pl-2 text-sm text-zinc-600 dark:text-zinc-400\">\n                      <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-3.5 text-zinc-950 motion-safe:animate-spin dark:text-white\">\n                        <circle cx=\"8\" cy=\"8\" r=\"6\" stroke=\"currentColor\" strokeOpacity=\"0.2\" strokeWidth=\"1.75\" />\n                        <path d=\"M14 8a6 6 0 0 0-6-6\" stroke=\"currentColor\" strokeWidth=\"1.75\" strokeLinecap=\"round\" />\n                      </svg>\n                      {pendingLabel}…\n                    </span>\n                    <button\n                      type=\"button\"\n                      data-primary=\"\"\n                      onClick={() => {\n                        controller.current?.abort();\n                        setPhase(\"idle\");\n                        setAnnouncement(\"Stopped.\");\n                      }}\n                      className={barButton}\n                    >\n                      Stop\n                    </button>\n                  </>\n                ) : phase === \"review\" ? (\n                  <>\n                    <button type=\"button\" data-primary=\"\" onClick={keep} className={keepButton}>\n                      Keep\n                    </button>\n                    <button type=\"button\" onClick={discard} className={barButton}>\n                      Discard\n                    </button>\n                    <button type=\"button\" aria-label=\"Try again\" onClick={retry} className={cx(barButton, \"w-7 px-0\")}>\n                      <RetryIcon />\n                    </button>\n                  </>\n                ) : phase === \"note\" ? (\n                  <>\n                    <p className=\"max-h-48 overflow-y-auto px-3 pt-2.5 pb-2 text-sm leading-relaxed text-pretty text-zinc-700 dark:text-zinc-300\">{result}</p>\n                    <div className=\"flex justify-end gap-0.5 border-t border-zinc-950/[0.07] p-1 dark:border-white/[0.08]\">\n                      <button type=\"button\" onClick={retry} className={barButton}>\n                        Try again\n                      </button>\n                      <button\n                        type=\"button\"\n                        data-primary=\"\"\n                        onClick={() => {\n                          document.getSelection()?.removeAllRanges();\n                          close();\n                        }}\n                        className={barButton}\n                      >\n                        Done\n                      </button>\n                    </div>\n                  </>\n                ) : (\n                  <>\n                    <span className=\"flex h-7 items-center gap-2 px-2 text-sm text-red-700 dark:text-red-400\">That did not work.</span>\n                    <button type=\"button\" data-primary=\"\" onClick={retry} className={barButton}>\n                      Try again\n                    </button>\n                    <button type=\"button\" onClick={close} className={barButton}>\n                      Close\n                    </button>\n                  </>\n                )}\n              </div>\n            </div>\n          </div>\n        </motion.div>\n      ) : null}\n\n      <span role=\"status\" className=\"sr-only\">\n        {announcement}\n      </span>\n    </div>\n  );\n}\n\n/** Text offset of a DOM point inside a paragraph rendered by SelectionActions. */\nfunction offsetOf(node: Node, offset: number): number | null {\n  const element = node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement;\n  const paragraph = element?.closest<HTMLElement>(\"[data-start]\");\n  if (!paragraph) return null;\n  const range = document.createRange();\n  range.setStart(paragraph, 0);\n  range.setEnd(node, offset);\n  return Number(paragraph.dataset.start) + range.toString().length;\n}\n\n// In a narrow passage the toolbar keeps its words and drops the icons.\nconst iconSlot = \"flex text-zinc-500 @max-[26rem]:hidden dark:text-zinc-400\";\n\nconst barButton = cx(\n  \"inline-flex h-7 items-center justify-center gap-1.5 rounded-lg px-2 text-sm font-medium whitespace-nowrap select-none\",\n  \"text-zinc-700 hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:text-zinc-300 dark:hover:bg-white/[0.08] dark:hover:text-white\",\n  \"transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.96] motion-reduce:transition-none\",\n  \"focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500 focus-visible:outline-solid\",\n  \"disabled:pointer-events-none disabled:opacity-40 [&_svg]:size-4 [&_svg]:shrink-0\",\n);\n\nconst keepButton = cx(\n  \"inline-flex h-7 items-center justify-center rounded-lg px-2.5 text-sm font-medium whitespace-nowrap select-none\",\n  \"bg-zinc-950 text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.12),0_1px_2px_rgb(0_0_0/0.2)] hover:bg-zinc-800\",\n  \"dark:bg-white dark:text-black dark:shadow-[inset_0_-1px_0_rgb(0_0_0/0.12)] dark:hover:bg-zinc-200\",\n  \"transition-[background-color,scale] duration-150 ease-out motion-safe:active:scale-[0.96] motion-reduce:transition-none\",\n  \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 focus-visible:outline-solid\",\n);\n\nconst stroke = { fill: \"none\", stroke: \"currentColor\", strokeWidth: 1.5, strokeLinecap: \"round\", strokeLinejoin: \"round\" } as const;\n\nfunction RewriteIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" {...stroke}>\n      <path d=\"M10.75 2.75 13.25 5.25 6 12.5 3 13l.5-3z\" />\n      <path d=\"M9 4.5 11.5 7\" />\n    </svg>\n  );\n}\n\nfunction ShortenIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" {...stroke}>\n      <path d=\"M2.75 8h3.5m0 0L4.5 6.25M6.25 8 4.5 9.75M13.25 8h-3.5m0 0 1.75-1.75M9.75 8l1.75 1.75\" />\n    </svg>\n  );\n}\n\nfunction ExplainIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" {...stroke}>\n      <circle cx=\"8\" cy=\"8\" r=\"6\" />\n      <path d=\"M6.4 6.3a1.7 1.7 0 0 1 3.2.6c0 1.1-1.6 1.4-1.6 2.4\" />\n      <path d=\"M8 11.25h.01\" strokeWidth={2} />\n    </svg>\n  );\n}\n\nfunction AskIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" {...stroke}>\n      <path d=\"M8 2.5 9.2 6.8 13.5 8 9.2 9.2 8 13.5 6.8 9.2 2.5 8 6.8 6.8Z\" />\n    </svg>\n  );\n}\n\nfunction RetryIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" {...stroke}>\n      <path d=\"M12.75 8a4.75 4.75 0 1 1-1.4-3.36M12.75 3v2.5h-2.5\" />\n    </svg>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { type SelectionRequest, SelectionActions } from \"@/components/shaken/agent/selection-actions\";\n\nconst passage = `On Tuesday at 14:05 UTC, a configuration change to the rate limiter caused roughly 6% of API requests to fail with 429 errors for about 22 minutes. The change was intended to lower limits only for unauthenticated traffic, but a missing condition applied it to every workspace on the Pro plan.\n\nWe rolled the change back at 14:27 and added a check that compares limits before and after each deploy. Going forward, rate limit changes will ship to 1% of traffic first and wait for an hour of clean metrics before going wider.`;\n\nconst selected = \"The change was intended to lower limits only for unauthenticated traffic, but a missing condition applied it to every workspace on the Pro plan.\";\n\nconst rewrites: Record<string, Record<string, string>> = {\n  rewrite: {\n    [selected]: \"The change should have lowered limits for unauthenticated traffic only; a missing condition applied it to every Pro workspace instead.\",\n  },\n  shorten: {\n    [selected]: \"A missing condition applied a limit meant for anonymous traffic to every Pro workspace.\",\n  },\n};\n\nconst swaps: [RegExp, string][] = [\n  [/\\broughly\\b/g, \"about\"],\n  [/\\bintended\\b/g, \"meant\"],\n  [/\\bGoing forward\\b/g, \"From now on\"],\n  [/\\bwait for\\b/g, \"need\"],\n  [/\\bgoing wider\\b/g, \"rolling out further\"],\n];\n\n// Stands in for a model call: answers after a short pause and stops when aborted.\nfunction fakeModel({ action, prompt, text, signal }: SelectionRequest): Promise<string> {\n  return new Promise((resolve, reject) => {\n    const timer = setTimeout(() => {\n      const id = action?.id ?? \"custom\";\n      if (id === \"explain\") {\n        resolve(\n          /429|rate limit/i.test(text)\n            ? \"A rate limiter caps how many requests one client can send per minute. A 429 status means a request went over that cap and was refused.\"\n            : \"This sentence describes how the team will release limit changes: to a small slice of traffic first, and only wider once metrics stay clean.\",\n        );\n        return;\n      }\n      const canned = rewrites[id]?.[text];\n      if (canned) return resolve(canned);\n      if (id === \"shorten\") return resolve((text.split(/,\\s|;\\s/)[0] ?? text).replace(/[.]?$/, \".\"));\n      if (id === \"custom\" && /direct/i.test(prompt ?? \"\")) return resolve(text.replace(/^The change was intended to/, \"We meant to\"));\n      resolve(swaps.reduce((out, [pattern, next]) => out.replace(pattern, next), text));\n    }, 900);\n    signal.addEventListener(\"abort\", () => {\n      clearTimeout(timer);\n      reject(new DOMException(\"Aborted\", \"AbortError\"));\n    });\n  });\n}\n\nexport default function SelectionActionsExample() {\n  const start = passage.indexOf(selected);\n  return (\n    <article className=\"w-full max-w-lg\">\n      <h3 className=\"mb-2 text-sm font-semibold text-zinc-950 dark:text-white\">Incident summary: API rate limiting</h3>\n      <SelectionActions defaultValue={passage} defaultSelection={{ start, end: start + selected.length }} onRun={fakeModel} />\n      <p className=\"mt-16 text-xs text-zinc-500\">Select any sentence to rewrite, shorten, or explain it.</p>\n    </article>\n  );\n}\n"
  }
}
