@vaadin/select 24.2.0-alpha4 → 24.2.0-alpha6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,621 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2017 - 2023 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
+ */
6
+ import { setAriaIDReference } from '@vaadin/a11y-base/src/aria-id-reference.js';
7
+ import { DelegateFocusMixin } from '@vaadin/a11y-base/src/delegate-focus-mixin.js';
8
+ import { KeyboardMixin } from '@vaadin/a11y-base/src/keyboard-mixin.js';
9
+ import { DelegateStateMixin } from '@vaadin/component-base/src/delegate-state-mixin.js';
10
+ import { MediaQueryController } from '@vaadin/component-base/src/media-query-controller.js';
11
+ import { OverlayClassMixin } from '@vaadin/component-base/src/overlay-class-mixin.js';
12
+ import { TooltipController } from '@vaadin/component-base/src/tooltip-controller.js';
13
+ import { generateUniqueId } from '@vaadin/component-base/src/unique-id-utils.js';
14
+ import { FieldMixin } from '@vaadin/field-base/src/field-mixin.js';
15
+ import { LabelController } from '@vaadin/field-base/src/label-controller.js';
16
+ import { ButtonController } from './button-controller.js';
17
+
18
+ /**
19
+ * @polymerMixin
20
+ * @mixes DelegateFocusMixin
21
+ * @mixes DelegateStateMixin
22
+ * @mixes FieldMixin
23
+ * @mixes KeyboardMixin
24
+ * @mixes OverlayClassMixin
25
+ */
26
+ export const SelectBaseMixin = (superClass) =>
27
+ class SelectBaseMixin extends OverlayClassMixin(
28
+ DelegateFocusMixin(DelegateStateMixin(KeyboardMixin(FieldMixin(superClass)))),
29
+ ) {
30
+ static get properties() {
31
+ return {
32
+ /**
33
+ * An array containing items that will be rendered as the options of the select.
34
+ *
35
+ * #### Example
36
+ * ```js
37
+ * select.items = [
38
+ * { label: 'Most recent first', value: 'recent' },
39
+ * { component: 'hr' },
40
+ * { label: 'Rating: low to high', value: 'rating-asc' },
41
+ * { label: 'Rating: high to low', value: 'rating-desc' },
42
+ * { component: 'hr' },
43
+ * { label: 'Price: low to high', value: 'price-asc', disabled: true },
44
+ * { label: 'Price: high to low', value: 'price-desc', disabled: true }
45
+ * ];
46
+ * ```
47
+ *
48
+ * Note: each item is rendered by default as the internal `<vaadin-select-item>` that is an extension of `<vaadin-item>`.
49
+ * To render the item with a custom component, provide a tag name by the `component` property.
50
+ *
51
+ * @type {!Array<!SelectItem>}
52
+ */
53
+ items: {
54
+ type: Array,
55
+ observer: '__itemsChanged',
56
+ },
57
+
58
+ /**
59
+ * Set when the select is open
60
+ * @type {boolean}
61
+ */
62
+ opened: {
63
+ type: Boolean,
64
+ value: false,
65
+ notify: true,
66
+ reflectToAttribute: true,
67
+ observer: '_openedChanged',
68
+ },
69
+
70
+ /**
71
+ * Custom function for rendering the content of the `<vaadin-select>`.
72
+ * Receives two arguments:
73
+ *
74
+ * - `root` The `<vaadin-select-overlay>` internal container
75
+ * DOM element. Append your content to it.
76
+ * - `select` The reference to the `<vaadin-select>` element.
77
+ * @type {!SelectRenderer | undefined}
78
+ */
79
+ renderer: {
80
+ type: Object,
81
+ },
82
+
83
+ /**
84
+ * The `value` property of the selected item, or an empty string
85
+ * if no item is selected.
86
+ * On change or initialization, the component finds the item which matches the
87
+ * value and displays it.
88
+ * If no value is provided to the component, it selects the first item without
89
+ * value or empty value.
90
+ * Hint: If you do not want to select any item by default, you can either set all
91
+ * the values of inner vaadin-items, or set the vaadin-select value to
92
+ * an inexistent value in the items list.
93
+ * @type {string}
94
+ */
95
+ value: {
96
+ type: String,
97
+ value: '',
98
+ notify: true,
99
+ observer: '_valueChanged',
100
+ },
101
+
102
+ /**
103
+ * The name of this element.
104
+ */
105
+ name: {
106
+ type: String,
107
+ },
108
+
109
+ /**
110
+ * A hint to the user of what can be entered in the control.
111
+ * The placeholder will be displayed in the case that there
112
+ * is no item selected, or the selected item has an empty
113
+ * string label, or the selected item has no label and it's
114
+ * DOM content is empty.
115
+ */
116
+ placeholder: {
117
+ type: String,
118
+ },
119
+
120
+ /**
121
+ * When present, it specifies that the element is read-only.
122
+ * @type {boolean}
123
+ */
124
+ readonly: {
125
+ type: Boolean,
126
+ value: false,
127
+ reflectToAttribute: true,
128
+ },
129
+
130
+ /** @private */
131
+ _phone: Boolean,
132
+
133
+ /** @private */
134
+ _phoneMediaQuery: {
135
+ value: '(max-width: 420px), (max-height: 420px)',
136
+ },
137
+
138
+ /** @private */
139
+ _inputContainer: Object,
140
+
141
+ /** @private */
142
+ _items: Object,
143
+ };
144
+ }
145
+
146
+ static get delegateAttrs() {
147
+ return [...super.delegateAttrs, 'invalid'];
148
+ }
149
+
150
+ static get observers() {
151
+ return ['_updateAriaExpanded(opened, focusElement)', '_updateSelectedItem(value, _items, placeholder)'];
152
+ }
153
+
154
+ constructor() {
155
+ super();
156
+
157
+ this._itemId = `value-${this.localName}-${generateUniqueId()}`;
158
+ this._srLabelController = new LabelController(this);
159
+ this._srLabelController.slotName = 'sr-label';
160
+ }
161
+
162
+ /** @protected */
163
+ disconnectedCallback() {
164
+ super.disconnectedCallback();
165
+
166
+ // Making sure the select is closed and removed from DOM after detaching the select.
167
+ this.opened = false;
168
+ }
169
+
170
+ /** @protected */
171
+ ready() {
172
+ super.ready();
173
+
174
+ const overlay = this.shadowRoot.querySelector('vaadin-select-overlay');
175
+ overlay.owner = this;
176
+ this._overlayElement = overlay;
177
+
178
+ this._inputContainer = this.shadowRoot.querySelector('[part~="input-field"]');
179
+
180
+ this._valueButtonController = new ButtonController(this);
181
+ this.addController(this._valueButtonController);
182
+
183
+ this.addController(this._srLabelController);
184
+
185
+ this.addController(
186
+ new MediaQueryController(this._phoneMediaQuery, (matches) => {
187
+ this._phone = matches;
188
+ }),
189
+ );
190
+
191
+ this._tooltipController = new TooltipController(this);
192
+ this._tooltipController.setPosition('top');
193
+ this.addController(this._tooltipController);
194
+ }
195
+
196
+ /**
197
+ * Requests an update for the content of the select.
198
+ * While performing the update, it invokes the renderer passed in the `renderer` property.
199
+ *
200
+ * It is not guaranteed that the update happens immediately (synchronously) after it is requested.
201
+ */
202
+ requestContentUpdate() {
203
+ if (!this._overlayElement) {
204
+ return;
205
+ }
206
+
207
+ this._overlayElement.requestContentUpdate();
208
+
209
+ if (this._menuElement && this._menuElement.items) {
210
+ this._updateSelectedItem(this.value, this._menuElement.items);
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Override an observer from `FieldMixin`
216
+ * to validate when required is removed.
217
+ *
218
+ * @protected
219
+ * @override
220
+ */
221
+ _requiredChanged(required) {
222
+ super._requiredChanged(required);
223
+
224
+ if (required === false) {
225
+ this.validate();
226
+ }
227
+ }
228
+
229
+ /**
230
+ * @param {SelectItem[] | undefined | null} newItems
231
+ * @param {SelectItem[] | undefined | null} oldItems
232
+ * @private
233
+ */
234
+ __itemsChanged(newItems, oldItems) {
235
+ if (newItems || oldItems) {
236
+ this.requestContentUpdate();
237
+ }
238
+ }
239
+
240
+ /**
241
+ * @param {HTMLElement} menuElement
242
+ * @protected
243
+ */
244
+ _assignMenuElement(menuElement) {
245
+ if (menuElement && menuElement !== this.__lastMenuElement) {
246
+ this._menuElement = menuElement;
247
+
248
+ // Ensure items are initialized
249
+ this.__initMenuItems(menuElement);
250
+
251
+ menuElement.addEventListener('items-changed', () => {
252
+ this.__initMenuItems(menuElement);
253
+ });
254
+
255
+ menuElement.addEventListener('selected-changed', () => this.__updateValueButton());
256
+ // Use capture phase to make it possible for `<vaadin-grid-pro-edit-select>`
257
+ // to override and handle the keydown event before the value change happens.
258
+ menuElement.addEventListener('keydown', (e) => this._onKeyDownInside(e), true);
259
+ menuElement.addEventListener(
260
+ 'click',
261
+ () => {
262
+ this.__dispatchChangePending = true;
263
+ },
264
+ true,
265
+ );
266
+
267
+ // Store the menu element reference
268
+ this.__lastMenuElement = menuElement;
269
+ }
270
+ }
271
+
272
+ /** @private */
273
+ __initMenuItems(menuElement) {
274
+ if (menuElement.items) {
275
+ this._items = menuElement.items;
276
+ }
277
+ }
278
+
279
+ /** @private */
280
+ _valueChanged(value, oldValue) {
281
+ this.toggleAttribute('has-value', Boolean(value));
282
+
283
+ // Skip validation during initialization and when
284
+ // a change event is scheduled, as validation will be
285
+ // triggered by `__dispatchChange()` in that case.
286
+ if (oldValue !== undefined && !this.__dispatchChangePending) {
287
+ this.validate();
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Opens the overlay if the field is not read-only.
293
+ *
294
+ * @private
295
+ */
296
+ _onClick(event) {
297
+ // Prevent parent components such as `vaadin-grid`
298
+ // from handling the click event after it bubbles.
299
+ event.preventDefault();
300
+
301
+ this.opened = !this.readonly;
302
+ }
303
+
304
+ /** @private */
305
+ _onToggleMouseDown(event) {
306
+ // Prevent mousedown event to avoid blur and preserve focused state
307
+ // while opening, and to restore focus-ring attribute on closing.
308
+ event.preventDefault();
309
+ }
310
+
311
+ /**
312
+ * @param {!KeyboardEvent} e
313
+ * @protected
314
+ * @override
315
+ */
316
+ _onKeyDown(e) {
317
+ if (e.target === this.focusElement && !this.readonly && !this.opened) {
318
+ if (/^(Enter|SpaceBar|\s|ArrowDown|Down|ArrowUp|Up)$/u.test(e.key)) {
319
+ e.preventDefault();
320
+ this.opened = true;
321
+ } else if (/[\p{L}\p{Nd}]/u.test(e.key) && e.key.length === 1) {
322
+ const selected = this._menuElement.selected;
323
+ const currentIdx = selected !== undefined ? selected : -1;
324
+ const newIdx = this._menuElement._searchKey(currentIdx, e.key);
325
+ if (newIdx >= 0) {
326
+ this.__dispatchChangePending = true;
327
+
328
+ // Announce the value selected with the first letter shortcut
329
+ this._updateAriaLive(true);
330
+ this._menuElement.selected = newIdx;
331
+ }
332
+ }
333
+ }
334
+ }
335
+
336
+ /**
337
+ * @param {!KeyboardEvent} e
338
+ * @protected
339
+ */
340
+ _onKeyDownInside(e) {
341
+ if (/^(Tab)$/u.test(e.key)) {
342
+ this.opened = false;
343
+ }
344
+ }
345
+
346
+ /** @private */
347
+ _openedChanged(opened, wasOpened) {
348
+ if (opened) {
349
+ // Avoid multiple announcements when a value gets selected from the dropdown
350
+ this._updateAriaLive(false);
351
+
352
+ if (!this._overlayElement || !this._menuElement || !this.focusElement || this.disabled || this.readonly) {
353
+ this.opened = false;
354
+ return;
355
+ }
356
+
357
+ this._overlayElement.style.setProperty(
358
+ '--vaadin-select-text-field-width',
359
+ `${this._inputContainer.offsetWidth}px`,
360
+ );
361
+
362
+ // Preserve focus-ring to restore it later
363
+ const hasFocusRing = this.hasAttribute('focus-ring');
364
+ this._openedWithFocusRing = hasFocusRing;
365
+
366
+ // Opened select should not keep focus-ring
367
+ if (hasFocusRing) {
368
+ this.removeAttribute('focus-ring');
369
+ }
370
+ } else if (wasOpened) {
371
+ this.focus();
372
+ if (this._openedWithFocusRing) {
373
+ this.setAttribute('focus-ring', '');
374
+ }
375
+
376
+ // Skip validation when a change event is scheduled, as validation
377
+ // will be triggered by `__dispatchChange()` in that case.
378
+ if (!this.__dispatchChangePending) {
379
+ this.validate();
380
+ }
381
+ }
382
+ }
383
+
384
+ /** @private */
385
+ _updateAriaExpanded(opened, focusElement) {
386
+ if (focusElement) {
387
+ focusElement.setAttribute('aria-expanded', opened ? 'true' : 'false');
388
+ }
389
+ }
390
+
391
+ /** @private */
392
+ _updateAriaLive(ariaLive) {
393
+ if (this.focusElement) {
394
+ if (ariaLive) {
395
+ this.focusElement.setAttribute('aria-live', 'polite');
396
+ } else {
397
+ this.focusElement.removeAttribute('aria-live');
398
+ }
399
+ }
400
+ }
401
+
402
+ /** @private */
403
+ __attachSelectedItem(selected) {
404
+ let labelItem;
405
+
406
+ const label = selected.getAttribute('label');
407
+ if (label) {
408
+ labelItem = this.__createItemElement({ label });
409
+ } else {
410
+ labelItem = selected.cloneNode(true);
411
+ }
412
+
413
+ // Store reference to the original item
414
+ labelItem._sourceItem = selected;
415
+
416
+ this.__appendValueItemElement(labelItem, this.focusElement);
417
+
418
+ // Ensure the item gets proper styles
419
+ labelItem.selected = true;
420
+ }
421
+
422
+ /**
423
+ * @param {!SelectItem} item
424
+ * @private
425
+ */
426
+ __createItemElement(item) {
427
+ const itemElement = document.createElement(item.component || 'vaadin-select-item');
428
+ if (item.label) {
429
+ itemElement.textContent = item.label;
430
+ }
431
+ if (item.value) {
432
+ itemElement.value = item.value;
433
+ }
434
+ if (item.disabled) {
435
+ itemElement.disabled = item.disabled;
436
+ }
437
+ return itemElement;
438
+ }
439
+
440
+ /**
441
+ * @param {!HTMLElement} itemElement
442
+ * @param {!HTMLElement} parent
443
+ * @private
444
+ */
445
+ __appendValueItemElement(itemElement, parent) {
446
+ parent.appendChild(itemElement);
447
+ itemElement.removeAttribute('tabindex');
448
+ itemElement.removeAttribute('aria-selected');
449
+ itemElement.removeAttribute('role');
450
+ itemElement.setAttribute('id', this._itemId);
451
+ }
452
+
453
+ /**
454
+ * @param {string} accessibleName
455
+ * @protected
456
+ */
457
+ _accessibleNameChanged(accessibleName) {
458
+ this._srLabelController.setLabel(accessibleName);
459
+ this._setCustomAriaLabelledBy(accessibleName ? this._srLabelController.defaultId : null);
460
+ }
461
+
462
+ /**
463
+ * @param {string} accessibleNameRef
464
+ * @protected
465
+ */
466
+ _accessibleNameRefChanged(accessibleNameRef) {
467
+ this._setCustomAriaLabelledBy(accessibleNameRef);
468
+ }
469
+
470
+ /**
471
+ * @param {string} ariaLabelledby
472
+ * @private
473
+ */
474
+ _setCustomAriaLabelledBy(ariaLabelledby) {
475
+ const labelId = this._getLabelIdWithItemId(ariaLabelledby);
476
+ this._fieldAriaController.setLabelId(labelId, true);
477
+ }
478
+
479
+ /**
480
+ * @param {string | null} labelId
481
+ * @returns string | null
482
+ * @private
483
+ */
484
+ _getLabelIdWithItemId(labelId) {
485
+ const selected = this._items ? this._items[this._menuElement.selected] : false;
486
+ const itemId = selected || this.placeholder ? this._itemId : '';
487
+
488
+ return labelId ? `${labelId} ${itemId}`.trim() : null;
489
+ }
490
+
491
+ /** @private */
492
+ __updateValueButton() {
493
+ const valueButton = this.focusElement;
494
+
495
+ if (!valueButton) {
496
+ return;
497
+ }
498
+
499
+ valueButton.innerHTML = '';
500
+
501
+ const selected = this._items[this._menuElement.selected];
502
+
503
+ valueButton.removeAttribute('placeholder');
504
+
505
+ if (!selected) {
506
+ if (this.placeholder) {
507
+ const item = this.__createItemElement({ label: this.placeholder });
508
+ this.__appendValueItemElement(item, valueButton);
509
+ valueButton.setAttribute('placeholder', '');
510
+ }
511
+ } else {
512
+ this.__attachSelectedItem(selected);
513
+
514
+ if (!this._valueChanging) {
515
+ this._selectedChanging = true;
516
+ this.value = selected.value || '';
517
+ if (this.__dispatchChangePending) {
518
+ this.opened = false;
519
+ this.__dispatchChange();
520
+ }
521
+ delete this._selectedChanging;
522
+ }
523
+ }
524
+
525
+ const labelledIdReferenceConfig =
526
+ selected || this.placeholder ? { newId: this._itemId } : { oldId: this._itemId };
527
+
528
+ setAriaIDReference(valueButton, 'aria-labelledby', labelledIdReferenceConfig);
529
+ if (this.accessibleName || this.accessibleNameRef) {
530
+ this._setCustomAriaLabelledBy(this.accessibleNameRef || this._srLabelController.defaultId);
531
+ }
532
+ }
533
+
534
+ /** @private */
535
+ _updateSelectedItem(value, items) {
536
+ if (items) {
537
+ const valueAsString = value == null ? value : value.toString();
538
+ this._menuElement.selected = items.reduce((prev, item, idx) => {
539
+ return prev === undefined && item.value === valueAsString ? idx : prev;
540
+ }, undefined);
541
+ if (!this._selectedChanging) {
542
+ this._valueChanging = true;
543
+ this.__updateValueButton();
544
+ delete this._valueChanging;
545
+ }
546
+ }
547
+ }
548
+
549
+ /**
550
+ * Override method inherited from `FocusMixin` to not remove focused
551
+ * state when select is opened and focus moves to list-box.
552
+ * @return {boolean}
553
+ * @protected
554
+ * @override
555
+ */
556
+ _shouldRemoveFocus() {
557
+ return !this.opened;
558
+ }
559
+
560
+ /**
561
+ * Override method inherited from `FocusMixin` to validate on blur.
562
+ * @param {boolean} focused
563
+ * @protected
564
+ * @override
565
+ */
566
+ _setFocused(focused) {
567
+ super._setFocused(focused);
568
+
569
+ // Do not validate when focusout is caused by document
570
+ // losing focus, which happens on browser tab switch.
571
+ if (!focused && document.hasFocus()) {
572
+ this.validate();
573
+ }
574
+ }
575
+
576
+ /**
577
+ * Returns true if the current value satisfies all constraints (if any)
578
+ *
579
+ * @return {boolean}
580
+ */
581
+ checkValidity() {
582
+ return !this.required || this.readonly || !!this.value;
583
+ }
584
+
585
+ /**
586
+ * Renders items when they are provided by the `items` property and clears the content otherwise.
587
+ * @param {!HTMLElement} root
588
+ * @param {!Select} _select
589
+ * @private
590
+ */
591
+ __defaultRenderer(root, _select) {
592
+ if (!this.items || this.items.length === 0) {
593
+ root.textContent = '';
594
+ return;
595
+ }
596
+
597
+ let listBox = root.firstElementChild;
598
+ if (!listBox) {
599
+ listBox = document.createElement('vaadin-select-list-box');
600
+ root.appendChild(listBox);
601
+ }
602
+
603
+ listBox.textContent = '';
604
+ this.items.forEach((item) => {
605
+ listBox.appendChild(this.__createItemElement(item));
606
+ });
607
+ }
608
+
609
+ /** @private */
610
+ async __dispatchChange() {
611
+ // Wait for the update complete to guarantee that value-changed is fired
612
+ // before validated and change events when using the Lit version of the component.
613
+ if (this.updateComplete) {
614
+ await this.updateComplete;
615
+ }
616
+
617
+ this.validate();
618
+ this.dispatchEvent(new CustomEvent('change', { bubbles: true }));
619
+ this.__dispatchChangePending = false;
620
+ }
621
+ };
@@ -3,37 +3,56 @@
3
3
  * Copyright (c) 2017 - 2023 Vaadin Ltd.
4
4
  * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
5
  */
6
- import { Overlay } from '@vaadin/overlay/src/vaadin-overlay.js';
6
+ import { html, PolymerElement } from '@polymer/polymer/polymer-element.js';
7
+ import { DirMixin } from '@vaadin/component-base/src/dir-mixin.js';
8
+ import { OverlayMixin } from '@vaadin/overlay/src/vaadin-overlay-mixin.js';
7
9
  import { PositionMixin } from '@vaadin/overlay/src/vaadin-overlay-position-mixin.js';
8
- import { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';
9
-
10
- registerStyles(
11
- 'vaadin-select-overlay',
12
- css`
13
- :host {
14
- align-items: flex-start;
15
- justify-content: flex-start;
16
- }
17
- @media (forced-colors: active) {
18
- [part='overlay'] {
19
- outline: 3px solid;
20
- }
10
+ import { overlayStyles } from '@vaadin/overlay/src/vaadin-overlay-styles.js';
11
+ import { css, registerStyles, ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';
12
+
13
+ const selectOverlayStyles = css`
14
+ :host {
15
+ align-items: flex-start;
16
+ justify-content: flex-start;
17
+ }
18
+
19
+ @media (forced-colors: active) {
20
+ [part='overlay'] {
21
+ outline: 3px solid;
21
22
  }
22
- `,
23
- { moduleId: 'vaadin-select-overlay-styles' },
24
- );
23
+ }
24
+ `;
25
+
26
+ registerStyles('vaadin-select-overlay', [overlayStyles, selectOverlayStyles], {
27
+ moduleId: 'vaadin-select-overlay-styles',
28
+ });
25
29
 
26
30
  /**
27
31
  * An element used internally by `<vaadin-select>`. Not intended to be used separately.
28
32
  *
29
- * @extends Overlay
30
- * @protected
33
+ * @extends HTMLElement
34
+ * @mixes DirMixin
35
+ * @mixes OverlayMixin
36
+ * @mixes PositionMixin
37
+ * @mixes ThemableMixin
38
+ * @private
31
39
  */
32
- class SelectOverlay extends PositionMixin(Overlay) {
40
+ export class SelectOverlay extends PositionMixin(OverlayMixin(DirMixin(ThemableMixin(PolymerElement)))) {
33
41
  static get is() {
34
42
  return 'vaadin-select-overlay';
35
43
  }
36
44
 
45
+ static get template() {
46
+ return html`
47
+ <div id="backdrop" part="backdrop" hidden$="[[!withBackdrop]]"></div>
48
+ <div part="overlay" id="overlay" tabindex="0">
49
+ <div part="content" id="content">
50
+ <slot></slot>
51
+ </div>
52
+ </div>
53
+ `;
54
+ }
55
+
37
56
  requestContentUpdate() {
38
57
  super.requestContentUpdate();
39
58