/
Docsearch.ts
120 lines (107 loc) · 2.95 KB
/
Docsearch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import { usePageLang, useRouteLocale } from '@vuepress/client'
import {
computed,
defineComponent,
h,
onMounted,
type PropType,
ref,
watch,
} from 'vue'
import type { DocsearchOptions } from '../../shared/index.js'
import {
useDocsearchHotkeyListener,
useDocsearchShim,
} from '../composables/index.js'
import {
getFacetFilters,
getSearchButtonTemplate,
pollToOpenDocsearch,
preconnectToAlgolia,
} from '../utils/index.js'
declare const __DOCSEARCH_INJECT_STYLES__: boolean
declare const __DOCSEARCH_OPTIONS__: DocsearchOptions
const optionsDefault = __DOCSEARCH_OPTIONS__
if (__DOCSEARCH_INJECT_STYLES__) {
import('@docsearch/css')
import('../styles/docsearch.css')
}
export const Docsearch = defineComponent({
name: 'Docsearch',
props: {
containerId: {
type: String,
required: false,
default: 'docsearch-container',
},
options: {
type: Object as PropType<DocsearchOptions>,
required: false,
default: () => optionsDefault,
},
},
setup(props) {
const docsearchShim = useDocsearchShim()
const lang = usePageLang()
const routeLocale = useRouteLocale()
const hasInitialized = ref(false)
const hasTriggered = ref(false)
// resolve docsearch options for current locale
const options = computed(() => ({
...props.options,
...props.options.locales?.[routeLocale.value],
}))
/**
* Import docsearch js and initialize
*/
const initialize = async (): Promise<void> => {
const { default: docsearch } = await import('@docsearch/js')
// @ts-expect-error: https://github.com/microsoft/TypeScript/issues/50690
docsearch({
...docsearchShim,
...options.value,
container: `#${props.containerId}`,
searchParameters: {
...options.value.searchParameters,
facetFilters: getFacetFilters(
options.value.searchParameters?.facetFilters,
lang.value
),
},
})
// mark as initialized
hasInitialized.value = true
}
/**
* Trigger docsearch initialization and open it
*/
const trigger = (): void => {
if (hasTriggered.value || hasInitialized.value) return
// mark as triggered
hasTriggered.value = true
// initialize and open
initialize()
pollToOpenDocsearch()
// re-initialize when route locale changes
watch(routeLocale, initialize)
}
// trigger when hotkey is pressed
useDocsearchHotkeyListener(trigger)
// preconnect to algolia
onMounted(() => preconnectToAlgolia(options.value.appId))
return () => [
h('div', {
id: props.containerId,
style: { display: hasInitialized.value ? 'block' : 'none' },
}),
hasInitialized.value
? null
: h('div', {
onClick: trigger,
innerHTML: getSearchButtonTemplate(
options.value.translations?.button
),
}),
]
},
})