/
selection-list.ts
406 lines (346 loc) · 12.9 KB
/
selection-list.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
import {
Component,
Input,
HostBinding,
ContentChildren,
QueryList,
ChangeDetectionStrategy,
AfterContentInit,
Renderer2,
ElementRef,
OnInit,
EventEmitter,
Output,
OnDestroy,
NgZone,
forwardRef
} from '@angular/core';
import { FocusKeyManager, ActiveDescendantKeyManager } from '@angular/cdk/a11y';
import { SelectionModel } from '@angular/cdk/collections';
import {
ThyListOptionComponent,
THY_OPTION_PARENT_COMPONENT,
IThyOptionParentComponent,
ThyListLayout
} from '../../core/option';
import { keycodes, helpers, dom } from '../../util';
import { inputValueToBoolean } from '../../util/helpers';
import { Subscription, throwError } from 'rxjs';
import { ThySelectionListChange } from './selection.interface';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { ScrollToService } from '../../core';
import { UpdateHostClassService } from '../../shared/update-host-class.service';
import { startWith } from 'rxjs/operators';
export type ThyListSize = 'sm' | 'md' | 'lg';
const listSizesMap = {
sm: 'thy-list-sm'
};
@Component({
selector: 'thy-selection-list,[thy-selection-list]',
template: '<ng-content></ng-content>',
providers: [
UpdateHostClassService,
{
provide: THY_OPTION_PARENT_COMPONENT,
useExisting: ThySelectionListComponent
},
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => ThySelectionListComponent),
multi: true
}
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ThySelectionListComponent
implements OnInit, OnDestroy, AfterContentInit, IThyOptionParentComponent, ControlValueAccessor {
private _keyManager: ActiveDescendantKeyManager<ThyListOptionComponent>;
private _selectionChangesUnsubscribe$ = Subscription.EMPTY;
private _bindKeyEventUnsubscribe: () => void;
private _modelValues: any[];
/** The currently selected options. */
selectionModel: SelectionModel<any>;
disabled: boolean;
layout: ThyListLayout = 'list';
@HostBinding(`class.thy-list`) _isList = true;
@HostBinding(`class.thy-selection-list`) _isSelectionList = true;
@HostBinding(`class.thy-multiple-selection-list`) multiple = true;
@HostBinding(`class.thy-grid-list`) isLayoutGrid = false;
/** The option components contained within this selection-list. */
@ContentChildren(ThyListOptionComponent) options: QueryList<ThyListOptionComponent>;
@Input()
set thyMultiple(value: any) {
const previousValue = this.multiple;
this.multiple = inputValueToBoolean(value);
if (previousValue !== this.multiple) {
this._instanceSelectionModel();
}
}
@Input() thyBindKeyEventContainer: HTMLElement | ElementRef | string;
@Input() thyScrollContainer: HTMLElement | ElementRef | string;
@Input() thyBeforeKeydown: (event?: KeyboardEvent) => boolean;
@Input() thyUniqueKey: string;
@Input() thyCompareWith: (o1: any, o2: any) => boolean;
@Input() set thyLayout(value: ThyListLayout) {
this.layout = value;
this.isLayoutGrid = value === 'grid';
}
@Input() thyFirstItemDefaultActive: boolean;
@Input() set thySize(value: ThyListSize) {
this._setListSize(value);
}
/** Emits a change event whenever the selected state of an option changes. */
@Output() readonly thySelectionChange: EventEmitter<ThySelectionListChange> = new EventEmitter<
ThySelectionListChange
>();
private _onTouched: () => void = () => {};
private _onChange: (value: any) => void = (_: any) => {};
private _emitChangeEvent(option: ThyListOptionComponent, event: Event) {
this.thySelectionChange.emit({
source: this,
value: option.thyValue,
option: option,
event: event,
selected: this.isSelected(option)
});
}
private _emitModelValueChange() {
if (this.options) {
let selectedValues = this.selectionModel.selected;
if (this.thyUniqueKey) {
selectedValues = selectedValues.map(selectedValue => {
const selectedOption = this.options.find(option => {
return option.thyValue[this.thyUniqueKey] === selectedValue;
});
if (selectedOption) {
return selectedOption.thyValue;
} else {
return this._modelValues.find(value => {
return value[this.thyUniqueKey] === selectedValue;
});
}
});
}
this._modelValues = selectedValues;
let changeValue = selectedValues;
if (!this.multiple && selectedValues && selectedValues.length > 0) {
changeValue = selectedValues[0];
}
this._onChange(changeValue);
}
}
private _toggleFocusedOption(event: KeyboardEvent): void {
if (this._keyManager.activeItem) {
this.ngZone.run(() => {
this.toggleOption(this._keyManager.activeItem, event);
});
}
}
private _initializeFocusKeyManager() {
this._keyManager = new ActiveDescendantKeyManager<ThyListOptionComponent>(this.options)
.withWrap()
// .withTypeAhead()
// Allow disabled items to be focusable. For accessibility reasons, there must be a way for
// screenreader users, that allows reading the different options of the list.
.skipPredicate(() => false);
}
private _instanceSelectionModel() {
this.selectionModel = new SelectionModel<any>(this.multiple);
}
private _getElementBySelector(element: HTMLElement | ElementRef | string): HTMLElement {
return dom.getHTMLElementBySelector(element, this.elementRef);
}
private _compareValue(value1: any, value2: any) {
if (this.thyCompareWith) {
const compareFn = this.thyCompareWith as (o1: any, o2: any) => boolean;
return compareFn(value1, value2);
} else if (this.thyUniqueKey) {
return value1 && value1[this.thyUniqueKey] === value2 && value2[this.thyUniqueKey];
} else {
return value1 === value2;
}
}
private _getOptionSelectionValue(option: ThyListOptionComponent) {
if (option.thyValue) {
return this.thyUniqueKey ? option.thyValue[this.thyUniqueKey] : option.thyValue;
} else {
return option;
}
}
private _setSelectionByValues(values: any[]) {
this.selectionModel.clear();
values.forEach(value => {
if (this.thyUniqueKey) {
this.selectionModel.select(value[this.thyUniqueKey]);
} else {
this.selectionModel.select(value);
}
});
}
private _setAllOptionsSelected(toIsSelected: boolean) {
// Keep track of whether anything changed, because we only want to
// emit the changed event when something actually changed.
let hasChanged = false;
this.options.forEach(option => {
const fromIsSelected = this.selectionModel.isSelected(option.thyValue);
if (fromIsSelected !== toIsSelected) {
hasChanged = true;
this.selectionModel.toggle(option.thyValue);
}
});
if (hasChanged) {
this._emitModelValueChange();
}
}
private _getOptionByValue(value: any) {
return this.options.find(option => {
return this._compareValue(option.thyValue, value);
});
}
private _getActiveOption() {
if (this._keyManager.activeItem) {
return this._getOptionByValue(this._keyManager.activeItem.thyValue);
} else {
return null;
}
}
private _setListSize(size: ThyListSize) {
for (const key in listSizesMap) {
if (listSizesMap.hasOwnProperty(key)) {
this.updateHostClassService.removeClass(listSizesMap[key]);
}
}
if (size) {
this.updateHostClassService.addClass(listSizesMap[size]);
}
}
constructor(
private renderer: Renderer2,
private elementRef: ElementRef,
private ngZone: NgZone,
private updateHostClassService: UpdateHostClassService
) {
this.updateHostClassService.initializeElement(elementRef.nativeElement);
}
ngOnInit() {
const bindKeyEventElement = this._getElementBySelector(this.thyBindKeyEventContainer);
this.ngZone.runOutsideAngular(() => {
this._bindKeyEventUnsubscribe = this.renderer.listen(
bindKeyEventElement,
'keydown',
this.onKeydown.bind(this)
);
});
this._instanceSelectionModel();
}
writeValue(value: any[] | any): void {
if (value) {
if (this.multiple && !helpers.isArray(value)) {
throw new Error(`multiple selection ngModel must be array.`);
}
if (!this.multiple && helpers.isArray(value)) {
throw new Error(`single selection ngModel not be array.`);
}
}
const values = helpers.isArray(value) ? value : value ? [value] : [];
this._modelValues = values;
if (this.options) {
this._setSelectionByValues(values);
}
}
registerOnChange(fn: any): void {
this._onChange = fn;
}
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
onKeydown(event: KeyboardEvent) {
if (this.thyBeforeKeydown) {
// stop key down event
const isContinue = this.thyBeforeKeydown(event);
if (!isContinue) {
return;
}
}
const keyCode = event.keyCode || event.which;
const manager = this._keyManager;
const previousFocusIndex = manager.activeItemIndex;
switch (keyCode) {
case keycodes.SPACE:
case keycodes.ENTER:
this._toggleFocusedOption(event);
// Always prevent space from scrolling the page since the list has focus
event.preventDefault();
break;
default:
manager.onKeydown(event);
}
if (
(keyCode === keycodes.UP_ARROW || keyCode === keycodes.DOWN_ARROW) &&
event.shiftKey &&
manager.activeItemIndex !== previousFocusIndex
) {
this._toggleFocusedOption(event);
}
}
toggleOption(option: ThyListOptionComponent, event?: Event) {
if (option && !option.disabled) {
this.selectionModel.toggle(this._getOptionSelectionValue(option));
// Emit a change event because the focused option changed its state through user
// interaction.
this._emitModelValueChange();
this._emitChangeEvent(option, event);
}
}
setActiveOption(option: ThyListOptionComponent) {
this._keyManager.updateActiveItem(option); // .updateActiveItemIndex(this._getOptionIndex(option));
}
scrollIntoView(option: ThyListOptionComponent) {
const scrollContainerElement = dom.getHTMLElementBySelector(this.thyScrollContainer, this.elementRef);
ScrollToService.scrollToElement(option.element.nativeElement, scrollContainerElement);
}
isSelected(option: ThyListOptionComponent) {
return this.selectionModel.isSelected(this._getOptionSelectionValue(option));
}
clearActiveItem() {
if (this._keyManager.activeItem) {
this._keyManager.setActiveItem(-1);
}
}
determineClearActiveItem() {
if (!this._getActiveOption()) {
this.clearActiveItem();
}
}
/** Selects all of the options. */
selectAll() {
this._setAllOptionsSelected(true);
}
/** Deselects all of the options. */
deselectAll() {
this._setAllOptionsSelected(false);
}
ngAfterContentInit(): void {
this._initializeFocusKeyManager();
this.options.changes.pipe(startWith(true)).subscribe(() => {
if (this.thyFirstItemDefaultActive) {
if (!this._keyManager.activeItem || this.options.toArray().indexOf(this._keyManager.activeItem) < 0) {
this._keyManager.setFirstItemActive();
}
}
});
// if (this._tempValues) {
// this._setSelectionByValues(this._tempValues);
// this._tempValues = null;
// }
}
ngOnDestroy() {
this._selectionChangesUnsubscribe$.unsubscribe();
if (this._bindKeyEventUnsubscribe) {
this._bindKeyEventUnsubscribe();
}
}
}