-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathContentSearch.vue
More file actions
366 lines (318 loc) · 11.5 KB
/
Copy pathContentSearch.vue
File metadata and controls
366 lines (318 loc) · 11.5 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
<!-- eslint-disable vue/block-tag-newline -->
<script lang="ts">
import type { VNode } from 'vue'
import type { ContentNavigationItem } from '@nuxt/content'
import type { AppConfig } from '@nuxt/schema'
import type { UseFuseOptions } from '@vueuse/integrations/useFuse'
import theme from '#build/ui/content/content-search'
import type { ButtonProps, LinkProps, ModalProps, CommandPaletteProps, CommandPaletteSlots, CommandPaletteGroup, CommandPaletteItem, IconProps, LinkPropsKeys } from '../../types'
import type { ComponentConfig } from '../../types/tv'
type ContentSearch = ComponentConfig<typeof theme, AppConfig, 'contentSearch'>
export interface ContentSearchLink extends Omit<LinkProps, 'custom'> {
label?: string
description?: string
/**
* @IconifyIcon
*/
icon?: IconProps['name']
children?: ContentSearchLink[]
}
export interface ContentSearchFile {
id: string
title: string
titles: string[]
level: number
content: string
}
export interface ContentSearchResult extends ContentSearchFile {
snippets?: {
title?: string
content?: string
}
}
export interface ContentSearchOptions {
limit?: number
snippet?: {
columns?: ('title' | 'content')[]
around?: number
}
}
export type ContentSearchStatus = 'idle' | 'loading' | 'ready' | 'error'
export type ContentSearchFn = (query: string, opts?: ContentSearchOptions) => Promise<ContentSearchResult[]>
export interface ContentSearchItem extends Omit<LinkProps, 'custom'>, CommandPaletteItem {
level?: number
/**
* @IconifyIcon
*/
icon?: IconProps['name']
}
export interface ContentSearchProps<T extends ContentSearchLink = ContentSearchLink> extends Pick<ModalProps, 'title' | 'description' | 'overlay' | 'transition' | 'content' | 'dismissible' | 'fullscreen' | 'modal' | 'portal' | 'unmountOnHide'>, Pick<CommandPaletteProps<CommandPaletteGroup<ContentSearchItem>, ContentSearchItem>, 'icon' | 'trailingIcon' | 'selectedIcon' | 'childrenIcon' | 'placeholder' | 'autofocus' | 'loading' | 'loadingIcon' | 'closeIcon' | 'back' | 'backIcon' | 'disabled' | 'highlightOnHover' | 'labelKey' | 'descriptionKey' | 'preserveGroupOrder' | 'virtualize' | 'groups'> {
/**
* @defaultValue 'md'
*/
size?: ContentSearch['variants']['size']
/**
* Display a close button in the input (useful when inside a Modal for example).
* `{ size: 'md', color: 'neutral', variant: 'ghost' }`{lang="ts-type"}
* @emits 'update:open'
* @defaultValue true
*/
close?: boolean | Omit<ButtonProps, LinkPropsKeys>
/**
* Keyboard shortcut to open the search (used by [`defineShortcuts`](https://ui.nuxt.com/docs/composables/define-shortcuts))
* @defaultValue 'meta_k'
*/
shortcut?: string
/** Links group displayed as the first group in the command palette. */
links?: T[]
navigation?: ContentNavigationItem[]
files?: ContentSearchFile[]
/**
* Options for [useFuse](https://vueuse.org/integrations/useFuse) passed to the [CommandPalette](https://ui.nuxt.com/docs/components/command-palette).
* @defaultValue {
fuseOptions: {
ignoreLocation: true,
includeMatches: true,
useTokenSearch: true,
threshold: 0.1,
keys: ['label', 'description', 'suffix']
},
resultLimit: 12,
matchAllWhenSearchEmpty: true
}
*/
fuse?: UseFuseOptions<T>
/**
* Async search function (e.g. from [`useSearchCollection`](https://content.nuxt.com/docs/utils/use-search-collection)).
* When provided, ContentSearch calls it on each keystroke and uses the results instead of Fuse.
* Results are mapped, sanitized, and grouped by navigation internally.
*/
search?: ContentSearchFn
/**
* Status of the async search index (e.g. from `useSearchCollection`).
* When the status transitions to `'ready'`, the search is automatically re-triggered if there's a pending term.
*/
searchStatus?: ContentSearchStatus
/**
* Delay (in milliseconds) before the search is triggered (debounced).
* Keeps the input responsive by only running the search after typing settles.
* Set to `0` to disable.
* @defaultValue 100
*/
searchDelay?: number
/**
* When `true`, the theme command will be added to the groups.
* @defaultValue true
*/
colorMode?: boolean
class?: any
ui?: ContentSearch['slots'] & CommandPaletteProps<CommandPaletteGroup<ContentSearchItem>, ContentSearchItem>['ui']
}
export type ContentSearchSlots = CommandPaletteSlots<ContentSearchItem> & {
content?(props: { close: () => void }): VNode[]
}
</script>
<script setup lang="ts" generic="T extends ContentSearchLink">
import { computed, shallowRef, useTemplateRef, watch } from 'vue'
import { defu } from 'defu'
import { reactivePick, refDebounced } from '@vueuse/core'
import { useAppConfig, useColorMode, defineShortcuts } from '#imports'
import { useComponentProps } from '../../composables/useComponentProps'
import { useForwardProps } from '../../composables/useForwardProps'
import { useContentSearch } from '../../composables/useContentSearch'
import { useLocale } from '../../composables/useLocale'
import { omit, transformUI } from '../../utils'
import { tv } from '../../utils/tv'
import UModal from '../Modal.vue'
import UCommandPalette from '../CommandPalette.vue'
const _props = withDefaults(defineProps<ContentSearchProps<T>>(), {
shortcut: 'meta_k',
colorMode: true,
close: true,
fullscreen: false,
searchDelay: 100
})
const slots = defineSlots<ContentSearchSlots>()
const props = useComponentProps<ContentSearchProps<T>>('contentSearch', _props)
const searchTerm = defineModel<string>('searchTerm', { default: '' })
const { t } = useLocale()
const { open, mapNavigationItems, mapLinks, mapSearchResults, postFilter } = useContentSearch()
// eslint-disable-next-line vue/no-dupe-keys
const colorMode = useColorMode()
const appConfig = useAppConfig() as ContentSearch['AppConfig']
const commandPaletteProps = useForwardProps(reactivePick(props, 'size', 'icon', 'trailingIcon', 'selectedIcon', 'childrenIcon', 'placeholder', 'autofocus', 'loading', 'loadingIcon', 'close', 'closeIcon', 'back', 'backIcon', 'disabled', 'highlightOnHover', 'labelKey', 'descriptionKey', 'preserveGroupOrder', 'virtualize', 'searchDelay'))
const modalProps = useForwardProps(reactivePick(props, 'overlay', 'transition', 'content', 'dismissible', 'fullscreen', 'modal', 'portal', 'unmountOnHide'))
const getProxySlots = () => omit(slots, ['content'])
// eslint-disable-next-line vue/no-dupe-keys
const fuse = computed(() => defu({}, props.fuse, {
fuseOptions: {
includeMatches: true,
useTokenSearch: true
},
resultLimit: 12
} as UseFuseOptions<T>))
// eslint-disable-next-line vue/no-dupe-keys
const ui = computed(() => tv({ extend: tv(theme), ...(appConfig.ui?.contentSearch || {}) })({
size: props.size,
fullscreen: props.fullscreen
}))
const commandPaletteRef = useTemplateRef('commandPaletteRef')
const debouncedSearchTerm = refDebounced(searchTerm, () => props.searchDelay!)
const rawSearchResults = shallowRef<ContentSearchResult[]>([])
const searchResults = computed(() => mapSearchResults(rawSearchResults.value, props.navigation))
let searchRequestId = 0
async function runSearch(term: string) {
// Always bump the request id, even on the early-return path — otherwise an
// in-flight prior request could resolve after we clear results and overwrite
// them again (e.g. user types "foo" then backspaces before "foo" settles).
const requestId = ++searchRequestId
if (!props.search || !term) {
rawSearchResults.value = []
return
}
try {
const results = await props.search(term, {
limit: (fuse.value as UseFuseOptions<T>).resultLimit,
snippet: { columns: ['title', 'content'], around: 20 }
})
// Discard stale responses: a newer request started before this one resolved.
if (requestId !== searchRequestId) return
rawSearchResults.value = results
} catch (err) {
if (requestId !== searchRequestId) return
console.error('[ContentSearch] search failed:', err)
rawSearchResults.value = []
}
}
watch(debouncedSearchTerm, runSearch)
watch(() => props.search, () => {
if (debouncedSearchTerm.value) {
runSearch(debouncedSearchTerm.value)
}
})
watch(() => props.searchStatus, (status) => {
if (status === 'ready' && debouncedSearchTerm.value) {
runSearch(debouncedSearchTerm.value)
}
})
const linksGroup = computed(() => {
if (!props.links?.length) {
return null
}
return { id: 'links', label: t('contentSearch.links'), items: mapLinks(props.links) }
})
const searchGroups = computed(() => {
if (!searchTerm.value || !searchResults.value.length) return []
return [{ id: 'search', label: t('contentSearch.search'), items: searchResults.value, ignoreFilter: true }]
})
const navigationGroups = computed(() => {
if (!props.navigation?.length) {
return []
}
if (props.navigation.some(link => !!link.children?.length)) {
return props.navigation.map(group => ({
id: group.path,
label: group.title,
items: mapNavigationItems(group.children || [], props.files || []),
postFilter
}))
} else {
return [{ id: 'docs', items: mapNavigationItems(props.navigation, props.files || []), postFilter }]
}
})
const themeGroup = computed(() => {
if (!props.colorMode || colorMode?.forced) {
return null
}
return {
id: 'theme',
label: t('contentSearch.theme'),
items: [{
label: t('colorMode.system'),
icon: appConfig.ui.icons.system,
active: colorMode.preference === 'system',
onSelect: () => {
colorMode.preference = 'system'
}
}, {
label: t('colorMode.light'),
icon: appConfig.ui.icons.light,
active: colorMode.preference === 'light',
onSelect: () => {
colorMode.preference = 'light'
}
}, {
label: t('colorMode.dark'),
icon: appConfig.ui.icons.dark,
active: colorMode.preference === 'dark',
onSelect: () => {
colorMode.preference = 'dark'
}
}]
}
})
const groups = computed(() => {
const groups = []
if (linksGroup.value) {
groups.push(linksGroup.value)
}
if (props.search) {
groups.push(...searchGroups.value)
} else {
groups.push(...navigationGroups.value)
}
groups.push(...(props.groups || []))
if (themeGroup.value) {
groups.push(themeGroup.value)
}
return groups
})
function onSelect(item: ContentSearchItem) {
if (item.disabled) {
return
}
// Close modal on select
open.value = false
// Reset search term on select
searchTerm.value = ''
}
defineShortcuts({
[props.shortcut!]: {
usingInput: true,
handler: () => open.value = !open.value
}
})
defineExpose({
commandPaletteRef
})
</script>
<template>
<UModal
v-model:open="open"
:title="props.title || t('contentSearch.title')"
:description="props.description || t('contentSearch.description')"
v-bind="modalProps"
data-slot="modal"
:class="ui.modal({ class: [props.ui?.modal, props.class] })"
>
<template #content="contentData">
<slot name="content" v-bind="contentData">
<UCommandPalette
ref="commandPaletteRef"
v-model:search-term="searchTerm"
v-bind="commandPaletteProps"
:groups="groups"
:fuse="fuse"
:input="{ fixed: true }"
:ui="transformUI(omit(ui, ['modal']), props.ui)"
@update:model-value="onSelect"
@update:open="open = $event"
>
<template v-for="(_, name) in getProxySlots()" #[name]="slotData">
<slot :name="name" v-bind="slotData" />
</template>
</UCommandPalette>
</slot>
</template>
</UModal>
</template>