forked from angular/components
/
slider-input.ts
746 lines (652 loc) · 21.7 KB
/
slider-input.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
/**
* @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 {
BooleanInput,
coerceBooleanProperty,
coerceNumberProperty,
NumberInput,
} from '@angular/cdk/coercion';
import {
ChangeDetectorRef,
Directive,
ElementRef,
EventEmitter,
forwardRef,
Inject,
Input,
NgZone,
OnDestroy,
Output,
} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';
import {Subject} from 'rxjs';
import {
_MatThumb,
MatSliderDragEvent,
_MatSlider,
_MatSliderRangeThumb,
_MatSliderThumb,
MAT_SLIDER_RANGE_THUMB,
MAT_SLIDER_THUMB,
MAT_SLIDER,
} from './slider-interface';
/**
* Provider that allows the slider thumb to register as a ControlValueAccessor.
* @docs-private
*/
export const MAT_SLIDER_THUMB_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatSliderThumb),
multi: true,
};
/**
* Provider that allows the range slider thumb to register as a ControlValueAccessor.
* @docs-private
*/
export const MAT_SLIDER_RANGE_THUMB_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatSliderRangeThumb),
multi: true,
};
/**
* 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]',
exportAs: 'matSliderThumb',
host: {
'class': 'mdc-slider__input',
'type': 'range',
'[attr.aria-valuetext]': '_valuetext',
'(change)': '_onChange()',
'(input)': '_onInput()',
// TODO(wagnermaciel): Consider using a global event listener instead.
// Reason: I have found a semi-consistent way to mouse up without triggering this event.
'(blur)': '_onBlur()',
'(focus)': '_onFocus()',
},
providers: [
MAT_SLIDER_THUMB_VALUE_ACCESSOR,
{provide: MAT_SLIDER_THUMB, useExisting: MatSliderThumb},
],
})
export class MatSliderThumb implements _MatSliderThumb, OnDestroy, ControlValueAccessor {
@Input()
get value(): number {
return coerceNumberProperty(this._hostElement.value);
}
set value(v: NumberInput) {
const val = coerceNumberProperty(v).toString();
if (!this._hasSetInitialValue) {
this._initialValue = val;
return;
}
if (this._isActive) {
return;
}
this._hostElement.value = val;
this._updateThumbUIByValue();
this._slider._onValueChange(this);
this._cdr.detectChanges();
}
/** Event emitted when the `value` is changed. */
@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>();
/**
* The current translateX in px of the slider visual thumb.
* @docs-private
*/
get translateX(): number {
if (this._slider.min >= this._slider.max) {
this._translateX = 0;
return this._translateX;
}
if (this._translateX === undefined) {
this._translateX = this._calcTranslateXByValue();
}
return this._translateX;
}
set translateX(v: number) {
this._translateX = v;
}
private _translateX: number | undefined;
/**
* Indicates whether this thumb is the start or end thumb.
* @docs-private
*/
thumbPosition: _MatThumb = _MatThumb.END;
/** @docs-private */
get min(): number {
return coerceNumberProperty(this._hostElement.min);
}
set min(v: NumberInput) {
this._hostElement.min = coerceNumberProperty(v).toString();
this._cdr.detectChanges();
}
/** @docs-private */
get max(): number {
return coerceNumberProperty(this._hostElement.max);
}
set max(v: NumberInput) {
this._hostElement.max = coerceNumberProperty(v).toString();
this._cdr.detectChanges();
}
get step(): number {
return coerceNumberProperty(this._hostElement.step);
}
set step(v: NumberInput) {
this._hostElement.step = coerceNumberProperty(v).toString();
this._cdr.detectChanges();
}
/** @docs-private */
get disabled(): boolean {
return coerceBooleanProperty(this._hostElement.disabled);
}
set disabled(v: BooleanInput) {
this._hostElement.disabled = coerceBooleanProperty(v);
this._cdr.detectChanges();
if (this._slider.disabled !== this.disabled) {
this._slider.disabled = this.disabled;
}
}
/** The percentage of the slider that coincides with the value. */
get percentage(): number {
if (this._slider.min >= this._slider.max) {
return this._slider._isRtl ? 1 : 0;
}
return (this.value - this._slider.min) / (this._slider.max - this._slider.min);
}
/** @docs-private */
get fillPercentage(): number {
if (!this._slider._cachedWidth) {
return this._slider._isRtl ? 1 : 0;
}
if (this._translateX === 0) {
return 0;
}
return this.translateX / this._slider._cachedWidth;
}
/** The host native HTML input element. */
_hostElement: HTMLInputElement;
/** The aria-valuetext string representation of the input's value. */
_valuetext: string;
/** The radius of a native html slider's knob. */
_knobRadius: number = 8;
/** Whether user's cursor is currently in a mouse down state on the input. */
_isActive: boolean = false;
/** Whether the input is currently focused (either by tab or after clicking). */
_isFocused: boolean = false;
/** Used to relay updates to _isFocused to the slider visual thumbs. */
private _setIsFocused(v: boolean): void {
this._isFocused = v;
}
/**
* Whether the initial value has been set.
* This exists because the initial value cannot be immediately set because the min and max
* must first be relayed from the parent MatSlider component, which can only happen later
* in the component lifecycle.
*/
private _hasSetInitialValue: boolean = false;
/** The stored initial value. */
_initialValue: string | undefined;
/** Defined when a user is using a form control to manage slider value & validation. */
private _formControl: FormControl | undefined;
/** Emits when the component is destroyed. */
protected readonly _destroyed = new Subject<void>();
/**
* Indicates whether UI updates should be skipped.
*
* This flag is used to avoid flickering
* when correcting values on pointer up/down.
*/
_skipUIUpdate: boolean = false;
/** Callback called when the slider input value changes. */
private _onChangeFn: (value: any) => void = () => {};
/** Callback called when the slider input has been touched. */
private _onTouchedFn: () => void = () => {};
constructor(
readonly _ngZone: NgZone,
readonly _elementRef: ElementRef<HTMLInputElement>,
readonly _cdr: ChangeDetectorRef,
@Inject(MAT_SLIDER) protected _slider: _MatSlider,
) {
this._hostElement = _elementRef.nativeElement;
this._ngZone.runOutsideAngular(() => {
this._hostElement.addEventListener('pointerdown', this._onPointerDown.bind(this));
this._hostElement.addEventListener('pointermove', this._onPointerMove.bind(this));
this._hostElement.addEventListener('pointerup', this._onPointerUp.bind(this));
});
}
ngOnDestroy(): void {
this._hostElement.removeEventListener('pointerdown', this._onPointerDown);
this._hostElement.removeEventListener('pointermove', this._onPointerMove);
this._hostElement.removeEventListener('pointerup', this._onPointerUp);
this._destroyed.next();
this._destroyed.complete();
this.dragStart.complete();
this.dragEnd.complete();
}
/** @docs-private */
initProps(): void {
this._updateWidthInactive();
// If this or the parent slider is disabled, just make everything disabled.
if (this.disabled !== this._slider.disabled) {
// The MatSlider setter for disabled will relay this and disable both inputs.
this._slider.disabled = true;
}
this.step = this._slider.step;
this.min = this._slider.min;
this.max = this._slider.max;
this._initValue();
}
/** @docs-private */
initUI(): void {
this._updateThumbUIByValue();
}
_initValue(): void {
this._hasSetInitialValue = true;
if (this._initialValue === undefined) {
this.value = this._getDefaultValue();
} else {
this._hostElement.value = this._initialValue;
this._updateThumbUIByValue();
this._slider._onValueChange(this);
this._cdr.detectChanges();
}
}
_getDefaultValue(): number {
return this.min;
}
_onBlur(): void {
this._setIsFocused(false);
this._onTouchedFn();
}
_onFocus(): void {
this._setIsFocused(true);
}
_onChange(): void {
// only used to handle the edge case where user
// mousedown on the slider then uses arrow keys.
if (this._isActive) {
this._updateThumbUIByValue({withAnimation: true});
}
}
_onInput(): void {
this.valueChange.emit(this.value);
this._onChangeFn(this.value);
// handles arrowing and updating the value when
// a step is defined.
if (this._slider.step || !this._isActive) {
this._updateThumbUIByValue({withAnimation: true});
}
this._slider._onValueChange(this);
}
_onNgControlValueChange(): void {
// only used to handle when the value change
// originates outside of the slider.
if (!this._isActive || !this._isFocused) {
this._slider._onValueChange(this);
this._updateThumbUIByValue();
}
this._slider.disabled = this._formControl!.disabled;
}
_onPointerDown(event: PointerEvent): void {
if (this.disabled || event.button !== 0) {
return;
}
this._isActive = true;
this._setIsFocused(true);
this._updateWidthActive();
this._slider._updateDimensions();
// Does nothing if a step is defined because we
// want the value to snap to the values on input.
if (!this._slider.step) {
this._updateThumbUIByPointerEvent(event, {withAnimation: true});
}
if (!this.disabled) {
this._handleValueCorrection(event);
}
}
/**
* Corrects the value of the slider on pointer up/down.
*
* Called on pointer down and up because the value is set based
* on the inactive width instead of the active width.
*/
private _handleValueCorrection(event: PointerEvent): void {
// Don't update the UI with the current value! The value on pointerdown
// and pointerup is calculated in the split second before the input(s)
// resize. See _updateWidthInactive() and _updateWidthActive() for more
// details.
this._skipUIUpdate = true;
// Note that this function gets triggered before the actual value of the
// slider is updated. This means if we were to set the value here, it
// would immediately be overwritten. Using setTimeout ensures the setting
// of the value happens after the value has been updated by the
// pointerdown event.
setTimeout(() => {
this._skipUIUpdate = false;
this._fixValue(event);
}, 0);
}
/** Corrects the value of the slider based on the pointer event's position. */
_fixValue(event: PointerEvent): void {
const xPos = event.clientX - this._slider._cachedLeft;
const width = this._slider._cachedWidth;
const step = this._slider.step === 0 ? 1 : this._slider.step;
const numSteps = Math.floor((this._slider.max - this._slider.min) / step);
const percentage = this._slider._isRtl ? 1 - xPos / width : xPos / width;
// To ensure the percentage is rounded to the necessary number of decimals.
const fixedPercentage = Math.round(percentage * numSteps) / numSteps;
const impreciseValue =
fixedPercentage * (this._slider.max - this._slider.min) + this._slider.min;
const value = Math.round(impreciseValue / step) * step;
const prevValue = this.value;
const dragEvent = {source: this, parent: this._slider, value: value};
this._isActive ? this.dragStart.emit(dragEvent) : this.dragEnd.emit(dragEvent);
if (value === prevValue) {
// Because we prevented UI updates, if it turns out that the race
// condition didn't happen and the value is already correct, we
// have to apply the ui updates now.
this._slider._onValueChange(this);
this._slider.step > 0
? this._updateThumbUIByValue()
: this._updateThumbUIByPointerEvent(event, {withAnimation: this._slider._hasAnimation});
return;
}
this.value = value;
this.valueChange.emit(this.value);
this._onChangeFn(this.value);
this._slider._onValueChange(this);
this._slider.step > 0
? this._updateThumbUIByValue()
: this._updateThumbUIByPointerEvent(event, {withAnimation: this._slider._hasAnimation});
}
_onPointerMove(event: PointerEvent): void {
// Again, does nothing if a step is defined because
// we want the value to snap to the values on input.
if (!this._slider.step && this._isActive) {
this._updateThumbUIByPointerEvent(event);
}
}
_onPointerUp(): void {
this._isActive = false;
setTimeout(() => {
this._updateWidthInactive();
});
}
_clamp(v: number): number {
return Math.max(Math.min(v, this._slider._cachedWidth), 0);
}
_calcTranslateXByValue(): number {
if (this._slider._isRtl) {
return (1 - this.percentage) * this._slider._cachedWidth;
}
return this.percentage * this._slider._cachedWidth;
}
_calcTranslateXByPointerEvent(event: PointerEvent): number {
return event.clientX - this._slider._cachedLeft;
}
/**
* Used to set the slider width to the correct
* dimensions while the user is dragging.
*/
_updateWidthActive(): void {
this._hostElement.style.padding = `0 ${this._slider._inputPadding}px`;
this._hostElement.style.width = `calc(100% + ${this._slider._inputPadding}px)`;
}
/**
* Sets the slider input to disproportionate dimensions to allow for touch
* events to be captured on touch devices.
*/
_updateWidthInactive(): void {
this._hostElement.style.padding = '0px';
this._hostElement.style.width = 'calc(100% + 48px)';
this._hostElement.style.left = '-24px';
}
_updateThumbUIByValue(options?: {withAnimation: boolean}): void {
this.translateX = this._clamp(this._calcTranslateXByValue());
this._updateThumbUI(options);
}
_updateThumbUIByPointerEvent(event: PointerEvent, options?: {withAnimation: boolean}): void {
this.translateX = this._clamp(this._calcTranslateXByPointerEvent(event));
this._updateThumbUI(options);
}
_updateThumbUI(options?: {withAnimation: boolean}) {
this._slider._setTransition(!!options?.withAnimation);
this._slider._onTranslateXChange(this);
}
/**
* Sets the input's value.
* @param value The new value of the input
* @docs-private
*/
writeValue(value: any): void {
this.value = value;
}
/**
* Registers a callback to be invoked when the input's value changes from user input.
* @param fn The callback to register
* @docs-private
*/
registerOnChange(fn: any): void {
this._onChangeFn = fn;
}
/**
* Registers a callback to be invoked when the input is blurred by the user.
* @param fn The callback to register
* @docs-private
*/
registerOnTouched(fn: any): void {
this._onTouchedFn = fn;
}
/**
* Sets the disabled state of the slider.
* @param isDisabled The new disabled state
* @docs-private
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
focus(): void {
this._hostElement.focus();
}
blur(): void {
this._hostElement.blur();
}
}
@Directive({
selector: 'input[matSliderStartThumb], input[matSliderEndThumb]',
exportAs: 'matSliderRangeThumb',
providers: [
MAT_SLIDER_RANGE_THUMB_VALUE_ACCESSOR,
{provide: MAT_SLIDER_RANGE_THUMB, useExisting: MatSliderRangeThumb},
],
})
export class MatSliderRangeThumb extends MatSliderThumb implements _MatSliderRangeThumb {
/** @docs-private */
getSibling(): _MatSliderRangeThumb | undefined {
if (!this._sibling) {
this._sibling = this._slider._getInput(this._isEndThumb ? _MatThumb.START : _MatThumb.END) as
| MatSliderRangeThumb
| undefined;
}
return this._sibling;
}
private _sibling: MatSliderRangeThumb | undefined;
/**
* Returns the minimum translateX position allowed for this slider input's visual thumb.
* @docs-private
*/
getMinPos(): number {
const sibling = this.getSibling();
if (!this._isLeftThumb && sibling) {
return sibling.translateX;
}
return 0;
}
/**
* Returns the maximum translateX position allowed for this slider input's visual thumb.
* @docs-private
*/
getMaxPos(): number {
const sibling = this.getSibling();
if (this._isLeftThumb && sibling) {
return sibling.translateX;
}
return this._slider._cachedWidth;
}
_setIsLeftThumb(): void {
this._isLeftThumb =
(this._isEndThumb && this._slider._isRtl) || (!this._isEndThumb && !this._slider._isRtl);
}
/** Whether this slider corresponds to the input on the left hand side. */
_isLeftThumb: boolean;
/** Whether this slider corresponds to the input with greater value. */
_isEndThumb: boolean;
constructor(
_ngZone: NgZone,
@Inject(MAT_SLIDER) _slider: _MatSlider,
_elementRef: ElementRef<HTMLInputElement>,
override readonly _cdr: ChangeDetectorRef,
) {
super(_ngZone, _elementRef, _cdr, _slider);
this._isEndThumb = this._hostElement.hasAttribute('matSliderEndThumb');
this._setIsLeftThumb();
this.thumbPosition = this._isEndThumb ? _MatThumb.END : _MatThumb.START;
}
override _getDefaultValue(): number {
return this._isEndThumb && this._slider._isRange ? this.max : this.min;
}
override _onInput(): void {
super._onInput();
this._updateSibling();
if (!this._isActive) {
this._updateWidthInactive();
}
}
override _onNgControlValueChange(): void {
super._onNgControlValueChange();
this.getSibling()?._updateMinMax();
}
override _onPointerDown(event: PointerEvent): void {
if (this.disabled) {
return;
}
if (this._sibling) {
this._sibling._updateWidthActive();
this._sibling._hostElement.classList.add('mat-mdc-slider-input-no-pointer-events');
}
super._onPointerDown(event);
}
override _onPointerUp(): void {
super._onPointerUp();
if (this._sibling) {
setTimeout(() => {
this._sibling!._updateWidthInactive();
this._sibling!._hostElement.classList.remove('mat-mdc-slider-input-no-pointer-events');
});
}
}
override _onPointerMove(event: PointerEvent): void {
super._onPointerMove(event);
if (!this._slider.step && this._isActive) {
this._updateSibling();
}
}
override _fixValue(event: PointerEvent): void {
super._fixValue(event);
this._sibling?._updateMinMax();
}
override _clamp(v: number): number {
return Math.max(Math.min(v, this.getMaxPos()), this.getMinPos());
}
_updateMinMax(): void {
const sibling = this.getSibling();
if (!sibling) {
return;
}
if (this._isEndThumb) {
this.min = Math.max(this._slider.min, sibling.value);
this.max = this._slider.max;
} else {
this.min = this._slider.min;
this.max = Math.min(this._slider.max, sibling.value);
}
}
override _updateWidthActive(): void {
const minWidth = this._slider._rippleRadius * 2 - this._slider._inputPadding * 2;
const maxWidth = this._slider._cachedWidth + this._slider._inputPadding - minWidth;
const percentage =
this._slider.min < this._slider.max
? (this.max - this.min) / (this._slider.max - this._slider.min)
: 1;
const width = maxWidth * percentage + minWidth;
this._hostElement.style.width = `${width}px`;
this._hostElement.style.padding = `0 ${this._slider._inputPadding}px`;
}
override _updateWidthInactive(): void {
const sibling = this.getSibling();
if (!sibling) {
return;
}
const maxWidth = this._slider._cachedWidth;
const midValue = this._isEndThumb
? this.value - (this.value - sibling.value) / 2
: this.value + (sibling.value - this.value) / 2;
const _percentage = this._isEndThumb
? (this.max - midValue) / (this._slider.max - this._slider.min)
: (midValue - this.min) / (this._slider.max - this._slider.min);
const percentage = this._slider.min < this._slider.max ? _percentage : 1;
const width = maxWidth * percentage + 24;
this._hostElement.style.width = `${width}px`;
this._hostElement.style.padding = '0px';
if (this._isLeftThumb) {
this._hostElement.style.left = '-24px';
this._hostElement.style.right = 'auto';
} else {
this._hostElement.style.left = 'auto';
this._hostElement.style.right = '-24px';
}
}
_updateStaticStyles(): void {
this._hostElement.classList.toggle('mat-slider__right-input', !this._isLeftThumb);
}
private _updateSibling(): void {
const sibling = this.getSibling();
if (!sibling) {
return;
}
sibling._updateMinMax();
if (this._isActive) {
sibling._updateWidthActive();
} else {
sibling._updateWidthInactive();
}
}
/**
* Sets the input's value.
* @param value The new value of the input
* @docs-private
*/
override writeValue(value: any): void {
this.value = value;
this._updateWidthInactive();
this._updateSibling();
}
}