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

78ea9fc554970c86ce26acb3978ead8147153dad
wotaku/docs/.vitepress/theme/components/Search.vue

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