-
-
Notifications
You must be signed in to change notification settings - Fork 875
/
Copy pathselect.component.ts
971 lines (823 loc) · 32.7 KB
/
select.component.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
import { animateTo, stopAnimations } from '../../internal/animate.js';
import { classMap } from 'lit/directives/class-map.js';
import { FormControlController } from '../../internal/form.js';
import { getAnimation, setDefaultAnimation } from '../../utilities/animation-registry.js';
import { HasSlotController } from '../../internal/slot.js';
import { html } from 'lit';
import { LocalizeController } from '../../utilities/localize.js';
import { property, query, state } from 'lit/decorators.js';
import { scrollIntoView } from '../../internal/scroll.js';
import { unsafeHTML } from 'lit/directives/unsafe-html.js';
import { waitForEvent } from '../../internal/event.js';
import { watch } from '../../internal/watch.js';
import componentStyles from '../../styles/component.styles.js';
import formControlStyles from '../../styles/form-control.styles.js';
import ShoelaceElement from '../../internal/shoelace-element.js';
import SlIcon from '../icon/icon.component.js';
import SlPopup from '../popup/popup.component.js';
import SlTag from '../tag/tag.component.js';
import styles from './select.styles.js';
import type { CSSResultGroup, TemplateResult } from 'lit';
import type { ShoelaceFormControl } from '../../internal/shoelace-element.js';
import type { SlRemoveEvent } from '../../events/sl-remove.js';
import type SlOption from '../option/option.component.js';
/**
* @summary Selects allow you to choose items from a menu of predefined options.
* @documentation https://shoelace.style/components/select
* @status stable
* @since 2.0
*
* @dependency sl-icon
* @dependency sl-popup
* @dependency sl-tag
*
* @slot - The listbox options. Must be `<sl-option>` elements. You can use `<sl-divider>` to group items visually.
* @slot label - The input's label. Alternatively, you can use the `label` attribute.
* @slot prefix - Used to prepend a presentational icon or similar element to the combobox.
* @slot suffix - Used to append a presentational icon or similar element to the combobox.
* @slot clear-icon - An icon to use in lieu of the default clear icon.
* @slot expand-icon - The icon to show when the control is expanded and collapsed. Rotates on open and close.
* @slot help-text - Text that describes how to use the input. Alternatively, you can use the `help-text` attribute.
*
* @event sl-change - Emitted when the control's value changes.
* @event sl-clear - Emitted when the control's value is cleared.
* @event sl-input - Emitted when the control receives input.
* @event sl-focus - Emitted when the control gains focus.
* @event sl-blur - Emitted when the control loses focus.
* @event sl-show - Emitted when the select's menu opens.
* @event sl-after-show - Emitted after the select's menu opens and all animations are complete.
* @event sl-hide - Emitted when the select's menu closes.
* @event sl-after-hide - Emitted after the select's menu closes and all animations are complete.
* @event sl-invalid - Emitted when the form control has been checked for validity and its constraints aren't satisfied.
*
* @csspart form-control - The form control that wraps the label, input, and help text.
* @csspart form-control-label - The label's wrapper.
* @csspart form-control-input - The select's wrapper.
* @csspart form-control-help-text - The help text's wrapper.
* @csspart combobox - The container the wraps the prefix, suffix, combobox, clear icon, and expand button.
* @csspart prefix - The container that wraps the prefix slot.
* @csspart suffix - The container that wraps the suffix slot.
* @csspart display-input - The element that displays the selected option's label, an `<input>` element.
* @csspart listbox - The listbox container where options are slotted.
* @csspart tags - The container that houses option tags when `multiselect` is used.
* @csspart tag - The individual tags that represent each multiselect option.
* @csspart tag__base - The tag's base part.
* @csspart tag__content - The tag's content part.
* @csspart tag__remove-button - The tag's remove button.
* @csspart tag__remove-button__base - The tag's remove button base part.
* @csspart clear-button - The clear button.
* @csspart expand-icon - The container that wraps the expand icon.
*/
export default class SlSelect extends ShoelaceElement implements ShoelaceFormControl {
static styles: CSSResultGroup = [componentStyles, formControlStyles, styles];
static dependencies = {
'sl-icon': SlIcon,
'sl-popup': SlPopup,
'sl-tag': SlTag
};
private readonly formControlController = new FormControlController(this, {
assumeInteractionOn: ['sl-blur', 'sl-input']
});
private readonly hasSlotController = new HasSlotController(this, 'help-text', 'label');
private readonly localize = new LocalizeController(this);
private typeToSelectString = '';
private typeToSelectTimeout: number;
private closeWatcher: CloseWatcher | null;
@query('.select') popup: SlPopup;
@query('.select__combobox') combobox: HTMLSlotElement;
@query('.select__display-input') displayInput: HTMLInputElement;
@query('.select__value-input') valueInput: HTMLInputElement;
@query('.select__listbox') listbox: HTMLSlotElement;
@state() private hasFocus = false;
@state() displayLabel = '';
@state() currentOption: SlOption;
@state() selectedOptions: SlOption[] = [];
@state() private valueHasChanged: boolean = false;
/** The name of the select, submitted as a name/value pair with form data. */
@property() name = '';
private _value: string | string[] = '';
get value() {
return this._value;
}
/**
* The current value of the select, submitted as a name/value pair with form data. When `multiple` is enabled, the
* value attribute will be a space-delimited list of values based on the options selected, and the value property will
* be an array. **For this reason, values must not contain spaces.**
*/
@state()
set value(val: string | string[]) {
if (this.multiple) {
val = Array.isArray(val) ? val : val.split(' ');
} else {
val = Array.isArray(val) ? val.join(' ') : val;
}
if (this._value === val) {
return;
}
this.valueHasChanged = true;
this._value = val;
}
/** The default value of the form control. Primarily used for resetting the form control. */
@property({ attribute: 'value' }) defaultValue: string | string[] = '';
/** The select's size. */
@property({ reflect: true }) size: 'small' | 'medium' | 'large' = 'medium';
/** Placeholder text to show as a hint when the select is empty. */
@property() placeholder = '';
/** Allows more than one option to be selected. */
@property({ type: Boolean, reflect: true }) multiple = false;
/**
* The maximum number of selected options to show when `multiple` is true. After the maximum, "+n" will be shown to
* indicate the number of additional items that are selected. Set to 0 to remove the limit.
*/
@property({ attribute: 'max-options-visible', type: Number }) maxOptionsVisible = 3;
/** Disables the select control. */
@property({ type: Boolean, reflect: true }) disabled = false;
/** Adds a clear button when the select is not empty. */
@property({ type: Boolean }) clearable = false;
/**
* Indicates whether or not the select is open. You can toggle this attribute to show and hide the menu, or you can
* use the `show()` and `hide()` methods and this attribute will reflect the select's open state.
*/
@property({ type: Boolean, reflect: true }) open = false;
/**
* Enable this option to prevent the listbox from being clipped when the component is placed inside a container with
* `overflow: auto|scroll`. Hoisting uses a fixed positioning strategy that works in many, but not all, scenarios.
*/
@property({ type: Boolean }) hoist = false;
/** Draws a filled select. */
@property({ type: Boolean, reflect: true }) filled = false;
/** Draws a pill-style select with rounded edges. */
@property({ type: Boolean, reflect: true }) pill = false;
/** The select's label. If you need to display HTML, use the `label` slot instead. */
@property() label = '';
/**
* The preferred placement of the select's menu. Note that the actual placement may vary as needed to keep the listbox
* inside of the viewport.
*/
@property({ reflect: true }) placement: 'top' | 'bottom' = 'bottom';
/** The select's help text. If you need to display HTML, use the `help-text` slot instead. */
@property({ attribute: 'help-text' }) helpText = '';
/**
* By default, form controls are associated with the nearest containing `<form>` element. This attribute allows you
* to place the form control outside of a form and associate it with the form that has this `id`. The form must be in
* the same document or shadow root for this to work.
*/
@property({ reflect: true }) form = '';
/** The select's required attribute. */
@property({ type: Boolean, reflect: true }) required = false;
/**
* A function that customizes the tags to be rendered when multiple=true. The first argument is the option, the second
* is the current tag's index. The function should return either a Lit TemplateResult or a string containing trusted HTML of the symbol to render at
* the specified value.
*/
@property() getTag: (option: SlOption, index: number) => TemplateResult | string | HTMLElement = option => {
return html`
<sl-tag
part="tag"
exportparts="
base:tag__base,
content:tag__content,
remove-button:tag__remove-button,
remove-button__base:tag__remove-button__base
"
?pill=${this.pill}
size=${this.size}
removable
@sl-remove=${(event: SlRemoveEvent) => this.handleTagRemove(event, option)}
>
${option.getTextLabel()}
</sl-tag>
`;
};
/** Gets the validity state object */
get validity() {
return this.valueInput.validity;
}
/** Gets the validation message */
get validationMessage() {
return this.valueInput.validationMessage;
}
connectedCallback() {
super.connectedCallback();
setTimeout(() => {
this.handleDefaultSlotChange();
});
// Because this is a form control, it shouldn't be opened initially
this.open = false;
}
private addOpenListeners() {
//
// Listen on the root node instead of the document in case the elements are inside a shadow root
//
// https://github.com/shoelace-style/shoelace/issues/1763
//
document.addEventListener('focusin', this.handleDocumentFocusIn);
document.addEventListener('keydown', this.handleDocumentKeyDown);
document.addEventListener('mousedown', this.handleDocumentMouseDown);
// If the component is rendered in a shadow root, we need to attach the focusin listener there too
if (this.getRootNode() !== document) {
this.getRootNode().addEventListener('focusin', this.handleDocumentFocusIn);
}
if ('CloseWatcher' in window) {
this.closeWatcher?.destroy();
this.closeWatcher = new CloseWatcher();
this.closeWatcher.onclose = () => {
if (this.open) {
this.hide();
this.displayInput.focus({ preventScroll: true });
}
};
}
}
private removeOpenListeners() {
document.removeEventListener('focusin', this.handleDocumentFocusIn);
document.removeEventListener('keydown', this.handleDocumentKeyDown);
document.removeEventListener('mousedown', this.handleDocumentMouseDown);
if (this.getRootNode() !== document) {
this.getRootNode().removeEventListener('focusin', this.handleDocumentFocusIn);
}
this.closeWatcher?.destroy();
}
private handleFocus() {
this.hasFocus = true;
this.displayInput.setSelectionRange(0, 0);
this.emit('sl-focus');
}
private handleBlur() {
this.hasFocus = false;
this.emit('sl-blur');
}
private handleDocumentFocusIn = (event: KeyboardEvent) => {
// Close when focusing out of the select
const path = event.composedPath();
if (this && !path.includes(this)) {
this.hide();
}
};
private handleDocumentKeyDown = (event: KeyboardEvent) => {
const target = event.target as HTMLElement;
const isClearButton = target.closest('.select__clear') !== null;
const isIconButton = target.closest('sl-icon-button') !== null;
// Ignore presses when the target is an icon button (e.g. the remove button in <sl-tag>)
if (isClearButton || isIconButton) {
return;
}
// Close when pressing escape
if (event.key === 'Escape' && this.open && !this.closeWatcher) {
event.preventDefault();
event.stopPropagation();
this.hide();
this.displayInput.focus({ preventScroll: true });
}
// Handle enter and space. When pressing space, we allow for type to select behaviors so if there's anything in the
// buffer we _don't_ close it.
if (event.key === 'Enter' || (event.key === ' ' && this.typeToSelectString === '')) {
event.preventDefault();
event.stopImmediatePropagation();
// If it's not open, open it
if (!this.open) {
this.show();
return;
}
// If it is open, update the value based on the current selection and close it
if (this.currentOption && !this.currentOption.disabled) {
this.valueHasChanged = true;
if (this.multiple) {
this.toggleOptionSelection(this.currentOption);
} else {
this.setSelectedOptions(this.currentOption);
}
// Emit after updating
this.updateComplete.then(() => {
this.emit('sl-input');
this.emit('sl-change');
});
if (!this.multiple) {
this.hide();
this.displayInput.focus({ preventScroll: true });
}
}
return;
}
// Navigate options
if (['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) {
const allOptions = this.getAllOptions();
const currentIndex = allOptions.indexOf(this.currentOption);
let newIndex = Math.max(0, currentIndex);
// Prevent scrolling
event.preventDefault();
// Open it
if (!this.open) {
this.show();
// If an option is already selected, stop here because we want that one to remain highlighted when the listbox
// opens for the first time
if (this.currentOption) {
return;
}
}
if (event.key === 'ArrowDown') {
newIndex = currentIndex + 1;
if (newIndex > allOptions.length - 1) newIndex = 0;
} else if (event.key === 'ArrowUp') {
newIndex = currentIndex - 1;
if (newIndex < 0) newIndex = allOptions.length - 1;
} else if (event.key === 'Home') {
newIndex = 0;
} else if (event.key === 'End') {
newIndex = allOptions.length - 1;
}
this.setCurrentOption(allOptions[newIndex]);
}
// All other "printable" keys trigger type to select
if ((event.key && event.key.length === 1) || event.key === 'Backspace') {
const allOptions = this.getAllOptions();
// Don't block important key combos like CMD+R
if (event.metaKey || event.ctrlKey || event.altKey) {
return;
}
// Open, unless the key that triggered is backspace
if (!this.open) {
if (event.key === 'Backspace') {
return;
}
this.show();
}
event.stopPropagation();
event.preventDefault();
clearTimeout(this.typeToSelectTimeout);
this.typeToSelectTimeout = window.setTimeout(() => (this.typeToSelectString = ''), 1000);
if (event.key === 'Backspace') {
this.typeToSelectString = this.typeToSelectString.slice(0, -1);
} else {
this.typeToSelectString += event.key.toLowerCase();
}
for (const option of allOptions) {
const label = option.getTextLabel().toLowerCase();
if (label.startsWith(this.typeToSelectString)) {
this.setCurrentOption(option);
break;
}
}
}
};
private handleDocumentMouseDown = (event: MouseEvent) => {
// Close when clicking outside of the select
const path = event.composedPath();
if (this && !path.includes(this)) {
this.hide();
}
};
private handleLabelClick() {
this.displayInput.focus();
}
private handleComboboxMouseDown(event: MouseEvent) {
const path = event.composedPath();
const isIconButton = path.some(el => el instanceof Element && el.tagName.toLowerCase() === 'sl-icon-button');
// Ignore disabled controls and clicks on tags (remove buttons)
if (this.disabled || isIconButton) {
return;
}
event.preventDefault();
this.displayInput.focus({ preventScroll: true });
this.open = !this.open;
}
private handleComboboxKeyDown(event: KeyboardEvent) {
if (event.key === 'Tab') {
return;
}
event.stopPropagation();
this.handleDocumentKeyDown(event);
}
private handleClearClick(event: MouseEvent) {
event.stopPropagation();
this.valueHasChanged = true;
if (this.value !== '') {
this.setSelectedOptions([]);
this.displayInput.focus({ preventScroll: true });
// Emit after update
this.updateComplete.then(() => {
this.emit('sl-clear');
this.emit('sl-input');
this.emit('sl-change');
});
}
}
private handleClearMouseDown(event: MouseEvent) {
// Don't lose focus or propagate events when clicking the clear button
event.stopPropagation();
event.preventDefault();
}
private handleOptionClick(event: MouseEvent) {
const target = event.target as HTMLElement;
const option = target.closest('sl-option');
const oldValue = this.value;
if (option && !option.disabled) {
this.valueHasChanged = true;
if (this.multiple) {
this.toggleOptionSelection(option);
} else {
this.setSelectedOptions(option);
}
// Set focus after updating so the value is announced by screen readers
this.updateComplete.then(() => this.displayInput.focus({ preventScroll: true }));
if (this.value !== oldValue) {
// Emit after updating
this.updateComplete.then(() => {
this.emit('sl-input');
this.emit('sl-change');
});
}
if (!this.multiple) {
this.hide();
this.displayInput.focus({ preventScroll: true });
}
}
}
/* @internal - used by options to update labels */
public handleDefaultSlotChange() {
if (!customElements.get('sl-option')) {
customElements.whenDefined('sl-option').then(() => this.handleDefaultSlotChange());
}
const allOptions = this.getAllOptions();
const val = this.valueHasChanged ? this.value : this.defaultValue;
const value = Array.isArray(val) ? val : [val];
const values: string[] = [];
// Check for duplicate values in menu items
allOptions.forEach(option => values.push(option.value));
// Select only the options that match the new value
this.setSelectedOptions(allOptions.filter(el => value.includes(el.value)));
}
private handleTagRemove(event: SlRemoveEvent, option: SlOption) {
event.stopPropagation();
this.valueHasChanged = true;
if (!this.disabled) {
this.toggleOptionSelection(option, false);
// Emit after updating
this.updateComplete.then(() => {
this.emit('sl-input');
this.emit('sl-change');
});
}
}
// Gets an array of all <sl-option> elements
private getAllOptions() {
return [...this.querySelectorAll<SlOption>('sl-option')];
}
// Gets the first <sl-option> element
private getFirstOption() {
return this.querySelector<SlOption>('sl-option');
}
// Sets the current option, which is the option the user is currently interacting with (e.g. via keyboard). Only one
// option may be "current" at a time.
private setCurrentOption(option: SlOption | null) {
const allOptions = this.getAllOptions();
// Clear selection
allOptions.forEach(el => {
el.current = false;
el.tabIndex = -1;
});
// Select the target option
if (option) {
this.currentOption = option;
option.current = true;
option.tabIndex = 0;
option.focus();
}
}
// Sets the selected option(s)
private setSelectedOptions(option: SlOption | SlOption[]) {
const allOptions = this.getAllOptions();
const newSelectedOptions = Array.isArray(option) ? option : [option];
// Clear existing selection
allOptions.forEach(el => (el.selected = false));
// Set the new selection
if (newSelectedOptions.length) {
newSelectedOptions.forEach(el => (el.selected = true));
}
// Update selection, value, and display label
this.selectionChanged();
}
// Toggles an option's selected state
private toggleOptionSelection(option: SlOption, force?: boolean) {
if (force === true || force === false) {
option.selected = force;
} else {
option.selected = !option.selected;
}
this.selectionChanged();
}
// This method must be called whenever the selection changes. It will update the selected options cache, the current
// value, and the display value
private selectionChanged() {
const options = this.getAllOptions();
// Update selected options cache
this.selectedOptions = options.filter(el => el.selected);
// Keep a reference to the previous `valueHasChanged`. Changes made here don't count has changing the value.
const cachedValueHasChanged = this.valueHasChanged;
// Update the value and display label
if (this.multiple) {
this.value = this.selectedOptions.map(el => el.value);
if (this.placeholder && this.value.length === 0) {
// When no items are selected, keep the value empty so the placeholder shows
this.displayLabel = '';
} else {
this.displayLabel = this.localize.term('numOptionsSelected', this.selectedOptions.length);
}
} else {
const selectedOption = this.selectedOptions[0];
this.value = selectedOption?.value ?? '';
this.displayLabel = selectedOption?.getTextLabel?.() ?? '';
}
this.valueHasChanged = cachedValueHasChanged;
// Update validity
this.updateComplete.then(() => {
this.formControlController.updateValidity();
});
}
protected get tags() {
return this.selectedOptions.map((option, index) => {
if (index < this.maxOptionsVisible || this.maxOptionsVisible <= 0) {
const tag = this.getTag(option, index);
// Wrap so we can handle the remove
return html`<div @sl-remove=${(e: SlRemoveEvent) => this.handleTagRemove(e, option)}>
${typeof tag === 'string' ? unsafeHTML(tag) : tag}
</div>`;
} else if (index === this.maxOptionsVisible) {
// Hit tag limit
return html`<sl-tag size=${this.size}>+${this.selectedOptions.length - index}</sl-tag>`;
}
return html``;
});
}
private handleInvalid(event: Event) {
this.formControlController.setValidity(false);
this.formControlController.emitInvalidEvent(event);
}
@watch('disabled', { waitUntilFirstUpdate: true })
handleDisabledChange() {
// Close the listbox when the control is disabled
if (this.disabled) {
this.open = false;
this.handleOpenChange();
}
}
attributeChangedCallback(name: string, oldVal: string | null, newVal: string | null) {
super.attributeChangedCallback(name, oldVal, newVal);
/** This is a backwards compatibility call. In a new major version we should make a clean separation between "value" the attribute mapping to "defaultValue" property and "value" the property not reflecting. */
if (name === 'value') {
const cachedValueHasChanged = this.valueHasChanged;
this.value = this.defaultValue;
// Set it back to false since this isn't an interaction.
this.valueHasChanged = cachedValueHasChanged;
}
}
@watch(['defaultValue', 'value'], { waitUntilFirstUpdate: true })
handleValueChange() {
if (!this.valueHasChanged) {
const cachedValueHasChanged = this.valueHasChanged;
this.value = this.defaultValue;
// Set it back to false since this isn't an interaction.
this.valueHasChanged = cachedValueHasChanged;
}
const allOptions = this.getAllOptions();
const value = Array.isArray(this.value) ? this.value : [this.value];
// Select only the options that match the new value
this.setSelectedOptions(allOptions.filter(el => value.includes(el.value)));
}
@watch('open', { waitUntilFirstUpdate: true })
async handleOpenChange() {
if (this.open && !this.disabled) {
// Reset the current option
this.setCurrentOption(this.selectedOptions[0] || this.getFirstOption());
// Show
this.emit('sl-show');
this.addOpenListeners();
await stopAnimations(this);
this.listbox.hidden = false;
this.popup.active = true;
// Select the appropriate option based on value after the listbox opens
requestAnimationFrame(() => {
this.setCurrentOption(this.currentOption);
});
const { keyframes, options } = getAnimation(this, 'select.show', { dir: this.localize.dir() });
await animateTo(this.popup.popup, keyframes, options);
// Make sure the current option is scrolled into view (required for Safari)
if (this.currentOption) {
scrollIntoView(this.currentOption, this.listbox, 'vertical', 'auto');
}
this.emit('sl-after-show');
} else {
// Hide
this.emit('sl-hide');
this.removeOpenListeners();
await stopAnimations(this);
const { keyframes, options } = getAnimation(this, 'select.hide', { dir: this.localize.dir() });
await animateTo(this.popup.popup, keyframes, options);
this.listbox.hidden = true;
this.popup.active = false;
this.emit('sl-after-hide');
}
}
/** Shows the listbox. */
async show() {
if (this.open || this.disabled) {
this.open = false;
return undefined;
}
this.open = true;
return waitForEvent(this, 'sl-after-show');
}
/** Hides the listbox. */
async hide() {
if (!this.open || this.disabled) {
this.open = false;
return undefined;
}
this.open = false;
return waitForEvent(this, 'sl-after-hide');
}
/** Checks for validity but does not show a validation message. Returns `true` when valid and `false` when invalid. */
checkValidity() {
return this.valueInput.checkValidity();
}
/** Gets the associated form, if one exists. */
getForm(): HTMLFormElement | null {
return this.formControlController.getForm();
}
/** Checks for validity and shows the browser's validation message if the control is invalid. */
reportValidity() {
return this.valueInput.reportValidity();
}
/** Sets a custom validation message. Pass an empty string to restore validity. */
setCustomValidity(message: string) {
this.valueInput.setCustomValidity(message);
this.formControlController.updateValidity();
}
/** Sets focus on the control. */
focus(options?: FocusOptions) {
this.displayInput.focus(options);
}
/** Removes focus from the control. */
blur() {
this.displayInput.blur();
}
render() {
const hasLabelSlot = this.hasSlotController.test('label');
const hasHelpTextSlot = this.hasSlotController.test('help-text');
const hasLabel = this.label ? true : !!hasLabelSlot;
const hasHelpText = this.helpText ? true : !!hasHelpTextSlot;
const hasClearIcon = this.clearable && !this.disabled && this.value.length > 0;
const isPlaceholderVisible = this.placeholder && this.value && this.value.length <= 0;
return html`
<div
part="form-control"
class=${classMap({
'form-control': true,
'form-control--small': this.size === 'small',
'form-control--medium': this.size === 'medium',
'form-control--large': this.size === 'large',
'form-control--has-label': hasLabel,
'form-control--has-help-text': hasHelpText
})}
>
<label
id="label"
part="form-control-label"
class="form-control__label"
aria-hidden=${hasLabel ? 'false' : 'true'}
@click=${this.handleLabelClick}
>
<slot name="label">${this.label}</slot>
</label>
<div part="form-control-input" class="form-control-input">
<sl-popup
class=${classMap({
select: true,
'select--standard': true,
'select--filled': this.filled,
'select--pill': this.pill,
'select--open': this.open,
'select--disabled': this.disabled,
'select--multiple': this.multiple,
'select--focused': this.hasFocus,
'select--placeholder-visible': isPlaceholderVisible,
'select--top': this.placement === 'top',
'select--bottom': this.placement === 'bottom',
'select--small': this.size === 'small',
'select--medium': this.size === 'medium',
'select--large': this.size === 'large'
})}
placement=${this.placement}
strategy=${this.hoist ? 'fixed' : 'absolute'}
flip
shift
sync="width"
auto-size="vertical"
auto-size-padding="10"
>
<div
part="combobox"
class="select__combobox"
slot="anchor"
@keydown=${this.handleComboboxKeyDown}
@mousedown=${this.handleComboboxMouseDown}
>
<slot part="prefix" name="prefix" class="select__prefix"></slot>
<input
part="display-input"
class="select__display-input"
type="text"
placeholder=${this.placeholder}
.disabled=${this.disabled}
.value=${this.displayLabel}
autocomplete="off"
spellcheck="false"
autocapitalize="off"
readonly
aria-controls="listbox"
aria-expanded=${this.open ? 'true' : 'false'}
aria-haspopup="listbox"
aria-labelledby="label"
aria-disabled=${this.disabled ? 'true' : 'false'}
aria-describedby="help-text"
role="combobox"
tabindex="0"
@focus=${this.handleFocus}
@blur=${this.handleBlur}
/>
${this.multiple ? html`<div part="tags" class="select__tags">${this.tags}</div>` : ''}
<input
class="select__value-input"
type="text"
?disabled=${this.disabled}
?required=${this.required}
.value=${Array.isArray(this.value) ? this.value.join(', ') : this.value}
tabindex="-1"
aria-hidden="true"
@focus=${() => this.focus()}
@invalid=${this.handleInvalid}
/>
${hasClearIcon
? html`
<button
part="clear-button"
class="select__clear"
type="button"
aria-label=${this.localize.term('clearEntry')}
@mousedown=${this.handleClearMouseDown}
@click=${this.handleClearClick}
tabindex="-1"
>
<slot name="clear-icon">
<sl-icon name="x-circle-fill" library="system"></sl-icon>
</slot>
</button>
`
: ''}
<slot name="suffix" part="suffix" class="select__suffix"></slot>
<slot name="expand-icon" part="expand-icon" class="select__expand-icon">
<sl-icon library="system" name="chevron-down"></sl-icon>
</slot>
</div>
<div
id="listbox"
role="listbox"
aria-expanded=${this.open ? 'true' : 'false'}
aria-multiselectable=${this.multiple ? 'true' : 'false'}
aria-labelledby="label"
part="listbox"
class="select__listbox"
tabindex="-1"
@mouseup=${this.handleOptionClick}
@slotchange=${this.handleDefaultSlotChange}
>
<slot></slot>
</div>
</sl-popup>
</div>
<div
part="form-control-help-text"
id="help-text"
class="form-control__help-text"
aria-hidden=${hasHelpText ? 'false' : 'true'}
>
<slot name="help-text">${this.helpText}</slot>
</div>
</div>
`;
}
}
setDefaultAnimation('select.show', {
keyframes: [
{ opacity: 0, scale: 0.9 },
{ opacity: 1, scale: 1 }
],
options: { duration: 100, easing: 'ease' }
});
setDefaultAnimation('select.hide', {
keyframes: [
{ opacity: 1, scale: 1 },
{ opacity: 0, scale: 0.9 }
],
options: { duration: 100, easing: 'ease' }
});