-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
select.ts
1151 lines (971 loc) · 39 KB
/
select.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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright Google Inc. 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 {
AfterContentInit,
Component,
ContentChildren,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
QueryList,
Renderer2,
Self,
ViewEncapsulation,
ViewChild,
ChangeDetectorRef,
Attribute,
OnInit,
Inject,
ChangeDetectionStrategy,
InjectionToken,
} from '@angular/core';
import {NgForm, FormGroupDirective} from '@angular/forms';
import {MdOption, MdOptionSelectionChange, MdOptgroup} from '../core/option/index';
import {ENTER, SPACE, UP_ARROW, DOWN_ARROW, HOME, END} from '../core/keyboard/keycodes';
import {FocusKeyManager} from '../core/a11y/focus-key-manager';
import {Directionality} from '../core/bidi/index';
import {Observable} from 'rxjs/Observable';
import {Subscription} from 'rxjs/Subscription';
import {transformPlaceholder, transformPanel, fadeInContent} from './select-animations';
import {ControlValueAccessor, NgControl} from '@angular/forms';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {ConnectedOverlayDirective} from '../core/overlay/overlay-directives';
import {ViewportRuler} from '../core/overlay/position/viewport-ruler';
import {SelectionModel} from '../core/selection/selection';
import {Overlay} from '../core/overlay/overlay';
import {getMdSelectDynamicMultipleError, getMdSelectNonArrayValueError} from './select-errors';
import {startWith, filter} from '../core/rxjs/index';
import {merge} from 'rxjs/observable/merge';
import {CanColor, mixinColor} from '../core/common-behaviors/color';
import {CanDisable, mixinDisabled} from '../core/common-behaviors/disabled';
import {
FloatPlaceholderType,
PlaceholderOptions,
MD_PLACEHOLDER_GLOBAL_OPTIONS
} from '../core/placeholder/placeholder-options';
// This import is only used to define a generic type. The current TypeScript version incorrectly
// considers such imports as unused (https://github.com/Microsoft/TypeScript/issues/14953)
// tslint:disable-next-line:no-unused-variable
import {ScrollStrategy, RepositionScrollStrategy} from '../core/overlay/scroll';
import {Platform} from '@angular/cdk/platform';
/**
* The following style constants are necessary to save here in order
* to properly calculate the alignment of the selected option over
* the trigger element.
*/
/** The fixed height of every option element (option, group header etc.). */
export const SELECT_ITEM_HEIGHT = 48;
/** The max height of the select's overlay panel */
export const SELECT_PANEL_MAX_HEIGHT = 256;
/** The max number of options visible at once in the select panel. */
export const SELECT_MAX_OPTIONS_DISPLAYED =
Math.floor(SELECT_PANEL_MAX_HEIGHT / SELECT_ITEM_HEIGHT);
/** The fixed height of the select's trigger element. */
export const SELECT_TRIGGER_HEIGHT = 30;
/**
* Must adjust for the difference in height between the option and the trigger,
* so the text will align on the y axis.
*/
export const SELECT_OPTION_HEIGHT_ADJUSTMENT = (SELECT_ITEM_HEIGHT - SELECT_TRIGGER_HEIGHT) / 2;
/** The panel's padding on the x-axis */
export const SELECT_PANEL_PADDING_X = 16;
/** The panel's x axis padding if it is indented (e.g. there is an option group). */
export const SELECT_PANEL_INDENT_PADDING_X = SELECT_PANEL_PADDING_X * 2;
/**
* Distance between the panel edge and the option text in
* multi-selection mode.
*
* (SELECT_PADDING * 1.75) + 20 = 48
* The padding is multiplied by 1.75 because the checkbox's margin is half the padding, and
* the browser adds ~4px, because we're using inline elements.
* The checkbox width is 20px.
*/
export const SELECT_MULTIPLE_PANEL_PADDING_X = SELECT_PANEL_PADDING_X * 1.75 + 20;
/**
* The panel's padding on the y-axis. This padding indicates there are more
* options available if you scroll.
*/
export const SELECT_PANEL_PADDING_Y = 16;
/**
* The select panel will only "fit" inside the viewport if it is positioned at
* this value or more away from the viewport boundary.
*/
export const SELECT_PANEL_VIEWPORT_PADDING = 8;
/**
* Default minimum width of the trigger based on the CSS.
* Used as a fallback for server-side rendering.
* @docs-private
*/
const SELECT_TRIGGER_MIN_WIDTH = 112;
/** Injection token that determines the scroll handling while a select is open. */
export const MD_SELECT_SCROLL_STRATEGY =
new InjectionToken<() => ScrollStrategy>('md-select-scroll-strategy');
/** @docs-private */
export function MD_SELECT_SCROLL_STRATEGY_PROVIDER_FACTORY(overlay: Overlay) {
return () => overlay.scrollStrategies.reposition();
}
/** @docs-private */
export const MD_SELECT_SCROLL_STRATEGY_PROVIDER = {
provide: MD_SELECT_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MD_SELECT_SCROLL_STRATEGY_PROVIDER_FACTORY,
};
/** Change event object that is emitted when the select value has changed. */
export class MdSelectChange {
constructor(public source: MdSelect, public value: any) { }
}
// Boilerplate for applying mixins to MdSelect.
/** @docs-private */
export class MdSelectBase {
constructor(public _renderer: Renderer2, public _elementRef: ElementRef) {}
}
export const _MdSelectMixinBase = mixinColor(mixinDisabled(MdSelectBase), 'primary');
@Component({
moduleId: module.id,
selector: 'md-select, mat-select',
templateUrl: 'select.html',
styleUrls: ['select.css'],
inputs: ['color', 'disabled'],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'role': 'listbox',
'[attr.tabindex]': 'tabIndex',
'[attr.aria-label]': '_ariaLabel',
'[attr.aria-labelledby]': 'ariaLabelledby',
'[attr.aria-required]': 'required.toString()',
'[attr.aria-disabled]': 'disabled.toString()',
'[attr.aria-invalid]': '_isErrorState()',
'[attr.aria-owns]': '_optionIds',
'[class.mat-select-disabled]': 'disabled',
'[class.mat-select-invalid]': '_isErrorState()',
'[class.mat-select-required]': 'required',
'class': 'mat-select',
'(keydown)': '_handleClosedKeydown($event)',
'(blur)': '_onBlur()',
},
animations: [
transformPlaceholder,
transformPanel,
fadeInContent
],
exportAs: 'mdSelect',
})
export class MdSelect extends _MdSelectMixinBase implements AfterContentInit, OnDestroy, OnInit,
ControlValueAccessor, CanColor, CanDisable {
/** Whether or not the overlay panel is open. */
private _panelOpen = false;
/** Subscriptions to option events. */
private _optionSubscription: Subscription | null;
/** Subscription to changes in the option list. */
private _changeSubscription: Subscription;
/** Subscription to tab events while overlay is focused. */
private _tabSubscription: Subscription;
/** Whether filling out the select is required in the form. */
private _required: boolean = false;
/** The scroll position of the overlay panel, calculated to center the selected option. */
private _scrollTop = 0;
/** The placeholder displayed in the trigger of the select. */
private _placeholder: string;
/** Whether the component is in multiple selection mode. */
private _multiple: boolean = false;
/** Deals with the selection logic. */
_selectionModel: SelectionModel<MdOption>;
/** The animation state of the placeholder. */
private _placeholderState = '';
/** Tab index for the element. */
private _tabIndex: number;
/** Deals with configuring placeholder options */
private _placeholderOptions: PlaceholderOptions;
/**
* The width of the trigger. Must be saved to set the min width of the overlay panel
* and the width of the selected value.
*/
_triggerWidth: number;
/** Manages keyboard events for options in the panel. */
_keyManager: FocusKeyManager;
/**
* The width of the selected option's value. Must be set programmatically
* to ensure its overflow is clipped, as it's absolutely positioned.
*/
_selectedValueWidth: number;
/** View -> model callback called when value changes */
_onChange: (value: any) => void = () => {};
/** View -> model callback called when select has been touched */
_onTouched = () => {};
/** The IDs of child options to be passed to the aria-owns attribute. */
_optionIds: string = '';
/** The value of the select panel's transform-origin property. */
_transformOrigin: string = 'top';
/** Whether the panel's animation is done. */
_panelDoneAnimating: boolean = false;
/** Strategy that will be used to handle scrolling while the select panel is open. */
_scrollStrategy = this._scrollStrategyFactory();
/**
* The y-offset of the overlay panel in relation to the trigger's top start corner.
* This must be adjusted to align the selected option text over the trigger text.
* when the panel opens. Will change based on the y-position of the selected option.
*/
_offsetY = 0;
/**
* This position config ensures that the top "start" corner of the overlay
* is aligned with with the top "start" of the origin by default (overlapping
* the trigger completely). If the panel cannot fit below the trigger, it
* will fall back to a position above the trigger.
*/
_positions = [
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'top',
},
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'bottom',
},
];
/** Trigger that opens the select. */
@ViewChild('trigger') trigger: ElementRef;
/** Overlay pane containing the options. */
@ViewChild(ConnectedOverlayDirective) overlayDir: ConnectedOverlayDirective;
/** All of the defined select options. */
@ContentChildren(MdOption, { descendants: true }) options: QueryList<MdOption>;
/** All of the defined groups of options. */
@ContentChildren(MdOptgroup) optionGroups: QueryList<MdOptgroup>;
/** Classes to be passed to the select panel. Supports the same syntax as `ngClass`. */
@Input() panelClass: string|string[]|Set<string>|{[key: string]: any};
/** Placeholder to be shown if no value has been selected. */
@Input()
get placeholder() { return this._placeholder; }
set placeholder(value: string) {
this._placeholder = value;
// Must wait to record the trigger width to ensure placeholder width is included.
Promise.resolve(null).then(() => this._setTriggerWidth());
}
/** Whether the component is required. */
@Input()
get required() { return this._required; }
set required(value: any) { this._required = coerceBooleanProperty(value); }
/** Whether the user should be allowed to select multiple options. */
@Input()
get multiple(): boolean { return this._multiple; }
set multiple(value: boolean) {
if (this._selectionModel) {
throw getMdSelectDynamicMultipleError();
}
this._multiple = coerceBooleanProperty(value);
}
/** Whether to float the placeholder text. */
@Input()
get floatPlaceholder(): FloatPlaceholderType { return this._floatPlaceholder; }
set floatPlaceholder(value: FloatPlaceholderType) {
this._floatPlaceholder = value || this._placeholderOptions.float || 'auto';
}
private _floatPlaceholder: FloatPlaceholderType;
/** Tab index for the select element. */
@Input()
get tabIndex(): number { return this.disabled ? -1 : this._tabIndex; }
set tabIndex(value: number) {
if (typeof value !== 'undefined') {
this._tabIndex = value;
}
}
/** Value of the select control. */
@Input()
get value() { return this._value; }
set value(newValue: any) {
this.writeValue(newValue);
this._value = newValue;
}
private _value: any;
/** Aria label of the select. If not specified, the placeholder will be used as label. */
@Input('aria-label') ariaLabel: string = '';
/** Input that can be used to specify the `aria-labelledby` attribute. */
@Input('aria-labelledby') ariaLabelledby: string = '';
/** Combined stream of all of the child options' change events. */
get optionSelectionChanges(): Observable<MdOptionSelectionChange> {
return merge(...this.options.map(option => option.onSelectionChange));
}
/** Event emitted when the select has been opened. */
@Output() onOpen: EventEmitter<void> = new EventEmitter<void>();
/** Event emitted when the select has been closed. */
@Output() onClose: EventEmitter<void> = new EventEmitter<void>();
/** Event emitted when the selected value has been changed by the user. */
@Output() change: EventEmitter<MdSelectChange> = new EventEmitter<MdSelectChange>();
/**
* Event that emits whenever the raw value of the select changes. This is here primarily
* to facilitate the two-way binding for the `value` input.
* @docs-private
*/
@Output() valueChange = new EventEmitter<any>();
constructor(
private _viewportRuler: ViewportRuler,
private _changeDetectorRef: ChangeDetectorRef,
private _overlay: Overlay,
private _platform: Platform,
renderer: Renderer2,
elementRef: ElementRef,
@Optional() private _dir: Directionality,
@Optional() private _parentForm: NgForm,
@Optional() private _parentFormGroup: FormGroupDirective,
@Self() @Optional() public _control: NgControl,
@Attribute('tabindex') tabIndex: string,
@Optional() @Inject(MD_PLACEHOLDER_GLOBAL_OPTIONS) placeholderOptions: PlaceholderOptions,
@Inject(MD_SELECT_SCROLL_STRATEGY) private _scrollStrategyFactory) {
super(renderer, elementRef);
if (this._control) {
this._control.valueAccessor = this;
}
this._tabIndex = parseInt(tabIndex) || 0;
this._placeholderOptions = placeholderOptions ? placeholderOptions : {};
this.floatPlaceholder = this._placeholderOptions.float || 'auto';
}
ngOnInit() {
this._selectionModel = new SelectionModel<MdOption>(this.multiple, undefined, false);
}
ngAfterContentInit() {
this._initKeyManager();
this._changeSubscription = startWith.call(this.options.changes, null).subscribe(() => {
this._resetOptions();
// Defer setting the value in order to avoid the "Expression
// has changed after it was checked" errors from Angular.
Promise.resolve().then(() => {
this._setSelectionByValue(this._control ? this._control.value : this._value);
});
});
}
ngOnDestroy() {
this._dropSubscriptions();
if (this._changeSubscription) {
this._changeSubscription.unsubscribe();
}
if (this._tabSubscription) {
this._tabSubscription.unsubscribe();
}
}
/** Toggles the overlay panel open or closed. */
toggle(): void {
this.panelOpen ? this.close() : this.open();
}
/** Opens the overlay panel. */
open(): void {
if (this.disabled || !this.options.length) {
return;
}
if (!this._triggerWidth) {
this._setTriggerWidth();
}
this._calculateOverlayPosition();
this._placeholderState = this._floatPlaceholderState();
this._panelOpen = true;
this._changeDetectorRef.markForCheck();
}
/** Closes the overlay panel and focuses the host element. */
close(): void {
if (this._panelOpen) {
this._panelOpen = false;
if (this._selectionModel.isEmpty()) {
this._placeholderState = '';
}
this._changeDetectorRef.markForCheck();
this.focus();
}
}
/**
* Sets the select's value. Part of the ControlValueAccessor interface
* required to integrate with Angular's core forms API.
*
* @param value New value to be written to the model.
*/
writeValue(value: any): void {
if (this.options) {
this._setSelectionByValue(value);
}
}
/**
* Saves a callback function to be invoked when the select's value
* changes from user input. Part of the ControlValueAccessor interface
* required to integrate with Angular's core forms API.
*
* @param fn Callback to be triggered when the value changes.
*/
registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}
/**
* Saves a callback function to be invoked when the select is blurred
* by the user. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param fn Callback to be triggered when the component has been touched.
*/
registerOnTouched(fn: () => {}): void {
this._onTouched = fn;
}
/**
* Disables the select. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param isDisabled Sets whether the component is disabled.
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this._changeDetectorRef.markForCheck();
}
/** Whether or not the overlay panel is open. */
get panelOpen(): boolean {
return this._panelOpen;
}
/** The currently selected option. */
get selected(): MdOption | MdOption[] {
return this.multiple ? this._selectionModel.selected : this._selectionModel.selected[0];
}
/** The value displayed in the trigger. */
get triggerValue(): string {
if (this._multiple) {
let selectedOptions = this._selectionModel.selected.map(option => option.viewValue);
if (this._isRtl()) {
selectedOptions.reverse();
}
// TODO(crisbeto): delimiter should be configurable for proper localization.
return selectedOptions.join(', ');
}
return this._selectionModel.selected[0].viewValue;
}
/** Whether the element is in RTL mode. */
_isRtl(): boolean {
return this._dir ? this._dir.value === 'rtl' : false;
}
/**
* Sets the width of the trigger element. This is necessary to match
* the overlay width to the trigger width.
*/
private _setTriggerWidth(): void {
this._triggerWidth = this._platform.isBrowser ? this._getTriggerRect().width :
SELECT_TRIGGER_MIN_WIDTH;
this._changeDetectorRef.markForCheck();
}
/** Handles the keyboard interactions of a closed select. */
_handleClosedKeydown(event: KeyboardEvent): void {
if (!this.disabled) {
if (event.keyCode === ENTER || event.keyCode === SPACE) {
event.preventDefault(); // prevents the page from scrolling down when pressing space
this.open();
} else if (event.keyCode === UP_ARROW || event.keyCode === DOWN_ARROW) {
this._handleArrowKey(event);
}
}
}
/** Handles keypresses inside the panel. */
_handlePanelKeydown(event: KeyboardEvent): void {
if (event.keyCode === HOME || event.keyCode === END) {
event.preventDefault();
event.keyCode === HOME ? this._keyManager.setFirstItemActive() :
this._keyManager.setLastItemActive();
} else {
this._keyManager.onKeydown(event);
}
}
/**
* When the panel element is finished transforming in (though not fading in), it
* emits an event and focuses an option if the panel is open.
*/
_onPanelDone(): void {
if (this.panelOpen) {
this._focusCorrectOption();
this.onOpen.emit();
} else {
this.onClose.emit();
this._panelDoneAnimating = false;
this.overlayDir.offsetX = 0;
this._changeDetectorRef.markForCheck();
}
}
/**
* When the panel content is done fading in, the _panelDoneAnimating property is
* set so the proper class can be added to the panel.
*/
_onFadeInDone(): void {
this._panelDoneAnimating = this.panelOpen;
this._changeDetectorRef.markForCheck();
}
/**
* Calls the touched callback only if the panel is closed. Otherwise, the trigger will
* "blur" to the panel when it opens, causing a false positive.
*/
_onBlur() {
if (!this.disabled && !this.panelOpen) {
this._onTouched();
this._changeDetectorRef.markForCheck();
}
}
/**
* Callback that is invoked when the overlay panel has been attached.
*/
_onAttached(): void {
this._calculateOverlayOffsetX();
this._setScrollTop();
}
/** Whether the select has a value. */
_hasValue(): boolean {
return this._selectionModel && this._selectionModel.hasValue();
}
/** Whether the select is in an error state. */
_isErrorState(): boolean {
const isInvalid = this._control && this._control.invalid;
const isTouched = this._control && this._control.touched;
const isSubmitted = (this._parentFormGroup && this._parentFormGroup.submitted) ||
(this._parentForm && this._parentForm.submitted);
return !!(isInvalid && (isTouched || isSubmitted));
}
/**
* Sets the scroll position of the scroll container. This must be called after
* the overlay pane is attached or the scroll container element will not yet be
* present in the DOM.
*/
private _setScrollTop(): void {
const scrollContainer =
this.overlayDir.overlayRef.overlayElement.querySelector('.mat-select-panel');
scrollContainer!.scrollTop = this._scrollTop;
}
/**
* Sets the selected option based on a value. If no option can be
* found with the designated value, the select trigger is cleared.
*/
private _setSelectionByValue(value: any | any[], isUserInput = false): void {
const isArray = Array.isArray(value);
if (this.multiple && value && !isArray) {
throw getMdSelectNonArrayValueError();
}
this._clearSelection();
if (isArray) {
value.forEach((currentValue: any) => this._selectValue(currentValue, isUserInput));
this._sortValues();
} else {
this._selectValue(value, isUserInput);
}
this._setValueWidth();
if (this._selectionModel.isEmpty()) {
this._placeholderState = '';
}
this._changeDetectorRef.markForCheck();
}
/**
* Finds and selects and option based on its value.
* @returns Option that has the corresponding value.
*/
private _selectValue(value: any, isUserInput = false): MdOption | undefined {
let optionsArray = this.options.toArray();
let correspondingOption = optionsArray.find(option => {
return option.value != null && option.value === value;
});
if (correspondingOption) {
isUserInput ? correspondingOption._selectViaInteraction() : correspondingOption.select();
this._selectionModel.select(correspondingOption);
this._keyManager.setActiveItem(optionsArray.indexOf(correspondingOption));
}
return correspondingOption;
}
/**
* Clears the select trigger and deselects every option in the list.
* @param skip Option that should not be deselected.
*/
private _clearSelection(skip?: MdOption): void {
this._selectionModel.clear();
this.options.forEach(option => {
if (option !== skip) {
option.deselect();
}
});
}
private _getTriggerRect(): ClientRect {
return this.trigger.nativeElement.getBoundingClientRect();
}
/** Sets up a key manager to listen to keyboard events on the overlay panel. */
private _initKeyManager() {
this._keyManager = new FocusKeyManager(this.options);
this._tabSubscription = this._keyManager.tabOut.subscribe(() => this.close());
}
/** Drops current option subscriptions and IDs and resets from scratch. */
private _resetOptions(): void {
this._dropSubscriptions();
this._listenToOptions();
this._setOptionIds();
this._setOptionMultiple();
}
/** Listens to user-generated selection events on each option. */
private _listenToOptions(): void {
this._optionSubscription = filter.call(this.optionSelectionChanges,
event => event.isUserInput).subscribe(event => {
this._onSelect(event.source);
this._setValueWidth();
if (!this.multiple) {
this.close();
}
});
}
/** Invoked when an option is clicked. */
private _onSelect(option: MdOption): void {
const wasSelected = this._selectionModel.isSelected(option);
// TODO(crisbeto): handle blank/null options inside multi-select.
if (this.multiple) {
this._selectionModel.toggle(option);
wasSelected ? option.deselect() : option.select();
this._sortValues();
} else {
this._clearSelection(option.value == null ? undefined : option);
if (option.value == null) {
this._propagateChanges(option.value);
} else {
this._selectionModel.select(option);
}
}
if (wasSelected !== this._selectionModel.isSelected(option)) {
this._propagateChanges();
}
}
/**
* Sorts the model values, ensuring that they keep the same
* order that they have in the panel.
*/
private _sortValues(): void {
if (this._multiple) {
this._selectionModel.clear();
this.options.forEach(option => {
if (option.selected) {
this._selectionModel.select(option);
}
});
}
}
/** Unsubscribes from all option subscriptions. */
private _dropSubscriptions(): void {
if (this._optionSubscription) {
this._optionSubscription.unsubscribe();
this._optionSubscription = null;
}
}
/** Emits change event to set the model value. */
private _propagateChanges(fallbackValue?: any): void {
let valueToEmit: any = null;
if (Array.isArray(this.selected)) {
valueToEmit = this.selected.map(option => option.value);
} else {
valueToEmit = this.selected ? this.selected.value : fallbackValue;
}
this._value = valueToEmit;
this._onChange(valueToEmit);
this.change.emit(new MdSelectChange(this, valueToEmit));
this.valueChange.emit(valueToEmit);
}
/** Records option IDs to pass to the aria-owns property. */
private _setOptionIds() {
this._optionIds = this.options.map(option => option.id).join(' ');
}
/**
* Sets the `multiple` property on each option. The promise is necessary
* in order to avoid Angular errors when modifying the property after init.
*/
private _setOptionMultiple() {
if (this.multiple) {
Promise.resolve(null).then(() => {
this.options.forEach(option => option.multiple = this.multiple);
});
}
}
/**
* Must set the width of the selected option's value programmatically
* because it is absolutely positioned and otherwise will not clip
* overflow. The selection arrow is 9px wide, add 4px of padding = 13
*/
private _setValueWidth() {
this._selectedValueWidth = this._triggerWidth - 13;
this._changeDetectorRef.markForCheck();
}
/**
* Focuses the selected item. If no option is selected, it will focus
* the first item instead.
*/
private _focusCorrectOption(): void {
if (this._selectionModel.isEmpty()) {
this._keyManager.setFirstItemActive();
} else {
this._keyManager.setActiveItem(this._getOptionIndex(this._selectionModel.selected[0])!);
}
}
/** Focuses the select element. */
focus(): void {
this._elementRef.nativeElement.focus();
}
/** Gets the index of the provided option in the option list. */
private _getOptionIndex(option: MdOption): number | undefined {
return this.options.reduce((result: number, current: MdOption, index: number) => {
return result === undefined ? (option === current ? index : undefined) : result;
}, undefined);
}
/** Calculates the scroll position and x- and y-offsets of the overlay panel. */
private _calculateOverlayPosition(): void {
const items = this._getItemCount();
const panelHeight = Math.min(items * SELECT_ITEM_HEIGHT, SELECT_PANEL_MAX_HEIGHT);
const scrollContainerHeight = items * SELECT_ITEM_HEIGHT;
// The farthest the panel can be scrolled before it hits the bottom
const maxScroll = scrollContainerHeight - panelHeight;
if (this._hasValue()) {
let selectedOptionOffset = this._getOptionIndex(this._selectionModel.selected[0])!;
selectedOptionOffset += this._getLabelCountBeforeOption(selectedOptionOffset);
// We must maintain a scroll buffer so the selected option will be scrolled to the
// center of the overlay panel rather than the top.
const scrollBuffer = panelHeight / 2;
this._scrollTop = this._calculateOverlayScroll(selectedOptionOffset, scrollBuffer, maxScroll);
this._offsetY = this._calculateOverlayOffsetY(selectedOptionOffset, scrollBuffer, maxScroll);
} else {
// If no option is selected, the panel centers on the first option. In this case,
// we must only adjust for the height difference between the option element
// and the trigger element, then multiply it by -1 to ensure the panel moves
// in the correct direction up the page.
this._offsetY = (SELECT_ITEM_HEIGHT - SELECT_TRIGGER_HEIGHT) / 2 * -1 -
(this._getLabelCountBeforeOption(0) * SELECT_ITEM_HEIGHT);
}
this._checkOverlayWithinViewport(maxScroll);
}
/**
* Calculates the scroll position of the select's overlay panel.
*
* Attempts to center the selected option in the panel. If the option is
* too high or too low in the panel to be scrolled to the center, it clamps the
* scroll position to the min or max scroll positions respectively.
*/
_calculateOverlayScroll(selectedIndex: number, scrollBuffer: number,
maxScroll: number): number {
const optionOffsetFromScrollTop = SELECT_ITEM_HEIGHT * selectedIndex;
const halfOptionHeight = SELECT_ITEM_HEIGHT / 2;
// Starts at the optionOffsetFromScrollTop, which scrolls the option to the top of the
// scroll container, then subtracts the scroll buffer to scroll the option down to
// the center of the overlay panel. Half the option height must be re-added to the
// scrollTop so the option is centered based on its middle, not its top edge.
const optimalScrollPosition = optionOffsetFromScrollTop - scrollBuffer + halfOptionHeight;
return clampValue(0, optimalScrollPosition, maxScroll);
}
/**
* Figures out the appropriate animation state for the placeholder.
*/
_getPlaceholderAnimationState(): string {
if (this.floatPlaceholder === 'never') {
return '';
}
if (this.floatPlaceholder === 'always') {
return this._floatPlaceholderState();
}
return this._placeholderState;
}
/**
* Determines the CSS `opacity` of the placeholder element.
*/
_getPlaceholderOpacity(): string {
return (this.floatPlaceholder !== 'never' || this._selectionModel.isEmpty()) ? '1' : '0';
}
/** Returns the aria-label of the select component. */
get _ariaLabel(): string | null {
// If an ariaLabelledby value has been set, the select should not overwrite the
// `aria-labelledby` value by setting the ariaLabel to the placeholder.
return this.ariaLabelledby ? null : this.ariaLabel || this.placeholder;
}
/**
* Sets the x-offset of the overlay panel in relation to the trigger's top start corner.
* This must be adjusted to align the selected option text over the trigger text when
* the panel opens. Will change based on LTR or RTL text direction. Note that the offset
* can't be calculated until the panel has been attached, because we need to know the
* content width in order to constrain the panel within the viewport.
*/
private _calculateOverlayOffsetX(): void {
const overlayRect = this.overlayDir.overlayRef.overlayElement.getBoundingClientRect();
const viewportRect = this._viewportRuler.getViewportRect();
const isRtl = this._isRtl();
const paddingWidth = this.multiple ? SELECT_MULTIPLE_PANEL_PADDING_X + SELECT_PANEL_PADDING_X :
SELECT_PANEL_PADDING_X * 2;
let offsetX: number;
// Adjust the offset, depending on the option padding.
if (this.multiple) {
offsetX = SELECT_MULTIPLE_PANEL_PADDING_X;
} else {
let selected = this._selectionModel.selected[0] || this.options.first;
offsetX = selected && selected.group ? SELECT_PANEL_INDENT_PADDING_X : SELECT_PANEL_PADDING_X;
}
// Invert the offset in LTR.
if (!isRtl) {
offsetX *= -1;
}
// Determine how much the select overflows on each side.
const leftOverflow = 0 - (overlayRect.left + offsetX - (isRtl ? paddingWidth : 0));
const rightOverflow = overlayRect.right + offsetX - viewportRect.width
+ (isRtl ? 0 : paddingWidth);
// If the element overflows on either side, reduce the offset to allow it to fit.
if (leftOverflow > 0) {
offsetX += leftOverflow + SELECT_PANEL_VIEWPORT_PADDING;
} else if (rightOverflow > 0) {
offsetX -= rightOverflow + SELECT_PANEL_VIEWPORT_PADDING;
}
// Set the offset directly in order to avoid having to go through change detection and
// potentially triggering "changed after it was checked" errors.
this.overlayDir.offsetX = offsetX;
this.overlayDir.overlayRef.updatePosition();
}
/**
* Calculates the y-offset of the select's overlay panel in relation to the
* top start corner of the trigger. It has to be adjusted in order for the
* selected option to be aligned over the trigger when the panel opens.
*/
private _calculateOverlayOffsetY(selectedIndex: number, scrollBuffer: number,
maxScroll: number): number {
let optionOffsetFromPanelTop: number;
if (this._scrollTop === 0) {
optionOffsetFromPanelTop = selectedIndex * SELECT_ITEM_HEIGHT;
} else if (this._scrollTop === maxScroll) {
const firstDisplayedIndex = this._getItemCount() - SELECT_MAX_OPTIONS_DISPLAYED;
const selectedDisplayIndex = selectedIndex - firstDisplayedIndex;
// Because the panel height is longer than the height of the options alone,
// there is always extra padding at the top or bottom of the panel. When
// scrolled to the very bottom, this padding is at the top of the panel and
// must be added to the offset.
optionOffsetFromPanelTop =
selectedDisplayIndex * SELECT_ITEM_HEIGHT + SELECT_PANEL_PADDING_Y;
} else {
// If the option was scrolled to the middle of the panel using a scroll buffer,