-
Notifications
You must be signed in to change notification settings - Fork 586
/
combobox.ts
730 lines (635 loc) · 20 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
import { autoUpdate, computePosition, flip, hide, size } from "@floating-ui/dom";
import { attr, Observable, observable, Updates } from "@microsoft/fast-element";
import { limit, uniqueId } from "@microsoft/fast-web-utilities";
import type { StaticallyComposableHTML } from "../utilities/template-helpers.js";
import type { FASTListboxOption } from "../listbox-option/listbox-option.js";
import { DelegatesARIAListbox } from "../listbox/listbox.js";
import { StartEnd } from "../patterns/start-end.js";
import type { StartEndOptions } from "../patterns/start-end.js";
import { applyMixins } from "../utilities/apply-mixins.js";
import { FormAssociatedCombobox } from "./combobox.form-associated.js";
import { ComboboxAutocomplete } from "./combobox.options.js";
/**
* Combobox configuration options
* @public
*/
export type ComboboxOptions = StartEndOptions<FASTCombobox> & {
indicator?: StaticallyComposableHTML<FASTCombobox>;
};
/**
* A Combobox Custom HTML Element.
* Implements the {@link https://w3c.github.io/aria-practices/#combobox | ARIA combobox }.
*
* @slot start - Content which can be provided before the input
* @slot end - Content which can be provided after the input
* @slot control - Used to replace the input element representing the combobox
* @slot indicator - The visual indicator representing the expanded state
* @slot - The default slot for the options
* @csspart control - The wrapper element containing the input area, including start and end
* @csspart selected-value - The input element representing the selected value
* @csspart indicator - The element wrapping the indicator slot
* @csspart listbox - The wrapper for the listbox slotted options
* @fires change - Fires a custom 'change' event when the value updates
*
* @public
*/
export class FASTCombobox extends FormAssociatedCombobox {
/**
* The internal value property.
*
* @internal
*/
private _value: string = "";
/**
* The autocomplete attribute.
*
* @public
* @remarks
* HTML Attribute: autocomplete
*/
@attr({ attribute: "autocomplete", mode: "fromView" })
autocomplete: ComboboxAutocomplete | undefined;
/**
* Reference to the internal text input element.
*
* @internal
*/
public control: HTMLInputElement;
/**
* Reference to the internal listbox element.
*
* @internal
*/
public listbox: HTMLDivElement;
/**
* The collection of currently filtered options.
*
* @public
*/
public filteredOptions: FASTListboxOption[] = [];
/**
* The current filter value.
*
* @internal
*/
private filter: string = "";
/**
* Reset the element to its first selectable option when its parent form is reset.
*
* @internal
*/
public formResetCallback(): void {
super.formResetCallback();
this.setDefaultSelectedOption();
if (!this.firstSelectedOption) {
this.value = this.initialValue ?? "";
return;
}
this.updateValue();
}
/** {@inheritDoc (FormAssociated:interface).validate} */
public validate(): void {
super.validate(this.control);
}
private get isAutocompleteInline(): boolean {
return (
this.autocomplete === ComboboxAutocomplete.inline || this.isAutocompleteBoth
);
}
private get isAutocompleteList(): boolean {
return this.autocomplete === ComboboxAutocomplete.list || this.isAutocompleteBoth;
}
private get isAutocompleteBoth(): boolean {
return this.autocomplete === ComboboxAutocomplete.both;
}
/**
* The unique id for the internal listbox element.
*
* @internal
*/
public listboxId: string = uniqueId("listbox-");
/**
* The open attribute.
*
* @public
* @remarks
* HTML Attribute: open
*/
@attr({ attribute: "open", mode: "boolean" })
public open: boolean = false;
/**
* Sets focus and synchronize ARIA attributes when the open property changes.
*
* @param prev - the previous open value
* @param next - the current open value
*
* @internal
*/
protected openChanged() {
if (this.open) {
this.ariaControls = this.listboxId;
this.ariaExpanded = "true";
Updates.enqueue(() => this.setPositioning());
this.focusAndScrollOptionIntoView();
// focus is directed to the element when `open` is changed programmatically
Updates.enqueue(() => this.focus());
return;
}
this.ariaControls = "";
this.ariaExpanded = "false";
}
/**
* The list of options.
*
* @public
* @remarks
* Overrides `Listbox.options`.
*/
public get options(): FASTListboxOption[] {
Observable.track(this, "options");
return this.filteredOptions.length ? this.filteredOptions : this._options;
}
public set options(value: FASTListboxOption[]) {
this._options = value;
Observable.notify(this, "options");
}
/**
* Sets the placeholder value of the element, generally used to provide a hint to the user.
* @public
* @remarks
* HTML Attribute: placeholder
* Using this attribute is not a valid substitute for a labeling element.
*/
@attr
public placeholder: string;
/**
* Updates the placeholder on the proxy element.
* @internal
*/
protected placeholderChanged(): void {
if (this.proxy instanceof HTMLInputElement) {
this.proxy.placeholder = this.placeholder;
}
}
/**
* The value property.
*
* @public
*/
public get value() {
Observable.track(this, "value");
return this._value;
}
public set value(next: string) {
const prev = `${this._value}`;
if (this.$fastController.isConnected && this.options) {
const selectedIndex = this.options.findIndex(
el => el.text.toLowerCase() === next.toLowerCase()
);
const prevSelectedValue = this.options[this.selectedIndex]?.text;
const nextSelectedValue = this.options[selectedIndex]?.text;
this.selectedIndex =
prevSelectedValue !== nextSelectedValue
? selectedIndex
: this.selectedIndex;
next = this.firstSelectedOption?.text || next;
}
if (prev !== next) {
this._value = next;
super.valueChanged(prev, next);
Observable.notify(this, "value");
}
}
/**
* Cleanup function for the listbox positioner.
*
* @public
*/
public cleanup: () => void;
/**
* Handle opening and closing the listbox when the combobox is clicked.
*
* @param e - the mouse event
* @internal
*/
public clickHandler(e: MouseEvent): boolean | void {
if (this.disabled) {
return;
}
if (this.open) {
const captured = (e.target as HTMLElement).closest(
`option,[role=option]`
) as FASTListboxOption | null;
if (!captured || captured.disabled) {
return;
}
this.selectedOptions = [captured];
this.control.value = captured.text;
this.clearSelectionRange();
this.updateValue(true);
}
this.open = !this.open;
if (this.open) {
this.control.focus();
}
return true;
}
public connectedCallback() {
super.connectedCallback();
if (this.value) {
this.initialValue = this.value;
}
}
/**
* Synchronize the `aria-disabled` property when the `disabled` property changes.
*
* @param prev - The previous disabled value
* @param next - The next disabled value
*
* @internal
*/
public disabledChanged(prev: boolean, next: boolean): void {
if (super.disabledChanged) {
super.disabledChanged(prev, next);
}
this.ariaDisabled = this.disabled ? "true" : "false";
}
public disconnectedCallback(): void {
this.cleanup?.();
super.disconnectedCallback();
}
/**
* Filter available options by text value.
*
* @public
*/
public filterOptions(): void {
if (!this.autocomplete || this.autocomplete === ComboboxAutocomplete.none) {
this.filter = "";
}
const filter = this.filter.toLowerCase();
this.filteredOptions = this._options.filter(o =>
o.text.toLowerCase().startsWith(this.filter.toLowerCase())
);
if (this.isAutocompleteList) {
if (!this.filteredOptions.length && !filter) {
this.filteredOptions = this._options;
}
this._options.forEach(o => {
o.hidden = !this.filteredOptions.includes(o);
});
}
}
/**
* Focus the control and scroll the first selected option into view.
*
* @internal
* @remarks
* Overrides: `Listbox.focusAndScrollOptionIntoView`
*/
protected focusAndScrollOptionIntoView(): void {
if (this.contains(document.activeElement)) {
this.control.focus();
if (this.firstSelectedOption) {
requestAnimationFrame(() => {
this.firstSelectedOption?.scrollIntoView({ block: "nearest" });
});
}
}
}
/**
* Handle focus state when the element or its children lose focus.
*
* @param e - The focus event
* @internal
*/
public focusoutHandler(e: FocusEvent): boolean | void {
this.updateValue();
if (!this.open) {
return true;
}
const focusTarget = e.relatedTarget as HTMLElement;
if (this.isSameNode(focusTarget)) {
this.focus();
return;
}
if (!this.options || !this.options.includes(focusTarget as FASTListboxOption)) {
this.open = false;
}
}
/**
* Handle content changes on the control input.
*
* @param e - the input event
* @internal
*/
public inputHandler(e: InputEvent): boolean | void {
this.filter = this.control.value;
this.filterOptions();
if (e.inputType === "deleteContentBackward" || !this.filter.length) {
return true;
}
if (this.isAutocompleteList && !this.open) {
this.open = true;
}
if (this.isAutocompleteInline && this.filteredOptions.length) {
this.selectedOptions = [this.filteredOptions[0]];
this.selectedIndex = this.options.indexOf(this.firstSelectedOption);
this.setInlineSelection();
}
return;
}
/**
* Handle keydown actions for listbox navigation.
*
* @param e - the keyboard event
* @internal
*/
public keydownHandler(e: Event & KeyboardEvent): boolean | void {
const key = e.key;
if (e.ctrlKey || e.shiftKey) {
return true;
}
switch (key) {
case "Enter": {
this.updateValue(true);
if (this.isAutocompleteInline) {
this.filter = this.value;
}
this.open = false;
this.clearSelectionRange();
break;
}
case "Escape": {
if (!this.isAutocompleteInline) {
this.selectedIndex = -1;
}
if (this.open) {
this.open = false;
break;
}
this.value = "";
this.control.value = "";
this.filter = "";
this.filterOptions();
break;
}
case "Tab": {
this.updateValue();
if (!this.open) {
return true;
}
e.preventDefault();
this.open = false;
break;
}
case "ArrowUp":
case "ArrowDown": {
this.filterOptions();
if (!this.open) {
this.open = true;
break;
}
if (this.filteredOptions.length > 0) {
super.keydownHandler(e);
}
if (this.isAutocompleteInline) {
this.updateValue();
this.setInlineSelection();
}
break;
}
default: {
return true;
}
}
}
/**
* Handle keyup actions for value input and text field manipulations.
*
* @param e - the keyboard event
* @internal
*/
public keyupHandler(e: KeyboardEvent): boolean | void {
const key = e.key;
switch (key) {
case "ArrowLeft":
case "ArrowRight":
case "Backspace":
case "Delete":
case "Home":
case "End": {
this.filter = this.control.value;
this.selectedIndex = -1;
this.filterOptions();
break;
}
}
}
/**
* Ensure that the selectedIndex is within the current allowable filtered range.
*
* @param prev - the previous selected index value
* @param next - the current selected index value
*
* @internal
*/
public selectedIndexChanged(prev: number | undefined, next: number): void {
if (this.$fastController.isConnected) {
next = limit(-1, this.options.length - 1, next);
// we only want to call the super method when the selectedIndex is in range
if (next !== this.selectedIndex) {
this.selectedIndex = next;
return;
}
super.selectedIndexChanged(prev, next);
}
}
/**
* Move focus to the previous selectable option.
*
* @internal
* @remarks
* Overrides `Listbox.selectPreviousOption`
*/
public selectPreviousOption(): void {
if (!this.disabled && this.selectedIndex >= 0) {
this.selectedIndex = this.selectedIndex - 1;
}
}
/**
* Set the default selected options at initialization or reset.
*
* @internal
* @remarks
* Overrides `Listbox.setDefaultSelectedOption`
*/
public setDefaultSelectedOption(): void {
if (this.$fastController.isConnected && this.options) {
const selectedIndex = this.options.findIndex(
el => el.getAttribute("selected") !== null || el.selected
);
this.selectedIndex = selectedIndex;
if (!this.dirtyValue && this.firstSelectedOption) {
this.value = this.firstSelectedOption.text;
} else {
this.value = "";
}
this.setSelectedOptions();
}
}
/**
* Focus and select the content of the control based on the first selected option.
*
* @param start - The index for the starting range
* @internal
*/
private setInlineSelection(): void {
if (this.firstSelectedOption) {
this.control.value = this.firstSelectedOption.text;
this.control.focus();
this.control.setSelectionRange(
this.filter.length,
this.control.value.length,
"backward"
);
}
}
/**
* Calculate and apply listbox positioning based on available viewport space.
*
* @public
*/
public setPositioning(): void {
if (this.$fastController.isConnected) {
this.cleanup = autoUpdate(this, this.listbox, async () => {
const { middlewareData, x, y } = await computePosition(
this,
this.listbox,
{
placement: "bottom",
strategy: "fixed",
middleware: [
flip(),
size({
apply: ({ availableHeight, rects }) => {
Object.assign(this.listbox.style, {
maxHeight: `${availableHeight}px`,
width: `${rects.reference.width}px`,
});
},
}),
hide(),
],
}
);
if (middlewareData.hide?.referenceHidden) {
this.open = false;
this.cleanup();
return;
}
Object.assign(this.listbox.style, {
position: "fixed",
top: "0",
left: "0",
transform: `translate(${x}px, ${y}px)`,
});
});
}
}
/**
* Ensure that the entire list of options is used when setting the selected property.
*
* @param prev - the previous list of selected options
* @param next - the current list of selected options
*
* @internal
* @remarks
* Overrides: `Listbox.selectedOptionsChanged`
*/
public selectedOptionsChanged(
prev: FASTListboxOption[] | undefined,
next: FASTListboxOption[]
): void {
if (this.$fastController.isConnected) {
this._options.forEach(o => {
o.selected = next.includes(o);
});
}
}
/**
* Synchronize the form-associated proxy and update the value property of the element.
*
* @param prev - the previous collection of slotted option elements
* @param next - the next collection of slotted option elements
*
* @internal
*/
public slottedOptionsChanged(prev: Element[] | undefined, next: Element[]): void {
super.slottedOptionsChanged(prev, next);
this.updateValue();
}
/**
* Sets the value and to match the first selected option.
*
* @param shouldEmit - if true, the change event will be emitted
*
* @internal
*/
private updateValue(shouldEmit?: boolean) {
if (this.$fastController.isConnected) {
this.value = this.firstSelectedOption?.text || this.control.value;
}
if (shouldEmit) {
this.$emit("change");
}
}
/**
* @internal
*/
private clearSelectionRange() {
const controlValueLength = this.control.value.length;
this.control.setSelectionRange(controlValueLength, controlValueLength);
}
}
/**
* Includes ARIA states and properties relating to the ARIA combobox role.
*
* @public
*/
export class DelegatesARIACombobox {
/**
* See {@link https://www.w3.org/TR/wai-aria-1.2/#aria-autocomplete} for more information.
*
* @public
* @remarks
* HTML Attribute: `aria-autocomplete`
*/
@observable
public ariaAutoComplete: "inline" | "list" | "both" | "none" | string | null;
/**
* See {@link https://www.w3.org/TR/wai-aria-1.2/#aria-controls} for more information.
*
* @public
* @remarks
* HTML Attribute: `aria-controls`
*/
@observable
public ariaControls: string | null;
}
/**
* Mark internal because exporting class and interface of the same name
* confuses API documenter.
* TODO: https://github.com/microsoft/fast/issues/3317
* @internal
*/
export interface DelegatesARIACombobox extends DelegatesARIAListbox {}
applyMixins(DelegatesARIACombobox, DelegatesARIAListbox);
/**
* Mark internal because exporting class and interface of the same name
* confuses API documenter.
* TODO: https://github.com/microsoft/fast/issues/3317
* @internal
*/
export interface FASTCombobox extends StartEnd, DelegatesARIACombobox {}
applyMixins(FASTCombobox, StartEnd, DelegatesARIACombobox);