-
-
Notifications
You must be signed in to change notification settings - Fork 132
/
mat-select-search.component.ts
executable file
·677 lines (588 loc) · 23.1 KB
/
mat-select-search.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
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
/**
* Copyright (c) 2018 Bithost GmbH All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ElementRef,
EventEmitter,
forwardRef,
HostBinding,
Inject,
Input,
OnDestroy,
OnInit,
Optional,
Output,
QueryList,
ViewChild
} from '@angular/core';
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR } from '@angular/forms';
import { _countGroupLabelsBeforeOption, MatOption } from '@angular/material/core';
import { MatSelect } from '@angular/material/select';
import { MatFormField } from '@angular/material/form-field';
import { A, DOWN_ARROW, END, ENTER, ESCAPE, HOME, NINE, SPACE, UP_ARROW, Z, ZERO, } from '@angular/cdk/keycodes';
import { ViewportRuler } from '@angular/cdk/scrolling';
import { LiveAnnouncer } from '@angular/cdk/a11y';
import { BehaviorSubject, combineLatest, Observable, of, Subject } from 'rxjs';
import { delay, filter, map, startWith, switchMap, take, takeUntil, tap } from 'rxjs/operators';
import { MatSelectSearchClearDirective } from './mat-select-search-clear.directive';
/** The max height of the select's overlay panel. */
const SELECT_PANEL_MAX_HEIGHT = 256;
/* tslint:disable:member-ordering component-selector */
/**
* Component providing an input field for searching MatSelect options.
*
* Example usage:
*
* interface Bank {
* id: string;
* name: string;
* }
*
* @Component({
* selector: 'my-app-data-selection',
* template: `
* <mat-form-field>
* <mat-select [formControl]="bankCtrl" placeholder="Bank">
* <mat-option>
* <ngx-mat-select-search [formControl]="bankFilterCtrl"></ngx-mat-select-search>
* </mat-option>
* <mat-option *ngFor="let bank of filteredBanks | async" [value]="bank.id">
* {{bank.name}}
* </mat-option>
* </mat-select>
* </mat-form-field>
* `
* })
* export class DataSelectionComponent implements OnInit, OnDestroy {
*
* // control for the selected bank
* public bankCtrl: FormControl = new FormControl();
* // control for the MatSelect filter keyword
* public bankFilterCtrl: FormControl = new FormControl();
*
* // list of banks
* private banks: Bank[] = [{name: 'Bank A', id: 'A'}, {name: 'Bank B', id: 'B'}, {name: 'Bank C', id: 'C'}];
* // list of banks filtered by search keyword
* public filteredBanks: ReplaySubject<Bank[]> = new ReplaySubject<Bank[]>(1);
*
* // Subject that emits when the component has been destroyed.
* private _onDestroy = new Subject<void>();
*
*
* ngOnInit() {
* // load the initial bank list
* this.filteredBanks.next(this.banks.slice());
* // listen for search field value changes
* this.bankFilterCtrl.valueChanges
* .pipe(takeUntil(this._onDestroy))
* .subscribe(() => {
* this.filterBanks();
* });
* }
*
* ngOnDestroy() {
* this._onDestroy.next();
* this._onDestroy.complete();
* }
*
* private filterBanks() {
* if (!this.banks) {
* return;
* }
*
* // get the search keyword
* let search = this.bankFilterCtrl.value;
* if (!search) {
* this.filteredBanks.next(this.banks.slice());
* return;
* } else {
* search = search.toLowerCase();
* }
*
* // filter the banks
* this.filteredBanks.next(
* this.banks.filter(bank => bank.name.toLowerCase().indexOf(search) > -1)
* );
* }
* }
*/
@Component({
selector: 'ngx-mat-select-search',
templateUrl: './mat-select-search.component.html',
styleUrls: ['./mat-select-search.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatSelectSearchComponent),
multi: true
}
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MatSelectSearchComponent implements OnInit, OnDestroy, ControlValueAccessor {
/** Label of the search placeholder */
@Input() placeholderLabel = 'Suche';
/** Type of the search input field */
@Input() type = 'text';
/** Label to be shown when no entries are found. Set to null if no message should be shown. */
@Input() noEntriesFoundLabel = 'Keine Optionen gefunden';
/**
* Text that is appended to the currently active item label announced by screen readers,
* informing the user of the current index, value and total options.
* eg: Bank R (Germany) 1 of 6
*/
@Input() indexAndLengthScreenReaderText = ' of ';
/**
* Whether or not the search field should be cleared after the dropdown menu is closed.
* Useful for server-side filtering. See [#3](https://github.com/bithost-gmbh/ngx-mat-select-search/issues/3)
*/
@Input() clearSearchInput = true;
/** Whether to show the search-in-progress indicator */
@Input() searching = false;
/** Disables initial focusing of the input field */
@Input() disableInitialFocus = false;
/** Enable clear input on escape pressed */
@Input() enableClearOnEscapePressed = false;
/**
* Prevents home / end key being propagated to mat-select,
* allowing to move the cursor within the search input instead of navigating the options
*/
@Input() preventHomeEndKeyPropagation = false;
/** Disables scrolling to active options when option list changes. Useful for server-side search */
@Input() disableScrollToActiveOnOptionsChanged = false;
/** Adds 508 screen reader support for search box */
@Input() ariaLabel = 'dropdown search';
/** Whether to show Select All Checkbox (for mat-select[multi=true]) */
@Input() showToggleAllCheckbox = false;
/** select all checkbox checked state */
@Input() toggleAllCheckboxChecked = false;
/** select all checkbox indeterminate state */
@Input() toggleAllCheckboxIndeterminate = false;
/** Display a message in a tooltip on the toggle-all checkbox */
@Input() toggleAllCheckboxTooltipMessage = '';
/** Define the position of the tooltip on the toggle-all checkbox. */
@Input() toogleAllCheckboxTooltipPosition: 'left' | 'right' | 'above' | 'below' | 'before' | 'after' = 'below';
/** Show/Hide the search clear button of the search input */
@Input() hideClearSearchButton = false;
/**
* Always restore selected options on selectionChange for mode multi (e.g. for lazy loading/infinity scrolling).
* Defaults to false, so selected options are only restored while filtering is active.
*/
@Input() alwaysRestoreSelectedOptionsMulti = false;
/** Output emitter to send to parent component with the toggle all boolean */
@Output() toggleAll = new EventEmitter<boolean>();
/** Reference to the search input field */
@ViewChild('searchSelectInput', { read: ElementRef, static: true }) searchSelectInput: ElementRef;
/** Reference to the search input field */
@ViewChild('innerSelectSearch', { read: ElementRef, static: true }) innerSelectSearch: ElementRef;
/** Reference to custom search input clear icon */
@ContentChild(MatSelectSearchClearDirective, { static: false }) clearIcon: MatSelectSearchClearDirective;
@HostBinding('class.mat-select-search-inside-mat-option')
get isInsideMatOption(): boolean {
return !!this.matOption;
}
/** Current search value */
get value(): string {
return this._formControl.value;
}
private _lastExternalInputValue: string;
onTouched: Function = (_: any) => { };
/** Reference to the MatSelect options */
public set _options(_options: QueryList<MatOption>) {
this._options$.next(_options);
}
public get _options(): QueryList<MatOption> {
return this._options$.getValue();
}
public _options$: BehaviorSubject<QueryList<MatOption>> = new BehaviorSubject<QueryList<MatOption>>(null);
private optionsList$: Observable<MatOption[]> = this._options$.pipe(
switchMap(_options => _options ?
_options.changes.pipe(
map(options => options.toArray()),
startWith<MatOption[]>(_options.toArray()),
) : of(null)
)
);
private optionsLength$: Observable<number> = this.optionsList$.pipe(
map(options => options ? options.length : 0)
);
/** Previously selected values when using <mat-select [multiple]="true">*/
private previousSelectedValues: any[];
public _formControl: FormControl = new FormControl('');
/** whether to show the no entries found message */
public _showNoEntriesFound$: Observable<boolean> = combineLatest([
this._formControl.valueChanges,
this.optionsLength$
]).pipe(
map(([value, optionsLength]) => this.noEntriesFoundLabel && value
&& optionsLength === this.getOptionsLengthOffset())
);
/** Subject that emits when the component has been destroyed. */
private _onDestroy = new Subject<void>();
constructor(@Inject(MatSelect) public matSelect: MatSelect,
public changeDetectorRef: ChangeDetectorRef,
private _viewportRuler: ViewportRuler,
@Optional() @Inject(MatOption) public matOption: MatOption = null,
private liveAnnouncer: LiveAnnouncer,
@Optional() @Inject(MatFormField) public matFormField: MatFormField = null
) {
}
ngOnInit() {
// set custom panel class
const panelClass = 'mat-select-search-panel';
if (this.matSelect.panelClass) {
if (Array.isArray(this.matSelect.panelClass)) {
(<string[]>this.matSelect.panelClass).push(panelClass);
} else if (typeof this.matSelect.panelClass === 'string') {
this.matSelect.panelClass = [this.matSelect.panelClass, panelClass];
} else if (typeof this.matSelect.panelClass === 'object') {
this.matSelect.panelClass[panelClass] = true;
}
} else {
this.matSelect.panelClass = panelClass;
}
// set custom mat-option class if the component was placed inside a mat-option
if (this.matOption) {
this.matOption.disabled = true;
this.matOption._getHostElement().classList.add('contains-mat-select-search');
} else {
console.error('<ngx-mat-select-search> must be placed inside a <mat-option> element');
}
// when the select dropdown panel is opened or closed
this.matSelect.openedChange
.pipe(
delay(1),
takeUntil(this._onDestroy)
)
.subscribe((opened) => {
if (opened) {
this.updateInputWidth();
// focus the search field when opening
if (!this.disableInitialFocus) {
this._focus();
}
} else {
// clear it when closing
if (this.clearSearchInput) {
this._reset();
}
}
});
// set the first item active after the options changed
this.matSelect.openedChange
.pipe(take(1))
.pipe(takeUntil(this._onDestroy))
.subscribe(() => {
if (this.matSelect._keyManager) {
this.matSelect._keyManager.change.pipe(takeUntil(this._onDestroy))
.subscribe(() => this.adjustScrollTopToFitActiveOptionIntoView());
} else {
console.log('_keyManager was not initialized.');
}
this._options = this.matSelect.options;
// Closure variable for tracking the most recent first option.
// In order to avoid avoid causing the list to
// scroll to the top when options are added to the bottom of
// the list (eg: infinite scroll), we compare only
// the changes to the first options to determine if we
// should set the first item as active.
// This prevents unnecessary scrolling to the top of the list
// when options are appended, but allows the first item
// in the list to be set as active by default when there
// is no active selection
let previousFirstOption = this._options.toArray()[this.getOptionsLengthOffset()];
this._options.changes
.pipe(
takeUntil(this._onDestroy)
)
.subscribe(() => {
// avoid "expression has been changed" error
setTimeout(() => {
// Convert the QueryList to an array
const options = this._options.toArray();
// The true first item is offset by 1
const currentFirstOption = options[this.getOptionsLengthOffset()];
const keyManager = this.matSelect._keyManager;
if (keyManager && this.matSelect.panelOpen) {
// set first item active and input width
// Check to see if the first option in these changes is different from the previous.
const firstOptionIsChanged = !this.matSelect.compareWith(previousFirstOption, currentFirstOption);
// CASE: The first option is different now.
// Indiciates we should set it as active and scroll to the top.
if (firstOptionIsChanged
|| !keyManager.activeItem
|| !options.find(option => this.matSelect.compareWith(option, keyManager.activeItem))) {
keyManager.setFirstItemActive();
}
// wait for panel width changes
setTimeout(() => {
this.updateInputWidth();
});
if (!this.disableScrollToActiveOnOptionsChanged) {
this.adjustScrollTopToFitActiveOptionIntoView();
}
}
// Update our reference
previousFirstOption = currentFirstOption;
});
});
});
// add or remove css class depending on whether to show the no entries found message
// note: this is hacky
this._showNoEntriesFound$.pipe(
takeUntil(this._onDestroy)
).subscribe(showNoEntriesFound => {
// set no entries found class on mat option
if (this.matOption) {
if (showNoEntriesFound) {
this.matOption._getHostElement().classList.add('mat-select-search-no-entries-found');
} else {
this.matOption._getHostElement().classList.remove('mat-select-search-no-entries-found');
}
}
});
// resize the input width when the viewport is resized, i.e. the trigger width could potentially be resized
this._viewportRuler.change()
.pipe(takeUntil(this._onDestroy))
.subscribe(() => {
if (this.matSelect.panelOpen) {
this.updateInputWidth();
}
});
this.initMultipleHandling();
this.optionsList$.pipe(
takeUntil(this._onDestroy)
).subscribe(() => {
// update view when available options change
this.changeDetectorRef.markForCheck();
});
}
_emitSelectAllBooleanToParent(state: boolean) {
this.toggleAll.emit(state);
}
ngOnDestroy() {
this._onDestroy.next();
this._onDestroy.complete();
}
_isToggleAllCheckboxVisible(): boolean {
return this.matSelect.multiple && this.showToggleAllCheckbox;
}
/**
* Handles the key down event with MatSelect.
* Allows e.g. selecting with enter key, navigation with arrow keys, etc.
* @param event
*/
_handleKeydown(event: KeyboardEvent) {
// Prevent propagation for all alphanumeric characters in order to avoid selection issues
if ((event.key && event.key.length === 1) ||
(event.keyCode >= A && event.keyCode <= Z) ||
(event.keyCode >= ZERO && event.keyCode <= NINE) ||
(event.keyCode === SPACE)
|| (this.preventHomeEndKeyPropagation && (event.keyCode === HOME || event.keyCode === END))
) {
event.stopPropagation();
}
if (this.matSelect.multiple && event.key && event.keyCode === ENTER) {
// Regain focus after multiselect, so we can further type
setTimeout(() => this._focus());
}
// Special case if click Escape, if input is empty, close the dropdown, if not, empty out the search field
if (this.enableClearOnEscapePressed === true && event.keyCode === ESCAPE && this.value) {
this._reset(true);
event.stopPropagation();
}
}
/**
* Handles the key up event with MatSelect.
* Allows e.g. the announcing of the currently activeDescendant by screen readers.
*/
_handleKeyup(event: KeyboardEvent) {
if (event.keyCode === UP_ARROW || event.keyCode === DOWN_ARROW) {
const ariaActiveDescendantId = this.matSelect._getAriaActiveDescendant();
const index = this._options.toArray().findIndex(item => item.id === ariaActiveDescendantId);
if (index !== -1) {
const activeDescendant = this._options.toArray()[index];
this.liveAnnouncer.announce(
activeDescendant.viewValue + ' '
+ this.getAriaIndex(index)
+ this.indexAndLengthScreenReaderText
+ this.getAriaLength()
);
}
}
}
/**
* Calculate the index of the current option, taking the offset to length into account.
* examples:
* Case 1 [Search, 1, 2, 3] will have offset of 1, due to search and will read index of total.
* Case 2 [1, 2, 3] will have offset of 0 and will read index +1 of total.
*/
getAriaIndex(optionIndex: number): number {
if (this.getOptionsLengthOffset() === 0) {
return optionIndex + 1;
}
return optionIndex;
}
/**
* Calculate the length of the options, taking the offset to length into account.
* examples:
* Case 1 [Search, 1, 2, 3] will have length of options.length -1, due to search.
* Case 2 [1, 2, 3] will have length of options.length.
*/
getAriaLength(): number {
return this._options.toArray().length - this.getOptionsLengthOffset();
}
writeValue(value: string) {
this._lastExternalInputValue = value;
this._formControl.setValue(value);
this.changeDetectorRef.markForCheck();
}
onBlur() {
this.onTouched();
}
registerOnChange(fn: (value: string) => void) {
this._formControl.valueChanges.pipe(
filter(value => value !== this._lastExternalInputValue),
tap(() => this._lastExternalInputValue = undefined),
takeUntil(this._onDestroy)
).subscribe(fn);
}
registerOnTouched(fn: Function) {
this.onTouched = fn;
}
/**
* Focuses the search input field
*/
public _focus() {
if (!this.searchSelectInput || !this.matSelect.panel) {
return;
}
// save and restore scrollTop of panel, since it will be reset by focus()
// note: this is hacky
const panel = this.matSelect.panel.nativeElement;
const scrollTop = panel.scrollTop;
// focus
this.searchSelectInput.nativeElement.focus();
panel.scrollTop = scrollTop;
}
/**
* Resets the current search value
* @param focus whether to focus after resetting
*/
public _reset(focus?: boolean) {
this._formControl.setValue('');
if (focus) {
this._focus();
}
}
/**
* Initializes handling <mat-select [multiple]="true">
* Note: to improve this code, mat-select should be extended to allow disabling resetting the selection while filtering.
*/
private initMultipleHandling() {
if (!this.matSelect.ngControl) {
if (this.matSelect.multiple) {
// note: the access to matSelect.ngControl (instead of matSelect.value / matSelect.valueChanges)
// is necessary to properly work in multi-selection mode.
console.error('the mat-select containing ngx-mat-select-search must have a ngModel or formControl directive when multiple=true');
}
return;
}
// if <mat-select [multiple]="true">
// store previously selected values and restore them when they are deselected
// because the option is not available while we are currently filtering
this.previousSelectedValues = this.matSelect.ngControl.value;
this.matSelect.ngControl.valueChanges
.pipe(takeUntil(this._onDestroy))
.subscribe((values) => {
let restoreSelectedValues = false;
if (this.matSelect.multiple) {
if ((this.alwaysRestoreSelectedOptionsMulti || (this._formControl.value && this._formControl.value.length))
&& this.previousSelectedValues && Array.isArray(this.previousSelectedValues)) {
if (!values || !Array.isArray(values)) {
values = [];
}
const optionValues = this.matSelect.options.map(option => option.value);
this.previousSelectedValues.forEach(previousValue => {
if (!values.some(v => this.matSelect.compareWith(v, previousValue))
&& !optionValues.some(v => this.matSelect.compareWith(v, previousValue))) {
// if a value that was selected before is deselected and not found in the options, it was deselected
// due to the filtering, so we restore it.
values.push(previousValue);
restoreSelectedValues = true;
}
});
}
}
this.previousSelectedValues = values;
if (restoreSelectedValues) {
this.matSelect._onChange(values);
}
});
}
/**
* Scrolls the currently active option into the view if it is not yet visible.
*/
private adjustScrollTopToFitActiveOptionIntoView(): void {
if (this.matSelect.panel && this.matSelect.options.length > 0) {
const matOptionHeight = this.getMatOptionHeight();
const activeOptionIndex = this.matSelect._keyManager.activeItemIndex || 0;
const labelCount = _countGroupLabelsBeforeOption(activeOptionIndex, this.matSelect.options, this.matSelect.optionGroups);
// If the component is in a MatOption, the activeItemIndex will be offset by one.
const indexOfOptionToFitIntoView = (this.matOption ? -1 : 0) + labelCount + activeOptionIndex;
const currentScrollTop = this.matSelect.panel.nativeElement.scrollTop;
const searchInputHeight = this.innerSelectSearch.nativeElement.offsetHeight;
const amountOfVisibleOptions = Math.floor((SELECT_PANEL_MAX_HEIGHT - searchInputHeight) / matOptionHeight);
const indexOfFirstVisibleOption = Math.round((currentScrollTop + searchInputHeight) / matOptionHeight) - 1;
if (indexOfFirstVisibleOption >= indexOfOptionToFitIntoView) {
this.matSelect.panel.nativeElement.scrollTop = indexOfOptionToFitIntoView * matOptionHeight;
} else if (indexOfFirstVisibleOption + amountOfVisibleOptions <= indexOfOptionToFitIntoView) {
this.matSelect.panel.nativeElement.scrollTop = (indexOfOptionToFitIntoView + 1) * matOptionHeight
- (SELECT_PANEL_MAX_HEIGHT - searchInputHeight);
}
}
}
/**
* Set the width of the innerSelectSearch to fit even custom scrollbars
* And support all Operation Systems
*/
public updateInputWidth() {
if (!this.innerSelectSearch || !this.innerSelectSearch.nativeElement) {
return;
}
let element: HTMLElement = this.innerSelectSearch.nativeElement;
let panelElement: HTMLElement;
while (element = element.parentElement) {
if (element.classList.contains('mat-select-panel')) {
panelElement = element;
break;
}
}
if (panelElement) {
this.innerSelectSearch.nativeElement.style.width = panelElement.clientWidth + 'px';
}
}
private getMatOptionHeight(): number {
if (this.matSelect.options.length > 0) {
return this.matSelect.options.first._getHostElement().getBoundingClientRect().height;
}
return 0;
}
/**
* Determine the offset to length that can be caused by the optional matOption used as a search input.
*/
private getOptionsLengthOffset(): number {
if (this.matOption) {
return 1;
} else {
return 0;
}
}
}