/
FieldAutoCompleteInput.vue
541 lines (476 loc) · 16.9 KB
/
FieldAutoCompleteInput.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
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
<!-- Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/ -->
<script setup lang="ts">
import {
computed,
markRaw,
nextTick,
onMounted,
ref,
toRef,
watch,
type ConcreteComponent,
type Ref,
} from 'vue'
import { cloneDeep, escapeRegExp } from 'lodash-es'
import gql from 'graphql-tag'
import {
refDebounced,
useElementBounding,
useWindowSize,
watchOnce,
} from '@vueuse/core'
import { useLazyQuery } from '@vue/apollo-composable'
import type { FormKitNode } from '@formkit/core'
import type { NameNode, OperationDefinitionNode, SelectionNode } from 'graphql'
import CommonInputSearch from '#desktop/components/CommonInputSearch/CommonInputSearch.vue'
import CommonSelect from '#desktop/components/CommonSelect/CommonSelect.vue'
import type { CommonSelectInstance } from '#desktop/components/CommonSelect/types'
import { i18n } from '#shared/i18n.ts'
import { useFormBlock } from '#shared/form/useFormBlock.ts'
import useValue from '#shared/components/Form/composables/useValue.ts'
import useSelectOptions from '#shared/composables/useSelectOptions.ts'
import { useTrapTab } from '#shared/composables/useTrapTab.ts'
import { QueryHandler } from '#shared/server/apollo/handler/index.ts'
import type { ObjectLike } from '#shared/types/utils.ts'
import type { FormFieldContext } from '#shared/components/Form/types/field.ts'
import type {
AutoCompleteOption,
AutoCompleteProps,
AutocompleteSelectValue,
} from '#shared/components/Form/fields/FieldAutocomplete/types.ts'
import type { SelectOption } from '#shared/components/CommonSelect/types'
import FieldAutoCompleteOptionIcon from './FieldAutoCompleteOptionIcon.vue'
interface Props {
context: FormFieldContext<AutoCompleteProps>
}
const props = defineProps<Props>()
const contextReactive = toRef(props, 'context')
const { hasValue, valueContainer, currentValue, isCurrentValue, clearValue } =
useValue<AutocompleteSelectValue>(contextReactive)
const localOptions = ref(props.context.options || [])
const {
sortedOptions,
appendedOptions,
optionValueLookup,
getSelectedOptionLabel,
} = useSelectOptions<AutoCompleteOption[]>(localOptions, contextReactive)
let areLocalOptionsReplaced = false
const replacementLocalOptions: Ref<AutoCompleteOption[]> = ref(
cloneDeep(localOptions),
)
onMounted(() => {
if (props.context.options && areLocalOptionsReplaced) {
replacementLocalOptions.value = [...props.context.options]
}
})
watch(
() => props.context.options,
(options) => {
localOptions.value = options || []
},
)
// Remember current optionValueLookup in node context.
contextReactive.value.optionValueLookup = optionValueLookup
// Initial options prefill for non-multiple fields (multiple fields needs to be handled in
// the form updater or via options prop).
let rememberedInitialOptionFromBuilder: AutoCompleteOption | undefined
const initialOptionBuilderHandler = (rootNode: FormKitNode) => {
if (
hasValue.value &&
props.context.initialOptionBuilder &&
!getSelectedOptionLabel(currentValue.value)
) {
const initialOption = props.context.initialOptionBuilder(
rootNode?.context?.initialEntityObject as ObjectLike,
currentValue.value,
props.context,
)
if (initialOption) {
localOptions.value.push(initialOption)
if (rememberedInitialOptionFromBuilder) {
const rememberedOptionValue = rememberedInitialOptionFromBuilder.value
localOptions.value = localOptions.value.filter(
(option) => option.value !== rememberedOptionValue,
)
}
rememberedInitialOptionFromBuilder = initialOption
}
}
}
if (!props.context.multiple && props.context.initialOptionBuilder) {
const rootNode = props.context.node.at('$root')
if (rootNode) {
initialOptionBuilderHandler(rootNode)
rootNode?.on('reset', ({ origin }) => {
initialOptionBuilderHandler(origin)
})
}
}
const input = ref<HTMLDivElement>()
const outputElement = ref<HTMLOutputElement>()
const filter = ref('')
const filterInput = ref<HTMLInputElement>()
const select = ref<CommonSelectInstance>()
const { activateTabTrap, deactivateTabTrap } = useTrapTab(input, true)
const clearFilter = () => {
filter.value = ''
}
const trimmedFilter = computed(() => filter.value.trim())
const debouncedFilter = refDebounced(
trimmedFilter,
props.context.debounceInterval ?? 500,
)
const AutocompleteSearchDocument = gql`
${props.context.gqlQuery}
`
const additionalQueryParams = () => {
if (typeof props.context.additionalQueryParams === 'function') {
return props.context.additionalQueryParams()
}
return props.context.additionalQueryParams || {}
}
const autocompleteQueryHandler = new QueryHandler(
useLazyQuery(
AutocompleteSearchDocument,
() => ({
input: {
query: debouncedFilter.value || props.context.defaultFilter || '',
limit: props.context.limit,
...(additionalQueryParams() || {}),
},
}),
() => ({
enabled: !!(debouncedFilter.value || props.context.defaultFilter),
cachePolicy: 'no-cache', // Do not use cache, because we want always up-to-date results.
}),
),
)
if (props.context.defaultFilter) {
autocompleteQueryHandler.load()
} else {
watchOnce(
() => debouncedFilter.value,
(newValue) => {
if (!newValue.length) return
autocompleteQueryHandler.load()
},
)
}
const autocompleteQueryResultKey = (
(AutocompleteSearchDocument.definitions[0] as OperationDefinitionNode)
.selectionSet.selections[0] as SelectionNode & { name: NameNode }
).name.value
const autocompleteQueryResultOptions = computed(
() =>
autocompleteQueryHandler.result().value?.[
autocompleteQueryResultKey
] as unknown as AutoCompleteOption[],
)
const autocompleteOptions = computed(
() => cloneDeep(autocompleteQueryResultOptions.value) || [],
)
const {
sortedOptions: sortedAutocompleteOptions,
selectOption: selectAutocompleteOption,
getSelectedOption: getSelectedAutocompleteOption,
getSelectedOptionIcon: getSelectedAutocompleteOptionIcon,
getSelectedOptionLabel: getSelectedAutocompleteOptionLabel,
} = useSelectOptions<AutoCompleteOption[]>(
autocompleteOptions,
toRef(props, 'context'),
)
const selectOption = (option: SelectOption) => {
selectAutocompleteOption(option as AutoCompleteOption)
if (props.context.multiple) {
// If the current value contains the selected option, make sure it's added to the replacement list
// if it's not already there.
if (
isCurrentValue(option.value) &&
!replacementLocalOptions.value.some(
(replacementLocalOption) =>
replacementLocalOption.value === option.value,
)
) {
replacementLocalOptions.value.push(option as AutoCompleteOption)
}
// Remove any extra options from the replacement list.
replacementLocalOptions.value = replacementLocalOptions.value.filter(
(replacementLocalOption) => isCurrentValue(replacementLocalOption.value),
)
if (!sortedOptions.value.some((elem) => elem.value === option.value)) {
appendedOptions.value.push(option as AutoCompleteOption)
}
appendedOptions.value = appendedOptions.value.filter((elem) =>
isCurrentValue(elem.value),
)
// Sort the replacement list according to the original order.
replacementLocalOptions.value.sort(
(a, b) =>
sortedOptions.value.findIndex((option) => option.value === a.value) -
sortedOptions.value.findIndex((option) => option.value === b.value),
)
clearFilter()
return
}
localOptions.value = [option as AutoCompleteOption]
select.value?.closeDropdown()
}
const availableOptions = computed(() =>
filter.value || props.context.defaultFilter
? sortedAutocompleteOptions.value
: sortedOptions.value,
)
const deaccent = (s: string) =>
s.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
const availableOptionsWithMatches = computed(() => {
// Trim and de-accent search keywords and compile them as a case-insensitive regex.
// Make sure to escape special regex characters!
const filterRegex = new RegExp(
escapeRegExp(deaccent(filter.value.trim())),
'i',
)
return availableOptions.value.map(
(option) =>
({
...option,
// Match options via their de-accented labels.
match: filterRegex.exec(deaccent(option.label || String(option.value))),
}) as AutoCompleteOption,
)
})
const suggestedOptionLabel = computed(() => {
if (!filter.value || !availableOptionsWithMatches.value.length)
return undefined
const exactMatches = availableOptionsWithMatches.value.filter(
(option) =>
(
getSelectedAutocompleteOptionLabel(option.value) ||
option.value.toString()
)
.toLowerCase()
.indexOf(filter.value.toLowerCase()) === 0 &&
(
getSelectedAutocompleteOptionLabel(option.value) ||
option.value.toString()
).length > filter.value.length,
)
if (!exactMatches.length) return undefined
return getSelectedAutocompleteOptionLabel(exactMatches[0].value)
})
const inputElementBounds = useElementBounding(input)
const windowSize = useWindowSize()
const isBelowHalfScreen = computed(() => {
return inputElementBounds.y.value > windowSize.height.value / 2
})
const openSelectDropdown = () => {
if (select.value?.isOpen || props.context.disabled) return
select.value?.openDropdown(inputElementBounds, windowSize.height)
requestAnimationFrame(() => {
activateTabTrap()
if (props.context.noFiltering) outputElement.value?.focus()
else filterInput.value?.focus()
})
}
const openOrMoveFocusToDropdown = (lastOption = false) => {
if (!select.value?.isOpen) {
openSelectDropdown()
return
}
deactivateTabTrap()
nextTick(() => {
requestAnimationFrame(() => {
select.value?.moveFocusToDropdown(lastOption)
})
})
}
const onCloseDropdown = () => {
if (props.context.multiple) {
replacementLocalOptions.value = []
areLocalOptionsReplaced = true
}
clearFilter()
deactivateTabTrap()
}
const OptionIconComponent =
props.context.optionIconComponent ??
(FieldAutoCompleteOptionIcon as ConcreteComponent)
useFormBlock(contextReactive, openSelectDropdown)
</script>
<template>
<div
ref="input"
class="flex h-auto min-h-10 hover:outline hover:outline-1 hover:outline-offset-1 hover:outline-blue-600 has-[output:focus,input:focus]:outline has-[output:focus,input:focus]:outline-1 has-[output:focus,input:focus]:outline-offset-1 has-[output:focus,input:focus]:outline-blue-800 dark:hover:outline-blue-900 dark:has-[output:focus,input:focus]:outline-blue-800"
:class="[
context.classes.input,
{
'rounded-lg': !select?.isOpen,
'rounded-t-lg': select?.isOpen && !isBelowHalfScreen,
'rounded-b-lg': select?.isOpen && isBelowHalfScreen,
'bg-blue-200 dark:bg-gray-700': !context.alternativeBackground,
'bg-white dark:bg-gray-500': context.alternativeBackground,
},
]"
data-test-id="field-autocomplete"
>
<CommonSelect
ref="select"
#default="{ state: expanded, close: closeDropdown }"
:model-value="currentValue"
:options="availableOptionsWithMatches"
:multiple="context.multiple"
:owner="context.id"
:filter="filter"
:option-icon-component="markRaw(OptionIconComponent)"
no-options-label-translation
no-close
passive
initially-empty
@select="selectOption"
@close="onCloseDropdown"
>
<output
:id="context.id"
ref="outputElement"
role="combobox"
aria-controls="common-select"
aria-owns="common-select"
aria-haspopup="menu"
:aria-expanded="expanded"
:name="context.node.name"
class="formkit-disabled:pointer-events-none flex grow items-center gap-2.5 px-2.5 py-2 text-black focus:outline-none dark:text-white"
:aria-labelledby="`label-${context.id}`"
:aria-disabled="context.disabled"
:aria-describedby="context.describedBy"
aria-autocomplete="none"
:data-multiple="context.multiple"
tabindex="0"
v-bind="context.attrs"
@keydown.escape.prevent="closeDropdown()"
@keypress.enter.prevent="openSelectDropdown()"
@keydown.down.prevent="openOrMoveFocusToDropdown()"
@keydown.up.prevent="openOrMoveFocusToDropdown(true)"
@keypress.space.prevent="openSelectDropdown()"
@blur="context.handlers.blur"
>
<div
v-if="hasValue && context.multiple"
class="flex flex-wrap gap-1.5"
role="list"
>
<div
v-for="selectedValue in valueContainer"
:key="selectedValue.toString()"
class="flex items-center gap-1.5"
role="listitem"
>
<div
class="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-black dark:text-white"
:class="{
'bg-white dark:bg-gray-200': !context.alternativeBackground,
'bg-neutral-100 dark:bg-gray-200':
context.alternativeBackground,
}"
>
<CommonIcon
v-if="getSelectedAutocompleteOptionIcon(selectedValue)"
:name="getSelectedAutocompleteOptionIcon(selectedValue)"
class="shrink-0 fill-gray-100 dark:fill-neutral-400"
size="xs"
decorative
/>
<span
class="line-clamp-3 whitespace-pre-wrap break-words"
:title="
getSelectedOptionLabel(selectedValue) ||
i18n.t('%s (unknown)', selectedValue.toString())
"
>
{{
getSelectedOptionLabel(selectedValue) ||
i18n.t('%s (unknown)', selectedValue.toString())
}}
</span>
<CommonIcon
:aria-label="i18n.t('Unselect Option')"
class="shrink-0 fill-stone-200 hover:fill-black focus-visible:rounded-sm focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1 focus-visible:outline-blue-800 dark:fill-neutral-500 dark:hover:fill-white"
name="x-lg"
size="xs"
role="button"
tabindex="0"
@click.stop="
selectAutocompleteOption(
getSelectedAutocompleteOption(selectedValue),
)
"
@keypress.enter.prevent.stop="
selectAutocompleteOption(
getSelectedAutocompleteOption(selectedValue),
)
"
@keypress.space.prevent.stop="
selectAutocompleteOption(
getSelectedAutocompleteOption(selectedValue),
)
"
/>
</div>
</div>
</div>
<CommonInputSearch
v-if="expanded || !hasValue"
ref="filterInput"
v-model="filter"
:class="{ 'pointer-events-none': !expanded }"
:suggestion="suggestedOptionLabel"
:alternative-background="context.alternativeBackground"
@keypress.space.stop
/>
<div v-if="!expanded" class="flex grow flex-wrap gap-1" role="list">
<div
v-if="hasValue && !context.multiple"
class="flex items-center gap-1.5 text-sm"
role="listitem"
>
<CommonIcon
v-if="getSelectedAutocompleteOptionIcon(currentValue)"
:name="getSelectedAutocompleteOptionIcon(currentValue)"
class="shrink-0 fill-gray-100 dark:fill-neutral-400"
size="tiny"
decorative
/>
<span
class="line-clamp-3 whitespace-pre-wrap break-words"
:title="
getSelectedOptionLabel(currentValue) ||
i18n.t('%s (unknown)', currentValue.toString())
"
>
{{
getSelectedOptionLabel(currentValue) ||
i18n.t('%s (unknown)', currentValue.toString())
}}
</span>
</div>
</div>
<CommonIcon
v-if="context.clearable && hasValue && !context.disabled"
:aria-label="i18n.t('Clear Selection')"
class="shrink-0 fill-stone-200 hover:fill-black focus-visible:rounded-sm focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1 focus-visible:outline-blue-800 dark:fill-neutral-500 dark:hover:fill-white"
name="x-lg"
size="xs"
role="button"
tabindex="0"
@click.stop="clearValue()"
@keypress.enter.prevent.stop="clearValue()"
@keypress.space.prevent.stop="clearValue()"
/>
<CommonIcon
class="shrink-0 fill-stone-200 dark:fill-neutral-500"
name="chevron-down"
size="xs"
decorative
/>
</output>
</CommonSelect>
</div>
</template>