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

33a4e4c6fa7d78deb08b14d2b151ff82c28e461a
wotaku/docs/.vitepress/theme/components/Search.vue history · blame · raw

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