-
Notifications
You must be signed in to change notification settings - Fork 80
/
vaadin-combo-box-mixin.js
1342 lines (1160 loc) · 39.1 KB
/
vaadin-combo-box-mixin.js
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 (c) 2015 - 2022 Vaadin Ltd.
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
*/
import { isTouch } from '@vaadin/component-base/src/browser-utils.js';
import { ControllerMixin } from '@vaadin/component-base/src/controller-mixin.js';
import { DisabledMixin } from '@vaadin/component-base/src/disabled-mixin.js';
import { isElementFocused } from '@vaadin/component-base/src/focus-utils.js';
import { KeyboardMixin } from '@vaadin/component-base/src/keyboard-mixin.js';
import { processTemplates } from '@vaadin/component-base/src/templates.js';
import { InputMixin } from '@vaadin/field-base/src/input-mixin.js';
import { VirtualKeyboardController } from '@vaadin/field-base/src/virtual-keyboard-controller.js';
import { ComboBoxPlaceholder } from './vaadin-combo-box-placeholder.js';
/**
* Checks if the value is supported as an item value in this control.
*
* @param {unknown} value
* @return {boolean}
*/
function isValidValue(value) {
return value !== undefined && value !== null;
}
/**
* Returns the index of the first item that satisfies the provided testing function
* ignoring placeholder items.
*
* @param {Array<ComboBoxItem | string>} items
* @param {Function} callback
* @return {number}
*/
function findItemIndex(items, callback) {
return items.findIndex((item) => {
if (item instanceof ComboBoxPlaceholder) {
return false;
}
return callback(item);
});
}
/**
* @polymerMixin
* @param {function(new:HTMLElement)} subclass
*/
export const ComboBoxMixin = (subclass) =>
class VaadinComboBoxMixinElement extends ControllerMixin(KeyboardMixin(InputMixin(DisabledMixin(subclass)))) {
static get properties() {
return {
/**
* True if the dropdown is open, false otherwise.
* @type {boolean}
*/
opened: {
type: Boolean,
notify: true,
value: false,
reflectToAttribute: true,
observer: '_openedChanged',
},
/**
* Set true to prevent the overlay from opening automatically.
* @attr {boolean} auto-open-disabled
*/
autoOpenDisabled: {
type: Boolean,
},
/**
* When present, it specifies that the field is read-only.
* @type {boolean}
*/
readonly: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/**
* Custom function for rendering the content of every item.
* Receives three arguments:
*
* - `root` The `<vaadin-combo-box-item>` internal container DOM element.
* - `comboBox` The reference to the `<vaadin-combo-box>` element.
* - `model` The object with the properties related with the rendered
* item, contains:
* - `model.index` The index of the rendered item.
* - `model.item` The item.
* @type {ComboBoxRenderer | undefined}
*/
renderer: Function,
/**
* A full set of items to filter the visible options from.
* The items can be of either `String` or `Object` type.
* @type {!Array<!ComboBoxItem | string> | undefined}
*/
items: {
type: Array,
observer: '_itemsChanged',
},
/**
* If `true`, the user can input a value that is not present in the items list.
* `value` property will be set to the input value in this case.
* Also, when `value` is set programmatically, the input value will be set
* to reflect that value.
* @attr {boolean} allow-custom-value
* @type {boolean}
*/
allowCustomValue: {
type: Boolean,
value: false,
},
/**
* A subset of items, filtered based on the user input. Filtered items
* can be assigned directly to omit the internal filtering functionality.
* The items can be of either `String` or `Object` type.
* @type {!Array<!ComboBoxItem | string> | undefined}
*/
filteredItems: {
type: Array,
observer: '_filteredItemsChanged',
},
/**
* Used to detect user value changes and fire `change` events.
* @private
*/
_lastCommittedValue: String,
/**
* When set to `true`, "loading" attribute is added to host and the overlay element.
* @type {boolean}
*/
loading: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/**
* @type {number}
* @protected
*/
_focusedIndex: {
type: Number,
observer: '_focusedIndexChanged',
value: -1,
},
/**
* Filtering string the user has typed into the input field.
* @type {string}
*/
filter: {
type: String,
value: '',
notify: true,
},
/**
* The selected item from the `items` array.
* @type {ComboBoxItem | string | undefined}
*/
selectedItem: {
type: Object,
notify: true,
},
/**
* Path for label of the item. If `items` is an array of objects, the
* `itemLabelPath` is used to fetch the displayed string label for each
* item.
*
* The item label is also used for matching items when processing user
* input, i.e., for filtering and selecting items.
* @attr {string} item-label-path
* @type {string}
*/
itemLabelPath: {
type: String,
value: 'label',
observer: '_itemLabelPathChanged',
},
/**
* Path for the value of the item. If `items` is an array of objects, the
* `itemValuePath:` is used to fetch the string value for the selected
* item.
*
* The item value is used in the `value` property of the combo box,
* to provide the form value.
* @attr {string} item-value-path
* @type {string}
*/
itemValuePath: {
type: String,
value: 'value',
},
/**
* Path for the id of the item. If `items` is an array of objects,
* the `itemIdPath` is used to compare and identify the same item
* in `selectedItem` and `filteredItems` (items given by the
* `dataProvider` callback).
* @attr {string} item-id-path
*/
itemIdPath: String,
/**
* @type {!HTMLElement | undefined}
* @protected
*/
_toggleElement: {
type: Object,
observer: '_toggleElementChanged',
},
/**
* Set of items to be rendered in the dropdown.
* @protected
*/
_dropdownItems: {
type: Array,
},
/** @private */
_closeOnBlurIsPrevented: Boolean,
/** @private */
_scroller: Object,
/** @private */
_overlayOpened: {
type: Boolean,
observer: '_overlayOpenedChanged',
},
};
}
static get observers() {
return [
'_selectedItemChanged(selectedItem, itemValuePath, itemLabelPath)',
'_openedOrItemsChanged(opened, _dropdownItems, loading)',
'_updateScroller(_scroller, _dropdownItems, opened, loading, selectedItem, itemIdPath, _focusedIndex, renderer, theme)',
];
}
constructor() {
super();
this._boundOnFocusout = this._onFocusout.bind(this);
this._boundOverlaySelectedItemChanged = this._overlaySelectedItemChanged.bind(this);
this._boundOnClearButtonMouseDown = this.__onClearButtonMouseDown.bind(this);
this._boundOnClick = this._onClick.bind(this);
this._boundOnOverlayTouchAction = this._onOverlayTouchAction.bind(this);
this._boundOnTouchend = this._onTouchend.bind(this);
}
/**
* Tag name prefix used by scroller and items.
* @protected
* @return {string}
*/
get _tagNamePrefix() {
return 'vaadin-combo-box';
}
/**
* @return {string | undefined}
* @protected
*/
get _inputElementValue() {
return this.inputElement ? this.inputElement[this._propertyForValue] : undefined;
}
/**
* @param {string} value
* @protected
*/
set _inputElementValue(value) {
if (this.inputElement) {
this.inputElement[this._propertyForValue] = value;
}
}
/**
* Get a reference to the native `<input>` element.
* Override to provide a custom input.
* @protected
* @return {HTMLInputElement | undefined}
*/
get _nativeInput() {
return this.inputElement;
}
/**
* Override method inherited from `InputMixin`
* to customize the input element.
* @protected
* @override
*/
_inputElementChanged(inputElement) {
super._inputElementChanged(inputElement);
const input = this._nativeInput;
if (input) {
input.autocomplete = 'off';
input.autocapitalize = 'off';
input.setAttribute('role', 'combobox');
input.setAttribute('aria-autocomplete', 'list');
input.setAttribute('aria-expanded', !!this.opened);
// Disable the macOS Safari spell check auto corrections.
input.setAttribute('spellcheck', 'false');
// Disable iOS autocorrect suggestions.
input.setAttribute('autocorrect', 'off');
this._revertInputValueToValue();
if (this.clearElement) {
this.clearElement.addEventListener('mousedown', this._boundOnClearButtonMouseDown);
}
}
}
/** @protected */
ready() {
super.ready();
this._initOverlay();
this._initScroller();
this.addEventListener('focusout', this._boundOnFocusout);
this._lastCommittedValue = this.value;
this.addEventListener('click', this._boundOnClick);
this.addEventListener('touchend', this._boundOnTouchend);
const bringToFrontListener = () => {
requestAnimationFrame(() => {
this.$.overlay.bringToFront();
});
};
this.addEventListener('mousedown', bringToFrontListener);
this.addEventListener('touchstart', bringToFrontListener);
processTemplates(this);
this.addController(new VirtualKeyboardController(this));
}
/** @protected */
disconnectedCallback() {
super.disconnectedCallback();
// Close the overlay on detach
this.close();
}
/**
* Requests an update for the content of items.
* While performing the update, it invokes the renderer (passed in the `renderer` property) once an item.
*
* It is not guaranteed that the update happens immediately (synchronously) after it is requested.
*/
requestContentUpdate() {
if (!this._scroller) {
return;
}
this._scroller.requestContentUpdate();
this._getItemElements().forEach((item) => {
item.requestContentUpdate();
});
}
/**
* Opens the dropdown list.
*/
open() {
// Prevent _open() being called when input is disabled or read-only
if (!this.disabled && !this.readonly) {
this.opened = true;
}
}
/**
* Closes the dropdown list.
*/
close() {
this.opened = false;
}
/**
* Override Polymer lifecycle callback to handle `filter` property change after
* the observer for `opened` property is triggered. This is needed when opening
* combo-box on user input to ensure the focused index is set correctly.
*
* @param {!Object} currentProps Current accessor values
* @param {?Object} changedProps Properties changed since the last call
* @param {?Object} oldProps Previous values for each changed property
* @protected
* @override
*/
_propertiesChanged(currentProps, changedProps, oldProps) {
super._propertiesChanged(currentProps, changedProps, oldProps);
if (changedProps.filter !== undefined) {
this._filterChanged(changedProps.filter);
}
}
/** @private */
_initOverlay() {
const overlay = this.$.overlay;
// Store instance for detecting "dir" attribute on opening
overlay._comboBox = this;
overlay.addEventListener('touchend', this._boundOnOverlayTouchAction);
overlay.addEventListener('touchmove', this._boundOnOverlayTouchAction);
// Prevent blurring the input when clicking inside the overlay
overlay.addEventListener('mousedown', (e) => e.preventDefault());
// Manual two-way binding for the overlay "opened" property
overlay.addEventListener('opened-changed', (e) => {
this._overlayOpened = e.detail.value;
});
}
/**
* Create and initialize the scroller element.
* Override to provide custom host reference.
*
* @protected
*/
_initScroller(host) {
const scrollerTag = `${this._tagNamePrefix}-scroller`;
const overlay = this.$.overlay;
overlay.renderer = (root) => {
if (!root.firstChild) {
root.appendChild(document.createElement(scrollerTag));
}
};
// Ensure the scroller is rendered
overlay.requestContentUpdate();
const scroller = overlay.querySelector(scrollerTag);
scroller.comboBox = host || this;
scroller.getItemLabel = this._getItemLabel.bind(this);
scroller.addEventListener('selection-changed', this._boundOverlaySelectedItemChanged);
// Trigger the observer to set properties
this._scroller = scroller;
}
/** @private */
// eslint-disable-next-line max-params
_updateScroller(scroller, items, opened, loading, selectedItem, itemIdPath, focusedIndex, renderer, theme) {
if (scroller) {
if (opened) {
scroller.style.maxHeight =
getComputedStyle(this).getPropertyValue(`--${this._tagNamePrefix}-overlay-max-height`) || '65vh';
}
scroller.setProperties({
items: opened ? items : [],
opened,
loading,
selectedItem,
itemIdPath,
focusedIndex,
renderer,
theme,
});
}
}
/** @private */
_openedOrItemsChanged(opened, items, loading) {
// Close the overlay if there are no items to display.
// See https://github.com/vaadin/vaadin-combo-box/pull/964
this._overlayOpened = !!(opened && (loading || (items && items.length)));
}
/** @private */
_overlayOpenedChanged(opened, wasOpened) {
if (opened) {
this.dispatchEvent(new CustomEvent('vaadin-combo-box-dropdown-opened', { bubbles: true, composed: true }));
this._onOpened();
} else if (wasOpened && this._dropdownItems && this._dropdownItems.length) {
this.close();
this.dispatchEvent(new CustomEvent('vaadin-combo-box-dropdown-closed', { bubbles: true, composed: true }));
}
}
/** @private */
_focusedIndexChanged(index, oldIndex) {
if (oldIndex === undefined) {
return;
}
this._updateActiveDescendant(index);
}
/** @protected */
_isInputFocused() {
return this.inputElement && isElementFocused(this.inputElement);
}
/** @private */
_updateActiveDescendant(index) {
const input = this._nativeInput;
if (!input) {
return;
}
const item = this._getItemElements().find((el) => el.index === index);
if (item) {
input.setAttribute('aria-activedescendant', item.id);
} else {
input.removeAttribute('aria-activedescendant');
}
}
/** @private */
_openedChanged(opened, wasOpened) {
// Prevent _close() being called when opened is set to its default value (false).
if (wasOpened === undefined) {
return;
}
if (opened) {
this._openedWithFocusRing = this.hasAttribute('focus-ring');
// For touch devices, we don't want to popup virtual keyboard
// unless input element is explicitly focused by the user.
if (!this._isInputFocused() && !isTouch) {
if (this.inputElement) {
this.inputElement.focus();
}
}
this.$.overlay.restoreFocusOnClose = true;
} else {
this._onClosed();
if (this._openedWithFocusRing && this._isInputFocused()) {
this.setAttribute('focus-ring', '');
}
}
const input = this._nativeInput;
if (input) {
input.setAttribute('aria-expanded', !!opened);
if (opened) {
input.setAttribute('aria-controls', this._scroller.id);
} else {
input.removeAttribute('aria-controls');
}
}
}
/** @private */
_onOverlayTouchAction() {
// On touch devices, blur the input on touch start inside the overlay, in order to hide
// the virtual keyboard. But don't close the overlay on this blur.
this._closeOnBlurIsPrevented = true;
this.inputElement.blur();
this._closeOnBlurIsPrevented = false;
}
/** @protected */
_isClearButton(event) {
return event.composedPath()[0] === this.clearElement;
}
/**
* @param {Event} event
* @protected
*/
_handleClearButtonClick(event) {
event.preventDefault();
this._clear();
// De-select dropdown item
if (this.opened) {
this.requestContentUpdate();
}
}
/**
* @param {Event} event
* @private
*/
_onToggleButtonClick(event) {
// Prevent parent components such as `vaadin-grid`
// from handling the click event after it bubbles.
event.preventDefault();
if (this.opened) {
this.close();
} else {
this.open();
}
}
/**
* @param {Event} event
* @protected
*/
_onHostClick(event) {
if (!this.autoOpenDisabled) {
event.preventDefault();
this.open();
}
}
/** @private */
_onClick(e) {
const path = e.composedPath();
if (this._isClearButton(e)) {
this._handleClearButtonClick(e);
} else if (path.indexOf(this._toggleElement) > -1) {
this._onToggleButtonClick(e);
} else {
this._onHostClick(e);
}
}
/**
* Override an event listener from `KeyboardMixin`.
*
* @param {KeyboardEvent} e
* @protected
* @override
*/
_onKeyDown(e) {
super._onKeyDown(e);
if (e.key === 'Tab') {
this.$.overlay.restoreFocusOnClose = false;
} else if (e.key === 'ArrowDown') {
this._onArrowDown();
// Prevent caret from moving
e.preventDefault();
} else if (e.key === 'ArrowUp') {
this._onArrowUp();
// Prevent caret from moving
e.preventDefault();
}
}
/** @private */
_getItemLabel(item) {
let label = item && this.itemLabelPath ? this.get(this.itemLabelPath, item) : undefined;
if (label === undefined || label === null) {
label = item ? item.toString() : '';
}
return label;
}
/** @private */
_getItemValue(item) {
let value = item && this.itemValuePath ? this.get(this.itemValuePath, item) : undefined;
if (value === undefined) {
value = item ? item.toString() : '';
}
return value;
}
/** @private */
_onArrowDown() {
if (this.opened) {
const items = this._dropdownItems;
if (items) {
this._focusedIndex = Math.min(items.length - 1, this._focusedIndex + 1);
this._prefillFocusedItemLabel();
}
} else {
this.open();
}
}
/** @private */
_onArrowUp() {
if (this.opened) {
if (this._focusedIndex > -1) {
this._focusedIndex = Math.max(0, this._focusedIndex - 1);
} else {
const items = this._dropdownItems;
if (items) {
this._focusedIndex = items.length - 1;
}
}
this._prefillFocusedItemLabel();
} else {
this.open();
}
}
/** @private */
_prefillFocusedItemLabel() {
if (this._focusedIndex > -1) {
const focusedItem = this._dropdownItems[this._focusedIndex];
this._inputElementValue = this._getItemLabel(focusedItem);
this._markAllSelectionRange();
}
}
/** @private */
_setSelectionRange(start, end) {
// Setting selection range focuses and/or moves the caret in some browsers,
// and there's no need to modify the selection range if the input isn't focused anyway.
// This affects Safari. When the overlay is open, and then hitting tab, browser should focus
// the next focusable element instead of the combo-box itself.
if (this._isInputFocused() && this.inputElement.setSelectionRange) {
this.inputElement.setSelectionRange(start, end);
}
}
/** @private */
_markAllSelectionRange() {
if (this._inputElementValue !== undefined) {
this._setSelectionRange(0, this._inputElementValue.length);
}
}
/** @private */
_clearSelectionRange() {
if (this._inputElementValue !== undefined) {
const pos = this._inputElementValue ? this._inputElementValue.length : 0;
this._setSelectionRange(pos, pos);
}
}
/** @private */
_closeOrCommit() {
if (!this.opened && !this.loading) {
this._commitValue();
} else {
this.close();
}
}
/**
* Override an event listener from `KeyboardMixin`.
*
* @param {KeyboardEvent} e
* @protected
* @override
*/
_onEnter(e) {
// Do not commit value when custom values are disallowed and input value is not a valid option
// also stop propagation of the event, otherwise the user could submit a form while the input
// still contains an invalid value
const hasInvalidOption =
this._focusedIndex < 0 &&
this._inputElementValue !== '' &&
this._getItemLabel(this.selectedItem) !== this._inputElementValue;
if (!this.allowCustomValue && hasInvalidOption) {
// Do not submit the surrounding form.
e.preventDefault();
// Do not trigger global listeners
e.stopPropagation();
return;
}
// Stop propagation of the enter event only if the dropdown is opened, this
// "consumes" the enter event for the action of closing the dropdown
if (this.opened) {
// Do not submit the surrounding form.
e.preventDefault();
// Do not trigger global listeners
e.stopPropagation();
}
this._closeOrCommit();
}
/**
* Override an event listener from `KeyboardMixin`.
* Do not call `super` in order to override clear
* button logic defined in `InputControlMixin`.
*
* @param {!KeyboardEvent} e
* @protected
* @override
*/
_onEscape(e) {
if (this.autoOpenDisabled) {
// Auto-open is disabled
if (this.opened || (this.value !== this._inputElementValue && this._inputElementValue.length > 0)) {
// The overlay is open or
// The input value has changed but the change hasn't been committed, so cancel it.
e.stopPropagation();
this._focusedIndex = -1;
this.cancel();
} else if (this.clearButtonVisible && !this.opened && !!this.value) {
e.stopPropagation();
// The clear button is visible and the overlay is closed, so clear the value.
this._clear();
}
} else if (this.opened) {
// Auto-open is enabled
// The overlay is open
e.stopPropagation();
if (this._focusedIndex > -1) {
// An item is focused, revert the input to the filtered value
this._focusedIndex = -1;
this._revertInputValue();
} else {
// No item is focused, cancel the change and close the overlay
this.cancel();
}
} else if (this.clearButtonVisible && !!this.value) {
e.stopPropagation();
// The clear button is visible and the overlay is closed, so clear the value.
this._clear();
}
}
/** @private */
_toggleElementChanged(toggleElement) {
if (toggleElement) {
// Don't blur the input on toggle mousedown
toggleElement.addEventListener('mousedown', (e) => e.preventDefault());
// Unfocus previously focused element if focus is not inside combo box (on touch devices)
toggleElement.addEventListener('click', () => {
if (isTouch && !this._isInputFocused()) {
document.activeElement.blur();
}
});
}
}
/**
* Clears the current value.
* @protected
*/
_clear() {
this.selectedItem = null;
if (this.allowCustomValue) {
this.value = '';
}
this._detectAndDispatchChange();
}
/**
* Reverts back to original value.
*/
cancel() {
this._revertInputValueToValue();
// In the next _detectAndDispatchChange() call, the change detection should not pass
this._lastCommittedValue = this.value;
this._closeOrCommit();
}
/** @private */
_onOpened() {
// _detectAndDispatchChange() should not consider value changes done before opening
this._lastCommittedValue = this.value;
}
/** @private */
_onClosed() {
if (!this.loading || this.allowCustomValue) {
this._commitValue();
}
}
/** @private */
_commitValue() {
if (this._focusedIndex > -1) {
const focusedItem = this._dropdownItems[this._focusedIndex];
if (this.selectedItem !== focusedItem) {
this.selectedItem = focusedItem;
}
// Make sure input field is updated in case value doesn't change (i.e. FOO -> foo)
this._inputElementValue = this._getItemLabel(this.selectedItem);
this._focusedIndex = -1;
} else if (this._inputElementValue === '' || this._inputElementValue === undefined) {
this.selectedItem = null;
if (this.allowCustomValue) {
this.value = '';
}
} else {
// Try to find an item which label matches the input value.
const items = [...(this._dropdownItems || []), this.selectedItem];
const itemMatchingInputValue = items[this.__getItemIndexByLabel(items, this._inputElementValue)];
if (
this.allowCustomValue &&
// To prevent a repetitive input value being saved after pressing ESC and Tab.
!itemMatchingInputValue
) {
const customValue = this._inputElementValue;
// Store reference to the last custom value for checking it on focusout.
this._lastCustomValue = customValue;
// An item matching by label was not found, but custom values are allowed.
// Dispatch a custom-value-set event with the input value.
const e = new CustomEvent('custom-value-set', {
detail: customValue,
composed: true,
cancelable: true,
bubbles: true,
});
this.dispatchEvent(e);
if (!e.defaultPrevented) {
this.value = customValue;
}
} else if (!this.allowCustomValue && !this.opened && itemMatchingInputValue) {
// An item matching by label was found, select it.
this.value = this._getItemValue(itemMatchingInputValue);
} else {
// Revert the input value
this._inputElementValue = this.selectedItem ? this._getItemLabel(this.selectedItem) : this.value || '';
}
}
this._detectAndDispatchChange();
this._clearSelectionRange();
this.filter = '';
}
/**
* @return {string}
* @protected
*/
get _propertyForValue() {
return 'value';
}
/**
* Override an event listener from `InputMixin`.
* @param {!Event} event
* @protected
* @override
*/
_onInput(event) {
const filter = this._inputElementValue;
// When opening dropdown on user input, both `opened` and `filter` properties are set.
// Perform a batched property update instead of relying on sync property observers.
// This is necessary to avoid an extra data-provider request for loading first page.
const props = {};
if (this.filter === filter) {
// Filter and input value might get out of sync, while keyboard navigating for example.
// Afterwards, input value might be changed to the same value as used in filtering.
// In situation like these, we need to make sure all the filter changes handlers are run.
this._filterChanged(this.filter);
} else {
props.filter = filter;
}
if (!this.opened && !this._isClearButton(event) && !this.autoOpenDisabled) {
props.opened = true;
}
this.setProperties(props);
}
/**
* Override an event listener from `InputMixin`.
* @param {!Event} event
* @protected
* @override
*/
_onChange(event) {
// Suppress the native change event fired on the native input.
// We use `_detectAndDispatchChange` to fire a custom event.