@vaadin/select 24.2.0-alpha4 → 24.2.0-alpha5

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,603 @@
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.__userInteraction = true;
263
+ this.opened = false;
264
+ },
265
+ true,
266
+ );
267
+
268
+ // Store the menu element reference
269
+ this.__lastMenuElement = menuElement;
270
+ }
271
+ }
272
+
273
+ /** @private */
274
+ __initMenuItems(menuElement) {
275
+ if (menuElement.items) {
276
+ this._items = menuElement.items;
277
+ }
278
+ }
279
+
280
+ /** @private */
281
+ _valueChanged(value, oldValue) {
282
+ this.toggleAttribute('has-value', Boolean(value));
283
+
284
+ // Validate only if `value` changes after initialization.
285
+ if (oldValue !== undefined) {
286
+ this.validate();
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Opens the overlay if the field is not read-only.
292
+ *
293
+ * @private
294
+ */
295
+ _onClick(event) {
296
+ // Prevent parent components such as `vaadin-grid`
297
+ // from handling the click event after it bubbles.
298
+ event.preventDefault();
299
+
300
+ this.opened = !this.readonly;
301
+ }
302
+
303
+ /** @private */
304
+ _onToggleMouseDown(event) {
305
+ // Prevent mousedown event to avoid blur and preserve focused state
306
+ // while opening, and to restore focus-ring attribute on closing.
307
+ event.preventDefault();
308
+ }
309
+
310
+ /**
311
+ * @param {!KeyboardEvent} e
312
+ * @protected
313
+ * @override
314
+ */
315
+ _onKeyDown(e) {
316
+ if (e.target === this.focusElement && !this.readonly && !this.opened) {
317
+ if (/^(Enter|SpaceBar|\s|ArrowDown|Down|ArrowUp|Up)$/u.test(e.key)) {
318
+ e.preventDefault();
319
+ this.opened = true;
320
+ } else if (/[\p{L}\p{Nd}]/u.test(e.key) && e.key.length === 1) {
321
+ const selected = this._menuElement.selected;
322
+ const currentIdx = selected !== undefined ? selected : -1;
323
+ const newIdx = this._menuElement._searchKey(currentIdx, e.key);
324
+ if (newIdx >= 0) {
325
+ this.__userInteraction = true;
326
+
327
+ // Announce the value selected with the first letter shortcut
328
+ this._updateAriaLive(true);
329
+ this._menuElement.selected = newIdx;
330
+ }
331
+ }
332
+ }
333
+ }
334
+
335
+ /**
336
+ * @param {!KeyboardEvent} e
337
+ * @protected
338
+ */
339
+ _onKeyDownInside(e) {
340
+ if (/^(Tab)$/u.test(e.key)) {
341
+ this.opened = false;
342
+ }
343
+ }
344
+
345
+ /** @private */
346
+ _openedChanged(opened, wasOpened) {
347
+ if (opened) {
348
+ // Avoid multiple announcements when a value gets selected from the dropdown
349
+ this._updateAriaLive(false);
350
+
351
+ if (!this._overlayElement || !this._menuElement || !this.focusElement || this.disabled || this.readonly) {
352
+ this.opened = false;
353
+ return;
354
+ }
355
+
356
+ this._overlayElement.style.setProperty(
357
+ '--vaadin-select-text-field-width',
358
+ `${this._inputContainer.offsetWidth}px`,
359
+ );
360
+
361
+ // Preserve focus-ring to restore it later
362
+ const hasFocusRing = this.hasAttribute('focus-ring');
363
+ this._openedWithFocusRing = hasFocusRing;
364
+
365
+ // Opened select should not keep focus-ring
366
+ if (hasFocusRing) {
367
+ this.removeAttribute('focus-ring');
368
+ }
369
+ } else if (wasOpened) {
370
+ this.focus();
371
+ if (this._openedWithFocusRing) {
372
+ this.setAttribute('focus-ring', '');
373
+ }
374
+ this.validate();
375
+ }
376
+ }
377
+
378
+ /** @private */
379
+ _updateAriaExpanded(opened, focusElement) {
380
+ if (focusElement) {
381
+ focusElement.setAttribute('aria-expanded', opened ? 'true' : 'false');
382
+ }
383
+ }
384
+
385
+ /** @private */
386
+ _updateAriaLive(ariaLive) {
387
+ if (this.focusElement) {
388
+ if (ariaLive) {
389
+ this.focusElement.setAttribute('aria-live', 'polite');
390
+ } else {
391
+ this.focusElement.removeAttribute('aria-live');
392
+ }
393
+ }
394
+ }
395
+
396
+ /** @private */
397
+ __attachSelectedItem(selected) {
398
+ let labelItem;
399
+
400
+ const label = selected.getAttribute('label');
401
+ if (label) {
402
+ labelItem = this.__createItemElement({ label });
403
+ } else {
404
+ labelItem = selected.cloneNode(true);
405
+ }
406
+
407
+ // Store reference to the original item
408
+ labelItem._sourceItem = selected;
409
+
410
+ this.__appendValueItemElement(labelItem, this.focusElement);
411
+
412
+ // Ensure the item gets proper styles
413
+ labelItem.selected = true;
414
+ }
415
+
416
+ /**
417
+ * @param {!SelectItem} item
418
+ * @private
419
+ */
420
+ __createItemElement(item) {
421
+ const itemElement = document.createElement(item.component || 'vaadin-select-item');
422
+ if (item.label) {
423
+ itemElement.textContent = item.label;
424
+ }
425
+ if (item.value) {
426
+ itemElement.value = item.value;
427
+ }
428
+ if (item.disabled) {
429
+ itemElement.disabled = item.disabled;
430
+ }
431
+ return itemElement;
432
+ }
433
+
434
+ /**
435
+ * @param {!HTMLElement} itemElement
436
+ * @param {!HTMLElement} parent
437
+ * @private
438
+ */
439
+ __appendValueItemElement(itemElement, parent) {
440
+ parent.appendChild(itemElement);
441
+ itemElement.removeAttribute('tabindex');
442
+ itemElement.removeAttribute('aria-selected');
443
+ itemElement.removeAttribute('role');
444
+ itemElement.setAttribute('id', this._itemId);
445
+ }
446
+
447
+ /**
448
+ * @param {string} accessibleName
449
+ * @protected
450
+ */
451
+ _accessibleNameChanged(accessibleName) {
452
+ this._srLabelController.setLabel(accessibleName);
453
+ this._setCustomAriaLabelledBy(accessibleName ? this._srLabelController.defaultId : null);
454
+ }
455
+
456
+ /**
457
+ * @param {string} accessibleNameRef
458
+ * @protected
459
+ */
460
+ _accessibleNameRefChanged(accessibleNameRef) {
461
+ this._setCustomAriaLabelledBy(accessibleNameRef);
462
+ }
463
+
464
+ /**
465
+ * @param {string} ariaLabelledby
466
+ * @private
467
+ */
468
+ _setCustomAriaLabelledBy(ariaLabelledby) {
469
+ const labelId = this._getLabelIdWithItemId(ariaLabelledby);
470
+ this._fieldAriaController.setLabelId(labelId, true);
471
+ }
472
+
473
+ /**
474
+ * @param {string | null} labelId
475
+ * @returns string | null
476
+ * @private
477
+ */
478
+ _getLabelIdWithItemId(labelId) {
479
+ const selected = this._items ? this._items[this._menuElement.selected] : false;
480
+ const itemId = selected || this.placeholder ? this._itemId : '';
481
+
482
+ return labelId ? `${labelId} ${itemId}`.trim() : null;
483
+ }
484
+
485
+ /** @private */
486
+ __updateValueButton() {
487
+ const valueButton = this.focusElement;
488
+
489
+ if (!valueButton) {
490
+ return;
491
+ }
492
+
493
+ valueButton.innerHTML = '';
494
+
495
+ const selected = this._items[this._menuElement.selected];
496
+
497
+ valueButton.removeAttribute('placeholder');
498
+
499
+ if (!selected) {
500
+ if (this.placeholder) {
501
+ const item = this.__createItemElement({ label: this.placeholder });
502
+ this.__appendValueItemElement(item, valueButton);
503
+ valueButton.setAttribute('placeholder', '');
504
+ }
505
+ } else {
506
+ this.__attachSelectedItem(selected);
507
+
508
+ if (!this._valueChanging) {
509
+ this._selectedChanging = true;
510
+ this.value = selected.value || '';
511
+ if (this.__userInteraction) {
512
+ this.opened = false;
513
+ this.dispatchEvent(new CustomEvent('change', { bubbles: true }));
514
+ this.__userInteraction = false;
515
+ }
516
+ delete this._selectedChanging;
517
+ }
518
+ }
519
+
520
+ const labelledIdReferenceConfig =
521
+ selected || this.placeholder ? { newId: this._itemId } : { oldId: this._itemId };
522
+
523
+ setAriaIDReference(valueButton, 'aria-labelledby', labelledIdReferenceConfig);
524
+ if (this.accessibleName || this.accessibleNameRef) {
525
+ this._setCustomAriaLabelledBy(this.accessibleNameRef || this._srLabelController.defaultId);
526
+ }
527
+ }
528
+
529
+ /** @private */
530
+ _updateSelectedItem(value, items) {
531
+ if (items) {
532
+ const valueAsString = value == null ? value : value.toString();
533
+ this._menuElement.selected = items.reduce((prev, item, idx) => {
534
+ return prev === undefined && item.value === valueAsString ? idx : prev;
535
+ }, undefined);
536
+ if (!this._selectedChanging) {
537
+ this._valueChanging = true;
538
+ this.__updateValueButton();
539
+ delete this._valueChanging;
540
+ }
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Override method inherited from `FocusMixin` to not remove focused
546
+ * state when select is opened and focus moves to list-box.
547
+ * @return {boolean}
548
+ * @protected
549
+ * @override
550
+ */
551
+ _shouldRemoveFocus() {
552
+ return !this.opened;
553
+ }
554
+
555
+ /**
556
+ * Override method inherited from `FocusMixin` to validate on blur.
557
+ * @param {boolean} focused
558
+ * @protected
559
+ * @override
560
+ */
561
+ _setFocused(focused) {
562
+ super._setFocused(focused);
563
+
564
+ // Do not validate when focusout is caused by document
565
+ // losing focus, which happens on browser tab switch.
566
+ if (!focused && document.hasFocus()) {
567
+ this.validate();
568
+ }
569
+ }
570
+
571
+ /**
572
+ * Returns true if the current value satisfies all constraints (if any)
573
+ *
574
+ * @return {boolean}
575
+ */
576
+ checkValidity() {
577
+ return !this.required || this.readonly || !!this.value;
578
+ }
579
+
580
+ /**
581
+ * Renders items when they are provided by the `items` property and clears the content otherwise.
582
+ * @param {!HTMLElement} root
583
+ * @param {!Select} _select
584
+ * @private
585
+ */
586
+ __defaultRenderer(root, _select) {
587
+ if (!this.items || this.items.length === 0) {
588
+ root.textContent = '';
589
+ return;
590
+ }
591
+
592
+ let listBox = root.firstElementChild;
593
+ if (!listBox) {
594
+ listBox = document.createElement('vaadin-select-list-box');
595
+ root.appendChild(listBox);
596
+ }
597
+
598
+ listBox.textContent = '';
599
+ this.items.forEach((item) => {
600
+ listBox.appendChild(this.__createItemElement(item));
601
+ });
602
+ }
603
+ };
@@ -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