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

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

3107 lines · 82104 bytes

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