-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
/
VCombobox.tsx
438 lines (383 loc) Β· 13.9 KB
/
VCombobox.tsx
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// Styles
import './VCombobox.sass'
// Components
import { makeSelectProps } from '@/components/VSelect/VSelect'
import { VCheckboxBtn } from '@/components/VCheckbox'
import { VChip } from '@/components/VChip'
import { VDefaultsProvider } from '@/components/VDefaultsProvider'
import { VList, VListItem } from '@/components/VList'
import { VMenu } from '@/components/VMenu'
import { VTextField } from '@/components/VTextField'
// Composables
import { makeFilterProps, useFilter } from '@/composables/filter'
import { makeTransitionProps } from '@/composables/transition'
import { transformItem, useItems } from '@/composables/items'
import { forwardRefs } from '@/composables/forwardRefs'
import { useLocale } from '@/composables/locale'
import { useProxiedModel } from '@/composables/proxiedModel'
import { useTextColor } from '@/composables/color'
// Utility
import { computed, mergeProps, nextTick, ref, watch } from 'vue'
import { genericComponent, useRender, wrapInArray } from '@/util'
// Types
import type { FilterMatch } from '@/composables/filter'
import type { InternalItem } from '@/composables/items'
import type { MakeSlots } from '@/util'
import type { PropType } from 'vue'
import type { VFieldSlots } from '@/components/VField/VField'
import type { VInputSlots } from '@/components/VInput/VInput'
function highlightResult (text: string, matches: FilterMatch, length: number) {
if (Array.isArray(matches)) throw new Error('Multiple matches is not implemented')
return typeof matches === 'number' && ~matches
? (
<>
<span class="v-combobox__unmask">{ text.substr(0, matches) }</span>
<span class="v-combobox__mask">{ text.substr(matches, length) }</span>
<span class="v-combobox__unmask">{ text.substr(matches + length) }</span>
</>
)
: text
}
type Primitive = string | number | boolean | symbol
type Val <T, ReturnObject extends boolean> = T extends Primitive
? T
: (ReturnObject extends true ? T : any)
type Value <T, ReturnObject extends boolean, Multiple extends boolean> =
Multiple extends true
? Val<T, ReturnObject>[]
: Val<T, ReturnObject>
export const VCombobox = genericComponent<new <
T,
ReturnObject extends boolean = true,
Multiple extends boolean = false,
V extends Value<T, ReturnObject, Multiple> = Value<T, ReturnObject, Multiple>
>() => {
$props: {
items?: readonly T[]
returnObject?: ReturnObject
multiple?: Multiple
modelValue?: Readonly<V>
'onUpdate:modelValue'?: (val: V) => void
} & Omit<VTextField['$props'], 'modelValue' | 'onUpdate:modelValue'>
$slots: Omit<VInputSlots & VFieldSlots, 'default'> & MakeSlots<{
item: [{ item: InternalItem<T>, index: number, props: Record<string, unknown> }]
chip: [{ item: InternalItem<T>, index: number, props: Record<string, unknown> }]
selection: [{ item: InternalItem<T>, index: number }]
'no-data': []
}>
}>()({
name: 'VCombobox',
props: {
// TODO: implement post keyboard support
// autoSelectFirst: Boolean,
delimiters: Array as PropType<string[]>,
...makeFilterProps({ filterKeys: ['title'] }),
...makeSelectProps({ hideNoData: true, returnObject: true }),
...makeTransitionProps({ transition: false }),
},
emits: {
'update:modelValue': (val: any) => true,
'update:searchInput': (val: string) => true,
'update:menu': (val: boolean) => true,
},
setup (props, { emit, slots }) {
const { t } = useLocale()
const vTextFieldRef = ref()
const isFocused = ref(false)
const isPristine = ref(true)
const menu = useProxiedModel(props, 'menu')
const selectionIndex = ref(-1)
const color = computed(() => vTextFieldRef.value?.color)
const { items, transformIn, transformOut } = useItems(props)
const { textColorClasses, textColorStyles } = useTextColor(color)
const model = useProxiedModel(
props,
'modelValue',
[],
v => transformIn(wrapInArray(v || [])),
v => {
const transformed = transformOut(v)
return props.multiple ? transformed : (transformed[0] ?? null)
}
)
const _search = ref('')
const search = computed<string>({
get: () => {
return _search.value
},
set: val => {
_search.value = val
if (!props.multiple) {
model.value = [transformItem(props, val)]
}
if (val && props.multiple && props.delimiters?.length) {
const values = val.split(new RegExp(`(?:${props.delimiters.join('|')})+`))
if (values.length > 1) {
values.forEach(v => {
v = v.trim()
if (v) select(transformItem(props, v))
})
_search.value = ''
}
}
if (!val) selectionIndex.value = -1
if (isFocused.value) menu.value = true
isPristine.value = !val
},
})
watch(_search, value => {
emit('update:searchInput', value)
})
const { filteredItems } = useFilter(props, items, computed(() => isPristine.value ? undefined : search.value))
const selections = computed(() => {
return model.value.map(v => {
return items.value.find(item => item.value === v.value) || v
})
})
const selected = computed(() => selections.value.map(selection => selection.props.value))
const selection = computed(() => selections.value[selectionIndex.value])
function onClear (e: MouseEvent) {
model.value = []
if (props.openOnClear) {
menu.value = true
}
}
function onClickControl () {
if (
(props.hideNoData && !items.value.length) ||
props.readonly
) return
menu.value = true
}
function onKeydown (e: KeyboardEvent) {
if (props.readonly) return
const selectionStart = vTextFieldRef.value.selectionStart
const length = selected.value.length
if (selectionIndex.value > -1) e.preventDefault()
if (['Enter', 'ArrowDown'].includes(e.key)) {
menu.value = true
}
if (['Escape'].includes(e.key)) {
menu.value = false
}
if (['Enter', 'Escape', 'Tab'].includes(e.key)) {
isPristine.value = true
}
if (!props.multiple) return
if (['Backspace', 'Delete'].includes(e.key)) {
if (selectionIndex.value < 0) {
if (e.key === 'Backspace' && !search.value) {
selectionIndex.value = length - 1
}
return
}
select(selection.value)
nextTick(() => !selection.value && (selectionIndex.value = length - 2))
}
if (e.key === 'ArrowLeft') {
if (selectionIndex.value < 0 && selectionStart > 0) return
const prev = selectionIndex.value > -1
? selectionIndex.value - 1
: length - 1
if (selections.value[prev]) {
selectionIndex.value = prev
} else {
selectionIndex.value = -1
vTextFieldRef.value.setSelectionRange(search.value.length, search.value.length)
}
}
if (e.key === 'ArrowRight') {
if (selectionIndex.value < 0) return
const next = selectionIndex.value + 1
if (selections.value[next]) {
selectionIndex.value = next
} else {
selectionIndex.value = -1
vTextFieldRef.value.setSelectionRange(0, 0)
}
}
if (e.key === 'Enter') {
select(transformItem(props, search.value))
search.value = ''
}
}
function onAfterLeave () {
if (isFocused.value) isPristine.value = true
}
function select (item: InternalItem) {
if (props.multiple) {
const index = selected.value.findIndex(selection => selection === item.value)
if (index === -1) {
model.value = [...model.value, item]
} else {
const value = [...model.value]
value.splice(index, 1)
model.value = value
}
search.value = ''
} else {
search.value = item.title
// watch for search watcher to trigger
nextTick(() => {
menu.value = false
isPristine.value = true
})
}
}
watch(filteredItems, val => {
if (!val.length && props.hideNoData) menu.value = false
})
watch(isFocused, val => {
if (val) {
selectionIndex.value = -1
} else {
menu.value = false
if (!props.multiple || !search.value) return
model.value = [...model.value, transformItem(props, search.value)]
search.value = ''
}
})
useRender(() => {
const hasChips = !!(props.chips || slots.chip)
return (
<VTextField
ref={ vTextFieldRef }
v-model={ search.value }
onUpdate:modelValue={ v => { if (v == null) model.value = [] } }
validationValue={ model.externalValue }
dirty={ model.value.length > 0 }
class={[
'v-combobox',
{
'v-combobox--active-menu': menu.value,
'v-combobox--chips': !!props.chips,
'v-combobox--selecting-index': selectionIndex.value > -1,
[`v-combobox--${props.multiple ? 'multiple' : 'single'}`]: true,
},
]}
appendInnerIcon={ props.items.length ? props.menuIcon : undefined }
readonly={ props.readonly }
onClick:clear={ onClear }
onClick:control={ onClickControl }
onClick:input={ onClickControl }
onFocus={ () => isFocused.value = true }
onBlur={ () => isFocused.value = false }
onKeydown={ onKeydown }
>
{{
...slots,
default: () => (
<>
<VMenu
v-model={ menu.value }
activator="parent"
contentClass="v-combobox__content"
eager={ props.eager }
openOnClick={ false }
closeOnContentClick={ false }
transition={ props.transition }
onAfterLeave={ onAfterLeave }
{ ...props.menuProps }
>
<VList
selected={ selected.value }
selectStrategy={ props.multiple ? 'independent' : 'single-independent' }
onMousedown={ (e: MouseEvent) => e.preventDefault() }
>
{ !filteredItems.value.length && !props.hideNoData && (slots['no-data']?.() ?? (
<VListItem title={ t(props.noDataText) } />
)) }
{ filteredItems.value.map(({ item, matches }, index) => slots.item?.({
item,
index,
props: mergeProps(item.props, { onClick: () => select(item) }),
}) ?? (
<VListItem
key={ index }
{ ...item.props }
onClick={ () => select(item) }
>
{{
prepend: ({ isSelected }) => props.multiple && !props.hideSelected ? (
<VCheckboxBtn modelValue={ isSelected } ripple={ false } />
) : undefined,
title: () => {
return isPristine.value
? item.title
: highlightResult(item.title, matches.title, search.value?.length ?? 0)
},
}}
</VListItem>
)) }
</VList>
</VMenu>
{ selections.value.map((item, index) => {
function onChipClose (e: Event) {
e.stopPropagation()
e.preventDefault()
select(item)
}
const slotProps = {
'onClick:close': onChipClose,
modelValue: true,
}
return (
<div
key={ index }
class={[
'v-combobox__selection',
index === selectionIndex.value && [
'v-combobox__selection--selected',
textColorClasses.value,
],
]}
style={ index === selectionIndex.value ? textColorStyles.value : {} }
>
{ hasChips ? (
<VDefaultsProvider
defaults={{
VChip: {
closable: props.closableChips,
size: 'small',
text: item.title,
},
}}
>
{ slots.chip
? slots.chip({ item, index, props: slotProps })
: (<VChip { ...slotProps } />)
}
</VDefaultsProvider>
) : (
slots.selection
? slots.selection({ item, index })
: (
<span class="v-combobox__selection-text">
{ item.title }
{ props.multiple && (index < selections.value.length - 1) && (
<span class="v-combobox__selection-comma">,</span>
) }
</span>
)
) }
</div>
)
}) }
</>
),
}}
</VTextField>
)
})
return forwardRefs({
isFocused,
isPristine,
menu,
search,
selectionIndex,
filteredItems,
select,
}, vTextFieldRef)
},
})
export type VCombobox = InstanceType<typeof VCombobox>