-
Notifications
You must be signed in to change notification settings - Fork 80
/
vaadin-multi-select-combo-box.js
1308 lines (1136 loc) · 36.1 KB
/
vaadin-multi-select-combo-box.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) 2021 - 2022 Vaadin Ltd.
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
*/
import './vaadin-multi-select-combo-box-chip.js';
import './vaadin-multi-select-combo-box-container.js';
import './vaadin-multi-select-combo-box-internal.js';
import { html, PolymerElement } from '@polymer/polymer/polymer-element.js';
import { announce } from '@vaadin/component-base/src/a11y-announcer.js';
import { ElementMixin } from '@vaadin/component-base/src/element-mixin.js';
import { ResizeMixin } from '@vaadin/component-base/src/resize-mixin.js';
import { processTemplates } from '@vaadin/component-base/src/templates.js';
import { TooltipController } from '@vaadin/component-base/src/tooltip-controller.js';
import { InputControlMixin } from '@vaadin/field-base/src/input-control-mixin.js';
import { InputController } from '@vaadin/field-base/src/input-controller.js';
import { LabelledInputController } from '@vaadin/field-base/src/labelled-input-controller.js';
import { inputFieldShared } from '@vaadin/field-base/src/styles/input-field-shared-styles.js';
import { css, registerStyles, ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';
const multiSelectComboBox = css`
:host {
--input-min-width: var(--vaadin-multi-select-combo-box-input-min-width, 4em);
}
[hidden] {
display: none !important;
}
#chips {
display: flex;
align-items: center;
}
::slotted(input) {
box-sizing: border-box;
flex: 1 0 var(--input-min-width);
}
[part='chip'] {
flex: 0 1 auto;
}
:host(:is([readonly], [disabled])) ::slotted(input) {
flex-grow: 0;
flex-basis: 0;
padding: 0;
}
:host([auto-expand-vertically]) #chips {
display: contents;
}
:host([auto-expand-horizontally]) [class$='container'] {
width: auto;
}
`;
registerStyles('vaadin-multi-select-combo-box', [inputFieldShared, multiSelectComboBox], {
moduleId: 'vaadin-multi-select-combo-box-styles',
});
/**
* `<vaadin-multi-select-combo-box>` is a web component that wraps `<vaadin-combo-box>` and extends
* its functionality to allow selecting multiple items, in addition to basic features.
*
* ```html
* <vaadin-multi-select-combo-box id="comboBox"></vaadin-multi-select-combo-box>
* ```
*
* ```js
* const comboBox = document.querySelector('#comboBox');
* comboBox.items = ['apple', 'banana', 'lemon', 'orange'];
* comboBox.selectedItems = ['lemon', 'orange'];
* ```
*
* ### Styling
*
* The following shadow DOM parts are available for styling:
*
* Part name | Description
* -----------------------|----------------
* `chips` | The element that wraps chips for selected items
* `chip` | Chip shown for every selected item
* `label` | The label element
* `input-field` | The element that wraps prefix, value and suffix
* `clear-button` | The clear button
* `error-message` | The error message element
* `helper-text` | The helper text element wrapper
* `required-indicator` | The `required` state indicator element
* `overflow` | The chip shown when component width is not enough to fit all chips
* `overflow-one` | Set on the overflow chip when only one chip does not fit
* `overflow-two` | Set on the overflow chip when two chips do not fit
* `toggle-button` | The toggle button
*
* The following state attributes are available for styling:
*
* Attribute | Description
* -----------------------|-----------------
* `disabled` | Set to a disabled element
* `has-value` | Set when the element has a value
* `has-label` | Set when the element has a label
* `has-helper` | Set when the element has helper text or slot
* `has-error-message` | Set when the element has an error message
* `invalid` | Set when the element is invalid
* `focused` | Set when the element is focused
* `focus-ring` | Set when the element is keyboard focused
* `loading` | Set when loading items from the data provider
* `opened` | Set when the dropdown is open
* `readonly` | Set to a readonly element
*
* The following custom CSS properties are available for styling:
*
* Custom property | Description | Default
* -----------------------------------------------------|----------------------------|--------
* `--vaadin-field-default-width` | Default width of the field | `12em`
* `--vaadin-multi-select-combo-box-overlay-width` | Width of the overlay | `auto`
* `--vaadin-multi-select-combo-box-overlay-max-height` | Max height of the overlay | `65vh`
* `--vaadin-multi-select-combo-box-input-min-width` | Min width of the input | `4em`
*
* ### Internal components
*
* In addition to `<vaadin-multi-select-combo-box>` itself, the following internal
* components are themable:
*
* - `<vaadin-multi-select-combo-box-overlay>` - has the same API as `<vaadin-overlay>`.
* - `<vaadin-multi-select-combo-box-item>` - has the same API as `<vaadin-item>`.
* - `<vaadin-multi-select-combo-box-container>` - has the same API as `<vaadin-input-container>`.
*
* Note: the `theme` attribute value set on `<vaadin-multi-select-combo-box>` is
* propagated to these components.
*
* See [Styling Components](https://vaadin.com/docs/latest/styling/custom-theme/styling-components) documentation.
*
* @fires {Event} change - Fired when the user commits a value change.
* @fires {CustomEvent} custom-value-set - Fired when the user sets a custom value.
* @fires {CustomEvent} filter-changed - Fired when the `filter` property changes.
* @fires {CustomEvent} invalid-changed - Fired when the `invalid` property changes.
* @fires {CustomEvent} selected-items-changed - Fired when the `selectedItems` property changes.
* @fires {CustomEvent} validated - Fired whenever the field is validated.
*
* @extends HTMLElement
* @mixes ElementMixin
* @mixes ThemableMixin
* @mixes InputControlMixin
* @mixes ResizeMixin
*/
class MultiSelectComboBox extends ResizeMixin(InputControlMixin(ThemableMixin(ElementMixin(PolymerElement)))) {
static get is() {
return 'vaadin-multi-select-combo-box';
}
static get template() {
return html`
<div class="vaadin-multi-select-combo-box-container">
<div part="label">
<slot name="label"></slot>
<span part="required-indicator" aria-hidden="true" on-click="focus"></span>
</div>
<vaadin-multi-select-combo-box-internal
id="comboBox"
items="[[__effectiveItems]]"
item-id-path="[[itemIdPath]]"
item-label-path="[[itemLabelPath]]"
item-value-path="[[itemValuePath]]"
disabled="[[disabled]]"
readonly="[[readonly]]"
auto-open-disabled="[[autoOpenDisabled]]"
allow-custom-value="[[allowCustomValue]]"
data-provider="[[dataProvider]]"
filter="{{filter}}"
last-filter="{{_lastFilter}}"
loading="{{loading}}"
size="{{size}}"
filtered-items="[[__effectiveFilteredItems]]"
selected-items="[[selectedItems]]"
selected-items-on-top="[[selectedItemsOnTop]]"
top-group="[[_topGroup]]"
opened="{{opened}}"
renderer="[[renderer]]"
keep-filter="[[keepFilter]]"
theme$="[[_theme]]"
on-combo-box-item-selected="_onComboBoxItemSelected"
on-change="_onComboBoxChange"
on-custom-value-set="_onCustomValueSet"
on-filtered-items-changed="_onFilteredItemsChanged"
>
<vaadin-multi-select-combo-box-container
part="input-field"
auto-expand-vertically="[[autoExpandVertically]]"
readonly="[[readonly]]"
disabled="[[disabled]]"
invalid="[[invalid]]"
theme$="[[_theme]]"
>
<vaadin-multi-select-combo-box-chip
id="overflow"
slot="prefix"
part$="[[_getOverflowPart(_overflowItems.length)]]"
disabled="[[disabled]]"
readonly="[[readonly]]"
label="[[_getOverflowLabel(_overflowItems.length)]]"
title$="[[_getOverflowTitle(_overflowItems)]]"
hidden$="[[_isOverflowHidden(_overflowItems.length)]]"
on-mousedown="_preventBlur"
></vaadin-multi-select-combo-box-chip>
<div id="chips" part="chips" slot="prefix"></div>
<slot name="input"></slot>
<div
id="clearButton"
part="clear-button"
slot="suffix"
on-touchend="_onClearButtonTouchend"
aria-hidden="true"
></div>
<div id="toggleButton" class="toggle-button" part="toggle-button" slot="suffix" aria-hidden="true"></div>
</vaadin-multi-select-combo-box-container>
</vaadin-multi-select-combo-box-internal>
<div part="helper-text">
<slot name="helper"></slot>
</div>
<div part="error-message">
<slot name="error-message"></slot>
</div>
</div>
<slot name="tooltip"></slot>
`;
}
static get properties() {
return {
/**
* Set to true to auto expand horizontally, causing input field to
* grow until max width is reached.
* @attr {boolean} auto-expand-horizontally
*/
autoExpandHorizontally: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: '_autoExpandHorizontallyChanged',
},
/**
* Set to true to not collapse selected items chips into the overflow
* chip and instead always expand vertically, causing input field to
* wrap into multiple lines when width is limited.
* @attr {boolean} auto-expand-vertically
*/
autoExpandVertically: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: '_autoExpandVerticallyChanged',
},
/**
* Set true to prevent the overlay from opening automatically.
* @attr {boolean} auto-open-disabled
*/
autoOpenDisabled: Boolean,
/**
* Set to true to display the clear icon which clears the input.
* @attr {boolean} clear-button-visible
*/
clearButtonVisible: {
type: Boolean,
reflectToAttribute: true,
observer: '_clearButtonVisibleChanged',
value: false,
},
/**
* A full set of items to filter the visible options from.
* The items can be of either `String` or `Object` type.
*/
items: {
type: Array,
},
/**
* The item property used for a visual representation of the item.
* @attr {string} item-label-path
*/
itemLabelPath: {
type: String,
value: 'label',
},
/**
* Path for the value of the item. If `items` is an array of objects,
* this property is used as a string value for the selected item.
* @attr {string} item-value-path
*/
itemValuePath: {
type: String,
value: 'value',
},
/**
* Path for the id of the item, used to detect whether the item is selected.
* @attr {string} item-id-path
*/
itemIdPath: {
type: String,
},
/**
* The object used to localize this component.
* To change the default localization, replace the entire
* _i18n_ object or just the property you want to modify.
*
* The object has the following JSON structure and default values:
* ```
* {
* // Screen reader announcement on clear button click.
* cleared: 'Selection cleared',
* // Screen reader announcement when a chip is focused.
* focused: ' focused. Press Backspace to remove',
* // Screen reader announcement when item is selected.
* selected: 'added to selection',
* // Screen reader announcement when item is deselected.
* deselected: 'removed from selection',
* // Screen reader announcement of the selected items count.
* // {count} is replaced with the actual count of items.
* total: '{count} items selected',
* }
* ```
* @type {!MultiSelectComboBoxI18n}
* @default {English/US}
*/
i18n: {
type: Object,
value: () => {
return {
cleared: 'Selection cleared',
focused: 'focused. Press Backspace to remove',
selected: 'added to selection',
deselected: 'removed from selection',
total: '{count} items selected',
};
},
},
/**
* When true, filter string isn't cleared after selecting an item.
*/
keepFilter: {
type: Boolean,
value: false,
},
/**
* True when loading items from the data provider, false otherwise.
*/
loading: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
/**
* When present, it specifies that the field is read-only.
*/
readonly: {
type: Boolean,
value: false,
observer: '_readonlyChanged',
reflectToAttribute: true,
},
/**
* The list of selected items.
* Note: modifying the selected items creates a new array each time.
*/
selectedItems: {
type: Array,
value: () => [],
notify: true,
},
/**
* True if the dropdown is open, false otherwise.
*/
opened: {
type: Boolean,
notify: true,
value: false,
reflectToAttribute: true,
},
/**
* Total number of items.
*/
size: {
type: Number,
},
/**
* Number of items fetched at a time from the data provider.
* @attr {number} page-size
*/
pageSize: {
type: Number,
value: 50,
observer: '_pageSizeChanged',
},
/**
* Function that provides items lazily. Receives two arguments:
*
* - `params` - Object with the following properties:
* - `params.page` Requested page index
* - `params.pageSize` Current page size
* - `params.filter` Currently applied filter
*
* - `callback(items, size)` - Callback function with arguments:
* - `items` Current page of items
* - `size` Total number of items.
*/
dataProvider: {
type: Object,
},
/**
* When true, the user can input a value that is not present in the items list.
* @attr {boolean} allow-custom-value
*/
allowCustomValue: {
type: Boolean,
value: false,
},
/**
* A hint to the user of what can be entered in the control.
* The placeholder will be only displayed in the case when
* there is no item selected.
*/
placeholder: {
type: String,
value: '',
observer: '_placeholderChanged',
},
/**
* Custom function for rendering the content of every item.
* Receives three arguments:
*
* - `root` The `<vaadin-multi-select-combo-box-item>` internal container DOM element.
* - `comboBox` The reference to the `<vaadin-multi-select-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.
*/
renderer: Function,
/**
* Filtering string the user has typed into the input field.
*/
filter: {
type: String,
value: '',
notify: true,
},
/**
* 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.
*/
filteredItems: Array,
/**
* Set to true to group selected items at the top of the overlay.
* @attr {boolean} selected-items-on-top
*/
selectedItemsOnTop: {
type: Boolean,
value: false,
},
/** @private */
value: {
type: String,
},
/** @private */
__effectiveItems: {
type: Array,
computed: '__computeEffectiveItems(items, selectedItems, readonly)',
},
/** @private */
__effectiveFilteredItems: {
type: Array,
computed: '__computeEffectiveFilteredItems(items, filteredItems, selectedItems, readonly)',
},
/** @private */
_overflowItems: {
type: Array,
value: () => [],
},
/** @private */
_focusedChipIndex: {
type: Number,
value: -1,
observer: '_focusedChipIndexChanged',
},
/** @private */
_lastFilter: {
type: String,
},
/** @private */
_topGroup: {
type: Array,
},
};
}
static get observers() {
return [
'_selectedItemsChanged(selectedItems, selectedItems.*)',
'__updateTopGroup(selectedItemsOnTop, selectedItems, opened)',
];
}
/** @protected */
get slotStyles() {
const tag = this.localName;
return [
...super.slotStyles,
`
${tag}[has-value] input::placeholder {
color: transparent !important;
}
`,
];
}
/**
* Used by `InputControlMixin` as a reference to the clear button element.
* @protected
* @return {!HTMLElement}
*/
get clearElement() {
return this.$.clearButton;
}
/** @protected */
get _chips() {
return this.shadowRoot.querySelectorAll('[part~="chip"]');
}
/** @protected */
ready() {
super.ready();
this.addController(
new InputController(this, (input) => {
this._setInputElement(input);
this._setFocusElement(input);
this.stateTarget = input;
this.ariaTarget = input;
}),
);
this.addController(new LabelledInputController(this.inputElement, this._labelController));
this._tooltipController = new TooltipController(this);
this.addController(this._tooltipController);
this._tooltipController.setPosition('top');
this._tooltipController.setShouldShow((target) => !target.opened);
this._inputField = this.shadowRoot.querySelector('[part="input-field"]');
this.__updateChips();
processTemplates(this);
}
/**
* Returns true if the current input value satisfies all constraints (if any).
* @return {boolean}
*/
checkValidity() {
return this.required && !this.readonly ? this._hasValue : true;
}
/**
* Clears the selected items.
*/
clear() {
this.__updateSelection([]);
announce(this.i18n.cleared);
}
/**
* Clears the cached pages and reloads data from data provider when needed.
*/
clearCache() {
if (this.$ && this.$.comboBox) {
this.$.comboBox.clearCache();
}
}
/**
* 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.$ && this.$.comboBox) {
this.$.comboBox.requestContentUpdate();
}
}
/**
* Override method inherited from `DisabledMixin` to forward disabled to chips.
* @protected
* @override
*/
_disabledChanged(disabled, oldDisabled) {
super._disabledChanged(disabled, oldDisabled);
if (disabled || oldDisabled) {
this.__updateChips();
}
}
/**
* Override method inherited from `InputMixin` to forward the input to combo-box.
* @protected
* @override
*/
_inputElementChanged(input) {
super._inputElementChanged(input);
if (input) {
this.$.comboBox._setInputElement(input);
}
}
/**
* Override method inherited from `FocusMixin` to validate on blur.
* @param {boolean} focused
* @protected
*/
_setFocused(focused) {
super._setFocused(focused);
if (!focused) {
this._focusedChipIndex = -1;
this.validate();
}
}
/**
* Implement callback from `ResizeMixin` to update chips.
* @protected
* @override
*/
_onResize() {
this.__updateChips();
}
/**
* Override method from `DelegateStateMixin` to set required state
* using `aria-required` attribute instead of `required`, in order
* to prevent screen readers from announcing "invalid entry".
* @protected
* @override
*/
_delegateAttribute(name, value) {
if (!this.stateTarget) {
return;
}
if (name === 'required') {
this._delegateAttribute('aria-required', value ? 'true' : false);
return;
}
super._delegateAttribute(name, value);
}
/** @private */
_autoExpandHorizontallyChanged(autoExpand, oldAutoExpand) {
if (autoExpand || oldAutoExpand) {
this.__updateChips();
}
}
/** @private */
_autoExpandVerticallyChanged(autoExpand, oldAutoExpand) {
if (autoExpand || oldAutoExpand) {
this.__updateChips();
}
}
/**
* Setting clear button visible reduces total space available
* for rendering chips, and making it hidden increases it.
* @private
*/
_clearButtonVisibleChanged(visible, oldVisible) {
if (visible || oldVisible) {
this.__updateChips();
}
}
/**
* Implement two-way binding for the `filteredItems` property
* that can be set on the internal combo-box element.
*
* @param {CustomEvent} event
* @private
*/
_onFilteredItemsChanged(event) {
const { value } = event.detail;
if (Array.isArray(value) || value == null) {
this.filteredItems = value;
}
}
/** @private */
_readonlyChanged(readonly, oldReadonly) {
if (readonly || oldReadonly) {
this.__updateChips();
}
if (this.dataProvider) {
this.clearCache();
}
}
/** @private */
_pageSizeChanged(pageSize, oldPageSize) {
if (Math.floor(pageSize) !== pageSize || pageSize <= 0) {
this.pageSize = oldPageSize;
console.error('"pageSize" value must be an integer > 0');
}
this.$.comboBox.pageSize = this.pageSize;
}
/** @private */
_placeholderChanged(placeholder) {
const tmpPlaceholder = this.__tmpA11yPlaceholder;
// Do not store temporary placeholder
if (tmpPlaceholder !== placeholder) {
this.__savedPlaceholder = placeholder;
if (tmpPlaceholder) {
this.placeholder = tmpPlaceholder;
}
}
}
/** @private */
_selectedItemsChanged(selectedItems) {
this._toggleHasValue(this._hasValue);
// Use placeholder for announcing items
if (this._hasValue) {
const tmpPlaceholder = this._mergeItemLabels(selectedItems);
this.__tmpA11yPlaceholder = tmpPlaceholder;
this.placeholder = tmpPlaceholder;
} else {
delete this.__tmpA11yPlaceholder;
this.placeholder = this.__savedPlaceholder;
}
// Re-render chips
this.__updateChips();
// Update selected for dropdown items
this.requestContentUpdate();
if (this.opened) {
this.$.comboBox.$.overlay._updateOverlayWidth();
}
}
/** @private */
_getItemLabel(item) {
return this.$.comboBox._getItemLabel(item);
}
/** @private */
_getOverflowLabel(length) {
return length;
}
/** @private */
_getOverflowPart(length) {
let part = `chip overflow`;
if (length === 1) {
part += ' overflow-one';
} else if (length === 2) {
part += ' overflow-two';
}
return part;
}
/** @private */
_getOverflowTitle(items) {
return this._mergeItemLabels(items);
}
/** @private */
_isOverflowHidden(length) {
return length === 0;
}
/** @private */
_mergeItemLabels(items) {
return items.map((item) => this._getItemLabel(item)).join(', ');
}
/** @private */
_findIndex(item, selectedItems, itemIdPath) {
if (itemIdPath && item) {
for (let index = 0; index < selectedItems.length; index++) {
if (selectedItems[index] && selectedItems[index][itemIdPath] === item[itemIdPath]) {
return index;
}
}
return -1;
}
return selectedItems.indexOf(item);
}
/**
* Clear the internal combo box value and filter. Filter will not be cleared
* when the `keepFilter` option is enabled. Using `force` can enforce clearing
* the filter.
* @param {boolean} force overrides the keepFilter option
* @private
*/
__clearInternalValue(force = false) {
if (!this.keepFilter || force) {
// Clear both combo box value and filter.
this.filter = '';
this.$.comboBox.clear();
} else {
// Only clear combo box value. This effectively resets _lastCommittedValue
// which allows toggling the same item multiple times via keyboard.
this.$.comboBox.clear();
// Restore input to the filter value. Needed when items are
// navigated with keyboard, which overrides the input value
// with the item label.
this.inputElement.value = this.filter;
}
}
/** @private */
__announceItem(itemLabel, isSelected, itemCount) {
const state = isSelected ? 'selected' : 'deselected';
const total = this.i18n.total.replace('{count}', itemCount || 0);
announce(`${itemLabel} ${this.i18n[state]} ${total}`);
}
/** @private */
__removeItem(item) {
const itemsCopy = [...this.selectedItems];
itemsCopy.splice(itemsCopy.indexOf(item), 1);
this.__updateSelection(itemsCopy);
const itemLabel = this._getItemLabel(item);
this.__announceItem(itemLabel, false, itemsCopy.length);
}
/** @private */
__selectItem(item) {
const itemsCopy = [...this.selectedItems];
const index = this._findIndex(item, itemsCopy, this.itemIdPath);
const itemLabel = this._getItemLabel(item);
let isSelected = false;
if (index !== -1) {
const lastFilter = this._lastFilter;
// Do not unselect when manually typing and committing an already selected item.
if (lastFilter && lastFilter.toLowerCase() === itemLabel.toLowerCase()) {
this.__clearInternalValue();
return;
}
itemsCopy.splice(index, 1);
} else {
itemsCopy.push(item);
isSelected = true;
}
this.__updateSelection(itemsCopy);
// Suppress `value-changed` event.
this.__clearInternalValue();
this.__announceItem(itemLabel, isSelected, itemsCopy.length);
}
/** @private */
__updateSelection(selectedItems) {
this.selectedItems = selectedItems;
this.validate();
this.dispatchEvent(new CustomEvent('change', { bubbles: true }));
}
/** @private */
__updateTopGroup(selectedItemsOnTop, selectedItems, opened) {
if (!selectedItemsOnTop) {
this._topGroup = [];
} else if (!opened) {
this._topGroup = [...selectedItems];
}
}
/** @private */
__createChip(item) {
const chip = document.createElement('vaadin-multi-select-combo-box-chip');
chip.setAttribute('part', 'chip');
chip.setAttribute('slot', 'prefix');
chip.item = item;
chip.disabled = this.disabled;
chip.readonly = this.readonly;
const label = this._getItemLabel(item);
chip.label = label;
chip.setAttribute('title', label);
chip.addEventListener('item-removed', (e) => this._onItemRemoved(e));
chip.addEventListener('mousedown', (e) => this._preventBlur(e));
return chip;
}
/** @private */
__getOverflowWidth() {
const chip = this.$.overflow;
chip.style.visibility = 'hidden';
chip.removeAttribute('hidden');
// Detect max possible width of the overflow chip
chip.setAttribute('part', 'chip overflow');
const overflowStyle = getComputedStyle(chip);
const overflowWidth = chip.clientWidth + parseInt(overflowStyle.marginInlineStart);
chip.setAttribute('hidden', '');
chip.style.visibility = '';
return overflowWidth;
}
/** @private */
__updateChips() {
if (!this._inputField || !this.inputElement) {
return;
}
// Clear all chips except the overflow
Array.from(this._chips).forEach((chip) => {
if (chip !== this.$.overflow) {
chip.remove();
}
});
const items = [...this.selectedItems];
// Detect available remaining width for chips
const totalWidth = this._inputField.$.wrapper.clientWidth;
const inputWidth = parseInt(getComputedStyle(this.inputElement).flexBasis);
let remainingWidth = totalWidth - inputWidth;
if (items.length > 1) {
remainingWidth -= this.__getOverflowWidth();
}
const chipMinWidth = parseInt(getComputedStyle(this).getPropertyValue('--_chip-min-width'));
if (this.autoExpandHorizontally) {
const chips = [];