-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
combobox.ts
1583 lines (1387 loc) · 51.8 KB
/
combobox.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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Virtualizer } from '@tanstack/virtual-core'
import { useVirtualizer } from '@tanstack/vue-virtual'
import {
Fragment,
cloneVNode,
computed,
defineComponent,
h,
inject,
nextTick,
onMounted,
onUnmounted,
provide,
reactive,
ref,
toRaw,
watch,
watchEffect,
type ComputedRef,
type InjectionKey,
type PropType,
type Ref,
type UnwrapNestedRefs,
} from 'vue'
import { useControllable } from '../../hooks/use-controllable'
import { useFrameDebounce } from '../../hooks/use-frame-debounce'
import { useId } from '../../hooks/use-id'
import { useOutsideClick } from '../../hooks/use-outside-click'
import { useResolveButtonType } from '../../hooks/use-resolve-button-type'
import { useTrackedPointer } from '../../hooks/use-tracked-pointer'
import { useTreeWalker } from '../../hooks/use-tree-walker'
import { Hidden, Features as HiddenFeatures } from '../../internal/hidden'
import { State, useOpenClosed, useOpenClosedProvider } from '../../internal/open-closed'
import { Keys } from '../../keyboard'
import { MouseButton } from '../../mouse'
import { history } from '../../utils/active-element-history'
import { Focus, calculateActiveIndex } from '../../utils/calculate-active-index'
import { disposables } from '../../utils/disposables'
import { dom } from '../../utils/dom'
import { sortByDomNode } from '../../utils/focus-management'
import { objectToFormEntries } from '../../utils/form'
import { match } from '../../utils/match'
import { getOwnerDocument } from '../../utils/owner'
import { isMobile } from '../../utils/platform'
import { Features, compact, omit, render } from '../../utils/render'
function defaultComparator<T>(a: T, z: T): boolean {
return a === z
}
enum ComboboxStates {
Open,
Closed,
}
enum ValueMode {
Single,
Multi,
}
enum ActivationTrigger {
Pointer,
Focus,
Other,
}
type ComboboxOptionData = {
disabled: boolean
value: unknown
domRef: Ref<HTMLElement | null>
order: Ref<number | null>
}
type StateDefinition = {
// State
comboboxState: Ref<ComboboxStates>
value: ComputedRef<unknown>
defaultValue: ComputedRef<unknown>
mode: ComputedRef<ValueMode>
nullable: ComputedRef<boolean>
immediate: ComputedRef<boolean>
virtual: ComputedRef<{
options: unknown[]
disabled: (value: unknown) => boolean
} | null>
calculateIndex(value: unknown): number
isSelected(value: unknown): boolean
isActive(value: unknown): boolean
compare: (a: unknown, z: unknown) => boolean
optionsPropsRef: Ref<{ static: boolean; hold: boolean }>
labelRef: Ref<HTMLLabelElement | null>
inputRef: Ref<HTMLInputElement | null>
buttonRef: Ref<HTMLButtonElement | null>
optionsRef: Ref<HTMLDivElement | null>
disabled: Ref<boolean>
options: Ref<{ id: string; dataRef: ComputedRef<ComboboxOptionData> }[]>
activeOptionIndex: Ref<number | null>
activationTrigger: Ref<ActivationTrigger>
// State mutators
closeCombobox(): void
openCombobox(): void
setActivationTrigger(trigger: ActivationTrigger): void
goToOption(focus: Focus, idx?: number, trigger?: ActivationTrigger): void
change(value: unknown): void
selectOption(id: string): void
selectActiveOption(): void
registerOption(id: string, dataRef: ComputedRef<ComboboxOptionData>): void
unregisterOption(id: string, active: boolean): void
select(value: unknown): void
}
let ComboboxContext = Symbol('ComboboxContext') as InjectionKey<StateDefinition>
function useComboboxContext(component: string) {
let context = inject(ComboboxContext, null)
if (context === null) {
let err = new Error(`<${component} /> is missing a parent <Combobox /> component.`)
if (Error.captureStackTrace) Error.captureStackTrace(err, useComboboxContext)
throw err
}
return context
}
// ---
let VirtualContext = Symbol('VirtualContext') as InjectionKey<Ref<Virtualizer<any, any>> | null>
let VirtualProvider = defineComponent({
name: 'VirtualProvider',
setup(_, { slots }) {
let api = useComboboxContext('VirtualProvider')
let padding = computed(() => {
let el = dom(api.optionsRef)
if (!el) return { start: 0, end: 0 }
let styles = window.getComputedStyle(el)
return {
start: parseFloat(styles.paddingBlockStart || styles.paddingTop),
end: parseFloat(styles.paddingBlockEnd || styles.paddingBottom),
}
})
let virtualizer = useVirtualizer<HTMLDivElement, HTMLLIElement>(
computed(() => {
return {
scrollPaddingStart: padding.value.start,
scrollPaddingEnd: padding.value.end,
count: api.virtual.value!.options.length,
estimateSize() {
return 40
},
getScrollElement() {
return dom(api.optionsRef)
},
overscan: 12,
}
})
)
let options = computed(() => api.virtual.value?.options)
let baseKey = ref(0)
watch([options], () => {
baseKey.value += 1
})
provide(VirtualContext, api.virtual.value ? virtualizer : null)
return () => {
return [
h(
'div',
{
style: {
position: 'relative',
width: '100%',
height: `${virtualizer.value.getTotalSize()}px`,
},
ref: (el) => {
if (!el) {
return
}
// Do not scroll when the mouse/pointer is being used
if (api.activationTrigger.value === ActivationTrigger.Pointer) {
return
}
// Scroll to the active index
if (
api.activeOptionIndex.value !== null &&
api.virtual.value!.options.length > api.activeOptionIndex.value
) {
virtualizer.value.scrollToIndex(api.activeOptionIndex.value)
}
},
},
virtualizer.value.getVirtualItems().map((item) => {
return cloneVNode(
slots.default!({
option: api.virtual.value!.options[item.index],
open: api.comboboxState.value === ComboboxStates.Open,
})![0],
{
key: `${baseKey.value}-${item.index}`,
'data-index': item.index,
'aria-setsize': api.virtual.value!.options.length,
'aria-posinset': item.index + 1,
style: {
position: 'absolute',
top: 0,
left: 0,
transform: `translateY(${item.start}px)`,
overflowAnchor: 'none',
},
}
)
})
),
]
}
},
})
// ---
export let Combobox = defineComponent({
name: 'Combobox',
emits: { 'update:modelValue': (_value: any) => true },
props: {
as: { type: [Object, String], default: 'template' },
disabled: { type: [Boolean], default: false },
by: { type: [String, Function], nullable: true, default: null },
modelValue: {
type: [Object, String, Number, Boolean] as PropType<
object | string | number | boolean | null
>,
default: undefined,
},
defaultValue: {
type: [Object, String, Number, Boolean] as PropType<
object | string | number | boolean | null
>,
default: undefined,
},
form: { type: String, optional: true },
name: { type: String, optional: true },
nullable: { type: Boolean, default: false },
multiple: { type: [Boolean], default: false },
immediate: { type: [Boolean], default: false },
virtual: {
type: Object as PropType<null | {
options: unknown[]
disabled?: (value: unknown) => boolean
}>,
default: null,
},
},
inheritAttrs: false,
setup(props, { slots, attrs, emit }) {
let comboboxState = ref<StateDefinition['comboboxState']['value']>(ComboboxStates.Closed)
let labelRef = ref<StateDefinition['labelRef']['value']>(null)
let inputRef = ref<StateDefinition['inputRef']['value']>(null) as StateDefinition['inputRef']
let buttonRef = ref<StateDefinition['buttonRef']['value']>(null) as StateDefinition['buttonRef']
let optionsRef = ref<StateDefinition['optionsRef']['value']>(
null
) as StateDefinition['optionsRef']
let optionsPropsRef = ref<StateDefinition['optionsPropsRef']['value']>({
static: false,
hold: false,
}) as StateDefinition['optionsPropsRef']
let options = ref<StateDefinition['options']['value']>([])
let activeOptionIndex = ref<StateDefinition['activeOptionIndex']['value']>(null)
let activationTrigger = ref<StateDefinition['activationTrigger']['value']>(
ActivationTrigger.Other
)
let defaultToFirstOption = ref(false)
function adjustOrderedState(
adjustment: (
options: UnwrapNestedRefs<StateDefinition['options']['value']>
) => UnwrapNestedRefs<StateDefinition['options']['value']> = (i) => i
) {
let currentActiveOption =
activeOptionIndex.value !== null ? options.value[activeOptionIndex.value] : null
let list = adjustment(options.value.slice())
let sortedOptions =
list.length > 0 && list[0].dataRef.order.value !== null
? // Prefer sorting based on the `order`
list.sort((a, z) => a.dataRef.order.value! - z.dataRef.order.value!)
: // Fallback to much slower DOM order
sortByDomNode(list, (option) => dom(option.dataRef.domRef))
// If we inserted an option before the current active option then the active option index
// would be wrong. To fix this, we will re-lookup the correct index.
let adjustedActiveOptionIndex = currentActiveOption
? sortedOptions.indexOf(currentActiveOption)
: null
// Reset to `null` in case the currentActiveOption was removed.
if (adjustedActiveOptionIndex === -1) {
adjustedActiveOptionIndex = null
}
return {
options: sortedOptions,
activeOptionIndex: adjustedActiveOptionIndex,
}
}
let mode = computed(() => (props.multiple ? ValueMode.Multi : ValueMode.Single))
let nullable = computed(() => props.nullable)
let [directValue, theirOnChange] = useControllable(
computed(() => props.modelValue),
(value: unknown) => emit('update:modelValue', value),
computed(() => props.defaultValue)
)
let value = computed(() =>
directValue.value === undefined
? match(mode.value, {
[ValueMode.Multi]: [],
[ValueMode.Single]: undefined,
})
: directValue.value
)
let goToOptionRaf: ReturnType<typeof requestAnimationFrame> | null = null
let orderOptionsRaf: ReturnType<typeof requestAnimationFrame> | null = null
function onChange(value: unknown) {
return match(mode.value, {
[ValueMode.Single]() {
return theirOnChange?.(value)
},
[ValueMode.Multi]: () => {
let copy = toRaw(api.value.value as unknown[]).slice()
let raw = toRaw(value)
let idx = copy.findIndex((value) => api.compare(raw, toRaw(value)))
if (idx === -1) {
copy.push(raw)
} else {
copy.splice(idx, 1)
}
return theirOnChange?.(copy)
},
})
}
let virtualOptions = computed(() => props.virtual?.options)
watch([virtualOptions], ([newOptions], [oldOptions]) => {
if (!api.virtual.value) return
if (!newOptions) return
if (!oldOptions) return
if (activeOptionIndex.value !== null) {
let idx = newOptions.indexOf(oldOptions[activeOptionIndex.value])
if (idx !== -1) {
activeOptionIndex.value = idx
} else {
activeOptionIndex.value = null
}
}
})
let api: StateDefinition = {
comboboxState,
value,
mode,
compare(a: any, z: any) {
if (typeof props.by === 'string') {
let property = props.by as unknown as any
return a?.[property] === z?.[property]
}
if (props.by === null) {
return defaultComparator(a, z)
}
return props.by(a, z)
},
calculateIndex(value: any) {
if (api.virtual.value) {
if (props.by === null) {
return api.virtual.value!.options.indexOf(value)
} else {
return api.virtual.value!.options.findIndex((other) => api.compare(other, value))
}
} else {
return options.value.findIndex((other) => api.compare(other.dataRef.value, value))
}
},
defaultValue: computed(() => props.defaultValue),
nullable,
immediate: computed(() => props.immediate),
virtual: computed(() => {
return props.virtual
? {
options: props.virtual.options,
disabled: props.virtual.disabled ?? (() => false),
}
: null
}),
inputRef,
labelRef,
buttonRef,
optionsRef,
disabled: computed(() => props.disabled),
// @ts-expect-error dateRef types are incorrect due to unwrapped or wrapped refs
options,
change(value: unknown) {
theirOnChange(value as typeof props.modelValue)
},
activeOptionIndex: computed(() => {
if (
defaultToFirstOption.value &&
activeOptionIndex.value === null &&
(api.virtual.value ? api.virtual.value.options.length > 0 : options.value.length > 0)
) {
if (api.virtual.value) {
let localActiveOptionIndex = api.virtual.value.options.findIndex(
(option) => !api.virtual.value?.disabled(option)
)
if (localActiveOptionIndex !== -1) {
return localActiveOptionIndex
}
}
let localActiveOptionIndex = options.value.findIndex((option) => !option.dataRef.disabled)
if (localActiveOptionIndex !== -1) {
return localActiveOptionIndex
}
}
return activeOptionIndex.value
}),
activationTrigger,
optionsPropsRef,
closeCombobox() {
defaultToFirstOption.value = false
if (props.disabled) return
if (comboboxState.value === ComboboxStates.Closed) return
comboboxState.value = ComboboxStates.Closed
activeOptionIndex.value = null
},
openCombobox() {
defaultToFirstOption.value = true
if (props.disabled) return
if (comboboxState.value === ComboboxStates.Open) return
// Check if we have a selected value that we can make active
if (api.value.value) {
let idx = api.calculateIndex(api.value.value)
if (idx !== -1) {
activeOptionIndex.value = idx
}
}
comboboxState.value = ComboboxStates.Open
},
setActivationTrigger(trigger: ActivationTrigger) {
activationTrigger.value = trigger
},
goToOption(focus: Focus, idx?: number, trigger?: ActivationTrigger) {
defaultToFirstOption.value = false
if (goToOptionRaf !== null) {
cancelAnimationFrame(goToOptionRaf)
}
goToOptionRaf = requestAnimationFrame(() => {
if (props.disabled) return
if (
optionsRef.value &&
!optionsPropsRef.value.static &&
comboboxState.value === ComboboxStates.Closed
) {
return
}
if (api.virtual.value) {
activeOptionIndex.value =
focus === Focus.Specific
? idx!
: calculateActiveIndex(
{ focus: focus as Exclude<Focus, Focus.Specific> },
{
resolveItems: () => api.virtual.value!.options,
resolveActiveIndex: () => {
return (
api.activeOptionIndex.value ??
api.virtual.value!.options.findIndex(
(option) => !api.virtual.value?.disabled(option)
) ??
null
)
},
resolveDisabled: (item) => api.virtual.value!.disabled(item),
resolveId() {
throw new Error('Function not implemented.')
},
}
)
activationTrigger.value = trigger ?? ActivationTrigger.Other
return
}
let adjustedState = adjustOrderedState()
// It's possible that the activeOptionIndex is set to `null` internally, but
// this means that we will fallback to the first non-disabled option by default.
// We have to take this into account.
if (adjustedState.activeOptionIndex === null) {
let localActiveOptionIndex = adjustedState.options.findIndex(
(option) => !option.dataRef.disabled
)
if (localActiveOptionIndex !== -1) {
adjustedState.activeOptionIndex = localActiveOptionIndex
}
}
let nextActiveOptionIndex =
focus === Focus.Specific
? idx!
: calculateActiveIndex(
{ focus: focus as Exclude<Focus, Focus.Specific> },
{
resolveItems: () => adjustedState.options,
resolveActiveIndex: () => adjustedState.activeOptionIndex,
resolveId: (option) => option.id,
resolveDisabled: (option) => option.dataRef.disabled,
}
)
activeOptionIndex.value = nextActiveOptionIndex
activationTrigger.value = trigger ?? ActivationTrigger.Other
options.value = adjustedState.options
})
},
selectOption(id: string) {
let option = options.value.find((item) => item.id === id)
if (!option) return
let { dataRef } = option
onChange(dataRef.value)
},
selectActiveOption() {
if (api.activeOptionIndex.value === null) return
if (api.virtual.value) {
onChange(api.virtual.value.options[api.activeOptionIndex.value])
} else {
let { dataRef } = options.value[api.activeOptionIndex.value]
onChange(dataRef.value)
}
// It could happen that the `activeOptionIndex` stored in state is actually null,
// but we are getting the fallback active option back instead.
api.goToOption(Focus.Specific, api.activeOptionIndex.value)
},
registerOption(id: string, dataRef: ComputedRef<ComboboxOptionData>) {
let option = reactive({ id, dataRef }) as unknown as {
id: typeof id
dataRef: (typeof dataRef)['value']
}
if (api.virtual.value) {
options.value.push(option)
return
}
if (orderOptionsRaf) cancelAnimationFrame(orderOptionsRaf)
let adjustedState = adjustOrderedState((options) => {
options.push(option)
return options
})
// Check if we need to make the newly registered option active.
if (activeOptionIndex.value === null) {
if (api.isSelected(dataRef.value.value)) {
adjustedState.activeOptionIndex = adjustedState.options.indexOf(option)
}
}
options.value = adjustedState.options
activeOptionIndex.value = adjustedState.activeOptionIndex
activationTrigger.value = ActivationTrigger.Other
// If some of the DOM elements aren't ready yet, then we can retry in the next tick.
if (adjustedState.options.some((option) => !dom(option.dataRef.domRef))) {
orderOptionsRaf = requestAnimationFrame(() => {
let adjustedState = adjustOrderedState()
options.value = adjustedState.options
activeOptionIndex.value = adjustedState.activeOptionIndex
})
}
},
unregisterOption(id: string, active: boolean) {
if (goToOptionRaf !== null) {
cancelAnimationFrame(goToOptionRaf)
}
// When we are unregistering the currently active option, then we also have to make sure to
// reset the `defaultToFirstOption` flag, so that visually something is selected and the
// next time you press a key on your keyboard it will go to the proper next or previous
// option in the list.
//
// Since this was the active option and it could have been anywhere in the list, resetting
// to the very first option seems like a fine default. We _could_ be smarter about this by
// going to the previous / next item in list if we know the direction of the keyboard
// navigation, but that might be too complex/confusing from an end users perspective.
if (active) {
defaultToFirstOption.value = true
}
if (api.virtual.value) {
options.value = options.value.filter((option) => option.id !== id)
return
}
let adjustedState = adjustOrderedState((options) => {
let idx = options.findIndex((option) => option.id === id)
if (idx !== -1) options.splice(idx, 1)
return options
})
options.value = adjustedState.options
activeOptionIndex.value = adjustedState.activeOptionIndex
activationTrigger.value = ActivationTrigger.Other
},
isSelected(other) {
return match(mode.value, {
[ValueMode.Single]: () => api.compare(toRaw(api.value.value), toRaw(other)),
[ValueMode.Multi]: () =>
(toRaw(api.value.value) as unknown[]).some((option) =>
api.compare(toRaw(option), toRaw(other))
),
})
},
isActive(other) {
return activeOptionIndex.value === api.calculateIndex(other)
},
}
// Handle outside click
useOutsideClick(
[inputRef, buttonRef, optionsRef],
() => api.closeCombobox(),
computed(() => comboboxState.value === ComboboxStates.Open)
)
provide(ComboboxContext, api)
useOpenClosedProvider(
computed(() =>
match(comboboxState.value, {
[ComboboxStates.Open]: State.Open,
[ComboboxStates.Closed]: State.Closed,
})
)
)
let form = computed(() => dom(inputRef)?.closest('form'))
onMounted(() => {
watch(
[form],
() => {
if (!form.value) return
if (props.defaultValue === undefined) return
function handle() {
api.change(props.defaultValue)
}
form.value.addEventListener('reset', handle)
return () => {
form.value?.removeEventListener('reset', handle)
}
},
{ immediate: true }
)
})
return () => {
let { name, disabled, form, ...theirProps } = props
let slot = {
open: comboboxState.value === ComboboxStates.Open,
disabled,
activeIndex: api.activeOptionIndex.value,
activeOption:
api.activeOptionIndex.value === null
? null
: api.virtual.value
? api.virtual.value.options[api.activeOptionIndex.value ?? 0]
: api.options.value[api.activeOptionIndex.value]?.dataRef.value ?? null,
value: value.value,
}
return h(Fragment, [
...(name != null && value.value != null
? objectToFormEntries({ [name]: value.value }).map(([name, value]) => {
return h(
Hidden,
compact({
features: HiddenFeatures.Hidden,
key: name,
as: 'input',
type: 'hidden',
hidden: true,
readOnly: true,
form,
disabled,
name,
value,
})
)
})
: []),
render({
theirProps: {
...attrs,
...omit(theirProps, [
'by',
'defaultValue',
'immediate',
'modelValue',
'multiple',
'nullable',
'onUpdate:modelValue',
'virtual',
]),
},
ourProps: {},
slot,
slots,
attrs,
name: 'Combobox',
}),
])
}
},
})
// ---
export let ComboboxLabel = defineComponent({
name: 'ComboboxLabel',
props: {
as: { type: [Object, String], default: 'label' },
id: { type: String, default: () => `headlessui-combobox-label-${useId()}` },
},
setup(props, { attrs, slots }) {
let api = useComboboxContext('ComboboxLabel')
function handleClick() {
dom(api.inputRef)?.focus({ preventScroll: true })
}
return () => {
let slot = {
open: api.comboboxState.value === ComboboxStates.Open,
disabled: api.disabled.value,
}
let { id, ...theirProps } = props
let ourProps = { id, ref: api.labelRef, onClick: handleClick }
return render({
ourProps,
theirProps,
slot,
attrs,
slots,
name: 'ComboboxLabel',
})
}
},
})
// ---
export let ComboboxButton = defineComponent({
name: 'ComboboxButton',
props: {
as: { type: [Object, String], default: 'button' },
id: { type: String, default: () => `headlessui-combobox-button-${useId()}` },
},
setup(props, { attrs, slots, expose }) {
let api = useComboboxContext('ComboboxButton')
expose({ el: api.buttonRef, $el: api.buttonRef })
function handleClick(event: MouseEvent) {
if (api.disabled.value) return
if (api.comboboxState.value === ComboboxStates.Open) {
api.closeCombobox()
} else {
event.preventDefault()
api.openCombobox()
}
nextTick(() => dom(api.inputRef)?.focus({ preventScroll: true }))
}
function handleKeydown(event: KeyboardEvent) {
switch (event.key) {
// Ref: https://www.w3.org/WAI/ARIA/apg/patterns/menu/#keyboard-interaction-12
case Keys.ArrowDown:
event.preventDefault()
event.stopPropagation()
if (api.comboboxState.value === ComboboxStates.Closed) {
api.openCombobox()
}
nextTick(() => api.inputRef.value?.focus({ preventScroll: true }))
return
case Keys.ArrowUp:
event.preventDefault()
event.stopPropagation()
if (api.comboboxState.value === ComboboxStates.Closed) {
api.openCombobox()
nextTick(() => {
if (!api.value.value) {
api.goToOption(Focus.Last)
}
})
}
nextTick(() => api.inputRef.value?.focus({ preventScroll: true }))
return
case Keys.Escape:
if (api.comboboxState.value !== ComboboxStates.Open) return
event.preventDefault()
if (api.optionsRef.value && !api.optionsPropsRef.value.static) {
event.stopPropagation()
}
api.closeCombobox()
nextTick(() => api.inputRef.value?.focus({ preventScroll: true }))
return
}
}
let type = useResolveButtonType(
computed(() => ({ as: props.as, type: attrs.type })),
api.buttonRef
)
return () => {
let slot = {
open: api.comboboxState.value === ComboboxStates.Open,
disabled: api.disabled.value,
value: api.value.value,
}
let { id, ...theirProps } = props
let ourProps = {
ref: api.buttonRef,
id,
type: type.value,
tabindex: '-1',
'aria-haspopup': 'listbox',
'aria-controls': dom(api.optionsRef)?.id,
'aria-expanded': api.comboboxState.value === ComboboxStates.Open,
'aria-labelledby': api.labelRef.value ? [dom(api.labelRef)?.id, id].join(' ') : undefined,
disabled: api.disabled.value === true ? true : undefined,
onKeydown: handleKeydown,
onClick: handleClick,
}
return render({
ourProps,
theirProps,
slot,
attrs,
slots,
name: 'ComboboxButton',
})
}
},
})
// ---
export let ComboboxInput = defineComponent({
name: 'ComboboxInput',
props: {
as: { type: [Object, String], default: 'input' },
static: { type: Boolean, default: false },
unmount: { type: Boolean, default: true },
displayValue: { type: Function as PropType<(item: unknown) => string> },
defaultValue: { type: String, default: undefined },
id: { type: String, default: () => `headlessui-combobox-input-${useId()}` },
},
emits: {
change: (_value: Event & { target: HTMLInputElement }) => true,
},
setup(props, { emit, attrs, slots, expose }) {
let api = useComboboxContext('ComboboxInput')
let ownerDocument = computed(() => getOwnerDocument(dom(api.inputRef)))
let isTyping = { value: false }
expose({ el: api.inputRef, $el: api.inputRef })
function clear() {
api.change(null)
let options = dom(api.optionsRef)
if (options) {
options.scrollTop = 0
}
api.goToOption(Focus.Nothing)
}
// When a `displayValue` prop is given, we should use it to transform the current selected
// option(s) so that the format can be chosen by developers implementing this. This is useful if
// your data is an object and you just want to pick a certain property or want to create a dynamic
// value like `firstName + ' ' + lastName`.
//
// Note: This can also be used with multiple selected options, but this is a very simple transform
// which should always result in a string (since we are filling in the value of the text input),
// you don't have to use this at all, a more common UI is a "tag" based UI, which you can render
// yourself using the selected option(s).
let currentDisplayValue = computed(() => {
let value = api.value.value
if (!dom(api.inputRef)) return ''
if (typeof props.displayValue !== 'undefined' && value !== undefined) {
return props.displayValue(value as unknown) ?? ''
} else if (typeof value === 'string') {
return value
} else {
return ''
}
})
onMounted(() => {
// Syncing the input value has some rules attached to it to guarantee a smooth and expected user
// experience:
//
// - When a user is not typing in the input field, it is safe to update the input value based on
// the selected option(s). See `currentDisplayValue` computation from above.
// - The value can be updated when:
// - The `value` is set from outside of the component
// - The `value` is set when the user uses their keyboard (confirm via enter or space)
// - The `value` is set when the user clicks on a value to select it
// - The value will be reset to the current selected option(s), when:
// - The user is _not_ typing (otherwise you will loose your current state / query)
// - The user cancels the current changes:
// - By pressing `escape`
// - By clicking `outside` of the Combobox
watch(
[currentDisplayValue, api.comboboxState, ownerDocument],
([currentDisplayValue, state], [oldCurrentDisplayValue, oldState]) => {
// When the user is typing, we want to not touch the `input` at all. Especially when they
// are using an IME, we don't want to mess with the input at all.
if (isTyping.value) return
let input = dom(api.inputRef)
if (!input) return
if (oldState === ComboboxStates.Open && state === ComboboxStates.Closed) {
input.value = currentDisplayValue
} else if (currentDisplayValue !== oldCurrentDisplayValue) {
input.value = currentDisplayValue
}
// Once we synced the input value, we want to make sure the cursor is at the end of the
// input field. This makes it easier to continue typing and append to the query. We will
// bail out if the user is currently typing, because we don't want to mess with the cursor
// position while typing.
requestAnimationFrame(() => {
if (isTyping.value) return
if (!input) return
// Bail when the input is not the currently focused element. When it is not the focused
// element, and we call the `setSelectionRange`, then it will become the focused
// element which may be unwanted.
if (ownerDocument.value?.activeElement !== input) return