{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prompt-05",
  "title": "Ghost text",
  "description": "A faint completion after the caret in a textarea or a line of code: Tab takes it, Ctrl or Cmd with Right takes one word and Escape dismisses it.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/kbd.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/prompt/prompt-05.tsx",
      "content": "'use client';\n\nimport { motion } from 'motion/react';\nimport { useEffect, useId, useImperativeHandle, useRef, useState } from 'react';\n\nimport { typingSteps, useAutoplay } from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Kbd, KbdGroup } from '@/registry/ndeko/ui/kbd';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\n\nimport { useAutosize } from './_parts/use-autosize';\n\n/** Both layers share these metrics exactly, so the suggestion wraps where the typed text wraps. */\nconst TEXT_BOX =\n  'border border-transparent px-2.5 py-2 text-base leading-normal md:text-[13px]';\n\nconst FIELD_SHELL = [\n  'relative rounded-md bg-card shadow-[0_1px_2px_rgb(0_0_0/0.05)] hairline-ring ring-foreground/12',\n  'transition-[box-shadow] duration-150 dark:bg-foreground/[0.04] dark:ring-foreground/15',\n  'has-[textarea:focus]:ring-[3px] has-[textarea:focus]:ring-ring/25',\n].join(' ');\n\nconst DEFAULT_DELAY_MS = 300;\n\nconst ACCEPTED_MESSAGE = 'Suggestion accepted';\n\nconst AVAILABLE_MESSAGE = 'Suggestion available, press Tab to accept';\n\nfunction appendedPart(previous: string, next: string) {\n  const isAppend = next.startsWith(previous);\n  if (!isAppend) {\n    return null;\n  }\n  return next.slice(previous.length);\n}\n\n/** The next word of a suggestion with the spaces before it, for Ctrl or Cmd plus Right. */\nexport function firstWordOf(suggestion: string) {\n  const match = suggestion.match(/^\\s*\\S+/);\n  return match?.[0] ?? suggestion;\n}\n\nfunction isCaretAtEnd(textarea: HTMLTextAreaElement) {\n  const end = textarea.value.length;\n  const isCollapsed = textarea.selectionStart === textarea.selectionEnd;\n  const isAtEnd = textarea.selectionEnd === end;\n  return isCollapsed && isAtEnd;\n}\n\nfunction isAbort(error: unknown) {\n  return error instanceof DOMException && error.name === 'AbortError';\n}\n\nfunction hintOf(suggestion: string) {\n  const trimmed = suggestion.trim();\n  if (trimmed === '') {\n    return '';\n  }\n  return `Suggestion: ${trimmed}. Tab accepts it, Control or Command with Right accepts one word, Escape dismisses it.`;\n}\n\nfunction WaitingDot() {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const pulse = pulseOf(shouldReduceMotion);\n\n  return (\n    <motion.span\n      className='bg-primary ms-1 inline-block size-1.5 rounded-full align-middle'\n      initial={{ opacity: 0.35 }}\n      animate={pulse}\n      transition={{ duration: 1.1, repeat: Infinity, ease: 'easeInOut' }}\n    />\n  );\n}\n\nfunction pulseOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return { opacity: [0.35, 0.9, 0.35] };\n  }\n  return { opacity: [0.35, 1, 0.35], scale: [0.85, 1, 0.85] };\n}\n\nexport type GhostTextareaProps = Omit<\n  React.ComponentProps<'textarea'>,\n  'value' | 'onChange' | 'defaultValue'\n> & {\n  value: string;\n  onValueChange: (value: string) => void;\n  /** Returns what would follow the text; an empty string means nothing to suggest. */\n  suggest: (text: string, signal: AbortSignal) => Promise<string>;\n  /** How long typing has to pause before a suggestion is asked for. */\n  delay?: number;\n  monospace?: boolean;\n  /** Enter never adds a line, for a field of one line such as code or a title. */\n  singleLine?: boolean;\n  maxHeight?: number;\n  /** Shows the suggestion without focus, for a demonstration or a preview nobody types in. */\n  showsUnfocused?: boolean;\n  onSuggestionAccept?: (kind: AcceptKind) => void;\n  onSuggestionDismiss?: () => void;\n  /** Accept or dismiss from a button, for screens with no Tab key. */\n  handleRef?: React.Ref<GhostTextareaHandle>;\n};\n\nexport type AcceptKind = 'all' | 'word';\n\nexport type GhostTextareaHandle = {\n  accept: () => void;\n  acceptWord: () => void;\n  dismiss: () => void;\n  /** Asks for a suggestion for the text as it is now, after a change made from outside the field. */\n  suggest: () => void;\n};\n\ntype Landed = {\n  from: number;\n  to: number;\n  id: number;\n};\n\n/** The text just accepted lights for a moment behind its letters, then the tint leaves. */\nfunction MirrorText({\n  value,\n  landed,\n}: {\n  value: string;\n  landed: Landed | null;\n}) {\n  if (!landed) {\n    return <span>{value}</span>;\n  }\n  const before = value.slice(0, landed.from);\n  const part = value.slice(landed.from, landed.to);\n  const after = value.slice(landed.to);\n\n  return (\n    <>\n      <span>{before}</span>\n      <span\n        key={landed.id}\n        className='bg-primary/0 starting:bg-primary/20 rounded-[3px] transition-colors duration-700 ease-out'\n      >\n        {part}\n      </span>\n      <span>{after}</span>\n    </>\n  );\n}\n\nexport function GhostTextarea({\n  value,\n  onValueChange,\n  suggest,\n  delay = DEFAULT_DELAY_MS,\n  monospace = false,\n  singleLine = false,\n  maxHeight = 240,\n  showsUnfocused = false,\n  onSuggestionAccept,\n  onSuggestionDismiss,\n  handleRef,\n  className,\n  onKeyDown,\n  onFocus,\n  onBlur,\n  onScroll,\n  onSelect,\n  ...props\n}: GhostTextareaProps) {\n  const [suggestion, setSuggestion] = useState('');\n  const [isWaiting, setIsWaiting] = useState(false);\n  const [isFocused, setIsFocused] = useState(false);\n  const [announcement, setAnnouncement] = useState('');\n  const [landed, setLanded] = useState<Landed | null>(null);\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const mirrorRef = useRef<HTMLDivElement>(null);\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const request = useRef<AbortController | null>(null);\n  const hintId = useId();\n  const hasSuggestion = suggestion !== '';\n  const isShowing = isFocused || showsUnfocused;\n  const showsSuggestion = hasSuggestion && isShowing;\n  const showsWaiting = isWaiting && isShowing;\n  const hint = hintOf(suggestion);\n  useAutosize(textareaRef, value, maxHeight);\n\n  useEffect(() => {\n    return () => {\n      if (timer.current) {\n        clearTimeout(timer.current);\n      }\n      request.current?.abort();\n    };\n  }, []);\n\n  useImperativeHandle(handleRef, () => ({\n    accept: acceptAll,\n    acceptWord,\n    dismiss,\n    suggest: suggestNow,\n  }));\n\n  function cancelPending() {\n    if (timer.current) {\n      clearTimeout(timer.current);\n      timer.current = null;\n    }\n    request.current?.abort();\n    request.current = null;\n    setIsWaiting(false);\n  }\n\n  function ask(text: string) {\n    const textarea = textareaRef.current;\n    if (!textarea) {\n      return;\n    }\n    if (!isCaretAtEnd(textarea)) {\n      return;\n    }\n    const controller = new AbortController();\n    request.current = controller;\n    setIsWaiting(true);\n    suggest(text, controller.signal)\n      .then((next) => {\n        if (controller.signal.aborted) {\n          return;\n        }\n        setIsWaiting(false);\n        setSuggestion(next);\n        if (next.trim() !== '') {\n          setAnnouncement(AVAILABLE_MESSAGE);\n        }\n      })\n      .catch((error: unknown) => {\n        if (isAbort(error)) {\n          return;\n        }\n        setIsWaiting(false);\n      });\n  }\n\n  function askAfterPause(text: string) {\n    cancelPending();\n    if (text.trim() === '') {\n      return;\n    }\n    timer.current = setTimeout(() => {\n      timer.current = null;\n      ask(text);\n    }, delay);\n  }\n\n  function changeValue(event: React.ChangeEvent<HTMLTextAreaElement>) {\n    const next = event.target.value;\n    const typed = appendedPart(value, next);\n    const isTyping = typed !== null && typed !== '';\n    const keepsSuggestion = isTyping && suggestion.startsWith(typed);\n    setLanded(null);\n    onValueChange(next);\n    if (keepsSuggestion) {\n      const rest = suggestion.slice(typed.length);\n      setSuggestion(rest);\n      if (rest === '') {\n        askAfterPause(next);\n      }\n      return;\n    }\n    setSuggestion('');\n    askAfterPause(next);\n  }\n\n  function accept(part: string) {\n    const next = `${value}${part}`;\n    const rest = suggestion.slice(part.length);\n    setLanded({ from: value.length, to: next.length, id: Date.now() });\n    onValueChange(next);\n    setSuggestion(rest);\n    setAnnouncement(ACCEPTED_MESSAGE);\n    requestAnimationFrame(() => {\n      const textarea = textareaRef.current;\n      if (!textarea) {\n        return;\n      }\n      const end = textarea.value.length;\n      textarea.setSelectionRange(end, end);\n    });\n    if (rest === '') {\n      askAfterPause(next);\n    }\n  }\n\n  function acceptAll() {\n    if (!hasSuggestion) {\n      return;\n    }\n    accept(suggestion);\n    onSuggestionAccept?.('all');\n  }\n\n  function acceptWord() {\n    if (!hasSuggestion) {\n      return;\n    }\n    accept(firstWordOf(suggestion));\n    onSuggestionAccept?.('word');\n  }\n\n  function suggestNow() {\n    setLanded(null);\n    setSuggestion('');\n    askAfterPause(value);\n  }\n\n  function dismiss() {\n    cancelPending();\n    setSuggestion('');\n    setAnnouncement('Suggestion dismissed');\n    onSuggestionDismiss?.();\n  }\n\n  function handleKeys(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n    onKeyDown?.(event);\n    if (event.defaultPrevented) {\n      return;\n    }\n    const isEnter = event.key === 'Enter';\n    const blocksNewLine = isEnter && singleLine;\n    if (blocksNewLine) {\n      event.preventDefault();\n      return;\n    }\n    if (!hasSuggestion) {\n      return;\n    }\n    const isTab = event.key === 'Tab' && !event.shiftKey;\n    if (isTab) {\n      event.preventDefault();\n      acceptAll();\n      return;\n    }\n    const hasWordModifier = event.ctrlKey || event.metaKey;\n    const isWordKey = event.key === 'ArrowRight' && hasWordModifier;\n    if (isWordKey) {\n      event.preventDefault();\n      acceptWord();\n      return;\n    }\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      dismiss();\n    }\n  }\n\n  function handleFocus(event: React.FocusEvent<HTMLTextAreaElement>) {\n    onFocus?.(event);\n    setIsFocused(true);\n    const shouldAsk = !hasSuggestion && !isWaiting;\n    if (shouldAsk) {\n      askAfterPause(event.currentTarget.value);\n    }\n  }\n\n  function handleBlur(event: React.FocusEvent<HTMLTextAreaElement>) {\n    onBlur?.(event);\n    setIsFocused(false);\n    cancelPending();\n  }\n\n  function followScroll(event: React.UIEvent<HTMLTextAreaElement>) {\n    onScroll?.(event);\n    const mirror = mirrorRef.current;\n    if (mirror) {\n      mirror.scrollTop = event.currentTarget.scrollTop;\n    }\n  }\n\n  function handleSelect(event: React.SyntheticEvent<HTMLTextAreaElement>) {\n    onSelect?.(event);\n    const isAway = !isCaretAtEnd(event.currentTarget);\n    if (!isAway) {\n      return;\n    }\n    if (hasSuggestion) {\n      setSuggestion('');\n    }\n    if (isWaiting) {\n      cancelPending();\n    }\n  }\n\n  return (\n    <div className={cn(FIELD_SHELL, className)}>\n      <div\n        ref={mirrorRef}\n        aria-hidden='true'\n        className={cn(\n          TEXT_BOX,\n          'pointer-events-none absolute inset-0 overflow-hidden break-words whitespace-pre-wrap text-transparent',\n          monospace && 'font-mono'\n        )}\n      >\n        <MirrorText value={value} landed={landed} />\n        {showsSuggestion && (\n          <span className='text-muted-foreground/60'>{suggestion}</span>\n        )}\n        {showsWaiting && <WaitingDot />}\n      </div>\n      <textarea\n        ref={textareaRef}\n        value={value}\n        onChange={changeValue}\n        onKeyDown={handleKeys}\n        onFocus={handleFocus}\n        onBlur={handleBlur}\n        onScroll={followScroll}\n        onSelect={handleSelect}\n        aria-describedby={hintId}\n        spellCheck={!monospace}\n        className={cn(\n          TEXT_BOX,\n          'placeholder:text-muted-foreground/75 relative block w-full resize-none bg-transparent outline-none',\n          monospace && 'font-mono'\n        )}\n        {...props}\n      />\n      <span id={hintId} className='sr-only'>\n        {hint}\n      </span>\n      <LiveRegion message={announcement} />\n    </div>\n  );\n}\n\nconst PAUSE_MS = 420;\n\nfunction wait(milliseconds: number, signal: AbortSignal) {\n  return new Promise<void>((resolve, reject) => {\n    const timeout = setTimeout(resolve, milliseconds);\n    signal.addEventListener('abort', () => {\n      clearTimeout(timeout);\n      reject(new DOMException('The suggestion was cancelled', 'AbortError'));\n    });\n  });\n}\n\nconst EMAIL_SENTENCES = [\n  'Hi Maren,',\n  'Thanks for sending the revised quote so quickly.',\n  'I went through it with the team this morning and the new rates work for us.',\n  'Could you send the contract by Friday so we can sign before the end of the month?',\n  'Happy to jump on a call if anything needs a closer look.',\n  'Best,',\n  'Jonas',\n];\n\nconst MIN_PREFIX = 3;\n\nfunction separatorBefore(index: number) {\n  const isAfterGreeting = index === 1;\n  const isSignOff = index >= EMAIL_SENTENCES.length - 2;\n  if (isAfterGreeting) {\n    return '\\n\\n';\n  }\n  if (isSignOff) {\n    return '\\n\\n';\n  }\n  return ' ';\n}\n\nfunction restOfSentence(text: string) {\n  const lowered = text.toLowerCase();\n  let best = '';\n  for (const sentence of EMAIL_SENTENCES) {\n    const loweredSentence = sentence.toLowerCase();\n    for (let length = sentence.length - 1; length >= MIN_PREFIX; length -= 1) {\n      const prefix = loweredSentence.slice(0, length);\n      const isTyped = lowered.endsWith(prefix);\n      const isLonger = length > best.length;\n      const isBetter = isTyped && isLonger;\n      if (isBetter) {\n        best = sentence.slice(0, length);\n        break;\n      }\n    }\n  }\n  if (best === '') {\n    return '';\n  }\n  const sentence = EMAIL_SENTENCES.find((candidate) =>\n    candidate.toLowerCase().startsWith(best.toLowerCase())\n  );\n  return sentence?.slice(best.length) ?? '';\n}\n\nfunction nextSentence(text: string) {\n  const trimmed = text.trimEnd();\n  const index = EMAIL_SENTENCES.findIndex((sentence) =>\n    trimmed.endsWith(sentence)\n  );\n  const nextIndex = index + 1;\n  const hasNext = index >= 0 && nextIndex < EMAIL_SENTENCES.length;\n  if (!hasNext) {\n    return '';\n  }\n  const separator = separatorBefore(nextIndex);\n  const trailing = text.slice(trimmed.length);\n  const sentence = EMAIL_SENTENCES[nextIndex];\n  if (trailing !== '') {\n    return sentence;\n  }\n  return `${separator}${sentence}`;\n}\n\nasync function suggestEmail(text: string, signal: AbortSignal) {\n  await wait(PAUSE_MS, signal);\n  const rest = restOfSentence(text);\n  if (rest !== '') {\n    return rest;\n  }\n  return nextSentence(text);\n}\n\nconst CODE_LINES = [\n  \"const paidOrders = orders.filter((order) => order.status === 'paid');\",\n  'const lateInvoices = invoices.filter((invoice) => invoice.dueAt < today);',\n  'export function formatAmount(cents: number) {',\n  'const dueSoon = invoices.filter((invoice) => invoice.daysLeft < 7);',\n];\n\nasync function suggestCode(text: string, signal: AbortSignal) {\n  await wait(PAUSE_MS, signal);\n  const isLongEnough = text.trim().length >= 2;\n  if (!isLongEnough) {\n    return '';\n  }\n  const line = CODE_LINES.find((candidate) => {\n    const isPrefix = candidate.startsWith(text);\n    const isLonger = candidate.length > text.length;\n    return isPrefix && isLonger;\n  });\n  return line?.slice(text.length) ?? '';\n}\n\ntype HintKey = 'tab' | 'word' | 'escape';\n\nconst KEY_PRESS_MS = 220;\n\nfunction keyClassOf(isPressed: boolean) {\n  if (isPressed) {\n    return 'scale-90 bg-primary/15 text-primary-ink';\n  }\n  return '';\n}\n\nfunction hintKeyOf(kind: AcceptKind): HintKey {\n  if (kind === 'word') {\n    return 'word';\n  }\n  return 'tab';\n}\n\nfunction KeyHints({ pressed }: { pressed: HintKey | null }) {\n  const tabClass = keyClassOf(pressed === 'tab');\n  const wordClass = keyClassOf(pressed === 'word');\n  const escapeClass = keyClassOf(pressed === 'escape');\n  const keyMotion = 'transition-[scale,background-color,color] duration-150';\n\n  return (\n    <p className='text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-xs'>\n      <span className='inline-flex items-center gap-1'>\n        <Kbd className={cn(keyMotion, tabClass)}>Tab</Kbd> accepts\n      </span>\n      <span className='inline-flex items-center gap-1'>\n        <KbdGroup aria-hidden='true'>\n          <Kbd className={cn(keyMotion, wordClass)}>Ctrl</Kbd>\n          <Kbd className={cn(keyMotion, wordClass)}>→</Kbd>\n        </KbdGroup>\n        <span className='sr-only'>Control or Command with Right</span>\n        one word\n      </span>\n      <span className='inline-flex items-center gap-1'>\n        <Kbd className={cn(keyMotion, escapeClass)}>Esc</Kbd> dismisses\n      </span>\n    </p>\n  );\n}\n\nconst EMAIL_START = 'Hi Maren,\\n\\nThanks for sending the revised';\n\nconst EMAIL_TYPED = ' quote';\n\nconst CODE_START = 'const paidOrders = orders.';\n\nconst CODE_TYPED = 'fil';\n\n/** Long enough for the pause after typing and for the suggestion to come back. */\nconst SUGGESTION_WAIT_MS = 1500;\n\nexport default function Prompt05() {\n  const [email, setEmail] = useState(EMAIL_START);\n  const [code, setCode] = useState(CODE_START);\n  const [pressed, setPressed] = useState<HintKey | null>(null);\n  const emailHandle = useRef<GhostTextareaHandle>(null);\n  const codeHandle = useRef<GhostTextareaHandle>(null);\n  const { schedule } = useTimeouts();\n  const emailId = useId();\n  const codeId = useId();\n\n  function pressHint(key: HintKey) {\n    setPressed(key);\n    schedule(() => setPressed(null), KEY_PRESS_MS);\n  }\n\n  function typeEmail(typed: string) {\n    setEmail(`${EMAIL_START}${typed}`);\n  }\n\n  function typeCode(typed: string) {\n    setCode(`${CODE_START}${typed}`);\n  }\n\n  function resetFields() {\n    setEmail(EMAIL_START);\n    setCode(CODE_START);\n  }\n\n  const steps = [\n    ...typingSteps(EMAIL_TYPED, typeEmail, {\n      startAfter: 900,\n      characterMs: 70,\n    }),\n    { after: 80, run: () => emailHandle.current?.suggest() },\n    { after: SUGGESTION_WAIT_MS, run: () => emailHandle.current?.acceptWord() },\n    { after: 520, run: () => emailHandle.current?.acceptWord() },\n    { after: 700, run: () => emailHandle.current?.accept() },\n    { after: SUGGESTION_WAIT_MS, run: () => emailHandle.current?.accept() },\n    { after: 300, run: () => emailHandle.current?.dismiss() },\n    ...typingSteps(CODE_TYPED, typeCode, { startAfter: 700, characterMs: 90 }),\n    { after: 80, run: () => codeHandle.current?.suggest() },\n    { after: SUGGESTION_WAIT_MS, run: () => codeHandle.current?.accept() },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 2600,\n    onReset: resetFields,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div ref={ref} className='w-full max-w-[32rem]'>\n      <div className='flex flex-col gap-5'>\n        <div className='flex flex-col gap-1.5'>\n          <label htmlFor={emailId} className='text-[13px] font-medium'>\n            Reply to Maren\n          </label>\n          <GhostTextarea\n            id={emailId}\n            value={email}\n            onValueChange={setEmail}\n            suggest={suggestEmail}\n            rows={5}\n            placeholder='Write your reply'\n            showsUnfocused={isAutoplaying}\n            handleRef={emailHandle}\n            onSuggestionAccept={(kind) => pressHint(hintKeyOf(kind))}\n            onSuggestionDismiss={() => pressHint('escape')}\n          />\n        </div>\n        <div className='flex flex-col gap-1.5'>\n          <label htmlFor={codeId} className='text-[13px] font-medium'>\n            orders.ts, line 18\n          </label>\n          <GhostTextarea\n            id={codeId}\n            value={code}\n            onValueChange={setCode}\n            suggest={suggestCode}\n            monospace\n            singleLine\n            rows={1}\n            placeholder='Type a line of code'\n            showsUnfocused={isAutoplaying}\n            handleRef={codeHandle}\n            onSuggestionAccept={(kind) => pressHint(hintKeyOf(kind))}\n            onSuggestionDismiss={() => pressHint('escape')}\n          />\n        </div>\n        <KeyHints pressed={pressed} />\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/prompt/prompt-05.tsx"
    },
    {
      "path": "registry/ndeko/components/prompt/_parts/use-autosize.ts",
      "content": "'use client';\n\nimport { useLayoutEffect } from 'react';\n\nfunction fitHeight(textarea: HTMLTextAreaElement, maxHeight: number) {\n  textarea.style.height = 'auto';\n  const height = Math.min(textarea.scrollHeight, maxHeight);\n  textarea.style.height = `${height}px`;\n}\n\n/** Also fits again when the width changes, and when `remountKey` changes for a textarea shown again. */\nexport function useAutosize(\n  ref: React.RefObject<HTMLTextAreaElement | null>,\n  value: string,\n  maxHeight: number,\n  remountKey?: unknown\n) {\n  useLayoutEffect(() => {\n    const textarea = ref.current;\n    if (!textarea) {\n      return;\n    }\n    fitHeight(textarea, maxHeight);\n    let lastWidth = textarea.offsetWidth;\n    const observer = new ResizeObserver(() => {\n      const width = textarea.offsetWidth;\n      if (width === lastWidth) {\n        return;\n      }\n      lastWidth = width;\n      fitHeight(textarea, maxHeight);\n    });\n    observer.observe(textarea);\n    return () => observer.disconnect();\n  }, [ref, value, maxHeight, remountKey]);\n}\n\nexport function isSendKey(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n  const isEnter = event.key === 'Enter';\n  const isNewLine = event.shiftKey;\n  const isComposing = event.nativeEvent.isComposing;\n  const isPlainEnter = isEnter && !isNewLine;\n  return isPlainEnter && !isComposing;\n}\n\n/** Puts the caret after the last character once React has committed the new text. */\nexport function caretToEnd(ref: React.RefObject<HTMLTextAreaElement | null>) {\n  requestAnimationFrame(() => {\n    const textarea = ref.current;\n    if (!textarea) {\n      return;\n    }\n    const end = textarea.value.length;\n    textarea.focus();\n    textarea.setSelectionRange(end, end);\n  });\n}\n\n/** Keydown that started inside this element, not in a menu or popover portalled out of it. */\nexport function isOwnKey(event: React.KeyboardEvent<HTMLElement>) {\n  const target = event.target;\n  if (!(target instanceof Node)) {\n    return false;\n  }\n  return event.currentTarget.contains(target);\n}\n",
      "type": "registry:component",
      "target": "components/prompt/_parts/use-autosize.ts"
    }
  ],
  "categories": [
    "components",
    "prompt"
  ],
  "type": "registry:component"
}