-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathComboBox.ts
1411 lines (1167 loc) · 38.1 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 UI5Element from "@ui5/webcomponents-base/dist/UI5Element.js";
import { renderFinished } from "@ui5/webcomponents-base/dist/Render.js";
import customElement from "@ui5/webcomponents-base/dist/decorators/customElement.js";
import property from "@ui5/webcomponents-base/dist/decorators/property.js";
import event from "@ui5/webcomponents-base/dist/decorators/event.js";
import slot from "@ui5/webcomponents-base/dist/decorators/slot.js";
import litRender from "@ui5/webcomponents-base/dist/renderer/LitRenderer.js";
import ValueState from "@ui5/webcomponents-base/dist/types/ValueState.js";
import { isPhone, isAndroid } from "@ui5/webcomponents-base/dist/Device.js";
import Integer from "@ui5/webcomponents-base/dist/types/Integer.js";
import InvisibleMessageMode from "@ui5/webcomponents-base/dist/types/InvisibleMessageMode.js";
import { getEffectiveAriaLabelText } from "@ui5/webcomponents-base/dist/util/AriaLabelHelper.js";
import announce from "@ui5/webcomponents-base/dist/util/InvisibleMessage.js";
import { getScopedVarName } from "@ui5/webcomponents-base/dist/CustomElementsScope.js";
import "@ui5/webcomponents-icons/dist/slim-arrow-down.js";
import "@ui5/webcomponents-icons/dist/decline.js";
import "@ui5/webcomponents-icons/dist/not-editable.js";
import "@ui5/webcomponents-icons/dist/error.js";
import "@ui5/webcomponents-icons/dist/alert.js";
import "@ui5/webcomponents-icons/dist/sys-enter-2.js";
import "@ui5/webcomponents-icons/dist/information.js";
import type I18nBundle from "@ui5/webcomponents-base/dist/i18nBundle.js";
import { getI18nBundle } from "@ui5/webcomponents-base/dist/i18nBundle.js";
import { submitForm } from "@ui5/webcomponents-base/dist/features/InputElementsFormSupport.js";
import type { IFormInputElement } from "@ui5/webcomponents-base/dist/features/InputElementsFormSupport.js";
import {
isBackSpace,
isDelete,
isShow,
isUp,
isDown,
isEnter,
isEscape,
isTabNext,
isTabPrevious,
isPageUp,
isPageDown,
isHome,
isEnd,
} from "@ui5/webcomponents-base/dist/Keys.js";
import type { IIcon } from "./Icon.js";
import * as Filters from "./Filters.js";
import {
VALUE_STATE_SUCCESS,
VALUE_STATE_ERROR,
VALUE_STATE_WARNING,
VALUE_STATE_INFORMATION,
VALUE_STATE_TYPE_SUCCESS,
VALUE_STATE_TYPE_INFORMATION,
VALUE_STATE_TYPE_ERROR,
VALUE_STATE_TYPE_WARNING,
INPUT_SUGGESTIONS_TITLE,
SELECT_OPTIONS,
LIST_ITEM_POSITION,
LIST_ITEM_GROUP_HEADER,
INPUT_CLEAR_ICON_ACC_NAME,
FORM_TEXTFIELD_REQUIRED,
} from "./generated/i18n/i18n-defaults.js";
// Templates
import ComboBoxTemplate from "./generated/templates/ComboBoxTemplate.lit.js";
// Styles
import ComboBoxCss from "./generated/themes/ComboBox.css.js";
import ComboBoxPopoverCss from "./generated/themes/ComboBoxPopover.css.js";
import ResponsivePopoverCommonCss from "./generated/themes/ResponsivePopoverCommon.css.js";
import ValueStateMessageCss from "./generated/themes/ValueStateMessage.css.js";
import SuggestionsCss from "./generated/themes/Suggestions.css.js";
import ComboBoxItem from "./ComboBoxItem.js";
import Icon from "./Icon.js";
import Popover from "./Popover.js";
import ResponsivePopover from "./ResponsivePopover.js";
import List from "./List.js";
import type { ListItemClickEventDetail } from "./List.js";
import BusyIndicator from "./BusyIndicator.js";
import Button from "./Button.js";
import ListItemStandard from "./ListItemStandard.js";
import ComboBoxItemGroup, { isInstanceOfComboBoxItemGroup } from "./ComboBoxItemGroup.js";
import ListItemGroup from "./ListItemGroup.js";
import ListItemGroupHeader from "./ListItemGroupHeader.js";
import ComboBoxFilter from "./types/ComboBoxFilter.js";
import PopoverHorizontalAlign from "./types/PopoverHorizontalAlign.js";
import Input from "./Input.js";
import type { InputEventDetail } from "./Input.js";
import SuggestionItem from "./SuggestionItem.js";
const SKIP_ITEMS_SIZE = 10;
/**
* Interface for components that may be slotted inside a `ui5-combobox`
* @public
*/
interface IComboBoxItem extends UI5Element {
text: string,
focused: boolean,
isGroupItem?: boolean,
selected?: boolean,
additionalText?: string,
stableDomRef: string,
_isVisible?: boolean,
items?: Array<IComboBoxItem>
}
type ValueStateAnnouncement = Record<Exclude<ValueState, ValueState.None>, string>;
type ValueStateTypeAnnouncement = Record<Exclude<ValueState, ValueState.None>, string>;
type ComboBoxListItem = ListItemStandard & {
mappedItem: ComboBoxItem
};
enum ValueStateIconMapping {
Negative = "error",
Critical = "alert",
Positive = "sys-enter-2",
Information = "information",
}
type ComboBoxSelectionChangeEventDetail = {
item: ComboBoxItem,
};
/**
* @class
*
* ### Overview
*
* The `ui5-combobox` component represents a drop-down menu with a list of the available options and a text input field to narrow down the options.
*
* It is commonly used to enable users to select an option from a predefined list.
*
* ### Structure
* The `ui5-combobox` consists of the following elements:
*
* - Input field - displays the selected option or a custom user entry. Users can type to narrow down the list or enter their own value.
* - Drop-down arrow - expands\collapses the option list.
* - Option list - the list of available options.
*
* ### Keyboard Handling
*
* The `ui5-combobox` provides advanced keyboard handling.
*
* - [F4], [Alt]+[Up], or [Alt]+[Down] - Toggles the picker.
* - [Escape] - Closes the picker, if open. If closed, cancels changes and reverts the typed in value.
* - [Enter] or [Return] - If picker is open, takes over the currently selected item and closes it.
* - [Down] - Selects the next matching item in the picker.
* - [Up] - Selects the previous matching item in the picker.
* - [Page Down] - Moves selection down by page size (10 items by default).
* - [Page Up] - Moves selection up by page size (10 items by default).
* - [Home] - If focus is in the ComboBox, moves cursor at the beginning of text. If focus is in the picker, selects the first item.
* - [End] - If focus is in the ComboBox, moves cursor at the end of text. If focus is in the picker, selects the last item.
*
* ### ES6 Module Import
*
* `import "@ui5/webcomponents/dist/ComboBox.js";`
* @constructor
* @extends UI5Element
* @public
* @since 1.0.0-rc.6
*/
@customElement({
tag: "ui5-combobox",
languageAware: true,
formAssociated: true,
renderer: litRender,
styles: [
ComboBoxCss,
ResponsivePopoverCommonCss,
ValueStateMessageCss,
ComboBoxPopoverCss,
SuggestionsCss,
],
template: ComboBoxTemplate,
dependencies: [
ComboBoxItem,
Icon,
ResponsivePopover,
List,
BusyIndicator,
Button,
ListItemStandard,
ListItemGroup,
ListItemGroupHeader,
Popover,
ComboBoxItemGroup,
Input,
SuggestionItem,
],
})
/**
* Fired when the input operation has finished by pressing Enter, focusout or an item is selected.
* @public
*/
@event("change")
/**
* Fired when typing in input or clear icon is pressed.
*
* **Note:** filterValue property is updated, input is changed.
* @public
*/
@event("input")
/**
* Fired when selection is changed by user interaction
* @param {IComboBoxItem} item item to be selected.
* @public
*/
@event<ComboBoxSelectionChangeEventDetail>("selection-change", {
detail: {
/**
* @public
*/
item: { type: HTMLElement },
},
})
class ComboBox extends UI5Element implements IFormInputElement {
/**
* Defines the value of the component.
* @default ""
* @formEvents change input
* @formProperty
* @public
*/
@property()
value!: string;
/**
* Determines the name by which the component will be identified upon submission in an HTML form.
*
* **Note:** This property is only applicable within the context of an HTML Form element.
* @default ""
* @public
* @since 2.0.0
*/
@property()
name!: string;
/**
* Defines whether the value will be autocompleted to match an item
* @default false
* @public
* @since 1.19.0
*/
@property({ type: Boolean })
noTypeahead!: boolean;
/**
* Defines the "live" value of the component.
*
* **Note:** If we have an item e.g. "Bulgaria", "B" is typed, "ulgaria" is typed ahead, value will be "Bulgaria", filterValue will be "B".
*
* **Note:** Initially the filter value is synced with value.
* @default ""
* @private
*/
@property()
filterValue!: string;
/**
* Defines a short hint intended to aid the user with data entry when the
* component has no value.
* @default ""
* @public
*/
@property()
placeholder!: string;
/**
* Defines whether the component is in disabled state.
*
* **Note:** A disabled component is completely noninteractive.
* @default false
* @public
*/
@property({ type: Boolean })
disabled!: boolean;
/**
* Defines the value state of the component.
* @default "None"
* @public
*/
@property({ type: ValueState, defaultValue: ValueState.None })
valueState!: `${ValueState}`;
/**
* Defines whether the component is read-only.
*
* **Note:** A read-only component is not editable,
* but still provides visual feedback upon user interaction.
* @default false
* @public
*/
@property({ type: Boolean })
readonly!: boolean;
/**
* Defines whether the component is required.
* @default false
* @public
*/
@property({ type: Boolean })
required!: boolean;
/**
* Indicates whether a loading indicator should be shown in the picker.
* @default false
* @public
*/
@property({ type: Boolean })
loading!: boolean;
/**
* Defines the filter type of the component.
* @default "StartsWithPerTerm"
* @public
*/
@property({ type: ComboBoxFilter, defaultValue: ComboBoxFilter.StartsWithPerTerm })
filter!: `${ComboBoxFilter}`;
/**
* Defines whether the clear icon of the combobox will be shown.
* @default false
* @public
* @since 1.20.1
*/
@property({ type: Boolean })
showClearIcon!: boolean;
/**
* Indicates whether the input is focssed
* @private
*/
@property({ type: Boolean })
focused!: boolean;
/**
* Indicates whether the visual focus is on the value state header
* @private
*/
@property({ type: Boolean })
_isValueStateFocused!: boolean;
/**
* Defines the accessible ARIA name of the component.
* @default ""
* @public
* @since 1.0.0-rc.15
*/
@property()
accessibleName!: string;
/**
* Receives id(or many ids) of the elements that label the component
* @default ""
* @public
* @since 1.0.0-rc.15
*/
@property()
accessibleNameRef!: string;
@property({ type: Boolean, noAttribute: true })
_iconPressed!: boolean;
@property({ type: Object, noAttribute: true, multiple: true })
_filteredItems!: Array<IComboBoxItem>;
@property({ validator: Integer, noAttribute: true })
_listWidth!: number;
@property({ type: Boolean, noAttribute: true })
_effectiveShowClearIcon!: boolean;
/**
* Defines the component items.
* @public
*/
@slot({ type: HTMLElement, "default": true, invalidateOnChildChange: true })
items!: Array<IComboBoxItem>;
/**
* Defines the value state message that will be displayed as pop up under the component.
* The value state message slot should contain only one root element.
*
* **Note:** If not specified, a default text (in the respective language) will be displayed.
*
* **Note:** The `valueStateMessage` would be displayed,
* when the `ui5-combobox` is in `Information`, `Warning` or `Error` value state.
* @since 1.0.0-rc.9
* @public
*/
@slot()
valueStateMessage!: Array<HTMLElement>;
/**
* Defines the icon to be displayed in the input field.
* @public
* @since 1.0.0-rc.9
*/
@slot()
icon!: Array<IIcon>;
_initialRendering: boolean;
_itemFocused: boolean;
// used only for Safari fix (check onAfterRendering)
_autocomplete: boolean;
_isKeyNavigation: boolean;
_selectionPerformed: boolean;
_lastValue: string;
_selectedItemText: string;
_userTypedValue: string;
responsivePopover?: ResponsivePopover;
valueStatePopover?: Popover;
static i18nBundle: I18nBundle;
get formValidityMessage() {
return ComboBox.i18nBundle.getText(FORM_TEXTFIELD_REQUIRED);
}
get formValidity(): ValidityStateFlags {
return { valueMissing: this.required && !this.value };
}
async formElementAnchor() {
return this.getFocusDomRefAsync();
}
get formFormattedValue() {
return this.value;
}
constructor() {
super();
this._filteredItems = [];
this._initialRendering = true;
this._itemFocused = false;
this._autocomplete = false;
this._isKeyNavigation = false;
// when an initial value is set it should be considered as a _lastValue
this._lastValue = this.getAttribute("value") || "";
this._selectionPerformed = false;
this._selectedItemText = "";
this._userTypedValue = "";
}
async onBeforeRendering() {
const popover: Popover | undefined = this.valueStatePopover;
this._effectiveShowClearIcon = (this.showClearIcon && !!this.value && !this.readonly && !this.disabled);
if (this._initialRendering || this.filter === "None") {
this._filteredItems = this.items;
}
if (this.open && !this._isKeyNavigation) {
const items = this._filterItems(this.filterValue);
this._filteredItems = (items.length && items) || [];
}
const hasNoVisibleItems = !this._filteredItems.length || !this._filteredItems.some(i => i._isVisible);
// If there is no filtered items matching the value, show all items when the arrow is pressed
if (((hasNoVisibleItems && !isPhone()) && this.value)) {
this.items.forEach(this._makeAllVisible.bind(this));
this._filteredItems = this.items;
}
if (!this._initialRendering && document.activeElement === this && !this._filteredItems.length && popover) {
popover.open = false;
}
this._selectMatchingItem();
this._initialRendering = false;
this.style.setProperty(getScopedVarName("--_ui5-input-icons-count"), `${this.iconsCount}`);
const suggestionsPopover = await this._getPicker();
this.items.forEach(item => {
item._getRealDomRef = () => suggestionsPopover.querySelector(`*[data-ui5-stable=${item.stableDomRef}]`)!;
});
}
get iconsCount() {
const slottedIconsCount = this.icon?.length || 0;
const clearIconCount = Number(this._effectiveShowClearIcon) ?? 0;
const arrowDownIconsCount = this.readonly ? 0 : 1;
return slottedIconsCount + clearIconCount + arrowDownIconsCount;
}
async onAfterRendering() {
const picker: ResponsivePopover = await this._getPicker();
if ((await this.shouldClosePopover()) && !isPhone()) {
picker.preventFocusRestore = true;
picker.open = false;
this._clearFocus();
this._itemFocused = false;
}
this.toggleValueStatePopover(this.shouldOpenValueStateMessagePopover);
this.storeResponsivePopoverWidth();
if (isPhone()) {
this.value = this.inner.value;
this._selectMatchingItem();
}
}
async shouldClosePopover(): Promise<boolean> {
const popover: ResponsivePopover = await this._getPicker();
return popover.open && !this.focused && !this._itemFocused && !this._isValueStateFocused;
}
_focusin(e: FocusEvent) {
this.focused = true;
this._autocomplete = false;
!isPhone() && (e.target as HTMLInputElement).setSelectionRange(0, this.value.length);
}
_focusout(e: FocusEvent) {
const toBeFocused = e.relatedTarget as HTMLElement;
const focusedOutToValueStateMessage = toBeFocused?.shadowRoot?.querySelector(".ui5-valuestatemessage-root");
const clearIconWrapper = this.shadowRoot!.querySelector(".ui5-input-clear-icon-wrapper");
const focusedOutToClearIcon = clearIconWrapper === toBeFocused || clearIconWrapper?.contains(toBeFocused);
if (this._effectiveShowClearIcon && focusedOutToClearIcon) {
return;
}
this._fireChangeEvent();
if (focusedOutToValueStateMessage) {
e.stopImmediatePropagation();
return;
}
const popover = this.shadowRoot!.querySelector("[ui5-responsive-popover]");
if (!(this.getDomRef()!.contains(toBeFocused)) && (popover !== e.relatedTarget)) {
this.focused = false;
!isPhone() && this._closeRespPopover(e);
}
}
_afterOpenPopover() {
this._iconPressed = true;
this.inner.focus();
}
_afterClosePopover() {
this._iconPressed = false;
this._filteredItems = this.items;
this.filterValue = "";
// close device's keyboard and prevent further typing
if (isPhone()) {
this.blur();
}
if (this._selectionPerformed) {
this._lastValue = this.value;
this._selectionPerformed = false;
}
}
async _toggleRespPopover() {
const picker: ResponsivePopover = await this._getPicker();
if (picker.open) {
this._closeRespPopover();
} else {
this._openRespPopover();
}
}
async storeResponsivePopoverWidth() {
if (this.open && !this._listWidth) {
this._listWidth = (await this._getPicker()).offsetWidth;
}
}
toggleValueStatePopover(open: boolean) {
if (open) {
this.openValueStatePopover();
} else {
this.closeValueStatePopover();
}
}
async openValueStatePopover() {
const valueStatePopover = await this._getValueStatePopover();
if (valueStatePopover) {
valueStatePopover.opener = this;
valueStatePopover.open = true;
}
}
async closeValueStatePopover() {
const valueStatePopover = await this._getValueStatePopover();
if (valueStatePopover) {
valueStatePopover.open = false;
}
}
async _getValueStatePopover() {
await renderFinished();
const popover: Popover = this.shadowRoot!.querySelector<Popover>(".ui5-valuestatemessage-popover")!;
// backward compatibility
// rework all methods to work with async getters
this.valueStatePopover = popover;
return popover;
}
_resetFilter() {
this._userTypedValue = "";
this.inner.setSelectionRange(0, this.value.length);
this._filteredItems = this._filterItems("");
this._selectMatchingItem();
}
_resetItemVisibility() {
this.items.forEach(item => {
if (isInstanceOfComboBoxItemGroup(item)) {
item.items?.forEach(i => {
i._isVisible = false;
});
return;
}
item._isVisible = false;
});
}
_arrowClick() {
this.inner.focus();
this._resetFilter();
if (isPhone() && this.value && !this._lastValue) {
this._lastValue = this.value;
}
this._toggleRespPopover();
}
_handleMobileInput(e: CustomEvent<InputEventDetail>) {
const { target } = e;
this.filterValue = (target as Input).value;
this.value = (target as Input).value;
this.fireEvent("input");
}
_input(e: InputEvent) {
const { value } = e.target as HTMLInputElement;
const shouldAutocomplete = this.shouldAutocomplete(e);
if (e.target === this.inner) {
// stop the native event, as the semantic "input" would be fired.
e.stopImmediatePropagation();
this.focused = true;
this._isValueStateFocused = false;
}
this._filteredItems = this._filterItems(value);
this.value = value;
this.filterValue = value;
this._clearFocus();
// autocomplete
if (shouldAutocomplete && !isAndroid()) {
const item = this._getFirstMatchingItem(value);
item && this._applyAtomicValueAndSelection(item, value, true);
if (value !== "" && (item && !item.selected && !item.isGroupItem)) {
this.fireEvent<ComboBoxSelectionChangeEventDetail>("selection-change", {
item: item as ComboBoxItem,
});
}
}
this.fireEvent("input");
if (isPhone()) {
return;
}
if (!this._filteredItems.length || value === "") {
this._closeRespPopover();
} else {
this._openRespPopover();
}
}
shouldAutocomplete(e: InputEvent): boolean {
const eventType = e.inputType;
const allowedEventTypes = [
"deleteWordBackward",
"deleteWordForward",
"deleteSoftLineBackward",
"deleteSoftLineForward",
"deleteEntireSoftLine",
"deleteHardLineBackward",
"deleteHardLineForward",
"deleteByDrag",
"deleteByCut",
"deleteContent",
"deleteContentBackward",
"deleteContentForward",
"historyUndo",
];
return !this.noTypeahead && !allowedEventTypes.includes(eventType);
}
_startsWithMatchingItems(str: string): Array<IComboBoxItem> {
const allItems:Array<IComboBoxItem> = this._getItems();
return Filters.StartsWith(str, allItems, "text");
}
_clearFocus() {
const allItems = this._getItems();
allItems.map(item => {
item.focused = false;
return item;
});
}
// Get groups and items as a flat array for filtering
_getItems() {
const allItems: Array<IComboBoxItem> = [];
this._filteredItems.forEach(item => {
if (isInstanceOfComboBoxItemGroup(item)) {
const groupedItems = [item, ...item.items];
allItems.push(...groupedItems);
return;
}
allItems.push(item);
});
return allItems;
}
handleNavKeyPress(e: KeyboardEvent) {
const allItems = this._getItems();
if (this.focused && (isHome(e) || isEnd(e)) && this.value) {
return;
}
const isOpen = this.open;
const currentItem = allItems.find(item => {
return isOpen ? item.focused : item.selected;
});
const indexOfItem = currentItem ? allItems.indexOf(currentItem) : -1;
e.preventDefault();
if (this.focused && isOpen && (isUp(e) || isPageUp(e) || isPageDown(e))) {
return;
}
if (allItems.length - 1 === indexOfItem && isDown(e)) {
return;
}
this._isKeyNavigation = true;
if (
e.key === "ArrowDown"
|| e.key === "ArrowUp"
|| e.key === "PageUp"
|| e.key === "PageDown"
|| e.key === "Home"
|| e.key === "End"
) {
this[`_handle${e.key}`](e, indexOfItem);
}
}
_handleItemNavigation(e: KeyboardEvent, indexOfItem: number, isForward: boolean) {
const allItems = this._getItems();
const isOpen = this.open;
const currentItem: IComboBoxItem = allItems[indexOfItem];
const isGroupItem = currentItem && currentItem.isGroupItem;
const nextItem = isForward ? allItems[indexOfItem + 1] : allItems[indexOfItem - 1];
if ((!isOpen) && ((isGroupItem && !nextItem) || (!isGroupItem && !currentItem))) {
return;
}
this._clearFocus();
if (isOpen) {
this._itemFocused = true;
this.value = isGroupItem ? "" : currentItem.text;
this.focused = false;
currentItem.focused = true;
} else {
this.focused = true;
this.value = isGroupItem ? nextItem.text : currentItem.text;
currentItem.focused = false;
}
this._isValueStateFocused = false;
this._announceSelectedItem(indexOfItem);
this._scrollToItem(indexOfItem, isForward);
if (isGroupItem && isOpen) {
return;
}
// autocomplete
const item = this._getFirstMatchingItem(this.value);
item && this._applyAtomicValueAndSelection(item, (this.open ? this._userTypedValue : ""), true);
if ((item && !item.selected)) {
this.fireEvent<ComboBoxSelectionChangeEventDetail>("selection-change", {
item: item as ComboBoxItem,
});
}
this.fireEvent("input");
}
_handleArrowDown(e: KeyboardEvent, indexOfItem: number) {
const isOpen = this.open;
if (this.focused && indexOfItem === -1 && this.hasValueStateText && isOpen) {
this._isValueStateFocused = true;
this._announceValueStateText();
this.focused = false;
return;
}
indexOfItem = !isOpen && this.hasValueState && indexOfItem === -1 ? 0 : indexOfItem;
this._handleItemNavigation(e, ++indexOfItem, true /* isForward */);
}
_handleArrowUp(e: KeyboardEvent, indexOfItem: number) {
const isOpen = this.open;
if (indexOfItem === 0 && !this.hasValueStateText) {
this._clearFocus();
this.focused = true;
this._itemFocused = false;
return;
}
if (indexOfItem === 0 && this.hasValueStateText && isOpen) {
this._clearFocus();
this._itemFocused = false;
this._isValueStateFocused = true;
this._announceValueStateText();
this._filteredItems[0].selected = false;
return;
}
if (this._isValueStateFocused) {
this.focused = true;
this._isValueStateFocused = false;
return;
}
indexOfItem = !isOpen && this.hasValueState && indexOfItem === -1 ? 0 : indexOfItem;
this._handleItemNavigation(e, --indexOfItem, false /* isForward */);
}
_handlePageUp(e: KeyboardEvent, indexOfItem: number) {
const allItems = this._getItems();
const isProposedIndexValid = indexOfItem - SKIP_ITEMS_SIZE > -1;
indexOfItem = isProposedIndexValid ? indexOfItem - SKIP_ITEMS_SIZE : 0;
const shouldMoveForward = isInstanceOfComboBoxItemGroup(allItems[indexOfItem]) && !this.open;
if (!isProposedIndexValid && this.hasValueStateText && this.open) {
this._clearFocus();
this._itemFocused = false;
this._isValueStateFocused = true;
this._announceValueStateText();
return;
}
this._handleItemNavigation(e, indexOfItem, shouldMoveForward);
}
_handlePageDown(e: KeyboardEvent, indexOfItem: number) {
const allItems = this._getItems();
const itemsLength = allItems.length;
const isProposedIndexValid = indexOfItem + SKIP_ITEMS_SIZE < itemsLength;
indexOfItem = isProposedIndexValid ? indexOfItem + SKIP_ITEMS_SIZE : itemsLength - 1;
const shouldMoveForward = isInstanceOfComboBoxItemGroup(allItems[indexOfItem]) && !this.open;
this._handleItemNavigation(e, indexOfItem, shouldMoveForward);
}
_handleHome(e: KeyboardEvent) {
const shouldMoveForward = isInstanceOfComboBoxItemGroup(this._filteredItems[0]) && !this.open;
if (this.hasValueStateText && this.open) {
this._clearFocus();
this._itemFocused = false;
this._isValueStateFocused = true;
this._announceValueStateText();
return;
}
this._handleItemNavigation(e, 0, shouldMoveForward);
}
_handleEnd(e: KeyboardEvent) {
this._handleItemNavigation(e, this._getItems().length - 1, true /* isForward */);
}
_keyup() {
this._userTypedValue = this.value.substring(0, this.inner.selectionStart || 0);
}
_keydown(e: KeyboardEvent) {
const isNavKey = isDown(e) || isUp(e) || isPageUp(e) || isPageDown(e) || isHome(e) || isEnd(e);
const picker = this.responsivePopover;
const allItems: Array<IComboBoxItem> = this._getItems();
this._autocomplete = !(isBackSpace(e) || isDelete(e));
this._isKeyNavigation = false;
if (isNavKey && !this.readonly && this._filteredItems.length) {
this.handleNavKeyPress(e);
}
if (isEnter(e)) {
let focusedItem: IComboBoxItem | undefined;
this._filteredItems.forEach(item => {
if (isInstanceOfComboBoxItemGroup(item) && !focusedItem) {
focusedItem = item.items.find(groupItem => groupItem.focused);
}
if (item.focused) {
focusedItem = item;
}
});
this._fireChangeEvent();
if (picker?.open && !focusedItem?.isGroupItem) {
this._closeRespPopover();
this.focused = true;
this.inner.setSelectionRange(this.value.length, this.value.length);
} else if (this._internals?.form) {
submitForm(this);
}
}
if (isEscape(e)) {
this.focused = true;
this.value = !this.open ? this._lastValue : this.value;
this._isValueStateFocused = false;
}
if ((isTabNext(e) || isTabPrevious(e)) && this.open) {
this._closeRespPopover();
}
if (isShow(e) && !this.readonly && !this.disabled) {
e.preventDefault();
this._resetFilter();
this._toggleRespPopover();
const selectedItem = allItems.find(item => {
return item.selected;
});
if (selectedItem && this.open) {
this._itemFocused = true;
selectedItem.focused = true;
this.focused = false;
} else if (this.open && this._filteredItems.length) {
// If no item is selected, select the first one on "Show" (F4, Alt+Up/Down)
this._handleItemNavigation(e, 0, true /* isForward */);
} else {
this.focused = true;
}
}
}