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

29fae34075541b9056536846db51ac39afbc3e91
wotaku/docs/.vitepress/theme/components/Search.vue

2866 lines · 74414 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.titles.length > 0"
1940                          stroke-width="1.25"
1941                          :size="18"
1942                        />
1943                        <File v-else stroke-width="1.25" :size="18" />
1944                        <span
1945                          v-for="(t, ti) in item.titles"
1946                          :key="ti"
1947                          class="url-path-segment"
1948                        >
1949                          <span class="text" v-html="t" />
1950                          <ArrowRight
1951                            stroke-width="1.25"
1952                            :size="18"
1953                            class="mx-0.5"
1954                          />
1955                        </span>
1956                        <span
1957                          v-if="item.linkText"
1958                          class="url-path-current"
1959                          v-html="item.linkText"
1960                        />
1961                      </div>
1962                      <a
1963                        :href="item.href"
1964                        target="_blank"
1965                        rel="noopener noreferrer"
1966                        class="url-link"
1967                        :title="item.href"
1968                        @click.stop
1969                        v-html="item.highlighted"
1970                      >
1971                      </a>
1972                    </div>
1973                  </div>
1974                </component>
1975              </AnimatePresence>
1976            </template>
1977
1978            <!-- Normal search results -->
1979            <template v-else>
1980              <AnimatePresence>
1981                <component
1982                  :is="searchMotionLi"
1983                  v-for="(p, index) in pagedResults"
1984                  :key="'normal-' + normalCurrentPage + '-' + p.id"
1985                  class="result-layout"
1986                  :id="'localsearch-item-' + (index + 1)"
1987                  :aria-selected="selectedIndex === index + 1
1988                  ? 'true'
1989                  : 'false'"
1990                  role="option"
1991                  v-bind="resultMotion(index)"
1992                >
1993                  <a
1994                    :href="p.id"
1995                    class="result"
1996                    :class="{
1997                      selected: selectedIndex === index + 1
1998                    }"
1999                    :aria-label="[...p.titles, p.title].join(' > ')"
2000                    @mouseenter="!disableMouseOver &&
2001                    (selectedIndex = index + 1)"
2002                    @focusin="selectedIndex = index + 1"
2003                    @click="onResultClick"
2004                    :data-index="index + 1"
2005                  >
2006                    <div>
2007                      <div class="titles">
2008                        <Hash
2009                          v-if="p.titles.length > 0"
2010                          stroke-width="1.25"
2011                          :size="18"
2012                        />
2013                        <File v-else stroke-width="1.25" :size="18" />
2014                        <span
2015                          v-for="(t, index) in p.titles"
2016                          :key="index"
2017                          class="title"
2018                        >
2019                          <span class="text" v-html="t" />
2020                          <ArrowRight
2021                            stroke-width="1.25"
2022                            :size="18"
2023                            class="mx-0.5"
2024                          />
2025                        </span>
2026                        <span class="title main">
2027                          <span class="text" v-html="p.title" />
2028                        </span>
2029                      </div>
2030
2031                      <div
2032                        v-if="showDetailedList &&
2033                        hasExcerptPreview(p.text)"
2034                        class="excerpt-wrapper"
2035                      >
2036                        <component
2037                          :is="searchMotionDiv"
2038                          class="excerpt"
2039                          inert
2040                          v-bind="excerptMotion"
2041                        >
2042                          <div class="vp-doc" v-html="p.text" />
2043                        </component>
2044                        <div class="excerpt-gradient-bottom" />
2045                        <div class="excerpt-gradient-top" />
2046                      </div>
2047                    </div>
2048                  </a>
2049                </component>
2050              </AnimatePresence>
2051            </template>
2052          </ul>
2053
2054          <!-- Bottom section: pagination (when needed). Always rendered so the
2055             shell's rounded bottom edge stays consistent. -->
2056          <nav
2057            class="url-pagination"
2058            aria-label="Search result pages"
2059          >
2060            <div
2061              v-if="(urlSearchMode
2062              ? urlTotalPages
2063              : normalTotalPages) > 1"
2064              class="url-pagination-segment"
2065            >
2066              <button
2067                type="button"
2068                class="url-page-btn url-page-nav"
2069                :disabled="(urlSearchMode
2070                ? urlCurrentPage
2071                : normalCurrentPage) <= 1"
2072                aria-label="Previous page"
2073                @click="urlSearchMode
2074                ? goToUrlPage(urlCurrentPage - 1)
2075                : goToNormalPage(normalCurrentPage - 1)"
2076              >
2077                <ChevronRight
2078                  :size="14"
2079                  stroke-width="2"
2080                  style="transform: rotate(180deg)"
2081                />
2082              </button>
2083
2084              <template
2085                v-for="(p, pi) in urlSearchMode ? urlPageList : normalPageList"
2086                :key="pi"
2087              >
2088                <span v-if="p === '…'" class="url-page-ellipsis">…</span>
2089                <button
2090                  v-else
2091                  type="button"
2092                  class="url-page-btn"
2093                  :class="{
2094                    active: p === (urlSearchMode
2095                      ? urlCurrentPage
2096                      : normalCurrentPage)
2097                  }"
2098                  :aria-current="p === (urlSearchMode
2099                    ? urlCurrentPage
2100                    : normalCurrentPage)
2101                  ? 'page'
2102                  : undefined"
2103                  @click="urlSearchMode
2104                  ? goToUrlPage(p as number)
2105                  : goToNormalPage(p as number)"
2106                >
2107                  {{ p }}
2108                </button>
2109              </template>
2110
2111              <button
2112                type="button"
2113                class="url-page-btn url-page-nav"
2114                :disabled="(urlSearchMode
2115                ? urlCurrentPage
2116                : normalCurrentPage) >=
2117                (urlSearchMode
2118                  ? urlTotalPages
2119                  : normalTotalPages)"
2120                aria-label="Next page"
2121                @click="urlSearchMode
2122                ? goToUrlPage(urlCurrentPage + 1)
2123                : goToNormalPage(normalCurrentPage + 1)"
2124              >
2125                <ChevronRight :size="14" stroke-width="2" />
2126              </button>
2127            </div>
2128          </nav>
2129
2130          <component
2131            :is="searchMotionDiv"
2132            v-if="showKeyboardShortcuts"
2133            class="search-keyboard-shortcuts"
2134            v-bind="footerMotion"
2135          >
2136            <span>
2137              <kbd
2138                :aria-label="translate(
2139                  'modal.footer.navigateUpKeyAriaLabel'
2140                )"
2141              >
2142                <span class="vpi-arrow-up navigate-icon" />
2143              </kbd>
2144              <kbd
2145                :aria-label="translate(
2146                  'modal.footer.navigateDownKeyAriaLabel'
2147                )"
2148              >
2149                <span class="vpi-arrow-down navigate-icon" />
2150              </kbd>
2151              {{ translate('modal.footer.navigateText') }}
2152            </span>
2153            <span>
2154              <kbd :aria-label="translate('modal.footer.selectKeyAriaLabel')">
2155                <span class="vpi-corner-down-left navigate-icon" />
2156              </kbd>
2157              {{ translate('modal.footer.selectText') }}
2158            </span>
2159            <span>
2160              <kbd :aria-label="translate('modal.footer.closeKeyAriaLabel')">
2161                esc
2162              </kbd>
2163              {{ translate('modal.footer.closeText') }}
2164            </span>
2165          </component>
2166        </component>
2167      </AnimatePresence>
2168
2169      <button v-if="!showSearch" />
2170    </div>
2171  </Teleport>
2172</template>
2173
2174<style scoped>
2175.VPLocalSearchBox {
2176  position: fixed;
2177  z-index: 100;
2178  inset: 0;
2179  display: flex;
2180  align-items: flex-start;
2181}
2182
2183@media (max-width: 767px) {
2184  .VPLocalSearchBox {
2185    align-items: stretch;
2186  }
2187}
2188
2189.backdrop {
2190  position: absolute;
2191  inset: 0;
2192  background: var(--vp-backdrop-bg-color);
2193}
2194
2195.shell {
2196  position: relative;
2197  box-sizing: border-box;
2198  padding: 12px 12px 8px;
2199  margin: 64px auto;
2200  display: flex;
2201  flex-direction: column;
2202  gap: 16px;
2203  background: var(--vp-local-search-bg);
2204  width: min(100vw - 60px, 900px);
2205  height: 100%;
2206  max-height: min(100vh - 128px, 900px);
2207  border-radius: 6px;
2208}
2209
2210@media (max-width: 767px) {
2211  .shell {
2212    margin: 0;
2213    width: 100vw;
2214    height: 100vh;
2215    height: 100dvh;
2216    max-height: none;
2217    border-radius: 0;
2218    overflow: hidden;
2219    gap: 8px;
2220  }
2221}
2222
2223.search-bar {
2224  flex: 0 0 auto !important;
2225  min-height: 44px !important;
2226  border: 1px solid var(--vp-c-divider);
2227  border-radius: 4px;
2228  display: flex;
2229  align-items: center;
2230  padding: 0 12px;
2231  cursor: text;
2232}
2233
2234@media (max-width: 767px) {
2235  .search-bar {
2236    padding: 0 8px;
2237    min-height: 40px !important;
2238  }
2239}
2240
2241.search-bar:focus-within {
2242  border-color: var(--vp-c-brand-1);
2243}
2244
2245.page-ribbon {
2246  display: flex;
2247  align-items: center;
2248  padding: 12px 0 4px;
2249  padding-inline: calc(var(--spacing) * 3);
2250  position: relative;
2251  min-width: 0;
2252  flex: none;
2253  overflow: hidden;
2254  transition: padding-inline 0.15s;
2255}
2256
2257.page-ribbon.can-scroll-left {
2258  padding-left: 42px;
2259}
2260
2261.page-ribbon.can-scroll-right {
2262  padding-right: 42px;
2263}
2264
2265.page-ribbon-track {
2266  display: flex;
2267  flex-wrap: nowrap;
2268  gap: 8px;
2269  min-width: 0;
2270  flex: 1;
2271  overflow-x: auto;
2272  overflow-y: hidden;
2273  scrollbar-width: none;
2274  -ms-overflow-style: none;
2275  overscroll-behavior-x: contain;
2276}
2277
2278.page-ribbon-track::-webkit-scrollbar {
2279  display: none;
2280  width: 0;
2281  height: 0;
2282}
2283
2284.page-ribbon-arrow {
2285  position: absolute;
2286  top: 12px;
2287  bottom: 4px;
2288  z-index: 2;
2289  display: inline-flex;
2290  align-items: center;
2291  justify-content: center;
2292  width: 48px;
2293  border: none;
2294  background: transparent;
2295  color: var(--vp-c-text-2);
2296  cursor: pointer;
2297  transition: color 0.15s;
2298}
2299
2300.page-ribbon-arrow:hover {
2301  color: var(--vp-c-text-1);
2302}
2303
2304.page-ribbon-arrow.right {
2305  right: 0;
2306  justify-content: flex-end;
2307  padding-right: 6px;
2308}
2309
2310.page-ribbon-arrow.left {
2311  left: 0;
2312  justify-content: flex-start;
2313  padding-left: 6px;
2314}
2315
2316.page-ribbon-arrow.left svg {
2317  transform: rotate(180deg);
2318}
2319
2320.page-pill {
2321  flex: none;
2322  display: inline-flex;
2323  align-items: center;
2324  gap: 6px;
2325  padding: 6px 10px;
2326  font-size: 0.8rem;
2327  line-height: 1.2;
2328  white-space: nowrap;
2329  border-radius: 8px;
2330  border: 1.5px solid var(--vp-c-divider);
2331  background: var(--vp-c-bg-soft);
2332  color: var(--vp-c-text-2);
2333  cursor: pointer;
2334  transition: color 0.15s, border-color 0.15s, background-color 0.15s;
2335}
2336
2337.page-pill:hover {
2338  color: var(--vp-c-text-1);
2339  border-color: var(--vp-c-brand-1);
2340}
2341
2342.page-pill.active {
2343  color: #6ab0f5;
2344  border: 1.5px solid #6ab0f5;
2345  background: rgba(60, 120, 210, 0.12);
2346  box-shadow: none;
2347}
2348
2349.page-pill-label {
2350  max-width: 180px;
2351  overflow: hidden;
2352  text-overflow: ellipsis;
2353}
2354
2355.page-pill-count {
2356  font-variant-numeric: tabular-nums;
2357  font-size: 0.7rem;
2358  padding: 1px 6px;
2359  border-radius: 4px;
2360  background: rgba(128, 128, 128, 0.15);
2361  color: inherit;
2362}
2363
2364.page-pill.active .page-pill-count {
2365  background: rgba(100, 160, 240, 0.18);
2366}
2367
2368@media (max-width: 767px) {
2369  .page-ribbon {
2370    padding: 14px 12px 4px;
2371  }
2372
2373  .page-pill {
2374    padding: 7px 14px;
2375    font-size: 0.82rem;
2376    background: var(--vp-c-bg-elv, var(--vp-c-bg-soft));
2377    border-color: var(--vp-c-divider);
2378    color: var(--vp-c-text-1);
2379  }
2380}
2381
2382.local-search-icon {
2383  display: block;
2384  font-size: 18px;
2385}
2386
2387.navigate-icon {
2388  display: block;
2389  font-size: 14px;
2390}
2391
2392.search-icon {
2393  margin: 8px;
2394}
2395
2396@media (max-width: 767px) {
2397  .search-icon {
2398    display: none;
2399  }
2400}
2401
2402.search-input {
2403  padding: 6px 12px;
2404  font-size: inherit;
2405  width: 100%;
2406}
2407
2408.search-input::-webkit-search-cancel-button {
2409  display: none;
2410}
2411
2412@media (max-width: 767px) {
2413  .search-input {
2414    padding: 6px 4px;
2415  }
2416}
2417
2418.search-actions {
2419  display: flex;
2420  gap: 4px;
2421}
2422
2423@media (any-pointer: coarse) {
2424  .search-actions {
2425    gap: 8px;
2426  }
2427}
2428
2429@media (min-width: 769px) {
2430  .search-actions.before {
2431    display: none;
2432  }
2433}
2434
2435.search-actions button {
2436  padding: 8px;
2437}
2438
2439.search-actions button:not([disabled]):hover,
2440.toggle-layout-button.detailed-list {
2441  color: var(--vp-c-brand-1);
2442}
2443
2444.search-actions button.clear-button:disabled {
2445  opacity: 0.37;
2446}
2447
2448.search-keyboard-shortcuts {
2449  font-size: 0.8rem;
2450  opacity: 75%;
2451  display: flex;
2452  flex-wrap: wrap;
2453  gap: 16px;
2454  line-height: 14px;
2455}
2456
2457.search-keyboard-shortcuts span {
2458  display: flex;
2459  align-items: center;
2460  gap: 4px;
2461}
2462
2463@media (max-width: 767px) {
2464  .search-keyboard-shortcuts {
2465    display: none;
2466  }
2467}
2468
2469.search-keyboard-shortcuts kbd {
2470  background: rgba(128, 128, 128, 0.1);
2471  border-radius: 4px;
2472  padding: 3px 6px;
2473  min-width: 24px;
2474  display: inline-block;
2475  text-align: center;
2476  vertical-align: middle;
2477  border: 1px solid rgba(128, 128, 128, 0.15);
2478  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
2479}
2480
2481.results {
2482  display: flex;
2483  flex-direction: column;
2484  gap: 6px;
2485  flex: 1 1 auto;
2486  min-height: 0 !important;
2487  overflow-x: hidden;
2488  overflow-y: auto;
2489  overscroll-behavior: contain;
2490}
2491
2492.result-layout {
2493  will-change: transform, opacity, height;
2494}
2495
2496.result {
2497  display: flex;
2498  align-items: center;
2499  gap: 8px;
2500  border-radius: 4px;
2501  transition: none;
2502  line-height: 1rem;
2503  border: solid 2px var(--vp-local-search-result-border);
2504  outline: none;
2505}
2506
2507.result > div {
2508  margin: 12px;
2509  width: 100%;
2510  overflow: hidden;
2511}
2512
2513@media (max-width: 767px) {
2514  .result > div {
2515    margin: 8px;
2516  }
2517}
2518
2519.titles {
2520  display: flex;
2521  flex-wrap: wrap;
2522  gap: 4px;
2523  position: relative;
2524  z-index: 1001;
2525  padding: 2px 0;
2526  align-items: center;
2527}
2528
2529.url-result-card {
2530  cursor: pointer;
2531}
2532
2533.url-result-body {
2534  display: flex;
2535  flex-direction: column;
2536  gap: 6px;
2537}
2538
2539.url-path {
2540  display: flex;
2541  align-items: center;
2542  flex-wrap: wrap;
2543  gap: 4px;
2544  color: var(--vp-c-text-3);
2545  font-size: 0.78rem;
2546  line-height: 1.2;
2547}
2548
2549.url-path > svg,
2550.url-path-segment svg {
2551  flex-shrink: 0;
2552  width: 1em;
2553  height: 1em;
2554  margin-top: -1px;
2555  opacity: 0.55;
2556}
2557
2558.url-path > svg {
2559  margin-top: -2px;
2560}
2561
2562.url-path-segment {
2563  display: flex;
2564  align-items: center;
2565  min-width: 0;
2566}
2567
2568.url-path-current {
2569  display: inline-flex;
2570  align-items: center;
2571  color: var(--vp-c-text-2);
2572}
2573
2574.url-path :deep(.icon-tip) {
2575  display: inline-flex;
2576  align-items: center;
2577  line-height: 1;
2578  vertical-align: middle;
2579}
2580
2581.url-path :deep(.icon-tip > span) {
2582  width: 1em;
2583  height: 1em;
2584  min-width: 1em;
2585}
2586
2587.url-link {
2588  align-self: flex-start;
2589  max-width: 100%;
2590  color: var(--vp-c-text-1);
2591  font-size: 0.95rem;
2592  font-weight: 500;
2593  line-height: 1.35;
2594  overflow-wrap: anywhere;
2595  word-break: break-word;
2596}
2597
2598.url-link:hover {
2599  color: var(--vp-c-brand-1);
2600  text-decoration: underline;
2601  text-underline-offset: 2px;
2602}
2603
2604.result.selected .url-link {
2605  color: var(--vp-c-brand-1);
2606}
2607
2608.titles > svg {
2609  flex-shrink: 0;
2610  align-self: center;
2611}
2612
2613.title {
2614  display: flex;
2615  align-items: center;
2616  gap: 4px;
2617}
2618
2619.title.main {
2620  font-weight: 500;
2621}
2622
2623.title-icon {
2624  opacity: 1;
2625  font-weight: 500;
2626}
2627
2628.title svg {
2629  opacity: 0.5;
2630}
2631
2632.result.selected {
2633  --vp-local-search-result-bg: var(--vp-local-search-result-selected-bg);
2634  border-color: var(--vp-local-search-result-selected-border);
2635}
2636
2637.excerpt-wrapper {
2638  position: relative;
2639}
2640
2641.excerpt {
2642  opacity: 50%;
2643  pointer-events: none;
2644  height: 84px;
2645  max-height: 84px;
2646  overflow: hidden;
2647  position: relative;
2648  margin-top: 4px;
2649}
2650
2651.result.selected .excerpt {
2652  opacity: 1;
2653}
2654
2655.excerpt :deep(*) {
2656  font-size: 0.8rem !important;
2657  line-height: 130% !important;
2658}
2659
2660.titles :deep(mark),
2661.excerpt :deep(mark) {
2662  background-color: var(--vp-local-search-highlight-bg);
2663  color: var(--vp-local-search-highlight-text);
2664  border-radius: 2px;
2665  padding: 0 2px;
2666}
2667
2668.excerpt :deep(.vp-code-group) .tabs {
2669  display: none;
2670}
2671
2672.excerpt :deep(.vp-code-group) div[class*="language-"] {
2673  border-radius: 8px !important;
2674}
2675
2676.excerpt > .vp-doc > *:first-child {
2677  margin-top: 6px !important;
2678}
2679
2680.excerpt-gradient-bottom {
2681  position: absolute;
2682  bottom: -1px;
2683  left: 0;
2684  width: 100%;
2685  height: 8px;
2686  background: linear-gradient(transparent, var(--vp-local-search-result-bg));
2687  z-index: 1000;
2688}
2689
2690.excerpt-gradient-top {
2691  position: absolute;
2692  top: -1px;
2693  left: 0;
2694  width: 100%;
2695  height: 8px;
2696  background: linear-gradient(var(--vp-local-search-result-bg), transparent);
2697  z-index: 1000;
2698}
2699
2700.result.selected .titles,
2701.result.selected .title-icon {
2702  color: var(--vp-c-brand-1) !important;
2703}
2704
2705.no-results {
2706  font-size: 0.9rem;
2707  text-align: center;
2708  padding: 12px;
2709}
2710
2711svg {
2712  flex: none;
2713}
2714
2715.exact-match-button.exact-match-active {
2716  color: var(--vp-c-brand-1);
2717  background-color: rgba(var(--vp-c-brand-1), 0.1);
2718  border-radius: 4px;
2719}
2720
2721.toolbar-group + .toolbar-group {
2722  margin-left: 6px;
2723}
2724
2725.search-mode-group,
2726.view-group {
2727  display: flex;
2728  align-items: center;
2729  border: 1px solid var(--vp-c-divider);
2730  border-radius: 5px;
2731  overflow: hidden;
2732}
2733
2734/* Mobile: hide inactive buttons in both groups — tap the active one to cycle */
2735@media (max-width: 767px) {
2736  .search-mode-group .mode-btn:not(.mode-active),
2737  .view-group .mode-btn:not(.mode-active) {
2738    display: none;
2739  }
2740
2741  .search-mode-group,
2742  .view-group {
2743    border-radius: 5px;
2744  }
2745
2746  /* Tapping the sole visible button cycles to the next option */
2747  .search-mode-group .mode-btn.mode-active,
2748  .view-group .mode-btn.mode-active {
2749    border-radius: 4px;
2750  }
2751}
2752
2753.mode-btn {
2754  display: flex;
2755  align-items: center;
2756  justify-content: center;
2757  padding: 5px 7px;
2758  color: var(--vp-c-text-2);
2759  background: transparent;
2760  border: none;
2761  cursor: pointer;
2762  transition: color 0.15s, background-color 0.15s;
2763  border-radius: 0;
2764}
2765
2766.mode-btn + .mode-btn {
2767  border-left: 1px solid var(--vp-c-divider);
2768}
2769
2770.mode-btn:hover {
2771  color: var(--vp-c-text-1);
2772  background: var(--vp-c-default-soft);
2773}
2774
2775.mode-btn.mode-active {
2776  color: var(--vp-c-brand-1);
2777  background: rgba(60, 120, 210, 0.10);
2778}
2779
2780:deep(.url-highlight) {
2781  background-color: var(--vp-local-search-highlight-bg);
2782  color: var(--vp-local-search-highlight-text);
2783  border-radius: 2px;
2784  padding: 0 2px;
2785  font-style: normal;
2786}
2787
2788/* Bottom-strip pagination. The <nav> is always rendered (empty when only one
2789   page) but collapses to zero height in that case so the shell's bottom
2790   rounded edge sits flush against the results. */
2791.url-pagination {
2792  display: flex;
2793  align-items: center;
2794  justify-content: center;
2795  flex: 0 0 auto !important;
2796}
2797
2798.url-pagination:has(.url-pagination-segment) {
2799  padding-top: 8px;
2800}
2801
2802.url-pagination-segment {
2803  display: flex;
2804  align-items: center;
2805  border: 1px solid var(--vp-c-divider);
2806  border-radius: 5px;
2807  overflow: hidden;
2808  background: transparent;
2809}
2810
2811.url-page-btn {
2812  display: flex;
2813  align-items: center;
2814  justify-content: center;
2815  min-width: 32px;
2816  height: 28px;
2817  padding: 0 8px;
2818  border: none;
2819  background: transparent;
2820  color: var(--vp-c-text-2);
2821  font-size: 0.82rem;
2822  cursor: pointer;
2823  transition: color 0.15s, background-color 0.15s;
2824  border-radius: 0;
2825}
2826
2827.url-page-btn + .url-page-btn,
2828.url-page-ellipsis + .url-page-btn,
2829.url-page-btn + .url-page-ellipsis {
2830  border-left: 1px solid var(--vp-c-divider);
2831}
2832
2833.url-page-btn:hover:not(:disabled):not(.active) {
2834  color: var(--vp-c-text-1);
2835  background: var(--vp-c-default-soft);
2836}
2837
2838.url-page-btn.active {
2839  color: var(--vp-c-brand-1);
2840  background: rgba(60, 120, 210, 0.10);
2841  font-weight: 500;
2842  cursor: default;
2843}
2844
2845.url-page-btn:disabled {
2846  opacity: 0.25;
2847  cursor: not-allowed;
2848  background: transparent;
2849}
2850
2851.url-page-nav {
2852  padding: 0 6px;
2853}
2854
2855.url-page-ellipsis {
2856  display: flex;
2857  align-items: center;
2858  justify-content: center;
2859  min-width: 28px;
2860  height: 28px;
2861  color: var(--vp-c-text-3);
2862  font-size: 0.8rem;
2863  user-select: none;
2864  background: transparent;
2865}
2866</style>
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form