This repository was archived by the owner on Oct 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathlist.ts
More file actions
488 lines (420 loc) · 14.9 KB
/
Copy pathlist.ts
File metadata and controls
488 lines (420 loc) · 14.9 KB
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
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Output,
QueryList,
ViewEncapsulation
} from '@angular/core';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {Platform} from '@angular/cdk/platform';
import {merge, Observable, Subscription} from 'rxjs';
import {startWith} from 'rxjs/operators';
import {MDCComponent} from '@angular-mdc/web/base';
import {MdcListItem, MdcListSelectionChange, MDC_LIST_PARENT_COMPONENT} from './list-item';
import {matches} from '@angular-mdc/web/dom';
import {cssClasses, strings, MDCListFoundation, MDCListAdapter} from '@material/list';
/** Change event that is being fired whenever the selected state of an option changes. */
export class MdcListItemChange {
constructor(
/** Reference to the selection list that emitted the event. */
public source: MdcList,
/** Reference to the option that has been changed. */
public option: MdcListItem) {}
}
/** Notifies user action on list item including keyboard and mouse actions. */
export interface MdcListItemAction {
index: number;
}
@Component({
selector: '[mdcListGroup], mdc-list-group',
exportAs: 'mdcListGroup',
host: {'class': 'mdc-list-group'},
template: `
<h3 class="mdc-list-group__subheader" *ngIf="subheader">{{subheader}}</h3>
<ng-content></ng-content>`,
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MdcListGroup {
@Input() subheader?: string;
constructor(public elementRef: ElementRef) {}
}
@Directive({
selector: '[mdcListGroupSubheader], mdc-list-group-subheader',
exportAs: 'mdcListGroupSubheader',
host: {'class': 'mdc-list-group__subheader'}
})
export class MdcListGroupSubheader {
constructor(public elementRef: ElementRef) {}
}
@Component({
selector: 'mdc-list',
exportAs: 'mdcList',
host: {
'role': 'list',
'class': 'mdc-list',
'[attr.aria-orientation]': 'verticalOrientation ? "vertical" : "horizontal"',
'[class.mdc-list--dense]': 'dense',
'[class.mdc-list--avatar-list]': 'avatar',
'[class.ngx-mdc-list--border]': 'border',
'[class.mdc-list--two-line]': 'twoLine',
'(click)': '_handleClickEvent($event)',
'(keydown)': '_onKeydown($event)',
'(focusin)': '_onFocusIn($event)',
'(focusout)': '_onFocusOut($event)'
},
template: '<ng-content></ng-content>',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [{provide: MDC_LIST_PARENT_COMPONENT, useExisting: MdcList}]
})
export class MdcList extends MDCComponent<any> implements AfterViewInit, OnDestroy {
@Input()
get twoLine(): boolean {
return this._twoLine;
}
set twoLine(value: boolean) {
this._twoLine = coerceBooleanProperty(value);
}
private _twoLine = false;
@Input()
get dense(): boolean {
return this._dense;
}
set dense(value: boolean) {
this._dense = coerceBooleanProperty(value);
}
private _dense = false;
@Input()
get border(): boolean {
return this._border;
}
set border(value: boolean) {
this._border = coerceBooleanProperty(value);
}
private _border = false;
@Input()
get avatar(): boolean {
return this._avatar;
}
set avatar(value: boolean) {
this._avatar = coerceBooleanProperty(value);
}
private _avatar = false;
@Input()
get disableRipple(): boolean {
return this._disableRipple;
}
set disableRipple(value: boolean) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this._disableRipple) {
this._disableRipple = newValue;
}
}
private _disableRipple = false;
@Input()
get singleSelection(): boolean | undefined {
return this._singleSelection;
}
set singleSelection(value: boolean | undefined) {
if (value !== undefined) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this._singleSelection) {
this._singleSelection = newValue;
this._foundation.setSingleSelection(this._singleSelection);
this._changeDetectorRef.markForCheck();
}
}
}
private _singleSelection: boolean | undefined;
@Input()
get useActivatedClass(): boolean {
return this._useActivatedClass;
}
set useActivatedClass(value: boolean) {
this._useActivatedClass = coerceBooleanProperty(value);
this._foundation.setUseActivatedClass(this._useActivatedClass);
this._changeDetectorRef.markForCheck();
}
private _useActivatedClass = false;
@Input()
get useSelectedClass(): boolean {
return this._useSelectedClass;
}
set useSelectedClass(value: boolean) {
this._useSelectedClass = coerceBooleanProperty(value);
this._changeDetectorRef.markForCheck();
}
private _useSelectedClass = false;
@Input()
get verticalOrientation(): boolean {
return this._verticalOrientation;
}
set verticalOrientation(value: boolean) {
this._verticalOrientation = coerceBooleanProperty(value);
this._foundation.setVerticalOrientation(this._verticalOrientation);
this._changeDetectorRef.markForCheck();
}
private _verticalOrientation = true;
@Input()
get wrapFocus(): boolean {
return this._wrapFocus;
}
set wrapFocus(value: boolean) {
this._wrapFocus = coerceBooleanProperty(value);
this._foundation.setWrapFocus(this._wrapFocus);
this._changeDetectorRef.markForCheck();
}
private _wrapFocus = false;
@ContentChildren(MdcListItem, {descendants: true}) items!: QueryList<MdcListItem>;
/** Emits a change event whenever the selected state of an option changes. */
@Output() readonly selectionChange: EventEmitter<MdcListItemChange> =
new EventEmitter<MdcListItemChange>();
/** Emits an event for keyboard and mouse actions. */
@Output() readonly actionEvent: EventEmitter<MdcListItemAction> =
new EventEmitter<MdcListItemAction>();
/** Subscription to changes in list items. */
private _changeSubscription: Subscription | null = null;
/** Subscription to selection events in list items. */
private itemSelectionSubscription: Subscription | null = null;
/** Combined stream of all of the list item selection events. */
get listItemSelections(): Observable<MdcListSelectionChange> {
return merge(...this.items.map(item => item.selectionChange));
}
getDefaultFoundation() {
const adapter: MDCListAdapter = {
getListItemCount: () => this.items.length,
getFocusedElementIndex: () => {
if (!this._platform.isBrowser && document.activeElement!) {
return -1;
}
return this.items.toArray().findIndex(_ => _.getListItemElement() === document.activeElement!) || -1;
},
setAttributeForElementIndex: (index: number, attr: string, value: string) => {
const item = this.getListItemByIndex(index);
item?.getListItemElement()?.setAttribute(attr, value);
},
addClassForElementIndex: (index: number, className: string) =>
this.items.toArray()[index].getListItemElement().classList.add(className),
removeClassForElementIndex: (index: number, className: string) => {
const item = this.getListItemByIndex(index);
item?.getListItemElement()?.classList?.remove(className);
},
getAttributeForElementIndex: (index, attr) =>
this.items.toArray()[index].getListItemElement().getAttribute(attr),
focusItemAtIndex: (index: number) => this.focusItemAtIndex(index),
setTabIndexForListItemChildren: (listItemIndex: number, tabIndexValue: string) => {
const listItemChildren = [].slice.call(this.items.toArray()[listItemIndex].getListItemElement()
.querySelectorAll(strings.CHILD_ELEMENTS_TO_TOGGLE_TABINDEX));
listItemChildren.forEach((ele: Element) => ele.setAttribute('tabindex', `${tabIndexValue}`));
},
hasCheckboxAtIndex: (index: number) => {
const listItem = this.items.toArray()[index].getListItemElement();
return !!listItem.querySelector(strings.CHECKBOX_SELECTOR);
},
hasRadioAtIndex: (index: number) => {
const listItem = this.items.toArray()[index].getListItemElement();
return !!listItem.querySelector(strings.RADIO_SELECTOR);
},
isCheckboxCheckedAtIndex: (index: number) => {
const listItem = this.items.toArray()[index].getListItemElement();
const toggleEl = listItem.querySelector<HTMLInputElement>(strings.CHECKBOX_SELECTOR);
return toggleEl!.checked;
},
setCheckedCheckboxOrRadioAtIndex: (index: number, isChecked: boolean) => {
const listItem = this.items.toArray()[index].getListItemElement();
const toggleEl = listItem.querySelector<HTMLInputElement>(strings.CHECKBOX_RADIO_SELECTOR);
toggleEl!.checked = isChecked;
if (this._platform.isBrowser) {
const event = document.createEvent('Event');
event.initEvent('change', true, true);
toggleEl!.dispatchEvent(event);
}
},
isFocusInsideList: () => this._platform.isBrowser ?
this.elementRef.nativeElement.contains(document.activeElement) : false,
isRootFocused: () => this._platform.isBrowser ? document.activeElement === this._getHostElement() : false,
listItemAtIndexHasClass: (index: number, className: string) =>
this.items.toArray()[index].getListItemElement().classList.contains(className),
notifyAction: (index: number) => this.actionEvent.emit({index: index})
};
return new MDCListFoundation(adapter);
}
constructor(
private _platform: Platform,
private _changeDetectorRef: ChangeDetectorRef,
public elementRef: ElementRef) {
super(elementRef);
}
ngAfterViewInit(): void {
this._foundation.init();
this._foundation.layout();
// When list items change, re-subscribe
this._changeSubscription = this.items.changes.pipe(startWith(null))
.subscribe(() => {
if (this.items.length) {
this._resetListItems();
}
});
}
ngOnDestroy(): void {
this._dropSubscriptions();
this._changeSubscription?.unsubscribe();
this._foundation.destroy();
}
setSelectedIndex(index: number): void {
this.reset();
this._foundation.setSelectedIndex(index);
if (index === -1) {
return;
}
const selectedItem = this.items.toArray()[index];
if (selectedItem) {
this._applySelectionState(selectedItem);
}
}
setSelectedValue(value: any): void {
this.reset();
if (value === null) {
return;
}
const selectedItem = this.getListItemByValue(value);
this._foundation.setSelectedIndex(this.getListItemIndexByValue(value));
if (selectedItem) {
this._applySelectionState(selectedItem);
}
}
getSelectedItem(): MdcListItem | undefined {
return this.items.toArray().find(_ => _.selected || _.activated);
}
getSelectedIndex(): number {
return this.items.toArray().findIndex(_ => _.selected || _.activated);
}
getSelectedValue(): any {
const item = this.items ? this.items.find(_ => _.selected) : null;
return item && item.value ? item.value : null;
}
getSelectedText(): string {
const selectedItem = this.getSelectedItem();
return selectedItem && selectedItem.getListItemElement().textContent || '';
}
getListItemByValue(value: any): MdcListItem | undefined {
return this.items.toArray().find(_ => _.value === value);
}
getListItemByIndex(index: number): MdcListItem | undefined {
return this.items.toArray()[index];
}
getListItemIndexByValue(value: any): number {
return this.items.toArray().findIndex(_ => _.value === value);
}
focusItemAtIndex(index: number): void {
this.items.toArray()[index].getListItemElement().focus();
}
focusFirstElement(): number {
return this._foundation.focusFirstElement();
}
focusLastElement(): number {
return this._foundation.focusLastElement();
}
focusNextElement(index: number): number {
return this._foundation.focusNextElement(index);
}
focusPrevElement(index: number): number {
return this._foundation.focusPrevElement(index);
}
setRole(role: string): void {
this._getHostElement().setAttribute('role', role);
}
setTabIndex(index: number): void {
this._getHostElement().tabIndex = index;
}
focus(): void {
this._getHostElement().focus();
}
reset(): void {
this.items.forEach(_ => {
_.selected = false;
_.activated = false;
});
}
private _applySelectionState(item: MdcListItem): void {
if (this.useActivatedClass) {
item.activated = true;
} else if (this.useSelectedClass) {
item.selected = true;
}
}
private _resetListItems() {
this._dropSubscriptions();
this._listenForListItemSelection();
}
private _dropSubscriptions() {
if (this.itemSelectionSubscription) {
this.itemSelectionSubscription.unsubscribe();
this.itemSelectionSubscription = null;
}
}
/** Listens to selected events on each list item. */
private _listenForListItemSelection(): void {
this.itemSelectionSubscription = this.listItemSelections.subscribe(event => {
if (this.singleSelection) {
this.items.filter(_ => _.id !== event.source.id && (_.activated || _.selected))
.forEach(_ => {
_.selected = false;
_.activated = false;
});
}
this._applySelectionState(event.source);
if (!this.singleSelection) {
event.source.ripple.handleBlur();
}
this.selectionChange.emit(new MdcListItemChange(this, event.source));
});
}
_onFocusIn(evt: FocusEvent): void {
const index = this._getListItemIndexByEvent(evt);
this._foundation.handleFocusIn(evt, index);
}
_onFocusOut(evt: FocusEvent): void {
const index = this._getListItemIndexByEvent(evt);
if (index >= 0) {
this._foundation.handleFocusOut(evt, index);
}
}
_onKeydown(evt: KeyboardEvent): void {
const index = this._getListItemIndexByEvent(evt);
const target = evt.target as Element;
if (index >= 0) {
this._foundation.handleKeydown(evt, target.classList.contains(cssClasses.LIST_ITEM_CLASS), index);
}
}
_handleClickEvent(evt: MouseEvent): void {
const index = this._getListItemIndexByEvent(evt);
const target = evt.target as HTMLElement;
const listItem = this._getListItemByEventTarget(evt.target!);
if (listItem && listItem.disabled) {
return;
}
// Toggle the checkbox only if it's not the target of the event, or the checkbox will have 2 change events.
const toggleCheckbox = !matches(target, strings.CHECKBOX_RADIO_SELECTOR);
this._foundation.handleClick(index, toggleCheckbox);
}
private _getListItemByEventTarget(target: EventTarget): MdcListItem | undefined {
return this.items.toArray().find(_ => _.getListItemElement() === target);
}
private _getListItemIndexByEvent(evt: Event): number {
return this.items.toArray().findIndex(_ => _.getListItemElement() === evt.target);
}
/** Retrieves the DOM element of the component host. */
private _getHostElement(): HTMLElement {
return this.elementRef.nativeElement;
}
}