/
slider.ts
1186 lines (1047 loc) · 42.9 KB
/
slider.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 LLC 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 {Directionality} from '@angular/cdk/bidi';
import {
BooleanInput,
coerceBooleanProperty,
coerceNumberProperty,
NumberInput
} from '@angular/cdk/coercion';
import {Platform} from '@angular/cdk/platform';
import {DOCUMENT} from '@angular/common';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
forwardRef,
Inject,
Input,
NgZone,
OnDestroy,
OnInit,
Optional,
Output,
QueryList,
ViewChild,
ViewChildren,
ViewEncapsulation,
} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {
CanColorCtor,
CanDisableRipple,
CanDisableRippleCtor,
MatRipple,
MAT_RIPPLE_GLOBAL_OPTIONS,
mixinColor,
mixinDisableRipple,
RippleAnimationConfig,
RippleGlobalOptions,
RippleRef,
RippleState,
} from '@angular/material/core';
import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations';
import {SpecificEventListener, EventType} from '@material/base/types';
import {MDCSliderAdapter, MDCSliderFoundation, Thumb, TickMark} from '@material/slider';
import {Subscription} from 'rxjs';
import {GlobalChangeAndInputListener} from './global-change-and-input-listener';
/** Represents a drag event emitted by the MatSlider component. */
export interface MatSliderDragEvent {
/** The MatSliderThumb that was interacted with. */
source: MatSliderThumb;
/** The MatSlider that was interacted with. */
parent: MatSlider;
/** The current value of the slider. */
value: number;
}
/**
* The visual slider thumb.
*
* Handles the slider thumb ripple states (hover, focus, and active),
* and displaying the value tooltip on discrete sliders.
* @docs-private
*/
@Component({
selector: 'mat-slider-visual-thumb',
templateUrl: './slider-thumb.html',
styleUrls: ['slider-thumb.css'],
host: {
'class': 'mdc-slider__thumb mat-mdc-slider-visual-thumb',
},
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class MatSliderVisualThumb implements AfterViewInit, OnDestroy {
/** Whether the slider displays a numeric value label upon pressing the thumb. */
@Input() discrete: boolean;
/** Indicates which slider thumb this input corresponds to. */
@Input() thumbPosition: Thumb;
/** The display value of the slider thumb. */
@Input() valueIndicatorText: string;
/** Whether ripples on the slider thumb should be disabled. */
@Input() disableRipple: boolean = false;
/** The MatRipple for this slider thumb. */
@ViewChild(MatRipple) private readonly _ripple: MatRipple;
/** The slider thumb knob */
@ViewChild('knob') _knob: ElementRef<HTMLElement>;
/** The slider input corresponding to this slider thumb. */
private _sliderInput: MatSliderThumb;
/** The RippleRef for the slider thumbs hover state. */
private _hoverRippleRef: RippleRef | undefined;
/** The RippleRef for the slider thumbs focus state. */
private _focusRippleRef: RippleRef | undefined;
/** The RippleRef for the slider thumbs active state. */
private _activeRippleRef: RippleRef | undefined;
/** Whether the slider thumb is currently being pressed. */
private _isActive: boolean = false;
/** Whether the slider thumb is currently being hovered. */
private _isHovered: boolean = false;
constructor(
private readonly _ngZone: NgZone,
@Inject(forwardRef(() => MatSlider)) private readonly _slider: MatSlider,
private readonly _elementRef: ElementRef<HTMLElement>) {}
ngAfterViewInit() {
this._ripple.radius = 24;
this._sliderInput = this._slider._getInput(this.thumbPosition);
this._sliderInput.dragStart.subscribe((e: MatSliderDragEvent) => this._onDragStart(e));
this._sliderInput.dragEnd.subscribe((e: MatSliderDragEvent) => this._onDragEnd(e));
this._sliderInput._focus.subscribe(() => this._onFocus());
this._sliderInput._blur.subscribe(() => this._onBlur());
// These two listeners don't update any data bindings so we bind them
// outside of the NgZone to pervent angular from needlessly running change detection.
this._ngZone.runOutsideAngular(() => {
this._elementRef.nativeElement.addEventListener('mouseenter', this._onMouseEnter.bind(this));
this._elementRef.nativeElement.addEventListener('mouseleave', this._onMouseLeave.bind(this));
});
}
ngOnDestroy() {
this._sliderInput.dragStart.unsubscribe();
this._sliderInput.dragEnd.unsubscribe();
this._sliderInput._focus.unsubscribe();
this._sliderInput._blur.unsubscribe();
this._elementRef.nativeElement.removeEventListener('mouseenter', this._onMouseEnter);
this._elementRef.nativeElement.removeEventListener('mouseleave', this._onMouseLeave);
}
private _onMouseEnter(): void {
this._isHovered = true;
// We don't want to show the hover ripple on top of the focus ripple.
// This can happen if the user tabs to a thumb and then the user moves their cursor over it.
if (!this._isShowingRipple(this._focusRippleRef)) {
this._showHoverRipple();
}
}
private _onMouseLeave(): void {
this._isHovered = false;
this._hoverRippleRef?.fadeOut();
}
private _onFocus(): void {
// We don't want to show the hover ripple on top of the focus ripple.
// Happen when the users cursor is over a thumb and then the user tabs to it.
this._hoverRippleRef?.fadeOut();
this._showFocusRipple();
}
private _onBlur(): void {
// Happens when the user tabs away while still dragging a thumb.
if (!this._isActive) {
this._focusRippleRef?.fadeOut();
}
// Happens when the user tabs away from a thumb but their cursor is still over it.
if (this._isHovered) {
this._showHoverRipple();
}
}
private _onDragStart(event: MatSliderDragEvent): void {
if (event.source._thumbPosition === this.thumbPosition) {
this._isActive = true;
this._showActiveRipple();
}
}
private _onDragEnd(event: MatSliderDragEvent): void {
if (event.source._thumbPosition === this.thumbPosition) {
this._isActive = false;
this._activeRippleRef?.fadeOut();
// Happens when the user starts dragging a thumb, tabs away, and then stops dragging.
if (!this._sliderInput._isFocused()) {
this._focusRippleRef?.fadeOut();
}
}
}
/** Handles displaying the hover ripple. */
private _showHoverRipple(): void {
if (!this._slider._noopAnimations && !this._isShowingRipple(this._hoverRippleRef)) {
this._hoverRippleRef = this._showRipple({ enterDuration: 0, exitDuration: 0 });
this._hoverRippleRef?.element.classList.add('mat-mdc-slider-hover-ripple');
}
}
/** Handles displaying the focus ripple. */
private _showFocusRipple(): void {
// Show the focus ripple event if noop animations are enabled.
if (!this._isShowingRipple(this._focusRippleRef)) {
this._focusRippleRef = this._showRipple({ enterDuration: 0, exitDuration: 0 });
this._focusRippleRef?.element.classList.add('mat-mdc-slider-focus-ripple');
}
}
/** Handles displaying the active ripple. */
private _showActiveRipple(): void {
if (!this._slider._noopAnimations && !this._isShowingRipple(this._activeRippleRef)) {
this._activeRippleRef = this._showRipple({ enterDuration: 225, exitDuration: 400 });
this._activeRippleRef?.element.classList.add('mat-mdc-slider-active-ripple');
}
}
/** Whether the given rippleRef is currently fading in or visible. */
private _isShowingRipple(rippleRef?: RippleRef): boolean {
return rippleRef?.state === RippleState.FADING_IN || rippleRef?.state === RippleState.VISIBLE;
}
/** Manually launches the slider thumb ripple using the specified ripple animation config. */
private _showRipple(animation: RippleAnimationConfig): RippleRef | undefined {
if (this.disableRipple) {
return;
}
return this._ripple.launch(
{animation, centered: true, persistent: true},
);
}
/** Gets the hosts native HTML element. */
_getHostElement(): HTMLElement {
return this._elementRef.nativeElement;
}
/** Gets the native HTML element of the slider thumb knob. */
_getKnob(): HTMLElement {
return this._knob.nativeElement;
}
}
/**
* Directive that adds slider-specific behaviors to an input element inside `<mat-slider>`.
* Up to two may be placed inside of a `<mat-slider>`.
*
* If one is used, the selector `matSliderThumb` must be used, and the outcome will be a normal
* slider. If two are used, the selectors `matSliderStartThumb` and `matSliderEndThumb` must be
* used, and the outcome will be a range slider with two slider thumbs.
*/
@Directive({
selector: 'input[matSliderThumb], input[matSliderStartThumb], input[matSliderEndThumb]',
exportAs: 'matSliderThumb',
host: {
'class': 'mdc-slider__input',
'type': 'range',
'(blur)': '_onBlur()',
'(focus)': '_focus.emit()',
},
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: MatSliderThumb,
multi: true
}],
})
export class MatSliderThumb implements AfterViewInit, ControlValueAccessor, OnInit {
// ** IMPORTANT NOTE **
//
// The way `value` is implemented for MatSliderThumb doesn't follow typical Angular conventions.
// Normally we would define a private variable `_value` as the source of truth for the value of
// the slider thumb input. The source of truth for the value of the slider inputs has already
// been decided for us by MDC to be the value attribute on the slider thumb inputs. This is
// because the MDC foundation and adapter expect that the value attribute is the source of truth
// for the slider inputs.
//
// Also, note that the value attribute is completely disconnected from the value property.
/** The current value of this slider input. */
@Input()
get value(): number {
return coerceNumberProperty(this._hostElement.getAttribute('value'));
}
set value(v: number) {
const value = coerceNumberProperty(v);
// If the foundation has already been initialized, we need to
// relay any value updates to it so that it can update the UI.
if (this._slider._initialized) {
this._slider._setValue(value, this._thumbPosition);
} else {
// Setup for the MDC foundation.
this._hostElement.setAttribute('value', `${value}`);
}
}
/**
* Emits when the raw value of the slider changes. This is here primarily
* to facilitate the two-way binding for the `value` input.
* @docs-private
*/
@Output() readonly valueChange: EventEmitter<number> = new EventEmitter<number>();
/** Event emitted when the slider thumb starts being dragged. */
@Output() readonly dragStart: EventEmitter<MatSliderDragEvent>
= new EventEmitter<MatSliderDragEvent>();
/** Event emitted when the slider thumb stops being dragged. */
@Output() readonly dragEnd: EventEmitter<MatSliderDragEvent>
= new EventEmitter<MatSliderDragEvent>();
/** Event emitted every time the MatSliderThumb is blurred. */
@Output() readonly _blur: EventEmitter<void> = new EventEmitter<void>();
/** Event emitted every time the MatSliderThumb is focused. */
@Output() readonly _focus: EventEmitter<void> = new EventEmitter<void>();
/** Event emitted on pointer up or after left or right arrow key presses. */
@Output() readonly change: EventEmitter<Event> = new EventEmitter<Event>();
/** Event emitted on each value change that happens to the slider. */
@Output() readonly input: EventEmitter<Event> = new EventEmitter<Event>();
/**
* Used to determine the disabled state of the MatSlider (ControlValueAccessor).
* For ranged sliders, the disabled state of the MatSlider depends on the combined state of the
* start and end inputs. See MatSlider._updateDisabled.
*/
_disabled: boolean = false;
/**
* A callback function that is called when the
* control's value changes in the UI (ControlValueAccessor).
*/
_onChange: (value: any) => void = () => {};
/**
* A callback function that is called by the forms API on
* initialization to update the form model on blur (ControlValueAccessor).
*/
private _onTouched: () => void = () => {};
/** Indicates which slider thumb this input corresponds to. */
_thumbPosition: Thumb = this._elementRef.nativeElement.hasAttribute('matSliderStartThumb')
? Thumb.START
: Thumb.END;
/** The injected document if available or fallback to the global document reference. */
private _document: Document;
/** The host native HTML input element. */
_hostElement: HTMLInputElement;
constructor(
@Inject(DOCUMENT) document: any,
@Inject(forwardRef(() => MatSlider)) private readonly _slider: MatSlider,
private readonly _elementRef: ElementRef<HTMLInputElement>) {
this._document = document;
this._hostElement = _elementRef.nativeElement;
}
ngOnInit() {
// By calling this in ngOnInit() we guarantee that the sibling sliders initial value by
// has already been set by the time we reach ngAfterViewInit().
this._initializeInputValueAttribute();
this._initializeAriaValueText();
}
ngAfterViewInit() {
this._initializeInputState();
this._initializeInputValueProperty();
// Setup for the MDC foundation.
if (this._slider.disabled) {
this._hostElement.disabled = true;
}
}
_onBlur(): void {
this._onTouched();
this._blur.emit();
}
_emitFakeEvent(type: 'change'|'input') {
const event = new Event(type) as any;
event._matIsHandled = true;
this._hostElement.dispatchEvent(event);
}
/**
* Sets the model value. Implemented as part of ControlValueAccessor.
* @param value
*/
writeValue(value: any): void {
this.value = value;
}
/**
* Registers a callback to be triggered when the value has changed.
* Implemented as part of ControlValueAccessor.
* @param fn Callback to be registered.
*/
registerOnChange(fn: any): void {
this._onChange = fn;
}
/**
* Registers a callback to be triggered when the component is touched.
* Implemented as part of ControlValueAccessor.
* @param fn Callback to be registered.
*/
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
/**
* Sets whether the component should be disabled.
* Implemented as part of ControlValueAccessor.
* @param isDisabled
*/
setDisabledState(isDisabled: boolean): void {
this._disabled = isDisabled;
this._slider._updateDisabled();
}
focus(): void {
this._hostElement.focus();
}
blur(): void {
this._hostElement.blur();
}
/** Returns true if this slider input currently has focus. */
_isFocused(): boolean {
return this._document.activeElement === this._hostElement;
}
/**
* Sets the min, max, and step properties on the slider thumb input.
*
* Must be called AFTER the sibling slider thumb input is guaranteed to have had its value
* attribute value set. For a range slider, the min and max of the slider thumb input depends on
* the value of its sibling slider thumb inputs value.
*
* Must be called BEFORE the value property is set. In the case where the min and max have not
* yet been set and we are setting the input value property to a value outside of the native
* inputs default min or max. The value property would not be set to our desired value, but
* instead be capped at either the default min or max.
*
*/
_initializeInputState(): void {
const min = this._hostElement.hasAttribute('matSliderEndThumb')
? this._slider._getInput(Thumb.START).value
: this._slider.min;
const max = this._hostElement.hasAttribute('matSliderStartThumb')
? this._slider._getInput(Thumb.END).value
: this._slider.max;
this._hostElement.min = `${min}`;
this._hostElement.max = `${max}`;
this._hostElement.step = `${this._slider.step}`;
}
/**
* Sets the value property on the slider thumb input.
*
* Must be called AFTER the min and max have been set. In the case where the min and max have not
* yet been set and we are setting the input value property to a value outside of the native
* inputs default min or max. The value property would not be set to our desired value, but
* instead be capped at either the default min or max.
*/
private _initializeInputValueProperty(): void {
this._hostElement.value = `${this.value}`;
}
/**
* Ensures the value attribute is initialized.
*
* Must be called BEFORE the min and max are set. For a range slider, the min and max of the
* slider thumb input depends on the value of its sibling slider thumb inputs value.
*/
private _initializeInputValueAttribute(): void {
// Only set the default value if an initial value has not already been provided.
if (!this._hostElement.hasAttribute('value')) {
this.value = this._hostElement.hasAttribute('matSliderEndThumb')
? this._slider.max
: this._slider.min;
}
}
/**
* Initializes the aria-valuetext attribute.
*
* Must be called AFTER the value attribute is set. This is because the slider's parent
* `displayWith` function is used to set the `aria-valuetext` attribute.
*/
private _initializeAriaValueText(): void {
this._hostElement.setAttribute('aria-valuetext', this._slider.displayWith(this.value));
}
static ngAcceptInputType_value: NumberInput;
}
// Boilerplate for applying mixins to MatSlider.
/** @docs-private */
class MatSliderBase {
constructor(public _elementRef: ElementRef<HTMLElement>) {}
}
const _MatSliderMixinBase:
CanColorCtor &
CanDisableRippleCtor &
typeof MatSliderBase =
mixinColor(mixinDisableRipple(MatSliderBase), 'primary');
/**
* Allows users to select from a range of values by moving the slider thumb. It is similar in
* behavior to the native `<input type="range">` element.
*/
@Component({
selector: 'mat-slider',
templateUrl: 'slider.html',
styleUrls: ['slider.css'],
host: {
'class': 'mat-mdc-slider mdc-slider',
'[class.mdc-slider--range]': '_isRange()',
'[class.mdc-slider--disabled]': 'disabled',
'[class.mdc-slider--discrete]': 'discrete',
'[class.mdc-slider--tick-marks]': 'showTickMarks',
'[class._mat-animation-noopable]': '_noopAnimations',
},
exportAs: 'matSlider',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
inputs: ['color', 'disableRipple'],
})
export class MatSlider extends _MatSliderMixinBase
implements AfterViewInit, CanDisableRipple, OnDestroy {
/** The slider thumb(s). */
@ViewChildren(MatSliderVisualThumb) _thumbs: QueryList<MatSliderVisualThumb>;
/** The active section of the slider track. */
@ViewChild('trackActive') _trackActive: ElementRef<HTMLElement>;
/** The sliders hidden range input(s). */
@ContentChildren(MatSliderThumb, {descendants: false})
_inputs: QueryList<MatSliderThumb>;
/** Whether the slider is disabled. */
@Input()
get disabled(): boolean { return this._disabled; }
set disabled(v: boolean) {
this._setDisabled(coerceBooleanProperty(v));
this._updateInputsDisabledState();
}
private _disabled: boolean = false;
/** Whether the slider displays a numeric value label upon pressing the thumb. */
@Input()
get discrete(): boolean { return this._discrete; }
set discrete(v: boolean) { this._discrete = coerceBooleanProperty(v); }
private _discrete: boolean = false;
/** Whether the slider displays tick marks along the slider track. */
@Input()
get showTickMarks(): boolean { return this._showTickMarks; }
set showTickMarks(v: boolean) { this._showTickMarks = coerceBooleanProperty(v); }
private _showTickMarks: boolean = false;
/** The minimum value that the slider can have. */
@Input()
get min(): number { return this._min; }
set min(v: number) {
this._min = coerceNumberProperty(v, this._min);
this._reinitialize();
}
private _min: number = 0;
/** The maximum value that the slider can have. */
@Input()
get max(): number { return this._max; }
set max(v: number) {
this._max = coerceNumberProperty(v, this._max);
this._reinitialize();
}
private _max: number = 100;
/** The values at which the thumb will snap. */
@Input()
get step(): number { return this._step; }
set step(v: number) {
this._step = coerceNumberProperty(v, this._step);
this._reinitialize();
}
private _step: number = 1;
/**
* Function that will be used to format the value before it is displayed
* in the thumb label. Can be used to format very large number in order
* for them to fit into the slider thumb.
*/
@Input() displayWith: ((value: number) => string) = (value: number) => `${value}`;
/** Instance of the MDC slider foundation for this slider. */
private _foundation = new MDCSliderFoundation(new SliderAdapter(this));
/** Whether the foundation has been initialized. */
_initialized: boolean = false;
/** The injected document if available or fallback to the global document reference. */
_document: Document;
/**
* The defaultView of the injected document if
* available or fallback to global window reference.
*/
_window: Window;
/** Used to keep track of & render the active & inactive tick marks on the slider track. */
_tickMarks: TickMark[];
/** The display value of the start thumb. */
_startValueIndicatorText: string;
/** The display value of the end thumb. */
_endValueIndicatorText: string;
/** Whether animations have been disabled. */
_noopAnimations: boolean;
/**
* Whether the browser supports pointer events.
*
* We exclude iOS to mirror the MDC Foundation. The MDC Foundation cannot use pointer events on
* iOS because of this open bug - https://bugs.webkit.org/show_bug.cgi?id=220196.
*/
private _SUPPORTS_POINTER_EVENTS = typeof PointerEvent !== 'undefined'
&& !!PointerEvent
&& !this._platform.IOS;
/** Subscription to changes to the directionality (LTR / RTL) context for the application. */
private _dirChangeSubscription: Subscription;
constructor(
readonly _ngZone: NgZone,
readonly _cdr: ChangeDetectorRef,
readonly _elementRef: ElementRef<HTMLElement>,
private readonly _platform: Platform,
readonly _globalChangeAndInputListener: GlobalChangeAndInputListener<'input'|'change'>,
@Inject(DOCUMENT) document: any,
@Optional() private _dir: Directionality,
@Optional() @Inject(MAT_RIPPLE_GLOBAL_OPTIONS)
readonly _globalRippleOptions?: RippleGlobalOptions,
@Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string) {
super(_elementRef);
this._document = document;
this._window = this._document.defaultView || window;
this._noopAnimations = animationMode === 'NoopAnimations';
this._dirChangeSubscription = this._dir.change.subscribe(() => this._onDirChange());
this._attachUISyncEventListener();
}
ngAfterViewInit() {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
_validateInputs(
this._isRange(),
this._getInputElement(Thumb.START),
this._getInputElement(Thumb.END),
);
}
if (this._platform.isBrowser) {
this._foundation.init();
this._foundation.layout();
this._initialized = true;
}
// The MDC foundation requires access to the view and content children of the MatSlider. In
// order to access the view and content children of MatSlider we need to wait until change
// detection runs and materializes them. That is why we call init() and layout() in
// ngAfterViewInit().
//
// The MDC foundation then uses the information it gathers from the DOM to compute an initial
// value for the tickMarks array. It then tries to update the component data, but because it is
// updating the component data AFTER change detection already ran, we will get a changed after
// checked error. Because of this, we need to force change detection to update the UI with the
// new state.
this._cdr.detectChanges();
}
ngOnDestroy() {
if (this._platform.isBrowser) {
this._foundation.destroy();
}
this._dirChangeSubscription.unsubscribe();
this._removeUISyncEventListener();
}
/** Returns true if the language direction for this slider element is right to left. */
_isRTL() {
return this._dir && this._dir.value === 'rtl';
}
/**
* Attaches an event listener that keeps sync the slider UI and the foundation in sync.
*
* Because the MDC Foundation stores the value of the bounding client rect when layout is called,
* we need to keep calling layout to avoid the position of the slider getting out of sync with
* what the foundation has stored. If we don't do this, the foundation will not be able to
* correctly calculate the slider value on click/slide.
*/
_attachUISyncEventListener(): void {
// Implementation detail: It may seem weird that we are using "mouseenter" instead of
// "mousedown" as the default for when a browser does not support pointer events. While we
// would prefer to use "mousedown" as the default, for some reason it does not work (the
// callback is never triggered).
if (this._SUPPORTS_POINTER_EVENTS) {
this._elementRef.nativeElement.addEventListener('pointerdown', this._layout);
} else {
this._elementRef.nativeElement.addEventListener('mouseenter', this._layout);
this._elementRef.nativeElement.addEventListener('touchstart', this._layout);
}
}
/** Removes the event listener that keeps sync the slider UI and the foundation in sync. */
_removeUISyncEventListener(): void {
if (this._SUPPORTS_POINTER_EVENTS) {
this._elementRef.nativeElement.removeEventListener('pointerdown', this._layout);
} else {
this._elementRef.nativeElement.removeEventListener('mouseenter', this._layout);
this._elementRef.nativeElement.removeEventListener('touchstart', this._layout);
}
}
/** Wrapper function for calling layout (needed for adding & removing an event listener). */
private _layout = () => this._foundation.layout();
/**
* Reinitializes the slider foundation and input state(s).
*
* The MDC Foundation does not support changing some slider attributes after it has been
* initialized (e.g. min, max, and step). To continue supporting this feature, we need to
* destroy the foundation and re-initialize everything whenever we make these changes.
*/
private _reinitialize(): void {
if (this._initialized) {
this._foundation.destroy();
if (this._isRange()) {
this._getInput(Thumb.START)._initializeInputState();
}
this._getInput(Thumb.END)._initializeInputState();
this._foundation.init();
this._foundation.layout();
}
}
/** Handles updating the slider foundation after a dir change. */
private _onDirChange(): void {
this._ngZone.runOutsideAngular(() => {
// We need to call layout() a few milliseconds after the dir change callback
// because we need to wait until the bounding client rect of the slider has updated.
setTimeout(() => this._foundation.layout(), 10);
});
}
/** Sets the value of a slider thumb. */
_setValue(value: number, thumbPosition: Thumb): void {
thumbPosition === Thumb.START
? this._foundation.setValueStart(value)
: this._foundation.setValue(value);
}
/** Sets the disabled state of the MatSlider. */
private _setDisabled(value: boolean) {
this._disabled = value;
// If we want to disable the slider after the foundation has been initialized,
// we need to inform the foundation by calling `setDisabled`. Also, we can't call
// this before initializing the foundation because it will throw errors.
if (this._initialized) {
this._foundation.setDisabled(value);
}
}
/** Sets the disabled state of the individual slider thumb(s) (ControlValueAccessor). */
private _updateInputsDisabledState() {
if (this._initialized) {
this._getInput(Thumb.END)._disabled = true;
if (this._isRange()) {
this._getInput(Thumb.START)._disabled = true;
}
}
}
/** Whether this is a ranged slider. */
_isRange(): boolean {
return this._inputs.length === 2;
}
/** Sets the disabled state based on the disabled state of the inputs (ControlValueAccessor). */
_updateDisabled(): void {
const disabled = this._inputs.some(input => input._disabled);
this._setDisabled(disabled);
}
/** Gets the slider thumb input of the given thumb position. */
_getInput(thumbPosition: Thumb): MatSliderThumb {
return thumbPosition === Thumb.END ? this._inputs.last : this._inputs.first;
}
/** Gets the slider thumb HTML input element of the given thumb position. */
_getInputElement(thumbPosition: Thumb): HTMLInputElement {
return this._getInput(thumbPosition)._hostElement;
}
_getThumb(thumbPosition: Thumb): MatSliderVisualThumb {
return thumbPosition === Thumb.END ? this._thumbs.last : this._thumbs.first;
}
/** Gets the slider thumb HTML element of the given thumb position. */
_getThumbElement(thumbPosition: Thumb): HTMLElement {
return this._getThumb(thumbPosition)._getHostElement();
}
/** Gets the slider knob HTML element of the given thumb position. */
_getKnobElement(thumbPosition: Thumb): HTMLElement {
return this._getThumb(thumbPosition)._getKnob();
}
/**
* Sets the value indicator text of the given thumb position using the given value.
*
* Uses the `displayWith` function if one has been provided. Otherwise, it just uses the
* numeric value as a string.
*/
_setValueIndicatorText(value: number, thumbPosition: Thumb) {
thumbPosition === Thumb.START
? this._startValueIndicatorText = this.displayWith(value)
: this._endValueIndicatorText = this.displayWith(value);
this._cdr.markForCheck();
}
/** Gets the value indicator text for the given thumb position. */
_getValueIndicatorText(thumbPosition: Thumb): string {
return thumbPosition === Thumb.START
? this._startValueIndicatorText
: this._endValueIndicatorText;
}
/** Determines the class name for a HTML element. */
_getTickMarkClass(tickMark: TickMark): string {
return tickMark === TickMark.ACTIVE
? 'mdc-slider__tick-mark--active'
: 'mdc-slider__tick-mark--inactive';
}
/** Whether the slider thumb ripples should be disabled. */
_isRippleDisabled(): boolean {
return this.disabled || this.disableRipple || !!this._globalRippleOptions?.disabled;
}
static ngAcceptInputType_disabled: BooleanInput;
static ngAcceptInputType_discrete: BooleanInput;
static ngAcceptInputType_showTickMarks: BooleanInput;
static ngAcceptInputType_min: NumberInput;
static ngAcceptInputType_max: NumberInput;
static ngAcceptInputType_step: NumberInput;
static ngAcceptInputType_disableRipple: BooleanInput;
}
/** The MDCSliderAdapter implementation. */
class SliderAdapter implements MDCSliderAdapter {
/** The global event listener subscription used to handle events on the slider inputs. */
private _globalEventSubscriptions = new Subscription();
/** The MDC Foundations handler function for start input change events. */
private _startInputChangeEventHandler: SpecificEventListener<EventType>;
/** The MDC Foundations handler function for end input change events. */
private _endInputChangeEventHandler: SpecificEventListener<EventType>;
constructor(private readonly _delegate: MatSlider) {
this._globalEventSubscriptions.add(this._subscribeToSliderInputEvents('change'));
this._globalEventSubscriptions.add(this._subscribeToSliderInputEvents('input'));
}
/**
* Handles "change" and "input" events on the slider inputs.
*
* Exposes a callback to allow the MDC Foundations "change" event handler to be called for "real"
* events.
*
* ** IMPORTANT NOTE **
*
* We block all "real" change and input events and emit fake events from #emitChangeEvent and
* #emitInputEvent, instead. We do this because interacting with the MDC slider won't trigger all
* of the correct change and input events, but it will call #emitChangeEvent and #emitInputEvent
* at the correct times. This allows users to listen for these events directly on the slider
* input as they would with a native range input.
*/
private _subscribeToSliderInputEvents(type: 'change'|'input') {
return this._delegate._globalChangeAndInputListener.listen(type, (event: Event) => {
const thumbPosition = this._getInputThumbPosition(event.target);
// Do nothing if the event isn't from a thumb input.
if (thumbPosition === null) { return; }
// Do nothing if the event is "fake".
if ((event as any)._matIsHandled) { return ; }
// Prevent "real" events from reaching end users.
event.stopImmediatePropagation();
// Relay "real" change events to the MDC Foundation.
if (type === 'change') {
this._callChangeEventHandler(event, thumbPosition);
}
});
}
/** Calls the MDC Foundations change event handler for the specified thumb position. */
private _callChangeEventHandler(event: Event, thumbPosition: Thumb) {
if (thumbPosition === Thumb.START) {
this._startInputChangeEventHandler(event);
} else {
this._endInputChangeEventHandler(event);
}
}
/** Save the event handler so it can be used in our global change event listener subscription. */
private _saveChangeEventHandler(thumbPosition: Thumb, handler: SpecificEventListener<EventType>) {
if (thumbPosition === Thumb.START) {
this._startInputChangeEventHandler = handler;
} else {
this._endInputChangeEventHandler = handler;
}
}
/**
* Returns the thumb position of the given event target.
* Returns null if the given event target does not correspond to a slider thumb input.
*/
private _getInputThumbPosition(target: EventTarget | null): Thumb | null {
if (target === this._delegate._getInputElement(Thumb.END)) {
return Thumb.END;
}
if (this._delegate._isRange() && target === this._delegate._getInputElement(Thumb.START)) {
return Thumb.START;
}
return null;
}
// We manually assign functions instead of using prototype methods because
// MDC clobbers the values otherwise.
// See https://github.com/material-components/material-components-web/pull/6256
hasClass = (className: string): boolean => {
return this._delegate._elementRef.nativeElement.classList.contains(className);
}
addClass = (className: string): void => {
this._delegate._elementRef.nativeElement.classList.add(className);
}
removeClass = (className: string): void => {
this._delegate._elementRef.nativeElement.classList.remove(className);
}
getAttribute = (attribute: string): string | null => {
return this._delegate._elementRef.nativeElement.getAttribute(attribute);
}
addThumbClass = (className: string, thumbPosition: Thumb): void => {
this._delegate._getThumbElement(thumbPosition).classList.add(className);
}
removeThumbClass = (className: string, thumbPosition: Thumb): void => {
this._delegate._getThumbElement(thumbPosition).classList.remove(className);
}
getInputValue = (thumbPosition: Thumb): string => {
return this._delegate._getInputElement(thumbPosition).value;
}
setInputValue = (value: string, thumbPosition: Thumb): void => {
this._delegate._getInputElement(thumbPosition).value = value;
}
getInputAttribute = (attribute: string, thumbPosition: Thumb): string | null => {
return this._delegate._getInputElement(thumbPosition).getAttribute(attribute);
}
setInputAttribute = (attribute: string, value: string, thumbPosition: Thumb): void => {
const input = this._delegate._getInputElement(thumbPosition);