{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "search-01",
  "title": "Search results",
  "description": "Search over a local index with the count and the real time it took, type facets, pages of results with their breadcrumbs and matches marked, and a correction when nothing matches: each letter you type narrows the results while every facet count rolls, and the arrows walk a highlight through them for Enter to open.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/company-mark.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/kbd.json",
    "https://ui.ndekocode.dev/r/live-duration.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/recipes.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"
  ],
  "files": [
    {
      "path": "registry/ndeko/blocks/search/search-01/index.tsx",
      "content": "'use client';\n\nimport { useId, useRef } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport {\n  pressedQuietOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  ChevronLeftIcon,\n  ChevronRightIcon,\n  SearchIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { FOCUS_RING } from '@/registry/ndeko/lib/recipes';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { CompanyMark } from '@/registry/ndeko/ui/company-mark';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\nimport { ToggleGroup, ToggleGroupItem } from '@/registry/ndeko/ui/toggle-group';\n\nimport { POPULAR_SEARCHES, SITE, TYPES } from './data';\nimport { optionIdOf, ResultList } from './results';\nimport {\n  correctionOf,\n  countOfType,\n  matchesOf,\n  wordsOf,\n  type TypeFilter,\n} from './search';\nimport {\n  INITIAL,\n  LOOP_AFTER_MS,\n  pageCountOf,\n  pageOfResults,\n  reducer,\n  RESTING,\n  resultsIn,\n  SCRIPT,\n} from './session';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\nconst FILTERS: { id: TypeFilter; label: string }[] = [\n  { id: 'all', label: 'All' },\n  ...TYPES,\n];\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\nconst KEY_MOTION = 'transition-[scale] duration-150';\n\nfunction filterOf(values: unknown[]) {\n  const [value] = values;\n  const filter = FILTERS.find((candidate) => candidate.id === value);\n  return filter?.id;\n}\n\nfunction resultsWordOf(count: number) {\n  if (count === 1) {\n    return 'result';\n  }\n  return 'results';\n}\n\n/** Below a millisecond the clock of the browser is too coarse to say more. */\nfunction timingOf(searchMs: number) {\n  if (searchMs < 1) {\n    return 'in under 1 ms';\n  }\n  return `in ${Math.round(searchMs)} ms`;\n}\n\nfunction spokenOf(count: number, hasWords: boolean) {\n  if (!hasWords) {\n    return '';\n  }\n  if (count === 0) {\n    return 'No results';\n  }\n  return `${count} ${resultsWordOf(count)}`;\n}\n\nfunction pagesOf(pageCount: number) {\n  return Array.from({ length: pageCount }, (_, index) => index + 1);\n}\n\nfunction currentPageOf(isCurrent: boolean): 'page' | undefined {\n  if (isCurrent) {\n    return 'page';\n  }\n  return undefined;\n}\n\nfunction activeIdOf(listId: string, activeIndex: number, hasResults: boolean) {\n  const hasActive = activeIndex >= 0;\n  if (!hasResults || !hasActive) {\n    return undefined;\n  }\n  return optionIdOf(listId, activeIndex);\n}\n\nconst TYPE_NOUN: Record<TypeFilter, string> = {\n  all: 'page',\n  guide: 'guide',\n  api: 'API reference page',\n  changelog: 'changelog entry',\n  community: 'community thread',\n};\n\nfunction hiddenLineOf(type: TypeFilter, query: string) {\n  const noun = TYPE_NOUN[type];\n  const trimmed = query.trim();\n  return `No ${noun} matches “${trimmed}”`;\n}\n\ntype PopularSearchesProps = {\n  onPick: (query: string, control: HTMLElement) => void;\n  className?: string;\n};\n\nfunction PopularSearches({ onPick, className }: PopularSearchesProps) {\n  return (\n    <ul className={cn('flex flex-wrap gap-2', className)}>\n      {POPULAR_SEARCHES.map((query) => (\n        <li key={query}>\n          <Button\n            type='button'\n            variant='outline'\n            size='sm'\n            onClick={(event) => onPick(query, event.currentTarget)}\n          >\n            {query}\n          </Button>\n        </li>\n      ))}\n    </ul>\n  );\n}\n\nexport default function Search01() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const inputId = useId();\n  const listId = useId();\n  const words = wordsOf(state.query);\n  const hasWords = words.length > 0;\n  const matches = matchesOf(state.query);\n  const results = resultsIn(state);\n  const shownResults = pageOfResults(state);\n  const resultCount = results.length;\n  const pageCount = pageCountOf(resultCount);\n  const hasResults = resultCount > 0;\n  const hasMatches = matches.length > 0;\n  const isNothingFound = hasWords && !hasMatches;\n  const isHiddenByType = hasMatches && !hasResults;\n  let correction: string | null = null;\n  if (isNothingFound) {\n    correction = correctionOf(state.query);\n  }\n  const hasPages = pageCount > 1;\n  const pages = pagesOf(pageCount);\n  const activeId = activeIdOf(listId, state.activeIndex, hasResults);\n  const resultLine = spokenOf(resultCount, hasWords);\n  const message = spokenUnless(isAutoplaying, resultLine);\n  const canReplay = isFinished && !isAutoplaying;\n  useKeptHeight(ref);\n\n  function search(value: string) {\n    act({ type: 'typed', value });\n  }\n\n  /** A pick replaces the part of the page that held the focus: a keyboard goes back to the field. */\n  function returnKeyboardToField(control: HTMLElement) {\n    const isFromKeyboard = control.matches(':focus-visible');\n    if (isFromKeyboard) {\n      inputRef.current?.focus();\n    }\n  }\n\n  function pickSearch(value: string, control: HTMLElement) {\n    search(value);\n    returnKeyboardToField(control);\n  }\n\n  function showEveryType(control: HTMLElement) {\n    act({ type: 'typePicked', filter: 'all' });\n    returnKeyboardToField(control);\n  }\n\n  function pickFilter(values: unknown[]) {\n    const filter = filterOf(values);\n    if (filter) {\n      act({ type: 'typePicked', filter });\n    }\n  }\n\n  function openActive() {\n    let index = state.activeIndex;\n    if (index < 0) {\n      index = 0;\n    }\n    const optionId = optionIdOf(listId, index);\n    const option = document.getElementById(optionId);\n    option?.click();\n  }\n\n  function handleKeys(event: React.KeyboardEvent<HTMLInputElement>) {\n    if (event.key === 'ArrowDown') {\n      event.preventDefault();\n      act({ type: 'moved', by: 1 });\n      return;\n    }\n    if (event.key === 'ArrowUp') {\n      event.preventDefault();\n      act({ type: 'moved', by: -1 });\n      return;\n    }\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      act({ type: 'cleared' });\n      return;\n    }\n    const isEnter = event.key === 'Enter';\n    if (isEnter && hasResults) {\n      event.preventDefault();\n      openActive();\n    }\n  }\n\n  return (\n    <ClockGate isActive={isInView}>\n      <div\n        ref={ref}\n        className='bg-background text-foreground @container min-h-dvh w-full'\n      >\n        <div className='mx-auto flex max-w-3xl flex-col gap-5 px-4 py-6 @2xl:px-8 @2xl:py-10'>\n          <header className='flex min-h-8 items-center gap-2'>\n            <a\n              href={SITE.homeHref}\n              className={cn(\n                'flex items-center gap-2 rounded-md text-sm font-semibold',\n                FOCUS_RING\n              )}\n            >\n              <CompanyMark seed={SITE.name} size='lg' />\n              {SITE.name}\n            </a>\n            <span className='text-muted-foreground text-sm'>Docs</span>\n            <span className='flex-1' />\n            <ReplayButton\n              isShown={canReplay}\n              onReplay={restart}\n              label='Replay'\n            />\n          </header>\n\n          <div className='flex flex-col gap-3'>\n            <div className='relative'>\n              <label htmlFor={inputId} className='sr-only'>\n                Search the docs\n              </label>\n              <SearchIcon className='text-muted-foreground pointer-events-none absolute start-4 top-1/2 size-[18px] -translate-y-1/2' />\n              <Input\n                ref={inputRef}\n                id={inputId}\n                type='search'\n                role='combobox'\n                autoComplete='off'\n                spellCheck={false}\n                aria-autocomplete='list'\n                aria-expanded={hasResults}\n                aria-controls={listId}\n                aria-activedescendant={activeId}\n                placeholder='Search guides, endpoints and errors'\n                value={state.query}\n                onChange={(event) => search(event.target.value)}\n                onKeyDown={handleKeys}\n                className='h-12 rounded-xl ps-11 pe-4 md:text-sm'\n              />\n            </div>\n\n            <div className='flex min-h-6 flex-wrap items-center gap-x-4 gap-y-2'>\n              {hasWords && (\n                <p className='text-muted-foreground flex items-baseline gap-1 text-xs tabular-nums'>\n                  <MotionNumber\n                    value={resultCount}\n                    className='text-foreground font-medium'\n                  />\n                  {resultsWordOf(resultCount)} {timingOf(state.searchMs)}\n                </p>\n              )}\n              {!hasWords && (\n                <p className='text-muted-foreground text-xs'>\n                  Search every guide, endpoint and changelog entry\n                </p>\n              )}\n              <p\n                aria-hidden='true'\n                className='text-muted-foreground ms-auto hidden items-center gap-1 text-xs @md:flex'\n              >\n                <Kbd\n                  className={cn(\n                    KEY_MOTION,\n                    pressedQuietOf(pressed === 'key-down')\n                  )}\n                >\n                  ↓\n                </Kbd>\n                <Kbd>Enter</Kbd>\n                <Kbd\n                  className={cn(\n                    KEY_MOTION,\n                    pressedQuietOf(pressed === 'key-escape')\n                  )}\n                >\n                  Esc\n                </Kbd>\n              </p>\n            </div>\n          </div>\n\n          <div className='relative -mx-4 overflow-x-auto px-4 @2xl:mx-0 @2xl:px-0'>\n            <ToggleGroup\n              aria-label='Type of page'\n              value={[state.type]}\n              onValueChange={pickFilter}\n              travel\n              indicatorClassName={THUMB}\n              className='bg-foreground/[0.04] rounded-xl p-1'\n            >\n              {FILTERS.map((filter) => (\n                <ToggleGroupItem\n                  key={filter.id}\n                  value={filter.id}\n                  className={cn(\n                    'h-7 gap-1.5 rounded-lg px-2.5 text-xs',\n                    pressedQuietOf(pressed === `type-${filter.id}`)\n                  )}\n                >\n                  {filter.label}\n                  <MotionNumber\n                    value={countOfType(matches, filter.id)}\n                    className='text-muted-foreground'\n                  />\n                </ToggleGroupItem>\n              ))}\n            </ToggleGroup>\n          </div>\n\n          {hasResults && (\n            <ResultList\n              listId={listId}\n              results={shownResults}\n              words={words}\n              activeIndex={state.activeIndex}\n            />\n          )}\n\n          {hasPages && (\n            <nav\n              aria-label='Pages of results'\n              className='flex items-center justify-center gap-1'\n            >\n              <Button\n                type='button'\n                variant='ghost'\n                size='icon'\n                aria-label='Previous page'\n                disabled={state.page === 1}\n                focusableWhenDisabled\n                onClick={() => act({ type: 'paged', page: state.page - 1 })}\n              >\n                <ChevronLeftIcon />\n              </Button>\n              {pages.map((page) => {\n                const isCurrent = page === state.page;\n                let variant: 'outline' | 'ghost' = 'ghost';\n                if (isCurrent) {\n                  variant = 'outline';\n                }\n                return (\n                  <Button\n                    key={page}\n                    type='button'\n                    variant={variant}\n                    size='icon'\n                    aria-label={`Page ${page}`}\n                    aria-current={currentPageOf(isCurrent)}\n                    onClick={() => act({ type: 'paged', page })}\n                    className={cn(\n                      'tabular-nums',\n                      pressedQuietOf(pressed === `page-${page}`)\n                    )}\n                  >\n                    {page}\n                  </Button>\n                );\n              })}\n              <Button\n                type='button'\n                variant='ghost'\n                size='icon'\n                aria-label='Next page'\n                disabled={state.page === pageCount}\n                focusableWhenDisabled\n                onClick={() => act({ type: 'paged', page: state.page + 1 })}\n              >\n                <ChevronRightIcon />\n              </Button>\n            </nav>\n          )}\n\n          {isNothingFound && (\n            <div className='bg-foreground/[0.025] flex flex-col items-center gap-4 rounded-2xl px-6 py-10 text-center transition-opacity duration-200 starting:opacity-0'>\n              <span className='keycap-3d flex size-10 items-center justify-center rounded-xl'>\n                <SearchIcon className='text-muted-foreground size-5' />\n              </span>\n              <div className='flex flex-col gap-1'>\n                <p className='text-sm font-medium text-balance'>\n                  Nothing matches “{state.query.trim()}”\n                </p>\n                {correction && (\n                  <p className='text-muted-foreground text-[13px]'>\n                    Did you mean{' '}\n                    <button\n                      type='button'\n                      onClick={(event) =>\n                        pickSearch(correction, event.currentTarget)\n                      }\n                      className={cn(\n                        'text-primary-ink rounded-sm font-medium underline-offset-4 transition-[scale] duration-150 hover:underline',\n                        pressedQuietOf(pressed === 'correction'),\n                        FOCUS_RING\n                      )}\n                    >\n                      {correction}\n                    </button>\n                    ?\n                  </p>\n                )}\n              </div>\n              <PopularSearches onPick={pickSearch} className='justify-center' />\n            </div>\n          )}\n\n          {isHiddenByType && (\n            <div className='bg-foreground/[0.025] flex flex-col items-center gap-3 rounded-2xl px-6 py-10 text-center transition-opacity duration-200 starting:opacity-0'>\n              <p className='text-sm font-medium text-balance'>\n                {hiddenLineOf(state.type, state.query)}\n              </p>\n              <Button\n                type='button'\n                variant='outline'\n                onClick={(event) => showEveryType(event.currentTarget)}\n              >\n                Show all {matches.length} {resultsWordOf(matches.length)}\n              </Button>\n            </div>\n          )}\n\n          {!hasWords && (\n            <div className='flex flex-col gap-3 pt-2'>\n              <p className='text-[13px] font-medium'>Popular searches</p>\n              <PopularSearches onPick={pickSearch} />\n            </div>\n          )}\n        </div>\n        <LiveRegion message={message} />\n      </div>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/search-01/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/search/search-01/results.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion, type Transition } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { ChevronRightIcon } from '@/registry/ndeko/lib/icons';\nimport {\n  EASE_OUT_STRONG,\n  INSTANT,\n  SPRING,\n} from '@/registry/ndeko/lib/motion-presets';\n\nimport { TYPE_GLYPH, type IndexedPage } from './data';\nimport { markedPartsOf } from './search';\n\nconst ROW_SHOWN = { opacity: 1 };\n\nconst ROW_HIDDEN = { opacity: 0 };\n\nconst ROW_LEAVE: Transition = { duration: 0.1, ease: EASE_OUT_STRONG };\n\nfunction rowMotionOf(shouldReduceMotion: boolean): Transition {\n  if (shouldReduceMotion) {\n    return { duration: 0.15, layout: INSTANT };\n  }\n  return { duration: 0.2, ease: EASE_OUT_STRONG, layout: SPRING };\n}\n\nfunction travelOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return INSTANT;\n  }\n  return SPRING;\n}\n\nexport function optionIdOf(listId: string, index: number) {\n  return `${listId}-${index}`;\n}\n\nfunction Marked({ text, words }: { text: string; words: string[] }) {\n  const parts = markedPartsOf(text, words);\n\n  return (\n    <>\n      {parts.map((part) => {\n        if (part.isMatch) {\n          return (\n            <mark\n              key={part.key}\n              className='bg-primary/15 text-foreground rounded-[3px]'\n            >\n              {part.text}\n            </mark>\n          );\n        }\n        return <span key={part.key}>{part.text}</span>;\n      })}\n    </>\n  );\n}\n\nfunction Trail({ trail }: { trail: string[] }) {\n  return (\n    <span className='text-muted-foreground flex min-w-0 items-center gap-1 text-xs'>\n      {trail.map((step, index) => (\n        <span key={step} className='flex min-w-0 items-center gap-1'>\n          {index > 0 && <ChevronRightIcon className='size-3 shrink-0' />}\n          <span className='truncate'>{step}</span>\n        </span>\n      ))}\n    </span>\n  );\n}\n\ntype ResultListProps = {\n  listId: string;\n  results: IndexedPage[];\n  words: string[];\n  activeIndex: number;\n};\n\n/** The input keeps the focus; the arrows walk a highlight through these rows. */\nexport function ResultList({\n  listId,\n  results,\n  words,\n  activeIndex,\n}: ResultListProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const layoutKey = results.map((page) => page.id).join(' ');\n\n  return (\n    <ul\n      id={listId}\n      role='listbox'\n      aria-label='Results'\n      className='bg-card hairline-ring ring-border dark:bg-foreground/[0.03] relative flex flex-col rounded-xl p-1 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'\n    >\n      <AnimatePresence mode='popLayout' initial={false}>\n        {results.map((page, index) => {\n          const Glyph = TYPE_GLYPH[page.type];\n          const isActive = index === activeIndex;\n          return (\n            <motion.li\n              key={page.id}\n              role='none'\n              layout\n              layoutDependency={layoutKey}\n              initial={ROW_HIDDEN}\n              animate={ROW_SHOWN}\n              exit={{ opacity: 0, transition: ROW_LEAVE }}\n              transition={rowMotionOf(shouldReduceMotion)}\n            >\n              <a\n                id={optionIdOf(listId, index)}\n                role='option'\n                aria-selected={isActive}\n                href={page.href}\n                tabIndex={-1}\n                className='hover:bg-foreground/[0.03] relative isolate flex items-start gap-3 rounded-lg p-3 transition-colors duration-100 outline-none'\n              >\n                {isActive && (\n                  <motion.span\n                    layoutId={`${listId}-highlight`}\n                    transition={travelOf(shouldReduceMotion)}\n                    className='bg-foreground/[0.06] absolute inset-0 -z-10 rounded-lg'\n                  />\n                )}\n                <span className='keycap-3d flex size-8 shrink-0 items-center justify-center rounded-lg'>\n                  <Glyph className='text-muted-foreground size-4' />\n                </span>\n                <span className='flex min-w-0 flex-1 flex-col gap-1'>\n                  <Trail trail={page.trail} />\n                  <span className='text-[13px] font-medium text-pretty'>\n                    <Marked text={page.title} words={words} />\n                  </span>\n                  <span className='text-muted-foreground line-clamp-2 text-xs leading-5 text-pretty'>\n                    <Marked text={page.excerpt} words={words} />\n                  </span>\n                </span>\n              </a>\n            </motion.li>\n          );\n        })}\n      </AnimatePresence>\n    </ul>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/search-01/results.tsx"
    },
    {
      "path": "registry/ndeko/blocks/search/search-01/search.ts",
      "content": "import { PAGES, type IndexedPage, type PageType } from './data';\n\nexport type TypeFilter = PageType | 'all';\n\nexport type MarkedPart = {\n  key: string;\n  text: string;\n  isMatch: boolean;\n};\n\ntype Range = {\n  start: number;\n  end: number;\n};\n\ntype Scored = {\n  page: IndexedPage;\n  order: number;\n  score: number;\n};\n\n/** A single letter matches nearly every page, so a word counts from two letters. */\nconst MIN_WORD_LENGTH = 2;\n\n/** Corrections stay close to what was typed: at most two letters off. */\nconst MAX_DISTANCE = 2;\n\nexport function wordsOf(query: string) {\n  const lowered = query.toLowerCase();\n  const pieces = lowered.split(/\\s+/);\n  return pieces.filter((piece) => piece.length >= MIN_WORD_LENGTH);\n}\n\nfunction rangesOfWord(lowered: string, word: string) {\n  const ranges: Range[] = [];\n  let start = lowered.indexOf(word);\n  while (start !== -1) {\n    const end = start + word.length;\n    ranges.push({ start, end });\n    start = lowered.indexOf(word, end);\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 last = merged.at(-1);\n    const overlaps = last !== undefined && range.start <= last.end;\n    if (overlaps) {\n      last.end = Math.max(last.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 lowered = text.toLowerCase();\n  const ranges = words.flatMap((word) => rangesOfWord(lowered, 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\n/** Every word must be on the page; the words in its title count twice. */\nfunction scoreOf(page: IndexedPage, words: string[]) {\n  const title = page.title.toLowerCase();\n  const text = `${title} ${page.excerpt.toLowerCase()}`;\n  const isMatch = words.every((word) => text.includes(word));\n  if (!isMatch) {\n    return 0;\n  }\n  const inTitle = words.filter((word) => title.includes(word));\n  return 1 + inTitle.length;\n}\n\nfunction byScoreThenOrder(first: Scored, second: Scored) {\n  const scoreGap = second.score - first.score;\n  if (scoreGap !== 0) {\n    return scoreGap;\n  }\n  return first.order - second.order;\n}\n\nexport function matchesOf(query: string) {\n  const words = wordsOf(query);\n  if (words.length === 0) {\n    return [];\n  }\n  const scored = PAGES.map((page, order) => ({\n    page,\n    order,\n    score: scoreOf(page, words),\n  }));\n  const matching = scored.filter((entry) => entry.score > 0);\n  matching.sort(byScoreThenOrder);\n  return matching.map((entry) => entry.page);\n}\n\nexport function ofType(matches: IndexedPage[], type: TypeFilter) {\n  if (type === 'all') {\n    return matches;\n  }\n  return matches.filter((page) => page.type === type);\n}\n\nexport function countOfType(matches: IndexedPage[], type: TypeFilter) {\n  return ofType(matches, type).length;\n}\n\nfunction vocabularyOf(pages: IndexedPage[]) {\n  const words = new Set<string>();\n  for (const page of pages) {\n    const text = `${page.title} ${page.excerpt}`.toLowerCase();\n    for (const word of text.split(/[^a-z]+/)) {\n      if (word.length >= 4) {\n        words.add(word);\n      }\n    }\n  }\n  return [...words];\n}\n\nconst VOCABULARY = vocabularyOf(PAGES);\n\n/** How many letters to add, remove or change to turn one word into the other. */\nfunction distanceBetween(first: string, second: string) {\n  let previous = Array.from({ length: second.length + 1 }, (_, index) => index);\n  for (let row = 1; row <= first.length; row += 1) {\n    const current = [row];\n    for (let column = 1; column <= second.length; column += 1) {\n      const isSame = first[row - 1] === second[column - 1];\n      let cost = 1;\n      if (isSame) {\n        cost = 0;\n      }\n      const removal = previous[column] + 1;\n      const insertion = current[column - 1] + 1;\n      const change = previous[column - 1] + cost;\n      current.push(Math.min(removal, insertion, change));\n    }\n    previous = current;\n  }\n  return previous[second.length];\n}\n\nfunction closestWordOf(word: string) {\n  let best = word;\n  let bestDistance = MAX_DISTANCE + 1;\n  for (const candidate of VOCABULARY) {\n    const distance = distanceBetween(word, candidate);\n    if (distance < bestDistance) {\n      best = candidate;\n      bestDistance = distance;\n    }\n  }\n  return best;\n}\n\nexport function correctionOf(query: string) {\n  const words = wordsOf(query);\n  if (words.length === 0) {\n    return null;\n  }\n  const corrected = words.map(closestWordOf);\n  const correction = corrected.join(' ');\n  const original = words.join(' ');\n  if (correction === original) {\n    return null;\n  }\n  return correction;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/search-01/search.ts"
    },
    {
      "path": "registry/ndeko/blocks/search/search-01/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\nimport { keyDelayOf, prefixesOf } from '@/registry/ndeko/lib/demonstration';\n\nimport { matchesOf, ofType, type TypeFilter } from './search';\n\nexport type SearchState = {\n  query: string;\n  type: TypeFilter;\n  /** The page of results, counted from 1. */\n  page: number;\n  /** The result Enter opens, on the current page. Nothing is highlighted before the arrows are used. */\n  activeIndex: number;\n  searchMs: number;\n};\n\nexport type SearchAction =\n  | { type: 'typed'; value: string }\n  | { type: 'typePicked'; filter: TypeFilter }\n  | { type: 'moved'; by: 1 | -1 }\n  | { type: 'paged'; page: number }\n  | { type: 'cleared' };\n\ntype Step = SessionStep<SearchState, SearchAction>;\n\nexport const PAGE_SIZE = 5;\n\nconst NOTHING_HIGHLIGHTED = -1;\n\nexport const INITIAL: SearchState = {\n  query: '',\n  type: 'all',\n  page: 1,\n  activeIndex: NOTHING_HIGHLIGHTED,\n  searchMs: 0,\n};\n\nexport function resultsIn(state: SearchState) {\n  const matches = matchesOf(state.query);\n  return ofType(matches, state.type);\n}\n\nexport function pageCountOf(resultCount: number) {\n  const pages = Math.ceil(resultCount / PAGE_SIZE);\n  return Math.max(1, pages);\n}\n\nexport function pageOfResults(state: SearchState) {\n  const results = resultsIn(state);\n  const start = (state.page - 1) * PAGE_SIZE;\n  const end = start + PAGE_SIZE;\n  return results.slice(start, end);\n}\n\n/** The search itself is timed where it runs, so the figure on the page is the real one. */\nfunction searched(state: SearchState, query: string): SearchState {\n  const startedAt = performance.now();\n  matchesOf(query);\n  const searchMs = performance.now() - startedAt;\n  return {\n    ...state,\n    query,\n    page: 1,\n    activeIndex: NOTHING_HIGHLIGHTED,\n    searchMs,\n  };\n}\n\nfunction nextIndexOf(current: number, by: 1 | -1, count: number) {\n  if (current === NOTHING_HIGHLIGHTED) {\n    if (by === 1) {\n      return 0;\n    }\n    return count - 1;\n  }\n  const moved = current + by + count;\n  return moved % count;\n}\n\nfunction moved(state: SearchState, by: 1 | -1): SearchState {\n  const count = pageOfResults(state).length;\n  if (count === 0) {\n    return state;\n  }\n  const activeIndex = nextIndexOf(state.activeIndex, by, count);\n  return { ...state, activeIndex };\n}\n\nfunction paged(state: SearchState, page: number): SearchState {\n  const resultCount = resultsIn(state).length;\n  const pageCount = pageCountOf(resultCount);\n  const isInRange = page >= 1 && page <= pageCount;\n  if (!isInRange) {\n    return state;\n  }\n  return { ...state, page, activeIndex: NOTHING_HIGHLIGHTED };\n}\n\nexport function reducer(state: SearchState, action: SearchAction): SearchState {\n  switch (action.type) {\n    case 'typed':\n      return searched(state, action.value);\n    case 'typePicked':\n      return {\n        ...state,\n        type: action.filter,\n        page: 1,\n        activeIndex: NOTHING_HIGHLIGHTED,\n      };\n    case 'moved':\n      return moved(state, action.by);\n    case 'paged':\n      return paged(state, action.page);\n    case 'cleared':\n      return INITIAL;\n  }\n}\n\nconst KEY_MS = 95;\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\nfunction arrow(after: number): Step {\n  return {\n    after,\n    by: 'demo',\n    press: 'key-down',\n    action: { type: 'moved', by: 1 },\n  };\n}\n\nfunction picked(after: number, filter: TypeFilter): Step {\n  return {\n    after,\n    by: 'demo',\n    press: `type-${filter}`,\n    action: { type: 'typePicked', filter },\n  };\n}\n\n/**\n * Someone searches, walks the results, narrows to guides and back, turns a page and clears; then a\n * misspelled word finds nothing and the correction the page offers is taken. The round ends empty.\n */\nexport const SCRIPT: Step[] = [\n  ...typing('deliver', 1400),\n  arrow(1300),\n  arrow(650),\n  picked(1500, 'guide'),\n  picked(1700, 'all'),\n  {\n    after: 1300,\n    by: 'demo',\n    press: 'page-2',\n    action: { type: 'paged', page: 2 },\n  },\n  {\n    after: 1900,\n    by: 'demo',\n    press: 'key-escape',\n    action: { type: 'cleared' },\n  },\n  ...typing('signatre', 1100),\n  {\n    after: 1700,\n    by: 'demo',\n    press: 'correction',\n    action: { type: 'typed', value: 'signature' },\n  },\n  {\n    after: 2300,\n    by: 'demo',\n    press: 'key-escape',\n    action: { type: 'cleared' },\n  },\n];\n\n/** Under reduced motion the results of a search are on the page with the first one highlighted. */\nexport const RESTING: SearchState = {\n  query: 'deliver',\n  type: 'all',\n  page: 1,\n  activeIndex: 0,\n  searchMs: 0,\n};\n\nexport const LOOP_AFTER_MS = 2200;\n",
      "type": "registry:component",
      "target": "components/blocks/search-01/session.ts"
    },
    {
      "path": "registry/ndeko/blocks/search/search-01/data.ts",
      "content": "import {\n  BookOpenIcon,\n  CodeIcon,\n  HistoryIcon,\n  MessageCircleIcon,\n  type Icon,\n} from '@/registry/ndeko/lib/icons';\n\nexport type PageType = 'guide' | 'api' | 'changelog' | 'community';\n\nexport type IndexedPage = {\n  id: string;\n  type: PageType;\n  title: string;\n  trail: string[];\n  excerpt: string;\n  href: string;\n};\n\nexport const SITE = {\n  name: 'Tideway',\n  homeHref: '#',\n};\n\nexport const TYPES: { id: PageType; label: string }[] = [\n  { id: 'guide', label: 'Guides' },\n  { id: 'api', label: 'API reference' },\n  { id: 'changelog', label: 'Changelog' },\n  { id: 'community', label: 'Community' },\n];\n\nexport const TYPE_GLYPH: Record<PageType, Icon> = {\n  guide: BookOpenIcon,\n  api: CodeIcon,\n  changelog: HistoryIcon,\n  community: MessageCircleIcon,\n};\n\nexport const POPULAR_SEARCHES = [\n  'signature',\n  'retry',\n  'rate limits',\n  'idempotency',\n];\n\nexport const PAGES: IndexedPage[] = [\n  {\n    id: 'verify-signatures',\n    type: 'guide',\n    title: 'Verify webhook signatures',\n    trail: ['Docs', 'Webhooks'],\n    excerpt:\n      'Every delivery carries a Tideway-Signature header. Compute the HMAC of the raw body with your signing secret and compare the two in constant time.',\n    href: '#verify-webhook-signatures',\n  },\n  {\n    id: 'rotate-secret',\n    type: 'guide',\n    title: 'Rotate a signing secret',\n    trail: ['Docs', 'Webhooks'],\n    excerpt:\n      'Create a second secret, accept both for a day, then remove the old one. Deliveries are signed with every active secret during the overlap.',\n    href: '#rotate-a-signing-secret',\n  },\n  {\n    id: 'retry-failed',\n    type: 'guide',\n    title: 'Retry failed deliveries',\n    trail: ['Docs', 'Webhooks'],\n    excerpt:\n      'Failed deliveries are retried for three days with a growing delay. You can also resend one by hand from the event log.',\n    href: '#retry-failed-deliveries',\n  },\n  {\n    id: 'behind-firewall',\n    type: 'guide',\n    title: 'Receive webhooks behind a firewall',\n    trail: ['Docs', 'Webhooks'],\n    excerpt:\n      'Allow the delivery addresses listed in your dashboard, or pull events from the events endpoint instead of receiving them.',\n    href: '#receive-webhooks-behind-a-firewall',\n  },\n  {\n    id: 'first-event',\n    type: 'guide',\n    title: 'Send your first event',\n    trail: ['Docs', 'Getting started'],\n    excerpt:\n      'Create an API key, post an event with curl, and watch it arrive on the test endpoint in the dashboard.',\n    href: '#send-your-first-event',\n  },\n  {\n    id: 'idempotency-keys',\n    type: 'guide',\n    title: 'Idempotency keys',\n    trail: ['Docs', 'Concepts'],\n    excerpt:\n      'Send the same key with a repeated request and Tideway returns the first result instead of creating the event twice.',\n    href: '#idempotency-keys',\n  },\n  {\n    id: 'test-locally',\n    type: 'guide',\n    title: 'Test webhooks on your machine',\n    trail: ['Docs', 'Webhooks'],\n    excerpt:\n      'Forward deliveries to localhost with the command line tool and replay any past event while you work on your handler.',\n    href: '#test-webhooks-locally',\n  },\n  {\n    id: 'rate-limits',\n    type: 'guide',\n    title: 'Rate limits',\n    trail: ['Docs', 'Concepts'],\n    excerpt:\n      'Each key can send 100 requests per second. Responses carry the remaining budget, so a client can slow down before it is refused.',\n    href: '#rate-limits',\n  },\n  {\n    id: 'signature-header',\n    type: 'api',\n    title: 'Signature header',\n    trail: ['API reference', 'Headers'],\n    excerpt:\n      'Tideway-Signature holds a timestamp and one signature per active secret, separated by commas.',\n    href: '#signature-header',\n  },\n  {\n    id: 'create-event',\n    type: 'api',\n    title: 'POST /v1/events',\n    trail: ['API reference', 'Events'],\n    excerpt:\n      'Creates an event and queues a delivery to every endpoint subscribed to its type.',\n    href: '#post-v1-events',\n  },\n  {\n    id: 'list-events',\n    type: 'api',\n    title: 'GET /v1/events',\n    trail: ['API reference', 'Events'],\n    excerpt:\n      'Lists events from newest to oldest, 50 at a time, with a cursor for the next page.',\n    href: '#get-v1-events',\n  },\n  {\n    id: 'retry-delivery',\n    type: 'api',\n    title: 'POST /v1/deliveries/{id}/retry',\n    trail: ['API reference', 'Deliveries'],\n    excerpt:\n      'Queues one more attempt for a failed delivery, outside the automatic retry schedule.',\n    href: '#post-v1-deliveries-retry',\n  },\n  {\n    id: 'endpoint-object',\n    type: 'api',\n    title: 'The endpoint object',\n    trail: ['API reference', 'Endpoints'],\n    excerpt:\n      'An endpoint has an address, the event types it receives and the secrets used to sign its deliveries.',\n    href: '#endpoint-object',\n  },\n  {\n    id: 'errors',\n    type: 'api',\n    title: 'Errors',\n    trail: ['API reference'],\n    excerpt:\n      'Errors return a code, a message written for people and the id of the request to quote to support.',\n    href: '#errors',\n  },\n  {\n    id: 'timestamped-signatures',\n    type: 'changelog',\n    title: 'Signatures include a timestamp',\n    trail: ['Changelog', '2026'],\n    excerpt:\n      'Signatures now cover the time of delivery, so a replayed request older than five minutes can be refused.',\n    href: '#changelog-timestamped-signatures',\n  },\n  {\n    id: 'three-day-retries',\n    type: 'changelog',\n    title: 'Retry schedule extended to three days',\n    trail: ['Changelog', '2026'],\n    excerpt:\n      'Failed deliveries are now retried for three days instead of one, with the same growing delay.',\n    href: '#changelog-three-day-retries',\n  },\n  {\n    id: 'event-log',\n    type: 'changelog',\n    title: 'The event log keeps 30 days',\n    trail: ['Changelog', '2026'],\n    excerpt:\n      'The event log now keeps 30 days of events on every plan, up from 7.',\n    href: '#changelog-event-log',\n  },\n  {\n    id: 'listen-command',\n    type: 'changelog',\n    title: 'New command: tideway listen',\n    trail: ['Changelog', '2025'],\n    excerpt:\n      'tideway listen forwards deliveries to a local address and prints each one as it arrives.',\n    href: '#changelog-listen-command',\n  },\n  {\n    id: 'proxy-signature',\n    type: 'community',\n    title: 'Signature check fails behind a proxy',\n    trail: ['Community', 'Webhooks'],\n    excerpt:\n      'Our proxy re-encoded the body before it reached the handler, so the signature never matched. Reading the raw body fixed it.',\n    href: '#community-proxy-signature',\n  },\n  {\n    id: 'out-of-order',\n    type: 'community',\n    title: 'Retries arriving out of order',\n    trail: ['Community', 'Webhooks'],\n    excerpt:\n      'A retried delivery can arrive after a newer one. Store the time of the event and ignore anything older than what you have.',\n    href: '#community-out-of-order',\n  },\n  {\n    id: 'keys-with-queues',\n    type: 'community',\n    title: 'Idempotency keys with a job queue',\n    trail: ['Community', 'Patterns'],\n    excerpt:\n      'We derive the key from the job id, so a job that runs twice never creates two events.',\n    href: '#community-keys-with-queues',\n  },\n  {\n    id: 'handler-timeout',\n    type: 'community',\n    title: 'Webhook handler times out',\n    trail: ['Community', 'Webhooks'],\n    excerpt:\n      'Answer within ten seconds and do the slow work afterwards: a slow answer counts as a failed delivery.',\n    href: '#community-handler-timeout',\n  },\n];\n",
      "type": "registry:component",
      "target": "components/blocks/search-01/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "search"
  ],
  "type": "registry:block"
}