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

5cfd00170df32fd4acbac60b0ed25c4b7910c205
wotaku/docs/.vitepress/theme/components/Search.vue

2831 lines · 73659 bytes

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