-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauro-select.js
575 lines (487 loc) · 16.5 KB
/
auro-select.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
// Copyright (c) 2021 Alaska Airlines. All right reserved. Licensed under the Apache-2.0 license
// See LICENSE in the project root for license information.
// ---------------------------------------------------------------------
/* eslint-disable prefer-named-capture-group, max-lines, no-underscore-dangle, lit/binding-positions, lit/no-invalid-html */
// If using litElement base class
import { LitElement } from "lit";
import { html } from 'lit/static-html.js';
import AuroFormValidation from '@aurodesignsystem/auro-formvalidation/src/validation.js';
import AuroLibraryRuntimeUtils from '@aurodesignsystem/auro-library/scripts/utils/runtimeUtils.mjs';
import { AuroDependencyVersioning } from '@aurodesignsystem/auro-library/scripts/runtime/dependencyTagVersioning.mjs';
import { AuroDropdown } from '@aurodesignsystem/auro-dropdown/src/auro-dropdown.js';
import dropdownVersion from './dropdownVersion.js';
import '@aurodesignsystem/auro-menu';
import styleCss from "./style-css.js";
import colorCss from "./color-css.js";
import tokensCss from "./tokens-css.js";
// See https://git.io/JJ6SJ for "How to document your components using JSDoc"
/**
* The auro-select element is a wrapper for auro-dropdown and auro-menu to create a dropdown menu control.
*
* @attr {String} validity - Specifies the `validityState` this element is in.
* @attr {String} setCustomValidity - Sets a custom help text message to display for all validityStates.
* @attr {String} setCustomValidityCustomError - Custom help text message to display when validity = `customError`.
* @attr {String} setCustomValidityValueMissing - Custom help text message to display when validity = `valueMissing`.
* @attr {String} error - When defined, sets persistent validity to `customError` and sets `setCustomValidity` = attribute value.
* @attr {Boolean} noValidate - If set, disables auto-validation on blur.
* @attr {Boolean} required - Populates the `required` attribute on the element. Used for client-side validation.
* @prop {String} placeholder - Define placeholder text to display before a value is manually selected.
* @prop {String} value - Value selected for the component.
* @prop {Boolean} disabled - When attribute is present element shows disabled state.
* @prop {Boolean} noCheckmark - When true, checkmark on selected option will no longer be present.
* @attr {Object} optionSelected - Specifies the current selected menuOption.
* @slot - Default slot for the menu content.
* @slot label - Defines the content of the label.
* @slot helpText - Defines the content of the helpText.
* @event auroSelect-ready - Notifies that the component has finished initializing.
* @event auroSelect-valueSet - Notifies that the component has a new value set.
* @event auroFormElement-validated - Notifies that the `validity` and `errorMessage` values have changed.
*/
// build the component class
export class AuroSelect extends LitElement {
constructor() {
super();
this.placeholder = 'Please select option';
this.optionSelected = undefined;
this.validity = undefined;
const idLength = 36;
const idSubstrEnd = 8;
const idSubstrStart = 2;
/**
* @private
*/
this.uniqueId = Math.random().
toString(idLength).
substring(idSubstrStart, idSubstrEnd);
/**
* @private
*/
this.validation = new AuroFormValidation();
/**
* @private
*/
this.runtimeUtils = new AuroLibraryRuntimeUtils();
/**
* Generate unique names for dependency components.
*/
const versioning = new AuroDependencyVersioning();
/**
* @private
*/
this.dropdownTag = versioning.generateTag('auro-dropdown', dropdownVersion, AuroDropdown);
}
/**
* @private
* @returns {void} Internal defaults.
*/
privateDefaults() {
this.options = [];
this.optionActive = null;
}
// This function is to define props used within the scope of this component
// Be sure to review https://lit-element.polymer-project.org/guide/properties#reflected-attributes
// to understand how to use reflected attributes with your property settings.
static get properties() {
return {
// ...super.properties,
optionSelected: {
type: Object
},
value: {
type: String,
reflect: true
},
noValidate: {
type: Boolean,
reflect: true
},
required: {
type: Boolean,
reflect: true
},
error: {
type: String,
reflect: true
},
setCustomValidity: {
type: String
},
setCustomValidityCustomError: {
type: String
},
setCustomValidityValueMissing: {
type: String
},
validity: {
type: String,
reflect: true
},
disabled: {
type: Boolean,
reflect: true
},
noCheckmark: {
type: Boolean,
reflect: true
},
placeholder: { type: String },
/**
* @private
*/
options: { type: Array },
/**
* @private
*/
optionActive: { type: Object },
};
}
static get styles() {
return [
styleCss,
colorCss,
tokensCss
];
}
/**
* Binds all behavior needed to the dropdown after rendering.
* @private
* @returns {void}
*/
configureDropdown() {
this.dropdown = this.shadowRoot.querySelector(this.dropdownTag._$litStatic$);
this.dropdown.addEventListener('auroDropdown-ready', () => {
this.auroDropdownReady = true;
});
}
/**
* Updates the displayed value in an Auro dropdown component based on the provided option.
* @param {string|HTMLElement} option - The option to display. If a string, a new span element with the value string is created. If an HTMLElement, the selected option is cloned and non-styling attributes are removed.
* @private
* @returns {void}
*/
updateDisplayedValue(option) {
const triggerContentEl = this.dropdown.querySelector('#triggerFocus');
// remove all existing rendered value(s)
triggerContentEl.querySelectorAll('auro-menuoption, [valuestr]').forEach((elm) => {
elm.remove();
});
if (typeof option === 'string' && option !== this.placeholder) {
// create a new span element with the value string
const valueElem = document.createElement('span');
valueElem.setAttribute('valuestr', true);
valueElem.textContent = option;
// append the new element into the trigger content
triggerContentEl.appendChild(valueElem);
} else if (typeof option === 'object') {
// clone the selected option and remove attributes that style it
const clone = option.cloneNode(true);
clone.removeAttribute('selected');
clone.removeAttribute('class');
// insert the non-styled clone into the trigger
triggerContentEl.appendChild(clone);
}
}
/**
* Binds all behavior needed to the menu after rendering.
* @private
* @returns {void}
*/
configureMenu() {
this.menu = this.querySelector('auro-menu');
this.menu.setAttribute('aria-hidden', 'true');
this.generateOptionsArray();
this.menu.addEventListener('auroMenu-ready', () => {
this.auroMenuReady = true;
});
this.addEventListener('auroMenu-activatedOption', (evt) => {
this.optionActive = evt.detail;
});
this.menu.addEventListener('selectedOption', () => {
this.optionSelected = this.menu.optionSelected;
this.value = this.optionSelected.value;
this.updateDisplayedValue(this.optionSelected);
if (this.dropdown.isPopoverVisible) {
this.dropdown.hide();
}
});
/**
* When this.value is preset auro-menu.selectByValue(this.value) is called.
* However, if this.value does not match one of the menu options,
* auro-menu will notify via event. In this case, clear out this.value
* so that it is not storing an invalid value which can then later be returned
* with `auro-select.value`.
*/
this.menu.addEventListener('auroMenu-selectValueFailure', () => {
this.menu.optionSelected = undefined;
this.optionSelected = this.menu.optionSelected;
this.validity = 'badInput';
// Capitalizes the first letter of each word in this.value string
const valueStr = this.value.replace(/(^\w{1})|(\s+\w{1})/gu, (letter) => letter.toUpperCase());
// Pass the new string to the trigger content
this.updateDisplayedValue(valueStr);
});
this.menu.addEventListener('auroMenu-selectValueReset', () => {
// set the trigger content back to the placeholder
this.updateDisplayedValue(this.placeholder);
this.optionSelected = undefined;
this.value = undefined;
this.validation.validate(this);
});
}
/**
* Binds all behavior needed to the component after rendering.
* @private
* @returns {void}
*/
configureSelect() {
this.addEventListener('keydown', (evt) => {
if (evt.key === 'ArrowUp') {
evt.preventDefault();
this.dropdown.show();
if (this.dropdown.isPopoverVisible) {
this.menu.selectNextItem('up');
}
}
if (evt.key === 'ArrowDown') {
evt.preventDefault();
this.dropdown.show();
if (this.dropdown.isPopoverVisible) {
this.menu.selectNextItem('down');
}
}
if (evt.key === 'Enter') {
if (!this.dropdown.isPopoverVisible) {
evt.preventDefault();
this.menu.makeSelection();
}
}
if (evt.key === 'Tab') {
this.dropdown.hide();
}
});
this.addEventListener('focusin', this.handleFocusin);
this.addEventListener('blur', () => {
this.validation.validate(this);
});
this.labelForSr();
}
/**
* Function to support @focusin event.
* @private
* @return {void}
*/
handleFocusin() {
/**
* The input is considered to be in it's initial state based on
* if this.value === undefined. The first time we interact with the
* input manually, by applying focusin, we need to flag the
* input as no longer in the initial state.
*/
if (this.value === undefined) {
this.value = '';
this.removeEventListener('focusin', this.handleFocusin);
}
}
/**
* Marks the component as ready and sends event.
* @private
* @returns {void}
*/
notifyReady() {
this.ready = true;
this.dispatchEvent(new CustomEvent('auroSelect-ready', {
bubbles: true,
cancelable: false,
composed: true,
}));
}
/**
* Monitors readiness of peer dependencies and begins work that should only start when ready.
* @private
* @returns {void}
*/
async checkReadiness() {
if (this.auroDropdownReady && this.auroMenuReady) {
this.readyActions();
this.notifyReady();
} else {
// Start a retry counter to limit the retry count
if (!this.readyRetryCount && this.readyRetryCount !== 0) {
this.readyRetryCount = 0;
} else {
this.readyRetryCount += 1;
}
const readyTimer = 0;
const readyRetryLimit = 200;
if (this.readyRetryCount <= readyRetryLimit) {
const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time));
await sleep(readyTimer);
this.checkReadiness();
}
}
}
/**
* Determines the element error state based on the `required` attribute and input value.
* @private
* @returns {void}
*/
generateOptionsArray() {
if (this.menu) {
this.options = [...this.menu.querySelectorAll('auro-menuoption')];
} else {
this.options = [];
}
}
/**
* Functionality that should not be performed until the combobox is in a ready state.
* @private
* @returns {void}
*/
readyActions() {
// Set the initial value in auro-menu if defined
if (this.hasAttribute('value') && this.getAttribute('value').length > 0) {
this.menu.value = this.value;
}
}
/**
* Handle element attributes on update.
* @private
* @returns {void}
*/
performUpdate() {
super.performUpdate();
if (this.validity && this.validity !== 'valid') {
this.dropdown.setAttribute('error', '');
} else {
this.dropdown.removeAttribute('error');
}
if (this.disabled) {
this.dropdown.setAttribute('disabled', '');
} else if (!this.disabled) {
this.dropdown.removeAttribute('disabled');
}
if (this.noCheckmark) {
this.menu.setAttribute('nocheckmark', '');
}
}
// lifecycle runs only after the element's DOM has been updated the first time
firstUpdated() {
// Add the tag name as an attribute if it is different than the component name
this.runtimeUtils.handleComponentTagRename(this, 'auro-select');
this.configureMenu();
this.configureDropdown();
this.configureSelect();
this.checkReadiness();
}
updated(changedProperties) {
// After the component is ready, send direct value changes to auro-menu.
if (this.ready && changedProperties.has('value')) {
if (this.value) {
this.menu.value = this.value;
} else {
this.menu.value = undefined;
}
}
if (changedProperties.has('value')) {
this.validation.validate(this);
}
if (changedProperties.has('value')) {
this.dispatchEvent(new CustomEvent('auroSelect-valueSet', {
bubbles: true,
cancelable: false,
composed: true,
}));
}
if (changedProperties.has('error')) {
this.validation.validate(this, true);
}
}
/**
* Handles reading of auro-select by screen readers.
* @private
* @returns {void}
*/
labelForSr() {
const placeholderLabel = document.createElement("div");
const textId = "label";
placeholderLabel.setAttribute("id", textId);
placeholderLabel.setAttribute("aria-live", "polite");
const styles = {
position: 'absolute',
overflow: 'hidden',
clipPath: 'inset(1px, 1px, 1px, 1px)',
width: '1px',
height: '1px',
padding: '0',
border: '0'
};
Object.assign(placeholderLabel.style, styles);
this.addEventListener('focus', () => {
document.body.appendChild(placeholderLabel);
if (!this.optionSelected) {
document.getElementById(textId).innerHTML = this.placeholder;
} else {
document.getElementById(textId).innerHTML = `${this.optionSelected.innerText}, ${this.placeholder}`;
}
});
this.addEventListener('blur', () => {
if (document.contains(placeholderLabel)) {
document.body.removeChild(placeholderLabel);
}
});
}
// When using auroElement, use the following attribute and function when hiding content from screen readers.
// aria-hidden="${this.hideAudible(this.hiddenAudible)}"
// function that renders the HTML and CSS into the scope of the component
render() {
return html`
<div class="outerWrapper">
<div aria-live="polite" class="util_displayHiddenVisually">
${this.optionActive && this.options.length > 0
? html`
${`${this.optionActive.innerText}, option ${this.options.indexOf(this.optionActive) + 1} of ${this.options.length}`}
`
: undefined
};
${this.optionSelected && this.options.length > 0
? html`
${`${this.optionSelected.innerText} selected`}
`
: undefined
};
</div>
<${this.dropdownTag}
for="selectmenu"
?error="${this.validity !== undefined && this.validity !== 'valid'}"
common
matchWidth
chevron>
<span slot="trigger" aria-haspopup="true" id="triggerFocus">
${this.value ? this.displayValue : html`<span class="placeholder">${this.placeholder}</span>`}
</span>
<div class="menuWrapper">
<slot></slot>
</div>
<slot name="label" slot="label"></slot>
<span slot="helpText">
${!this.validity || this.validity === undefined || this.validity === 'valid'
? html`
<p class="selectElement-helpText" id="${this.uniqueId}" part="helpText">
<slot name="helpText"></slot>
</p>`
: html`
<p class="selectElement-helpText" id="${this.uniqueId}" role="alert" aria-live="assertive" part="helpText">
${this.setCustomValidity}
</p>`
}
</span>
</${this.dropdownTag}>
<!-- Help text and error message template -->
</div>
`;
}
}
// define the name of the custom component
if (!customElements.get("auro-select")) {
customElements.define("auro-select", AuroSelect);
}