docs/.vitepress/theme/components/Search.vue
1235 lines · 30832 bytes
1<script lang="ts" setup>
2import MiniSearch, { type SearchResult } from 'minisearch'
3import { 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 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'
50
51export interface FooterTranslations {
52 selectText?: string
53 selectKeyAriaLabel?: string
54 navigateText?: string
55 navigateUpKeyAriaLabel?: string
56 navigateDownKeyAriaLabel?: string
57 closeText?: string
58 closeKeyAriaLabel?: string
59}
60
61export interface ModalTranslations {
62 displayDetails?: string
63 resetButtonTitle?: string
64 backButtonTitle?: string
65 noResultsText?: string
66 footer?: FooterTranslations
67}
68
69const showSearch = defineModel<boolean>()
70
71const el = shallowRef<HTMLElement>()
72const resultsEl = shallowRef<HTMLElement>()
73
74/* Search */
75const searchIndexData = shallowRef(localSearchIndex)
76
77// @ts-ignore
78if (import.meta.hot) {
79 // @ts-ignore
80 import.meta.hot.accept('@localSearchIndex', (m) => {
81 if (m) {
82 searchIndexData.value = m.default
83 }
84 })
85}
86
87interface Result {
88 title: string
89 titles: string[]
90 text?: string
91}
92
93const vitePressData = useData()
94const { activate } = useFocusTrap(el, {
95 immediate: true,
96 allowOutsideClick: true,
97 clickOutsideDeactivates: true,
98 escapeDeactivates: true,
99 returnFocusOnDeactivate: false,
100 initialFocus: () => {
101 return searchInput.value
102 }
103})
104const { localeIndex, theme } = vitePressData
105const searchIndex = computedAsync(async () =>
106 markRaw(
107 MiniSearch.loadJSON<Result>(
108 (await searchIndexData.value[localeIndex.value]?.())?.default,
109 {
110 fields: ['title', 'titles', 'text'],
111 storeFields: ['title', 'titles'],
112 searchOptions: {
113 // Conditional fuzzy search based on matchExact value
114 fuzzy: matchExact.value ? false : 0.07,
115 // Conditional prefix search based on matchExact value
116 prefix: matchExact.value ? false : (term) => term.length > 3,
117 // Disable max fuzzy if match exact is enabled
118 maxFuzzy: matchExact.value ? 0 : 1,
119 boost: { title: 4, text: 2, titles: 1 },
120 ...(theme.value.search?.provider === 'local' &&
121 theme.value.search.options?.miniSearch?.searchOptions)
122 },
123 ...(theme.value.search?.provider === 'local' &&
124 theme.value.search.options?.miniSearch?.options)
125 }
126 )
127 )
128)
129
130const disableQueryPersistence = computed(() => {
131 return (
132 theme.value.search?.provider === 'local' &&
133 theme.value.search.options?.disableQueryPersistence === true
134 )
135})
136
137const filterText = disableQueryPersistence.value
138 ? ref('')
139 : useSessionStorage('vitepress:local-search-filter', '')
140
141const showDetailedList = useLocalStorage(
142 'vitepress:local-search-detailed-list',
143 theme.value.search?.provider === 'local' &&
144 theme.value.search.options?.detailedView === true
145)
146
147const matchExact = useLocalStorage(
148 'vitepress:local-search-match-exact',
149 false // disabled by default
150)
151
152const disableDetailedView = computed(() => {
153 return (
154 theme.value.search?.provider === 'local' &&
155 theme.value.search.options?.detailedView === false
156 )
157})
158
159const buttonText = computed(() => {
160 const options = theme.value.search?.options
161
162 return (
163 options?.locales?.[localeIndex.value]?.translations?.button?.buttonText ||
164 options?.translations?.button?.buttonText ||
165 'Search'
166 )
167})
168
169watchEffect(() => {
170 if (disableDetailedView.value) {
171 showDetailedList.value = false
172 }
173})
174
175const results: Ref<(SearchResult & Result)[]> = shallowRef([])
176
177const enableNoResults = ref(false)
178
179watch(filterText, () => {
180 enableNoResults.value = false
181})
182
183const mark = computedAsync(async () => {
184 if (!resultsEl.value) return
185 return markRaw(new Mark(resultsEl.value))
186}, null)
187
188const cache = new LRUCache<string, Map<string, string>>(16) // 16 files
189
190watchDebounced(
191 () => [searchIndex.value, filterText.value, showDetailedList.value] as const,
192 async ([index, filterTextValue, showDetailedListValue], old, onCleanup) => {
193 if (old?.[0] !== index) {
194 // in case of hmr
195 cache.clear()
196 }
197
198 let canceled = false
199 onCleanup(() => {
200 canceled = true
201 })
202
203 if (!index) return
204
205 // Search
206 const isUrlQuery = looksLikeUrl(filterTextValue)
207 const queryForSearch = isUrlQuery
208 ? normalizeUrlQuery(filterTextValue)
209 : filterTextValue
210 const _result = index
211 .search(
212 queryForSearch,
213 isUrlQuery ? { combineWith: 'OR' } : undefined
214 )
215 .slice(0, 16) as (SearchResult & Result)[]
216 enableNoResults.value = true
217
218 if (!_result) {
219 results.value = []
220 return
221 }
222
223 // Highlighting
224 const mods = showDetailedListValue
225 ? await Promise.all(_result.map((r) => fetchExcerpt(r.id)))
226 : []
227 if (canceled) return
228 for (const { id, mod } of mods) {
229 const mapId = id.slice(0, id.indexOf('#'))
230 const cacheId = `${mapId}\n${filterTextValue}`
231 let map = cache.get(cacheId)
232 if (map) continue
233 map = new Map()
234 cache.set(cacheId, map)
235 const comp = mod.default ?? mod
236 if (comp?.render || comp?.setup) {
237 const app = createApp(comp)
238 // Silence warnings about missing components
239 app.config.warnHandler = () => {}
240 enhanceAppWithTabs(app)
241 app.provide(dataSymbol, vitePressData)
242 Object.defineProperties(app.config.globalProperties, {
243 $frontmatter: {
244 get() {
245 return vitePressData.frontmatter.value
246 }
247 },
248 $params: {
249 get() {
250 return vitePressData.page.value.params
251 }
252 }
253 })
254 const div = document.createElement('div')
255 app.mount(div)
256 await selectExcerptTabs(div, filterTextValue)
257 const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6')
258 headings.forEach((el) => {
259 const href = el.querySelector('a')?.getAttribute('href')
260 const anchor = href?.startsWith('#') && href.slice(1)
261 if (!anchor) return
262 let html = ''
263 while (
264 (el = el.nextElementSibling!) &&
265 !/^h[1-6]$/i.test(el.tagName)
266 ) {
267 html += el.outerHTML
268 }
269 map!.set(anchor, html)
270 })
271 app.unmount()
272 }
273 if (canceled) return
274 }
275
276 const terms = new Set<string>()
277
278 results.value = _result.map((r) => {
279 const [id, anchor] = r.id.split('#')
280 const map = cache.get(`${id}\n${filterTextValue}`)
281 const text = map?.get(anchor) ?? ''
282 for (const term in r.match) {
283 terms.add(term)
284 }
285 return { ...r, text }
286 })
287
288 await nextTick()
289 if (canceled) return
290
291 await new Promise((r) => {
292 mark.value?.unmark({
293 done: () => {
294 mark.value?.markRegExp(formMarkRegex(terms), { done: r })
295 }
296 })
297 })
298
299 const excerpts = el.value?.querySelectorAll('.result .excerpt') ?? []
300 const scrollMutations: { element: HTMLElement; scrollTop: number }[] = []
301 for (let i = 0; i < excerpts.length; i++) {
302 const excerptElement = excerpts[i] as HTMLElement
303
304 const markNode = excerptElement.querySelector(
305 'mark[data-markjs="true"]'
306 ) as HTMLElement | null
307 if (markNode) {
308 const markRect = markNode.getBoundingClientRect()
309 const excerptRect = excerptElement.getBoundingClientRect()
310
311 const relativeTop = (markRect.top - excerptRect.top) +
312 excerptElement.scrollTop
313 const targetScrollTop = relativeTop -
314 (excerptElement.clientHeight / 2) + (markRect.height / 2)
315
316 scrollMutations.push({
317 element: excerptElement,
318 scrollTop: targetScrollTop
319 })
320 }
321 }
322 for (let i = 0; i < scrollMutations.length; i++) {
323 scrollMutations[i].element.scrollTop = scrollMutations[i].scrollTop
324 }
325 if (resultsEl.value) {
326 resultsEl.value.scrollTop = 0
327 }
328 },
329 { debounce: 180, immediate: true }
330)
331
332const excerptCache = new LRUCache<string, unknown>(60) // 60 excerpts
333
334async function fetchExcerpt(id: string) {
335 const cache = excerptCache.get(id)
336 if (cache) return { id, mod: cache }
337
338 const file = pathToFile(id.slice(0, id.indexOf('#')))
339 try {
340 if (!file) throw new Error(`Cannot find file for id: ${id}`)
341 const mod = await import(/*@vite-ignore*/ file)
342
343 excerptCache.set(id, mod)
344
345 return { id, mod }
346 } catch (e) {
347 console.error(e)
348 return { id, mod: {} }
349 }
350}
351
352const nextFrame = () =>
353 new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
354
355const getSearchTerms = (query: string) =>
356 query
357 .toLowerCase()
358 .split(/\s+/)
359 .map((term) => term.trim())
360 .filter(Boolean)
361
362async function selectExcerptTabs(root: HTMLElement, query: string) {
363 const terms = getSearchTerms(query)
364 if (!terms.length) return
365
366 const tabs = root.querySelectorAll<HTMLElement>('.plugin-tabs')
367
368 for (let i = 0; i < tabs.length; i++) {
369 const tab = tabs[i]
370 const selectedTab = tab.querySelector<HTMLButtonElement>(
371 '.plugin-tabs--tab[aria-selected="true"]'
372 )
373 const buttons = tab.querySelectorAll<HTMLButtonElement>(
374 '.plugin-tabs--tab[role="tab"]'
375 )
376
377 let found = false
378
379 for (let j = 0; j < buttons.length; j++) {
380 const button = buttons[j]
381 button.click()
382 await nextTick()
383 await nextFrame()
384
385 const panelId = button.getAttribute('aria-controls')
386 const panel = panelId
387 ? root.querySelector<HTMLElement>(`#${CSS.escape(panelId)}`)
388 : tab.querySelector<HTMLElement>('.plugin-tabs--content')
389 const text = panel?.textContent?.toLowerCase() ?? ''
390
391 if (terms.every((term) => text.includes(term))) {
392 found = true
393 break
394 }
395 }
396
397 if (!found) {
398 selectedTab?.click()
399 await nextTick()
400 }
401 }
402}
403
404/* Search input focus */
405
406const searchInput = ref<HTMLInputElement>()
407const disableReset = computed(() => {
408 return filterText.value?.length <= 0
409})
410function focusSearchInput(select = true) {
411 searchInput.value?.focus()
412 select && searchInput.value?.select()
413}
414
415onMounted(() => {
416 focusSearchInput()
417})
418
419function onSearchBarClick(event: PointerEvent) {
420 if (event.pointerType === 'mouse') {
421 focusSearchInput()
422 }
423}
424
425/* Search keyboard selection */
426
427const selectedIndex = ref(-1)
428const disableMouseOver = ref(true)
429
430watch(results, (r) => {
431 selectedIndex.value = r.length ? 0 : -1
432 scrollToSelectedResult()
433})
434
435function scrollToSelectedResult() {
436 nextTick(() => {
437 const selectedEl = document.querySelector('.result.selected')
438 selectedEl?.scrollIntoView({ block: 'nearest' })
439 })
440}
441
442onKeyStroke('ArrowUp', (event) => {
443 event.preventDefault()
444 selectedIndex.value--
445 if (selectedIndex.value < 0) {
446 selectedIndex.value = results.value.length - 1
447 }
448 disableMouseOver.value = true
449 scrollToSelectedResult()
450})
451
452onKeyStroke('ArrowDown', (event) => {
453 event.preventDefault()
454 selectedIndex.value++
455 if (selectedIndex.value >= results.value.length + 1) {
456 selectedIndex.value = 0
457 }
458 disableMouseOver.value = true
459 scrollToSelectedResult()
460})
461
462const router = useRouter()
463
464onKeyStroke('Enter', (e) => {
465 if (e.isComposing) return
466
467 if (e.target instanceof HTMLButtonElement && e.target.type !== 'submit') {
468 return
469 }
470
471 const index = selectedIndex.value - 1
472
473 if (index === -1) {
474 // @ts-ignore
475 window.toggleAI({ value: filterText.value })
476 showSearch.value = false
477 return
478 }
479
480 const selectedPackage = results.value[index]
481 if (e.target instanceof HTMLInputElement && !selectedPackage) {
482 e.preventDefault()
483 return
484 }
485
486 if (selectedPackage) {
487 window.dispatchEvent(
488 new CustomEvent('search-nav', {
489 detail: { query: filterText.value }
490 })
491 )
492 router.go(selectedPackage.id)
493 showSearch.value = false
494 }
495})
496
497function onResultClick() {
498 window.dispatchEvent(
499 new CustomEvent('search-nav', {
500 detail: { query: filterText.value }
501 })
502 )
503 showSearch.value = false
504}
505
506onKeyStroke('Escape', () => {
507 showSearch.value = false
508})
509
510// Translations
511const defaultTranslations = {
512 modal: {
513 displayDetails: 'Display detailed list',
514 exactMatchTitle: 'Match exact phrases',
515 resetButtonTitle: 'Reset search',
516 backButtonTitle: 'Close search',
517 noResultsText: 'No results for',
518 footer: {
519 selectText: 'to select',
520 selectKeyAriaLabel: 'enter',
521 navigateText: 'to navigate',
522 navigateUpKeyAriaLabel: 'up arrow',
523 navigateDownKeyAriaLabel: 'down arrow',
524 closeText: 'to close',
525 closeKeyAriaLabel: 'escape'
526 }
527 }
528}
529
530const translate = createSearchTranslate(defaultTranslations)
531
532// Back
533
534onMounted(() => {
535 // Prevents going to previous site
536 window.history.pushState(null, '', null)
537})
538
539useEventListener('popstate', (event) => {
540 event.preventDefault()
541 showSearch.value = false
542})
543
544/** Lock body */
545const isLocked = useScrollLock(inBrowser ? document.body : null)
546
547watch(
548 () => showSearch.value,
549 (val) => {
550 if (!val) {
551 isLocked.value = false
552 return
553 }
554
555 nextTick(() => {
556 isLocked.value = true
557 nextTick().then(() => activate())
558 })
559 }
560)
561
562function looksLikeUrl(query: string) {
563 return /https?:\/\/|www\.|[^\s]+\.[a-z]{2,}(\/|$)/i.test(query.trim())
564}
565
566function normalizeUrlQuery(query: string) {
567 const cleaned = query
568 .trim()
569 .replace(/^https?:\/\//i, '')
570 .replace(/^www\./i, '')
571 .replace(/[?#].*$/, '')
572 .replace(/\/.*$/, '') // drop path, keep host only
573 const host = cleaned.trim()
574 if (!host) return query.trim()
575 const bareName = host.split('.')[0]
576 return bareName && bareName !== host ? `${host} ${bareName}` : host
577}
578
579function formMarkRegex(terms: Set<string>) {
580 return new RegExp(
581 [...terms]
582 .sort((a, b) => b.length - a.length)
583 .map((term) => `(${escapeRegExp(term)})`)
584 .join('|'),
585 'gi'
586 )
587}
588
589function resetSearch() {
590 filterText.value = ''
591 nextTick().then(() => focusSearchInput(false))
592}
593
594function onMouseMove(e: MouseEvent) {
595 if (!disableMouseOver.value) return
596 const el = (e.target as HTMLElement)?.closest<HTMLAnchorElement>('.result')
597 const index = Number.parseInt(el?.dataset.index!)
598 if (index >= 0 && index !== selectedIndex.value) {
599 selectedIndex.value = index
600 }
601 disableMouseOver.value = false
602}
603</script>
604
605<template>
606 <Teleport to="body">
607 <div
608 ref="el"
609 role="button"
610 :aria-owns="results?.length ? 'localsearch-list' : undefined"
611 aria-expanded="true"
612 aria-haspopup="listbox"
613 aria-labelledby="localsearch-label"
614 class="VPLocalSearchBox"
615 :class="{ 'pointer-events-none': !showSearch }"
616 >
617 <AnimatePresence>
618 <motion.div
619 v-if="showSearch"
620 class="backdrop"
621 @click="showSearch = false"
622 :initial="{
623 opacity: 0
624 }"
625 :animate="{
626 opacity: 1
627 }"
628 :exit="{
629 opacity: 0
630 }"
631 :transition="{
632 duration: 0.55,
633 ease: [0.16, 1, 0.3, 1]
634 }"
635 />
636 </AnimatePresence>
637
638 <AnimatePresence>
639 <motion.div
640 v-if="showSearch"
641 layout="size"
642 class="shell"
643 :initial="{
644 opacity: 0,
645 scale: 0.9375
646 }"
647 :animate="{
648 opacity: 1,
649 scale: 1
650 }"
651 :exit="{
652 opacity: 0,
653 scale: 0.9375
654 }"
655 :transition="{
656 duration: 0.55,
657 ease: [0.16, 1, 0.3, 1]
658 }"
659 >
660 <motion.form
661 layout="position"
662 class="search-bar"
663 @pointerup="onSearchBarClick($event)"
664 @submit.prevent=""
665 >
666 <label
667 :title="buttonText"
668 id="localsearch-label"
669 for="localsearch-input"
670 >
671 <span
672 aria-hidden="true"
673 class="vpi-search search-icon local-search-icon"
674 />
675 </label>
676 <div class="search-actions before">
677 <button
678 class="back-button"
679 :title="translate('modal.backButtonTitle')"
680 @click="showSearch = false"
681 >
682 <span class="vpi-arrow-left local-search-icon" />
683 </button>
684 </div>
685 <input
686 ref="searchInput"
687 v-model="filterText"
688 :aria-activedescendant="selectedIndex > -1
689 ? 'localsearch-item-' + selectedIndex
690 : undefined"
691 aria-autocomplete="both"
692 :aria-controls="results?.length ? 'localsearch-list' : undefined"
693 aria-labelledby="localsearch-label"
694 autocapitalize="off"
695 autocomplete="off"
696 autocorrect="off"
697 class="search-input"
698 id="localsearch-input"
699 enterkeyhint="go"
700 maxlength="64"
701 :placeholder="buttonText"
702 spellcheck="false"
703 type="search"
704 />
705 <div class="search-actions">
706 <button
707 v-if="!disableDetailedView"
708 class="toggle-layout-button"
709 type="button"
710 :class="{ 'detailed-list': showDetailedList }"
711 :title="translate('modal.displayDetails')"
712 @click="selectedIndex > -1 &&
713 (showDetailedList = !showDetailedList)"
714 >
715 <TextAlignStart :size="19" stroke-width="1.25" />
716 </button>
717 <button
718 class="exact-match-button"
719 type="button"
720 :class="{ 'exact-match-active': matchExact }"
721 :title="translate('modal.exactMatchTitle')"
722 @click="matchExact = !matchExact"
723 >
724 <Regex :size="19" stroke-width="1.25" />
725 </button>
726 <button
727 class="clear-button"
728 type="reset"
729 :disabled="disableReset"
730 :title="translate('modal.resetButtonTitle')"
731 @click="resetSearch"
732 >
733 <Delete :size="19" stroke-width="1.25" />
734 </button>
735 </div>
736 </motion.form>
737
738 <ul
739 ref="resultsEl"
740 :id="results?.length ? 'localsearch-list' : undefined"
741 :role="results?.length ? 'listbox' : undefined"
742 :aria-labelledby="results?.length ? 'localsearch-label' : undefined"
743 class="results"
744 @mousemove="onMouseMove"
745 >
746 <AnimatePresence>
747 <motion.div
748 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"
749 v-if="!filterText || (filterText && !results.length)"
750 :initial="{
751 opacity: 0
752 }"
753 :animate="{
754 opacity: 1,
755 transition: {
756 delay: 0.1
757 }
758 }"
759 :exit="{
760 opacity: 0,
761 height: 0,
762 transition: {
763 duration: 0.2
764 }
765 }"
766 :transition="{
767 duration: 0.7,
768 ease: [0.16, 1, 0.3, 1]
769 }"
770 >
771 <img
772 class="h-40 object-contain object-center -translate-x-2"
773 src="/asset/smolame.png"
774 alt="Smol ame"
775 />
776 <h1 v-if="filterText && !results.length">
777 Couldn't find anything, try again?
778 </h1>
779 <h1 v-else>Looking for something?</h1>
780 </motion.div>
781 </AnimatePresence>
782
783 <AnimatePresence>
784 <motion.li
785 v-for="(p, index) in results"
786 :key="p.id"
787 layout
788 class="result-layout"
789 :id="'localsearch-item-' + (index + 1)"
790 :aria-selected="selectedIndex === index + 1 ? 'true' : 'false'"
791 role="option"
792 :initial="{
793 opacity: 0,
794 scale: 0.9375
795 }"
796 :animate="{
797 opacity: 1,
798 scale: 1
799 }"
800 :exit="{
801 opacity: 0,
802 scale: 0.9375,
803 height: 0,
804 transition: {
805 duration: 0.25
806 }
807 }"
808 :transition="{
809 duration: 0.55,
810 ease: [0.16, 1, 0.3, 1],
811 delay: index * 0.02
812 }"
813 >
814 <a
815 :href="p.id"
816 class="result"
817 :class="{
818 selected: selectedIndex === index + 1
819 }"
820 :aria-label="[...p.titles, p.title].join(' > ')"
821 @mouseenter="!disableMouseOver &&
822 (selectedIndex = index + 1)"
823 @focusin="selectedIndex = index + 1"
824 @click="onResultClick"
825 :data-index="index + 1"
826 >
827 <div>
828 <div class="titles">
829 <Hash
830 v-if="p.titles.length > 0"
831 stroke-width="1.25"
832 :size="18"
833 />
834 <File v-else stroke-width="1.25" :size="18" />
835
836 <span
837 v-for="(t, index) in p.titles"
838 :key="index"
839 class="title"
840 >
841 <span class="text" v-html="t" />
842 <ArrowRight
843 stroke-width="1.25"
844 :size="18"
845 class="mx-0.5"
846 />
847 </span>
848 <span class="title main">
849 <span class="text" v-html="p.title" />
850 </span>
851 </div>
852
853 <div v-if="showDetailedList" class="excerpt-wrapper">
854 <motion.div
855 v-if="p.text"
856 layout
857 class="excerpt"
858 inert
859 :initial="{
860 height: 0
861 }"
862 :animate="{
863 height: '84px'
864 }"
865 :exit="{
866 height: 0
867 }"
868 :transition="{
869 duration: 0.4,
870 ease: [0.16, 1, 0.3, 1]
871 }"
872 >
873 <div class="vp-doc" v-html="p.text" />
874 </motion.div>
875 <div class="excerpt-gradient-bottom" />
876 <div class="excerpt-gradient-top" />
877 </div>
878 </div>
879 </a>
880 </motion.li>
881 </AnimatePresence>
882 </ul>
883
884 <motion.div layout class="search-keyboard-shortcuts">
885 <span>
886 <kbd
887 :aria-label="translate(
888 'modal.footer.navigateUpKeyAriaLabel'
889 )"
890 >
891 <span class="vpi-arrow-up navigate-icon" />
892 </kbd>
893 <kbd
894 :aria-label="translate(
895 'modal.footer.navigateDownKeyAriaLabel'
896 )"
897 >
898 <span class="vpi-arrow-down navigate-icon" />
899 </kbd>
900 {{ translate('modal.footer.navigateText') }}
901 </span>
902 <span>
903 <kbd :aria-label="translate('modal.footer.selectKeyAriaLabel')">
904 <span class="vpi-corner-down-left navigate-icon" />
905 </kbd>
906 {{ translate('modal.footer.selectText') }}
907 </span>
908 <span>
909 <kbd :aria-label="translate('modal.footer.closeKeyAriaLabel')">
910 esc
911 </kbd>
912 {{ translate('modal.footer.closeText') }}
913 </span>
914 </motion.div>
915 </motion.div>
916 </AnimatePresence>
917
918 <button v-if="!showSearch" />
919 </div>
920 </Teleport>
921</template>
922
923<style scoped>
924.VPLocalSearchBox {
925 position: fixed;
926 z-index: 100;
927 inset: 0;
928 display: flex;
929}
930
931.backdrop {
932 position: absolute;
933 inset: 0;
934 background: var(--vp-backdrop-bg-color);
935 transition: opacity 0.5s;
936 will-change: opacity;
937}
938
939.shell {
940 position: relative;
941 padding: 12px;
942 margin: 64px auto;
943 display: flex;
944 flex-direction: column;
945 gap: 16px;
946 background: var(--vp-local-search-bg);
947 width: min(100vw - 60px, 900px);
948 height: min-content;
949 max-height: min(100vh - 128px, 900px);
950 border-radius: 6px;
951 will-change: transform, opacity, height;
952}
953
954@media (max-width: 767px) {
955 .shell {
956 margin: 0;
957 width: 100vw;
958 height: 100vh;
959 max-height: none;
960 border-radius: 0;
961 }
962}
963
964.search-bar {
965 border: 1px solid var(--vp-c-divider);
966 border-radius: 4px;
967 display: flex;
968 align-items: center;
969 padding: 0 12px;
970 cursor: text;
971 will-change: height;
972}
973
974@media (max-width: 767px) {
975 .search-bar {
976 padding: 0 8px;
977 }
978}
979
980.search-bar:focus-within {
981 border-color: var(--vp-c-brand-1);
982}
983
984.local-search-icon {
985 display: block;
986 font-size: 18px;
987}
988
989.navigate-icon {
990 display: block;
991 font-size: 14px;
992}
993
994.search-icon {
995 margin: 8px;
996}
997
998@media (max-width: 767px) {
999 .search-icon {
1000 display: none;
1001 }
1002}
1003
1004.search-input {
1005 padding: 6px 12px;
1006 font-size: inherit;
1007 width: 100%;
1008}
1009
1010.search-input::-webkit-search-cancel-button {
1011 display: none;
1012}
1013
1014@media (max-width: 767px) {
1015 .search-input {
1016 padding: 6px 4px;
1017 }
1018}
1019
1020.search-actions {
1021 display: flex;
1022 gap: 4px;
1023}
1024
1025@media (any-pointer: coarse) {
1026 .search-actions {
1027 gap: 8px;
1028 }
1029}
1030
1031@media (min-width: 769px) {
1032 .search-actions.before {
1033 display: none;
1034 }
1035}
1036
1037.search-actions button {
1038 padding: 8px;
1039}
1040
1041.search-actions button:not([disabled]):hover,
1042.toggle-layout-button.detailed-list {
1043 color: var(--vp-c-brand-1);
1044}
1045
1046.search-actions button.clear-button:disabled {
1047 opacity: 0.37;
1048}
1049
1050.search-keyboard-shortcuts {
1051 font-size: 0.8rem;
1052 opacity: 75%;
1053 display: flex;
1054 flex-wrap: wrap;
1055 gap: 16px;
1056 line-height: 14px;
1057}
1058
1059.search-keyboard-shortcuts span {
1060 display: flex;
1061 align-items: center;
1062 gap: 4px;
1063}
1064
1065@media (max-width: 767px) {
1066 .search-keyboard-shortcuts {
1067 display: none;
1068 }
1069}
1070
1071.search-keyboard-shortcuts kbd {
1072 background: rgba(128, 128, 128, 0.1);
1073 border-radius: 4px;
1074 padding: 3px 6px;
1075 min-width: 24px;
1076 display: inline-block;
1077 text-align: center;
1078 vertical-align: middle;
1079 border: 1px solid rgba(128, 128, 128, 0.15);
1080 box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
1081}
1082
1083.results {
1084 display: flex;
1085 flex-direction: column;
1086 gap: 6px;
1087 overflow-x: hidden;
1088 overflow-y: auto;
1089 overscroll-behavior: contain;
1090}
1091
1092.result-layout {
1093 will-change: transform, opacity, height;
1094}
1095
1096.result {
1097 display: flex;
1098 align-items: center;
1099 gap: 8px;
1100 border-radius: 4px;
1101 transition: none;
1102 line-height: 1rem;
1103 border: solid 2px var(--vp-local-search-result-border);
1104 outline: none;
1105}
1106
1107.result > div {
1108 margin: 12px;
1109 width: 100%;
1110 overflow: hidden;
1111}
1112
1113@media (max-width: 767px) {
1114 .result > div {
1115 margin: 8px;
1116 }
1117}
1118
1119.titles {
1120 display: flex;
1121 flex-wrap: wrap;
1122 gap: 4px;
1123 position: relative;
1124 z-index: 1001;
1125 padding: 2px 0;
1126}
1127
1128.title {
1129 display: flex;
1130 align-items: center;
1131 gap: 4px;
1132}
1133
1134.title.main {
1135 font-weight: 500;
1136}
1137
1138.title-icon {
1139 opacity: 1;
1140 font-weight: 500;
1141}
1142
1143.title svg {
1144 opacity: 0.5;
1145}
1146
1147.result.selected {
1148 --vp-local-search-result-bg: var(--vp-local-search-result-selected-bg);
1149 border-color: var(--vp-local-search-result-selected-border);
1150}
1151
1152.excerpt-wrapper {
1153 position: relative;
1154}
1155
1156.excerpt {
1157 opacity: 50%;
1158 pointer-events: none;
1159 max-height: 84px;
1160 overflow: hidden;
1161 position: relative;
1162 margin-top: 4px;
1163 will-change: height;
1164}
1165
1166.result.selected .excerpt {
1167 opacity: 1;
1168}
1169
1170.excerpt :deep(*) {
1171 font-size: 0.8rem !important;
1172 line-height: 130% !important;
1173}
1174
1175.titles :deep(mark),
1176.excerpt :deep(mark) {
1177 background-color: var(--vp-local-search-highlight-bg);
1178 color: var(--vp-local-search-highlight-text);
1179 border-radius: 2px;
1180 padding: 0 2px;
1181}
1182
1183.excerpt :deep(.vp-code-group) .tabs {
1184 display: none;
1185}
1186
1187.excerpt :deep(.vp-code-group) div[class*="language-"] {
1188 border-radius: 8px !important;
1189}
1190
1191.excerpt > .vp-doc > *:first-child {
1192 margin-top: 6px !important;
1193}
1194
1195.excerpt-gradient-bottom {
1196 position: absolute;
1197 bottom: -1px;
1198 left: 0;
1199 width: 100%;
1200 height: 8px;
1201 background: linear-gradient(transparent, var(--vp-local-search-result-bg));
1202 z-index: 1000;
1203}
1204
1205.excerpt-gradient-top {
1206 position: absolute;
1207 top: -1px;
1208 left: 0;
1209 width: 100%;
1210 height: 8px;
1211 background: linear-gradient(var(--vp-local-search-result-bg), transparent);
1212 z-index: 1000;
1213}
1214
1215.result.selected .titles,
1216.result.selected .title-icon {
1217 color: var(--vp-c-brand-1) !important;
1218}
1219
1220.no-results {
1221 font-size: 0.9rem;
1222 text-align: center;
1223 padding: 12px;
1224}
1225
1226svg {
1227 flex: none;
1228}
1229
1230.exact-match-button.exact-match-active {
1231 color: var(--vp-c-brand-1);
1232 background-color: rgba(var(--vp-c-brand-1), 0.1);
1233 border-radius: 4px;
1234}
1235</style>