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

59e2770299344d1d729dd168c1fc261319fe0313
wotaku/docs/.vitepress/theme/components/Search.vue
Duck Revert "meme"59e2770299 5 months ago

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form