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