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

616352988139968773a69944e2f9c82b0ec83e2c
wotaku/docs/.vitepress/theme/components/Search.vue
Duck update509de1f8ca 5 months ago

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