{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prompt-08",
  "title": "Ask filter",
  "description": "Plain words become filter chips tied to their phrases by threads, an ambiguous week asks which one you mean, and the orders fold away as they stop matching.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/badge.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/live-region.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.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-08.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport {\n  useId,\n  useImperativeHandle,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { WordRoll } from '@/components/core/word-roll';\nimport {\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  keyDelayOf,\n  prefixesOf,\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  CalendarIcon,\n  CircleCheckIcon,\n  MapPinIcon,\n  WalletIcon,\n  XIcon,\n  type Icon,\n} from '@/registry/ndeko/lib/icons';\nimport {\n  fadePresence,\n  rowPresenceOf,\n  springOf,\n} from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { nounOf } from '@/registry/ndeko/lib/words';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\n\nimport { useAutosize } from './_parts/use-autosize';\n\nexport type OrderStatus =\n  'paid' | 'pending' | 'shipped' | 'refunded' | 'cancelled';\n\nexport type Order = {\n  id: string;\n  customer: string;\n  country: string;\n  /** ISO day, 2026-03-10. */\n  placedOn: string;\n  amount: number;\n  status: OrderStatus;\n};\n\ntype FilterKind = 'amount' | 'period' | 'country' | 'status';\n\ntype PeriodKind =\n  | 'today'\n  | 'yesterday'\n  | 'this-week'\n  | 'last-week'\n  | 'last-7-days'\n  | 'this-month'\n  | 'last-month';\n\nexport type WeekReading = 'calendar' | 'rolling';\n\nexport type AskFilterHandle = {\n  /** Replaces the question, as typing in the field does. */\n  type: (text: string) => void;\n  /** Shows a button held down: `week:rolling`, `week:calendar` or `chip:` and the key of a filter. */\n  press: (key: string) => void;\n  answerWeek: (reading: WeekReading) => void;\n  /** Removes a filter by its key, as the cross of its chip does. */\n  remove: (key: string) => void;\n  /** A new question with nothing removed and nothing answered yet. */\n  reset: (text: string) => void;\n};\n\ntype DayRange = {\n  from: string;\n  to: string;\n};\n\ntype Phrase = {\n  start: number;\n  end: number;\n  text: string;\n};\n\ntype FilterDetail =\n  | { kind: 'amount'; isOver: boolean; value: number }\n  | { kind: 'period'; period: PeriodKind }\n  | { kind: 'country'; country: string }\n  | { kind: 'status'; status: OrderStatus };\n\nexport type ParsedFilter = FilterDetail & {\n  key: string;\n  phrase: Phrase;\n};\n\ntype Matcher = {\n  pattern: RegExp;\n  detailOf: (match: RegExpMatchArray) => FilterDetail;\n};\n\nfunction amountOf(digits: string, thousands: string | undefined) {\n  const plain = digits.replace(/,/g, '');\n  const value = Number(plain);\n  if (thousands) {\n    return value * 1000;\n  }\n  return value;\n}\n\nfunction periodMatcher(period: PeriodKind, pattern: RegExp): Matcher {\n  return { pattern, detailOf: () => ({ kind: 'period', period }) };\n}\n\nfunction countryMatcher(country: string, pattern: RegExp): Matcher {\n  return { pattern, detailOf: () => ({ kind: 'country', country }) };\n}\n\nfunction statusMatcher(status: OrderStatus, pattern: RegExp): Matcher {\n  return { pattern, detailOf: () => ({ kind: 'status', status }) };\n}\n\nconst MATCHERS: Matcher[] = [\n  {\n    pattern:\n      /\\b(?:over|above|more than|greater than|at least)\\s+\\$?(\\d[\\d,]*)(k)?\\b/gi,\n    detailOf: (match) => ({\n      kind: 'amount',\n      isOver: true,\n      value: amountOf(match[1] ?? '0', match[2]),\n    }),\n  },\n  {\n    pattern: /\\b(?:under|below|less than|at most)\\s+\\$?(\\d[\\d,]*)(k)?\\b/gi,\n    detailOf: (match) => ({\n      kind: 'amount',\n      isOver: false,\n      value: amountOf(match[1] ?? '0', match[2]),\n    }),\n  },\n  periodMatcher('last-7-days', /\\b(?:last|past)\\s+(?:7|seven)\\s+days\\b/gi),\n  periodMatcher('last-week', /\\blast\\s+week\\b/gi),\n  periodMatcher('this-week', /\\bthis\\s+week\\b/gi),\n  periodMatcher('today', /\\btoday\\b/gi),\n  periodMatcher('yesterday', /\\byesterday\\b/gi),\n  periodMatcher('this-month', /\\bthis\\s+month\\b/gi),\n  periodMatcher('last-month', /\\blast\\s+month\\b/gi),\n  countryMatcher('Canada', /\\b(?:(?:to|in|from)\\s+)?canada\\b/gi),\n  countryMatcher('Germany', /\\b(?:(?:to|in|from)\\s+)?germany\\b/gi),\n  countryMatcher('France', /\\b(?:(?:to|in|from)\\s+)?france\\b/gi),\n  countryMatcher('Japan', /\\b(?:(?:to|in|from)\\s+)?japan\\b/gi),\n  countryMatcher('Brazil', /\\b(?:(?:to|in|from)\\s+)?brazil\\b/gi),\n  countryMatcher(\n    'United States',\n    /\\b(?:(?:to|in|from)\\s+)?(?:the\\s+(?:us|usa)|usa|united states)\\b/gi\n  ),\n  statusMatcher('paid', /\\bpaid\\b/gi),\n  statusMatcher('pending', /\\b(?:unpaid|pending)\\b/gi),\n  statusMatcher('shipped', /\\bshipped\\b/gi),\n  statusMatcher('refunded', /\\brefund(?:ed|s)?\\b/gi),\n  statusMatcher('cancelled', /\\bcancell?ed\\b/gi),\n];\n\nfunction overlapsAny(phrase: Phrase, taken: ParsedFilter[]) {\n  return taken.some((filter) => {\n    const startsBeforeEnd = phrase.start < filter.phrase.end;\n    const endsAfterStart = phrase.end > filter.phrase.start;\n    return startsBeforeEnd && endsAfterStart;\n  });\n}\n\nfunction byStart(first: ParsedFilter, second: ParsedFilter) {\n  return first.phrase.start - second.phrase.start;\n}\n\nexport function parseFilters(text: string) {\n  const found: ParsedFilter[] = [];\n  for (const matcher of MATCHERS) {\n    for (const match of text.matchAll(matcher.pattern)) {\n      const start = match.index ?? 0;\n      const phraseText = match[0];\n      const end = start + phraseText.length;\n      const phrase = { start, end, text: phraseText };\n      if (overlapsAny(phrase, found)) {\n        continue;\n      }\n      const detail = matcher.detailOf(match);\n      const normalized = phraseText.toLowerCase();\n      const key = `${detail.kind}:${normalized}`;\n      found.push({ ...detail, key, phrase });\n    }\n  }\n  return found.sort(byStart);\n}\n\nconst TODAY = '2026-03-18';\n\nconst PERIOD_RANGE: Record<Exclude<PeriodKind, 'last-week'>, DayRange> = {\n  today: { from: '2026-03-18', to: '2026-03-18' },\n  yesterday: { from: '2026-03-17', to: '2026-03-17' },\n  'this-week': { from: '2026-03-16', to: '2026-03-22' },\n  'last-7-days': { from: '2026-03-12', to: TODAY },\n  'this-month': { from: '2026-03-01', to: '2026-03-31' },\n  'last-month': { from: '2026-02-01', to: '2026-02-28' },\n};\n\nconst WEEK_RANGE: Record<WeekReading, DayRange> = {\n  calendar: { from: '2026-03-09', to: '2026-03-15' },\n  rolling: { from: '2026-03-12', to: TODAY },\n};\n\nconst PERIOD_LABEL: Record<Exclude<PeriodKind, 'last-week'>, string> = {\n  today: 'Today',\n  yesterday: 'Yesterday',\n  'this-week': 'This week',\n  'last-7-days': 'Last 7 days',\n  'this-month': 'March',\n  'last-month': 'February',\n};\n\nconst WEEK_LABEL: Record<WeekReading, string> = {\n  calendar: 'Mar 9 to 15',\n  rolling: 'Last 7 days',\n};\n\nconst STATUS_LABEL: Record<OrderStatus, string> = {\n  paid: 'Paid',\n  pending: 'Pending',\n  shipped: 'Shipped',\n  refunded: 'Refunded',\n  cancelled: 'Cancelled',\n};\n\nconst STATUS_BADGE: Record<\n  OrderStatus,\n  'success' | 'warning' | 'info' | 'secondary' | 'destructive'\n> = {\n  paid: 'success',\n  pending: 'warning',\n  shipped: 'info',\n  refunded: 'secondary',\n  cancelled: 'destructive',\n};\n\nconst KIND_ICON: Record<FilterKind, Icon> = {\n  amount: WalletIcon,\n  period: CalendarIcon,\n  country: MapPinIcon,\n  status: CircleCheckIcon,\n};\n\nconst MONTHS = [\n  'Jan',\n  'Feb',\n  'Mar',\n  'Apr',\n  'May',\n  'Jun',\n  'Jul',\n  'Aug',\n  'Sep',\n  'Oct',\n  'Nov',\n  'Dec',\n];\n\nconst MONEY = new Intl.NumberFormat('en-US', {\n  style: 'currency',\n  currency: 'USD',\n  maximumFractionDigits: 0,\n});\n\nfunction dayLabelOf(isoDay: string) {\n  const [, month, day] = isoDay.split('-');\n  const monthIndex = Number(month) - 1;\n  const monthName = MONTHS[monthIndex] ?? '';\n  const dayNumber = Number(day);\n  return `${monthName} ${dayNumber}`;\n}\n\nfunction isAmbiguous(filter: ParsedFilter) {\n  return filter.kind === 'period' && filter.period === 'last-week';\n}\n\nfunction rangeOf(filter: ParsedFilter, reading: WeekReading | null) {\n  if (filter.kind !== 'period') {\n    return null;\n  }\n  if (filter.period === 'last-week') {\n    if (!reading) {\n      return null;\n    }\n    return WEEK_RANGE[reading];\n  }\n  return PERIOD_RANGE[filter.period];\n}\n\nexport function labelOfFilter(\n  filter: ParsedFilter,\n  reading: WeekReading | null\n) {\n  if (filter.kind === 'amount') {\n    const amount = MONEY.format(filter.value);\n    if (filter.isOver) {\n      return `Over ${amount}`;\n    }\n    return `Under ${amount}`;\n  }\n  if (filter.kind === 'country') {\n    return filter.country;\n  }\n  if (filter.kind === 'status') {\n    return STATUS_LABEL[filter.status];\n  }\n  if (filter.period === 'last-week') {\n    if (!reading) {\n      return 'Last week?';\n    }\n    return WEEK_LABEL[reading];\n  }\n  return PERIOD_LABEL[filter.period];\n}\n\nfunction isInRange(order: Order, range: DayRange) {\n  const isAfterStart = order.placedOn >= range.from;\n  const isBeforeEnd = order.placedOn <= range.to;\n  return isAfterStart && isBeforeEnd;\n}\n\n/** A filter that still waits for an answer keeps nothing out: the question comes first. */\nfunction keepsOrder(\n  order: Order,\n  filter: ParsedFilter,\n  reading: WeekReading | null\n) {\n  if (filter.kind === 'amount') {\n    if (filter.isOver) {\n      return order.amount > filter.value;\n    }\n    return order.amount < filter.value;\n  }\n  if (filter.kind === 'country') {\n    return order.country === filter.country;\n  }\n  if (filter.kind === 'status') {\n    return order.status === filter.status;\n  }\n  const range = rangeOf(filter, reading);\n  if (!range) {\n    return true;\n  }\n  return isInRange(order, range);\n}\n\nfunction threadPathOf(container: DOMRect, phrase: DOMRect, chip: DOMRect) {\n  const phraseCentre = phrase.left + phrase.width / 2;\n  const chipCentre = chip.left + chip.width / 2;\n  const startX = phraseCentre - container.left;\n  const startY = phrase.bottom - container.top + 2;\n  const endX = chipCentre - container.left;\n  const endY = chip.top - container.top;\n  const bend = (endY - startY) / 2;\n  const firstControlY = startY + bend;\n  const secondControlY = endY - bend;\n  return `M ${startX} ${startY} C ${startX} ${firstControlY}, ${endX} ${secondControlY}, ${endX} ${endY}`;\n}\n\nfunction lastLineOf(element: Element) {\n  const lines = element.getClientRects();\n  const last = lines[lines.length - 1];\n  return last ?? element.getBoundingClientRect();\n}\n\nfunction placeThreads(container: HTMLElement) {\n  const box = container.getBoundingClientRect();\n  const threads = container.querySelectorAll<SVGPathElement>('[data-thread]');\n  threads.forEach((thread) => {\n    const key = thread.dataset.thread ?? '';\n    const escapedKey = CSS.escape(key);\n    const phrase = container.querySelector(`[data-phrase=\"${escapedKey}\"]`);\n    const chip = container.querySelector(`[data-chip=\"${escapedKey}\"]`);\n    if (!phrase) {\n      return;\n    }\n    if (!chip) {\n      return;\n    }\n    const phraseRect = lastLineOf(phrase);\n    const chipRect = chip.getBoundingClientRect();\n    const path = threadPathOf(box, phraseRect, chipRect);\n    thread.setAttribute('d', path);\n  });\n}\n\nconst FOLLOW_LAYOUT_MS = 500;\n\ntype PhraseLook = 'linked' | 'asking' | 'struck';\n\nfunction phraseClassOf(look: PhraseLook) {\n  if (look === 'struck') {\n    return 'line-through decoration-foreground/45';\n  }\n  if (look === 'asking') {\n    return 'underline decoration-dotted decoration-warning-foreground/80 underline-offset-4';\n  }\n  return 'underline decoration-primary-ink/45 underline-offset-4';\n}\n\ntype PhrasePiece = {\n  text: string;\n  key: string | null;\n  look: PhraseLook;\n};\n\nfunction piecesOfText(\n  text: string,\n  filters: ParsedFilter[],\n  dismissed: string[],\n  reading: WeekReading | null\n) {\n  const pieces: PhrasePiece[] = [];\n  let cursor = 0;\n  for (const filter of filters) {\n    const before = text.slice(cursor, filter.phrase.start);\n    if (before !== '') {\n      pieces.push({ text: before, key: null, look: 'linked' });\n    }\n    const isStruck = dismissed.includes(filter.key);\n    const isAsking = isAmbiguous(filter) && reading === null;\n    let look: PhraseLook = 'linked';\n    if (isAsking) {\n      look = 'asking';\n    }\n    if (isStruck) {\n      look = 'struck';\n    }\n    pieces.push({ text: filter.phrase.text, key: filter.key, look });\n    cursor = filter.phrase.end;\n  }\n  const rest = text.slice(cursor);\n  if (rest !== '') {\n    pieces.push({ text: rest, key: null, look: 'linked' });\n  }\n  return pieces;\n}\n\nconst FIELD_TEXT =\n  'border border-transparent px-2.5 py-2 text-base leading-6 md:text-[13px]';\n\ntype FilterChipProps = {\n  filter: ParsedFilter;\n  reading: WeekReading | null;\n  onRemove: (key: string) => void;\n  isRemovePressed: boolean;\n};\n\nfunction FilterChip({\n  filter,\n  reading,\n  onRemove,\n  isRemovePressed,\n}: FilterChipProps) {\n  const KindIcon = KIND_ICON[filter.kind];\n  const label = labelOfFilter(filter, reading);\n  const isAsking = isAmbiguous(filter) && reading === null;\n\n  return (\n    <span\n      data-chip={filter.key}\n      className={cn(\n        'hairline-ring flex h-6 items-center gap-1 rounded-full ps-2 pe-0.5 text-xs transition-colors duration-200',\n        chipToneOf(isAsking)\n      )}\n    >\n      <KindIcon className='size-3.5 shrink-0 opacity-70' />\n      <WordRoll text={label} />\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon-sm'\n        aria-label={`Remove the filter ${label}`}\n        onClick={() => onRemove(filter.key)}\n        className={cn('size-5 rounded-full', pressedQuietOf(isRemovePressed))}\n      >\n        <XIcon className='size-3' />\n      </Button>\n    </span>\n  );\n}\n\nfunction chipToneOf(isAsking: boolean) {\n  if (isAsking) {\n    return 'bg-warning/10 text-warning-foreground ring-warning/30';\n  }\n  return 'bg-card text-foreground ring-foreground/15 dark:bg-foreground/[0.06]';\n}\n\ntype AskFilterProps = {\n  orders: Order[];\n  value: string;\n  onValueChange: (value: string) => void;\n  /** Runs what the field, the chips and the question do, for a demonstration or a control beside them. */\n  handleRef?: React.Ref<AskFilterHandle>;\n  /** A demonstration drives the piece: its counts are not read aloud. */\n  isDemonstrated?: boolean;\n  className?: string;\n};\n\nexport function AskFilter({\n  orders,\n  value,\n  onValueChange,\n  handleRef,\n  isDemonstrated = false,\n  className,\n}: AskFilterProps) {\n  const [dismissed, setDismissed] = useState<string[]>([]);\n  const [reading, setReading] = useState<WeekReading | null>(null);\n  const { pressed, press } = usePress<string>();\n  const containerRef = useRef<HTMLDivElement>(null);\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const mirrorRef = useRef<HTMLDivElement>(null);\n  const fieldId = useId();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const spring = springOf(shouldReduceMotion);\n  const chipTransition = { ...fadePresence().transition, layout: spring };\n  const filters = parseFilters(value);\n  const live = filters.filter((filter) => !dismissed.includes(filter.key));\n  const pieces = piecesOfText(value, filters, dismissed, reading);\n  const asking = live.find((filter) => isAmbiguous(filter) && reading === null);\n  const shown = orders.filter((order) =>\n    live.every((filter) => keepsOrder(order, filter, reading))\n  );\n  const isEmpty = shown.length === 0;\n  const hasFilters = live.length > 0;\n  const appliedLabels = live.map((filter) => labelOfFilter(filter, reading));\n  const announcement = announcementOf(\n    shown.length,\n    orders.length,\n    appliedLabels,\n    asking\n  );\n  const threadKeys = live.map((filter) => filter.key).join('|');\n  useAutosize(textareaRef, value, 160);\n\n  useLayoutEffect(() => {\n    const element = containerRef.current;\n    if (!element) {\n      return;\n    }\n    const root: HTMLElement = element;\n    placeThreads(root);\n    const observer = new ResizeObserver(() => placeThreads(root));\n    observer.observe(root);\n    return () => observer.disconnect();\n  }, [value]);\n\n  // The chips glide to their new place when a filter comes, goes or gets its answer:\n  // the threads follow them for that long, and only then.\n  useLayoutEffect(() => {\n    const element = containerRef.current;\n    if (!element) {\n      return;\n    }\n    const root: HTMLElement = element;\n    const until = performance.now() + FOLLOW_LAYOUT_MS;\n    let frame = 0;\n    function follow(now: number) {\n      placeThreads(root);\n      if (now < until) {\n        frame = requestAnimationFrame(follow);\n      }\n    }\n    frame = requestAnimationFrame(follow);\n    return () => cancelAnimationFrame(frame);\n  }, [threadKeys, reading]);\n\n  function remove(key: string) {\n    setDismissed((current) => [...current, key]);\n  }\n\n  function reset(text: string) {\n    onValueChange(text);\n    setDismissed([]);\n    setReading(null);\n  }\n\n  function clearFilters() {\n    onValueChange('');\n    setDismissed([]);\n    setReading(null);\n    textareaRef.current?.focus();\n  }\n\n  function changeText(event: React.ChangeEvent<HTMLTextAreaElement>) {\n    applyText(event.target.value);\n  }\n\n  function applyText(next: string) {\n    onValueChange(next);\n    const nextKeys = parseFilters(next).map((filter) => filter.key);\n    setDismissed((current) => current.filter((key) => nextKeys.includes(key)));\n    const stillAsksWeek = nextKeys.some((key) =>\n      key.startsWith('period:last week')\n    );\n    if (!stillAsksWeek) {\n      setReading(null);\n    }\n  }\n\n  function blockNewLine(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n    if (event.key === 'Enter') {\n      event.preventDefault();\n    }\n  }\n\n  function followScroll(event: React.UIEvent<HTMLTextAreaElement>) {\n    const mirror = mirrorRef.current;\n    if (mirror) {\n      mirror.scrollTop = event.currentTarget.scrollTop;\n    }\n  }\n\n  useImperativeHandle(handleRef, () => ({\n    type: applyText,\n    press,\n    answerWeek: setReading,\n    remove,\n    reset,\n  }));\n\n  return (\n    <div\n      ref={containerRef}\n      className={cn('relative flex flex-col gap-3', className)}\n    >\n      <div className='flex flex-col gap-1.5'>\n        <label htmlFor={fieldId} className='text-[13px] font-medium'>\n          Show me\n        </label>\n        <div className='bg-card hairline-ring ring-foreground/12 dark:ring-foreground/15 has-[textarea:focus]:ring-ring/25 dark:bg-foreground/[0.04] relative rounded-md shadow-[0_1px_2px_rgb(0_0_0/0.05)] transition-shadow duration-150 has-[textarea:focus]:ring-[3px]'>\n          <div\n            ref={mirrorRef}\n            aria-hidden='true'\n            className={cn(\n              FIELD_TEXT,\n              'pointer-events-none absolute inset-0 overflow-hidden break-words whitespace-pre-wrap text-transparent'\n            )}\n          >\n            {pieces.map((piece, index) => {\n              if (piece.key === null) {\n                return <span key={`text:${index}`}>{piece.text}</span>;\n              }\n              return (\n                <span\n                  key={`${index}:${piece.key}`}\n                  data-phrase={piece.key}\n                  className={cn(\n                    'rounded-[2px] transition-[text-decoration-color] duration-300 starting:decoration-transparent',\n                    phraseClassOf(piece.look)\n                  )}\n                >\n                  {piece.text}\n                </span>\n              );\n            })}\n          </div>\n          <textarea\n            ref={textareaRef}\n            id={fieldId}\n            rows={1}\n            value={value}\n            onChange={changeText}\n            onKeyDown={blockNewLine}\n            onScroll={followScroll}\n            placeholder='orders over 500 from last week to Canada'\n            spellCheck={false}\n            className={cn(\n              FIELD_TEXT,\n              'placeholder:text-muted-foreground/75 relative block w-full resize-none bg-transparent outline-none'\n            )}\n          />\n        </div>\n      </div>\n      <svg\n        aria-hidden='true'\n        className='pointer-events-none absolute inset-0 size-full overflow-visible'\n      >\n        <AnimatePresence initial={false}>\n          {live.map((filter) => (\n            <motion.path\n              key={filter.key}\n              data-thread={filter.key}\n              fill='none'\n              strokeWidth='1'\n              className={threadToneOf(isAmbiguous(filter) && reading === null)}\n              initial={{ pathLength: 0, opacity: 0 }}\n              animate={{ pathLength: 1, opacity: 1 }}\n              exit={{ opacity: 0, transition: { duration: 0.12 } }}\n              transition={{ duration: threadDurationOf(shouldReduceMotion) }}\n            />\n          ))}\n        </AnimatePresence>\n      </svg>\n      <AnimatedSize>\n        <ul\n          aria-label='Filters'\n          className='flex min-h-6 flex-wrap gap-1.5 pt-3'\n        >\n          <AnimatePresence initial={false} mode='popLayout'>\n            {live.map((filter) => (\n              <motion.li\n                key={filter.key}\n                layout\n                layoutDependency={threadKeys}\n                initial={{ opacity: 0, scale: 0.95 }}\n                animate={{ opacity: 1, scale: 1 }}\n                exit={{ opacity: 0, scale: 0.95 }}\n                transition={chipTransition}\n              >\n                <FilterChip\n                  filter={filter}\n                  reading={reading}\n                  onRemove={remove}\n                  isRemovePressed={pressed === `chip:${filter.key}`}\n                />\n              </motion.li>\n            ))}\n          </AnimatePresence>\n          {!hasFilters && (\n            <li className='text-muted-foreground text-xs'>\n              No filter yet: try an amount, a period, a country or a status\n            </li>\n          )}\n        </ul>\n        <AnimatePresence initial={false}>\n          {asking && (\n            <motion.div\n              key='asking'\n              className='@container overflow-hidden'\n              {...rowPresence}\n            >\n              <div className='bg-warning/10 mt-3 flex flex-col gap-2 rounded-lg p-2.5 @lg:flex-row @lg:items-center'>\n                <p className='text-warning-foreground min-w-0 flex-1 text-xs leading-5'>\n                  “{asking.phrase.text}” could mean two things. Calendar week or\n                  the last 7 days?\n                </p>\n                <div className='flex shrink-0 flex-wrap gap-1.5'>\n                  <Button\n                    type='button'\n                    variant='outline'\n                    size='sm'\n                    onClick={() => setReading('calendar')}\n                    className={pressedQuietOf(pressed === 'week:calendar')}\n                  >\n                    Calendar week, {WEEK_LABEL.calendar}\n                  </Button>\n                  <Button\n                    type='button'\n                    variant='outline'\n                    size='sm'\n                    onClick={() => setReading('rolling')}\n                    className={pressedQuietOf(pressed === 'week:rolling')}\n                  >\n                    Last 7 days\n                  </Button>\n                </div>\n              </div>\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </AnimatedSize>\n      <OrderTable\n        orders={shown}\n        total={orders.length}\n        rowPresence={rowPresence}\n      />\n      <AnimatePresence initial={false}>\n        {isEmpty && (\n          <motion.div key='empty' className='overflow-hidden' {...rowPresence}>\n            <div className='bg-foreground/[0.03] dark:bg-foreground/[0.05] flex flex-col items-center gap-3 rounded-lg px-4 py-6 text-center'>\n              <p className='text-muted-foreground text-[13px] text-balance'>\n                No orders match {appliedLabels.join(', ')}\n              </p>\n              <Button\n                type='button'\n                variant='outline'\n                size='sm'\n                onClick={clearFilters}\n              >\n                <XIcon />\n                Clear filters\n              </Button>\n            </div>\n          </motion.div>\n        )}\n      </AnimatePresence>\n      <LiveRegion message={spokenUnless(isDemonstrated, announcement)} />\n    </div>\n  );\n}\n\nfunction threadToneOf(isAsking: boolean) {\n  if (isAsking) {\n    return 'stroke-warning';\n  }\n  return 'stroke-foreground/30';\n}\n\nfunction threadDurationOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return 0;\n  }\n  return 0.45;\n}\n\nfunction announcementOf(\n  shownCount: number,\n  total: number,\n  labels: string[],\n  asking: ParsedFilter | undefined\n) {\n  const orders = nounOf(total, 'order');\n  const applied = labels.join(', ');\n  const base = `${shownCount} of ${total} ${orders}`;\n  if (asking) {\n    return `${base}. “${asking.phrase.text}” needs an answer: calendar week or the last 7 days`;\n  }\n  if (applied === '') {\n    return base;\n  }\n  return `${base}: ${applied}`;\n}\n\ntype OrderTableProps = {\n  orders: Order[];\n  total: number;\n  rowPresence: ReturnType<typeof rowPresenceOf>;\n};\n\n/** In a narrow card the customer and the day step aside, so the country takes the free width. */\nconst ROW_GRID =\n  'grid grid-cols-[3rem_minmax(0,1fr)_4.75rem_3.5rem] items-center gap-1.5 px-2 @xl:gap-2 @xl:grid-cols-[3.5rem_minmax(0,1fr)_6.5rem_3.5rem_5rem_4.5rem]';\n\nfunction OrderTable({ orders, total, rowPresence }: OrderTableProps) {\n  const ordersWord = nounOf(total, 'order');\n\n  return (\n    <div className='@container flex flex-col gap-1.5'>\n      <p className='text-muted-foreground px-2 text-xs'>\n        <MotionNumber value={orders.length} /> of {total} {ordersWord}\n      </p>\n      <div role='table' aria-label='Orders' className='text-[13px]'>\n        <div role='rowgroup'>\n          <div\n            role='row'\n            className={cn(\n              ROW_GRID,\n              'text-muted-foreground hairline-b border-border h-8 text-xs'\n            )}\n          >\n            <span role='columnheader'>Order</span>\n            <span role='columnheader' className='hidden @xl:block'>\n              Customer\n            </span>\n            <span role='columnheader'>Country</span>\n            <span role='columnheader' className='hidden @xl:block'>\n              Placed\n            </span>\n            <span role='columnheader'>Status</span>\n            <span role='columnheader' className='text-end'>\n              Amount\n            </span>\n          </div>\n        </div>\n        <div role='rowgroup'>\n          <AnimatePresence initial={false}>\n            {orders.map((order) => (\n              <motion.div\n                key={order.id}\n                role='row'\n                className='hairline-b border-border overflow-hidden'\n                {...rowPresence}\n              >\n                <div className={cn(ROW_GRID, 'h-9')}>\n                  <span\n                    role='cell'\n                    className='text-muted-foreground font-mono text-xs'\n                  >\n                    {order.id}\n                  </span>\n                  <span role='cell' className='hidden truncate @xl:block'>\n                    {order.customer}\n                  </span>\n                  <span role='cell' className='truncate'>\n                    {order.country}\n                  </span>\n                  <span\n                    role='cell'\n                    className='text-muted-foreground hidden tabular-nums @xl:block'\n                  >\n                    {dayLabelOf(order.placedOn)}\n                  </span>\n                  <span role='cell'>\n                    <Badge variant={STATUS_BADGE[order.status]}>\n                      {STATUS_LABEL[order.status]}\n                    </Badge>\n                  </span>\n                  <span role='cell' className='text-end tabular-nums'>\n                    {MONEY.format(order.amount)}\n                  </span>\n                </div>\n              </motion.div>\n            ))}\n          </AnimatePresence>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nconst ORDERS: Order[] = [\n  {\n    id: '#1042',\n    customer: 'Northwind Cafe',\n    country: 'Canada',\n    placedOn: '2026-03-10',\n    amount: 640,\n    status: 'paid',\n  },\n  {\n    id: '#1043',\n    customer: 'Halvorsen Tools',\n    country: 'Germany',\n    placedOn: '2026-03-11',\n    amount: 220,\n    status: 'paid',\n  },\n  {\n    id: '#1044',\n    customer: 'Maple and Rye',\n    country: 'Canada',\n    placedOn: '2026-03-13',\n    amount: 890,\n    status: 'shipped',\n  },\n  {\n    id: '#1045',\n    customer: 'Sora Studio',\n    country: 'Japan',\n    placedOn: '2026-03-14',\n    amount: 1240,\n    status: 'pending',\n  },\n  {\n    id: '#1046',\n    customer: 'Bluefin Market',\n    country: 'Canada',\n    placedOn: '2026-03-16',\n    amount: 515,\n    status: 'paid',\n  },\n  {\n    id: '#1047',\n    customer: 'Atelier Brun',\n    country: 'France',\n    placedOn: '2026-03-16',\n    amount: 95,\n    status: 'refunded',\n  },\n  {\n    id: '#1048',\n    customer: 'Cedar Lane Books',\n    country: 'Canada',\n    placedOn: '2026-03-04',\n    amount: 730,\n    status: 'paid',\n  },\n  {\n    id: '#1049',\n    customer: 'Pampa Coffee',\n    country: 'Brazil',\n    placedOn: '2026-03-17',\n    amount: 310,\n    status: 'shipped',\n  },\n  {\n    id: '#1050',\n    customer: 'Lakeside Outfitters',\n    country: 'Canada',\n    placedOn: '2026-03-17',\n    amount: 460,\n    status: 'pending',\n  },\n  {\n    id: '#1051',\n    customer: 'Kestrel Labs',\n    country: 'United States',\n    placedOn: '2026-03-12',\n    amount: 1980,\n    status: 'paid',\n  },\n];\n\nconst EXAMPLES = [\n  'paid orders under 300',\n  'refunded this month',\n  'orders to Japan this week',\n];\n\nconst START_QUERY = 'orders over 500 from last week to Canada';\n\ntype DemoQuestion = {\n  text: string;\n  /** The key of the filter the demonstration removes at the end. */\n  removes: string;\n};\n\n/** A round types one of these questions, a different one each time. Both leave the week to be asked. */\nconst DEMO_QUESTIONS: DemoQuestion[] = [\n  { text: 'paid orders to Canada last week', removes: 'status:paid' },\n  { text: 'orders from last week to Japan', removes: 'country:to japan' },\n];\n\nexport default function Prompt08() {\n  const [query, setQuery] = useState(START_QUERY);\n  const [exampleRound, setExampleRound] = useState(0);\n  const [round, setRound] = useState(0);\n  const filter = useRef<AskFilterHandle>(null);\n  const question = DEMO_QUESTIONS[round % DEMO_QUESTIONS.length];\n  const removedChip = `chip:${question.removes}`;\n\n  function tryExample(example: string) {\n    setQuery(example);\n    setExampleRound((current) => current + 1);\n  }\n\n  function resetDemo() {\n    filter.current?.reset(START_QUERY);\n    setRound((current) => current + 1);\n  }\n\n  const typing = prefixesOf(question.text).map((typed, index) => ({\n    after: keyDelayOf(index, 700, 52),\n    run: () => filter.current?.type(typed),\n  }));\n  const steps: AutoplayStep[] = [\n    { after: 1800, run: () => filter.current?.type('') },\n    ...typing,\n    { after: 1100, run: () => filter.current?.press('week:rolling') },\n    { after: PRESS_LEAD_MS, run: () => filter.current?.answerWeek('rolling') },\n    { after: 1900, run: () => filter.current?.press(removedChip) },\n    {\n      after: PRESS_LEAD_MS,\n      run: () => filter.current?.remove(question.removes),\n    },\n    { after: 1700, run: hold },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 2400,\n    onReset: resetDemo,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div ref={ref} className='flex w-full max-w-[40rem] flex-col gap-3'>\n      <AskFilter\n        key={exampleRound}\n        orders={ORDERS}\n        value={query}\n        onValueChange={setQuery}\n        handleRef={filter}\n        isDemonstrated={isAutoplaying}\n        className='bg-card hairline-ring ring-border rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'\n      />\n      <div className='flex flex-wrap items-center gap-1.5 px-1'>\n        <span className='text-muted-foreground text-xs'>Try</span>\n        {EXAMPLES.map((example) => (\n          <Button\n            key={example}\n            type='button'\n            variant='ghost'\n            size='sm'\n            onClick={() => tryExample(example)}\n            className='text-muted-foreground h-6 px-2'\n          >\n            {example}\n          </Button>\n        ))}\n      </div>\n      <p className='text-muted-foreground px-1 text-[11px]'>\n        Today is Wednesday, March 18 in this demo\n      </p>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/prompt/prompt-08.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"
}