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

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

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