docs/.vitepress/theme/components/NavBarSearch.vue
88 lines · 1838 bytes
1<script setup lang="ts">
2import { onKeyStroke } from '@vueuse/core'
3import { defineAsyncComponent, onMounted, onUnmounted, ref } from 'vue'
4
5import { AnimatePresence } from 'motion-v'
6import VPNavBarSearchButton from './NavBarSearchButton.vue'
7
8const VPLocalSearchBox = defineAsyncComponent(() => import('./Search.vue'))
9
10onMounted(() => {
11 const handleSearchHotKey = (event: KeyboardEvent) => {
12 if (
13 (event.key?.toLowerCase() === 'k' && (event.metaKey || event.ctrlKey)) ||
14 (!isEditingContent(event) && event.key === '/')
15 ) {
16 event.preventDefault()
17 remove()
18 }
19 }
20
21 const remove = () => {
22 window.removeEventListener('keydown', handleSearchHotKey)
23 }
24
25 window.addEventListener('keydown', handleSearchHotKey)
26
27 onUnmounted(remove)
28})
29
30function isEditingContent(event: KeyboardEvent): boolean {
31 const element = event.target as HTMLElement
32 const tagName = element.tagName
33
34 return (
35 element.isContentEditable ||
36 tagName === 'INPUT' ||
37 tagName === 'SELECT' ||
38 tagName === 'TEXTAREA'
39 )
40}
41
42// Local search
43const showSearch = ref(false)
44
45onKeyStroke('k', (event) => {
46 if (event.ctrlKey || event.metaKey) {
47 event.preventDefault()
48 showSearch.value = true
49 }
50})
51
52onKeyStroke('/', (event) => {
53 if (!isEditingContent(event)) {
54 event.preventDefault()
55 showSearch.value = true
56 }
57})
58</script>
59
60<template>
61 <section class="VPNavBarSearch">
62 <VPLocalSearchBox v-model="showSearch" />
63
64 <div id="local-search">
65 <VPNavBarSearchButton @click="showSearch = true" />
66 </div>
67 </section>
68</template>
69
70<style>
71.VPNavBarSearch {
72 display: flex;
73 align-items: center;
74}
75
76@media (min-width: 768px) {
77 .VPNavBarSearch {
78 flex-grow: 1;
79 padding-left: 24px;
80 }
81}
82
83@media (min-width: 960px) {
84 .VPNavBarSearch {
85 padding-left: 32px;
86 }
87}
88</style>