docs/.vitepress/theme/components/Search.vue

e0daadf6cde09d5b3ac0fd1013593e43afe6b0f2
wotaku/docs/.vitepress/theme/components/Search.vue history · blame · raw

2937 lines · 77130 bytes

   1<script lang="ts" setup>
   2import type { SearchResult } from 'minisearch'
   3import { dataSymbol, type DefaultTheme, inBrowser, useRouter } from 'vitepress'
   4import {
   5  computed,
   6  createApp,
   7  markRaw,
   8  nextTick,
   9  onBeforeUnmount,
  10  onMounted,
  11  type Ref,
  12  ref,
  13  shallowRef,
  14  watch,
  15  watchEffect
  16} from 'vue'
  17// @ts-ignore
  18import { pathToFile } from 'vitepress/dist/client/app/utils'
  19// @ts-ignore
  20import { escapeRegExp } from 'vitepress/dist/client/shared'
  21
  22import {
  23  computedAsync,
  24  onKeyStroke,
  25  useEventListener,
  26  useLocalStorage,
  27  useScrollLock,
  28  useSessionStorage,
  29  useStorage,
  30  watchDebounced
  31} from '@vueuse/core'
  32import { useFocusTrap } from '@vueuse/integrations/useFocusTrap'
  33import { AnimatePresence, motion } from 'motion-v'
  34
  35// @ts-ignore
  36import localSearchIndex from '@localSearchIndex'
  37
  38import {
  39  ArrowLeft,
  40  ArrowLeftToLine,
  41  ArrowRight,
  42  ArrowRightToLine,
  43  ChevronRight,
  44  Delete,
  45  File,
  46  Globe,
  47  Hash,
  48  List,
  49  LocateOff,
  50  Regex,
  51  TextAlignStart
  52} from 'lucide-vue-next'
  53import Mark from 'mark.js/dist/mark.es6.js'
  54import { sidebar } from '../../configs/constants'
  55import type { PageLink } from '../../plugins/urlSearchPlugin'
  56import { LRUCache } from '../composables/search/lru-cache'
  57import { createSearchTranslate } from '../composables/search/translation'
  58import { useData } from '../composables/search/use-data'
  59import { LowEndDeviceModeStorageKey } from '../constants'
  60import { enhanceAppWithTabs } from './tabs'
  61
  62export interface FooterTranslations {
  63  selectText?: string
  64  selectKeyAriaLabel?: string
  65  navigateText?: string
  66  navigateUpKeyAriaLabel?: string
  67  navigateDownKeyAriaLabel?: string
  68  switchTabsText?: string
  69  switchTabsKeyAriaLabel?: string
  70  switchPagesText?: string
  71  switchPagesKeyAriaLabel?: string
  72  closeText?: string
  73  closeKeyAriaLabel?: string
  74}
  75
  76export interface ModalTranslations {
  77  displayDetails?: string
  78  resetButtonTitle?: string
  79  backButtonTitle?: string
  80  noResultsText?: string
  81  footer?: FooterTranslations
  82}
  83
  84const showSearch = defineModel<boolean>()
  85
  86const el = shallowRef<HTMLElement>()
  87const resultsEl = shallowRef<HTMLElement>()
  88
  89/* Search */
  90interface Result {
  91  tabs?: string[]
  92  title: string
  93  titles: string[]
  94  text?: string
  95}
  96
  97const searchIndexData = shallowRef(localSearchIndex)
  98const searchIndexVersion = ref(0)
  99
 100// @ts-ignore
 101if (import.meta.hot) {
 102  // @ts-ignore
 103  import.meta.hot.accept('@localSearchIndex', (m) => {
 104    if (m) {
 105      searchIndexData.value = m.default
 106      searchIndexVersion.value++
 107    }
 108  })
 109}
 110
 111const vitePressData = useData()
 112const { activate } = useFocusTrap(el, {
 113  immediate: true,
 114  allowOutsideClick: true,
 115  clickOutsideDeactivates: true,
 116  escapeDeactivates: true,
 117  returnFocusOnDeactivate: false,
 118  initialFocus: () => {
 119    return searchInput.value
 120  }
 121})
 122const { localeIndex, theme } = vitePressData
 123
 124const disableQueryPersistence = computed(() => {
 125  return (
 126    theme.value.search?.provider === 'local' &&
 127    theme.value.search.options?.disableQueryPersistence === true
 128  )
 129})
 130
 131const filterText = disableQueryPersistence.value
 132  ? ref('')
 133  : useSessionStorage('vitepress:local-search-filter', '')
 134
 135const lowEndDeviceMode = useStorage(LowEndDeviceModeStorageKey, 'off')
 136const searchAnimationsEnabled = computed(() => lowEndDeviceMode.value !== 'on')
 137const showKeyboardShortcuts = computed(() => !filterText.value)
 138
 139const SearchMotionDiv = motion.div
 140const SearchMotionForm = motion.form
 141const SearchMotionLi = motion.li
 142const searchMotionDiv = computed(() =>
 143  searchAnimationsEnabled.value ? SearchMotionDiv : 'div'
 144)
 145const searchMotionForm = computed(() =>
 146  searchAnimationsEnabled.value ? SearchMotionForm : 'form'
 147)
 148const searchMotionLi = computed(() =>
 149  searchAnimationsEnabled.value ? SearchMotionLi : 'li'
 150)
 151const searchMotionEase = [0.16, 1, 0.3, 1]
 152
 153const backdropMotion = computed(() =>
 154  searchAnimationsEnabled.value
 155    ? {
 156      initial: { opacity: 0 },
 157      animate: { opacity: 1 },
 158      exit: { opacity: 0 },
 159      transition: { duration: 0.55, ease: searchMotionEase }
 160    }
 161    : {}
 162)
 163
 164const shellMotion = computed(() =>
 165  searchAnimationsEnabled.value
 166    ? {
 167      layout: 'size',
 168      initial: { opacity: 0, scale: 0.9375 },
 169      animate: { opacity: 1, scale: 1 },
 170      exit: { opacity: 0, scale: 0.9375 },
 171      transition: { duration: 0.55, ease: searchMotionEase }
 172    }
 173    : {}
 174)
 175
 176const formMotion = computed(() =>
 177  searchAnimationsEnabled.value ? { layout: 'position' } : {}
 178)
 179
 180const ribbonMotion = computed(() =>
 181  searchAnimationsEnabled.value
 182    ? {
 183      layout: 'position',
 184      initial: { opacity: 0, height: 0 },
 185      animate: { opacity: 1, height: 'auto' },
 186      exit: { opacity: 0, height: 0 },
 187      transition: { duration: 0.4, ease: searchMotionEase }
 188    }
 189    : {}
 190)
 191
 192const emptyStateMotion = computed(() =>
 193  searchAnimationsEnabled.value
 194    ? {
 195      initial: { opacity: 0 },
 196      animate: {
 197        opacity: 1,
 198        transition: { delay: 0.1 }
 199      },
 200      exit: {
 201        opacity: 0,
 202        height: 0,
 203        transition: { duration: 0.2 }
 204      },
 205      transition: { duration: 0.7, ease: searchMotionEase }
 206    }
 207    : {}
 208)
 209
 210function resultMotion(index: number) {
 211  if (!searchAnimationsEnabled.value) return {}
 212  return {
 213    layout: true,
 214    initial: { opacity: 0, scale: 0.9375 },
 215    animate: { opacity: 1, scale: 1 },
 216    exit: {
 217      opacity: 0,
 218      scale: 0.9375,
 219      height: 0,
 220      transition: { duration: 0.25 }
 221    },
 222    transition: {
 223      duration: 0.55,
 224      ease: searchMotionEase,
 225      delay: index * 0.02
 226    }
 227  }
 228}
 229
 230const excerptMotion = computed(() =>
 231  searchAnimationsEnabled.value
 232    ? {
 233      layout: true,
 234      initial: { height: 0 },
 235      animate: { height: '84px' },
 236      exit: { height: 0 },
 237      transition: { duration: 0.4, ease: searchMotionEase }
 238    }
 239    : {}
 240)
 241
 242const footerMotion = computed(() =>
 243  searchAnimationsEnabled.value ? { layout: true } : {}
 244)
 245
 246const urlFilterDebounced = ref(filterText.value)
 247let urlDebounceTimer: ReturnType<typeof setTimeout> | undefined
 248watch(filterText, (v) => {
 249  clearTimeout(urlDebounceTimer)
 250  if (!v) {
 251    urlFilterDebounced.value = '' // instant clear, no trailing-edge delay
 252    return
 253  }
 254  urlDebounceTimer = setTimeout(() => {
 255    urlFilterDebounced.value = v
 256  }, 60)
 257})
 258onBeforeUnmount(() => clearTimeout(urlDebounceTimer))
 259
 260const showDetailedList = useLocalStorage(
 261  'vitepress:local-search-detailed-list',
 262  false
 263)
 264
 265// Three search modes: 'exact' | 'fuzzy' | 'url'
 266const searchMode = useLocalStorage<'exact' | 'fuzzy' | 'url'>(
 267  'vitepress:local-search-mode',
 268  'exact'
 269)
 270
 271// Cycle through modes on mobile (only active button is visible, tap it to advance)
 272function cycleSearchMode() {
 273  const modes = ['exact', 'fuzzy', 'url'] as const
 274  const idx = modes.indexOf(searchMode.value)
 275  searchMode.value = modes[(idx + 1) % modes.length]
 276}
 277
 278// Keep matchExact and urlSearchMode as computed aliases
 279const matchExact = computed(() => searchMode.value === 'exact')
 280const urlSearchMode = computed(() => searchMode.value === 'url')
 281
 282interface PageGroupCount {
 283  key: string
 284  count: number
 285}
 286
 287const urlMatches = shallowRef<PageLink[]>([])
 288const urlPageGroupCounts = shallowRef<PageGroupCount[]>([])
 289
 290interface UrlResult {
 291  tabs?: string[]
 292  href: string
 293  linkText: string
 294  pageId: string
 295  anchor: string
 296  titles: string[]
 297  highlighted: string
 298}
 299
 300const URL_PAGE_SIZE = 25
 301
 302// 1-indexed current page within the URL results.
 303const urlPage = ref(1)
 304
 305// Full URL match set returned by the search worker.
 306// Used for accurate page-group counts in the ribbon and for pagination.
 307
 308// URL mode page ribbon — mirrors the normal pageGroups/filteredResults logic
 309const urlActivePageFilter = ref<string | null>(null)
 310
 311const urlPageGroups = computed(() =>
 312  urlPageGroupCounts.value
 313    .map((group) => ({
 314      key: group.key,
 315      label: getPageLabel(group.key),
 316      count: group.count
 317    }))
 318    .sort((a, b) => getPageOrder(a.key) - getPageOrder(b.key))
 319)
 320
 321// Full match set honoring the active ribbon page filter (uncapped).
 322const urlFilteredMatches = computed((): PageLink[] => {
 323  if (!urlActivePageFilter.value) return urlMatches.value
 324  return urlMatches.value.filter((l) => l.pageId === urlActivePageFilter.value)
 325})
 326
 327// Total number of result pages (Google-style paging through urlFilteredMatches).
 328const urlTotalPages = computed(() =>
 329  Math.max(1, Math.ceil(urlFilteredMatches.value.length / URL_PAGE_SIZE))
 330)
 331
 332// Clamp the current page whenever the result set shrinks.
 333const urlCurrentPage = computed(() =>
 334  Math.min(urlPage.value, urlTotalPages.value)
 335)
 336
 337// The rows actually rendered: the current page's slice of the filtered matches.
 338const filteredUrlResults = computed((): UrlResult[] => {
 339  const matches = urlFilteredMatches.value
 340  const start = (urlCurrentPage.value - 1) * URL_PAGE_SIZE
 341  const end = start + URL_PAGE_SIZE
 342  const out: UrlResult[] = []
 343  const query = urlFilterDebounced.value.trim()
 344  for (let i = start; i < end && i < matches.length; i++) {
 345    const link = matches[i]
 346    out.push({
 347      href: link.href,
 348      linkText: link.linkText,
 349      pageId: link.pageId,
 350      anchor: link.anchor,
 351      titles: link.titles,
 352      tabs: link.tabs,
 353      highlighted: highlightUrl(link.href, query)
 354    })
 355  }
 356  return out
 357})
 358
 359function escapeHtml(value: string) {
 360  return value
 361    .replace(/&/g, '&amp;')
 362    .replace(/</g, '&lt;')
 363    .replace(/>/g, '&gt;')
 364    .replace(/"/g, '&quot;')
 365    .replace(/'/g, '&#39;')
 366}
 367
 368function highlightUrl(url: string, query: string) {
 369  const needle = query.trim()
 370  if (!needle) return escapeHtml(url)
 371
 372  const lowerUrl = url.toLowerCase()
 373  const lowerNeedle = needle.toLowerCase()
 374  let out = ''
 375  let cursor = 0
 376  let index = lowerUrl.indexOf(lowerNeedle)
 377
 378  while (index !== -1) {
 379    out += escapeHtml(url.slice(cursor, index))
 380    out += `<mark class="url-highlight">${
 381      escapeHtml(url.slice(index, index + needle.length))
 382    }</mark>`
 383    cursor = index + needle.length
 384    index = lowerUrl.indexOf(lowerNeedle, cursor)
 385  }
 386
 387  return out + escapeHtml(url.slice(cursor))
 388}
 389
 390// Compact page-number list with ellipses, e.g. [1, '…', 4, 5, 6, '…', 12].
 391const urlPageList = computed<(number | '…')[]>(() => {
 392  const total = urlTotalPages.value
 393  const current = urlCurrentPage.value
 394  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1)
 395  const pages: (number | '…')[] = [1]
 396  const left = Math.max(2, current - 1)
 397  const right = Math.min(total - 1, current + 1)
 398  if (left > 2) pages.push('…')
 399  for (let p = left; p <= right; p++) pages.push(p)
 400  if (right < total - 1) pages.push('…')
 401  pages.push(total)
 402  return pages
 403})
 404
 405function goToUrlPage(p: number) {
 406  const target = Math.min(Math.max(1, p), urlTotalPages.value)
 407  if (target === urlCurrentPage.value) return
 408  urlPage.value = target
 409  selectedIndex.value = filteredUrlResults.value.length ? 1 : -1
 410  nextTick(() => {
 411    if (resultsEl.value) resultsEl.value.scrollTop = 0
 412    scrollToSelectedResult()
 413  })
 414}
 415
 416// Reset to page 1 whenever the query changes or the page filter changes.
 417watch([urlFilterDebounced, urlActivePageFilter], () => {
 418  urlPage.value = 1
 419})
 420
 421// Reset URL ribbon filter if the active page disappears from the groups.
 422watch(urlMatches, () => {
 423  if (
 424    urlActivePageFilter.value &&
 425    !urlPageGroups.value.some((g) => g.key === urlActivePageFilter.value)
 426  ) {
 427    urlActivePageFilter.value = null
 428  }
 429})
 430
 431watch(urlSearchMode, (active) => {
 432  if (!active) {
 433    urlActivePageFilter.value = null
 434    urlPage.value = 1
 435  }
 436})
 437
 438function setUrlPageFilter(key: string | null) {
 439  urlActivePageFilter.value = urlActivePageFilter.value === key ? null : key
 440  urlPage.value = 1
 441  selectedIndex.value = filteredUrlResults.value.length ? 1 : -1
 442  nextTick(() => {
 443    if (resultsEl.value) resultsEl.value.scrollTop = 0
 444    scrollToSelectedResult()
 445  })
 446}
 447
 448const disableDetailedView = computed(() => {
 449  return (
 450    theme.value.search?.provider === 'local' &&
 451    theme.value.search.options?.detailedView === false
 452  )
 453})
 454
 455const buttonText = computed(() => {
 456  const options = theme.value.search?.options
 457
 458  return (
 459    options?.locales?.[localeIndex.value]?.translations?.button?.buttonText ||
 460    options?.translations?.button?.buttonText ||
 461    'Search'
 462  )
 463})
 464
 465watchEffect(() => {
 466  if (disableDetailedView.value) {
 467    showDetailedList.value = false
 468  }
 469})
 470
 471const results: Ref<(SearchResult & Result)[]> = shallowRef([])
 472
 473const currentTerms = shallowRef(new Set<string>())
 474
 475const enableNoResults = ref(false)
 476const textSearchLoading = ref(false)
 477const urlSearchLoading = ref(false)
 478const searchLoading = computed(() =>
 479  urlSearchMode.value ? urlSearchLoading.value : textSearchLoading.value
 480)
 481const holdingLoadingImage = ref(false)
 482const loadingImageSrc = computed(() =>
 483  holdingLoadingImage.value ? '/pet.webp' : '/bubba.webp'
 484)
 485
 486const pageMeta = (() => {
 487  const map = new Map<string, { label: string; order: number }>()
 488  let order = 0
 489  const stripIcon = (text: string) =>
 490    text
 491      .replace(/<[^>]*>/g, '')
 492      .replace(/\s+/g, ' ')
 493      .trim()
 494  const walk = (items: DefaultTheme.SidebarItem[]) => {
 495    for (const item of items) {
 496      if (item.link) {
 497        const key = item.link.replace(/\/$/, '')
 498        if (!map.has(key)) {
 499          map.set(key, { label: stripIcon(item.text ?? key), order: order++ })
 500        }
 501      }
 502      if (item.items) walk(item.items)
 503    }
 504  }
 505  walk(sidebar as DefaultTheme.SidebarItem[])
 506  return map
 507})()
 508
 509type SearchMode = 'exact' | 'fuzzy' | 'url'
 510
 511interface TextSearchWorkerPayload {
 512  results: (SearchResult & Result)[]
 513  terms: string[]
 514}
 515
 516interface UrlSearchWorkerPayload {
 517  matches: PageLink[]
 518  pageGroups: PageGroupCount[]
 519}
 520
 521interface LoadIndexWorkerRequest {
 522  type: 'load-index'
 523  localeIndex: string
 524  indexJson: unknown
 525  indexVersion: number
 526  config: ReturnType<typeof getMiniSearchWorkerConfig>
 527}
 528
 529interface TextSearchWorkerRequest {
 530  type: 'text-search'
 531  query: string
 532  mode: SearchMode
 533  pageOrderEntries: [string, number][]
 534}
 535
 536interface UrlSearchWorkerRequest {
 537  type: 'url-search'
 538  query: string
 539  pageOrderEntries: [string, number][]
 540}
 541
 542type SearchWorkerRequest =
 543  | LoadIndexWorkerRequest
 544  | TextSearchWorkerRequest
 545  | UrlSearchWorkerRequest
 546
 547const activePageFilter = ref<string | null>(null)
 548const searchWorkerReady = ref(false)
 549const searchWorkerConfigKey = computed(() =>
 550  JSON.stringify(getMiniSearchWorkerConfig())
 551)
 552let searchWorker: Worker | undefined
 553let searchWorkerRequestId = 0
 554let loadedWorkerIndexKey = ''
 555const searchWorkerRequests = new Map<
 556  number,
 557  {
 558    resolve: (value: unknown) => void
 559    reject: (reason?: unknown) => void
 560  }
 561>()
 562
 563function getPageOrderEntries(): [string, number][] {
 564  return [...pageMeta.entries()].map(([key, meta]) => [key, meta.order])
 565}
 566
 567function stripNonCloneable(value: unknown): unknown {
 568  if (typeof value === 'function' || typeof value === 'symbol') return undefined
 569  if (!value || typeof value !== 'object') return value
 570  if (Array.isArray(value)) {
 571    return value
 572      .map((item) => stripNonCloneable(item))
 573      .filter((item) => item !== undefined)
 574  }
 575
 576  const out: Record<string, unknown> = {}
 577  for (const [key, nestedValue] of Object.entries(value)) {
 578    const cloneable = stripNonCloneable(nestedValue)
 579    if (cloneable !== undefined) out[key] = cloneable
 580  }
 581  return out
 582}
 583
 584function getMiniSearchWorkerConfig() {
 585  const miniSearch = theme.value.search?.provider === 'local'
 586    ? theme.value.search.options?.miniSearch
 587    : undefined
 588  const rawSearchOptions = miniSearch?.searchOptions as
 589    | Record<string, unknown>
 590    | undefined
 591
 592  return {
 593    options: stripNonCloneable(miniSearch?.options) as
 594      | Record<string, unknown>
 595      | undefined,
 596    searchOptions: stripNonCloneable(rawSearchOptions) as
 597      | Record<string, unknown>
 598      | undefined,
 599    useDefaultBoostDocument:
 600      typeof rawSearchOptions?.boostDocument === 'function'
 601  }
 602}
 603
 604function ensureSearchWorker() {
 605  if (!inBrowser || searchWorker) return searchWorker
 606
 607  try {
 608    searchWorker = new Worker(
 609      new URL('../workers/searchWorker.ts', import.meta.url),
 610      {
 611        type: 'module'
 612      }
 613    )
 614  } catch (error) {
 615    console.error('[search] failed to start search worker', error)
 616    return
 617  }
 618
 619  searchWorker.onmessage = (event: MessageEvent) => {
 620    const data = event.data as {
 621      id: number
 622      type: string
 623      payload?: unknown
 624      error?: string
 625    }
 626    const request = searchWorkerRequests.get(data.id)
 627    if (!request) return
 628
 629    searchWorkerRequests.delete(data.id)
 630    if (data.type.endsWith(':error')) {
 631      request.reject(new Error(data.error ?? 'Search worker failed'))
 632    } else {
 633      request.resolve(data.payload)
 634    }
 635  }
 636  searchWorker.onerror = (event) => {
 637    console.error('[search] search worker error', event)
 638  }
 639  searchWorkerReady.value = true
 640  return searchWorker
 641}
 642
 643function postSearchWorker<T>(message: SearchWorkerRequest) {
 644  const worker = ensureSearchWorker()
 645  if (!worker) return Promise.reject(new Error('Search worker is unavailable'))
 646
 647  const id = ++searchWorkerRequestId
 648  return new Promise<T>((resolve, reject) => {
 649    searchWorkerRequests.set(id, {
 650      resolve: (value) => resolve(value as T),
 651      reject
 652    })
 653    worker.postMessage({ ...message, id })
 654  })
 655}
 656
 657onMounted(() => {
 658  ensureSearchWorker()
 659})
 660
 661onBeforeUnmount(() => {
 662  searchWorker?.terminate()
 663  searchWorker = undefined
 664  loadedWorkerIndexKey = ''
 665  searchWorkerReady.value = false
 666  for (const request of searchWorkerRequests.values()) {
 667    request.reject(new Error('Search worker was terminated'))
 668  }
 669  searchWorkerRequests.clear()
 670})
 671
 672watch(
 673  () =>
 674    [
 675      searchWorkerReady.value,
 676      showSearch.value,
 677      urlSearchMode.value,
 678      urlFilterDebounced.value
 679    ] as const,
 680  async ([ready, isOpen, active, query], _old, onCleanup) => {
 681    let canceled = false
 682    onCleanup(() => {
 683      canceled = true
 684    })
 685
 686    if (!active || !isOpen || !query.trim()) {
 687      urlMatches.value = []
 688      urlPageGroupCounts.value = []
 689      urlSearchLoading.value = false
 690      return
 691    }
 692    if (!ready) {
 693      urlSearchLoading.value = false
 694      return
 695    }
 696
 697    urlSearchLoading.value = true
 698    try {
 699      const payload = await postSearchWorker<UrlSearchWorkerPayload>({
 700        type: 'url-search',
 701        query,
 702        pageOrderEntries: getPageOrderEntries()
 703      })
 704      if (canceled) return
 705      urlMatches.value = payload.matches
 706      urlPageGroupCounts.value = payload.pageGroups
 707      urlSearchLoading.value = false
 708    } catch (error) {
 709      if (!canceled) {
 710        console.error('[search] URL search worker request failed', error)
 711        urlMatches.value = []
 712        urlPageGroupCounts.value = []
 713        urlSearchLoading.value = false
 714      }
 715    }
 716  },
 717  { immediate: true }
 718)
 719
 720function getPageKey(id: string) {
 721  return getDocId(id).replace(/\/$/, '')
 722}
 723
 724function getDocId(id: string) {
 725  const hashIndex = id.indexOf('#')
 726  return hashIndex === -1 ? id : id.slice(0, hashIndex)
 727}
 728
 729function getDocAnchor(id: string) {
 730  const hashIndex = id.indexOf('#')
 731  return hashIndex === -1 ? '' : id.slice(hashIndex + 1)
 732}
 733
 734function getPageLabel(key: string) {
 735  return pageMeta.get(key)?.label ?? key.replace(/^\//, '')
 736}
 737
 738function getPageOrder(key: string) {
 739  return pageMeta.get(key)?.order ?? Number.MAX_SAFE_INTEGER
 740}
 741
 742const pageGroups = computed(() => {
 743  const map = new Map<string, { key: string; label: string; count: number }>()
 744  for (const r of results.value) {
 745    const key = getPageKey(r.id)
 746    const existing = map.get(key)
 747    if (existing) existing.count++
 748    else map.set(key, { key, label: getPageLabel(key), count: 1 })
 749  }
 750  return [...map.values()].sort(
 751    (a, b) => getPageOrder(a.key) - getPageOrder(b.key)
 752  )
 753})
 754
 755const filteredResults = computed(() => {
 756  if (!activePageFilter.value) return results.value
 757  return results.value.filter(
 758    (r) => getPageKey(r.id) === activePageFilter.value
 759  )
 760})
 761
 762// --- Normal-mode (exact/fuzzy) pagination ---------------------------------
 763// Mirrors the URL-mode pager. filteredResults stays the full filtered set;
 764// pagedResults is the current page slice that actually renders.
 765const NORMAL_PAGE_SIZE = URL_PAGE_SIZE
 766
 767const normalPage = ref(1)
 768
 769const normalTotalPages = computed(() =>
 770  Math.max(1, Math.ceil(filteredResults.value.length / NORMAL_PAGE_SIZE))
 771)
 772
 773const normalCurrentPage = computed(() =>
 774  Math.min(normalPage.value, normalTotalPages.value)
 775)
 776
 777const pagedResults = computed(() => {
 778  const start = (normalCurrentPage.value - 1) * NORMAL_PAGE_SIZE
 779  return filteredResults.value.slice(start, start + NORMAL_PAGE_SIZE)
 780})
 781
 782const normalPageList = computed<(number | '…')[]>(() => {
 783  const total = normalTotalPages.value
 784  const current = normalCurrentPage.value
 785  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1)
 786  const pages: (number | '…')[] = [1]
 787  const left = Math.max(2, current - 1)
 788  const right = Math.min(total - 1, current + 1)
 789  if (left > 2) pages.push('…')
 790  for (let p = left; p <= right; p++) pages.push(p)
 791  if (right < total - 1) pages.push('…')
 792  pages.push(total)
 793  return pages
 794})
 795
 796function goToNormalPage(p: number) {
 797  const target = Math.min(Math.max(1, p), normalTotalPages.value)
 798  if (target === normalCurrentPage.value) return
 799  normalPage.value = target
 800  selectedIndex.value = pagedResults.value.length ? 1 : -1
 801  nextTick(() => {
 802    if (resultsEl.value) resultsEl.value.scrollTop = 0
 803    scrollToSelectedResult()
 804    reapplyHighlights()
 805  })
 806}
 807
 808// Reset to page 1 when the query changes (results replaced) or filter changes.
 809watch([results, activePageFilter], () => {
 810  normalPage.value = 1
 811})
 812// ---------------------------------------------------------------------------
 813
 814function setPageFilter(key: string | null) {
 815  activePageFilter.value = activePageFilter.value === key ? null : key
 816  selectedIndex.value = filteredResults.value.length ? 1 : -1
 817  nextTick(() => {
 818    if (resultsEl.value) resultsEl.value.scrollTop = 0
 819    scrollToSelectedResult()
 820    reapplyHighlights()
 821  })
 822}
 823
 824async function reapplyHighlights() {
 825  if (!showDetailedList.value || !currentTerms.value.size) {
 826    centerExcerptsUntilSettled()
 827    return
 828  }
 829  await new Promise<void>((resolve) => {
 830    mark.value?.unmark({
 831      done: () => {
 832        mark.value?.markRegExp(formMarkRegex(currentTerms.value), {
 833          done: () => resolve()
 834        })
 835      }
 836    })
 837  })
 838  await nextTick()
 839  centerExcerptsUntilSettled()
 840}
 841
 842watch(results, () => {
 843  if (
 844    activePageFilter.value &&
 845    !pageGroups.value.some((g) => g.key === activePageFilter.value)
 846  ) {
 847    activePageFilter.value = null
 848  }
 849})
 850
 851watch(filterText, () => {
 852  enableNoResults.value = false
 853})
 854
 855const ribbonTrack = shallowRef<HTMLElement>()
 856const ribbonCanScrollLeft = ref(false)
 857const ribbonCanScrollRight = ref(false)
 858
 859function getRibbonTrack(): HTMLElement | null {
 860  return (
 861    ribbonTrack.value ??
 862      (el.value?.querySelector('.page-ribbon-track') as HTMLElement | null)
 863  )
 864}
 865
 866function updateRibbonOverflow() {
 867  const track = getRibbonTrack()
 868  if (!track) {
 869    ribbonCanScrollLeft.value = false
 870    ribbonCanScrollRight.value = false
 871    return
 872  }
 873  ribbonCanScrollLeft.value = track.scrollLeft > 2
 874  ribbonCanScrollRight.value =
 875    track.scrollWidth - track.clientWidth - track.scrollLeft > 2
 876}
 877
 878function scrollActivePagePillIntoView(direction = 0) {
 879  nextTick(() => {
 880    const track = getRibbonTrack()
 881    if (!track) return
 882
 883    const pills = [...track.querySelectorAll<HTMLElement>('.page-pill')]
 884    const activeIndex = pills.findIndex((pill) =>
 885      pill.classList.contains('active')
 886    )
 887    const active = pills[activeIndex]
 888    if (!active) return
 889
 890    const trackRect = track.getBoundingClientRect()
 891    const activeRect = active.getBoundingClientRect()
 892    const gap = 8
 893    let nextScrollLeft = track.scrollLeft
 894
 895    if (activeRect.left < trackRect.left) {
 896      nextScrollLeft += activeRect.left - trackRect.left - gap
 897    } else if (activeRect.right > trackRect.right) {
 898      nextScrollLeft += activeRect.right - trackRect.right + gap
 899    }
 900
 901    const peek = pills[activeIndex + Math.sign(direction)]
 902    if (peek) {
 903      const peekRect = peek.getBoundingClientRect()
 904      if (direction > 0 && peekRect.right > trackRect.right) {
 905        nextScrollLeft += peekRect.right - trackRect.right + gap
 906      } else if (direction < 0 && peekRect.left < trackRect.left) {
 907        nextScrollLeft += peekRect.left - trackRect.left - gap
 908      }
 909    }
 910
 911    const max = track.scrollWidth - track.clientWidth
 912    track.scrollTo({
 913      left: Math.max(0, Math.min(max, nextScrollLeft)),
 914      behavior: searchAnimationsEnabled.value ? 'smooth' : 'auto'
 915    })
 916    updateRibbonOverflow()
 917  })
 918}
 919
 920let ribbonAnimHandle = 0
 921
 922function scrollRibbon(direction: number) {
 923  const track = getRibbonTrack()
 924  if (!track) return
 925  const max = track.scrollWidth - track.clientWidth
 926  const amount = track.clientWidth * 0.7 * direction
 927  const from = track.scrollLeft
 928  const to = Math.max(0, Math.min(max, from + amount))
 929  if (to === from) return
 930
 931  if (ribbonAnimHandle) cancelAnimationFrame(ribbonAnimHandle)
 932
 933  if (!searchAnimationsEnabled.value) {
 934    track.scrollLeft = to
 935    updateRibbonOverflow()
 936    return
 937  }
 938
 939  const duration = 280
 940  const start = performance.now()
 941  const ease = (t: number) => 1 - Math.pow(1 - t, 3)
 942
 943  const step = (now: number) => {
 944    const t = Math.min(1, (now - start) / duration)
 945    track.scrollLeft = from + (to - from) * ease(t)
 946    updateRibbonOverflow()
 947    if (t < 1) {
 948      ribbonAnimHandle = requestAnimationFrame(step)
 949    } else {
 950      ribbonAnimHandle = 0
 951    }
 952  }
 953  ribbonAnimHandle = requestAnimationFrame(step)
 954}
 955
 956watch(pageGroups, () => {
 957  nextTick(updateRibbonOverflow)
 958})
 959
 960watch(urlPageGroups, () => {
 961  nextTick(updateRibbonOverflow)
 962})
 963
 964useEventListener('resize', () => {
 965  updateRibbonOverflow()
 966})
 967
 968const mark = computedAsync(async () => {
 969  if (!resultsEl.value) return
 970  return markRaw(new Mark(resultsEl.value))
 971}, null)
 972
 973const cache = new LRUCache<string, Map<string, string>>(120)
 974
 975const inFlightExcerpts = new Map<string, Promise<void>>()
 976
 977const EAGER_EXCERPTS = 15
 978
 979function buildDocExcerpt(
 980  docId: string,
 981  filterTextValue: string
 982): Promise<void> {
 983  const cacheId = `${docId}\n${filterTextValue}`
 984  if (cache.get(cacheId)) return Promise.resolve()
 985  const pending = inFlightExcerpts.get(cacheId)
 986  if (pending) return pending
 987
 988  const job = (async () => {
 989    const { mod } = await fetchExcerpt(docId)
 990    if (cache.get(cacheId)) return
 991
 992    const comp = (mod as any).default ?? mod
 993    if (!(comp?.render || comp?.setup)) return // nothing renderable; don't cache
 994
 995    const map = new Map<string, string>()
 996    const app = createApp(comp)
 997    app.config.warnHandler = () => {}
 998    enhanceAppWithTabs(app, { renderAll: true })
 999    app.provide(dataSymbol, vitePressData)
1000    Object.defineProperties(app.config.globalProperties, {
1001      $frontmatter: {
1002        get() {
1003          return vitePressData.frontmatter.value
1004        }
1005      },
1006      $params: {
1007        get() {
1008          return vitePressData.page.value.params
1009        }
1010      }
1011    })
1012    const div = document.createElement('div')
1013    try {
1014      app.mount(div)
1015      const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6')
1016      headings.forEach((heading) => {
1017        const href = heading.querySelector('a')?.getAttribute('href')
1018        const anchor = href?.startsWith('#') && href.slice(1)
1019        if (!anchor) return
1020        let html = ''
1021        let node = heading as Element
1022        while (
1023          (node = node.nextElementSibling!) &&
1024          !/^h[1-6]$/i.test(node.tagName)
1025        ) {
1026          html += (node as HTMLElement).outerHTML
1027        }
1028        map.set(anchor, html)
1029      })
1030    } catch (e) {
1031      console.error('[search] excerpt render failed for', docId, e)
1032    } finally {
1033      try {
1034        app.unmount()
1035      } catch {
1036        /* ignore */
1037      }
1038    }
1039    cache.set(cacheId, map)
1040  })()
1041
1042  inFlightExcerpts.set(cacheId, job)
1043  job.finally(() => {
1044    if (inFlightExcerpts.get(cacheId) === job) inFlightExcerpts.delete(cacheId)
1045  })
1046  return job
1047}
1048
1049watchDebounced(
1050  () =>
1051    [
1052      searchWorkerReady.value,
1053      showSearch.value,
1054      localeIndex.value,
1055      searchIndexVersion.value,
1056      searchWorkerConfigKey.value,
1057      filterText.value,
1058      showDetailedList.value,
1059      searchMode.value
1060    ] as const,
1061  async (
1062    [
1063      ready,
1064      isOpen,
1065      localeIndexValue,
1066      indexVersion,
1067      configKey,
1068      filterTextValue,
1069      showDetailedListValue,
1070      mode
1071    ],
1072    old,
1073    onCleanup
1074  ) => {
1075    if (
1076      old?.[2] !== localeIndexValue ||
1077      old?.[3] !== indexVersion ||
1078      old?.[4] !== configKey
1079    ) {
1080      // Locale/config changes rebuild the worker index, so cached excerpts may no
1081      // longer match the active result set.
1082      cache.clear()
1083    }
1084
1085    let canceled = false
1086    onCleanup(() => {
1087      canceled = true
1088    })
1089
1090    if (!ready || !isOpen) {
1091      textSearchLoading.value = false
1092      return
1093    }
1094
1095    // In URL search mode, skip normal text search
1096    if (mode === 'url') {
1097      results.value = []
1098      currentTerms.value = new Set()
1099      enableNoResults.value = Boolean(filterTextValue.trim())
1100      textSearchLoading.value = false
1101      return
1102    }
1103
1104    const searchQuery = filterTextValue.trim()
1105    if (!searchQuery) {
1106      results.value = []
1107      currentTerms.value = new Set()
1108      enableNoResults.value = false
1109      textSearchLoading.value = false
1110      return
1111    }
1112
1113    textSearchLoading.value = true
1114    let workerPayload: TextSearchWorkerPayload
1115    try {
1116      const workerIndexKey =
1117        `${localeIndexValue}\n${indexVersion}\n${configKey}`
1118      if (loadedWorkerIndexKey !== workerIndexKey) {
1119        const indexJson = (await searchIndexData.value[localeIndexValue]?.())
1120          ?.default
1121        if (canceled) return
1122        await postSearchWorker<void>({
1123          type: 'load-index',
1124          localeIndex: localeIndexValue,
1125          indexJson,
1126          indexVersion,
1127          config: getMiniSearchWorkerConfig()
1128        })
1129        if (canceled) return
1130        loadedWorkerIndexKey = workerIndexKey
1131      }
1132
1133      workerPayload = await postSearchWorker<TextSearchWorkerPayload>({
1134        type: 'text-search',
1135        query: searchQuery,
1136        mode,
1137        pageOrderEntries: getPageOrderEntries()
1138      })
1139    } catch (error) {
1140      if (!canceled) {
1141        console.error('[search] text search worker request failed', error)
1142        results.value = []
1143        currentTerms.value = new Set()
1144        enableNoResults.value = true
1145        textSearchLoading.value = false
1146      }
1147      return
1148    }
1149    if (canceled) return
1150
1151    const _result = workerPayload.results
1152    const terms = new Set(workerPayload.terms)
1153    currentTerms.value = terms
1154    enableNoResults.value = true
1155
1156    if (!_result.length) {
1157      results.value = []
1158      textSearchLoading.value = false
1159      return
1160    }
1161
1162    const toRows = (list: (SearchResult & Result)[]) =>
1163      list.map((r) => {
1164        const id = getDocId(r.id)
1165        const anchor = getDocAnchor(r.id)
1166        const map = cache.get(`${id}\n${searchQuery}`)
1167        return { ...r, text: map?.get(anchor) ?? '' }
1168      })
1169
1170    const highlight = () =>
1171      new Promise<void>((resolve) => {
1172        if (!terms.size || !mark.value) {
1173          resolve()
1174          return
1175        }
1176        mark.value.unmark({
1177          done: () => {
1178            mark.value?.markRegExp(formMarkRegex(terms), {
1179              done: () => resolve()
1180            })
1181          }
1182        })
1183      })
1184
1185    const docOrderList: string[] = []
1186    const seenDocs = new Set<string>()
1187    for (const r of _result) {
1188      const docId = getDocId(r.id)
1189      if (!seenDocs.has(docId)) {
1190        seenDocs.add(docId)
1191        docOrderList.push(docId)
1192      }
1193    }
1194
1195    // Show results immediately (excerpts may be empty on first detail-view switch;
1196    // they fill in below once built)
1197    results.value = toRows(_result)
1198
1199    if (showDetailedListValue) {
1200      const eagerDocs = new Set<string>()
1201      for (const r of _result.slice(0, EAGER_EXCERPTS)) {
1202        eagerDocs.add(getDocId(r.id))
1203      }
1204      await Promise.all(
1205        [...eagerDocs].map((docId) => buildDocExcerpt(docId, searchQuery))
1206      )
1207      if (canceled) return
1208    }
1209
1210    results.value = toRows(_result)
1211
1212    await nextTick()
1213    if (canceled) return
1214    await highlight()
1215    await nextTick()
1216    await nextFrame()
1217    if (canceled) return
1218
1219    if (resultsEl.value) {
1220      resultsEl.value.scrollTop = 0
1221    }
1222    centerExcerptsUntilSettled()
1223
1224    if (showDetailedListValue) {
1225      const built = new Set<string>()
1226      for (const r of _result.slice(0, EAGER_EXCERPTS)) {
1227        built.add(getDocId(r.id))
1228      }
1229      const remaining = docOrderList.filter((d) => !built.has(d))
1230      if (remaining.length) {
1231        for (const docId of remaining) {
1232          await buildDocExcerpt(docId, searchQuery)
1233          if (canceled) return
1234          await nextFrame()
1235          if (canceled) return
1236        }
1237        results.value = toRows(_result)
1238        await nextTick()
1239        if (canceled) return
1240        await highlight()
1241        await nextTick()
1242        await nextFrame()
1243        if (canceled) return
1244        centerExcerptsUntilSettled()
1245      }
1246    }
1247    textSearchLoading.value = false
1248  },
1249  { debounce: 80, immediate: true }
1250)
1251
1252function centerExcerpts() {
1253  const excerpts = el.value?.querySelectorAll('.result .excerpt') ?? []
1254  for (let i = 0; i < excerpts.length; i++) {
1255    const excerptElement = excerpts[i] as HTMLElement
1256
1257    const markNode = excerptElement.querySelector(
1258      'mark[data-markjs="true"]'
1259    ) as HTMLElement | null
1260    if (!markNode) continue
1261
1262    const viewportHeight =
1263      Number.parseFloat(getComputedStyle(excerptElement).maxHeight) || 84
1264
1265    let offset = 0
1266    let node: HTMLElement | null = markNode
1267    while (node && node !== excerptElement) {
1268      offset += node.offsetTop
1269      node = node.offsetParent as HTMLElement | null
1270    }
1271
1272    const targetScrollTop = offset - viewportHeight / 2 +
1273      markNode.offsetHeight / 2
1274    excerptElement.scrollTop = Math.max(0, targetScrollTop)
1275  }
1276}
1277
1278let centerHandle = 0
1279
1280function centerExcerptsUntilSettled(
1281  duration = searchAnimationsEnabled.value ? 450 : 0
1282) {
1283  if (centerHandle) cancelAnimationFrame(centerHandle)
1284
1285  if (duration <= 0) {
1286    centerHandle = requestAnimationFrame(() => {
1287      centerExcerpts()
1288      centerHandle = 0
1289    })
1290    return
1291  }
1292
1293  const start = performance.now()
1294  const tick = () => {
1295    centerExcerpts()
1296    if (performance.now() - start < duration) {
1297      centerHandle = requestAnimationFrame(tick)
1298    } else {
1299      centerHandle = 0
1300    }
1301  }
1302  centerHandle = requestAnimationFrame(tick)
1303}
1304
1305onBeforeUnmount(() => {
1306  if (centerHandle) cancelAnimationFrame(centerHandle)
1307  if (ribbonAnimHandle) cancelAnimationFrame(ribbonAnimHandle)
1308})
1309
1310const excerptCache = new LRUCache<string, unknown>(24)
1311
1312async function fetchExcerpt(id: string) {
1313  const docId = getDocId(id)
1314
1315  const cached = excerptCache.get(docId)
1316  if (cached) return { id, mod: cached }
1317
1318  const file = pathToFile(docId)
1319  try {
1320    if (!file) throw new Error(`Cannot find file for id: ${id}`)
1321    const mod = await import(/*@vite-ignore*/ file)
1322
1323    excerptCache.set(docId, mod)
1324
1325    return { id, mod }
1326  } catch (e) {
1327    console.error(e)
1328    return { id, mod: {} }
1329  }
1330}
1331
1332const nextFrame = () =>
1333  new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
1334
1335function hasExcerptPreview(html?: string) {
1336  if (!html) return false
1337  return Boolean(
1338    html
1339      .replace(/<[^>]*>/g, ' ')
1340      .replace(/&nbsp;|&#160;/gi, ' ')
1341      .replace(/\s+/g, ' ')
1342      .trim()
1343  )
1344}
1345
1346/* Search input focus */
1347
1348const searchInput = ref<HTMLInputElement>()
1349const disableReset = computed(() => {
1350  return filterText.value?.length <= 0
1351})
1352function focusSearchInput(select = true) {
1353  searchInput.value?.focus()
1354  select && searchInput.value?.select()
1355}
1356
1357onMounted(() => {
1358  focusSearchInput()
1359})
1360
1361function onSearchBarClick(event: PointerEvent) {
1362  if (event.pointerType === 'mouse') {
1363    focusSearchInput()
1364  }
1365}
1366
1367/* Search keyboard selection */
1368
1369const selectedIndex = ref(-1)
1370const disableMouseOver = ref(true)
1371
1372// Active result list length (URL mode vs normal mode) — current page only
1373const activeResultsLength = computed(() =>
1374  urlSearchMode.value
1375    ? filteredUrlResults.value.length
1376    : pagedResults.value.length
1377)
1378
1379watch(pagedResults, (r) => {
1380  if (!urlSearchMode.value) {
1381    selectedIndex.value = r.length ? 0 : -1
1382    scrollToSelectedResult()
1383  }
1384})
1385
1386watch(filteredUrlResults, (r) => {
1387  if (urlSearchMode.value) {
1388    selectedIndex.value = r.length ? 0 : -1
1389    scrollToSelectedResult()
1390  }
1391})
1392
1393function scrollToSelectedResult() {
1394  nextTick(() => {
1395    const selectedEl = document.querySelector('.result.selected')
1396    selectedEl?.scrollIntoView({ block: 'nearest' })
1397  })
1398}
1399
1400function goToSearchPageDelta(delta: number) {
1401  if (urlSearchMode.value) {
1402    const target = urlCurrentPage.value + delta
1403    if (target < 1 || target > urlTotalPages.value) return false
1404    goToUrlPage(target)
1405    return true
1406  }
1407
1408  const target = normalCurrentPage.value + delta
1409  if (target < 1 || target > normalTotalPages.value) return false
1410  goToNormalPage(target)
1411  return true
1412}
1413
1414function cyclePageTab(delta: number) {
1415  if (urlSearchMode.value) {
1416    if (urlPageGroups.value.length <= 1) return false
1417    const keys = [null, ...urlPageGroups.value.map((group) => group.key)]
1418    const current = keys.indexOf(urlActivePageFilter.value)
1419    const next = (current + delta + keys.length) % keys.length
1420    setUrlPageFilter(keys[next])
1421    scrollActivePagePillIntoView(delta)
1422    return true
1423  }
1424
1425  if (pageGroups.value.length <= 1) return false
1426  const keys = [null, ...pageGroups.value.map((group) => group.key)]
1427  const current = keys.indexOf(activePageFilter.value)
1428  const next = (current + delta + keys.length) % keys.length
1429  setPageFilter(keys[next])
1430  scrollActivePagePillIntoView(delta)
1431  return true
1432}
1433
1434onKeyStroke('ArrowUp', (event) => {
1435  event.preventDefault()
1436  selectedIndex.value--
1437  if (selectedIndex.value < 0) {
1438    selectedIndex.value = activeResultsLength.value - 1
1439  }
1440  disableMouseOver.value = true
1441  scrollToSelectedResult()
1442})
1443
1444onKeyStroke('ArrowDown', (event) => {
1445  event.preventDefault()
1446  selectedIndex.value++
1447  if (selectedIndex.value >= activeResultsLength.value + 1) {
1448    selectedIndex.value = 0
1449  }
1450  disableMouseOver.value = true
1451  scrollToSelectedResult()
1452})
1453
1454onKeyStroke('ArrowLeft', (event) => {
1455  if (!goToSearchPageDelta(-1)) return
1456  event.preventDefault()
1457  disableMouseOver.value = true
1458})
1459
1460onKeyStroke('ArrowRight', (event) => {
1461  if (!goToSearchPageDelta(1)) return
1462  event.preventDefault()
1463  disableMouseOver.value = true
1464})
1465
1466onKeyStroke('Tab', (event) => {
1467  if (!showSearch.value) return
1468  if (!cyclePageTab(event.shiftKey ? -1 : 1)) return
1469  event.preventDefault()
1470  disableMouseOver.value = true
1471})
1472
1473const router = useRouter()
1474
1475function buildResultHref(pageId: string, tabs?: string[], anchor = '') {
1476  const query = tabs?.length
1477    ? `?tabs=${tabs.map((tab) => encodeURIComponent(tab)).join(',')}`
1478    : ''
1479  const hash = anchor ? `#${encodeURIComponent(anchor)}` : ''
1480  return `${pageId}${query}${hash}`
1481}
1482
1483function getSearchResultHref(item: SearchResult & Result) {
1484  const id = String(item.id)
1485  const hashIndex = id.indexOf('#')
1486  if (hashIndex < 0) return buildResultHref(id, item.tabs)
1487
1488  return buildResultHref(
1489    id.slice(0, hashIndex),
1490    item.tabs,
1491    id.slice(hashIndex + 1)
1492  )
1493}
1494
1495function navigateToUrlResult(item: UrlResult) {
1496  window.dispatchEvent(
1497    new CustomEvent('search-nav', { detail: { query: filterText.value } })
1498  )
1499  router.go(buildResultHref(item.pageId, item.tabs, item.anchor))
1500  showSearch.value = false
1501}
1502
1503onKeyStroke('Enter', (e) => {
1504  if (e.isComposing) return
1505
1506  if (e.target instanceof HTMLButtonElement && e.target.type !== 'submit') {
1507    return
1508  }
1509
1510  const index = selectedIndex.value - 1
1511
1512  if (index === -1) {
1513    // @ts-ignore
1514    window.toggleAI({ value: filterText.value })
1515    showSearch.value = false
1516    return
1517  }
1518
1519  // URL search mode: navigate to the page containing the link (like normal search)
1520  if (urlSearchMode.value) {
1521    const selectedUrl = filteredUrlResults.value[index]
1522    if (selectedUrl) {
1523      navigateToUrlResult(selectedUrl)
1524    }
1525    return
1526  }
1527
1528  const selectedPackage = pagedResults.value[index]
1529  if (e.target instanceof HTMLInputElement && !selectedPackage) {
1530    e.preventDefault()
1531    return
1532  }
1533
1534  if (selectedPackage) {
1535    window.dispatchEvent(
1536      new CustomEvent('search-nav', {
1537        detail: { query: filterText.value }
1538      })
1539    )
1540    router.go(getSearchResultHref(selectedPackage))
1541    showSearch.value = false
1542  }
1543})
1544
1545function onResultClick() {
1546  window.dispatchEvent(
1547    new CustomEvent('search-nav', {
1548      detail: { query: filterText.value }
1549    })
1550  )
1551  showSearch.value = false
1552}
1553
1554onKeyStroke('Escape', () => {
1555  showSearch.value = false
1556})
1557
1558// Translations
1559const defaultTranslations = {
1560  modal: {
1561    displayDetails: 'Display detailed list',
1562    exactMatchTitle: 'Exact search',
1563    resetButtonTitle: 'Reset search',
1564    backButtonTitle: 'Close search',
1565    noResultsText: 'No results for',
1566    footer: {
1567      selectText: 'select',
1568      selectKeyAriaLabel: 'enter',
1569      navigateText: 'navigate',
1570      navigateUpKeyAriaLabel: 'up arrow',
1571      navigateDownKeyAriaLabel: 'down arrow',
1572      switchTabsText: 'switch tabs',
1573      switchTabsKeyAriaLabel: 'shift tab and tab',
1574      switchPagesText: 'switch pages',
1575      switchPagesKeyAriaLabel: 'left and right arrow',
1576      closeText: 'close',
1577      closeKeyAriaLabel: 'escape'
1578    }
1579  }
1580}
1581
1582const translate = createSearchTranslate(defaultTranslations)
1583
1584// Back
1585
1586onMounted(() => {
1587  // Prevents going to previous site
1588  window.history.pushState(null, '', null)
1589})
1590
1591useEventListener('popstate', (event) => {
1592  event.preventDefault()
1593  showSearch.value = false
1594})
1595
1596/** Lock body */
1597const isLocked = useScrollLock(inBrowser ? document.body : null)
1598
1599watch(
1600  () => showSearch.value,
1601  (val) => {
1602    if (!val) {
1603      isLocked.value = false
1604      return
1605    }
1606
1607    nextTick(() => {
1608      isLocked.value = true
1609      nextTick().then(() => {
1610        activate()
1611        updateRibbonOverflow()
1612      })
1613    })
1614  }
1615)
1616
1617function formMarkRegex(terms: Set<string>) {
1618  return new RegExp(
1619    [...terms]
1620      .sort((a, b) => b.length - a.length)
1621      .map((term) => `(${escapeRegExp(term)})`)
1622      .join('|'),
1623    'gi'
1624  )
1625}
1626
1627function resetSearch() {
1628  filterText.value = ''
1629  nextTick().then(() => focusSearchInput(false))
1630}
1631
1632function onMouseMove(e: MouseEvent) {
1633  if (!disableMouseOver.value) return
1634  const el = (e.target as HTMLElement)?.closest<HTMLAnchorElement>('.result')
1635  const index = Number.parseInt(el?.dataset.index!)
1636  if (index >= 0 && index !== selectedIndex.value) {
1637    selectedIndex.value = index
1638  }
1639  disableMouseOver.value = false
1640}
1641</script>
1642
1643<template>
1644  <Teleport to="body">
1645    <div
1646      ref="el"
1647      role="button"
1648      :aria-owns="results?.length ? 'localsearch-list' : undefined"
1649      aria-expanded="true"
1650      aria-haspopup="listbox"
1651      aria-labelledby="localsearch-label"
1652      class="VPLocalSearchBox"
1653      :class="{ 'pointer-events-none': !showSearch }"
1654    >
1655      <AnimatePresence>
1656        <component
1657          :is="searchMotionDiv"
1658          v-if="showSearch"
1659          class="backdrop"
1660          @click="showSearch = false"
1661          v-bind="backdropMotion"
1662        />
1663      </AnimatePresence>
1664
1665      <AnimatePresence>
1666        <component
1667          :is="searchMotionDiv"
1668          v-if="showSearch"
1669          class="shell"
1670          v-bind="shellMotion"
1671        >
1672          <component
1673            :is="searchMotionForm"
1674            class="search-bar"
1675            v-bind="formMotion"
1676            @pointerup="onSearchBarClick($event)"
1677            @submit.prevent=""
1678          >
1679            <label
1680              :title="buttonText"
1681              id="localsearch-label"
1682              for="localsearch-input"
1683            >
1684              <span
1685                aria-hidden="true"
1686                class="vpi-search search-icon local-search-icon"
1687              />
1688            </label>
1689            <div class="search-actions before">
1690              <button
1691                class="back-button"
1692                :title="translate('modal.backButtonTitle')"
1693                @click="showSearch = false"
1694              >
1695                <span class="vpi-arrow-left local-search-icon" />
1696              </button>
1697            </div>
1698            <input
1699              ref="searchInput"
1700              v-model="filterText"
1701              :aria-activedescendant="selectedIndex > -1
1702              ? 'localsearch-item-' + selectedIndex
1703              : undefined"
1704              aria-autocomplete="both"
1705              :aria-controls="results?.length ? 'localsearch-list' : undefined"
1706              aria-labelledby="localsearch-label"
1707              autocapitalize="off"
1708              autocomplete="off"
1709              autocorrect="off"
1710              class="search-input"
1711              id="localsearch-input"
1712              enterkeyhint="go"
1713              maxlength="64"
1714              :placeholder="buttonText"
1715              spellcheck="false"
1716              type="search"
1717            />
1718            <div class="search-actions">
1719              <button
1720                v-if="searchLoading"
1721                class="search-loading-button"
1722                type="button"
1723                aria-label="Hold to show pet image"
1724                @pointerdown.stop="holdingLoadingImage = true"
1725                @pointerup.stop="holdingLoadingImage = false"
1726                @pointerleave="holdingLoadingImage = false"
1727                @pointercancel="holdingLoadingImage = false"
1728                @blur="holdingLoadingImage = false"
1729                @contextmenu.prevent
1730              >
1731                <img
1732                  class="search-loading-bubba"
1733                  :src="loadingImageSrc"
1734                  :alt="holdingLoadingImage
1735                  ? 'Pet'
1736                  : 'Bubba loading'"
1737                />
1738              </button>
1739              <div
1740                v-if="!disableDetailedView && searchMode !== 'url'"
1741                class="view-group toolbar-group"
1742              >
1743                <button
1744                  type="button"
1745                  class="mode-btn"
1746                  :class="{ 'mode-active': showDetailedList }"
1747                  title="Detail view (Consumes more RAM)"
1748                  @click="showDetailedList
1749                  ? showDetailedList = false
1750                  : showDetailedList = true"
1751                >
1752                  <TextAlignStart :size="18" stroke-width="1.25" />
1753                </button>
1754                <button
1755                  type="button"
1756                  class="mode-btn"
1757                  :class="{ 'mode-active': !showDetailedList }"
1758                  title="List view (Consumes less RAM)"
1759                  @click="!showDetailedList
1760                  ? showDetailedList = true
1761                  : showDetailedList = false"
1762                >
1763                  <List :size="18" stroke-width="1.25" />
1764                </button>
1765              </div>
1766              <div class="search-mode-group toolbar-group">
1767                <button
1768                  type="button"
1769                  class="mode-btn"
1770                  :class="{ 'mode-active': searchMode === 'exact' }"
1771                  title="Exact search"
1772                  @click="searchMode === 'exact'
1773                  ? cycleSearchMode()
1774                  : searchMode = 'exact'"
1775                >
1776                  <Regex :size="18" stroke-width="1.25" />
1777                </button>
1778                <button
1779                  type="button"
1780                  class="mode-btn"
1781                  :class="{ 'mode-active': searchMode === 'fuzzy' }"
1782                  title="Fuzzy search"
1783                  @click="searchMode === 'fuzzy'
1784                  ? cycleSearchMode()
1785                  : searchMode = 'fuzzy'"
1786                >
1787                  <LocateOff :size="18" stroke-width="1.25" />
1788                </button>
1789                <button
1790                  type="button"
1791                  class="mode-btn"
1792                  :class="{ 'mode-active': searchMode === 'url' }"
1793                  title="URL search"
1794                  @click="searchMode === 'url'
1795                  ? cycleSearchMode()
1796                  : searchMode = 'url'"
1797                >
1798                  <Globe :size="18" stroke-width="1.25" />
1799                </button>
1800              </div>
1801              <button
1802                class="clear-button"
1803                type="reset"
1804                :disabled="disableReset"
1805                :title="translate('modal.resetButtonTitle')"
1806                @click="resetSearch"
1807              >
1808                <Delete :size="19" stroke-width="1.25" />
1809              </button>
1810            </div>
1811          </component>
1812
1813          <AnimatePresence>
1814            <component
1815              :is="searchMotionDiv"
1816              v-if="urlSearchMode
1817              ? urlPageGroups.length > 1
1818              : pageGroups.length > 1"
1819              class="page-ribbon"
1820              :class="{
1821                'can-scroll-left': ribbonCanScrollLeft,
1822                'can-scroll-right': ribbonCanScrollRight
1823              }"
1824              v-bind="ribbonMotion"
1825            >
1826              <button
1827                v-if="ribbonCanScrollLeft"
1828                type="button"
1829                class="page-ribbon-arrow left"
1830                aria-label="Scroll filters left"
1831                @click="scrollRibbon(-1)"
1832              >
1833                <ChevronRight :size="18" stroke-width="1.75" />
1834              </button>
1835              <div
1836                ref="ribbonTrack"
1837                class="page-ribbon-track"
1838                @scroll="updateRibbonOverflow"
1839              >
1840                <!-- URL mode tabs -->
1841                <template v-if="urlSearchMode">
1842                  <button
1843                    type="button"
1844                    class="page-pill"
1845                    :class="{
1846                      active: urlActivePageFilter === null
1847                    }"
1848                    @click="setUrlPageFilter(null)"
1849                  >
1850                    All
1851                    <span class="page-pill-count">{{ urlMatches.length }}</span>
1852                  </button>
1853                  <button
1854                    v-for="group in urlPageGroups"
1855                    :key="group.key"
1856                    type="button"
1857                    class="page-pill"
1858                    :class="{
1859                      active:
1860                        urlActivePageFilter === group.key
1861                    }"
1862                    @click="setUrlPageFilter(group.key)"
1863                  >
1864                    <span class="page-pill-label">{{ group.label }}</span>
1865                    <span class="page-pill-count">{{ group.count }}</span>
1866                  </button>
1867                </template>
1868                <!-- Normal mode tabs -->
1869                <template v-else>
1870                  <button
1871                    type="button"
1872                    class="page-pill"
1873                    :class="{ active: activePageFilter === null }"
1874                    @click="setPageFilter(null)"
1875                  >
1876                    All
1877                    <span class="page-pill-count">{{ results.length }}</span>
1878                  </button>
1879                  <button
1880                    v-for="group in pageGroups"
1881                    :key="group.key"
1882                    type="button"
1883                    class="page-pill"
1884                    :class="{
1885                      active: activePageFilter === group.key
1886                    }"
1887                    @click="setPageFilter(group.key)"
1888                  >
1889                    <span class="page-pill-label">{{ group.label }}</span>
1890                    <span class="page-pill-count">{{ group.count }}</span>
1891                  </button>
1892                </template>
1893              </div>
1894              <button
1895                v-if="ribbonCanScrollRight"
1896                type="button"
1897                class="page-ribbon-arrow right"
1898                aria-label="Scroll filters right"
1899                @click="scrollRibbon(1)"
1900              >
1901                <ChevronRight :size="18" stroke-width="1.75" />
1902              </button>
1903            </component>
1904          </AnimatePresence>
1905
1906          <ul
1907            ref="resultsEl"
1908            :id="results?.length ? 'localsearch-list' : undefined"
1909            :role="results?.length ? 'listbox' : undefined"
1910            :aria-labelledby="results?.length ? 'localsearch-label' : undefined"
1911            class="results"
1912            @mousemove="onMouseMove"
1913          >
1914            <!-- Empty state (shared) -->
1915            <AnimatePresence>
1916              <component
1917                :is="searchMotionDiv"
1918                v-if="urlSearchMode
1919                ? (!filterText || !urlMatches.length)
1920                : (!filterText || !filteredResults.length)"
1921                class="flex flex-1 flex-col justify-center items-center w-full min-h-full gap-2 font-medium text-sm text-center text-gray-500 dark:text-gray-300 m-auto opacity-90"
1922                v-bind="emptyStateMotion"
1923              >
1924                <img
1925                  class="h-40 object-contain object-center"
1926                  src="/asset/smolame.png"
1927                  alt="Smol ame"
1928                />
1929                <h1 v-if="filterText">Couldn't find anything, try again?</h1>
1930                <h1 v-else>Looking for something?</h1>
1931              </component>
1932            </AnimatePresence>
1933
1934            <!-- URL search results -->
1935            <template v-if="urlSearchMode">
1936              <AnimatePresence>
1937                <component
1938                  :is="searchMotionLi"
1939                  v-for="(item, index) in filteredUrlResults"
1940                  :key="'url-' + urlCurrentPage + '-' +
1941                  item.pageId + '-' +
1942                  item.anchor + '-' + index"
1943                  class="result-layout"
1944                  :id="'localsearch-item-' + (index + 1)"
1945                  :aria-selected="selectedIndex === index + 1
1946                  ? 'true'
1947                  : 'false'"
1948                  role="option"
1949                  v-bind="resultMotion(index)"
1950                >
1951                  <div
1952                    class="result url-result-card"
1953                    :class="{
1954                      selected: selectedIndex === index + 1
1955                    }"
1956                    :aria-label="item.href"
1957                    role="button"
1958                    @mouseenter="!disableMouseOver &&
1959                    (selectedIndex = index + 1)"
1960                    @focusin="selectedIndex = index + 1"
1961                    @click="navigateToUrlResult(item)"
1962                    :data-index="index + 1"
1963                  >
1964                    <div class="url-result-body">
1965                      <div class="url-path">
1966                        <Hash
1967                          v-if="item.anchor ||
1968                          item.titles.length > 0"
1969                          stroke-width="1.25"
1970                          :size="18"
1971                        />
1972                        <File v-else stroke-width="1.25" :size="18" />
1973                        <span
1974                          v-for="(t, ti) in item.titles"
1975                          :key="ti"
1976                          class="url-path-segment"
1977                        >
1978                          <span class="text" v-html="t" />
1979                          <ArrowRight
1980                            stroke-width="1.25"
1981                            :size="18"
1982                            class="mx-0.5"
1983                          />
1984                        </span>
1985                        <span
1986                          v-if="item.linkText"
1987                          class="url-path-current"
1988                          v-html="item.linkText"
1989                        />
1990                      </div>
1991                      <a
1992                        :href="item.href"
1993                        target="_blank"
1994                        rel="noopener noreferrer"
1995                        class="url-link"
1996                        :title="item.href"
1997                        @click.stop
1998                        v-html="item.highlighted"
1999                      >
2000                      </a>
2001                    </div>
2002                  </div>
2003                </component>
2004              </AnimatePresence>
2005            </template>
2006
2007            <!-- Normal search results -->
2008            <template v-else>
2009              <AnimatePresence>
2010                <component
2011                  :is="searchMotionLi"
2012                  v-for="(p, index) in pagedResults"
2013                  :key="'normal-' + normalCurrentPage + '-' + p.id"
2014                  class="result-layout"
2015                  :id="'localsearch-item-' + (index + 1)"
2016                  :aria-selected="selectedIndex === index + 1
2017                  ? 'true'
2018                  : 'false'"
2019                  role="option"
2020                  v-bind="resultMotion(index)"
2021                >
2022                  <a
2023                    :href="getSearchResultHref(p)"
2024                    class="result"
2025                    :class="{
2026                      selected: selectedIndex === index + 1
2027                    }"
2028                    :aria-label="[...p.titles, p.title].join(' > ')"
2029                    @mouseenter="!disableMouseOver &&
2030                    (selectedIndex = index + 1)"
2031                    @focusin="selectedIndex = index + 1"
2032                    @click="onResultClick"
2033                    :data-index="index + 1"
2034                  >
2035                    <div>
2036                      <div class="titles">
2037                        <Hash
2038                          v-if="getDocAnchor(p.id) ||
2039                          p.titles.length > 0"
2040                          stroke-width="1.25"
2041                          :size="18"
2042                        />
2043                        <File v-else stroke-width="1.25" :size="18" />
2044                        <span
2045                          v-for="(t, index) in p.titles"
2046                          :key="index"
2047                          class="title"
2048                        >
2049                          <span class="text" v-html="t" />
2050                          <ArrowRight
2051                            stroke-width="1.25"
2052                            :size="18"
2053                            class="mx-0.5"
2054                          />
2055                        </span>
2056                        <span class="title main">
2057                          <span class="text" v-html="p.title" />
2058                        </span>
2059                      </div>
2060
2061                      <div
2062                        v-if="showDetailedList &&
2063                        hasExcerptPreview(p.text)"
2064                        class="excerpt-wrapper"
2065                      >
2066                        <component
2067                          :is="searchMotionDiv"
2068                          class="excerpt"
2069                          inert
2070                          v-bind="excerptMotion"
2071                        >
2072                          <div class="vp-doc" v-html="p.text" />
2073                        </component>
2074                        <div class="excerpt-gradient-bottom" />
2075                        <div class="excerpt-gradient-top" />
2076                      </div>
2077                    </div>
2078                  </a>
2079                </component>
2080              </AnimatePresence>
2081            </template>
2082          </ul>
2083
2084          <!-- Bottom section: pagination (when needed). Always rendered so the
2085             shell's rounded bottom edge stays consistent. -->
2086          <nav
2087            class="url-pagination"
2088            aria-label="Search result pages"
2089          >
2090            <div
2091              v-if="(urlSearchMode
2092              ? urlTotalPages
2093              : normalTotalPages) > 1"
2094              class="url-pagination-segment"
2095            >
2096              <button
2097                type="button"
2098                class="url-page-btn url-page-nav"
2099                :disabled="(urlSearchMode
2100                ? urlCurrentPage
2101                : normalCurrentPage) <= 1"
2102                aria-label="Previous page"
2103                @click="urlSearchMode
2104                ? goToUrlPage(urlCurrentPage - 1)
2105                : goToNormalPage(normalCurrentPage - 1)"
2106              >
2107                <ChevronRight
2108                  :size="14"
2109                  stroke-width="2"
2110                  style="transform: rotate(180deg)"
2111                />
2112              </button>
2113
2114              <template
2115                v-for="(p, pi) in urlSearchMode ? urlPageList : normalPageList"
2116                :key="pi"
2117              >
2118                <span v-if="p === '…'" class="url-page-ellipsis">…</span>
2119                <button
2120                  v-else
2121                  type="button"
2122                  class="url-page-btn"
2123                  :class="{
2124                    active: p === (urlSearchMode
2125                      ? urlCurrentPage
2126                      : normalCurrentPage)
2127                  }"
2128                  :aria-current="p === (urlSearchMode
2129                    ? urlCurrentPage
2130                    : normalCurrentPage)
2131                  ? 'page'
2132                  : undefined"
2133                  @click="urlSearchMode
2134                  ? goToUrlPage(p as number)
2135                  : goToNormalPage(p as number)"
2136                >
2137                  {{ p }}
2138                </button>
2139              </template>
2140
2141              <button
2142                type="button"
2143                class="url-page-btn url-page-nav"
2144                :disabled="(urlSearchMode
2145                ? urlCurrentPage
2146                : normalCurrentPage) >=
2147                (urlSearchMode
2148                  ? urlTotalPages
2149                  : normalTotalPages)"
2150                aria-label="Next page"
2151                @click="urlSearchMode
2152                ? goToUrlPage(urlCurrentPage + 1)
2153                : goToNormalPage(normalCurrentPage + 1)"
2154              >
2155                <ChevronRight :size="14" stroke-width="2" />
2156              </button>
2157            </div>
2158          </nav>
2159
2160          <component
2161            :is="searchMotionDiv"
2162            v-if="showKeyboardShortcuts"
2163            class="search-keyboard-shortcuts"
2164            v-bind="footerMotion"
2165          >
2166            <span>
2167              <kbd
2168                :aria-label="translate(
2169                  'modal.footer.navigateUpKeyAriaLabel'
2170                )"
2171              >
2172                <span class="vpi-arrow-up navigate-icon" />
2173              </kbd>
2174              <kbd
2175                :aria-label="translate(
2176                  'modal.footer.navigateDownKeyAriaLabel'
2177                )"
2178              >
2179                <span class="vpi-arrow-down navigate-icon" />
2180              </kbd>
2181              {{ translate('modal.footer.navigateText') }}
2182            </span>
2183            <span>
2184              <kbd :aria-label="translate('modal.footer.switchTabsKeyAriaLabel')">
2185                <ArrowLeftToLine class="navigate-icon" :size="14" stroke-width="2" />
2186              </kbd>
2187              <kbd :aria-label="translate('modal.footer.switchTabsKeyAriaLabel')">
2188                <ArrowRightToLine class="navigate-icon" :size="14" stroke-width="2" />
2189              </kbd>
2190              {{ translate('modal.footer.switchTabsText') }}
2191            </span>
2192            <span>
2193              <kbd :aria-label="translate('modal.footer.switchPagesKeyAriaLabel')">
2194                <ArrowLeft class="navigate-icon" :size="14" stroke-width="2" />
2195              </kbd>
2196              <kbd :aria-label="translate('modal.footer.switchPagesKeyAriaLabel')">
2197                <ArrowRight class="navigate-icon" :size="14" stroke-width="2" />
2198              </kbd>
2199              {{ translate('modal.footer.switchPagesText') }}
2200            </span>
2201            <span>
2202              <kbd :aria-label="translate('modal.footer.selectKeyAriaLabel')">
2203                <span class="vpi-corner-down-left navigate-icon" />
2204              </kbd>
2205              {{ translate('modal.footer.selectText') }}
2206            </span>
2207            <span>
2208              <kbd :aria-label="translate('modal.footer.closeKeyAriaLabel')">
2209                esc
2210              </kbd>
2211              {{ translate('modal.footer.closeText') }}
2212            </span>
2213          </component>
2214        </component>
2215      </AnimatePresence>
2216
2217      <button v-if="!showSearch" />
2218    </div>
2219  </Teleport>
2220</template>
2221
2222<style scoped>
2223.VPLocalSearchBox {
2224  position: fixed;
2225  z-index: 100;
2226  inset: 0;
2227  display: flex;
2228  align-items: flex-start;
2229}
2230
2231@media (max-width: 767px) {
2232  .VPLocalSearchBox {
2233    align-items: stretch;
2234  }
2235}
2236
2237.backdrop {
2238  position: absolute;
2239  inset: 0;
2240  background: var(--vp-backdrop-bg-color);
2241}
2242
2243.shell {
2244  position: relative;
2245  box-sizing: border-box;
2246  padding: 12px 12px 8px;
2247  margin: 64px auto;
2248  display: flex;
2249  flex-direction: column;
2250  gap: 16px;
2251  background: var(--vp-local-search-bg);
2252  width: min(100vw - 60px, 900px);
2253  height: 100%;
2254  max-height: min(100vh - 128px, 900px);
2255  border-radius: 6px;
2256}
2257
2258@media (max-width: 767px) {
2259  .shell {
2260    margin: 0;
2261    width: 100vw;
2262    height: 100vh;
2263    height: 100dvh;
2264    max-height: none;
2265    border-radius: 0;
2266    overflow: hidden;
2267    gap: 8px;
2268  }
2269}
2270
2271.search-bar {
2272  flex: 0 0 auto !important;
2273  min-height: 44px !important;
2274  border: 1px solid var(--vp-c-divider);
2275  border-radius: 4px;
2276  display: flex;
2277  align-items: center;
2278  padding: 0 12px;
2279  cursor: text;
2280}
2281
2282@media (max-width: 767px) {
2283  .search-bar {
2284    padding: 0 8px;
2285    min-height: 40px !important;
2286  }
2287}
2288
2289.search-bar:focus-within {
2290  border-color: var(--vp-c-brand-1);
2291}
2292
2293.page-ribbon {
2294  display: flex;
2295  align-items: center;
2296  padding: 12px 0 4px;
2297  padding-inline: calc(var(--spacing) * 3);
2298  position: relative;
2299  min-width: 0;
2300  flex: none;
2301  overflow: hidden;
2302  transition: padding-inline 0.15s;
2303}
2304
2305.page-ribbon.can-scroll-left {
2306  padding-left: 42px;
2307}
2308
2309.page-ribbon.can-scroll-right {
2310  padding-right: 42px;
2311}
2312
2313.page-ribbon-track {
2314  display: flex;
2315  flex-wrap: nowrap;
2316  gap: 8px;
2317  min-width: 0;
2318  flex: 1;
2319  overflow-x: auto;
2320  overflow-y: hidden;
2321  scrollbar-width: none;
2322  -ms-overflow-style: none;
2323  overscroll-behavior-x: contain;
2324}
2325
2326.page-ribbon-track::-webkit-scrollbar {
2327  display: none;
2328  width: 0;
2329  height: 0;
2330}
2331
2332.page-ribbon-arrow {
2333  position: absolute;
2334  top: 12px;
2335  bottom: 4px;
2336  z-index: 2;
2337  display: inline-flex;
2338  align-items: center;
2339  justify-content: center;
2340  width: 48px;
2341  border: none;
2342  background: transparent;
2343  color: var(--vp-c-text-2);
2344  cursor: pointer;
2345  transition: color 0.15s;
2346}
2347
2348.page-ribbon-arrow:hover {
2349  color: var(--vp-c-text-1);
2350}
2351
2352.page-ribbon-arrow.right {
2353  right: 0;
2354  justify-content: flex-end;
2355  padding-right: 6px;
2356}
2357
2358.page-ribbon-arrow.left {
2359  left: 0;
2360  justify-content: flex-start;
2361  padding-left: 6px;
2362}
2363
2364.page-ribbon-arrow.left svg {
2365  transform: rotate(180deg);
2366}
2367
2368.page-pill {
2369  flex: none;
2370  display: inline-flex;
2371  align-items: center;
2372  gap: 6px;
2373  padding: 6px 10px;
2374  font-size: 0.8rem;
2375  line-height: 1.2;
2376  white-space: nowrap;
2377  border-radius: 8px;
2378  border: 1.5px solid var(--vp-c-divider);
2379  background: var(--vp-c-bg-soft);
2380  color: var(--vp-c-text-2);
2381  cursor: pointer;
2382  transition: color 0.15s, border-color 0.15s, background-color 0.15s;
2383}
2384
2385.page-pill:hover {
2386  color: var(--vp-c-text-1);
2387  border-color: var(--vp-c-brand-1);
2388}
2389
2390.page-pill.active {
2391  color: #6ab0f5;
2392  border: 1.5px solid #6ab0f5;
2393  background: rgba(60, 120, 210, 0.12);
2394  box-shadow: none;
2395}
2396
2397.page-pill-label {
2398  max-width: 180px;
2399  overflow: hidden;
2400  text-overflow: ellipsis;
2401}
2402
2403.page-pill-count {
2404  font-variant-numeric: tabular-nums;
2405  font-size: 0.7rem;
2406  padding: 1px 6px;
2407  border-radius: 4px;
2408  background: rgba(128, 128, 128, 0.15);
2409  color: inherit;
2410}
2411
2412.page-pill.active .page-pill-count {
2413  background: rgba(100, 160, 240, 0.18);
2414}
2415
2416@media (max-width: 767px) {
2417  .page-ribbon {
2418    padding: 14px 12px 4px;
2419  }
2420
2421  .page-pill {
2422    padding: 7px 14px;
2423    font-size: 0.82rem;
2424    background: var(--vp-c-bg-elv, var(--vp-c-bg-soft));
2425    border-color: var(--vp-c-divider);
2426    color: var(--vp-c-text-1);
2427  }
2428}
2429
2430.local-search-icon {
2431  display: block;
2432  font-size: 18px;
2433}
2434
2435.navigate-icon {
2436  display: block;
2437  font-size: 14px;
2438}
2439
2440.search-icon {
2441  margin: 8px;
2442}
2443
2444@media (max-width: 767px) {
2445  .search-icon {
2446    display: none;
2447  }
2448}
2449
2450.search-input {
2451  flex: 1 1 auto;
2452  min-width: 0;
2453  padding: 6px 12px;
2454  font-size: inherit;
2455  width: 100%;
2456}
2457
2458.search-input::-webkit-search-cancel-button {
2459  display: none;
2460}
2461
2462@media (max-width: 767px) {
2463  .search-input {
2464    padding: 6px 4px;
2465  }
2466}
2467
2468.search-actions {
2469  flex: 0 0 auto;
2470  display: flex;
2471  align-items: center;
2472  gap: 4px;
2473}
2474
2475.search-loading-button {
2476  display: inline-flex;
2477  align-items: center;
2478  justify-content: center;
2479  padding: 0 !important;
2480  margin-inline-end: 6px;
2481  border: 0;
2482  background: transparent;
2483  cursor: pointer;
2484}
2485
2486.search-loading-bubba {
2487  width: 32px;
2488  height: 28px;
2489  object-fit: contain;
2490  image-rendering: pixelated;
2491  user-select: none;
2492}
2493
2494@media (any-pointer: coarse) {
2495  .search-actions {
2496    gap: 8px;
2497  }
2498}
2499
2500@media (min-width: 769px) {
2501  .search-actions.before {
2502    display: none;
2503  }
2504}
2505
2506.search-actions button {
2507  padding: 8px;
2508}
2509
2510.search-actions button:not([disabled]):hover,
2511.toggle-layout-button.detailed-list {
2512  color: var(--vp-c-brand-1);
2513}
2514
2515.search-actions button.clear-button:disabled {
2516  opacity: 0.37;
2517}
2518
2519.search-keyboard-shortcuts {
2520  font-size: 0.8rem;
2521  opacity: 75%;
2522  display: flex;
2523  flex-wrap: wrap;
2524  gap: 16px;
2525  line-height: 14px;
2526}
2527
2528.search-keyboard-shortcuts span {
2529  display: flex;
2530  align-items: center;
2531  gap: 4px;
2532}
2533
2534@media (max-width: 767px) {
2535  .search-keyboard-shortcuts {
2536    display: none;
2537  }
2538}
2539
2540.search-keyboard-shortcuts kbd {
2541  background: rgba(128, 128, 128, 0.1);
2542  border-radius: 4px;
2543  padding: 3px 6px;
2544  min-width: 24px;
2545  display: inline-block;
2546  text-align: center;
2547  vertical-align: middle;
2548  border: 1px solid rgba(128, 128, 128, 0.15);
2549  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
2550}
2551
2552.results {
2553  display: flex;
2554  flex-direction: column;
2555  gap: 6px;
2556  flex: 1 1 auto;
2557  min-height: 0 !important;
2558  overflow-x: hidden;
2559  overflow-y: auto;
2560  overscroll-behavior: contain;
2561}
2562
2563.result-layout {
2564  will-change: transform, opacity, height;
2565}
2566
2567.result {
2568  display: flex;
2569  align-items: center;
2570  gap: 8px;
2571  border-radius: 4px;
2572  transition: none;
2573  line-height: 1rem;
2574  border: solid 2px var(--vp-local-search-result-border);
2575  outline: none;
2576}
2577
2578.result > div {
2579  margin: 12px;
2580  width: 100%;
2581  overflow: hidden;
2582}
2583
2584@media (max-width: 767px) {
2585  .result > div {
2586    margin: 8px;
2587  }
2588}
2589
2590.titles {
2591  display: flex;
2592  flex-wrap: wrap;
2593  gap: 4px;
2594  position: relative;
2595  z-index: 1001;
2596  padding: 2px 0;
2597  align-items: center;
2598}
2599
2600.url-result-card {
2601  cursor: pointer;
2602}
2603
2604.url-result-body {
2605  display: flex;
2606  flex-direction: column;
2607  gap: 6px;
2608}
2609
2610.url-path {
2611  display: flex;
2612  align-items: center;
2613  flex-wrap: wrap;
2614  gap: 4px;
2615  color: var(--vp-c-text-3);
2616  font-size: 0.78rem;
2617  line-height: 1.2;
2618}
2619
2620.url-path > svg,
2621.url-path-segment svg {
2622  flex-shrink: 0;
2623  width: 1em;
2624  height: 1em;
2625  margin-top: -1px;
2626  opacity: 0.55;
2627}
2628
2629.url-path > svg {
2630  margin-top: -2px;
2631}
2632
2633.url-path-segment {
2634  display: flex;
2635  align-items: center;
2636  min-width: 0;
2637}
2638
2639.url-path-current {
2640  display: inline-flex;
2641  align-items: center;
2642  color: var(--vp-c-text-2);
2643}
2644
2645.url-path :deep(.icon-tip) {
2646  display: inline-flex;
2647  align-items: center;
2648  line-height: 1;
2649  vertical-align: middle;
2650}
2651
2652.url-path :deep(.icon-tip > span) {
2653  width: 1em;
2654  height: 1em;
2655  min-width: 1em;
2656}
2657
2658.url-link {
2659  align-self: flex-start;
2660  max-width: 100%;
2661  color: var(--vp-c-text-1);
2662  font-size: 0.95rem;
2663  font-weight: 500;
2664  line-height: 1.35;
2665  overflow-wrap: anywhere;
2666  word-break: break-word;
2667}
2668
2669.url-link:hover {
2670  color: var(--vp-c-brand-1);
2671  text-decoration: underline;
2672  text-underline-offset: 2px;
2673}
2674
2675.result.selected .url-link {
2676  color: var(--vp-c-brand-1);
2677}
2678
2679.titles > svg {
2680  flex-shrink: 0;
2681  align-self: center;
2682}
2683
2684.title {
2685  display: flex;
2686  align-items: center;
2687  gap: 4px;
2688}
2689
2690.title.main {
2691  font-weight: 500;
2692}
2693
2694.title-icon {
2695  opacity: 1;
2696  font-weight: 500;
2697}
2698
2699.title svg {
2700  opacity: 0.5;
2701}
2702
2703.result.selected {
2704  --vp-local-search-result-bg: var(--vp-local-search-result-selected-bg);
2705  border-color: var(--vp-local-search-result-selected-border);
2706}
2707
2708.excerpt-wrapper {
2709  position: relative;
2710}
2711
2712.excerpt {
2713  opacity: 50%;
2714  pointer-events: none;
2715  height: 84px;
2716  max-height: 84px;
2717  overflow: hidden;
2718  position: relative;
2719  margin-top: 4px;
2720}
2721
2722.result.selected .excerpt {
2723  opacity: 1;
2724}
2725
2726.excerpt :deep(*) {
2727  font-size: 0.8rem !important;
2728  line-height: 130% !important;
2729}
2730
2731.titles :deep(mark),
2732.excerpt :deep(mark) {
2733  background-color: var(--vp-local-search-highlight-bg);
2734  color: var(--vp-local-search-highlight-text);
2735  border-radius: 2px;
2736  padding: 0 2px;
2737}
2738
2739.excerpt :deep(.vp-code-group) .tabs {
2740  display: none;
2741}
2742
2743.excerpt :deep(.vp-code-group) div[class*="language-"] {
2744  border-radius: 8px !important;
2745}
2746
2747.excerpt > .vp-doc > *:first-child {
2748  margin-top: 6px !important;
2749}
2750
2751.excerpt-gradient-bottom {
2752  position: absolute;
2753  bottom: -1px;
2754  left: 0;
2755  width: 100%;
2756  height: 8px;
2757  background: linear-gradient(transparent, var(--vp-local-search-result-bg));
2758  z-index: 1000;
2759}
2760
2761.excerpt-gradient-top {
2762  position: absolute;
2763  top: -1px;
2764  left: 0;
2765  width: 100%;
2766  height: 8px;
2767  background: linear-gradient(var(--vp-local-search-result-bg), transparent);
2768  z-index: 1000;
2769}
2770
2771.result.selected .titles,
2772.result.selected .title-icon {
2773  color: var(--vp-c-brand-1) !important;
2774}
2775
2776.no-results {
2777  font-size: 0.9rem;
2778  text-align: center;
2779  padding: 12px;
2780}
2781
2782svg {
2783  flex: none;
2784}
2785
2786.exact-match-button.exact-match-active {
2787  color: var(--vp-c-brand-1);
2788  background-color: rgba(var(--vp-c-brand-1), 0.1);
2789  border-radius: 4px;
2790}
2791
2792.toolbar-group + .toolbar-group {
2793  margin-left: 6px;
2794}
2795
2796.search-mode-group,
2797.view-group {
2798  display: flex;
2799  align-items: center;
2800  border: 1px solid var(--vp-c-divider);
2801  border-radius: 5px;
2802  overflow: hidden;
2803}
2804
2805/* Mobile: hide inactive buttons in both groups — tap the active one to cycle */
2806@media (max-width: 767px) {
2807  .search-mode-group .mode-btn:not(.mode-active),
2808  .view-group .mode-btn:not(.mode-active) {
2809    display: none;
2810  }
2811
2812  .search-mode-group,
2813  .view-group {
2814    border-radius: 5px;
2815  }
2816
2817  /* Tapping the sole visible button cycles to the next option */
2818  .search-mode-group .mode-btn.mode-active,
2819  .view-group .mode-btn.mode-active {
2820    border-radius: 4px;
2821  }
2822}
2823
2824.mode-btn {
2825  display: flex;
2826  align-items: center;
2827  justify-content: center;
2828  padding: 5px 7px;
2829  color: var(--vp-c-text-2);
2830  background: transparent;
2831  border: none;
2832  cursor: pointer;
2833  transition: color 0.15s, background-color 0.15s;
2834  border-radius: 0;
2835}
2836
2837.mode-btn + .mode-btn {
2838  border-left: 1px solid var(--vp-c-divider);
2839}
2840
2841.mode-btn:hover {
2842  color: var(--vp-c-text-1);
2843  background: var(--vp-c-default-soft);
2844}
2845
2846.mode-btn.mode-active {
2847  color: var(--vp-c-brand-1);
2848  background: rgba(60, 120, 210, 0.10);
2849}
2850
2851:deep(.url-highlight) {
2852  background-color: var(--vp-local-search-highlight-bg);
2853  color: var(--vp-local-search-highlight-text);
2854  border-radius: 2px;
2855  padding: 0 2px;
2856  font-style: normal;
2857}
2858
2859/* Bottom-strip pagination. The <nav> is always rendered (empty when only one
2860   page) but collapses to zero height in that case so the shell's bottom
2861   rounded edge sits flush against the results. */
2862.url-pagination {
2863  display: flex;
2864  align-items: center;
2865  justify-content: center;
2866  flex: 0 0 auto !important;
2867}
2868
2869.url-pagination:has(.url-pagination-segment) {
2870  padding-top: 8px;
2871}
2872
2873.url-pagination-segment {
2874  display: flex;
2875  align-items: center;
2876  border: 1px solid var(--vp-c-divider);
2877  border-radius: 5px;
2878  overflow: hidden;
2879  background: transparent;
2880}
2881
2882.url-page-btn {
2883  display: flex;
2884  align-items: center;
2885  justify-content: center;
2886  min-width: 32px;
2887  height: 28px;
2888  padding: 0 8px;
2889  border: none;
2890  background: transparent;
2891  color: var(--vp-c-text-2);
2892  font-size: 0.82rem;
2893  cursor: pointer;
2894  transition: color 0.15s, background-color 0.15s;
2895  border-radius: 0;
2896}
2897
2898.url-page-btn + .url-page-btn,
2899.url-page-ellipsis + .url-page-btn,
2900.url-page-btn + .url-page-ellipsis {
2901  border-left: 1px solid var(--vp-c-divider);
2902}
2903
2904.url-page-btn:hover:not(:disabled):not(.active) {
2905  color: var(--vp-c-text-1);
2906  background: var(--vp-c-default-soft);
2907}
2908
2909.url-page-btn.active {
2910  color: var(--vp-c-brand-1);
2911  background: rgba(60, 120, 210, 0.10);
2912  font-weight: 500;
2913  cursor: default;
2914}
2915
2916.url-page-btn:disabled {
2917  opacity: 0.25;
2918  cursor: not-allowed;
2919  background: transparent;
2920}
2921
2922.url-page-nav {
2923  padding: 0 6px;
2924}
2925
2926.url-page-ellipsis {
2927  display: flex;
2928  align-items: center;
2929  justify-content: center;
2930  min-width: 28px;
2931  height: 28px;
2932  color: var(--vp-c-text-3);
2933  font-size: 0.8rem;
2934  user-select: none;
2935  background: transparent;
2936}
2937</style>