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

2f464e5a9a3e01dd35ab1b09ef3bf7b6f40933b7
wotaku/docs/.vitepress/theme/components/Search.vue history · blame · raw

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