{
  "schemaVersion": 1,
  "target": "react",
  "name": "inline-completion",
  "version": "0.1.0",
  "category": "ai-elements",
  "title": "Inline Completion",
  "description": "A text area that suggests how to finish what you are typing as ghost text after the caret, taken all at once with Tab, a word at a time, or up to a clicked word.",
  "tags": [
    "ai",
    "autocomplete",
    "completion",
    "suggestion",
    "ghost text",
    "textarea",
    "input",
    "copilot"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {},
  "registryDependencies": [],
  "docsPath": "/components/inline-completion",
  "props": [
    {
      "name": "getSuggestion",
      "type": "(text, { signal }) => string | null | Promise<string | null>",
      "description": "Returns text that continues the input, sync or async. Called after typing pauses; signal aborts when the user types again."
    },
    {
      "name": "defaultValue / value",
      "type": "string",
      "description": "The text. Pass value with onValueChange to control it."
    },
    {
      "name": "onValueChange",
      "type": "(value: string) => void",
      "description": "Called on every change, including accepted suggestions."
    },
    {
      "name": "delay",
      "type": "number",
      "default": "350",
      "description": "Pause after typing before asking for a suggestion, in milliseconds."
    },
    {
      "name": "singleLine",
      "type": "boolean",
      "default": "false",
      "description": "One line with no wrapping; Enter does not add a new line."
    },
    {
      "name": "suggestOnMount",
      "type": "boolean",
      "default": "false",
      "description": "Asks for a suggestion for the starting text when the field mounts."
    },
    {
      "name": "showHint",
      "type": "boolean",
      "default": "true",
      "description": "Shows a small Tab key after the suggestion while focused."
    },
    {
      "name": "onAccept",
      "type": "(text, how: \"all\" | \"word\" | \"click\") => void",
      "description": "Called when the user takes some or all of a suggestion."
    },
    {
      "name": "containerClassName",
      "type": "string",
      "description": "Classes for the bordered field; className styles the text area."
    }
  ],
  "accessibility": [
    "It is a native textarea, so labels, IME input, spellcheck, and selection behave as usual; it is described by a hidden hint listing the keys.",
    "Tab accepts the suggestion only while one is showing at the end of the text; otherwise Tab moves focus as normal. Right Arrow at the end takes one word, Escape dismisses.",
    "Accepted text is inserted as a native edit, so Undo removes exactly what was accepted.",
    "A polite status region reads the suggestion and \"Press Tab to accept\" when one appears.",
    "Ghost text is never part of the value and never moves the caret; typing a matching character keeps the rest of the suggestion.",
    "With reduced motion the suggestion appears at once instead of writing itself in word by word."
  ],
  "states": [
    "empty",
    "typing",
    "suggesting",
    "partially accepted",
    "dismissed",
    "disabled"
  ],
  "files": [
    {
      "path": "agent/inline-completion.tsx",
      "content": "\"use client\";\n\nimport {\n  type ChangeEvent,\n  type ComponentProps,\n  type KeyboardEvent,\n  type UIEvent,\n  useCallback,\n  useEffect,\n  useId,\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)]\";\n\nexport type SuggestionResult = string | null | undefined;\n\nexport interface InlineCompletionProps\n  extends Omit<ComponentProps<\"textarea\">, \"value\" | \"defaultValue\" | \"onChange\" | \"children\"> {\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /**\n   * Returns text that continues `text` (sync or async), or nothing. Called after the user pauses\n   * typing; `signal` aborts when they type again. Include a leading space when the suggestion starts a new word.\n   */\n  getSuggestion: (text: string, options: { signal: AbortSignal }) => SuggestionResult | Promise<SuggestionResult>;\n  /** Pause after typing before asking for a suggestion, in milliseconds. @default 350 */\n  delay?: number;\n  /** One line: no wrapping, and Enter does not add a new line. */\n  singleLine?: boolean;\n  /** Asks for a suggestion for the starting text as soon as the field mounts. */\n  suggestOnMount?: boolean;\n  /** Shows a small Tab key after the suggestion while the field has focus. @default true */\n  showHint?: boolean;\n  /** Called when the user takes some or all of a suggestion. */\n  onAccept?: (text: string, how: \"all\" | \"word\" | \"click\") => void;\n  /** Classes for the bordered field around the text. `className` styles the text area itself. */\n  containerClassName?: string;\n}\n\ninterface Suggestion {\n  /** Where the suggestion starts in the value. */\n  origin: number;\n  text: string;\n  /** Characters of the suggestion already typed or accepted. */\n  used: number;\n}\n\ninterface Word {\n  /** Offset in the suggestion text. */\n  start: number;\n  end: number;\n  text: string;\n}\n\n/** Words of a suggestion, each with the whitespace in front of it. */\nfunction words(text: string): Word[] {\n  const out: Word[] = [];\n  const pattern = /\\s*\\S+|\\s+$/g;\n  let match: RegExpExecArray | null;\n  while ((match = pattern.exec(text))) out.push({ start: match.index, end: match.index + match[0].length, text: match[0] });\n  return out;\n}\n\n/**\n * A text area that suggests how to finish what the user is typing, as grey ghost text after the\n * caret. Tab takes all of it, Right Arrow takes the next word, a click on a ghost word takes the\n * text up to it, and Escape dismisses it. Typing a matching character keeps the rest.\n */\nexport function InlineCompletion({\n  value: valueProp,\n  defaultValue = \"\",\n  onValueChange,\n  getSuggestion,\n  delay = 350,\n  singleLine = false,\n  suggestOnMount = false,\n  showHint = true,\n  onAccept,\n  containerClassName,\n  className,\n  onKeyDown,\n  onSelect,\n  onScroll,\n  onFocus,\n  onBlur,\n  disabled,\n  rows = 3,\n  \"aria-describedby\": describedBy,\n  ...props\n}: InlineCompletionProps) {\n  const id = useId();\n  const [inner, setInner] = useState(defaultValue);\n  const value = valueProp ?? inner;\n  const [suggestion, setSuggestion] = useState<Suggestion | null>(null);\n  const [atEnd, setAtEnd] = useState(true);\n  const [focused, setFocused] = useState(false);\n  const [touched, setTouched] = useState(false);\n  const [hovered, setHovered] = useState<number | null>(null);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const fieldRef = useRef<HTMLTextAreaElement>(null);\n  const mirrorRef = useRef<HTMLDivElement>(null);\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const controller = useRef<AbortController | null>(null);\n  const valueRef = useRef(value);\n  valueRef.current = value;\n  // How the next accepted insertion should be reported to onAccept.\n  const accepting = useRef<\"all\" | \"word\" | \"click\" | null>(null);\n  const getRef = useRef(getSuggestion);\n  getRef.current = getSuggestion;\n\n  const request = useCallback(\n    (text: string, wait: number) => {\n      if (timer.current) clearTimeout(timer.current);\n      controller.current?.abort();\n      if (!text.trim()) return;\n      timer.current = setTimeout(async () => {\n        const abort = new AbortController();\n        controller.current = abort;\n        try {\n          const result = await getRef.current(text, { signal: abort.signal });\n          if (abort.signal.aborted || valueRef.current !== text || !result) return;\n          setSuggestion({ origin: text.length, text: result, used: 0 });\n          setAnnouncement(`Suggestion: ${result.trim()}. Press Tab to accept.`);\n        } catch {\n          // A failed or aborted request just means no suggestion.\n        }\n      }, wait);\n    },\n    [],\n  );\n\n  useEffect(() => {\n    if (suggestOnMount) request(valueRef.current, 0);\n    return () => {\n      if (timer.current) clearTimeout(timer.current);\n      controller.current?.abort();\n    };\n  }, [suggestOnMount, request]);\n\n  const remaining = suggestion ? suggestion.text.slice(suggestion.used) : \"\";\n  const live = Boolean(suggestion && remaining && suggestion.origin + suggestion.used === value.length);\n  const visible = live && atEnd && (focused || !touched) && !disabled;\n\n  function setValue(next: string) {\n    if (valueProp === undefined) setInner(next);\n    onValueChange?.(next);\n  }\n\n  function dismiss() {\n    setSuggestion(null);\n    setHovered(null);\n    setAnnouncement(\"\");\n  }\n\n  function handleChange(event: ChangeEvent<HTMLTextAreaElement>) {\n    const next = event.target.value;\n    const previous = value;\n    setValue(next);\n    syncCaret(event.target);\n    // Typing (or accepting) text that matches the suggestion keeps the rest of it.\n    if (suggestion && next.startsWith(previous) && next.length > previous.length) {\n      const typed = next.slice(previous.length);\n      const offset = previous.length - suggestion.origin;\n      if (offset === suggestion.used && suggestion.text.startsWith(typed, suggestion.used)) {\n        const used = suggestion.used + typed.length;\n        if (accepting.current) onAccept?.(typed, accepting.current);\n        accepting.current = null;\n        if (used >= suggestion.text.length) {\n          dismiss();\n          request(next, delay);\n        } else {\n          setSuggestion({ ...suggestion, used });\n        }\n        return;\n      }\n    }\n    accepting.current = null;\n    dismiss();\n    request(next, delay);\n  }\n\n  function syncCaret(field: HTMLTextAreaElement) {\n    setAtEnd(field.selectionStart === field.value.length && field.selectionEnd === field.value.length);\n  }\n\n  /** Inserts accepted text at the end as a normal edit, so it can be undone. */\n  function insert(text: string, how: \"all\" | \"word\" | \"click\") {\n    const field = fieldRef.current;\n    if (!field || !text) return;\n    field.focus();\n    field.setSelectionRange(field.value.length, field.value.length);\n    accepting.current = how;\n    const inserted = typeof document.execCommand === \"function\" && document.execCommand(\"insertText\", false, text);\n    if (!inserted) {\n      field.setRangeText(text, field.value.length, field.value.length, \"end\");\n      field.dispatchEvent(new Event(\"input\", { bubbles: true }));\n    }\n    setHovered(null);\n  }\n\n  function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {\n    onKeyDown?.(event);\n    if (event.defaultPrevented) return;\n    if (singleLine && event.key === \"Enter\") {\n      event.preventDefault();\n      return;\n    }\n    if (!visible || event.metaKey || event.ctrlKey || event.altKey) return;\n    if (event.key === \"Tab\" && !event.shiftKey) {\n      event.preventDefault();\n      insert(remaining, \"all\");\n    } else if (event.key === \"ArrowRight\" && !event.shiftKey) {\n      const next = /^\\s*\\S+/.exec(remaining);\n      if (!next) return;\n      event.preventDefault();\n      insert(next[0], \"word\");\n    } else if (event.key === \"Escape\") {\n      event.preventDefault();\n      dismiss();\n      setAnnouncement(\"Suggestion dismissed.\");\n    }\n  }\n\n  function handleScroll(event: UIEvent<HTMLTextAreaElement>) {\n    onScroll?.(event);\n    const mirror = mirrorRef.current;\n    if (!mirror) return;\n    mirror.scrollTop = event.currentTarget.scrollTop;\n    mirror.scrollLeft = event.currentTarget.scrollLeft;\n  }\n\n  // Keep the mirror scrolled with the field when text is added at the end.\n  useEffect(() => {\n    const field = fieldRef.current;\n    const mirror = mirrorRef.current;\n    if (!field || !mirror) return;\n    mirror.scrollTop = field.scrollTop;\n    mirror.scrollLeft = field.scrollLeft;\n  });\n\n  const ghostWords = suggestion ? words(suggestion.text).filter((word) => word.end > suggestion.used) : [];\n  const metrics = cx(\n    \"px-3 py-2 text-sm leading-6 [scrollbar-gutter:stable]\",\n    singleLine ? \"whitespace-pre\" : \"whitespace-pre-wrap break-words\",\n  );\n\n  return (\n    <div\n      data-disabled={disabled || undefined}\n      className={cx(\n        \"relative w-full rounded-lg border border-zinc-950/15 bg-white text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]\",\n        \"transition-[border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none\",\n        \"hover:border-zinc-950/25 focus-within:border-zinc-950/30 focus-within:shadow-[0_0_0_3px_rgb(14_165_233/0.16)]\",\n        \"dark:border-white/15 dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)] dark:hover:border-white/25 dark:focus-within:border-white/30 dark:focus-within:shadow-[0_0_0_3px_rgb(56_189_248/0.18)]\",\n        \"data-[disabled]:pointer-events-none data-[disabled]:opacity-60\",\n        containerClassName,\n      )}\n    >\n      <textarea\n        ref={fieldRef}\n        value={value}\n        disabled={disabled}\n        rows={singleLine ? 1 : rows}\n        aria-describedby={cx(describedBy, `${id}-help`)}\n        onChange={handleChange}\n        onKeyDown={handleKeyDown}\n        onScroll={handleScroll}\n        onSelect={(event) => {\n          onSelect?.(event);\n          syncCaret(event.currentTarget);\n        }}\n        onFocus={(event) => {\n          onFocus?.(event);\n          setFocused(true);\n          setTouched(true);\n          syncCaret(event.currentTarget);\n        }}\n        onBlur={(event) => {\n          onBlur?.(event);\n          setFocused(false);\n          setHovered(null);\n        }}\n        {...props}\n        className={cx(\n          \"absolute inset-0 block size-full resize-none bg-transparent text-zinc-950 placeholder:text-zinc-500 focus:outline-none dark:text-white\",\n          singleLine ? \"overflow-x-auto overflow-y-hidden [scrollbar-width:none]\" : \"overflow-y-auto\",\n          metrics,\n          className,\n        )}\n      />\n      {/*\n        A transparent copy of the text in the same box, so the ghost words land right after the caret.\n        It sits in the flow and sizes the field, so a long suggestion grows the field instead of hiding.\n      */}\n      <div\n        ref={mirrorRef}\n        aria-hidden=\"true\"\n        style={singleLine ? undefined : { minHeight: `calc(${rows} * 1.5rem + 1rem)` }}\n        className={cx(\n          \"pointer-events-none relative overflow-hidden\",\n          singleLine ? \"h-10 [scrollbar-width:none]\" : \"max-h-60\",\n          metrics,\n        )}\n      >\n        <span className=\"text-transparent\">{value}</span>\n        {visible\n          ? ghostWords.map((word, index) => {\n              const shown = word.start < suggestion!.used ? word.text.slice(suggestion!.used - word.start) : word.text;\n              const lit = hovered !== null && index <= hovered;\n              return (\n                <span\n                  key={suggestion!.origin + word.start}\n                  onMouseDown={(event) => event.preventDefault()}\n                  onMouseEnter={() => setHovered(index)}\n                  onMouseLeave={() => setHovered((current) => (current === index ? null : current))}\n                  onClick={() => insert(suggestion!.text.slice(suggestion!.used, word.end), \"click\")}\n                  style={{ transitionDelay: word.start < suggestion!.used ? undefined : `${Math.min(index * 40, 600)}ms` }}\n                  className={cx(\n                    \"pointer-events-auto cursor-pointer\",\n                    \"transition-[opacity,filter,color] duration-300 starting:opacity-0 starting:blur-[3px] motion-reduce:transition-none\",\n                    ease,\n                    lit ? \"text-zinc-700 dark:text-zinc-300\" : \"text-zinc-500 dark:text-zinc-500\",\n                  )}\n                >\n                  {shown}\n                </span>\n              );\n            })\n          : null}\n        {visible && showHint && focused ? (\n          <kbd\n            className={cx(\n              \"ml-1.5 inline-flex h-4 translate-y-[-1px] items-center rounded-[4px] border border-b-[1.5px] px-1 align-middle font-sans text-[10px] leading-none font-medium\",\n              \"border-zinc-950/12 text-zinc-500 dark:border-white/15 dark:text-zinc-500\",\n              `transition-opacity duration-300 ${ease} starting:opacity-0 motion-reduce:transition-none`,\n            )}\n          >\n            Tab\n          </kbd>\n        ) : null}\n        {/* Keeps a trailing new line from collapsing, so the caret line has height. */}\n        {\"\\u200b\"}\n      </div>\n      <span id={`${id}-help`} className=\"sr-only\">\n        Suggestions appear as you type. Tab accepts a suggestion, Right Arrow accepts one word, Escape dismisses it.\n      </span>\n      <span role=\"status\" className=\"sr-only\">\n        {visible || announcement.startsWith(\"Suggestion dismissed\") ? announcement : \"\"}\n      </span>\n    </div>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useId } from \"react\";\nimport { InlineCompletion } from \"@/components/shaken/agent/inline-completion\";\n\n// Stands in for a completion model: finishes known drafts, then falls back to short endings.\nconst drafts = [\n  \"Hi Priya, thanks for flagging the duplicate invoices. We traced it to a retry in our billing webhook and refunded the extra charge to your card this morning. It should show up within 3 to 5 business days.\",\n  \"Fix duplicate charge when the billing webhook retries after a timeout\",\n  \"Add idempotency keys to invoice creation\",\n];\n\nconst endings: [RegExp, string][] = [\n  [/let me know$/i, \" if anything else looks off.\"],\n  [/thanks for$/i, \" your patience while we looked into this.\"],\n  [/\\bwe will$/i, \" follow up once the fix is deployed.\"],\n  [/sorry for$/i, \" the trouble this caused.\"],\n];\n\nfunction suggest(text: string, { signal }: { signal: AbortSignal }): Promise<string | null> {\n  return new Promise((resolve) => {\n    const timer = setTimeout(() => {\n      const lower = text.toLowerCase();\n      const draft = drafts.find((item) => item.toLowerCase().startsWith(lower) && item.length > text.length);\n      if (draft) return resolve(draft.slice(text.length));\n      const ending = endings.find(([pattern]) => pattern.test(text.trimEnd()));\n      resolve(ending && !/\\s$/.test(text) ? ending[1] : null);\n    }, 220);\n    signal.addEventListener(\"abort\", () => clearTimeout(timer));\n  });\n}\n\nexport default function InlineCompletionExample() {\n  const id = useId();\n  return (\n    <div className=\"grid w-full max-w-md gap-5\">\n      <div className=\"grid gap-2\">\n        <label htmlFor={`${id}-reply`} className=\"text-sm font-medium text-zinc-950 dark:text-white\">\n          Reply to Priya Raman\n        </label>\n        <InlineCompletion id={`${id}-reply`} defaultValue=\"Hi Priya, thanks for flagging the duplicate invoices.\" getSuggestion={suggest} suggestOnMount />\n      </div>\n      <div className=\"grid gap-2\">\n        <label htmlFor={`${id}-commit`} className=\"text-sm font-medium text-zinc-950 dark:text-white\">\n          Commit message\n        </label>\n        <InlineCompletion id={`${id}-commit`} singleLine placeholder=\"Fix duplicate…\" getSuggestion={suggest} />\n        <p className=\"text-xs text-zinc-500\">Tab accepts, Right Arrow takes one word, Escape dismisses.</p>\n      </div>\n    </div>\n  );\n}\n"
  }
}
