-
Notifications
You must be signed in to change notification settings - Fork 922
/
Docsearch.ts
100 lines (88 loc) · 2.72 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
import { default as docsearch } from '@docsearch/js'
import { usePageLang, useRouteLocale } from '@vuepress/client'
import { isArray } from '@vuepress/shared'
import { computed, defineComponent, h, onMounted, watch } from 'vue'
import type { PropType } from 'vue'
import type { DocsearchOptions } from '../../shared/index.js'
import { useDocsearchShim } from '../composables/index.js'
declare const __DOCSEARCH_INJECT_STYLES__: boolean
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: true,
},
},
setup(props) {
const routeLocale = useRouteLocale()
const lang = usePageLang()
const docsearchShim = useDocsearchShim()
// resolve docsearch props for current locale
const propsLocale = computed(() => ({
...props.options,
...props.options.locales?.[routeLocale.value],
}))
const facetFilters: string[] = []
const initialize = (): void => {
const rawFacetFilters =
propsLocale.value.searchParameters?.facetFilters ?? []
facetFilters.splice(
0,
facetFilters.length,
`lang:${lang.value}`,
...(isArray(rawFacetFilters) ? rawFacetFilters : [rawFacetFilters])
)
// @ts-expect-error: https://github.com/microsoft/TypeScript/issues/50690
docsearch({
...docsearchShim,
...propsLocale.value,
container: `#${props.containerId}`,
searchParameters: {
...propsLocale.value.searchParameters,
facetFilters,
},
})
}
onMounted(() => {
initialize()
// re-initialize if the options is changed
watch(
[routeLocale, propsLocale],
(
[curRouteLocale, curPropsLocale],
[prevRouteLocale, prevPropsLocale]
) => {
if (curRouteLocale === prevRouteLocale) return
if (
JSON.stringify(curPropsLocale) !== JSON.stringify(prevPropsLocale)
) {
initialize()
}
}
)
// modify the facetFilters in place to avoid re-initializing docsearch
// when page lang is changed
watch(lang, (curLang, prevLang) => {
if (curLang !== prevLang) {
const prevIndex = facetFilters.findIndex(
(item) => item === `lang:${prevLang}`
)
if (prevIndex > -1) {
facetFilters.splice(prevIndex, 1, `lang:${curLang}`)
}
}
})
})
return () => h('div', { id: props.containerId })
},
})