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

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

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