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

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

1594 lines · 39802 bytes

   1<script lang="ts" setup>
   2import MiniSearch, { type SearchResult } from 'minisearch'
   3import { type DefaultTheme, dataSymbol, 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  watchDebounced
  30} from '@vueuse/core'
  31import { useFocusTrap } from '@vueuse/integrations/useFocusTrap'
  32
  33// @ts-ignore
  34import localSearchIndex from '@localSearchIndex'
  35
  36import {
  37  ArrowRight,
  38  ChevronRight,
  39  Delete,
  40  File,
  41  Hash,
  42  Locate,
  43  LocateOff,
  44  TextAlignStart
  45} from 'lucide-vue-next'
  46import Mark from 'mark.js/dist/mark.es6.js'
  47import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client'
  48import { LRUCache } from '../composables/search/lru-cache'
  49import { createSearchTranslate } from '../composables/search/translation'
  50import { useData } from '../composables/search/use-data'
  51import { sidebar } from '../../configs/constants'
  52
  53export interface FooterTranslations {
  54  selectText?: string
  55  selectKeyAriaLabel?: string
  56  navigateText?: string
  57  navigateUpKeyAriaLabel?: string
  58  navigateDownKeyAriaLabel?: string
  59  closeText?: string
  60  closeKeyAriaLabel?: string
  61}
  62
  63export interface ModalTranslations {
  64  displayDetails?: string
  65  resetButtonTitle?: string
  66  backButtonTitle?: string
  67  noResultsText?: string
  68  footer?: FooterTranslations
  69}
  70
  71const showSearch = defineModel<boolean>()
  72
  73const el = shallowRef<HTMLElement>()
  74const resultsEl = shallowRef<HTMLElement>()
  75
  76/* Search */
  77const searchIndexData = shallowRef(localSearchIndex)
  78
  79// @ts-ignore
  80if (import.meta.hot) {
  81  // @ts-ignore
  82  import.meta.hot.accept('@localSearchIndex', (m) => {
  83    if (m) {
  84      searchIndexData.value = m.default
  85    }
  86  })
  87}
  88
  89interface Result {
  90  title: string
  91  titles: string[]
  92  text?: string
  93}
  94
  95const vitePressData = useData()
  96const { activate } = useFocusTrap(el, {
  97  immediate: true,
  98  allowOutsideClick: true,
  99  clickOutsideDeactivates: true,
 100  escapeDeactivates: true,
 101  returnFocusOnDeactivate: false,
 102  initialFocus: () => {
 103    return searchInput.value
 104  }
 105})
 106const { localeIndex, theme } = vitePressData
 107const searchIndex = computedAsync(async () =>
 108  markRaw(
 109    MiniSearch.loadJSON<Result>(
 110      (await searchIndexData.value[localeIndex.value]?.())?.default,
 111      {
 112        fields: ['title', 'titles', 'text'],
 113        storeFields: ['title', 'titles'],
 114        searchOptions: {
 115          boost: { title: 10, titles: 4, text: 1 },
 116          ...(theme.value.search?.provider === 'local' &&
 117            theme.value.search.options?.miniSearch?.searchOptions)
 118        },
 119        ...(theme.value.search?.provider === 'local' &&
 120          theme.value.search.options?.miniSearch?.options)
 121      }
 122    )
 123  )
 124)
 125
 126const disableQueryPersistence = computed(() => {
 127  return (
 128    theme.value.search?.provider === 'local' &&
 129    theme.value.search.options?.disableQueryPersistence === true
 130  )
 131})
 132
 133const filterText = disableQueryPersistence.value
 134  ? ref('')
 135  : useSessionStorage('vitepress:local-search-filter', '')
 136
 137const showDetailedList = useLocalStorage(
 138  'vitepress:local-search-detailed-list',
 139  theme.value.search?.provider === 'local' &&
 140    theme.value.search.options?.detailedView === true
 141)
 142
 143const matchExact = useLocalStorage(
 144  'vitepress:local-search-match-exact',
 145  true // enabled by default
 146)
 147
 148const disableDetailedView = computed(() => {
 149  return (
 150    theme.value.search?.provider === 'local' &&
 151    theme.value.search.options?.detailedView === false
 152  )
 153})
 154
 155const buttonText = computed(() => {
 156  const options = theme.value.search?.options
 157
 158  return (
 159    options?.locales?.[localeIndex.value]?.translations?.button?.buttonText ||
 160    options?.translations?.button?.buttonText ||
 161    'Search'
 162  )
 163})
 164
 165watchEffect(() => {
 166  if (disableDetailedView.value) {
 167    showDetailedList.value = false
 168  }
 169})
 170
 171const results: Ref<(SearchResult & Result)[]> = shallowRef([])
 172
 173const currentTerms = shallowRef(new Set<string>())
 174
 175const enableNoResults = ref(false)
 176
 177const pageMeta = (() => {
 178  const map = new Map<string, { label: string; order: number }>()
 179  let order = 0
 180  const stripIcon = (text: string) =>
 181    text
 182      .replace(/<[^>]*>/g, '')
 183      .replace(/\s+/g, ' ')
 184      .trim()
 185  const walk = (items: DefaultTheme.SidebarItem[]) => {
 186    for (const item of items) {
 187      if (item.link) {
 188        const key = item.link.replace(/\/$/, '')
 189        if (!map.has(key)) {
 190          map.set(key, { label: stripIcon(item.text ?? key), order: order++ })
 191        }
 192      }
 193      if (item.items) walk(item.items)
 194    }
 195  }
 196  walk(sidebar as DefaultTheme.SidebarItem[])
 197  return map
 198})()
 199
 200const activePageFilter = ref<string | null>(null)
 201
 202const docOrder = computed(() => {
 203  const map = new Map<string, number>()
 204  const index = searchIndex.value as any
 205  if (!index) return map
 206  // _documentIds maps internalDocId -> original id, in insertion order.
 207  const ids = index._documentIds
 208  if (ids instanceof Map) {
 209    let i = 0
 210    for (const originalId of ids.values()) {
 211      map.set(String(originalId), i++)
 212    }
 213  } else if (ids && typeof ids === 'object') {
 214    // Some versions store it as a plain object keyed by numeric doc id.
 215    const keys = Object.keys(ids)
 216      .map(Number)
 217      .sort((a, b) => a - b)
 218    let i = 0
 219    for (const k of keys) {
 220      map.set(String(ids[k]), i++)
 221    }
 222  }
 223  return map
 224})
 225
 226function getDocOrder(id: string) {
 227  return docOrder.value.get(id) ?? Number.MAX_SAFE_INTEGER
 228}
 229
 230function getPageKey(id: string) {
 231  return id.split('#')[0].replace(/\/$/, '')
 232}
 233
 234function getPageLabel(key: string) {
 235  return pageMeta.get(key)?.label ?? key.replace(/^\//, '')
 236}
 237
 238function getPageOrder(key: string) {
 239  return pageMeta.get(key)?.order ?? Number.MAX_SAFE_INTEGER
 240}
 241
 242const pageGroups = computed(() => {
 243  const map = new Map<string, { key: string; label: string; count: number }>()
 244  for (const r of results.value) {
 245    const key = getPageKey(r.id)
 246    const existing = map.get(key)
 247    if (existing) existing.count++
 248    else map.set(key, { key, label: getPageLabel(key), count: 1 })
 249  }
 250  return [...map.values()].sort(
 251    (a, b) => getPageOrder(a.key) - getPageOrder(b.key)
 252  )
 253})
 254
 255const filteredResults = computed(() => {
 256  if (!activePageFilter.value) return results.value
 257  return results.value.filter(
 258    (r) => getPageKey(r.id) === activePageFilter.value
 259  )
 260})
 261
 262function setPageFilter(key: string | null) {
 263  activePageFilter.value = activePageFilter.value === key ? null : key
 264  selectedIndex.value = filteredResults.value.length ? 1 : -1
 265  nextTick(() => {
 266    if (resultsEl.value) resultsEl.value.scrollTop = 0
 267    scrollToSelectedResult()
 268    reapplyHighlights()
 269  })
 270}
 271
 272async function reapplyHighlights() {
 273  if (!showDetailedList.value || !currentTerms.value.size) {
 274    centerExcerptsUntilSettled()
 275    return
 276  }
 277  await new Promise<void>((resolve) => {
 278    mark.value?.unmark({
 279      done: () => {
 280        mark.value?.markRegExp(formMarkRegex(currentTerms.value), {
 281          done: () => resolve()
 282        })
 283      }
 284    })
 285  })
 286  await nextTick()
 287  centerExcerptsUntilSettled()
 288}
 289
 290watch(results, () => {
 291  if (
 292    activePageFilter.value &&
 293    !pageGroups.value.some((g) => g.key === activePageFilter.value)
 294  ) {
 295    activePageFilter.value = null
 296  }
 297})
 298
 299watch(filterText, () => {
 300  enableNoResults.value = false
 301})
 302
 303const ribbonTrack = shallowRef<HTMLElement>()
 304const ribbonCanScrollLeft = ref(false)
 305const ribbonCanScrollRight = ref(false)
 306
 307function getRibbonTrack(): HTMLElement | null {
 308  return (
 309    ribbonTrack.value ??
 310    (el.value?.querySelector('.page-ribbon-track') as HTMLElement | null)
 311  )
 312}
 313
 314function updateRibbonOverflow() {
 315  const track = getRibbonTrack()
 316  if (!track) {
 317    ribbonCanScrollLeft.value = false
 318    ribbonCanScrollRight.value = false
 319    return
 320  }
 321  ribbonCanScrollLeft.value = track.scrollLeft > 2
 322  ribbonCanScrollRight.value =
 323    track.scrollWidth - track.clientWidth - track.scrollLeft > 2
 324}
 325
 326let ribbonAnimHandle = 0
 327
 328function scrollRibbon(direction: number) {
 329  const track = getRibbonTrack()
 330  if (!track) return
 331  const max = track.scrollWidth - track.clientWidth
 332  const amount = track.clientWidth * 0.7 * direction
 333  const from = track.scrollLeft
 334  const to = Math.max(0, Math.min(max, from + amount))
 335  if (to === from) return
 336
 337  if (ribbonAnimHandle) cancelAnimationFrame(ribbonAnimHandle)
 338  const duration = 280
 339  const start = performance.now()
 340  const ease = (t: number) => 1 - Math.pow(1 - t, 3)
 341
 342  const step = (now: number) => {
 343    const t = Math.min(1, (now - start) / duration)
 344    track.scrollLeft = from + (to - from) * ease(t)
 345    updateRibbonOverflow()
 346    if (t < 1) {
 347      ribbonAnimHandle = requestAnimationFrame(step)
 348    } else {
 349      ribbonAnimHandle = 0
 350    }
 351  }
 352  ribbonAnimHandle = requestAnimationFrame(step)
 353}
 354
 355watch(pageGroups, () => {
 356  nextTick(updateRibbonOverflow)
 357})
 358
 359useEventListener('resize', () => {
 360  updateRibbonOverflow()
 361})
 362
 363const mark = computedAsync(async () => {
 364  if (!resultsEl.value) return
 365  return markRaw(new Mark(resultsEl.value))
 366}, null)
 367
 368const cache = new LRUCache<string, Map<string, string>>(120)
 369
 370const inFlightExcerpts = new Map<string, Promise<void>>()
 371
 372const EAGER_EXCERPTS = 15
 373
 374function buildDocExcerpt(
 375  docId: string,
 376  filterTextValue: string
 377): Promise<void> {
 378  const cacheId = `${docId}\n${filterTextValue}`
 379  if (cache.get(cacheId)) return Promise.resolve()
 380  const pending = inFlightExcerpts.get(cacheId)
 381  if (pending) return pending
 382
 383  const job = (async () => {
 384    const { mod } = await fetchExcerpt(docId)
 385    if (cache.get(cacheId)) return
 386
 387    const comp = (mod as any).default ?? mod
 388    if (!(comp?.render || comp?.setup)) return // nothing renderable; don't cache
 389
 390    const map = new Map<string, string>()
 391    const app = createApp(comp)
 392    app.config.warnHandler = () => {}
 393    enhanceAppWithTabs(app)
 394    app.provide(dataSymbol, vitePressData)
 395    Object.defineProperties(app.config.globalProperties, {
 396      $frontmatter: {
 397        get() {
 398          return vitePressData.frontmatter.value
 399        }
 400      },
 401      $params: {
 402        get() {
 403          return vitePressData.page.value.params
 404        }
 405      }
 406    })
 407    const div = document.createElement('div')
 408    try {
 409      app.mount(div)
 410      await selectExcerptTabs(div, filterTextValue)
 411      const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6')
 412      headings.forEach((heading) => {
 413        const href = heading.querySelector('a')?.getAttribute('href')
 414        const anchor = href?.startsWith('#') && href.slice(1)
 415        if (!anchor) return
 416        let html = ''
 417        let node = heading as Element
 418        while (
 419          (node = node.nextElementSibling!) &&
 420          !/^h[1-6]$/i.test(node.tagName)
 421        ) {
 422          html += (node as HTMLElement).outerHTML
 423        }
 424        map.set(anchor, html)
 425      })
 426    } catch (e) {
 427      console.error('[search] excerpt render failed for', docId, e)
 428    } finally {
 429      try {
 430        app.unmount()
 431      } catch {
 432        /* ignore */
 433      }
 434    }
 435    cache.set(cacheId, map)
 436  })()
 437
 438  inFlightExcerpts.set(cacheId, job)
 439  job.finally(() => {
 440    if (inFlightExcerpts.get(cacheId) === job) inFlightExcerpts.delete(cacheId)
 441  })
 442  return job
 443}
 444
 445watchDebounced(
 446  () => [searchIndex.value, filterText.value, showDetailedList.value, matchExact.value] as const,
 447  async ([index, filterTextValue, showDetailedListValue, matchExactValue], old, onCleanup) => {
 448    if (old?.[0] !== index) {
 449      // in case of hmr
 450      cache.clear()
 451    }
 452
 453    let canceled = false
 454    onCleanup(() => {
 455      canceled = true
 456    })
 457
 458    if (!index) return
 459
 460    // Dynamic search options based on matchExact toggle
 461    const dynamicSearchOptions = {
 462      fuzzy: matchExactValue ? false : (0.3 as number | false),
 463      prefix: matchExactValue ? false : (term: string) => term.length > 3,
 464      maxFuzzy: matchExactValue ? 0 : 1,
 465      boost: { title: 10, titles: 4, text: 1 },
 466    }
 467
 468    // Search
 469    const ranked = index.search(filterTextValue, dynamicSearchOptions) as (SearchResult & Result)[]
 470
 471    const top = ranked.slice(0, 50)
 472    const seen = new Set(top.map((r) => r.id))
 473    const titleHits = ranked.filter(
 474      (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
 475    )
 476    const _result = [...top, ...titleHits] as (SearchResult & Result)[]
 477    enableNoResults.value = true
 478
 479    if (!_result.length) {
 480      results.value = []
 481      return
 482    }
 483
 484    // Collect highlight terms up front (cheap — no rendering needed).
 485    const terms = new Set<string>()
 486    for (const r of _result) {
 487      for (const term in r.match) terms.add(term)
 488    }
 489    currentTerms.value = terms
 490
 491    const toRows = (list: (SearchResult & Result)[]) =>
 492      list
 493        .map((r) => {
 494          const [id, anchor] = r.id.split('#')
 495          const map = cache.get(`${id}\n${filterTextValue}`)
 496          return { ...r, text: map?.get(anchor) ?? '' }
 497        })
 498        .sort((a, b) => {
 499          const pageDiff =
 500            getPageOrder(getPageKey(a.id)) - getPageOrder(getPageKey(b.id))
 501          if (pageDiff !== 0) return pageDiff
 502          return getDocOrder(a.id) - getDocOrder(b.id)
 503        })
 504
 505    const highlight = () =>
 506      new Promise<void>((resolve) => {
 507        if (!terms.size || !mark.value) {
 508          resolve()
 509          return
 510        }
 511        mark.value.unmark({
 512          done: () => {
 513            mark.value?.markRegExp(formMarkRegex(terms), {
 514              done: () => resolve()
 515            })
 516          }
 517        })
 518      })
 519
 520    const docOrderList: string[] = []
 521    const seenDocs = new Set<string>()
 522    for (const r of _result) {
 523      const docId = r.id.slice(0, r.id.indexOf('#'))
 524      if (!seenDocs.has(docId)) {
 525        seenDocs.add(docId)
 526        docOrderList.push(docId)
 527      }
 528    }
 529
 530    if (showDetailedListValue) {
 531      const eagerDocs = new Set<string>()
 532      for (const r of _result.slice(0, EAGER_EXCERPTS)) {
 533        eagerDocs.add(r.id.slice(0, r.id.indexOf('#')))
 534      }
 535      await Promise.all(
 536        [...eagerDocs].map((docId) => buildDocExcerpt(docId, filterTextValue))
 537      )
 538      if (canceled) return
 539    }
 540
 541    results.value = toRows(_result)
 542
 543    await nextTick()
 544    if (canceled) return
 545    await highlight()
 546    await nextTick()
 547    await nextFrame()
 548    if (canceled) return
 549
 550    if (resultsEl.value) {
 551      resultsEl.value.scrollTop = 0
 552    }
 553    centerExcerptsUntilSettled()
 554
 555    if (showDetailedListValue) {
 556      const built = new Set<string>()
 557      for (const r of _result.slice(0, EAGER_EXCERPTS)) {
 558        built.add(r.id.slice(0, r.id.indexOf('#')))
 559      }
 560      const remaining = docOrderList.filter((d) => !built.has(d))
 561      if (remaining.length) {
 562        for (const docId of remaining) {
 563          await buildDocExcerpt(docId, filterTextValue)
 564          if (canceled) return
 565          await nextFrame()
 566          if (canceled) return
 567        }
 568        results.value = toRows(_result)
 569        await nextTick()
 570        if (canceled) return
 571        await highlight()
 572        await nextTick()
 573        await nextFrame()
 574        if (canceled) return
 575        centerExcerptsUntilSettled()
 576      }
 577    }
 578  },
 579  { debounce: 80, immediate: true }
 580)
 581
 582function centerExcerpts() {
 583  const excerpts = el.value?.querySelectorAll('.result .excerpt') ?? []
 584  for (let i = 0; i < excerpts.length; i++) {
 585    const excerptElement = excerpts[i] as HTMLElement
 586
 587    const markNode = excerptElement.querySelector(
 588      'mark[data-markjs="true"]'
 589    ) as HTMLElement | null
 590    if (!markNode) continue
 591
 592    const viewportHeight =
 593      Number.parseFloat(getComputedStyle(excerptElement).maxHeight) || 84
 594
 595    let offset = 0
 596    let node: HTMLElement | null = markNode
 597    while (node && node !== excerptElement) {
 598      offset += node.offsetTop
 599      node = node.offsetParent as HTMLElement | null
 600    }
 601
 602    const targetScrollTop = offset - viewportHeight / 2 + markNode.offsetHeight / 2
 603    excerptElement.scrollTop = Math.max(0, targetScrollTop)
 604  }
 605}
 606
 607let centerHandle = 0
 608
 609function centerExcerptsUntilSettled() {
 610  // No layout animations to wait on anymore — a single pass after the
 611  // DOM has painted is enough.
 612  if (centerHandle) cancelAnimationFrame(centerHandle)
 613  centerHandle = requestAnimationFrame(() => {
 614    centerExcerpts()
 615    centerHandle = 0
 616  })
 617}
 618
 619onBeforeUnmount(() => {
 620  if (centerHandle) cancelAnimationFrame(centerHandle)
 621  if (ribbonAnimHandle) cancelAnimationFrame(ribbonAnimHandle)
 622})
 623
 624const excerptCache = new LRUCache<string, unknown>(24)
 625
 626async function fetchExcerpt(id: string) {
 627  const hashIndex = id.indexOf('#')
 628  const docId = hashIndex === -1 ? id : id.slice(0, hashIndex)
 629
 630  const cached = excerptCache.get(docId)
 631  if (cached) return { id, mod: cached }
 632
 633  const file = pathToFile(docId)
 634  try {
 635    if (!file) throw new Error(`Cannot find file for id: ${id}`)
 636    const mod = await import(/*@vite-ignore*/ file)
 637
 638    excerptCache.set(docId, mod)
 639
 640    return { id, mod }
 641  } catch (e) {
 642    console.error(e)
 643    return { id, mod: {} }
 644  }
 645}
 646
 647const nextFrame = () =>
 648  new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
 649
 650const getSearchTerms = (query: string) =>
 651  query
 652    .toLowerCase()
 653    .split(/\s+/)
 654    .map((term) => term.trim())
 655    .filter(Boolean)
 656
 657async function selectExcerptTabs(root: HTMLElement, query: string) {
 658  const terms = getSearchTerms(query)
 659  if (!terms.length) return
 660
 661  const tabs = root.querySelectorAll<HTMLElement>('.plugin-tabs')
 662
 663  for (let i = 0; i < tabs.length; i++) {
 664    const tab = tabs[i]
 665    const selectedTab = tab.querySelector<HTMLButtonElement>(
 666      '.plugin-tabs--tab[aria-selected="true"]'
 667    )
 668    const buttons = tab.querySelectorAll<HTMLButtonElement>(
 669      '.plugin-tabs--tab[role="tab"]'
 670    )
 671
 672    let found = false
 673
 674    for (let j = 0; j < buttons.length; j++) {
 675      const button = buttons[j]
 676      button.click()
 677      await nextTick()
 678      await nextFrame()
 679
 680      const panelId = button.getAttribute('aria-controls')
 681      const panel = panelId
 682        ? root.querySelector<HTMLElement>(`#${CSS.escape(panelId)}`)
 683        : tab.querySelector<HTMLElement>('.plugin-tabs--content')
 684      const text = panel?.textContent?.toLowerCase() ?? ''
 685
 686      if (terms.every((term) => text.includes(term))) {
 687        found = true
 688        break
 689      }
 690    }
 691
 692    if (!found) {
 693      selectedTab?.click()
 694      await nextTick()
 695    }
 696  }
 697}
 698
 699/* Search input focus */
 700
 701const searchInput = ref<HTMLInputElement>()
 702const disableReset = computed(() => {
 703  return filterText.value?.length <= 0
 704})
 705function focusSearchInput(select = true) {
 706  searchInput.value?.focus()
 707  select && searchInput.value?.select()
 708}
 709
 710onMounted(() => {
 711  focusSearchInput()
 712})
 713
 714function onSearchBarClick(event: PointerEvent) {
 715  if (event.pointerType === 'mouse') {
 716    focusSearchInput()
 717  }
 718}
 719
 720/* Search keyboard selection */
 721
 722const selectedIndex = ref(-1)
 723const disableMouseOver = ref(true)
 724
 725watch(filteredResults, (r) => {
 726  selectedIndex.value = r.length ? 0 : -1
 727  scrollToSelectedResult()
 728})
 729
 730function scrollToSelectedResult() {
 731  nextTick(() => {
 732    const selectedEl = document.querySelector('.result.selected')
 733    selectedEl?.scrollIntoView({ block: 'nearest' })
 734  })
 735}
 736
 737onKeyStroke('ArrowUp', (event) => {
 738  event.preventDefault()
 739  selectedIndex.value--
 740  if (selectedIndex.value < 0) {
 741    selectedIndex.value = filteredResults.value.length - 1
 742  }
 743  disableMouseOver.value = true
 744  scrollToSelectedResult()
 745})
 746
 747onKeyStroke('ArrowDown', (event) => {
 748  event.preventDefault()
 749  selectedIndex.value++
 750  if (selectedIndex.value >= filteredResults.value.length + 1) {
 751    selectedIndex.value = 0
 752  }
 753  disableMouseOver.value = true
 754  scrollToSelectedResult()
 755})
 756
 757const router = useRouter()
 758
 759onKeyStroke('Enter', (e) => {
 760  if (e.isComposing) return
 761
 762  if (e.target instanceof HTMLButtonElement && e.target.type !== 'submit') {
 763    return
 764  }
 765
 766  const index = selectedIndex.value - 1
 767
 768  if (index === -1) {
 769    // @ts-ignore
 770    window.toggleAI({ value: filterText.value })
 771    showSearch.value = false
 772    return
 773  }
 774
 775  const selectedPackage = filteredResults.value[index]
 776  if (e.target instanceof HTMLInputElement && !selectedPackage) {
 777    e.preventDefault()
 778    return
 779  }
 780
 781  if (selectedPackage) {
 782    window.dispatchEvent(
 783      new CustomEvent('search-nav', {
 784        detail: { query: filterText.value }
 785      })
 786    )
 787    router.go(selectedPackage.id)
 788    showSearch.value = false
 789  }
 790})
 791
 792function onResultClick() {
 793  window.dispatchEvent(
 794    new CustomEvent('search-nav', {
 795      detail: { query: filterText.value }
 796    })
 797  )
 798  showSearch.value = false
 799}
 800
 801onKeyStroke('Escape', () => {
 802  showSearch.value = false
 803})
 804
 805// Translations
 806const defaultTranslations = {
 807  modal: {
 808    displayDetails: 'Display detailed list',
 809    exactMatchTitle: 'Exact search',
 810    resetButtonTitle: 'Reset search',
 811    backButtonTitle: 'Close search',
 812    noResultsText: 'No results for',
 813    footer: {
 814      selectText: 'to select',
 815      selectKeyAriaLabel: 'enter',
 816      navigateText: 'to navigate',
 817      navigateUpKeyAriaLabel: 'up arrow',
 818      navigateDownKeyAriaLabel: 'down arrow',
 819      closeText: 'to close',
 820      closeKeyAriaLabel: 'escape'
 821    }
 822  }
 823}
 824
 825const translate = createSearchTranslate(defaultTranslations)
 826
 827// Back
 828
 829onMounted(() => {
 830  // Prevents going to previous site
 831  window.history.pushState(null, '', null)
 832})
 833
 834useEventListener('popstate', (event) => {
 835  event.preventDefault()
 836  showSearch.value = false
 837})
 838
 839/** Lock body */
 840const isLocked = useScrollLock(inBrowser ? document.body : null)
 841
 842watch(
 843  () => showSearch.value,
 844  (val) => {
 845    if (!val) {
 846      isLocked.value = false
 847      return
 848    }
 849
 850    nextTick(() => {
 851      isLocked.value = true
 852      nextTick().then(() => {
 853        activate()
 854        updateRibbonOverflow()
 855      })
 856    })
 857  }
 858)
 859
 860function formMarkRegex(terms: Set<string>) {
 861  return new RegExp(
 862    [...terms]
 863      .sort((a, b) => b.length - a.length)
 864      .map((term) => `(${escapeRegExp(term)})`)
 865      .join('|'),
 866    'gi'
 867  )
 868}
 869
 870function resetSearch() {
 871  filterText.value = ''
 872  nextTick().then(() => focusSearchInput(false))
 873}
 874
 875function onMouseMove(e: MouseEvent) {
 876  if (!disableMouseOver.value) return
 877  const el = (e.target as HTMLElement)?.closest<HTMLAnchorElement>('.result')
 878  const index = Number.parseInt(el?.dataset.index!)
 879  if (index >= 0 && index !== selectedIndex.value) {
 880    selectedIndex.value = index
 881  }
 882  disableMouseOver.value = false
 883}
 884</script>
 885
 886<template>
 887  <Teleport to="body">
 888    <div
 889      ref="el"
 890      role="button"
 891      :aria-owns="results?.length ? 'localsearch-list' : undefined"
 892      aria-expanded="true"
 893      aria-haspopup="listbox"
 894      aria-labelledby="localsearch-label"
 895      class="VPLocalSearchBox"
 896      :class="{ 'pointer-events-none': !showSearch }"
 897    >
 898      <div
 899        v-if="showSearch"
 900        class="backdrop"
 901        @click="showSearch = false"
 902      />
 903
 904      <div
 905        v-if="showSearch"
 906        class="shell"
 907      >
 908          <form
 909            class="search-bar"
 910            @pointerup="onSearchBarClick($event)"
 911            @submit.prevent=""
 912          >
 913            <label
 914              :title="buttonText"
 915              id="localsearch-label"
 916              for="localsearch-input"
 917            >
 918              <span
 919                aria-hidden="true"
 920                class="vpi-search search-icon local-search-icon"
 921              />
 922            </label>
 923            <div class="search-actions before">
 924              <button
 925                class="back-button"
 926                :title="translate('modal.backButtonTitle')"
 927                @click="showSearch = false"
 928              >
 929                <span class="vpi-arrow-left local-search-icon" />
 930              </button>
 931            </div>
 932            <input
 933              ref="searchInput"
 934              v-model="filterText"
 935              :aria-activedescendant="selectedIndex > -1
 936              ? 'localsearch-item-' + selectedIndex
 937              : undefined"
 938              aria-autocomplete="both"
 939              :aria-controls="results?.length ? 'localsearch-list' : undefined"
 940              aria-labelledby="localsearch-label"
 941              autocapitalize="off"
 942              autocomplete="off"
 943              autocorrect="off"
 944              class="search-input"
 945              id="localsearch-input"
 946              enterkeyhint="go"
 947              maxlength="64"
 948              :placeholder="buttonText"
 949              spellcheck="false"
 950              type="search"
 951            />
 952            <div class="search-actions">
 953              <button
 954                v-if="!disableDetailedView"
 955                class="toggle-layout-button"
 956                type="button"
 957                :class="{ 'detailed-list': showDetailedList }"
 958                :title="translate('modal.displayDetails')"
 959                @click="selectedIndex > -1 &&
 960                (showDetailedList = !showDetailedList)"
 961              >
 962                <TextAlignStart :size="19" stroke-width="1.25" />
 963              </button>
 964              <button
 965                class="exact-match-button"
 966                type="button"
 967                :class="{ 'exact-match-active': matchExact }"
 968                :title="translate('modal.exactMatchTitle')"
 969                @click="matchExact = !matchExact"
 970              >
 971                <Locate v-if="matchExact" :size="19" stroke-width="1.25" />
 972                <LocateOff v-else :size="19" stroke-width="1.25" />
 973              </button>
 974              <button
 975                class="clear-button"
 976                type="reset"
 977                :disabled="disableReset"
 978                :title="translate('modal.resetButtonTitle')"
 979                @click="resetSearch"
 980              >
 981                <Delete :size="19" stroke-width="1.25" />
 982              </button>
 983            </div>
 984          </form>
 985
 986          <div
 987            v-if="pageGroups.length > 1"
 988            class="page-ribbon"
 989          >
 990              <button
 991                v-if="ribbonCanScrollLeft"
 992                type="button"
 993                class="page-ribbon-arrow left"
 994                aria-label="Scroll filters left"
 995                @click="scrollRibbon(-1)"
 996              >
 997                <ChevronRight :size="18" stroke-width="1.75" />
 998              </button>
 999              <div
1000                ref="ribbonTrack"
1001                class="page-ribbon-track"
1002                @scroll="updateRibbonOverflow"
1003              >
1004                <button
1005                  type="button"
1006                  class="page-pill"
1007                  :class="{ active: activePageFilter === null }"
1008                  @click="setPageFilter(null)"
1009                >
1010                  All
1011                  <span class="page-pill-count">{{ results.length }}</span>
1012                </button>
1013                <button
1014                  v-for="group in pageGroups"
1015                  :key="group.key"
1016                  type="button"
1017                  class="page-pill"
1018                  :class="{ active: activePageFilter === group.key }"
1019                  @click="setPageFilter(group.key)"
1020                >
1021                  <span class="page-pill-label">{{ group.label }}</span>
1022                  <span class="page-pill-count">{{ group.count }}</span>
1023                </button>
1024              </div>
1025              <button
1026                v-if="ribbonCanScrollRight"
1027                type="button"
1028                class="page-ribbon-arrow right"
1029                aria-label="Scroll filters right"
1030                @click="scrollRibbon(1)"
1031              >
1032                <ChevronRight :size="18" stroke-width="1.75" />
1033              </button>
1034            </div>
1035
1036          <ul
1037            ref="resultsEl"
1038            :id="results?.length ? 'localsearch-list' : undefined"
1039            :role="results?.length ? 'listbox' : undefined"
1040            :aria-labelledby="results?.length ? 'localsearch-label' : undefined"
1041            class="results"
1042            @mousemove="onMouseMove"
1043          >
1044            <div
1045              class="flex flex-col justify-center items-center h-47.5 gap-2 font-medium text-sm text-gray-500 dark:text-gray-300 m-auto md:mt-10 md:mb-6 opacity-90"
1046              v-if="!filterText || (filterText && !filteredResults.length)"
1047            >
1048                <img
1049                  class="h-40 object-contain object-center -translate-x-2"
1050                  src="/asset/smolame.png"
1051                  alt="Smol ame"
1052                />
1053                <h1 v-if="filterText && !filteredResults.length">
1054                  Couldn't find anything, try again?
1055                </h1>
1056                <h1 v-else>Looking for something?</h1>
1057              </div>
1058
1059            <li
1060                v-for="(p, index) in filteredResults"
1061                :key="p.id"
1062                class="result-layout"
1063                :id="'localsearch-item-' + (index + 1)"
1064                :aria-selected="selectedIndex === index + 1 ? 'true' : 'false'"
1065                role="option"
1066              >
1067                <a
1068                  :href="p.id"
1069                  class="result"
1070                  :class="{
1071                    selected: selectedIndex === index + 1
1072                  }"
1073                  :aria-label="[...p.titles, p.title].join(' > ')"
1074                  @mouseenter="!disableMouseOver &&
1075                  (selectedIndex = index + 1)"
1076                  @focusin="selectedIndex = index + 1"
1077                  @click="onResultClick"
1078                  :data-index="index + 1"
1079                >
1080                  <div>
1081                    <div class="titles">
1082                      <Hash
1083                        v-if="p.titles.length > 0"
1084                        stroke-width="1.25"
1085                        :size="18"
1086                      />
1087                      <File v-else stroke-width="1.25" :size="18" />
1088
1089                      <span
1090                        v-for="(t, index) in p.titles"
1091                        :key="index"
1092                        class="title"
1093                      >
1094                        <span class="text" v-html="t" />
1095                        <ArrowRight
1096                          stroke-width="1.25"
1097                          :size="18"
1098                          class="mx-0.5"
1099                        />
1100                      </span>
1101                      <span class="title main">
1102                        <span class="text" v-html="p.title" />
1103                      </span>
1104                    </div>
1105
1106                    <div v-if="showDetailedList" class="excerpt-wrapper">
1107                      <div
1108                        v-if="p.text"
1109                        class="excerpt"
1110                        inert
1111                      >
1112                        <div class="vp-doc" v-html="p.text" />
1113                      </div>
1114                      <div class="excerpt-gradient-bottom" />
1115                      <div class="excerpt-gradient-top" />
1116                    </div>
1117                  </div>
1118                </a>
1119              </li>
1120          </ul>
1121
1122          <div class="search-keyboard-shortcuts">
1123            <span>
1124              <kbd
1125                :aria-label="translate(
1126                  'modal.footer.navigateUpKeyAriaLabel'
1127                )"
1128              >
1129                <span class="vpi-arrow-up navigate-icon" />
1130              </kbd>
1131              <kbd
1132                :aria-label="translate(
1133                  'modal.footer.navigateDownKeyAriaLabel'
1134                )"
1135              >
1136                <span class="vpi-arrow-down navigate-icon" />
1137              </kbd>
1138              {{ translate('modal.footer.navigateText') }}
1139            </span>
1140            <span>
1141              <kbd :aria-label="translate('modal.footer.selectKeyAriaLabel')">
1142                <span class="vpi-corner-down-left navigate-icon" />
1143              </kbd>
1144              {{ translate('modal.footer.selectText') }}
1145            </span>
1146            <span>
1147              <kbd :aria-label="translate('modal.footer.closeKeyAriaLabel')">
1148                esc
1149              </kbd>
1150              {{ translate('modal.footer.closeText') }}
1151            </span>
1152          </div>
1153        </div>
1154
1155      <button v-if="!showSearch" />
1156    </div>
1157  </Teleport>
1158</template>
1159
1160<style scoped>
1161.VPLocalSearchBox {
1162  position: fixed;
1163  z-index: 100;
1164  inset: 0;
1165  display: flex;
1166}
1167
1168.backdrop {
1169  position: absolute;
1170  inset: 0;
1171  background: var(--vp-backdrop-bg-color);
1172}
1173
1174.shell {
1175  position: relative;
1176  padding: 12px;
1177  margin: 64px auto;
1178  display: flex;
1179  flex-direction: column;
1180  gap: 16px;
1181  background: var(--vp-local-search-bg);
1182  width: min(100vw - 60px, 900px);
1183  height: min-content;
1184  max-height: min(100vh - 128px, 900px);
1185  border-radius: 6px;
1186}
1187
1188@media (max-width: 767px) {
1189  .shell {
1190    margin: 0;
1191    width: 100vw;
1192    height: 100vh;
1193    max-height: none;
1194    border-radius: 0;
1195  }
1196}
1197
1198.search-bar {
1199  border: 1px solid var(--vp-c-divider);
1200  border-radius: 4px;
1201  display: flex;
1202  align-items: center;
1203  padding: 0 12px;
1204  cursor: text;
1205}
1206
1207@media (max-width: 767px) {
1208  .search-bar {
1209    padding: 0 8px;
1210  }
1211}
1212
1213.search-bar:focus-within {
1214  border-color: var(--vp-c-brand-1);
1215}
1216
1217.page-ribbon {
1218  display: flex;
1219  align-items: center;
1220  padding: 12px 0 4px;
1221  padding-inline: calc(var(--spacing) * 3);
1222  position: relative;
1223  min-width: 0;
1224  flex: none;
1225  overflow: hidden;
1226}
1227
1228.page-ribbon-track {
1229  display: flex;
1230  flex-wrap: nowrap;
1231  gap: 8px;
1232  min-width: 0;
1233  flex: 1;
1234  overflow-x: auto;
1235  overflow-y: hidden;
1236  scrollbar-width: none;
1237  -ms-overflow-style: none;
1238  overscroll-behavior-x: contain;
1239}
1240
1241.page-ribbon-track::-webkit-scrollbar {
1242  display: none;
1243  width: 0;
1244  height: 0;
1245}
1246
1247.page-ribbon-arrow {
1248  position: absolute;
1249  top: 0;
1250  bottom: 0;
1251  z-index: 2;
1252  display: inline-flex;
1253  align-items: center;
1254  justify-content: center;
1255  width: 48px;
1256  border: none;
1257  background: transparent;
1258  color: var(--vp-c-text-2);
1259  cursor: pointer;
1260  transition: color 0.15s;
1261}
1262
1263.page-ribbon-arrow:hover {
1264  color: var(--vp-c-text-1);
1265}
1266
1267.page-ribbon-arrow.right {
1268  right: 0;
1269  background: linear-gradient(to right, transparent, var(--vp-local-search-bg, var(--vp-c-bg-soft)) 70%);
1270  justify-content: flex-end;
1271  padding-right: 6px;
1272}
1273
1274.page-ribbon-arrow.left {
1275  left: 0;
1276  background: linear-gradient(to left, transparent, var(--vp-local-search-bg, var(--vp-c-bg-soft)) 70%);
1277  justify-content: flex-start;
1278  padding-left: 6px;
1279}
1280
1281.page-ribbon-arrow.left svg {
1282  transform: rotate(180deg);
1283}
1284
1285.page-pill {
1286  flex: none;
1287  display: inline-flex;
1288  align-items: center;
1289  gap: 6px;
1290  padding: 6px 10px;
1291  font-size: 0.8rem;
1292  line-height: 1.2;
1293  white-space: nowrap;
1294  border-radius: 8px;
1295  border: 1.5px solid var(--vp-c-divider);
1296  background: var(--vp-c-bg-soft);
1297  color: var(--vp-c-text-2);
1298  cursor: pointer;
1299  transition: color 0.15s, border-color 0.15s, background-color 0.15s;
1300}
1301
1302.page-pill:hover {
1303  color: var(--vp-c-text-1);
1304  border-color: var(--vp-c-brand-1);
1305}
1306
1307.page-pill.active {
1308  color: #6ab0f5;
1309  border: 1.5px solid #6ab0f5;
1310  background: rgba(60, 120, 210, 0.12);
1311  box-shadow: none;
1312}
1313
1314.page-pill-label {
1315  max-width: 180px;
1316  overflow: hidden;
1317  text-overflow: ellipsis;
1318}
1319
1320.page-pill-count {
1321  font-variant-numeric: tabular-nums;
1322  font-size: 0.7rem;
1323  padding: 1px 6px;
1324  border-radius: 4px;
1325  background: rgba(128, 128, 128, 0.15);
1326  color: inherit;
1327}
1328
1329.page-pill.active .page-pill-count {
1330  background: rgba(100, 160, 240, 0.18);
1331}
1332
1333@media (max-width: 767px) {
1334  .page-ribbon {
1335    padding: 14px 0 4px;
1336  }
1337
1338  .page-pill {
1339    padding: 7px 14px;
1340    font-size: 0.82rem;
1341    background: var(--vp-c-bg-elv, var(--vp-c-bg-soft));
1342    border-color: var(--vp-c-divider);
1343    color: var(--vp-c-text-1);
1344  }
1345}
1346
1347.local-search-icon {
1348  display: block;
1349  font-size: 18px;
1350}
1351
1352.navigate-icon {
1353  display: block;
1354  font-size: 14px;
1355}
1356
1357.search-icon {
1358  margin: 8px;
1359}
1360
1361@media (max-width: 767px) {
1362  .search-icon {
1363    display: none;
1364  }
1365}
1366
1367.search-input {
1368  padding: 6px 12px;
1369  font-size: inherit;
1370  width: 100%;
1371}
1372
1373.search-input::-webkit-search-cancel-button {
1374  display: none;
1375}
1376
1377@media (max-width: 767px) {
1378  .search-input {
1379    padding: 6px 4px;
1380  }
1381}
1382
1383.search-actions {
1384  display: flex;
1385  gap: 4px;
1386}
1387
1388@media (any-pointer: coarse) {
1389  .search-actions {
1390    gap: 8px;
1391  }
1392}
1393
1394@media (min-width: 769px) {
1395  .search-actions.before {
1396    display: none;
1397  }
1398}
1399
1400.search-actions button {
1401  padding: 8px;
1402}
1403
1404.search-actions button:not([disabled]):hover,
1405.toggle-layout-button.detailed-list {
1406  color: var(--vp-c-brand-1);
1407}
1408
1409.search-actions button.clear-button:disabled {
1410  opacity: 0.37;
1411}
1412
1413.search-keyboard-shortcuts {
1414  font-size: 0.8rem;
1415  opacity: 75%;
1416  display: flex;
1417  flex-wrap: wrap;
1418  gap: 16px;
1419  line-height: 14px;
1420}
1421
1422.search-keyboard-shortcuts span {
1423  display: flex;
1424  align-items: center;
1425  gap: 4px;
1426}
1427
1428@media (max-width: 767px) {
1429  .search-keyboard-shortcuts {
1430    display: none;
1431  }
1432}
1433
1434.search-keyboard-shortcuts kbd {
1435  background: rgba(128, 128, 128, 0.1);
1436  border-radius: 4px;
1437  padding: 3px 6px;
1438  min-width: 24px;
1439  display: inline-block;
1440  text-align: center;
1441  vertical-align: middle;
1442  border: 1px solid rgba(128, 128, 128, 0.15);
1443  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
1444}
1445
1446.results {
1447  display: flex;
1448  flex-direction: column;
1449  gap: 6px;
1450  overflow-x: hidden;
1451  overflow-y: auto;
1452  overscroll-behavior: contain;
1453}
1454
1455.result {
1456  display: flex;
1457  align-items: center;
1458  gap: 8px;
1459  border-radius: 4px;
1460  transition: none;
1461  line-height: 1rem;
1462  border: solid 2px var(--vp-local-search-result-border);
1463  outline: none;
1464}
1465
1466.result > div {
1467  margin: 12px;
1468  width: 100%;
1469  overflow: hidden;
1470}
1471
1472@media (max-width: 767px) {
1473  .result > div {
1474    margin: 8px;
1475  }
1476}
1477
1478.titles {
1479  display: flex;
1480  flex-wrap: wrap;
1481  gap: 4px;
1482  position: relative;
1483  z-index: 1001;
1484  padding: 2px 0;
1485}
1486
1487.title {
1488  display: flex;
1489  align-items: center;
1490  gap: 4px;
1491}
1492
1493.title.main {
1494  font-weight: 500;
1495}
1496
1497.title-icon {
1498  opacity: 1;
1499  font-weight: 500;
1500}
1501
1502.title svg {
1503  opacity: 0.5;
1504}
1505
1506.result.selected {
1507  --vp-local-search-result-bg: var(--vp-local-search-result-selected-bg);
1508  border-color: var(--vp-local-search-result-selected-border);
1509}
1510
1511.excerpt-wrapper {
1512  position: relative;
1513}
1514
1515.excerpt {
1516  opacity: 50%;
1517  pointer-events: none;
1518  height: 84px;
1519  max-height: 84px;
1520  overflow: hidden;
1521  position: relative;
1522  margin-top: 4px;
1523}
1524
1525.result.selected .excerpt {
1526  opacity: 1;
1527}
1528
1529.excerpt :deep(*) {
1530  font-size: 0.8rem !important;
1531  line-height: 130% !important;
1532}
1533
1534.titles :deep(mark),
1535.excerpt :deep(mark) {
1536  background-color: var(--vp-local-search-highlight-bg);
1537  color: var(--vp-local-search-highlight-text);
1538  border-radius: 2px;
1539  padding: 0 2px;
1540}
1541
1542.excerpt :deep(.vp-code-group) .tabs {
1543  display: none;
1544}
1545
1546.excerpt :deep(.vp-code-group) div[class*="language-"] {
1547  border-radius: 8px !important;
1548}
1549
1550.excerpt > .vp-doc > *:first-child {
1551  margin-top: 6px !important;
1552}
1553
1554.excerpt-gradient-bottom {
1555  position: absolute;
1556  bottom: -1px;
1557  left: 0;
1558  width: 100%;
1559  height: 8px;
1560  background: linear-gradient(transparent, var(--vp-local-search-result-bg));
1561  z-index: 1000;
1562}
1563
1564.excerpt-gradient-top {
1565  position: absolute;
1566  top: -1px;
1567  left: 0;
1568  width: 100%;
1569  height: 8px;
1570  background: linear-gradient(var(--vp-local-search-result-bg), transparent);
1571  z-index: 1000;
1572}
1573
1574.result.selected .titles,
1575.result.selected .title-icon {
1576  color: var(--vp-c-brand-1) !important;
1577}
1578
1579.no-results {
1580  font-size: 0.9rem;
1581  text-align: center;
1582  padding: 12px;
1583}
1584
1585svg {
1586  flex: none;
1587}
1588
1589.exact-match-button.exact-match-active {
1590  color: var(--vp-c-brand-1);
1591  background-color: rgba(var(--vp-c-brand-1), 0.1);
1592  border-radius: 4px;
1593}
1594</style>