/
listbox.ts
1006 lines (894 loc) · 29.7 KB
/
listbox.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
AfterContentInit,
ChangeDetectorRef,
ContentChildren,
Directive,
ElementRef,
forwardRef,
inject,
Input,
OnDestroy,
Output,
QueryList,
} from '@angular/core';
import {ActiveDescendantKeyManager, Highlightable, ListKeyManagerOption} from '@angular/cdk/a11y';
import {
A,
DOWN_ARROW,
END,
ENTER,
hasModifierKey,
HOME,
LEFT_ARROW,
RIGHT_ARROW,
SPACE,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {BooleanInput, coerceArray, coerceBooleanProperty} from '@angular/cdk/coercion';
import {SelectionModel} from '@angular/cdk/collections';
import {defer, merge, Observable, Subject} from 'rxjs';
import {filter, map, startWith, switchMap, takeUntil} from 'rxjs/operators';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {Directionality} from '@angular/cdk/bidi';
/** The next id to use for creating unique DOM IDs. */
let nextId = 0;
/**
* An implementation of SelectionModel that internally always represents the selection as a
* multi-selection. This is necessary so that we can recover the full selection if the user
* switches the listbox from single-selection to multi-selection after initialization.
*
* This selection model may report multiple selected values, even if it is in single-selection
* mode. It is up to the user (CdkListbox) to check for invalid selections.
*/
class ListboxSelectionModel<T> extends SelectionModel<T> {
constructor(
public multiple = false,
initiallySelectedValues?: T[],
emitChanges = true,
compareWith?: (o1: T, o2: T) => boolean,
) {
super(true, initiallySelectedValues, emitChanges, compareWith);
}
override isMultipleSelection(): boolean {
return this.multiple;
}
override select(...values: T[]) {
// The super class is always in multi-selection mode, so we need to override the behavior if
// this selection model actually belongs to a single-selection listbox.
if (this.multiple) {
return super.select(...values);
} else {
return super.setSelection(...values);
}
}
}
/** A selectable option in a listbox. */
@Directive({
selector: '[cdkOption]',
exportAs: 'cdkOption',
host: {
'role': 'option',
'class': 'cdk-option',
'[id]': 'id',
'[attr.aria-selected]': 'isSelected()',
'[attr.tabindex]': '_getTabIndex()',
'[attr.aria-disabled]': 'disabled',
'[class.cdk-option-active]': 'isActive()',
'(click)': '_clicked.next($event)',
'(focus)': '_handleFocus()',
},
})
export class CdkOption<T = unknown> implements ListKeyManagerOption, Highlightable, OnDestroy {
/** The id of the option's host element. */
@Input()
get id() {
return this._id || this._generatedId;
}
set id(value) {
this._id = value;
}
private _id: string;
private _generatedId = `cdk-option-${nextId++}`;
/** The value of this option. */
@Input('cdkOption') value: T;
/**
* The text used to locate this item during listbox typeahead. If not specified,
* the `textContent` of the item will be used.
*/
@Input('cdkOptionTypeaheadLabel') typeaheadLabel: string;
/** Whether this option is disabled. */
@Input('cdkOptionDisabled')
get disabled(): boolean {
return this.listbox.disabled || this._disabled;
}
set disabled(value: BooleanInput) {
this._disabled = coerceBooleanProperty(value);
}
private _disabled: boolean = false;
/** The tabindex of the option when it is enabled. */
@Input('tabindex')
get enabledTabIndex() {
return this._enabledTabIndex === undefined
? this.listbox.enabledTabIndex
: this._enabledTabIndex;
}
set enabledTabIndex(value) {
this._enabledTabIndex = value;
}
private _enabledTabIndex?: number | null;
/** The option's host element */
readonly element: HTMLElement = inject(ElementRef).nativeElement;
/** The parent listbox this option belongs to. */
protected readonly listbox: CdkListbox<T> = inject(CdkListbox);
/** Emits when the option is destroyed. */
protected destroyed = new Subject<void>();
/** Emits when the option is clicked. */
readonly _clicked = new Subject<MouseEvent>();
ngOnDestroy() {
this.destroyed.next();
this.destroyed.complete();
}
/** Whether this option is selected. */
isSelected() {
return this.listbox.isSelected(this);
}
/** Whether this option is active. */
isActive() {
return this.listbox.isActive(this);
}
/** Toggle the selected state of this option. */
toggle() {
this.listbox.toggle(this);
}
/** Select this option if it is not selected. */
select() {
this.listbox.select(this);
}
/** Deselect this option if it is selected. */
deselect() {
this.listbox.deselect(this);
}
/** Focus this option. */
focus() {
this.element.focus();
}
/** Get the label for this element which is required by the FocusableOption interface. */
getLabel() {
return (this.typeaheadLabel ?? this.element.textContent?.trim()) || '';
}
/**
* No-op implemented as a part of `Highlightable`.
* @docs-private
*/
setActiveStyles() {}
/**
* No-op implemented as a part of `Highlightable`.
* @docs-private
*/
setInactiveStyles() {}
/** Handle focus events on the option. */
protected _handleFocus() {
// Options can wind up getting focused in active descendant mode if the user clicks on them.
// In this case, we push focus back to the parent listbox to prevent an extra tab stop when
// the user performs a shift+tab.
if (this.listbox.useActiveDescendant) {
this.listbox._setActiveOption(this);
this.listbox.focus();
}
}
/** Get the tabindex for this option. */
protected _getTabIndex() {
if (this.listbox.useActiveDescendant || this.disabled) {
return -1;
}
return this.isActive() ? this.enabledTabIndex : -1;
}
}
@Directive({
selector: '[cdkListbox]',
exportAs: 'cdkListbox',
host: {
'role': 'listbox',
'class': 'cdk-listbox',
'[id]': 'id',
'[attr.tabindex]': '_getTabIndex()',
'[attr.aria-disabled]': 'disabled',
'[attr.aria-multiselectable]': 'multiple',
'[attr.aria-activedescendant]': '_getAriaActiveDescendant()',
'[attr.aria-orientation]': 'orientation',
'(focus)': '_handleFocus()',
'(keydown)': '_handleKeydown($event)',
'(focusout)': '_handleFocusOut($event)',
'(focusin)': '_handleFocusIn()',
},
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CdkListbox),
multi: true,
},
],
})
export class CdkListbox<T = unknown> implements AfterContentInit, OnDestroy, ControlValueAccessor {
/** The id of the option's host element. */
@Input()
get id() {
return this._id || this._generatedId;
}
set id(value) {
this._id = value;
}
private _id: string;
private _generatedId = `cdk-listbox-${nextId++}`;
/** The tabindex to use when the listbox is enabled. */
@Input('tabindex')
get enabledTabIndex() {
return this._enabledTabIndex === undefined ? 0 : this._enabledTabIndex;
}
set enabledTabIndex(value) {
this._enabledTabIndex = value;
}
private _enabledTabIndex?: number | null;
/** The value selected in the listbox, represented as an array of option values. */
@Input('cdkListboxValue')
get value(): readonly T[] {
return this._invalid ? [] : this.selectionModel.selected;
}
set value(value: readonly T[]) {
this._setSelection(value);
}
/**
* Whether the listbox allows multiple options to be selected. If the value switches from `true`
* to `false`, and more than one option is selected, all options are deselected.
*/
@Input('cdkListboxMultiple')
get multiple(): boolean {
return this.selectionModel.multiple;
}
set multiple(value: BooleanInput) {
this.selectionModel.multiple = coerceBooleanProperty(value);
if (this.options) {
this._updateInternalValue();
}
}
/** Whether the listbox is disabled. */
@Input('cdkListboxDisabled')
get disabled(): boolean {
return this._disabled;
}
set disabled(value: BooleanInput) {
this._disabled = coerceBooleanProperty(value);
}
private _disabled: boolean = false;
/** Whether the listbox will use active descendant or will move focus onto the options. */
@Input('cdkListboxUseActiveDescendant')
get useActiveDescendant(): boolean {
return this._useActiveDescendant;
}
set useActiveDescendant(shouldUseActiveDescendant: BooleanInput) {
this._useActiveDescendant = coerceBooleanProperty(shouldUseActiveDescendant);
}
private _useActiveDescendant: boolean = false;
/** The orientation of the listbox. Only affects keyboard interaction, not visual layout. */
@Input('cdkListboxOrientation')
get orientation() {
return this._orientation;
}
set orientation(value: 'horizontal' | 'vertical') {
this._orientation = value === 'horizontal' ? 'horizontal' : 'vertical';
if (value === 'horizontal') {
this.listKeyManager?.withHorizontalOrientation(this._dir?.value || 'ltr');
} else {
this.listKeyManager?.withVerticalOrientation();
}
}
private _orientation: 'horizontal' | 'vertical' = 'vertical';
/** The function used to compare option values. */
@Input('cdkListboxCompareWith')
get compareWith(): undefined | ((o1: T, o2: T) => boolean) {
return this.selectionModel.compareWith;
}
set compareWith(fn: undefined | ((o1: T, o2: T) => boolean)) {
this.selectionModel.compareWith = fn;
}
/**
* Whether the keyboard navigation should wrap when the user presses arrow down on the last item
* or arrow up on the first item.
*/
@Input('cdkListboxNavigationWrapDisabled')
get navigationWrapDisabled() {
return this._navigationWrapDisabled;
}
set navigationWrapDisabled(wrap: BooleanInput) {
this._navigationWrapDisabled = coerceBooleanProperty(wrap);
this.listKeyManager?.withWrap(!this._navigationWrapDisabled);
}
private _navigationWrapDisabled = false;
/** Whether keyboard navigation should skip over disabled items. */
@Input('cdkListboxNavigatesDisabledOptions')
get navigateDisabledOptions() {
return this._navigateDisabledOptions;
}
set navigateDisabledOptions(skip: BooleanInput) {
this._navigateDisabledOptions = coerceBooleanProperty(skip);
this.listKeyManager?.skipPredicate(
this._navigateDisabledOptions ? this._skipNonePredicate : this._skipDisabledPredicate,
);
}
private _navigateDisabledOptions = false;
/** Emits when the selected value(s) in the listbox change. */
@Output('cdkListboxValueChange') readonly valueChange = new Subject<ListboxValueChangeEvent<T>>();
/** The child options in this listbox. */
@ContentChildren(CdkOption, {descendants: true}) protected options: QueryList<CdkOption<T>>;
/** The selection model used by the listbox. */
protected selectionModel = new ListboxSelectionModel<T>();
/** The key manager that manages keyboard navigation for this listbox. */
protected listKeyManager: ActiveDescendantKeyManager<CdkOption<T>>;
/** Emits when the listbox is destroyed. */
protected readonly destroyed = new Subject<void>();
/** The host element of the listbox. */
protected readonly element: HTMLElement = inject(ElementRef).nativeElement;
/** The change detector for this listbox. */
protected readonly changeDetectorRef = inject(ChangeDetectorRef);
/** Whether the currently selected value in the selection model is invalid. */
private _invalid = false;
/** The last user-triggered option. */
private _lastTriggered: CdkOption<T> | null = null;
/** Callback called when the listbox has been touched */
private _onTouched = () => {};
/** Callback called when the listbox value changes */
private _onChange: (value: readonly T[]) => void = () => {};
/** Emits when an option has been clicked. */
private _optionClicked = defer(() =>
(this.options.changes as Observable<CdkOption<T>[]>).pipe(
startWith(this.options),
switchMap(options =>
merge(...options.map(option => option._clicked.pipe(map(event => ({option, event}))))),
),
),
);
/** The directionality of the page. */
private readonly _dir = inject(Directionality, {optional: true});
/** A predicate that skips disabled options. */
private readonly _skipDisabledPredicate = (option: CdkOption<T>) => option.disabled;
/** A predicate that does not skip any options. */
private readonly _skipNonePredicate = () => false;
/** Whether the listbox currently has focus. */
private _hasFocus = false;
ngAfterContentInit() {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
this._verifyNoOptionValueCollisions();
this._verifyOptionValues();
}
this._initKeyManager();
// Update the internal value whenever the options or the model value changes.
merge(this.selectionModel.changed, this.options.changes)
.pipe(startWith(null), takeUntil(this.destroyed))
.subscribe(() => this._updateInternalValue());
this._optionClicked
.pipe(
filter(({option}) => !option.disabled),
takeUntil(this.destroyed),
)
.subscribe(({option, event}) => this._handleOptionClicked(option, event));
}
ngOnDestroy() {
this.listKeyManager?.destroy();
this.destroyed.next();
this.destroyed.complete();
}
/**
* Toggle the selected state of the given option.
* @param option The option to toggle
*/
toggle(option: CdkOption<T>) {
this.toggleValue(option.value);
}
/**
* Toggle the selected state of the given value.
* @param value The value to toggle
*/
toggleValue(value: T) {
if (this._invalid) {
this.selectionModel.clear(false);
}
this.selectionModel.toggle(value);
}
/**
* Select the given option.
* @param option The option to select
*/
select(option: CdkOption<T>) {
this.selectValue(option.value);
}
/**
* Select the given value.
* @param value The value to select
*/
selectValue(value: T) {
if (this._invalid) {
this.selectionModel.clear(false);
}
this.selectionModel.select(value);
}
/**
* Deselect the given option.
* @param option The option to deselect
*/
deselect(option: CdkOption<T>) {
this.deselectValue(option.value);
}
/**
* Deselect the given value.
* @param value The value to deselect
*/
deselectValue(value: T) {
if (this._invalid) {
this.selectionModel.clear(false);
}
this.selectionModel.deselect(value);
}
/**
* Set the selected state of all options.
* @param isSelected The new selected state to set
*/
setAllSelected(isSelected: boolean) {
if (!isSelected) {
this.selectionModel.clear();
} else {
if (this._invalid) {
this.selectionModel.clear(false);
}
this.selectionModel.select(...this.options.map(option => option.value));
}
}
/**
* Get whether the given option is selected.
* @param option The option to get the selected state of
*/
isSelected(option: CdkOption<T>) {
return this.isValueSelected(option.value);
}
/**
* Get whether the given option is active.
* @param option The option to get the active state of
*/
isActive(option: CdkOption<T>): boolean {
return !!(this.listKeyManager?.activeItem === option);
}
/**
* Get whether the given value is selected.
* @param value The value to get the selected state of
*/
isValueSelected(value: T) {
if (this._invalid) {
return false;
}
return this.selectionModel.isSelected(value);
}
/**
* Registers a callback to be invoked when the listbox's value changes from user input.
* @param fn The callback to register
* @docs-private
*/
registerOnChange(fn: (value: readonly T[]) => void): void {
this._onChange = fn;
}
/**
* Registers a callback to be invoked when the listbox is blurred by the user.
* @param fn The callback to register
* @docs-private
*/
registerOnTouched(fn: () => {}): void {
this._onTouched = fn;
}
/**
* Sets the listbox's value.
* @param value The new value of the listbox
* @docs-private
*/
writeValue(value: readonly T[]): void {
this._setSelection(value);
this._verifyOptionValues();
}
/**
* Sets the disabled state of the listbox.
* @param isDisabled The new disabled state
* @docs-private
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
/** Focus the listbox's host element. */
focus() {
this.element.focus();
}
/**
* Triggers the given option in response to user interaction.
* - In single selection mode: selects the option and deselects any other selected option.
* - In multi selection mode: toggles the selected state of the option.
* @param option The option to trigger
*/
protected triggerOption(option: CdkOption<T> | null) {
if (option && !option.disabled) {
this._lastTriggered = option;
const changed = this.multiple
? this.selectionModel.toggle(option.value)
: this.selectionModel.select(option.value);
if (changed) {
this._onChange(this.value);
this.valueChange.next({
value: this.value,
listbox: this,
option: option,
});
}
}
}
/**
* Trigger the given range of options in response to user interaction.
* Should only be called in multi-selection mode.
* @param trigger The option that was triggered
* @param from The start index of the options to toggle
* @param to The end index of the options to toggle
* @param on Whether to toggle the option range on
*/
protected triggerRange(trigger: CdkOption<T> | null, from: number, to: number, on: boolean) {
if (this.disabled || (trigger && trigger.disabled)) {
return;
}
this._lastTriggered = trigger;
const isEqual = this.compareWith ?? Object.is;
const updateValues = [...this.options]
.slice(Math.max(0, Math.min(from, to)), Math.min(this.options.length, Math.max(from, to) + 1))
.filter(option => !option.disabled)
.map(option => option.value);
const selected = [...this.value];
for (const updateValue of updateValues) {
const selectedIndex = selected.findIndex(selectedValue =>
isEqual(selectedValue, updateValue),
);
if (on && selectedIndex === -1) {
selected.push(updateValue);
} else if (!on && selectedIndex !== -1) {
selected.splice(selectedIndex, 1);
}
}
let changed = this.selectionModel.setSelection(...selected);
if (changed) {
this._onChange(this.value);
this.valueChange.next({
value: this.value,
listbox: this,
option: trigger,
});
}
}
/**
* Sets the given option as active.
* @param option The option to make active
*/
_setActiveOption(option: CdkOption<T>) {
this.listKeyManager.setActiveItem(option);
}
/** Called when the listbox receives focus. */
protected _handleFocus() {
if (!this.useActiveDescendant) {
if (this.selectionModel.selected.length > 0) {
this._setNextFocusToSelectedOption();
} else {
this.listKeyManager.setNextItemActive();
}
this._focusActiveOption();
}
}
/** Called when the user presses keydown on the listbox. */
protected _handleKeydown(event: KeyboardEvent) {
if (this._disabled) {
return;
}
const {keyCode} = event;
const previousActiveIndex = this.listKeyManager.activeItemIndex;
const ctrlKeys = ['ctrlKey', 'metaKey'] as const;
if (this.multiple && keyCode === A && hasModifierKey(event, ...ctrlKeys)) {
// Toggle all options off if they're all selected, otherwise toggle them all on.
this.triggerRange(
null,
0,
this.options.length - 1,
this.options.length !== this.value.length,
);
event.preventDefault();
return;
}
if (
this.multiple &&
(keyCode === SPACE || keyCode === ENTER) &&
hasModifierKey(event, 'shiftKey')
) {
if (this.listKeyManager.activeItem && this.listKeyManager.activeItemIndex != null) {
this.triggerRange(
this.listKeyManager.activeItem,
this._getLastTriggeredIndex() ?? this.listKeyManager.activeItemIndex,
this.listKeyManager.activeItemIndex,
!this.listKeyManager.activeItem.isSelected(),
);
}
event.preventDefault();
return;
}
if (
this.multiple &&
keyCode === HOME &&
hasModifierKey(event, ...ctrlKeys) &&
hasModifierKey(event, 'shiftKey')
) {
const trigger = this.listKeyManager.activeItem;
if (trigger) {
const from = this.listKeyManager.activeItemIndex!;
this.listKeyManager.setFirstItemActive();
this.triggerRange(
trigger,
from,
this.listKeyManager.activeItemIndex!,
!trigger.isSelected(),
);
}
event.preventDefault();
return;
}
if (
this.multiple &&
keyCode === END &&
hasModifierKey(event, ...ctrlKeys) &&
hasModifierKey(event, 'shiftKey')
) {
const trigger = this.listKeyManager.activeItem;
if (trigger) {
const from = this.listKeyManager.activeItemIndex!;
this.listKeyManager.setLastItemActive();
this.triggerRange(
trigger,
from,
this.listKeyManager.activeItemIndex!,
!trigger.isSelected(),
);
}
event.preventDefault();
return;
}
if (keyCode === SPACE || keyCode === ENTER) {
this.triggerOption(this.listKeyManager.activeItem);
event.preventDefault();
return;
}
const isNavKey =
keyCode === UP_ARROW ||
keyCode === DOWN_ARROW ||
keyCode === LEFT_ARROW ||
keyCode === RIGHT_ARROW ||
keyCode === HOME ||
keyCode === END;
this.listKeyManager.onKeydown(event);
// Will select an option if shift was pressed while navigating to the option
if (isNavKey && event.shiftKey && previousActiveIndex !== this.listKeyManager.activeItemIndex) {
this.triggerOption(this.listKeyManager.activeItem);
}
}
/** Called when a focus moves into the listbox. */
protected _handleFocusIn() {
// Note that we use a `focusin` handler for this instead of the existing `focus` handler,
// because focus won't land on the listbox if `useActiveDescendant` is enabled.
this._hasFocus = true;
}
/**
* Called when the focus leaves an element in the listbox.
* @param event The focusout event
*/
protected _handleFocusOut(event: FocusEvent) {
const otherElement = event.relatedTarget as Element;
if (this.element !== otherElement && !this.element.contains(otherElement)) {
this._onTouched();
this._hasFocus = false;
this._setNextFocusToSelectedOption();
}
}
/** Get the id of the active option if active descendant is being used. */
protected _getAriaActiveDescendant(): string | null | undefined {
return this._useActiveDescendant ? this.listKeyManager?.activeItem?.id : null;
}
/** Get the tabindex for the listbox. */
protected _getTabIndex() {
if (this.disabled) {
return -1;
}
return this.useActiveDescendant || !this.listKeyManager.activeItem ? this.enabledTabIndex : -1;
}
/** Initialize the key manager. */
private _initKeyManager() {
this.listKeyManager = new ActiveDescendantKeyManager(this.options)
.withWrap(!this._navigationWrapDisabled)
.withTypeAhead()
.withHomeAndEnd()
.withAllowedModifierKeys(['shiftKey'])
.skipPredicate(
this._navigateDisabledOptions ? this._skipNonePredicate : this._skipDisabledPredicate,
);
if (this.orientation === 'vertical') {
this.listKeyManager.withVerticalOrientation();
} else {
this.listKeyManager.withHorizontalOrientation(this._dir?.value || 'ltr');
}
if (this.selectionModel.selected.length) {
Promise.resolve().then(() => this._setNextFocusToSelectedOption());
}
this.listKeyManager.change.subscribe(() => this._focusActiveOption());
}
/** Focus the active option. */
private _focusActiveOption() {
if (!this.useActiveDescendant) {
this.listKeyManager.activeItem?.focus();
}
this.changeDetectorRef.markForCheck();
}
/**
* Set the selected values.
* @param value The list of new selected values.
*/
private _setSelection(value: readonly T[]) {
if (this._invalid) {
this.selectionModel.clear(false);
}
this.selectionModel.setSelection(...this._coerceValue(value));
if (!this._hasFocus) {
this._setNextFocusToSelectedOption();
}
}
/** Sets the first selected option as first in the keyboard focus order. */
private _setNextFocusToSelectedOption() {
// Null check the options since they only get defined after `ngAfterContentInit`.
const selected = this.options?.find(option => option.isSelected());
if (selected) {
this.listKeyManager.updateActiveItem(selected);
}
}
/** Update the internal value of the listbox based on the selection model. */
private _updateInternalValue() {
const indexCache = new Map<T, number>();
this.selectionModel.sort((a: T, b: T) => {
const aIndex = this._getIndexForValue(indexCache, a);
const bIndex = this._getIndexForValue(indexCache, b);
return aIndex - bIndex;
});
const selected = this.selectionModel.selected;
this._invalid =
(!this.multiple && selected.length > 1) || !!this._getInvalidOptionValues(selected).length;
this.changeDetectorRef.markForCheck();
}
/**
* Gets the index of the given value in the given list of options.
* @param cache The cache of indices found so far
* @param value The value to find
* @return The index of the value in the options list
*/
private _getIndexForValue(cache: Map<T, number>, value: T) {
const isEqual = this.compareWith || Object.is;
if (!cache.has(value)) {
let index = -1;
for (let i = 0; i < this.options.length; i++) {
if (isEqual(value, this.options.get(i)!.value)) {
index = i;
break;
}
}
cache.set(value, index);
}
return cache.get(value)!;
}
/**
* Handle the user clicking an option.
* @param option The option that was clicked.
*/
private _handleOptionClicked(option: CdkOption<T>, event: MouseEvent) {
event.preventDefault();
this.listKeyManager.setActiveItem(option);
if (event.shiftKey && this.multiple) {
this.triggerRange(
option,
this._getLastTriggeredIndex() ?? this.listKeyManager.activeItemIndex!,
this.listKeyManager.activeItemIndex!,
!option.isSelected(),
);
} else {
this.triggerOption(option);
}
}
/** Verifies that no two options represent the same value under the compareWith function. */
private _verifyNoOptionValueCollisions() {
this.options.changes.pipe(startWith(this.options), takeUntil(this.destroyed)).subscribe(() => {
const isEqual = this.compareWith ?? Object.is;
for (let i = 0; i < this.options.length; i++) {
const option = this.options.get(i)!;
let duplicate: CdkOption<T> | null = null;
for (let j = i + 1; j < this.options.length; j++) {
const other = this.options.get(j)!;
if (isEqual(option.value, other.value)) {
duplicate = other;
break;
}
}
if (duplicate) {
// TODO(mmalerba): Link to docs about this.
if (this.compareWith) {
console.warn(
`Found multiple CdkOption representing the same value under the given compareWith function`,
{
option1: option.element,
option2: duplicate.element,
compareWith: this.compareWith,
},
);
} else {
console.warn(`Found multiple CdkOption with the same value`, {
option1: option.element,
option2: duplicate.element,
});
}
return;
}
}
});
}
/** Verifies that the option values are valid. */
private _verifyOptionValues() {
if (this.options && (typeof ngDevMode === 'undefined' || ngDevMode)) {
const selected = this.selectionModel.selected;
const invalidValues = this._getInvalidOptionValues(selected);
if (!this.multiple && selected.length > 1) {
throw Error('Listbox cannot have more than one selected value in multi-selection mode.');
}
if (invalidValues.length) {
throw Error('Listbox has selected values that do not match any of its options.');
}
}
}
/**
* Coerces a value into an array representing a listbox selection.
* @param value The value to coerce
* @return An array
*/
private _coerceValue(value: readonly T[]) {
return value == null ? [] : coerceArray(value);
}
/**
* Get the sublist of values that do not represent valid option values in this listbox.
* @param values The list of values
* @return The sublist of values that are not valid option values
*/
private _getInvalidOptionValues(values: readonly T[]) {
const isEqual = this.compareWith || Object.is;
const validValues = (this.options || []).map(option => option.value);
return values.filter(value => !validValues.some(validValue => isEqual(value, validValue)));
}
/** Get the index of the last triggered option. */
private _getLastTriggeredIndex() {
const index = this.options.toArray().indexOf(this._lastTriggered!);
return index === -1 ? null : index;
}
}
/** Change event that is fired whenever the value of the listbox changes. */
export interface ListboxValueChangeEvent<T> {
/** The new value of the listbox. */
readonly value: readonly T[];