{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "faqs-03",
  "title": "Searchable questions",
  "description": "A search that ignores accents and marks its matches in place as you type, topic chips whose counts roll with the words, answers that open where they are with a link to copy, and a person to ask when nothing matches.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/accordion.json",
    "https://ui.ndekocode.dev/r/avatar.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/toggle-group.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-session.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/index.tsx",
      "content": "'use client';\n\nimport { useEffect, useId } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { WordRoll } from '@/components/core/word-roll';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf, nounOf } from '@/registry/ndeko/lib/words';\nimport { Accordion } from '@/registry/ndeko/ui/accordion';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport { AskPerson } from './ask-person';\nimport { Collapse } from './collapse';\nimport { PERSON, QUESTIONS, SECTION, TOPICS, type Question } from './data';\nimport { anchorOf, linkOf, useLinkedQuestion } from './hash';\nimport { QuestionRow } from './question-row';\nimport { SearchField } from './search-field';\nimport { hitsOf, inTopic, topicCountsOf, wordsOf } from './search';\nimport {\n  COPIED_MS,\n  INITIAL,\n  LOOP_AFTER_MS,\n  reducer,\n  RESTING,\n  SCRIPT,\n} from './session';\nimport { TopicChips } from './topic-chips';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\nconst QUESTION_WORDS = ['question', 'questions'];\n\nfunction scrollBehaviorOf(shouldReduceMotion: boolean): ScrollBehavior {\n  if (shouldReduceMotion) {\n    return 'auto';\n  }\n  return 'smooth';\n}\n\nfunction spokenLineOf(\n  copiedId: string | null,\n  shown: number,\n  isEmpty: boolean\n) {\n  if (copiedId !== null) {\n    return 'Link copied';\n  }\n  if (isEmpty) {\n    return `No question matches. ${PERSON.firstName} can answer by email.`;\n  }\n  return `${countOf(shown, 'question')} shown`;\n}\n\nfunction dividerOf(isFirstShown: boolean) {\n  if (isFirstShown) {\n    return undefined;\n  }\n  return 'hairline-t border-border';\n}\n\nfunction idsOf(value: unknown[]) {\n  return value.filter((item): item is string => typeof item === 'string');\n}\n\nexport default function Faqs03() {\n  const {\n    ref,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n    takeOver,\n  } = useSession(SESSION);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const listId = useId();\n  const linkedFromAddress = useLinkedQuestion();\n  const words = wordsOf(state.query);\n  const hits = hitsOf(state.query);\n  const counts = topicCountsOf(hits);\n  const visible = inTopic(hits, state.topic);\n  const shownIds = visible.map((hit) => hit.question.id);\n  const firstShownId = shownIds[0];\n  const isEmpty = visible.length === 0;\n  const isInOtherTopics = isEmpty && hits.length > 0;\n  const topic = TOPICS.find((candidate) => candidate.id === state.topic);\n  const topicLabel = topic?.label ?? 'this topic';\n  const shownLine = spokenLineOf(state.copiedId, visible.length, isEmpty);\n  const message = spokenUnless(isAutoplaying, shownLine);\n  const canReplay = isFinished && !isAutoplaying;\n  const copiedId = state.copiedId;\n  const linkedId = state.linkedId;\n\n  useKeptHeight(ref);\n\n  useEffect(() => {\n    if (linkedFromAddress === null) {\n      return;\n    }\n    takeOver();\n    act({ type: 'linked', id: linkedFromAddress });\n  }, [linkedFromAddress, takeOver, act]);\n\n  useEffect(() => {\n    if (linkedId === null) {\n      return;\n    }\n    const frame = requestAnimationFrame(() => {\n      const selector = `[id=\"${anchorOf(linkedId)}\"]`;\n      const row = ref.current?.querySelector<HTMLElement>(selector);\n      const behavior = scrollBehaviorOf(shouldReduceMotion);\n      row?.scrollIntoView({ block: 'nearest', behavior });\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [linkedId, shouldReduceMotion, ref]);\n\n  useEffect(() => {\n    if (copiedId === null) {\n      return;\n    }\n    const timer = setTimeout(() => act({ type: 'copyCleared' }), COPIED_MS);\n    return () => clearTimeout(timer);\n  }, [copiedId, act]);\n\n  async function copyLink(questionId: string) {\n    try {\n      await navigator.clipboard.writeText(linkOf(questionId));\n    } catch {\n      return;\n    }\n    act({ type: 'copied', id: questionId });\n  }\n\n  function hitOf(question: Question) {\n    const found = visible.find((hit) => hit.question.id === question.id);\n    return found ?? { question, inQuestion: false, inAnswer: false };\n  }\n\n  function changeOpen(value: unknown[]) {\n    act({ type: 'opened', ids: idsOf(value) });\n  }\n\n  return (\n    <div ref={ref} className='@container min-h-[58rem]'>\n      <section className='px-4 py-16 @2xl:px-6 @2xl:py-24 @5xl:px-8'>\n        <div className='mx-auto flex max-w-3xl flex-col gap-8'>\n          <header className='flex flex-col gap-3'>\n            <h2 className='text-2xl font-semibold text-balance @2xl:text-3xl'>\n              {SECTION.title}\n            </h2>\n            <p className='text-muted-foreground max-w-xl text-base text-pretty'>\n              {SECTION.description}\n            </p>\n          </header>\n          <div className='flex flex-col gap-3'>\n            <SearchField\n              query={state.query}\n              listId={listId}\n              isClearPressed={pressed === 'clear'}\n              onType={(value) => act({ type: 'typed', value })}\n              onClear={() => act({ type: 'cleared' })}\n            />\n            <TopicChips\n              topic={state.topic}\n              counts={counts}\n              pressed={pressed}\n              onPick={(next) => act({ type: 'topicPicked', topic: next })}\n            />\n          </div>\n          <div id={listId} className='flex flex-col gap-4'>\n            <Accordion value={state.openIds} onValueChange={changeOpen}>\n              {QUESTIONS.map((question) => (\n                <Collapse\n                  key={question.id}\n                  isShown={shownIds.includes(question.id)}\n                >\n                  <div\n                    className={cn(\n                      'px-[3px] py-[3px]',\n                      dividerOf(firstShownId === question.id)\n                    )}\n                  >\n                    <QuestionRow\n                      hit={hitOf(question)}\n                      words={words}\n                      isTriggerPressed={pressed === `trigger-${question.id}`}\n                      isCopyPressed={pressed === `copy-${question.id}`}\n                      isCopied={copiedId === question.id}\n                      onCopy={copyLink}\n                    />\n                  </div>\n                </Collapse>\n              ))}\n            </Accordion>\n            <Collapse isShown={isEmpty}>\n              <div className='p-[3px]'>\n                <AskPerson\n                  query={state.query}\n                  topicLabel={topicLabel}\n                  isInOtherTopics={isInOtherTopics}\n                  isClearPressed={pressed === 'clear-search'}\n                  onClear={() => act({ type: 'cleared' })}\n                  onAllTopics={() => act({ type: 'topicPicked', topic: 'all' })}\n                />\n              </div>\n            </Collapse>\n            <div className='flex min-h-8 items-center justify-between gap-3'>\n              <p className='text-muted-foreground flex items-baseline gap-1 text-xs tabular-nums'>\n                <MotionNumber value={visible.length} />\n                <WordRoll\n                  text={nounOf(visible.length, 'question')}\n                  labels={QUESTION_WORDS}\n                />\n              </p>\n              <ReplayButton\n                isShown={canReplay}\n                onReplay={restart}\n                label='Replay'\n              />\n            </div>\n          </div>\n        </div>\n      </section>\n      <LiveRegion message={message} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/ask-person.tsx",
      "content": "'use client';\n\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Avatar } from '@/registry/ndeko/ui/avatar';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport { PERSON } from './data';\n\ntype AskPersonProps = {\n  query: string;\n  topicLabel: string;\n  isInOtherTopics: boolean;\n  isClearPressed: boolean;\n  onClear: () => void;\n  onAllTopics: () => void;\n};\n\nexport function AskPerson({\n  query,\n  topicLabel,\n  isInOtherTopics,\n  isClearPressed,\n  onClear,\n  onAllTopics,\n}: AskPersonProps) {\n  const title = `Nothing matches “${query}”`;\n  const titleInTopic = `Nothing in ${topicLabel} matches “${query}”`;\n  let heading = title;\n  if (isInOtherTopics) {\n    heading = titleInTopic;\n  }\n\n  return (\n    <div className='bg-foreground/[0.04] flex flex-col gap-4 rounded-xl p-4 @md:flex-row @md:items-center @md:p-5'>\n      <Avatar seed={PERSON.name} className='size-10' />\n      <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n        <p className='text-sm font-medium break-words'>{heading}</p>\n        <p className='text-muted-foreground text-[13px] text-pretty'>\n          {PERSON.name}, {PERSON.role}, answers by email within a day.\n        </p>\n      </div>\n      <div className='flex flex-wrap gap-2'>\n        <Button nativeButton={false} render={<a href={PERSON.href} />}>\n          Ask {PERSON.firstName}\n        </Button>\n        {isInOtherTopics && (\n          <Button variant='outline' onClick={onAllTopics}>\n            Search all topics\n          </Button>\n        )}\n        <Button\n          variant='ghost'\n          onClick={onClear}\n          className={cn(pressedQuietOf(isClearPressed))}\n        >\n          Clear search\n        </Button>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/ask-person.tsx"
    },
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/collapse.tsx",
      "content": "import { cn } from '@/registry/ndeko/lib/utils';\n\ntype CollapseProps = {\n  isShown: boolean;\n  className?: string;\n  children: React.ReactNode;\n};\n\n/**\n * Rows that come and go while a list is filtered stay in the page: a closed row has no height,\n * no opacity and takes no focus, so the others close ranks and nothing is mounted again.\n */\nexport function Collapse({ isShown, className, children }: CollapseProps) {\n  return (\n    <div\n      data-shown={isShown}\n      inert={!isShown}\n      className={cn(\n        'grid grid-rows-[1fr] opacity-100 transition-[grid-template-rows,opacity] duration-200 ease-(--ease-out-strong) data-[shown=false]:grid-rows-[0fr] data-[shown=false]:opacity-0 motion-reduce:transition-none',\n        className\n      )}\n    >\n      <div className='min-h-0 overflow-hidden'>{children}</div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/collapse.tsx"
    },
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/hash.ts",
      "content": "import { useSyncExternalStore } from 'react';\n\nimport { QUESTIONS } from './data';\n\nconst ANCHOR_PREFIX = 'faq-';\n\nexport function anchorOf(questionId: string) {\n  return `${ANCHOR_PREFIX}${questionId}`;\n}\n\nexport function questionIdOfHash(hash: string) {\n  const anchor = hash.replace('#', '');\n  const found = QUESTIONS.find((question) => anchorOf(question.id) === anchor);\n  return found?.id ?? null;\n}\n\nexport function linkOf(questionId: string) {\n  const { origin, pathname } = window.location;\n  return `${origin}${pathname}#${anchorOf(questionId)}`;\n}\n\nfunction subscribe(onChange: () => void) {\n  window.addEventListener('hashchange', onChange);\n  return () => window.removeEventListener('hashchange', onChange);\n}\n\nfunction currentHash() {\n  return window.location.hash;\n}\n\nfunction serverHash() {\n  return '';\n}\n\nexport function useLinkedQuestion() {\n  const hash = useSyncExternalStore(subscribe, currentHash, serverHash);\n  return questionIdOfHash(hash);\n}\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/hash.ts"
    },
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/marked-text.tsx",
      "content": "import { markedPartsOf, type MarkedPart } from './search';\n\n/** A mark keeps the browser's yellow unless its background is set. */\nconst MARK = 'rounded-[3px] bg-primary/15 text-inherit';\n\nfunction Part({ part }: { part: MarkedPart }) {\n  if (part.isMatch) {\n    return <mark className={MARK}>{part.text}</mark>;\n  }\n  return <span>{part.text}</span>;\n}\n\ntype MarkedTextProps = {\n  text: string;\n  words: string[];\n};\n\nexport function MarkedText({ text, words }: MarkedTextProps) {\n  const parts = markedPartsOf(text, words);\n\n  return (\n    <>\n      {parts.map((part) => (\n        <Part key={part.key} part={part} />\n      ))}\n    </>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/marked-text.tsx"
    },
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/question-row.tsx",
      "content": "'use client';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { CheckIcon, LinkIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport {\n  AccordionContent,\n  AccordionItem,\n  AccordionTrigger,\n} from '@/registry/ndeko/ui/accordion';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\n\nimport { anchorOf } from './hash';\nimport { MarkedText } from './marked-text';\nimport type { Hit } from './search';\n\nconst COPY_LABELS = ['Copy link', 'Link copied'];\n\nfunction copyLabelOf(isCopied: boolean) {\n  if (isCopied) {\n    return 'Link copied';\n  }\n  return 'Copy link';\n}\n\ntype QuestionRowProps = {\n  hit: Hit;\n  words: string[];\n  isTriggerPressed: boolean;\n  isCopyPressed: boolean;\n  isCopied: boolean;\n  onCopy: (questionId: string) => void;\n};\n\nexport function QuestionRow({\n  hit,\n  words,\n  isTriggerPressed,\n  isCopyPressed,\n  isCopied,\n  onCopy,\n}: QuestionRowProps) {\n  const { question } = hit;\n  const isSearching = words.length > 0;\n  const missesQuestion = !hit.inQuestion;\n  const matchesAnswer = hit.inAnswer;\n  const isAnswerOnly = isSearching && missesQuestion && matchesAnswer;\n  const copyLabel = copyLabelOf(isCopied);\n\n  return (\n    <AccordionItem\n      value={question.id}\n      id={anchorOf(question.id)}\n      className='scroll-mt-4'\n    >\n      <AccordionTrigger\n        className={cn('text-sm', pressedQuietOf(isTriggerPressed))}\n      >\n        <span className='flex min-w-0 flex-col gap-0.5'>\n          <span className='text-balance'>\n            <MarkedText text={question.question} words={words} />\n          </span>\n          {isAnswerOnly && (\n            <span className='text-muted-foreground text-xs font-normal'>\n              Matches in the answer\n            </span>\n          )}\n        </span>\n      </AccordionTrigger>\n      <AccordionContent className='px-1 text-sm leading-relaxed text-pretty'>\n        <p>\n          <MarkedText text={question.answer} words={words} />\n        </p>\n        <Button\n          type='button'\n          variant='ghost'\n          size='sm'\n          onClick={() => onCopy(question.id)}\n          className={cn(\n            'text-muted-foreground mt-3',\n            pressedQuietOf(isCopyPressed)\n          )}\n        >\n          <Swap swapKey={String(isCopied)}>\n            {isCopied && <CheckIcon />}\n            {!isCopied && <LinkIcon />}\n          </Swap>\n          <WordRoll text={copyLabel} labels={COPY_LABELS} />\n        </Button>\n      </AccordionContent>\n    </AccordionItem>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/question-row.tsx"
    },
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/search-field.tsx",
      "content": "'use client';\n\nimport { useId } from 'react';\n\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { SearchIcon, XIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Input } from '@/registry/ndeko/ui/input';\n\nimport { SECTION } from './data';\n\ntype SearchFieldProps = {\n  query: string;\n  listId: string;\n  isClearPressed: boolean;\n  onType: (value: string) => void;\n  onClear: () => void;\n};\n\nexport function SearchField({\n  query,\n  listId,\n  isClearPressed,\n  onType,\n  onClear,\n}: SearchFieldProps) {\n  const inputId = useId();\n  const hasQuery = query !== '';\n\n  function clearOnEscape(event: React.KeyboardEvent<HTMLInputElement>) {\n    if (event.key === 'Escape' && hasQuery) {\n      event.preventDefault();\n      onClear();\n    }\n  }\n\n  return (\n    <div className='relative'>\n      <label htmlFor={inputId} className='sr-only'>\n        {SECTION.searchLabel}\n      </label>\n      <SearchIcon className='text-muted-foreground pointer-events-none absolute start-3 top-1/2 size-4 -translate-y-1/2' />\n      <Input\n        id={inputId}\n        type='search'\n        size='lg'\n        autoComplete='off'\n        spellCheck={false}\n        placeholder={SECTION.searchPlaceholder}\n        aria-controls={listId}\n        value={query}\n        onChange={(event) => onType(event.target.value)}\n        onKeyDown={clearOnEscape}\n        className='ps-9 pe-10'\n      />\n      {hasQuery && (\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Clear the search'\n          onClick={onClear}\n          className={cn(\n            'text-muted-foreground absolute end-1 top-1/2 -translate-y-1/2',\n            pressedQuietOf(isClearPressed)\n          )}\n        >\n          <XIcon />\n        </Button>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/search-field.tsx"
    },
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/search.ts",
      "content": "import { QUESTIONS, TOPICS, type Question, type TopicFilter } from './data';\n\nexport type MarkedPart = {\n  key: string;\n  text: string;\n  isMatch: boolean;\n};\n\nexport type Hit = {\n  question: Question;\n  inQuestion: boolean;\n  inAnswer: boolean;\n};\n\ntype Folded = {\n  text: string;\n  /** For each folded character, where its source character starts and ends in the original text. */\n  starts: number[];\n  ends: number[];\n};\n\ntype Range = {\n  start: number;\n  end: number;\n};\n\ntype Indexed = {\n  question: Question;\n  questionText: string;\n  answerText: string;\n};\n\nconst ACCENTS = /\\p{M}/gu;\n\n/** One letter matches half the list, so a word counts from two letters. */\nconst MIN_WORD_LENGTH = 2;\n\nfunction foldedCharOf(char: string) {\n  const decomposed = char.normalize('NFD');\n  const bare = decomposed.replace(ACCENTS, '');\n  return bare.toLowerCase();\n}\n\nexport function foldedOf(text: string): Folded {\n  const starts: number[] = [];\n  const ends: number[] = [];\n  let folded = '';\n  let position = 0;\n  for (const char of text) {\n    const part = foldedCharOf(char);\n    const end = position + char.length;\n    for (let index = 0; index < part.length; index += 1) {\n      starts.push(position);\n      ends.push(end);\n    }\n    folded += part;\n    position = end;\n  }\n  return { text: folded, starts, ends };\n}\n\nexport function wordsOf(query: string) {\n  const folded = foldedOf(query).text;\n  const pieces = folded.split(/\\s+/);\n  return pieces.filter((piece) => piece.length >= MIN_WORD_LENGTH);\n}\n\nconst INDEX: Indexed[] = QUESTIONS.map((question) => ({\n  question,\n  questionText: foldedOf(question.question).text,\n  answerText: foldedOf(question.answer).text,\n}));\n\nfunction holdsWord(entry: Indexed, word: string) {\n  const inQuestion = entry.questionText.includes(word);\n  const inAnswer = entry.answerText.includes(word);\n  return inQuestion || inAnswer;\n}\n\nfunction hitOf(entry: Indexed, words: string[]): Hit | null {\n  const holdsEveryWord = words.every((word) => holdsWord(entry, word));\n  if (!holdsEveryWord) {\n    return null;\n  }\n  const inQuestion = words.some((word) => entry.questionText.includes(word));\n  const inAnswer = words.some((word) => entry.answerText.includes(word));\n  return { question: entry.question, inQuestion, inAnswer };\n}\n\nexport function hitsOf(query: string): Hit[] {\n  const words = wordsOf(query);\n  const hits: Hit[] = [];\n  for (const entry of INDEX) {\n    const hit = hitOf(entry, words);\n    if (hit) {\n      hits.push(hit);\n    }\n  }\n  return hits;\n}\n\nexport function inTopic(hits: Hit[], topic: TopicFilter) {\n  if (topic === 'all') {\n    return hits;\n  }\n  return hits.filter((hit) => hit.question.topic === topic);\n}\n\nexport function topicCountsOf(hits: Hit[]) {\n  const counts: Record<string, number> = {};\n  for (const topic of TOPICS) {\n    counts[topic.id] = inTopic(hits, topic.id).length;\n  }\n  return counts;\n}\n\nfunction rangesOfWord(folded: Folded, word: string) {\n  const ranges: Range[] = [];\n  let from = folded.text.indexOf(word);\n  while (from !== -1) {\n    const last = from + word.length - 1;\n    ranges.push({ start: folded.starts[from], end: folded.ends[last] });\n    from = folded.text.indexOf(word, from + word.length);\n  }\n  return ranges;\n}\n\nfunction byStart(first: Range, second: Range) {\n  return first.start - second.start;\n}\n\nfunction mergedRanges(ranges: Range[]) {\n  const sorted = [...ranges].sort(byStart);\n  const merged: Range[] = [];\n  for (const range of sorted) {\n    const previous = merged.at(-1);\n    const overlaps = previous !== undefined && range.start <= previous.end;\n    if (overlaps) {\n      previous.end = Math.max(previous.end, range.end);\n      continue;\n    }\n    merged.push({ ...range });\n  }\n  return merged;\n}\n\nexport function markedPartsOf(text: string, words: string[]) {\n  const folded = foldedOf(text);\n  const ranges = words.flatMap((word) => rangesOfWord(folded, word));\n  const parts: MarkedPart[] = [];\n  let cursor = 0;\n  for (const range of mergedRanges(ranges)) {\n    if (range.start > cursor) {\n      const plain = text.slice(cursor, range.start);\n      parts.push({ key: String(cursor), text: plain, isMatch: false });\n    }\n    const match = text.slice(range.start, range.end);\n    parts.push({ key: String(range.start), text: match, isMatch: true });\n    cursor = range.end;\n  }\n  if (cursor < text.length) {\n    const rest = text.slice(cursor);\n    parts.push({ key: String(cursor), text: rest, isMatch: false });\n  }\n  return parts;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/search.ts"
    },
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\nimport { keyDelayOf, prefixesOf } from '@/registry/ndeko/lib/demonstration';\n\nimport type { TopicFilter } from './data';\n\nexport type FaqState = {\n  query: string;\n  topic: TopicFilter;\n  openIds: string[];\n  copiedId: string | null;\n  linkedId: string | null;\n};\n\nexport type FaqAction =\n  | { type: 'typed'; value: string }\n  | { type: 'topicPicked'; topic: TopicFilter }\n  | { type: 'opened'; ids: string[] }\n  | { type: 'cleared' }\n  | { type: 'copied'; id: string }\n  | { type: 'copyCleared' }\n  | { type: 'linked'; id: string };\n\ntype Step = SessionStep<FaqState, FaqAction>;\n\nexport const INITIAL: FaqState = {\n  query: '',\n  topic: 'all',\n  openIds: [],\n  copiedId: null,\n  linkedId: null,\n};\n\nexport function reducer(state: FaqState, action: FaqAction): FaqState {\n  switch (action.type) {\n    case 'typed':\n      return { ...state, query: action.value };\n    case 'topicPicked':\n      return { ...state, topic: action.topic };\n    case 'opened':\n      return { ...state, openIds: action.ids };\n    case 'cleared':\n      return { ...state, query: '' };\n    case 'copied':\n      return { ...state, copiedId: action.id };\n    case 'copyCleared':\n      return { ...state, copiedId: null };\n    case 'linked':\n      return {\n        ...state,\n        query: '',\n        topic: 'all',\n        openIds: [action.id],\n        linkedId: action.id,\n      };\n  }\n}\n\nexport const COPIED_MS = 1600;\n\nconst KEY_MS = 260;\n\nfunction typing(text: string, startAfter: number): Step[] {\n  const prefixes = prefixesOf(text);\n  return prefixes.map((value, index) => ({\n    after: keyDelayOf(index, startAfter, KEY_MS),\n    by: 'demo',\n    action: { type: 'typed', value },\n  }));\n}\n\n/**\n * Someone types \"cafe\" and finds the question with its accent, opens it and copies its link,\n * clears the search and filters by topic, then types a word nothing matches and meets the person\n * to ask.\n */\nexport const SCRIPT: Step[] = [\n  ...typing('cafe', 1000),\n  {\n    after: 1500,\n    by: 'demo',\n    press: 'trigger-split',\n    action: { type: 'opened', ids: ['split'] },\n  },\n  {\n    after: 1700,\n    by: 'demo',\n    press: 'copy-split',\n    action: { type: 'copied', id: 'split' },\n  },\n  {\n    after: 2400,\n    by: 'demo',\n    press: 'clear',\n    action: { type: 'cleared' },\n  },\n  {\n    after: 1500,\n    by: 'demo',\n    press: 'topic-payments',\n    action: { type: 'topicPicked', topic: 'payments' },\n  },\n  {\n    after: 1800,\n    by: 'demo',\n    press: 'topic-all',\n    action: { type: 'topicPicked', topic: 'all' },\n  },\n  ...typing('zzq', 1400),\n  {\n    after: 2600,\n    by: 'demo',\n    press: 'clear-search',\n    action: { type: 'cleared' },\n  },\n];\n\n/** Under reduced motion the word is typed, the question with its accent is marked and open. */\nexport const RESTING: FaqState = {\n  ...INITIAL,\n  query: 'cafe',\n  openIds: ['split'],\n};\n\nexport const LOOP_AFTER_MS = 2600;\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/session.ts"
    },
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/topic-chips.tsx",
      "content": "'use client';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { ToggleGroup, ToggleGroupItem } from '@/registry/ndeko/ui/toggle-group';\n\nimport { TOPICS, type TopicFilter } from './data';\n\nconst THUMB =\n  'bg-card shadow-[0_1px_2px_rgb(0_0_0/0.08)] hairline-ring ring-foreground/10 dark:bg-foreground/[0.09] dark:ring-foreground/15';\n\nfunction topicOf(value: unknown) {\n  const topic = TOPICS.find((candidate) => candidate.id === value);\n  return topic?.id;\n}\n\nfunction emptyDimOf(count: number) {\n  if (count === 0) {\n    return 'opacity-50';\n  }\n  return undefined;\n}\n\ntype TopicChipsProps = {\n  topic: TopicFilter;\n  counts: Record<string, number>;\n  pressed: string | null;\n  onPick: (topic: TopicFilter) => void;\n};\n\nexport function TopicChips({\n  topic,\n  counts,\n  pressed,\n  onPick,\n}: TopicChipsProps) {\n  const pressedValues = [topic];\n\n  function changeTopic(nextValues: unknown[]) {\n    const [next] = nextValues;\n    const picked = topicOf(next);\n    if (picked) {\n      onPick(picked);\n    }\n  }\n\n  return (\n    <div className='relative -mx-4 overflow-x-auto px-4 @2xl:mx-0 @2xl:px-0'>\n      <ToggleGroup\n        aria-label='Topics'\n        value={pressedValues}\n        onValueChange={changeTopic}\n        travel\n        size='sm'\n        indicatorClassName={THUMB}\n        className='bg-foreground/[0.05] rounded-lg p-0.5'\n      >\n        {TOPICS.map((item) => (\n          <ToggleGroupItem\n            key={item.id}\n            value={item.id}\n            className={cn(\n              'h-7 gap-1.5 rounded-md px-2.5 text-xs',\n              pressedQuietOf(pressed === `topic-${item.id}`)\n            )}\n          >\n            {item.label}\n            <MotionNumber\n              value={counts[item.id]}\n              className={cn(\n                'text-muted-foreground',\n                emptyDimOf(counts[item.id])\n              )}\n            />\n          </ToggleGroupItem>\n        ))}\n      </ToggleGroup>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/topic-chips.tsx"
    },
    {
      "path": "registry/ndeko/blocks/faqs/faqs-03/data.ts",
      "content": "export type TopicId = 'start' | 'payments' | 'hardware' | 'data';\n\nexport type TopicFilter = TopicId | 'all';\n\nexport type Topic = {\n  id: TopicFilter;\n  label: string;\n};\n\nexport type Question = {\n  id: string;\n  topic: TopicId;\n  question: string;\n  answer: string;\n};\n\nexport const SECTION = {\n  title: 'Questions shop owners ask before switching',\n  description:\n    'Search by a word, narrow by topic and copy the link to any answer.',\n  searchLabel: 'Search the questions',\n  searchPlaceholder: 'Search the questions',\n};\n\nexport const TOPICS: Topic[] = [\n  { id: 'all', label: 'All' },\n  { id: 'start', label: 'Getting started' },\n  { id: 'payments', label: 'Payments' },\n  { id: 'hardware', label: 'Hardware' },\n  { id: 'data', label: 'Your data' },\n];\n\nexport const PERSON = {\n  name: 'Grace Mbuyi',\n  firstName: 'Grace',\n  role: 'Support lead at Tallymark',\n  href: 'mailto:support@tallymark.example',\n};\n\nexport const QUESTIONS: Question[] = [\n  {\n    id: 'setup',\n    topic: 'start',\n    question: 'How long does it take to set up a shop?',\n    answer:\n      'Most shops sell the same afternoon. Add your products from a spreadsheet, pick a receipt layout and invite the people who work the till.',\n  },\n  {\n    id: 'split',\n    topic: 'start',\n    question: 'Can a café split one bill between guests?',\n    answer:\n      'Yes. Open the table, choose Split and share the items by guest or in equal parts. Each guest pays their own way and gets their own receipt.',\n  },\n  {\n    id: 'import',\n    topic: 'start',\n    question: 'Can I import my products from a spreadsheet?',\n    answer:\n      'Yes. Upload a CSV with a name, a price and an optional barcode. Tallymark shows what it understood before anything is added.',\n  },\n  {\n    id: 'currencies',\n    topic: 'payments',\n    question: 'Can I take payments in Congolese francs?',\n    answer:\n      'Yes. Prices can be set in francs, dollars or both, and the rate of the day is kept on every receipt. A shop in Kinshasa or Lubumbashi can show both on one screen.',\n  },\n  {\n    id: 'refunds',\n    topic: 'payments',\n    question: 'How do refunds work?',\n    answer:\n      'Open the sale, choose Refund and pick the items. The money goes back the way it came in, and the stock is added back if you ask for it.',\n  },\n  {\n    id: 'fees',\n    topic: 'payments',\n    question: 'Does Tallymark charge for card payments?',\n    answer:\n      'Tallymark adds no fee of its own. The fees of your card provider apply, and each sale lists them.',\n  },\n  {\n    id: 'readers',\n    topic: 'hardware',\n    question: 'Which card readers work with it?',\n    answer:\n      'Any reader that speaks the standard protocol of your provider. The setup screen lists the ones it finds nearby.',\n  },\n  {\n    id: 'offline',\n    topic: 'hardware',\n    question: 'Does the till work without internet?',\n    answer:\n      'Yes. Sales are saved on the device and sent when the connection returns. Cash and stored-value sales never wait for a signal.',\n  },\n  {\n    id: 'printers',\n    topic: 'hardware',\n    question: 'Can I print receipts on a thermal printer?',\n    answer:\n      'Yes, over Bluetooth or a cable. A receipt can also go to the guest by email or message.',\n  },\n  {\n    id: 'export',\n    topic: 'data',\n    question: 'Can I take my sales history with me?',\n    answer:\n      'Yes. Export every sale as a CSV or a spreadsheet at any time, with no waiting period.',\n  },\n  {\n    id: 'region',\n    topic: 'data',\n    question: 'Where is my data kept?',\n    answer:\n      'In the region you pick when you create the shop. Backups stay in the same region.',\n  },\n  {\n    id: 'staff',\n    topic: 'data',\n    question: 'Can I limit what my staff see?',\n    answer:\n      'Yes. Give each person a role: they can sell, refund up to a limit or manage the stock. Reports stay with the owner.',\n  },\n];\n",
      "type": "registry:component",
      "target": "components/blocks/faqs-03/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "faqs"
  ],
  "type": "registry:block"
}