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

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

1521 lines · 37812 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>>(16) // 16 files
 369
 370watchDebounced(
 371  () => [searchIndex.value, filterText.value, showDetailedList.value, matchExact.value] as const,
 372  async ([index, filterTextValue, showDetailedListValue, matchExactValue], old, onCleanup) => {
 373    if (old?.[0] !== index) {
 374      // in case of hmr
 375      cache.clear()
 376    }
 377
 378    let canceled = false
 379    onCleanup(() => {
 380      canceled = true
 381    })
 382
 383    if (!index) return
 384
 385    // Dynamic search options based on matchExact toggle
 386    const dynamicSearchOptions = {
 387      fuzzy: matchExactValue ? false : (0.07 as number | false),
 388      prefix: matchExactValue ? false : (term: string) => term.length > 3,
 389      maxFuzzy: matchExactValue ? 0 : 1,
 390    }
 391
 392    // Search
 393    const ranked = index.search(filterTextValue, dynamicSearchOptions) as (SearchResult & Result)[]
 394
 395    // Guaranteed heading matches: any section whose own heading (title)
 396    // contains the term should always show, regardless of score or cap.
 397    const titleHits = index.search(filterTextValue, {
 398      ...dynamicSearchOptions,
 399      fields: ['title']
 400    }) as (SearchResult & Result)[]
 401
 402    const top = ranked.slice(0, 50)
 403    const seen = new Set(top.map((r) => r.id))
 404    const _result = [
 405      ...top,
 406      ...titleHits.filter((r) => !seen.has(r.id))
 407    ] as (SearchResult & Result)[]
 408    enableNoResults.value = true
 409
 410    if (!_result) {
 411      results.value = []
 412      return
 413    }
 414
 415    // Highlighting
 416    const mods = showDetailedListValue
 417      ? await Promise.all(_result.map((r) => fetchExcerpt(r.id)))
 418      : []
 419    if (canceled) return
 420    for (const { id, mod } of mods) {
 421      const mapId = id.slice(0, id.indexOf('#'))
 422      const cacheId = `${mapId}\n${filterTextValue}`
 423      let map = cache.get(cacheId)
 424      if (map) continue
 425      map = new Map()
 426      cache.set(cacheId, map)
 427      const comp = mod.default ?? mod
 428      if (comp?.render || comp?.setup) {
 429        const app = createApp(comp)
 430        // Silence warnings about missing components
 431        app.config.warnHandler = () => {}
 432        enhanceAppWithTabs(app)
 433        app.provide(dataSymbol, vitePressData)
 434        Object.defineProperties(app.config.globalProperties, {
 435          $frontmatter: {
 436            get() {
 437              return vitePressData.frontmatter.value
 438            }
 439          },
 440          $params: {
 441            get() {
 442              return vitePressData.page.value.params
 443            }
 444          }
 445        })
 446        const div = document.createElement('div')
 447        app.mount(div)
 448        await selectExcerptTabs(div, filterTextValue)
 449        const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6')
 450        headings.forEach((el) => {
 451          const href = el.querySelector('a')?.getAttribute('href')
 452          const anchor = href?.startsWith('#') && href.slice(1)
 453          if (!anchor) return
 454          let html = ''
 455          while (
 456            (el = el.nextElementSibling!) &&
 457            !/^h[1-6]$/i.test(el.tagName)
 458          ) {
 459            html += el.outerHTML
 460          }
 461          map!.set(anchor, html)
 462        })
 463        app.unmount()
 464      }
 465      if (canceled) return
 466    }
 467
 468    const terms = new Set<string>()
 469
 470    results.value = _result
 471      .map((r) => {
 472        const [id, anchor] = r.id.split('#')
 473        const map = cache.get(`${id}\n${filterTextValue}`)
 474        const text = map?.get(anchor) ?? ''
 475        for (const term in r.match) {
 476          terms.add(term)
 477        }
 478        return { ...r, text }
 479      })
 480      .sort((a, b) => {
 481        const pageDiff =
 482          getPageOrder(getPageKey(a.id)) - getPageOrder(getPageKey(b.id))
 483        if (pageDiff !== 0) return pageDiff
 484        return getDocOrder(a.id) - getDocOrder(b.id)
 485      })
 486
 487    currentTerms.value = terms
 488
 489    await nextTick()
 490    if (canceled) return
 491
 492    await new Promise((r) => {
 493      mark.value?.unmark({
 494        done: () => {
 495          mark.value?.markRegExp(formMarkRegex(terms), { done: r })
 496        }
 497      })
 498    })
 499
 500    await nextTick()
 501    await nextFrame()
 502    if (canceled) return
 503
 504    if (resultsEl.value) {
 505      resultsEl.value.scrollTop = 0
 506    }
 507    centerExcerptsUntilSettled()
 508  },
 509  { debounce: 80, immediate: true }
 510)
 511
 512function centerExcerpts() {
 513  const excerpts = el.value?.querySelectorAll('.result .excerpt') ?? []
 514  for (let i = 0; i < excerpts.length; i++) {
 515    const excerptElement = excerpts[i] as HTMLElement
 516
 517    const markNode = excerptElement.querySelector(
 518      'mark[data-markjs="true"]'
 519    ) as HTMLElement | null
 520    if (!markNode) continue
 521
 522    const viewportHeight =
 523      Number.parseFloat(getComputedStyle(excerptElement).maxHeight) || 84
 524
 525    let offset = 0
 526    let node: HTMLElement | null = markNode
 527    while (node && node !== excerptElement) {
 528      offset += node.offsetTop
 529      node = node.offsetParent as HTMLElement | null
 530    }
 531
 532    const targetScrollTop = offset - viewportHeight / 2 + markNode.offsetHeight / 2
 533    excerptElement.scrollTop = Math.max(0, targetScrollTop)
 534  }
 535}
 536
 537let centerHandle = 0
 538
 539function centerExcerptsUntilSettled() {
 540  // No layout animations to wait on anymore — a single pass after the
 541  // DOM has painted is enough.
 542  if (centerHandle) cancelAnimationFrame(centerHandle)
 543  centerHandle = requestAnimationFrame(() => {
 544    centerExcerpts()
 545    centerHandle = 0
 546  })
 547}
 548
 549onBeforeUnmount(() => {
 550  if (centerHandle) cancelAnimationFrame(centerHandle)
 551  if (ribbonAnimHandle) cancelAnimationFrame(ribbonAnimHandle)
 552})
 553
 554const excerptCache = new LRUCache<string, unknown>(60) // 60 excerpts
 555
 556async function fetchExcerpt(id: string) {
 557  const cache = excerptCache.get(id)
 558  if (cache) return { id, mod: cache }
 559
 560  const file = pathToFile(id.slice(0, id.indexOf('#')))
 561  try {
 562    if (!file) throw new Error(`Cannot find file for id: ${id}`)
 563    const mod = await import(/*@vite-ignore*/ file)
 564
 565    excerptCache.set(id, mod)
 566
 567    return { id, mod }
 568  } catch (e) {
 569    console.error(e)
 570    return { id, mod: {} }
 571  }
 572}
 573
 574const nextFrame = () =>
 575  new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
 576
 577const getSearchTerms = (query: string) =>
 578  query
 579    .toLowerCase()
 580    .split(/\s+/)
 581    .map((term) => term.trim())
 582    .filter(Boolean)
 583
 584async function selectExcerptTabs(root: HTMLElement, query: string) {
 585  const terms = getSearchTerms(query)
 586  if (!terms.length) return
 587
 588  const tabs = root.querySelectorAll<HTMLElement>('.plugin-tabs')
 589
 590  for (let i = 0; i < tabs.length; i++) {
 591    const tab = tabs[i]
 592    const selectedTab = tab.querySelector<HTMLButtonElement>(
 593      '.plugin-tabs--tab[aria-selected="true"]'
 594    )
 595    const buttons = tab.querySelectorAll<HTMLButtonElement>(
 596      '.plugin-tabs--tab[role="tab"]'
 597    )
 598
 599    let found = false
 600
 601    for (let j = 0; j < buttons.length; j++) {
 602      const button = buttons[j]
 603      button.click()
 604      await nextTick()
 605      await nextFrame()
 606
 607      const panelId = button.getAttribute('aria-controls')
 608      const panel = panelId
 609        ? root.querySelector<HTMLElement>(`#${CSS.escape(panelId)}`)
 610        : tab.querySelector<HTMLElement>('.plugin-tabs--content')
 611      const text = panel?.textContent?.toLowerCase() ?? ''
 612
 613      if (terms.every((term) => text.includes(term))) {
 614        found = true
 615        break
 616      }
 617    }
 618
 619    if (!found) {
 620      selectedTab?.click()
 621      await nextTick()
 622    }
 623  }
 624}
 625
 626/* Search input focus */
 627
 628const searchInput = ref<HTMLInputElement>()
 629const disableReset = computed(() => {
 630  return filterText.value?.length <= 0
 631})
 632function focusSearchInput(select = true) {
 633  searchInput.value?.focus()
 634  select && searchInput.value?.select()
 635}
 636
 637onMounted(() => {
 638  focusSearchInput()
 639})
 640
 641function onSearchBarClick(event: PointerEvent) {
 642  if (event.pointerType === 'mouse') {
 643    focusSearchInput()
 644  }
 645}
 646
 647/* Search keyboard selection */
 648
 649const selectedIndex = ref(-1)
 650const disableMouseOver = ref(true)
 651
 652watch(filteredResults, (r) => {
 653  selectedIndex.value = r.length ? 0 : -1
 654  scrollToSelectedResult()
 655})
 656
 657function scrollToSelectedResult() {
 658  nextTick(() => {
 659    const selectedEl = document.querySelector('.result.selected')
 660    selectedEl?.scrollIntoView({ block: 'nearest' })
 661  })
 662}
 663
 664onKeyStroke('ArrowUp', (event) => {
 665  event.preventDefault()
 666  selectedIndex.value--
 667  if (selectedIndex.value < 0) {
 668    selectedIndex.value = filteredResults.value.length - 1
 669  }
 670  disableMouseOver.value = true
 671  scrollToSelectedResult()
 672})
 673
 674onKeyStroke('ArrowDown', (event) => {
 675  event.preventDefault()
 676  selectedIndex.value++
 677  if (selectedIndex.value >= filteredResults.value.length + 1) {
 678    selectedIndex.value = 0
 679  }
 680  disableMouseOver.value = true
 681  scrollToSelectedResult()
 682})
 683
 684const router = useRouter()
 685
 686onKeyStroke('Enter', (e) => {
 687  if (e.isComposing) return
 688
 689  if (e.target instanceof HTMLButtonElement && e.target.type !== 'submit') {
 690    return
 691  }
 692
 693  const index = selectedIndex.value - 1
 694
 695  if (index === -1) {
 696    // @ts-ignore
 697    window.toggleAI({ value: filterText.value })
 698    showSearch.value = false
 699    return
 700  }
 701
 702  const selectedPackage = filteredResults.value[index]
 703  if (e.target instanceof HTMLInputElement && !selectedPackage) {
 704    e.preventDefault()
 705    return
 706  }
 707
 708  if (selectedPackage) {
 709    window.dispatchEvent(
 710      new CustomEvent('search-nav', {
 711        detail: { query: filterText.value }
 712      })
 713    )
 714    router.go(selectedPackage.id)
 715    showSearch.value = false
 716  }
 717})
 718
 719function onResultClick() {
 720  window.dispatchEvent(
 721    new CustomEvent('search-nav', {
 722      detail: { query: filterText.value }
 723    })
 724  )
 725  showSearch.value = false
 726}
 727
 728onKeyStroke('Escape', () => {
 729  showSearch.value = false
 730})
 731
 732// Translations
 733const defaultTranslations = {
 734  modal: {
 735    displayDetails: 'Display detailed list',
 736    exactMatchTitle: 'Exact search',
 737    resetButtonTitle: 'Reset search',
 738    backButtonTitle: 'Close search',
 739    noResultsText: 'No results for',
 740    footer: {
 741      selectText: 'to select',
 742      selectKeyAriaLabel: 'enter',
 743      navigateText: 'to navigate',
 744      navigateUpKeyAriaLabel: 'up arrow',
 745      navigateDownKeyAriaLabel: 'down arrow',
 746      closeText: 'to close',
 747      closeKeyAriaLabel: 'escape'
 748    }
 749  }
 750}
 751
 752const translate = createSearchTranslate(defaultTranslations)
 753
 754// Back
 755
 756onMounted(() => {
 757  // Prevents going to previous site
 758  window.history.pushState(null, '', null)
 759})
 760
 761useEventListener('popstate', (event) => {
 762  event.preventDefault()
 763  showSearch.value = false
 764})
 765
 766/** Lock body */
 767const isLocked = useScrollLock(inBrowser ? document.body : null)
 768
 769watch(
 770  () => showSearch.value,
 771  (val) => {
 772    if (!val) {
 773      isLocked.value = false
 774      return
 775    }
 776
 777    nextTick(() => {
 778      isLocked.value = true
 779      nextTick().then(() => {
 780        activate()
 781        updateRibbonOverflow()
 782      })
 783    })
 784  }
 785)
 786
 787function formMarkRegex(terms: Set<string>) {
 788  return new RegExp(
 789    [...terms]
 790      .sort((a, b) => b.length - a.length)
 791      .map((term) => `(${escapeRegExp(term)})`)
 792      .join('|'),
 793    'gi'
 794  )
 795}
 796
 797function resetSearch() {
 798  filterText.value = ''
 799  nextTick().then(() => focusSearchInput(false))
 800}
 801
 802function onMouseMove(e: MouseEvent) {
 803  if (!disableMouseOver.value) return
 804  const el = (e.target as HTMLElement)?.closest<HTMLAnchorElement>('.result')
 805  const index = Number.parseInt(el?.dataset.index!)
 806  if (index >= 0 && index !== selectedIndex.value) {
 807    selectedIndex.value = index
 808  }
 809  disableMouseOver.value = false
 810}
 811</script>
 812
 813<template>
 814  <Teleport to="body">
 815    <div
 816      ref="el"
 817      role="button"
 818      :aria-owns="results?.length ? 'localsearch-list' : undefined"
 819      aria-expanded="true"
 820      aria-haspopup="listbox"
 821      aria-labelledby="localsearch-label"
 822      class="VPLocalSearchBox"
 823      :class="{ 'pointer-events-none': !showSearch }"
 824    >
 825      <div
 826        v-if="showSearch"
 827        class="backdrop"
 828        @click="showSearch = false"
 829      />
 830
 831      <div
 832        v-if="showSearch"
 833        class="shell"
 834      >
 835          <form
 836            class="search-bar"
 837            @pointerup="onSearchBarClick($event)"
 838            @submit.prevent=""
 839          >
 840            <label
 841              :title="buttonText"
 842              id="localsearch-label"
 843              for="localsearch-input"
 844            >
 845              <span
 846                aria-hidden="true"
 847                class="vpi-search search-icon local-search-icon"
 848              />
 849            </label>
 850            <div class="search-actions before">
 851              <button
 852                class="back-button"
 853                :title="translate('modal.backButtonTitle')"
 854                @click="showSearch = false"
 855              >
 856                <span class="vpi-arrow-left local-search-icon" />
 857              </button>
 858            </div>
 859            <input
 860              ref="searchInput"
 861              v-model="filterText"
 862              :aria-activedescendant="selectedIndex > -1
 863              ? 'localsearch-item-' + selectedIndex
 864              : undefined"
 865              aria-autocomplete="both"
 866              :aria-controls="results?.length ? 'localsearch-list' : undefined"
 867              aria-labelledby="localsearch-label"
 868              autocapitalize="off"
 869              autocomplete="off"
 870              autocorrect="off"
 871              class="search-input"
 872              id="localsearch-input"
 873              enterkeyhint="go"
 874              maxlength="64"
 875              :placeholder="buttonText"
 876              spellcheck="false"
 877              type="search"
 878            />
 879            <div class="search-actions">
 880              <button
 881                v-if="!disableDetailedView"
 882                class="toggle-layout-button"
 883                type="button"
 884                :class="{ 'detailed-list': showDetailedList }"
 885                :title="translate('modal.displayDetails')"
 886                @click="selectedIndex > -1 &&
 887                (showDetailedList = !showDetailedList)"
 888              >
 889                <TextAlignStart :size="19" stroke-width="1.25" />
 890              </button>
 891              <button
 892                class="exact-match-button"
 893                type="button"
 894                :class="{ 'exact-match-active': matchExact }"
 895                :title="translate('modal.exactMatchTitle')"
 896                @click="matchExact = !matchExact"
 897              >
 898                <Locate v-if="matchExact" :size="19" stroke-width="1.25" />
 899                <LocateOff v-else :size="19" stroke-width="1.25" />
 900              </button>
 901              <button
 902                class="clear-button"
 903                type="reset"
 904                :disabled="disableReset"
 905                :title="translate('modal.resetButtonTitle')"
 906                @click="resetSearch"
 907              >
 908                <Delete :size="19" stroke-width="1.25" />
 909              </button>
 910            </div>
 911          </form>
 912
 913          <div
 914            v-if="pageGroups.length > 1"
 915            class="page-ribbon"
 916          >
 917              <button
 918                v-if="ribbonCanScrollLeft"
 919                type="button"
 920                class="page-ribbon-arrow left"
 921                aria-label="Scroll filters left"
 922                @click="scrollRibbon(-1)"
 923              >
 924                <ChevronRight :size="18" stroke-width="1.75" />
 925              </button>
 926              <div
 927                ref="ribbonTrack"
 928                class="page-ribbon-track"
 929                @scroll="updateRibbonOverflow"
 930              >
 931                <button
 932                  type="button"
 933                  class="page-pill"
 934                  :class="{ active: activePageFilter === null }"
 935                  @click="setPageFilter(null)"
 936                >
 937                  All
 938                  <span class="page-pill-count">{{ results.length }}</span>
 939                </button>
 940                <button
 941                  v-for="group in pageGroups"
 942                  :key="group.key"
 943                  type="button"
 944                  class="page-pill"
 945                  :class="{ active: activePageFilter === group.key }"
 946                  @click="setPageFilter(group.key)"
 947                >
 948                  <span class="page-pill-label">{{ group.label }}</span>
 949                  <span class="page-pill-count">{{ group.count }}</span>
 950                </button>
 951              </div>
 952              <button
 953                v-if="ribbonCanScrollRight"
 954                type="button"
 955                class="page-ribbon-arrow right"
 956                aria-label="Scroll filters right"
 957                @click="scrollRibbon(1)"
 958              >
 959                <ChevronRight :size="18" stroke-width="1.75" />
 960              </button>
 961            </div>
 962
 963          <ul
 964            ref="resultsEl"
 965            :id="results?.length ? 'localsearch-list' : undefined"
 966            :role="results?.length ? 'listbox' : undefined"
 967            :aria-labelledby="results?.length ? 'localsearch-label' : undefined"
 968            class="results"
 969            @mousemove="onMouseMove"
 970          >
 971            <div
 972              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"
 973              v-if="!filterText || (filterText && !filteredResults.length)"
 974            >
 975                <img
 976                  class="h-40 object-contain object-center -translate-x-2"
 977                  src="/asset/smolame.png"
 978                  alt="Smol ame"
 979                />
 980                <h1 v-if="filterText && !filteredResults.length">
 981                  Couldn't find anything, try again?
 982                </h1>
 983                <h1 v-else>Looking for something?</h1>
 984              </div>
 985
 986            <li
 987                v-for="(p, index) in filteredResults"
 988                :key="p.id"
 989                class="result-layout"
 990                :id="'localsearch-item-' + (index + 1)"
 991                :aria-selected="selectedIndex === index + 1 ? 'true' : 'false'"
 992                role="option"
 993              >
 994                <a
 995                  :href="p.id"
 996                  class="result"
 997                  :class="{
 998                    selected: selectedIndex === index + 1
 999                  }"
1000                  :aria-label="[...p.titles, p.title].join(' > ')"
1001                  @mouseenter="!disableMouseOver &&
1002                  (selectedIndex = index + 1)"
1003                  @focusin="selectedIndex = index + 1"
1004                  @click="onResultClick"
1005                  :data-index="index + 1"
1006                >
1007                  <div>
1008                    <div class="titles">
1009                      <Hash
1010                        v-if="p.titles.length > 0"
1011                        stroke-width="1.25"
1012                        :size="18"
1013                      />
1014                      <File v-else stroke-width="1.25" :size="18" />
1015
1016                      <span
1017                        v-for="(t, index) in p.titles"
1018                        :key="index"
1019                        class="title"
1020                      >
1021                        <span class="text" v-html="t" />
1022                        <ArrowRight
1023                          stroke-width="1.25"
1024                          :size="18"
1025                          class="mx-0.5"
1026                        />
1027                      </span>
1028                      <span class="title main">
1029                        <span class="text" v-html="p.title" />
1030                      </span>
1031                    </div>
1032
1033                    <div v-if="showDetailedList" class="excerpt-wrapper">
1034                      <div
1035                        v-if="p.text"
1036                        class="excerpt"
1037                        inert
1038                      >
1039                        <div class="vp-doc" v-html="p.text" />
1040                      </div>
1041                      <div class="excerpt-gradient-bottom" />
1042                      <div class="excerpt-gradient-top" />
1043                    </div>
1044                  </div>
1045                </a>
1046              </li>
1047          </ul>
1048
1049          <div class="search-keyboard-shortcuts">
1050            <span>
1051              <kbd
1052                :aria-label="translate(
1053                  'modal.footer.navigateUpKeyAriaLabel'
1054                )"
1055              >
1056                <span class="vpi-arrow-up navigate-icon" />
1057              </kbd>
1058              <kbd
1059                :aria-label="translate(
1060                  'modal.footer.navigateDownKeyAriaLabel'
1061                )"
1062              >
1063                <span class="vpi-arrow-down navigate-icon" />
1064              </kbd>
1065              {{ translate('modal.footer.navigateText') }}
1066            </span>
1067            <span>
1068              <kbd :aria-label="translate('modal.footer.selectKeyAriaLabel')">
1069                <span class="vpi-corner-down-left navigate-icon" />
1070              </kbd>
1071              {{ translate('modal.footer.selectText') }}
1072            </span>
1073            <span>
1074              <kbd :aria-label="translate('modal.footer.closeKeyAriaLabel')">
1075                esc
1076              </kbd>
1077              {{ translate('modal.footer.closeText') }}
1078            </span>
1079          </div>
1080        </div>
1081
1082      <button v-if="!showSearch" />
1083    </div>
1084  </Teleport>
1085</template>
1086
1087<style scoped>
1088.VPLocalSearchBox {
1089  position: fixed;
1090  z-index: 100;
1091  inset: 0;
1092  display: flex;
1093}
1094
1095.backdrop {
1096  position: absolute;
1097  inset: 0;
1098  background: var(--vp-backdrop-bg-color);
1099}
1100
1101.shell {
1102  position: relative;
1103  padding: 12px;
1104  margin: 64px auto;
1105  display: flex;
1106  flex-direction: column;
1107  gap: 16px;
1108  background: var(--vp-local-search-bg);
1109  width: min(100vw - 60px, 900px);
1110  height: min-content;
1111  max-height: min(100vh - 128px, 900px);
1112  border-radius: 6px;
1113}
1114
1115@media (max-width: 767px) {
1116  .shell {
1117    margin: 0;
1118    width: 100vw;
1119    height: 100vh;
1120    max-height: none;
1121    border-radius: 0;
1122  }
1123}
1124
1125.search-bar {
1126  border: 1px solid var(--vp-c-divider);
1127  border-radius: 4px;
1128  display: flex;
1129  align-items: center;
1130  padding: 0 12px;
1131  cursor: text;
1132}
1133
1134@media (max-width: 767px) {
1135  .search-bar {
1136    padding: 0 8px;
1137  }
1138}
1139
1140.search-bar:focus-within {
1141  border-color: var(--vp-c-brand-1);
1142}
1143
1144.page-ribbon {
1145  display: flex;
1146  align-items: center;
1147  padding: 12px 0 4px;
1148  padding-inline: calc(var(--spacing) * 3);
1149  position: relative;
1150  min-width: 0;
1151  flex: none;
1152  overflow: hidden;
1153}
1154
1155.page-ribbon-track {
1156  display: flex;
1157  flex-wrap: nowrap;
1158  gap: 8px;
1159  min-width: 0;
1160  flex: 1;
1161  overflow-x: auto;
1162  overflow-y: hidden;
1163  scrollbar-width: none;
1164  -ms-overflow-style: none;
1165  overscroll-behavior-x: contain;
1166}
1167
1168.page-ribbon-track::-webkit-scrollbar {
1169  display: none;
1170  width: 0;
1171  height: 0;
1172}
1173
1174.page-ribbon-arrow {
1175  position: absolute;
1176  top: 0;
1177  bottom: 0;
1178  z-index: 2;
1179  display: inline-flex;
1180  align-items: center;
1181  justify-content: center;
1182  width: 48px;
1183  border: none;
1184  background: transparent;
1185  color: var(--vp-c-text-2);
1186  cursor: pointer;
1187  transition: color 0.15s;
1188}
1189
1190.page-ribbon-arrow:hover {
1191  color: var(--vp-c-text-1);
1192}
1193
1194.page-ribbon-arrow.right {
1195  right: 0;
1196  background: linear-gradient(to right, transparent, var(--vp-local-search-bg, var(--vp-c-bg-soft)) 70%);
1197  justify-content: flex-end;
1198  padding-right: 6px;
1199}
1200
1201.page-ribbon-arrow.left {
1202  left: 0;
1203  background: linear-gradient(to left, transparent, var(--vp-local-search-bg, var(--vp-c-bg-soft)) 70%);
1204  justify-content: flex-start;
1205  padding-left: 6px;
1206}
1207
1208.page-ribbon-arrow.left svg {
1209  transform: rotate(180deg);
1210}
1211
1212.page-pill {
1213  flex: none;
1214  display: inline-flex;
1215  align-items: center;
1216  gap: 6px;
1217  padding: 6px 10px;
1218  font-size: 0.8rem;
1219  line-height: 1.2;
1220  white-space: nowrap;
1221  border-radius: 8px;
1222  border: 1.5px solid var(--vp-c-divider);
1223  background: var(--vp-c-bg-soft);
1224  color: var(--vp-c-text-2);
1225  cursor: pointer;
1226  transition: color 0.15s, border-color 0.15s, background-color 0.15s;
1227}
1228
1229.page-pill:hover {
1230  color: var(--vp-c-text-1);
1231  border-color: var(--vp-c-brand-1);
1232}
1233
1234.page-pill.active {
1235  color: #6ab0f5;
1236  border: 1.5px solid #6ab0f5;
1237  background: rgba(60, 120, 210, 0.12);
1238  box-shadow: none;
1239}
1240
1241.page-pill-label {
1242  max-width: 180px;
1243  overflow: hidden;
1244  text-overflow: ellipsis;
1245}
1246
1247.page-pill-count {
1248  font-variant-numeric: tabular-nums;
1249  font-size: 0.7rem;
1250  padding: 1px 6px;
1251  border-radius: 4px;
1252  background: rgba(128, 128, 128, 0.15);
1253  color: inherit;
1254}
1255
1256.page-pill.active .page-pill-count {
1257  background: rgba(100, 160, 240, 0.18);
1258}
1259
1260@media (max-width: 767px) {
1261  .page-ribbon {
1262    padding: 14px 0 4px;
1263  }
1264
1265  .page-pill {
1266    padding: 7px 14px;
1267    font-size: 0.82rem;
1268    background: var(--vp-c-bg-elv, var(--vp-c-bg-soft));
1269    border-color: var(--vp-c-divider);
1270    color: var(--vp-c-text-1);
1271  }
1272}
1273
1274.local-search-icon {
1275  display: block;
1276  font-size: 18px;
1277}
1278
1279.navigate-icon {
1280  display: block;
1281  font-size: 14px;
1282}
1283
1284.search-icon {
1285  margin: 8px;
1286}
1287
1288@media (max-width: 767px) {
1289  .search-icon {
1290    display: none;
1291  }
1292}
1293
1294.search-input {
1295  padding: 6px 12px;
1296  font-size: inherit;
1297  width: 100%;
1298}
1299
1300.search-input::-webkit-search-cancel-button {
1301  display: none;
1302}
1303
1304@media (max-width: 767px) {
1305  .search-input {
1306    padding: 6px 4px;
1307  }
1308}
1309
1310.search-actions {
1311  display: flex;
1312  gap: 4px;
1313}
1314
1315@media (any-pointer: coarse) {
1316  .search-actions {
1317    gap: 8px;
1318  }
1319}
1320
1321@media (min-width: 769px) {
1322  .search-actions.before {
1323    display: none;
1324  }
1325}
1326
1327.search-actions button {
1328  padding: 8px;
1329}
1330
1331.search-actions button:not([disabled]):hover,
1332.toggle-layout-button.detailed-list {
1333  color: var(--vp-c-brand-1);
1334}
1335
1336.search-actions button.clear-button:disabled {
1337  opacity: 0.37;
1338}
1339
1340.search-keyboard-shortcuts {
1341  font-size: 0.8rem;
1342  opacity: 75%;
1343  display: flex;
1344  flex-wrap: wrap;
1345  gap: 16px;
1346  line-height: 14px;
1347}
1348
1349.search-keyboard-shortcuts span {
1350  display: flex;
1351  align-items: center;
1352  gap: 4px;
1353}
1354
1355@media (max-width: 767px) {
1356  .search-keyboard-shortcuts {
1357    display: none;
1358  }
1359}
1360
1361.search-keyboard-shortcuts kbd {
1362  background: rgba(128, 128, 128, 0.1);
1363  border-radius: 4px;
1364  padding: 3px 6px;
1365  min-width: 24px;
1366  display: inline-block;
1367  text-align: center;
1368  vertical-align: middle;
1369  border: 1px solid rgba(128, 128, 128, 0.15);
1370  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
1371}
1372
1373.results {
1374  display: flex;
1375  flex-direction: column;
1376  gap: 6px;
1377  overflow-x: hidden;
1378  overflow-y: auto;
1379  overscroll-behavior: contain;
1380}
1381
1382.result {
1383  display: flex;
1384  align-items: center;
1385  gap: 8px;
1386  border-radius: 4px;
1387  transition: none;
1388  line-height: 1rem;
1389  border: solid 2px var(--vp-local-search-result-border);
1390  outline: none;
1391}
1392
1393.result > div {
1394  margin: 12px;
1395  width: 100%;
1396  overflow: hidden;
1397}
1398
1399@media (max-width: 767px) {
1400  .result > div {
1401    margin: 8px;
1402  }
1403}
1404
1405.titles {
1406  display: flex;
1407  flex-wrap: wrap;
1408  gap: 4px;
1409  position: relative;
1410  z-index: 1001;
1411  padding: 2px 0;
1412}
1413
1414.title {
1415  display: flex;
1416  align-items: center;
1417  gap: 4px;
1418}
1419
1420.title.main {
1421  font-weight: 500;
1422}
1423
1424.title-icon {
1425  opacity: 1;
1426  font-weight: 500;
1427}
1428
1429.title svg {
1430  opacity: 0.5;
1431}
1432
1433.result.selected {
1434  --vp-local-search-result-bg: var(--vp-local-search-result-selected-bg);
1435  border-color: var(--vp-local-search-result-selected-border);
1436}
1437
1438.excerpt-wrapper {
1439  position: relative;
1440}
1441
1442.excerpt {
1443  opacity: 50%;
1444  pointer-events: none;
1445  height: 84px;
1446  max-height: 84px;
1447  overflow: hidden;
1448  position: relative;
1449  margin-top: 4px;
1450}
1451
1452.result.selected .excerpt {
1453  opacity: 1;
1454}
1455
1456.excerpt :deep(*) {
1457  font-size: 0.8rem !important;
1458  line-height: 130% !important;
1459}
1460
1461.titles :deep(mark),
1462.excerpt :deep(mark) {
1463  background-color: var(--vp-local-search-highlight-bg);
1464  color: var(--vp-local-search-highlight-text);
1465  border-radius: 2px;
1466  padding: 0 2px;
1467}
1468
1469.excerpt :deep(.vp-code-group) .tabs {
1470  display: none;
1471}
1472
1473.excerpt :deep(.vp-code-group) div[class*="language-"] {
1474  border-radius: 8px !important;
1475}
1476
1477.excerpt > .vp-doc > *:first-child {
1478  margin-top: 6px !important;
1479}
1480
1481.excerpt-gradient-bottom {
1482  position: absolute;
1483  bottom: -1px;
1484  left: 0;
1485  width: 100%;
1486  height: 8px;
1487  background: linear-gradient(transparent, var(--vp-local-search-result-bg));
1488  z-index: 1000;
1489}
1490
1491.excerpt-gradient-top {
1492  position: absolute;
1493  top: -1px;
1494  left: 0;
1495  width: 100%;
1496  height: 8px;
1497  background: linear-gradient(var(--vp-local-search-result-bg), transparent);
1498  z-index: 1000;
1499}
1500
1501.result.selected .titles,
1502.result.selected .title-icon {
1503  color: var(--vp-c-brand-1) !important;
1504}
1505
1506.no-results {
1507  font-size: 0.9rem;
1508  text-align: center;
1509  padding: 12px;
1510}
1511
1512svg {
1513  flex: none;
1514}
1515
1516.exact-match-button.exact-match-active {
1517  color: var(--vp-c-brand-1);
1518  background-color: rgba(var(--vp-c-brand-1), 0.1);
1519  border-radius: 4px;
1520}
1521</style>