-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
component.ts
544 lines (486 loc) · 19.1 KB
/
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
/**
* @license
* Copyright 2016 Google Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import {MDCComponent} from '@material/base/component';
import {CustomEventListener, SpecificEventListener} from '@material/base/types';
import {MDCFloatingLabel, MDCFloatingLabelFactory} from '@material/floating-label/component';
import {MDCLineRipple, MDCLineRippleFactory} from '@material/line-ripple/component';
import * as menuSurfaceConstants from '@material/menu-surface/constants';
import {MDCMenu, MDCMenuFactory} from '@material/menu/component';
import * as menuConstants from '@material/menu/constants';
import {MDCMenuItemEvent} from '@material/menu/types';
import {MDCNotchedOutline, MDCNotchedOutlineFactory} from '@material/notched-outline/component';
import {MDCRippleAdapter} from '@material/ripple/adapter';
import {MDCRipple} from '@material/ripple/component';
import {MDCRippleFoundation} from '@material/ripple/foundation';
import {MDCSelectAdapter} from './adapter';
import {cssClasses, strings} from './constants';
import {MDCSelectFoundation} from './foundation';
import {MDCSelectHelperText, MDCSelectHelperTextFactory} from './helper-text/component';
import {MDCSelectIcon, MDCSelectIconFactory} from './icon/component';
import {MDCSelectEventDetail, MDCSelectFoundationMap} from './types';
/** MDC Select */
export class MDCSelect extends MDCComponent<MDCSelectFoundation> {
static override attachTo(root: HTMLElement): MDCSelect {
return new MDCSelect(root);
}
private ripple!: MDCRipple|null;
private menu!: MDCMenu; // assigned in menuSetup()
private selectAnchor!: HTMLElement; // assigned in initialize()
private selectedText!: HTMLElement; // assigned in initialize()
private hiddenInput!: HTMLInputElement|null; // assigned in initialize()
private menuElement!: HTMLElement; // assigned in menuSetup()
private menuItemValues!: string[]; // assigned in menuSetup()
private leadingIcon?: MDCSelectIcon; // assigned in initialize()
private helperText!: MDCSelectHelperText|null; // assigned in initialize()
private lineRipple!: MDCLineRipple|null; // assigned in initialize()
private label!: MDCFloatingLabel|null; // assigned in initialize()
private outline!: MDCNotchedOutline|null; // assigned in initialize()
// Event handlers
private handleFocus!: SpecificEventListener<'focus'>;
private handleBlur!: SpecificEventListener<'blur'>;
private handleClick!: SpecificEventListener<'click'>;
private handleKeydown!: SpecificEventListener<'keydown'>;
private handleMenuOpened!: EventListener;
private handleMenuClosed!: EventListener;
private handleMenuClosing!: EventListener;
private handleMenuItemAction!: CustomEventListener<MDCMenuItemEvent>;
override initialize(
labelFactory: MDCFloatingLabelFactory = (el) => new MDCFloatingLabel(el),
lineRippleFactory: MDCLineRippleFactory = (el) => new MDCLineRipple(el),
outlineFactory:
MDCNotchedOutlineFactory = (el) => new MDCNotchedOutline(el),
menuFactory: MDCMenuFactory = (el) => new MDCMenu(el),
iconFactory: MDCSelectIconFactory = (el) => new MDCSelectIcon(el),
helperTextFactory:
MDCSelectHelperTextFactory = (el) => new MDCSelectHelperText(el),
) {
this.selectAnchor =
this.root.querySelector<HTMLElement>(strings.SELECT_ANCHOR_SELECTOR)!;
this.selectedText =
this.root.querySelector<HTMLElement>(strings.SELECTED_TEXT_SELECTOR)!;
this.hiddenInput = this.root.querySelector<HTMLInputElement>(
strings.HIDDEN_INPUT_SELECTOR)!;
if (!this.selectedText) {
throw new Error(
'MDCSelect: Missing required element: The following selector must be present: ' +
`'${strings.SELECTED_TEXT_SELECTOR}'`,
);
}
if (this.selectAnchor.hasAttribute(strings.ARIA_CONTROLS)) {
const helperTextElement = document.getElementById(
this.selectAnchor.getAttribute(strings.ARIA_CONTROLS)!);
if (helperTextElement) {
this.helperText = helperTextFactory(helperTextElement);
}
}
this.menuSetup(menuFactory);
const labelElement =
this.root.querySelector<HTMLElement>(strings.LABEL_SELECTOR);
this.label = labelElement ? labelFactory(labelElement) : null;
const lineRippleElement =
this.root.querySelector<HTMLElement>(strings.LINE_RIPPLE_SELECTOR);
this.lineRipple =
lineRippleElement ? lineRippleFactory(lineRippleElement) : null;
const outlineElement =
this.root.querySelector<HTMLElement>(strings.OUTLINE_SELECTOR);
this.outline = outlineElement ? outlineFactory(outlineElement) : null;
const leadingIcon =
this.root.querySelector<HTMLElement>(strings.LEADING_ICON_SELECTOR);
if (leadingIcon) {
this.leadingIcon = iconFactory(leadingIcon);
}
if (!this.root.classList.contains(cssClasses.OUTLINED)) {
this.ripple = this.createRipple();
}
}
/**
* Initializes the select's event listeners and internal state based
* on the environment's state.
*/
override initialSyncWithDOM() {
this.handleFocus = () => {
this.foundation.handleFocus();
};
this.handleBlur = () => {
this.foundation.handleBlur();
};
this.handleClick = (event) => {
this.selectAnchor.focus();
this.foundation.handleClick(this.getNormalizedXCoordinate(event));
};
this.handleKeydown = (event) => {
this.foundation.handleKeydown(event);
};
this.handleMenuItemAction = (event) => {
this.foundation.handleMenuItemAction(event.detail.index);
};
this.handleMenuOpened = () => {
this.foundation.handleMenuOpened();
};
this.handleMenuClosed = () => {
this.foundation.handleMenuClosed();
};
this.handleMenuClosing = () => {
this.foundation.handleMenuClosing();
};
this.selectAnchor.addEventListener('focus', this.handleFocus);
this.selectAnchor.addEventListener('blur', this.handleBlur);
this.selectAnchor.addEventListener(
'click', this.handleClick as EventListener);
this.selectAnchor.addEventListener('keydown', this.handleKeydown);
this.menu.listen(
menuSurfaceConstants.strings.CLOSED_EVENT, this.handleMenuClosed);
this.menu.listen(
menuSurfaceConstants.strings.CLOSING_EVENT, this.handleMenuClosing);
this.menu.listen(
menuSurfaceConstants.strings.OPENED_EVENT, this.handleMenuOpened);
this.menu.listen(
menuConstants.strings.SELECTED_EVENT, this.handleMenuItemAction);
if (this.hiddenInput) {
if (this.hiddenInput.value) {
// If the hidden input already has a value, use it to restore the
// select's value. This can happen e.g. if the user goes back or (in
// some browsers) refreshes the page.
this.foundation.setValue(
this.hiddenInput.value, /** skipNotify */ true);
this.foundation.layout();
return;
}
this.hiddenInput.value = this.value;
}
}
override destroy() {
this.selectAnchor.removeEventListener('focus', this.handleFocus);
this.selectAnchor.removeEventListener('blur', this.handleBlur);
this.selectAnchor.removeEventListener('keydown', this.handleKeydown);
this.selectAnchor.removeEventListener(
'click', this.handleClick as EventListener);
this.menu.unlisten(
menuSurfaceConstants.strings.CLOSED_EVENT, this.handleMenuClosed);
this.menu.unlisten(
menuSurfaceConstants.strings.OPENED_EVENT, this.handleMenuOpened);
this.menu.unlisten(
menuConstants.strings.SELECTED_EVENT, this.handleMenuItemAction);
this.menu.destroy();
if (this.ripple) {
this.ripple.destroy();
}
if (this.outline) {
this.outline.destroy();
}
if (this.leadingIcon) {
this.leadingIcon.destroy();
}
if (this.helperText) {
this.helperText.destroy();
}
super.destroy();
}
get value(): string {
return this.foundation.getValue();
}
set value(value: string) {
this.foundation.setValue(value);
}
setValue(value: string, skipNotify = false) {
this.foundation.setValue(value, skipNotify);
}
get selectedIndex(): number {
return this.foundation.getSelectedIndex();
}
set selectedIndex(selectedIndex: number) {
this.foundation.setSelectedIndex(selectedIndex, /* closeMenu */ true);
}
setSelectedIndex(selectedIndex: number, skipNotify = false) {
this.foundation.setSelectedIndex(
selectedIndex, /* closeMenu */ true, skipNotify);
}
get disabled(): boolean {
return this.foundation.getDisabled();
}
set disabled(disabled: boolean) {
this.foundation.setDisabled(disabled);
if (this.hiddenInput) {
this.hiddenInput.disabled = disabled;
}
}
set leadingIconAriaLabel(label: string) {
this.foundation.setLeadingIconAriaLabel(label);
}
/**
* Sets the text content of the leading icon.
*/
set leadingIconContent(content: string) {
this.foundation.setLeadingIconContent(content);
}
/**
* Sets the text content of the helper text.
*/
set helperTextContent(content: string) {
this.foundation.setHelperTextContent(content);
}
/**
* Enables or disables the default validation scheme where a required select
* must be non-empty. Set to false for custom validation.
* @param useDefaultValidation Set this to false to ignore default
* validation scheme.
*/
set useDefaultValidation(useDefaultValidation: boolean) {
this.foundation.setUseDefaultValidation(useDefaultValidation);
}
/**
* Sets the current invalid state of the select.
*/
set valid(isValid: boolean) {
this.foundation.setValid(isValid);
}
/**
* Checks if the select is in a valid state.
*/
get valid(): boolean {
return this.foundation.isValid();
}
/**
* Sets the control to the required state.
*/
set required(isRequired: boolean) {
this.foundation.setRequired(isRequired);
}
/**
* Returns whether the select is required.
*/
get required(): boolean {
return this.foundation.getRequired();
}
/**
* Re-calculates if the notched outline should be notched and if the label
* should float.
*/
layout() {
this.foundation.layout();
}
/**
* Synchronizes the list of options with the state of the foundation. Call
* this whenever menu options are dynamically updated.
*/
layoutOptions() {
this.foundation.layoutOptions();
this.menu.layout();
// Update cached menuItemValues for adapter.
this.menuItemValues =
this.menu.items.map((el) => el.getAttribute(strings.VALUE_ATTR) || '');
if (this.hiddenInput) {
this.hiddenInput.value = this.value;
}
}
override getDefaultFoundation() {
// DO NOT INLINE this variable. For backward compatibility, foundations take
// a Partial<MDCFooAdapter>. To ensure we don't accidentally omit any
// methods, we need a separate, strongly typed adapter variable.
const adapter: MDCSelectAdapter = {
...this.getSelectAdapterMethods(),
...this.getCommonAdapterMethods(),
...this.getOutlineAdapterMethods(),
...this.getLabelAdapterMethods(),
};
return new MDCSelectFoundation(adapter, this.getFoundationMap());
}
/**
* Handles setup for the menu.
*/
private menuSetup(menuFactory: MDCMenuFactory) {
this.menuElement =
this.root.querySelector<HTMLElement>(strings.MENU_SELECTOR)!;
this.menu = menuFactory(this.menuElement);
this.menu.hasTypeahead = true;
this.menu.singleSelection = true;
this.menuItemValues =
this.menu.items.map((el) => el.getAttribute(strings.VALUE_ATTR) || '');
}
private createRipple(): MDCRipple {
// DO NOT INLINE this variable. For backward compatibility, foundations take
// a Partial<MDCFooAdapter>. To ensure we don't accidentally omit any
// methods, we need a separate, strongly typed adapter variable.
// tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
const adapter: MDCRippleAdapter = {
...MDCRipple.createAdapter({root: this.selectAnchor}),
registerInteractionHandler: (eventType, handler) => {
this.selectAnchor.addEventListener(eventType, handler);
},
deregisterInteractionHandler: (eventType, handler) => {
this.selectAnchor.removeEventListener(eventType, handler);
},
};
// tslint:enable:object-literal-sort-keys
return new MDCRipple(this.selectAnchor, new MDCRippleFoundation(adapter));
}
private getSelectAdapterMethods() {
// tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
return {
getMenuItemAttr: (menuItem: Element, attr: string) =>
menuItem.getAttribute(attr),
setSelectedText: (text: string) => {
this.selectedText.textContent = text;
let index = this.menu.selectedIndex;
if (index === -1) return;
index = index instanceof Array ? index[0] : index;
const selectedItem = this.menu.items[index];
if (!selectedItem) return;
this.selectedText.setAttribute(
'aria-label', selectedItem.getAttribute('aria-label') || '');
},
isSelectAnchorFocused: () => document.activeElement === this.selectAnchor,
getSelectAnchorAttr: (attr: string) =>
this.selectAnchor.getAttribute(attr),
setSelectAnchorAttr: (attr: string, value: string) => {
this.safeSetAttribute(this.selectAnchor, attr, value);
},
removeSelectAnchorAttr: (attr: string) => {
this.selectAnchor.removeAttribute(attr);
},
addMenuClass: (className: string) => {
this.menuElement.classList.add(className);
},
removeMenuClass: (className: string) => {
this.menuElement.classList.remove(className);
},
openMenu: () => {
this.menu.open = true;
},
closeMenu: () => {
this.menu.open = false;
},
getAnchorElement: () =>
this.root.querySelector<HTMLElement>(strings.SELECT_ANCHOR_SELECTOR)!,
setMenuAnchorElement: (anchorEl: HTMLElement) => {
this.menu.setAnchorElement(anchorEl);
},
setMenuAnchorCorner: (anchorCorner: menuSurfaceConstants.Corner) => {
this.menu.setAnchorCorner(anchorCorner);
},
setMenuWrapFocus: (wrapFocus: boolean) => {
this.menu.wrapFocus = wrapFocus;
},
getSelectedIndex: () => {
const index = this.menu.selectedIndex;
return index instanceof Array ? index[0] : index;
},
setSelectedIndex: (index: number) => {
this.menu.selectedIndex = index;
},
focusMenuItemAtIndex: (index: number) => {
this.menu.items[index]?.focus();
},
getMenuItemCount: () => this.menu.items.length,
// Cache menu item values. layoutOptions() updates this cache.
getMenuItemValues: () => this.menuItemValues,
getMenuItemTextAtIndex: (index: number) =>
this.menu.getPrimaryTextAtIndex(index),
isTypeaheadInProgress: () => this.menu.typeaheadInProgress,
typeaheadMatchItem: (nextChar: string, startingIndex: number) =>
this.menu.typeaheadMatchItem(nextChar, startingIndex),
};
// tslint:enable:object-literal-sort-keys
}
private getCommonAdapterMethods() {
// tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
return {
addClass: (className: string) => {
this.root.classList.add(className);
},
removeClass: (className: string) => {
this.root.classList.remove(className);
},
hasClass: (className: string) => this.root.classList.contains(className),
setRippleCenter: (normalizedX: number) => {
this.lineRipple && this.lineRipple.setRippleCenter(normalizedX);
},
activateBottomLine: () => {
this.lineRipple && this.lineRipple.activate();
},
deactivateBottomLine: () => {
this.lineRipple && this.lineRipple.deactivate();
},
notifyChange: (value: string) => {
if (this.hiddenInput) {
this.hiddenInput.value = value;
}
const index = this.selectedIndex;
this.emit<MDCSelectEventDetail>(
strings.CHANGE_EVENT, {value, index}, true /* shouldBubble */);
},
};
// tslint:enable:object-literal-sort-keys
}
private getOutlineAdapterMethods() {
// tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
return {
hasOutline: () => Boolean(this.outline),
notchOutline: (labelWidth: number) => {
this.outline && this.outline.notch(labelWidth);
},
closeOutline: () => {
this.outline && this.outline.closeNotch();
},
};
// tslint:enable:object-literal-sort-keys
}
private getLabelAdapterMethods() {
// tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
return {
hasLabel: () => !!this.label,
floatLabel: (shouldFloat: boolean) => {
this.label && this.label.float(shouldFloat);
},
getLabelWidth: () => this.label ? this.label.getWidth() : 0,
setLabelRequired: (isRequired: boolean) => {
this.label && this.label.setRequired(isRequired);
},
};
// tslint:enable:object-literal-sort-keys
}
/**
* Calculates where the line ripple should start based on the x coordinate
* within the component.
*/
private getNormalizedXCoordinate(event: MouseEvent|TouchEvent): number {
const targetClientRect = (event.target as Element).getBoundingClientRect();
const xCoordinate =
this.isTouchEvent(event) ? event.touches[0].clientX : event.clientX;
return xCoordinate - targetClientRect.left;
}
private isTouchEvent(event: MouseEvent|TouchEvent): event is TouchEvent {
return Boolean((event as TouchEvent).touches);
}
/**
* Returns a map of all subcomponents to subfoundations.
*/
private getFoundationMap(): Partial<MDCSelectFoundationMap> {
return {
helperText: this.helperText ? this.helperText.foundationForSelect :
undefined,
leadingIcon: this.leadingIcon ? this.leadingIcon.foundationForSelect :
undefined,
};
}
}