{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prompt-12",
  "title": "Mention picker",
  "description": "Typing @ opens files, symbols, diffs, docs and pages that filter with marks and move with the arrows and Tab, and the picked item flies into the composer as a chip while the token total rolls.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/kbd.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/textarea.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/utils.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/prompt/prompt-12.tsx",
      "content": "'use client';\n\nimport {\n  AnimatePresence,\n  LayoutGroup,\n  motion,\n  type Transition,\n} from 'motion/react';\nimport { useId, useImperativeHandle, useRef, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport {\n  typingSteps,\n  useAutoplay,\n  type AutoplayStep,\n} 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 {\n  hold,\n  PRESS_LEAD_MS,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  ArrowUpIcon,\n  BookOpenIcon,\n  CodeIcon,\n  FileTextIcon,\n  GitCompareIcon,\n  GlobeIcon,\n  XIcon,\n} from '@/registry/ndeko/lib/icons';\nimport {\n  fadePresence,\n  risePresenceOf,\n  springOf,\n} from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf, nounOf } from '@/registry/ndeko/lib/words';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Textarea } from '@/registry/ndeko/ui/textarea';\n\nimport { ListKeys, type ListKey } from './_parts/list-keys';\nimport { includesQuery, Marked } from './_parts/marked';\nimport { activeIdOf, wrappedIndexOf } from './_parts/option-list';\nimport { useActiveRowInView } from './_parts/use-active-row';\nimport { isSendKey, useAutosize } from './_parts/use-autosize';\n\nexport type MentionKind = 'file' | 'symbol' | 'diff' | 'doc' | 'page';\n\nexport type MentionItem = {\n  id: string;\n  kind: MentionKind;\n  name: string;\n  path: string;\n  /** An estimate of what the item adds to the context. */\n  tokens: number;\n};\n\nexport type MentionMessage = {\n  text: string;\n  mentions: MentionItem[];\n};\n\nexport type MentionComposerHandle = {\n  move: (step: number) => void;\n  jumpGroup: (step: number) => void;\n  pickHighlighted: () => void;\n};\n\ntype MentionToken = {\n  start: number;\n  end: number;\n  query: string;\n};\n\ntype MentionGroup = {\n  kind: MentionKind;\n  title: string;\n  items: MentionItem[];\n};\n\nconst KINDS: MentionKind[] = ['file', 'symbol', 'diff', 'doc', 'page'];\n\nconst KIND_TITLES: Record<MentionKind, string> = {\n  file: 'Files',\n  symbol: 'Symbols',\n  diff: 'Diffs',\n  doc: 'Docs',\n  page: 'Pages',\n};\n\nconst KIND_ICONS: Record<MentionKind, React.ReactNode> = {\n  file: <FileTextIcon />,\n  symbol: <CodeIcon />,\n  diff: <GitCompareIcon />,\n  doc: <BookOpenIcon />,\n  page: <GlobeIcon />,\n};\n\nconst SHELL = [\n  'bg-card hairline-ring ring-foreground/12 dark:ring-foreground/15 has-[textarea:focus]:ring-ring/25 relative flex flex-col rounded-xl p-2',\n  'shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-shadow duration-150 has-[textarea:focus]:ring-[3px]',\n].join(' ');\n\nconst TILE =\n  'keycap-3d text-muted-foreground flex shrink-0 items-center justify-center [&_svg:not([class*=\"size-\"])]:size-3.5';\n\nconst TOKEN_FORMAT = new Intl.NumberFormat('en-US');\n\nfunction tokenTextOf(tokens: number) {\n  return TOKEN_FORMAT.format(tokens);\n}\n\nfunction totalTokensOf(mentions: MentionItem[]) {\n  let total = 0;\n  for (const mention of mentions) {\n    total += mention.tokens;\n  }\n  return total;\n}\n\nfunction mentionTokenAt(value: string, cursor: number): MentionToken | null {\n  const before = value.slice(0, cursor);\n  const at = before.lastIndexOf('@');\n  if (at < 0) {\n    return null;\n  }\n  const previous = before[at - 1];\n  const isAtStart = at === 0;\n  const isAfterSpace = previous !== undefined && /\\s/.test(previous);\n  const startsWord = isAtStart || isAfterSpace;\n  if (!startsWord) {\n    return null;\n  }\n  const query = before.slice(at + 1);\n  if (/\\s/.test(query)) {\n    return null;\n  }\n  return { start: at, end: cursor, query };\n}\n\nfunction textWithoutToken(value: string, token: MentionToken) {\n  const before = value.slice(0, token.start);\n  const after = value.slice(token.end);\n  const endsWithSpace = /\\s$/.test(before);\n  const startsWithSpace = /^\\s/.test(after);\n  const hasDoubleSpace = endsWithSpace && startsWithSpace;\n  if (hasDoubleSpace) {\n    return { text: `${before}${after.slice(1)}`, caret: before.length };\n  }\n  return { text: `${before}${after}`, caret: before.length };\n}\n\n/** At the end of the text the caret is left unset, so text written from outside still lands after it. */\nfunction caretAfterOf(next: { text: string; caret: number }) {\n  const isAtEnd = next.caret >= next.text.length;\n  if (isAtEnd) {\n    return null;\n  }\n  return next.caret;\n}\n\nfunction matchesOf(\n  items: MentionItem[],\n  mentions: MentionItem[],\n  query: string\n) {\n  const takenIds = mentions.map((mention) => mention.id);\n  return items.filter((item) => {\n    const isFree = !takenIds.includes(item.id);\n    const haystack = `${item.name} ${item.path}`;\n    return isFree && includesQuery(haystack, query);\n  });\n}\n\nfunction groupsOf(matches: MentionItem[]) {\n  const groups: MentionGroup[] = [];\n  for (const kind of KINDS) {\n    const items = matches.filter((item) => item.kind === kind);\n    if (items.length > 0) {\n      groups.push({ kind, title: KIND_TITLES[kind], items });\n    }\n  }\n  return groups;\n}\n\nfunction groupIndexOf(groups: MentionGroup[], activeId: string | null) {\n  return groups.findIndex((group) => {\n    return group.items.some((item) => item.id === activeId);\n  });\n}\n\nfunction stepOfTab(event: React.KeyboardEvent) {\n  if (event.shiftKey) {\n    return -1;\n  }\n  return 1;\n}\n\nfunction activeToneOf(isActive: boolean) {\n  if (isActive) {\n    return 'bg-foreground/5';\n  }\n  return undefined;\n}\n\nfunction sendLabelOf(hasContent: boolean) {\n  if (hasContent) {\n    return 'Send';\n  }\n  return 'Send, write something first';\n}\n\ntype OptionRowProps = {\n  item: MentionItem;\n  query: string;\n  optionId: string;\n  isActive: boolean;\n  glide: Transition;\n  onHover: (itemId: string) => void;\n  onPick: (item: MentionItem) => void;\n};\n\nfunction OptionRow({\n  item,\n  query,\n  optionId,\n  isActive,\n  glide,\n  onHover,\n  onPick,\n}: OptionRowProps) {\n  return (\n    <div\n      id={optionId}\n      role='option'\n      aria-selected={isActive}\n      onMouseMove={() => onHover(item.id)}\n      onClick={() => onPick(item)}\n      className={cn(\n        'flex h-11 cursor-default items-center gap-2.5 rounded-lg px-2 transition-colors duration-100',\n        activeToneOf(isActive)\n      )}\n    >\n      <motion.span\n        layoutId={`mention-tile-${item.id}`}\n        transition={glide}\n        className={cn(TILE, 'size-7 rounded-md')}\n      >\n        {KIND_ICONS[item.kind]}\n      </motion.span>\n      <span className='flex min-w-0 flex-1 flex-col'>\n        <span className='truncate text-[13px] font-medium'>\n          <Marked text={item.name} query={query} />\n        </span>\n        <span className='text-muted-foreground truncate font-mono text-[11px]'>\n          <Marked text={item.path} query={query} />\n        </span>\n      </span>\n      <span className='text-muted-foreground shrink-0 text-xs tabular-nums'>\n        {tokenTextOf(item.tokens)}\n      </span>\n    </div>\n  );\n}\n\ntype MentionListProps = {\n  groups: MentionGroup[];\n  query: string;\n  listId: string;\n  activeId: string | null;\n  optionIdOf: (itemId: string) => string;\n  listRef: React.RefObject<HTMLDivElement | null>;\n  pressedKey: ListKey | null;\n  glide: Transition;\n  onHover: (itemId: string) => void;\n  onPick: (item: MentionItem) => void;\n};\n\nfunction MentionList({\n  groups,\n  query,\n  listId,\n  activeId,\n  optionIdOf,\n  listRef,\n  pressedKey,\n  glide,\n  onHover,\n  onPick,\n}: MentionListProps) {\n  const hasGroups = groups.length > 1;\n  const isEmpty = groups.length === 0;\n\n  return (\n    <div className='surface-raised flex flex-col overflow-hidden rounded-xl'>\n      <div\n        ref={listRef}\n        id={listId}\n        role='listbox'\n        aria-label='Context to attach'\n        onMouseDown={(event) => event.preventDefault()}\n        className='relative flex max-h-56 flex-col overflow-y-auto p-1'\n      >\n        {isEmpty && (\n          <p className='text-muted-foreground px-2 py-6 text-center text-xs'>\n            Nothing matches “{query}”. Keep typing, or press Escape.\n          </p>\n        )}\n        {groups.map((group) => (\n          <div\n            key={group.kind}\n            role='group'\n            aria-label={group.title}\n            className='flex flex-col'\n          >\n            <p\n              aria-hidden='true'\n              className='text-muted-foreground px-2 pt-2 pb-1 text-xs font-medium'\n            >\n              {group.title}\n            </p>\n            {group.items.map((item) => (\n              <OptionRow\n                key={item.id}\n                item={item}\n                query={query}\n                optionId={optionIdOf(item.id)}\n                isActive={item.id === activeId}\n                glide={glide}\n                onHover={onHover}\n                onPick={onPick}\n              />\n            ))}\n          </div>\n        ))}\n      </div>\n      <ListKeys\n        pressed={pressedKey}\n        hasGroups={hasGroups}\n        enterLabel='attaches'\n        className='bg-foreground/[0.03] px-3 py-2'\n      />\n    </div>\n  );\n}\n\ntype MentionChipProps = {\n  item: MentionItem;\n  glide: Transition;\n  onRemove: (itemId: string) => void;\n};\n\nfunction MentionChip({ item, glide, onRemove }: MentionChipProps) {\n  const fade = fadePresence();\n\n  return (\n    <motion.li\n      {...fade}\n      className='bg-foreground/[0.05] dark:bg-foreground/[0.07] flex h-8 max-w-full items-center gap-1.5 rounded-lg ps-1 pe-0.5'\n    >\n      <motion.span\n        layoutId={`mention-tile-${item.id}`}\n        transition={glide}\n        className={cn(TILE, 'size-6 rounded-[5px]')}\n      >\n        {KIND_ICONS[item.kind]}\n      </motion.span>\n      <span className='min-w-0 truncate text-xs font-medium'>{item.name}</span>\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon-sm'\n        aria-label={`Remove ${item.name}`}\n        onClick={() => onRemove(item.id)}\n        className='text-muted-foreground size-6'\n      >\n        <XIcon className='size-3' />\n      </Button>\n    </motion.li>\n  );\n}\n\nexport type MentionComposerProps = {\n  items: MentionItem[];\n  value: string;\n  onValueChange: (value: string) => void;\n  mentions: MentionItem[];\n  onMentionsChange: (mentions: MentionItem[]) => void;\n  /** `floating` hangs the list over the page above the composer. `inline` draws it under the composer and keeps its place. */\n  listPlacement?: 'inline' | 'floating';\n  /** Shows the list without focus, for a demonstration or a preview nobody types in. */\n  showsUnfocused?: boolean;\n  onSend?: (message: MentionMessage) => void;\n  handleRef?: React.Ref<MentionComposerHandle>;\n  /** The key a demonstration is holding down in the list. */\n  pressedKey?: ListKey | null;\n  placeholder?: string;\n  className?: string;\n};\n\nexport function MentionComposer({\n  items,\n  value,\n  onValueChange,\n  mentions,\n  onMentionsChange,\n  listPlacement = 'floating',\n  showsUnfocused = false,\n  onSend,\n  handleRef,\n  pressedKey = null,\n  placeholder = 'Ask something, or type @ to attach context',\n  className,\n}: MentionComposerProps) {\n  const [isFocused, setIsFocused] = useState(false);\n  const [highlightedId, setHighlightedId] = useState<string | null>(null);\n  const [dismissedStart, setDismissedStart] = useState<number | null>(null);\n  const [caret, setCaret] = useState<number | null>(null);\n  const [notice, setNotice] = useState('');\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const listRef = useRef<HTMLDivElement>(null);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const risePresence = risePresenceOf(shouldReduceMotion);\n  const glide = springOf(shouldReduceMotion);\n  const layoutGroup = useId();\n  const listId = useId();\n  const optionPrefix = useId();\n  const cursor = Math.min(caret ?? value.length, value.length);\n  const token = mentionTokenAt(value, cursor);\n  const isDismissed = token !== null && token.start === dismissedStart;\n  const isShowing = isFocused || showsUnfocused;\n  const isOpen = token !== null && !isDismissed && isShowing;\n  const query = token?.query ?? '';\n  const matches = matchesOf(items, mentions, query);\n  const groups = groupsOf(matches);\n  const flat = groups.flatMap((group) => group.items);\n  const activeId = activeIdOf(flat, highlightedId);\n  const totalTokens = totalTokensOf(mentions);\n  const hasMentions = mentions.length > 0;\n  const hasContent = hasMentions || value.trim() !== '';\n  const resultsMessage = resultsMessageOf(isOpen, flat.length, showsUnfocused);\n  const activeDescendant = activeDescendantOf(isOpen, optionPrefix, activeId);\n  useAutosize(textareaRef, value, 120);\n\n  function optionIdOf(itemId: string) {\n    return `${optionPrefix}-${itemId}`;\n  }\n\n  useActiveRowInView(listRef, activeDescendant);\n\n  function move(step: number) {\n    const ids = flat.map((item) => item.id);\n    const current = ids.indexOf(activeId ?? '');\n    const next = wrappedIndexOf(current, step, ids.length);\n    const id = ids[next];\n    if (id) {\n      setHighlightedId(id);\n    }\n  }\n\n  function jumpGroup(step: number) {\n    const current = groupIndexOf(groups, activeId);\n    const next = wrappedIndexOf(current, step, groups.length);\n    const target = groups[next]?.items[0];\n    if (target) {\n      setHighlightedId(target.id);\n    }\n  }\n\n  function pick(item: MentionItem) {\n    if (!token) {\n      return;\n    }\n    const next = textWithoutToken(value, token);\n    onValueChange(next.text);\n    onMentionsChange([...mentions, item]);\n    setCaret(caretAfterOf(next));\n    setDismissedStart(null);\n    setNotice(`${item.name} attached`);\n    requestAnimationFrame(() => {\n      const textarea = textareaRef.current;\n      const isTyping = document.activeElement === textarea;\n      if (textarea && isTyping) {\n        textarea.setSelectionRange(next.caret, next.caret);\n      }\n    });\n  }\n\n  function pickHighlighted() {\n    const item = flat.find((entry) => entry.id === activeId);\n    if (item) {\n      pick(item);\n    }\n  }\n\n  useImperativeHandle(handleRef, () => ({ move, jumpGroup, pickHighlighted }));\n\n  function removeMention(itemId: string) {\n    const removed = mentions.find((mention) => mention.id === itemId);\n    onMentionsChange(mentions.filter((mention) => mention.id !== itemId));\n    setNotice(`${removed?.name ?? 'Mention'} removed`);\n  }\n\n  function dismiss() {\n    if (token) {\n      setDismissedStart(token.start);\n    }\n  }\n\n  function send() {\n    if (!hasContent) {\n      return;\n    }\n    const text = value.trim();\n    onSend?.({ text, mentions });\n    onValueChange('');\n    onMentionsChange([]);\n    setCaret(null);\n    setNotice('Message sent');\n  }\n\n  function changeValue(event: React.ChangeEvent<HTMLTextAreaElement>) {\n    setCaret(event.target.selectionStart);\n    setDismissedStart(null);\n    onValueChange(event.target.value);\n  }\n\n  function followSelection(event: React.SyntheticEvent<HTMLTextAreaElement>) {\n    setCaret(event.currentTarget.selectionStart);\n  }\n\n  function handleKeys(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n    const isComposing = event.nativeEvent.isComposing;\n    if (isComposing) {\n      return;\n    }\n    if (isOpen) {\n      const isEnter = event.key === 'Enter' && !event.shiftKey;\n      const canJump = event.key === 'Tab' && groups.length > 1;\n      if (event.key === 'ArrowDown') {\n        event.preventDefault();\n        move(1);\n        return;\n      }\n      if (event.key === 'ArrowUp') {\n        event.preventDefault();\n        move(-1);\n        return;\n      }\n      if (isEnter) {\n        event.preventDefault();\n        pickHighlighted();\n        return;\n      }\n      if (canJump) {\n        event.preventDefault();\n        jumpGroup(stepOfTab(event));\n        return;\n      }\n      if (event.key === 'Escape') {\n        event.preventDefault();\n        dismiss();\n        return;\n      }\n    }\n    if (isSendKey(event)) {\n      event.preventDefault();\n      send();\n      return;\n    }\n    const isBackspace = event.key === 'Backspace';\n    const canRemoveLast = isBackspace && value === '' && hasMentions;\n    if (canRemoveLast) {\n      event.preventDefault();\n      removeMention(mentions[mentions.length - 1].id);\n    }\n  }\n\n  const list = (\n    <MentionList\n      groups={groups}\n      query={query}\n      listId={listId}\n      activeId={activeId}\n      optionIdOf={optionIdOf}\n      listRef={listRef}\n      pressedKey={pressedKey}\n      glide={glide}\n      onHover={setHighlightedId}\n      onPick={pick}\n    />\n  );\n\n  return (\n    <LayoutGroup id={layoutGroup}>\n      <div className={cn('relative flex w-full flex-col gap-2', className)}>\n        <div className={SHELL}>\n          <AnimatedSize>\n            <ul\n              aria-label='Attached context'\n              className={cn(\n                'flex flex-wrap gap-1.5',\n                hasMentions && 'px-1 pt-1 pb-1.5'\n              )}\n            >\n              <AnimatePresence initial={false}>\n                {mentions.map((item) => (\n                  <MentionChip\n                    key={item.id}\n                    item={item}\n                    glide={glide}\n                    onRemove={removeMention}\n                  />\n                ))}\n              </AnimatePresence>\n            </ul>\n            <Textarea\n              ref={textareaRef}\n              rows={1}\n              value={value}\n              onChange={changeValue}\n              onSelect={followSelection}\n              onKeyDown={handleKeys}\n              onFocus={() => setIsFocused(true)}\n              onBlur={() => setIsFocused(false)}\n              aria-label='Message'\n              aria-autocomplete='list'\n              aria-controls={listId}\n              aria-activedescendant={activeDescendant}\n              placeholder={placeholder}\n              className='max-h-none min-h-10 border-0 bg-transparent px-2 py-1.5 shadow-none ring-0 focus-visible:ring-0 dark:bg-transparent'\n            />\n          </AnimatedSize>\n          <div className='flex items-center gap-2 pt-1'>\n            <p className='text-muted-foreground flex min-w-0 flex-1 items-baseline gap-1 ps-2 text-xs'>\n              {hasMentions && (\n                <span className='truncate'>\n                  <MotionNumber value={mentions.length} />{' '}\n                  {nounOf(mentions.length, 'mention')}, about{' '}\n                  <MotionNumber value={totalTokens} /> tokens\n                </span>\n              )}\n              {!hasMentions && (\n                <span className='truncate'>\n                  <Kbd>@</Kbd> attaches files, symbols, diffs, docs and pages\n                </span>\n              )}\n            </p>\n            <Button\n              type='button'\n              size='icon'\n              aria-label={sendLabelOf(hasContent)}\n              disabled={!hasContent}\n              focusableWhenDisabled\n              onClick={send}\n            >\n              <ArrowUpIcon />\n            </Button>\n          </div>\n        </div>\n        <AnimatePresence initial={false}>\n          {isOpen && listPlacement === 'inline' && (\n            <motion.div key='list' {...risePresence}>\n              {list}\n            </motion.div>\n          )}\n          {isOpen && listPlacement === 'floating' && (\n            <motion.div\n              key='list'\n              {...risePresence}\n              className='absolute inset-x-0 bottom-full z-20 mb-2'\n            >\n              {list}\n            </motion.div>\n          )}\n        </AnimatePresence>\n        <LiveRegion message={resultsMessage} />\n        <LiveRegion message={spokenUnless(showsUnfocused, notice)} />\n      </div>\n    </LayoutGroup>\n  );\n}\n\nfunction activeDescendantOf(\n  isOpen: boolean,\n  optionPrefix: string,\n  activeId: string | null\n) {\n  if (!isOpen || activeId === null) {\n    return undefined;\n  }\n  return `${optionPrefix}-${activeId}`;\n}\n\nfunction resultsMessageOf(\n  isOpen: boolean,\n  count: number,\n  isDemonstrating: boolean\n) {\n  if (!isOpen || isDemonstrating) {\n    return '';\n  }\n  return countOf(count, 'result');\n}\n\nconst ITEMS: MentionItem[] = [\n  {\n    id: 'invoice-file',\n    kind: 'file',\n    name: 'invoice.ts',\n    path: 'src/lib/invoice.ts',\n    tokens: 1240,\n  },\n  {\n    id: 'invoice-test',\n    kind: 'file',\n    name: 'invoice-totals.test.ts',\n    path: 'tests/invoice-totals.test.ts',\n    tokens: 860,\n  },\n  {\n    id: 'format-total',\n    kind: 'symbol',\n    name: 'formatInvoiceTotal',\n    path: 'src/lib/money.ts:42',\n    tokens: 180,\n  },\n  {\n    id: 'round-cents',\n    kind: 'symbol',\n    name: 'roundToCents',\n    path: 'src/lib/money.ts:18',\n    tokens: 120,\n  },\n  {\n    id: 'staged-diff',\n    kind: 'diff',\n    name: 'Invoice rounding, staged',\n    path: '3 files changed',\n    tokens: 540,\n  },\n  {\n    id: 'last-commit',\n    kind: 'diff',\n    name: 'Last commit',\n    path: '5 files changed',\n    tokens: 1100,\n  },\n  {\n    id: 'refund-policy',\n    kind: 'doc',\n    name: 'Refund policy',\n    path: 'docs/refunds.md',\n    tokens: 420,\n  },\n  {\n    id: 'invoice-numbering',\n    kind: 'doc',\n    name: 'Invoice numbering',\n    path: 'docs/invoice-numbering.md',\n    tokens: 310,\n  },\n  {\n    id: 'orders-page',\n    kind: 'page',\n    name: 'Orders dashboard',\n    path: 'shop.example/admin/orders',\n    tokens: 650,\n  },\n  {\n    id: 'returns-page',\n    kind: 'page',\n    name: 'Returns policy',\n    path: 'shop.example/returns-policy',\n    tokens: 380,\n  },\n];\n\nconst QUESTION = 'Why does the total differ by a cent?';\n\nconst START_VALUE = `${QUESTION} @`;\n\nconst AFTER_FIRST = `${QUESTION} `;\n\nconst RESTING_VALUE = `${QUESTION} @pol`;\n\nconst RESTING_MENTIONS = [ITEMS[0]];\n\nconst NO_MENTIONS: MentionItem[] = [];\n\nfunction restingValueOf(isResting: boolean) {\n  if (isResting) {\n    return RESTING_VALUE;\n  }\n  return START_VALUE;\n}\n\nfunction restingMentionsOf(isResting: boolean) {\n  if (isResting) {\n    return RESTING_MENTIONS;\n  }\n  return NO_MENTIONS;\n}\n\nfunction footnoteOf(sentCount: number) {\n  if (sentCount > 0) {\n    return `Sent with ${countOf(sentCount, 'mention')}`;\n  }\n  return 'Illustrative token estimates on sample files';\n}\n\nfunction MentionDemo({ isResting }: { isResting: boolean }) {\n  const [value, setValue] = useState(restingValueOf(isResting));\n  const [mentions, setMentions] = useState(restingMentionsOf(isResting));\n  const [sentCount, setSentCount] = useState(0);\n  const composer = useRef<MentionComposerHandle>(null);\n  const { pressed, press } = usePress<ListKey>();\n\n  function resetDemo() {\n    setValue(START_VALUE);\n    setMentions(NO_MENTIONS);\n  }\n\n  function typeFirst(typed: string) {\n    setValue(`${QUESTION} ${typed}`);\n  }\n\n  function typeSecond(typed: string) {\n    setValue(`${AFTER_FIRST}${typed}`);\n  }\n\n  function noteSent(message: MentionMessage) {\n    setSentCount(message.mentions.length);\n  }\n\n  const steps: AutoplayStep[] = [\n    ...typingSteps('@inv', typeFirst, { startAfter: 1500, characterMs: 140 }),\n    { after: 1000, run: () => press('move') },\n    { after: PRESS_LEAD_MS, run: () => composer.current?.move(1) },\n    { after: 800, run: () => press('move') },\n    { after: PRESS_LEAD_MS, run: () => composer.current?.move(-1) },\n    { after: 900, run: () => press('enter') },\n    { after: PRESS_LEAD_MS, run: () => composer.current?.pickHighlighted() },\n    ...typingSteps('@pol', typeSecond, { startAfter: 1500, characterMs: 140 }),\n    { after: 1000, run: () => press('tab') },\n    { after: PRESS_LEAD_MS, run: () => composer.current?.jumpGroup(1) },\n    { after: 900, run: () => press('enter') },\n    { after: PRESS_LEAD_MS, run: () => composer.current?.pickHighlighted() },\n    { after: 2800, run: hold },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 1600,\n    onReset: resetDemo,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='@container flex min-h-[27rem] w-full max-w-[32rem] flex-col gap-2'\n    >\n      <MentionComposer\n        items={ITEMS}\n        value={value}\n        onValueChange={setValue}\n        mentions={mentions}\n        onMentionsChange={setMentions}\n        listPlacement='inline'\n        showsUnfocused={isAutoplaying}\n        onSend={noteSent}\n        handleRef={composer}\n        pressedKey={pressed}\n      />\n      <p className='text-muted-foreground h-5 px-1 text-xs'>\n        {footnoteOf(sentCount)}\n      </p>\n    </div>\n  );\n}\n\nexport default function Prompt12() {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const restKey = String(shouldReduceMotion);\n\n  return <MentionDemo key={restKey} isResting={shouldReduceMotion} />;\n}\n",
      "type": "registry:component",
      "target": "components/prompt/prompt-12.tsx"
    },
    {
      "path": "registry/ndeko/components/prompt/_parts/list-keys.tsx",
      "content": "import { cn } from '@/registry/ndeko/lib/utils';\nimport { Kbd, KbdGroup } from '@/registry/ndeko/ui/kbd';\n\nexport type ListKey = 'move' | 'enter' | 'tab' | 'escape';\n\nconst KEY_MOTION = 'transition-[scale,background-color,color] duration-150';\n\nconst PRESSED = 'scale-90 bg-primary/15 text-primary-ink';\n\nfunction pressedOf(isPressed: boolean) {\n  if (isPressed) {\n    return PRESSED;\n  }\n  return undefined;\n}\n\ntype ListKeysProps = {\n  /** The key a demonstration is holding down. */\n  pressed: ListKey | null;\n  /** Adds Tab, for a list that has groups to jump between. */\n  hasGroups?: boolean;\n  enterLabel?: string;\n  className?: string;\n};\n\nexport function ListKeys({\n  pressed,\n  hasGroups = false,\n  enterLabel = 'picks',\n  className,\n}: ListKeysProps) {\n  const moveClass = cn(KEY_MOTION, pressedOf(pressed === 'move'));\n  const enterClass = cn(KEY_MOTION, pressedOf(pressed === 'enter'));\n  const tabClass = cn(KEY_MOTION, pressedOf(pressed === 'tab'));\n  const escapeClass = cn(KEY_MOTION, pressedOf(pressed === 'escape'));\n\n  return (\n    <p\n      className={cn(\n        'text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-xs',\n        className\n      )}\n    >\n      <span className='inline-flex items-center gap-1'>\n        <KbdGroup aria-hidden='true'>\n          <Kbd className={moveClass}>↑</Kbd>\n          <Kbd className={moveClass}>↓</Kbd>\n        </KbdGroup>\n        <span className='sr-only'>Up and Down arrows</span>\n        move\n      </span>\n      <span className='inline-flex items-center gap-1'>\n        <Kbd className={enterClass}>Enter</Kbd> {enterLabel}\n      </span>\n      {hasGroups && (\n        <span className='inline-flex items-center gap-1'>\n          <Kbd className={tabClass}>Tab</Kbd> next group\n        </span>\n      )}\n      <span className='inline-flex items-center gap-1'>\n        <Kbd className={escapeClass}>Esc</Kbd> closes\n      </span>\n    </p>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/prompt/_parts/list-keys.tsx"
    },
    {
      "path": "registry/ndeko/components/prompt/_parts/marked.tsx",
      "content": "type TextPiece = { text: string; isMatch: boolean };\n\nexport function piecesOf(text: string, query: string): TextPiece[] {\n  const needle = query.trim().toLowerCase();\n  if (needle === '') {\n    return [{ text, isMatch: false }];\n  }\n  const haystack = text.toLowerCase();\n  const pieces: TextPiece[] = [];\n  let cursor = 0;\n  let found = haystack.indexOf(needle, cursor);\n  while (found >= 0) {\n    const before = text.slice(cursor, found);\n    const matchEnd = found + needle.length;\n    const match = text.slice(found, matchEnd);\n    if (before !== '') {\n      pieces.push({ text: before, isMatch: false });\n    }\n    pieces.push({ text: match, isMatch: true });\n    cursor = matchEnd;\n    found = haystack.indexOf(needle, cursor);\n  }\n  const rest = text.slice(cursor);\n  if (rest !== '') {\n    pieces.push({ text: rest, isMatch: false });\n  }\n  return pieces;\n}\n\nexport function includesQuery(text: string, query: string) {\n  const needle = query.trim().toLowerCase();\n  if (needle === '') {\n    return true;\n  }\n  const haystack = text.toLowerCase();\n  return haystack.includes(needle);\n}\n\ntype MarkedProps = {\n  text: string;\n  query: string;\n};\n\nexport function Marked({ text, query }: MarkedProps) {\n  const pieces = piecesOf(text, query);\n\n  return (\n    <>\n      {pieces.map((piece, index) => {\n        if (piece.isMatch) {\n          return (\n            <mark\n              key={index}\n              className='bg-warning/25 text-foreground rounded-[3px] px-px'\n            >\n              {piece.text}\n            </mark>\n          );\n        }\n        return <span key={index}>{piece.text}</span>;\n      })}\n    </>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/prompt/_parts/marked.tsx"
    },
    {
      "path": "registry/ndeko/components/prompt/_parts/option-list.ts",
      "content": "/** The row after a step through a list that wraps round, or the first one when nothing is active. */\nexport function wrappedIndexOf(current: number, step: number, count: number) {\n  if (count === 0) {\n    return -1;\n  }\n  const hasCurrent = current >= 0;\n  if (!hasCurrent) {\n    return firstIndexFor(step, count);\n  }\n  const moved = current + step;\n  const shifted = moved + count;\n  return shifted % count;\n}\n\nfunction firstIndexFor(step: number, count: number) {\n  if (step > 0) {\n    return 0;\n  }\n  return count - 1;\n}\n\n/** Scrolls the list itself, never the page: `list` must be positioned so `offsetTop` is measured from it. */\nexport function keepRowInView(list: HTMLElement, row: HTMLElement) {\n  const rowTop = row.offsetTop;\n  const rowBottom = rowTop + row.offsetHeight;\n  const viewTop = list.scrollTop;\n  const viewBottom = viewTop + list.clientHeight;\n  if (rowTop < viewTop) {\n    list.scrollTop = rowTop;\n    return;\n  }\n  if (rowBottom > viewBottom) {\n    list.scrollTop = rowBottom - list.clientHeight;\n  }\n}\n\n/** The highlighted row if it is still listed, otherwise the first one. */\nexport function activeIdOf(\n  items: { id: string }[],\n  highlightedId: string | null\n) {\n  const stillListed = items.some((item) => item.id === highlightedId);\n  if (stillListed) {\n    return highlightedId;\n  }\n  return items[0]?.id ?? null;\n}\n",
      "type": "registry:component",
      "target": "components/prompt/_parts/option-list.ts"
    },
    {
      "path": "registry/ndeko/components/prompt/_parts/use-active-row.ts",
      "content": "'use client';\n\nimport { useEffect } from 'react';\n\nimport { keepRowInView } from './option-list';\n\n/** Keeps the active row of a list in view as it changes, scrolling the list and never the page. */\nexport function useActiveRowInView(\n  listRef: React.RefObject<HTMLElement | null>,\n  rowId: string | undefined\n) {\n  useEffect(() => {\n    if (rowId === undefined) {\n      return;\n    }\n    const list = listRef.current;\n    const row = document.getElementById(rowId);\n    if (list && row) {\n      keepRowInView(list, row);\n    }\n  }, [listRef, rowId]);\n}\n",
      "type": "registry:component",
      "target": "components/prompt/_parts/use-active-row.ts"
    },
    {
      "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"
}