forked from element-plus/element-plus
/
autocomplete.vue
377 lines (335 loc) Β· 10 KB
/
autocomplete.vue
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
<template>
<el-tooltip
ref="popperRef"
v-model:visible="suggestionVisible"
:placement="placement"
:fallback-placements="['bottom-start', 'top-start']"
:popper-class="[ns.e('popper'), popperClass]"
:teleported="teleported"
:gpu-acceleration="false"
pure
manual-mode
effect="light"
trigger="click"
:transition="`${ns.namespace.value}-zoom-in-top`"
persistent
@before-show="onSuggestionShow"
@show="onShow"
@hide="onHide"
>
<div
ref="listboxRef"
:class="[ns.b(), $attrs.class]"
:style="styles"
role="combobox"
aria-haspopup="listbox"
:aria-expanded="suggestionVisible"
:aria-owns="listboxId"
>
<el-input
ref="inputRef"
v-bind="attrs"
:model-value="modelValue"
@input="handleInput"
@change="handleChange"
@focus="handleFocus"
@blur="handleBlur"
@clear="handleClear"
@keydown.up.prevent="highlight(highlightedIndex - 1)"
@keydown.down.prevent="highlight(highlightedIndex + 1)"
@keydown.enter="handleKeyEnter"
@keydown.tab="close"
@keydown.esc="handleKeyEscape"
@mousedown="handleMouseDown"
>
<template v-if="$slots.prepend" #prepend>
<slot name="prepend" />
</template>
<template v-if="$slots.append" #append>
<slot name="append" />
</template>
<template v-if="$slots.prefix" #prefix>
<slot name="prefix" />
</template>
<template v-if="$slots.suffix" #suffix>
<slot name="suffix" />
</template>
</el-input>
</div>
<template #content>
<div
ref="regionRef"
:class="[ns.b('suggestion'), ns.is('loading', suggestionLoading)]"
:style="{ minWidth: dropdownWidth, outline: 'none' }"
role="region"
>
<el-scrollbar
:id="listboxId"
tag="ul"
:wrap-class="ns.be('suggestion', 'wrap')"
:view-class="ns.be('suggestion', 'list')"
role="listbox"
>
<li v-if="suggestionLoading">
<el-icon :class="ns.is('loading')"><Loading /></el-icon>
</li>
<template v-else>
<li
v-for="(item, index) in suggestions"
:id="`${listboxId}-item-${index}`"
:key="index"
:class="{ highlighted: highlightedIndex === index }"
role="option"
:aria-selected="highlightedIndex === index"
@click="handleSelect(item)"
>
<slot :item="item">{{ item[valueKey] }}</slot>
</li>
</template>
</el-scrollbar>
</div>
</template>
</el-tooltip>
</template>
<script lang="ts" setup>
import {
computed,
nextTick,
onMounted,
ref,
useAttrs as useRawAttrs,
} from 'vue'
import { debounce } from 'lodash-unified'
import { onClickOutside } from '@vueuse/core'
import { Loading } from '@element-plus/icons-vue'
import { useAttrs, useDisabled, useNamespace } from '@element-plus/hooks'
import { generateId, isArray, throwError } from '@element-plus/utils'
import {
CHANGE_EVENT,
INPUT_EVENT,
UPDATE_MODEL_EVENT,
} from '@element-plus/constants'
import ElInput from '@element-plus/components/input'
import ElScrollbar from '@element-plus/components/scrollbar'
import ElTooltip from '@element-plus/components/tooltip'
import ElIcon from '@element-plus/components/icon'
import { autocompleteEmits, autocompleteProps } from './autocomplete'
import type { AutocompleteData } from './autocomplete'
import type { StyleValue } from 'vue'
import type { TooltipInstance } from '@element-plus/components/tooltip'
import type { InputInstance } from '@element-plus/components/input'
defineOptions({
name: 'ElAutocomplete',
inheritAttrs: false,
})
const COMPONENT_NAME = 'ElAutocomplete'
const props = defineProps(autocompleteProps)
const emit = defineEmits(autocompleteEmits)
const attrs = useAttrs()
const rawAttrs = useRawAttrs()
const disabled = useDisabled()
const ns = useNamespace('autocomplete')
const inputRef = ref<InputInstance>()
const regionRef = ref<HTMLElement>()
const popperRef = ref<TooltipInstance>()
const listboxRef = ref<HTMLElement>()
let ignoreFocusEvent = false
const suggestions = ref<AutocompleteData>([])
const highlightedIndex = ref(-1)
const dropdownWidth = ref('')
const activated = ref(false)
const suggestionDisabled = ref(false)
const loading = ref(false)
const listboxId = computed(() => ns.b(String(generateId())))
const styles = computed(() => rawAttrs.style as StyleValue)
const suggestionVisible = computed(() => {
const isValidData = suggestions.value.length > 0
return (isValidData || loading.value) && activated.value
})
const suggestionLoading = computed(() => !props.hideLoading && loading.value)
const refInput = computed<HTMLInputElement[]>(() => {
if (inputRef.value) {
return Array.from<HTMLInputElement>(
inputRef.value.$el.querySelectorAll('input')
)
}
return []
})
const onSuggestionShow = async () => {
await nextTick()
if (suggestionVisible.value) {
dropdownWidth.value = `${inputRef.value!.$el.offsetWidth}px`
}
}
const onShow = () => {
ignoreFocusEvent = true
}
const onHide = () => {
ignoreFocusEvent = false
highlightedIndex.value = -1
}
const getData = async (queryString: string) => {
if (suggestionDisabled.value) return
const cb = (suggestionList: AutocompleteData) => {
loading.value = false
if (suggestionDisabled.value) return
if (isArray(suggestionList)) {
suggestions.value = suggestionList
highlightedIndex.value = props.highlightFirstItem ? 0 : -1
} else {
throwError(COMPONENT_NAME, 'autocomplete suggestions must be an array')
}
}
loading.value = true
if (isArray(props.fetchSuggestions)) {
cb(props.fetchSuggestions)
} else {
const result = await props.fetchSuggestions(queryString, cb)
if (isArray(result)) cb(result)
}
}
const debouncedGetData = debounce(getData, props.debounce)
const handleInput = (value: string) => {
const valuePresented = !!value
emit(INPUT_EVENT, value)
emit(UPDATE_MODEL_EVENT, value)
suggestionDisabled.value = false
activated.value ||= valuePresented
if (!props.triggerOnFocus && !value) {
suggestionDisabled.value = true
suggestions.value = []
return
}
debouncedGetData(value)
}
const handleMouseDown = (event: MouseEvent) => {
if (disabled.value) return
if (
(event.target as HTMLElement)?.tagName !== 'INPUT' ||
refInput.value.includes(document.activeElement as HTMLInputElement)
) {
activated.value = true
}
}
const handleChange = (value: string) => {
emit(CHANGE_EVENT, value)
}
const handleFocus = (evt: FocusEvent) => {
if (ignoreFocusEvent) return
activated.value = true
emit('focus', evt)
if (props.triggerOnFocus) {
debouncedGetData(String(props.modelValue))
}
}
const handleBlur = (evt: FocusEvent) => {
if (ignoreFocusEvent) return
emit('blur', evt)
}
const handleClear = () => {
activated.value = false
emit(UPDATE_MODEL_EVENT, '')
emit('clear')
}
const handleKeyEnter = async () => {
if (
suggestionVisible.value &&
highlightedIndex.value >= 0 &&
highlightedIndex.value < suggestions.value.length
) {
handleSelect(suggestions.value[highlightedIndex.value])
} else if (props.selectWhenUnmatched) {
emit('select', { value: props.modelValue })
suggestions.value = []
highlightedIndex.value = -1
}
}
const handleKeyEscape = (evt: Event) => {
if (suggestionVisible.value) {
evt.preventDefault()
evt.stopPropagation()
close()
}
}
const close = () => {
activated.value = false
}
const focus = () => {
inputRef.value?.focus()
}
const handleSelect = async (item: any) => {
emit(INPUT_EVENT, item[props.valueKey])
emit(UPDATE_MODEL_EVENT, item[props.valueKey])
emit('select', item)
suggestions.value = []
highlightedIndex.value = -1
}
const highlight = (index: number) => {
if (!suggestionVisible.value || loading.value) return
if (index < 0) {
highlightedIndex.value = -1
return
}
if (index >= suggestions.value.length) {
index = suggestions.value.length - 1
}
const suggestion = regionRef.value!.querySelector(
`.${ns.be('suggestion', 'wrap')}`
)!
const suggestionList = suggestion.querySelectorAll<HTMLElement>(
`.${ns.be('suggestion', 'list')} li`
)!
const highlightItem = suggestionList[index]
const scrollTop = suggestion.scrollTop
const { offsetTop, scrollHeight } = highlightItem
if (offsetTop + scrollHeight > scrollTop + suggestion.clientHeight) {
suggestion.scrollTop += scrollHeight
}
if (offsetTop < scrollTop) {
suggestion.scrollTop -= scrollHeight
}
highlightedIndex.value = index
// TODO: use Volar generate dts to fix it.
;(inputRef.value as any).ref!.setAttribute(
'aria-activedescendant',
`${listboxId.value}-item-${highlightedIndex.value}`
)
}
onClickOutside(listboxRef, () => {
suggestionVisible.value && close()
})
onMounted(() => {
// TODO: use Volar generate dts to fix it.
;(inputRef.value as any).ref!.setAttribute('role', 'textbox')
;(inputRef.value as any).ref!.setAttribute('aria-autocomplete', 'list')
;(inputRef.value as any).ref!.setAttribute('aria-controls', 'id')
;(inputRef.value as any).ref!.setAttribute(
'aria-activedescendant',
`${listboxId.value}-item-${highlightedIndex.value}`
)
})
defineExpose({
/** @description the index of the currently highlighted item */
highlightedIndex,
/** @description autocomplete whether activated */
activated,
/** @description remote search loading status */
loading,
/** @description el-input component instance */
inputRef,
/** @description el-tooltip component instance */
popperRef,
/** @description fetch suggestions result */
suggestions,
/** @description triggers when a suggestion is clicked */
handleSelect,
/** @description handle keyboard enter event */
handleKeyEnter,
/** @description focus the input element */
focus,
/** @description close suggestion */
close,
/** @description highlight an item in a suggestion */
highlight,
})
</script>