source: trip-planner-front/node_modules/@angular/material/fesm2015/slider.js@ 6a3a178

Last change on this file since 6a3a178 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 44.8 KB
Line 
1import { DOCUMENT, CommonModule } from '@angular/common';
2import { forwardRef, EventEmitter, Component, ViewEncapsulation, ChangeDetectionStrategy, ElementRef, ChangeDetectorRef, Optional, Attribute, NgZone, Inject, Input, Output, ViewChild, NgModule } from '@angular/core';
3import { mixinTabIndex, mixinColor, mixinDisabled, MatCommonModule } from '@angular/material/core';
4import { FocusMonitor } from '@angular/cdk/a11y';
5import { Directionality } from '@angular/cdk/bidi';
6import { coerceBooleanProperty, coerceNumberProperty } from '@angular/cdk/coercion';
7import { hasModifierKey, DOWN_ARROW, RIGHT_ARROW, UP_ARROW, LEFT_ARROW, HOME, END, PAGE_DOWN, PAGE_UP } from '@angular/cdk/keycodes';
8import { NG_VALUE_ACCESSOR } from '@angular/forms';
9import { ANIMATION_MODULE_TYPE } from '@angular/platform-browser/animations';
10import { normalizePassiveListenerOptions } from '@angular/cdk/platform';
11import { Subscription } from 'rxjs';
12
13/**
14 * @license
15 * Copyright Google LLC All Rights Reserved.
16 *
17 * Use of this source code is governed by an MIT-style license that can be
18 * found in the LICENSE file at https://angular.io/license
19 */
20const activeEventOptions = normalizePassiveListenerOptions({ passive: false });
21/**
22 * Visually, a 30px separation between tick marks looks best. This is very subjective but it is
23 * the default separation we chose.
24 */
25const MIN_AUTO_TICK_SEPARATION = 30;
26/** The thumb gap size for a disabled slider. */
27const DISABLED_THUMB_GAP = 7;
28/** The thumb gap size for a non-active slider at its minimum value. */
29const MIN_VALUE_NONACTIVE_THUMB_GAP = 7;
30/** The thumb gap size for an active slider at its minimum value. */
31const MIN_VALUE_ACTIVE_THUMB_GAP = 10;
32/**
33 * Provider Expression that allows mat-slider to register as a ControlValueAccessor.
34 * This allows it to support [(ngModel)] and [formControl].
35 * @docs-private
36 */
37const MAT_SLIDER_VALUE_ACCESSOR = {
38 provide: NG_VALUE_ACCESSOR,
39 useExisting: forwardRef(() => MatSlider),
40 multi: true
41};
42/** A simple change event emitted by the MatSlider component. */
43class MatSliderChange {
44}
45// Boilerplate for applying mixins to MatSlider.
46/** @docs-private */
47const _MatSliderBase = mixinTabIndex(mixinColor(mixinDisabled(class {
48 constructor(_elementRef) {
49 this._elementRef = _elementRef;
50 }
51}), 'accent'));
52/**
53 * Allows users to select from a range of values by moving the slider thumb. It is similar in
54 * behavior to the native `<input type="range">` element.
55 */
56class MatSlider extends _MatSliderBase {
57 constructor(elementRef, _focusMonitor, _changeDetectorRef, _dir, tabIndex, _ngZone, _document, _animationMode) {
58 super(elementRef);
59 this._focusMonitor = _focusMonitor;
60 this._changeDetectorRef = _changeDetectorRef;
61 this._dir = _dir;
62 this._ngZone = _ngZone;
63 this._animationMode = _animationMode;
64 this._invert = false;
65 this._max = 100;
66 this._min = 0;
67 this._step = 1;
68 this._thumbLabel = false;
69 this._tickInterval = 0;
70 this._value = null;
71 this._vertical = false;
72 /** Event emitted when the slider value has changed. */
73 this.change = new EventEmitter();
74 /** Event emitted when the slider thumb moves. */
75 this.input = new EventEmitter();
76 /**
77 * Emits when the raw value of the slider changes. This is here primarily
78 * to facilitate the two-way binding for the `value` input.
79 * @docs-private
80 */
81 this.valueChange = new EventEmitter();
82 /** onTouch function registered via registerOnTouch (ControlValueAccessor). */
83 this.onTouched = () => { };
84 this._percent = 0;
85 /**
86 * Whether or not the thumb is sliding and what the user is using to slide it with.
87 * Used to determine if there should be a transition for the thumb and fill track.
88 */
89 this._isSliding = null;
90 /**
91 * Whether or not the slider is active (clicked or sliding).
92 * Used to shrink and grow the thumb as according to the Material Design spec.
93 */
94 this._isActive = false;
95 /** The size of a tick interval as a percentage of the size of the track. */
96 this._tickIntervalPercent = 0;
97 /** The dimensions of the slider. */
98 this._sliderDimensions = null;
99 this._controlValueAccessorChangeFn = () => { };
100 /** Subscription to the Directionality change EventEmitter. */
101 this._dirChangeSubscription = Subscription.EMPTY;
102 /** Called when the user has put their pointer down on the slider. */
103 this._pointerDown = (event) => {
104 // Don't do anything if the slider is disabled or the
105 // user is using anything other than the main mouse button.
106 if (this.disabled || this._isSliding || (!isTouchEvent(event) && event.button !== 0)) {
107 return;
108 }
109 this._ngZone.run(() => {
110 this._touchId = isTouchEvent(event) ?
111 getTouchIdForSlider(event, this._elementRef.nativeElement) : undefined;
112 const pointerPosition = getPointerPositionOnPage(event, this._touchId);
113 if (pointerPosition) {
114 const oldValue = this.value;
115 this._isSliding = 'pointer';
116 this._lastPointerEvent = event;
117 event.preventDefault();
118 this._focusHostElement();
119 this._onMouseenter(); // Simulate mouseenter in case this is a mobile device.
120 this._bindGlobalEvents(event);
121 this._focusHostElement();
122 this._updateValueFromPosition(pointerPosition);
123 this._valueOnSlideStart = oldValue;
124 // Emit a change and input event if the value changed.
125 if (oldValue != this.value) {
126 this._emitInputEvent();
127 }
128 }
129 });
130 };
131 /**
132 * Called when the user has moved their pointer after
133 * starting to drag. Bound on the document level.
134 */
135 this._pointerMove = (event) => {
136 if (this._isSliding === 'pointer') {
137 const pointerPosition = getPointerPositionOnPage(event, this._touchId);
138 if (pointerPosition) {
139 // Prevent the slide from selecting anything else.
140 event.preventDefault();
141 const oldValue = this.value;
142 this._lastPointerEvent = event;
143 this._updateValueFromPosition(pointerPosition);
144 // Native range elements always emit `input` events when the value changed while sliding.
145 if (oldValue != this.value) {
146 this._emitInputEvent();
147 }
148 }
149 }
150 };
151 /** Called when the user has lifted their pointer. Bound on the document level. */
152 this._pointerUp = (event) => {
153 if (this._isSliding === 'pointer') {
154 if (!isTouchEvent(event) || typeof this._touchId !== 'number' ||
155 // Note that we use `changedTouches`, rather than `touches` because it
156 // seems like in most cases `touches` is empty for `touchend` events.
157 findMatchingTouch(event.changedTouches, this._touchId)) {
158 event.preventDefault();
159 this._removeGlobalEvents();
160 this._isSliding = null;
161 this._touchId = undefined;
162 if (this._valueOnSlideStart != this.value && !this.disabled) {
163 this._emitChangeEvent();
164 }
165 this._valueOnSlideStart = this._lastPointerEvent = null;
166 }
167 }
168 };
169 /** Called when the window has lost focus. */
170 this._windowBlur = () => {
171 // If the window is blurred while dragging we need to stop dragging because the
172 // browser won't dispatch the `mouseup` and `touchend` events anymore.
173 if (this._lastPointerEvent) {
174 this._pointerUp(this._lastPointerEvent);
175 }
176 };
177 this._document = _document;
178 this.tabIndex = parseInt(tabIndex) || 0;
179 _ngZone.runOutsideAngular(() => {
180 const element = elementRef.nativeElement;
181 element.addEventListener('mousedown', this._pointerDown, activeEventOptions);
182 element.addEventListener('touchstart', this._pointerDown, activeEventOptions);
183 });
184 }
185 /** Whether the slider is inverted. */
186 get invert() { return this._invert; }
187 set invert(value) {
188 this._invert = coerceBooleanProperty(value);
189 }
190 /** The maximum value that the slider can have. */
191 get max() { return this._max; }
192 set max(v) {
193 this._max = coerceNumberProperty(v, this._max);
194 this._percent = this._calculatePercentage(this._value);
195 // Since this also modifies the percentage, we need to let the change detection know.
196 this._changeDetectorRef.markForCheck();
197 }
198 /** The minimum value that the slider can have. */
199 get min() { return this._min; }
200 set min(v) {
201 this._min = coerceNumberProperty(v, this._min);
202 this._percent = this._calculatePercentage(this._value);
203 // Since this also modifies the percentage, we need to let the change detection know.
204 this._changeDetectorRef.markForCheck();
205 }
206 /** The values at which the thumb will snap. */
207 get step() { return this._step; }
208 set step(v) {
209 this._step = coerceNumberProperty(v, this._step);
210 if (this._step % 1 !== 0) {
211 this._roundToDecimal = this._step.toString().split('.').pop().length;
212 }
213 // Since this could modify the label, we need to notify the change detection.
214 this._changeDetectorRef.markForCheck();
215 }
216 /** Whether or not to show the thumb label. */
217 get thumbLabel() { return this._thumbLabel; }
218 set thumbLabel(value) { this._thumbLabel = coerceBooleanProperty(value); }
219 /**
220 * How often to show ticks. Relative to the step so that a tick always appears on a step.
221 * Ex: Tick interval of 4 with a step of 3 will draw a tick every 4 steps (every 12 values).
222 */
223 get tickInterval() { return this._tickInterval; }
224 set tickInterval(value) {
225 if (value === 'auto') {
226 this._tickInterval = 'auto';
227 }
228 else if (typeof value === 'number' || typeof value === 'string') {
229 this._tickInterval = coerceNumberProperty(value, this._tickInterval);
230 }
231 else {
232 this._tickInterval = 0;
233 }
234 }
235 /** Value of the slider. */
236 get value() {
237 // If the value needs to be read and it is still uninitialized, initialize it to the min.
238 if (this._value === null) {
239 this.value = this._min;
240 }
241 return this._value;
242 }
243 set value(v) {
244 if (v !== this._value) {
245 let value = coerceNumberProperty(v, 0);
246 // While incrementing by a decimal we can end up with values like 33.300000000000004.
247 // Truncate it to ensure that it matches the label and to make it easier to work with.
248 if (this._roundToDecimal && value !== this.min && value !== this.max) {
249 value = parseFloat(value.toFixed(this._roundToDecimal));
250 }
251 this._value = value;
252 this._percent = this._calculatePercentage(this._value);
253 // Since this also modifies the percentage, we need to let the change detection know.
254 this._changeDetectorRef.markForCheck();
255 }
256 }
257 /** Whether the slider is vertical. */
258 get vertical() { return this._vertical; }
259 set vertical(value) {
260 this._vertical = coerceBooleanProperty(value);
261 }
262 /** The value to be used for display purposes. */
263 get displayValue() {
264 if (this.displayWith) {
265 // Value is never null but since setters and getters cannot have
266 // different types, the value getter is also typed to return null.
267 return this.displayWith(this.value);
268 }
269 // Note that this could be improved further by rounding something like 0.999 to 1 or
270 // 0.899 to 0.9, however it is very performance sensitive, because it gets called on
271 // every change detection cycle.
272 if (this._roundToDecimal && this.value && this.value % 1 !== 0) {
273 return this.value.toFixed(this._roundToDecimal);
274 }
275 return this.value || 0;
276 }
277 /** set focus to the host element */
278 focus(options) {
279 this._focusHostElement(options);
280 }
281 /** blur the host element */
282 blur() {
283 this._blurHostElement();
284 }
285 /** The percentage of the slider that coincides with the value. */
286 get percent() { return this._clamp(this._percent); }
287 /**
288 * Whether the axis of the slider is inverted.
289 * (i.e. whether moving the thumb in the positive x or y direction decreases the slider's value).
290 */
291 _shouldInvertAxis() {
292 // Standard non-inverted mode for a vertical slider should be dragging the thumb from bottom to
293 // top. However from a y-axis standpoint this is inverted.
294 return this.vertical ? !this.invert : this.invert;
295 }
296 /** Whether the slider is at its minimum value. */
297 _isMinValue() {
298 return this.percent === 0;
299 }
300 /**
301 * The amount of space to leave between the slider thumb and the track fill & track background
302 * elements.
303 */
304 _getThumbGap() {
305 if (this.disabled) {
306 return DISABLED_THUMB_GAP;
307 }
308 if (this._isMinValue() && !this.thumbLabel) {
309 return this._isActive ? MIN_VALUE_ACTIVE_THUMB_GAP : MIN_VALUE_NONACTIVE_THUMB_GAP;
310 }
311 return 0;
312 }
313 /** CSS styles for the track background element. */
314 _getTrackBackgroundStyles() {
315 const axis = this.vertical ? 'Y' : 'X';
316 const scale = this.vertical ? `1, ${1 - this.percent}, 1` : `${1 - this.percent}, 1, 1`;
317 const sign = this._shouldInvertMouseCoords() ? '-' : '';
318 return {
319 // scale3d avoids some rendering issues in Chrome. See #12071.
320 transform: `translate${axis}(${sign}${this._getThumbGap()}px) scale3d(${scale})`
321 };
322 }
323 /** CSS styles for the track fill element. */
324 _getTrackFillStyles() {
325 const percent = this.percent;
326 const axis = this.vertical ? 'Y' : 'X';
327 const scale = this.vertical ? `1, ${percent}, 1` : `${percent}, 1, 1`;
328 const sign = this._shouldInvertMouseCoords() ? '' : '-';
329 return {
330 // scale3d avoids some rendering issues in Chrome. See #12071.
331 transform: `translate${axis}(${sign}${this._getThumbGap()}px) scale3d(${scale})`,
332 // iOS Safari has a bug where it won't re-render elements which start of as `scale(0)` until
333 // something forces a style recalculation on it. Since we'll end up with `scale(0)` when
334 // the value of the slider is 0, we can easily get into this situation. We force a
335 // recalculation by changing the element's `display` when it goes from 0 to any other value.
336 display: percent === 0 ? 'none' : ''
337 };
338 }
339 /** CSS styles for the ticks container element. */
340 _getTicksContainerStyles() {
341 let axis = this.vertical ? 'Y' : 'X';
342 // For a horizontal slider in RTL languages we push the ticks container off the left edge
343 // instead of the right edge to avoid causing a horizontal scrollbar to appear.
344 let sign = !this.vertical && this._getDirection() == 'rtl' ? '' : '-';
345 let offset = this._tickIntervalPercent / 2 * 100;
346 return {
347 'transform': `translate${axis}(${sign}${offset}%)`
348 };
349 }
350 /** CSS styles for the ticks element. */
351 _getTicksStyles() {
352 let tickSize = this._tickIntervalPercent * 100;
353 let backgroundSize = this.vertical ? `2px ${tickSize}%` : `${tickSize}% 2px`;
354 let axis = this.vertical ? 'Y' : 'X';
355 // Depending on the direction we pushed the ticks container, push the ticks the opposite
356 // direction to re-center them but clip off the end edge. In RTL languages we need to flip the
357 // ticks 180 degrees so we're really cutting off the end edge abd not the start.
358 let sign = !this.vertical && this._getDirection() == 'rtl' ? '-' : '';
359 let rotate = !this.vertical && this._getDirection() == 'rtl' ? ' rotate(180deg)' : '';
360 let styles = {
361 'backgroundSize': backgroundSize,
362 // Without translateZ ticks sometimes jitter as the slider moves on Chrome & Firefox.
363 'transform': `translateZ(0) translate${axis}(${sign}${tickSize / 2}%)${rotate}`
364 };
365 if (this._isMinValue() && this._getThumbGap()) {
366 const shouldInvertAxis = this._shouldInvertAxis();
367 let side;
368 if (this.vertical) {
369 side = shouldInvertAxis ? 'Bottom' : 'Top';
370 }
371 else {
372 side = shouldInvertAxis ? 'Right' : 'Left';
373 }
374 styles[`padding${side}`] = `${this._getThumbGap()}px`;
375 }
376 return styles;
377 }
378 _getThumbContainerStyles() {
379 const shouldInvertAxis = this._shouldInvertAxis();
380 let axis = this.vertical ? 'Y' : 'X';
381 // For a horizontal slider in RTL languages we push the thumb container off the left edge
382 // instead of the right edge to avoid causing a horizontal scrollbar to appear.
383 let invertOffset = (this._getDirection() == 'rtl' && !this.vertical) ? !shouldInvertAxis : shouldInvertAxis;
384 let offset = (invertOffset ? this.percent : 1 - this.percent) * 100;
385 return {
386 'transform': `translate${axis}(-${offset}%)`
387 };
388 }
389 /**
390 * Whether mouse events should be converted to a slider position by calculating their distance
391 * from the right or bottom edge of the slider as opposed to the top or left.
392 */
393 _shouldInvertMouseCoords() {
394 const shouldInvertAxis = this._shouldInvertAxis();
395 return (this._getDirection() == 'rtl' && !this.vertical) ? !shouldInvertAxis : shouldInvertAxis;
396 }
397 /** The language direction for this slider element. */
398 _getDirection() {
399 return (this._dir && this._dir.value == 'rtl') ? 'rtl' : 'ltr';
400 }
401 ngAfterViewInit() {
402 this._focusMonitor
403 .monitor(this._elementRef, true)
404 .subscribe((origin) => {
405 this._isActive = !!origin && origin !== 'keyboard';
406 this._changeDetectorRef.detectChanges();
407 });
408 if (this._dir) {
409 this._dirChangeSubscription = this._dir.change.subscribe(() => {
410 this._changeDetectorRef.markForCheck();
411 });
412 }
413 }
414 ngOnDestroy() {
415 const element = this._elementRef.nativeElement;
416 element.removeEventListener('mousedown', this._pointerDown, activeEventOptions);
417 element.removeEventListener('touchstart', this._pointerDown, activeEventOptions);
418 this._lastPointerEvent = null;
419 this._removeGlobalEvents();
420 this._focusMonitor.stopMonitoring(this._elementRef);
421 this._dirChangeSubscription.unsubscribe();
422 }
423 _onMouseenter() {
424 if (this.disabled) {
425 return;
426 }
427 // We save the dimensions of the slider here so we can use them to update the spacing of the
428 // ticks and determine where on the slider click and slide events happen.
429 this._sliderDimensions = this._getSliderDimensions();
430 this._updateTickIntervalPercent();
431 }
432 _onFocus() {
433 // We save the dimensions of the slider here so we can use them to update the spacing of the
434 // ticks and determine where on the slider click and slide events happen.
435 this._sliderDimensions = this._getSliderDimensions();
436 this._updateTickIntervalPercent();
437 }
438 _onBlur() {
439 this.onTouched();
440 }
441 _onKeydown(event) {
442 if (this.disabled || hasModifierKey(event) ||
443 (this._isSliding && this._isSliding !== 'keyboard')) {
444 return;
445 }
446 const oldValue = this.value;
447 switch (event.keyCode) {
448 case PAGE_UP:
449 this._increment(10);
450 break;
451 case PAGE_DOWN:
452 this._increment(-10);
453 break;
454 case END:
455 this.value = this.max;
456 break;
457 case HOME:
458 this.value = this.min;
459 break;
460 case LEFT_ARROW:
461 // NOTE: For a sighted user it would make more sense that when they press an arrow key on an
462 // inverted slider the thumb moves in that direction. However for a blind user, nothing
463 // about the slider indicates that it is inverted. They will expect left to be decrement,
464 // regardless of how it appears on the screen. For speakers ofRTL languages, they probably
465 // expect left to mean increment. Therefore we flip the meaning of the side arrow keys for
466 // RTL. For inverted sliders we prefer a good a11y experience to having it "look right" for
467 // sighted users, therefore we do not swap the meaning.
468 this._increment(this._getDirection() == 'rtl' ? 1 : -1);
469 break;
470 case UP_ARROW:
471 this._increment(1);
472 break;
473 case RIGHT_ARROW:
474 // See comment on LEFT_ARROW about the conditions under which we flip the meaning.
475 this._increment(this._getDirection() == 'rtl' ? -1 : 1);
476 break;
477 case DOWN_ARROW:
478 this._increment(-1);
479 break;
480 default:
481 // Return if the key is not one that we explicitly handle to avoid calling preventDefault on
482 // it.
483 return;
484 }
485 if (oldValue != this.value) {
486 this._emitInputEvent();
487 this._emitChangeEvent();
488 }
489 this._isSliding = 'keyboard';
490 event.preventDefault();
491 }
492 _onKeyup() {
493 if (this._isSliding === 'keyboard') {
494 this._isSliding = null;
495 }
496 }
497 /** Use defaultView of injected document if available or fallback to global window reference */
498 _getWindow() {
499 return this._document.defaultView || window;
500 }
501 /**
502 * Binds our global move and end events. They're bound at the document level and only while
503 * dragging so that the user doesn't have to keep their pointer exactly over the slider
504 * as they're swiping across the screen.
505 */
506 _bindGlobalEvents(triggerEvent) {
507 // Note that we bind the events to the `document`, because it allows us to capture
508 // drag cancel events where the user's pointer is outside the browser window.
509 const document = this._document;
510 const isTouch = isTouchEvent(triggerEvent);
511 const moveEventName = isTouch ? 'touchmove' : 'mousemove';
512 const endEventName = isTouch ? 'touchend' : 'mouseup';
513 document.addEventListener(moveEventName, this._pointerMove, activeEventOptions);
514 document.addEventListener(endEventName, this._pointerUp, activeEventOptions);
515 if (isTouch) {
516 document.addEventListener('touchcancel', this._pointerUp, activeEventOptions);
517 }
518 const window = this._getWindow();
519 if (typeof window !== 'undefined' && window) {
520 window.addEventListener('blur', this._windowBlur);
521 }
522 }
523 /** Removes any global event listeners that we may have added. */
524 _removeGlobalEvents() {
525 const document = this._document;
526 document.removeEventListener('mousemove', this._pointerMove, activeEventOptions);
527 document.removeEventListener('mouseup', this._pointerUp, activeEventOptions);
528 document.removeEventListener('touchmove', this._pointerMove, activeEventOptions);
529 document.removeEventListener('touchend', this._pointerUp, activeEventOptions);
530 document.removeEventListener('touchcancel', this._pointerUp, activeEventOptions);
531 const window = this._getWindow();
532 if (typeof window !== 'undefined' && window) {
533 window.removeEventListener('blur', this._windowBlur);
534 }
535 }
536 /** Increments the slider by the given number of steps (negative number decrements). */
537 _increment(numSteps) {
538 this.value = this._clamp((this.value || 0) + this.step * numSteps, this.min, this.max);
539 }
540 /** Calculate the new value from the new physical location. The value will always be snapped. */
541 _updateValueFromPosition(pos) {
542 if (!this._sliderDimensions) {
543 return;
544 }
545 let offset = this.vertical ? this._sliderDimensions.top : this._sliderDimensions.left;
546 let size = this.vertical ? this._sliderDimensions.height : this._sliderDimensions.width;
547 let posComponent = this.vertical ? pos.y : pos.x;
548 // The exact value is calculated from the event and used to find the closest snap value.
549 let percent = this._clamp((posComponent - offset) / size);
550 if (this._shouldInvertMouseCoords()) {
551 percent = 1 - percent;
552 }
553 // Since the steps may not divide cleanly into the max value, if the user
554 // slid to 0 or 100 percent, we jump to the min/max value. This approach
555 // is slightly more intuitive than using `Math.ceil` below, because it
556 // follows the user's pointer closer.
557 if (percent === 0) {
558 this.value = this.min;
559 }
560 else if (percent === 1) {
561 this.value = this.max;
562 }
563 else {
564 const exactValue = this._calculateValue(percent);
565 // This calculation finds the closest step by finding the closest
566 // whole number divisible by the step relative to the min.
567 const closestValue = Math.round((exactValue - this.min) / this.step) * this.step + this.min;
568 // The value needs to snap to the min and max.
569 this.value = this._clamp(closestValue, this.min, this.max);
570 }
571 }
572 /** Emits a change event if the current value is different from the last emitted value. */
573 _emitChangeEvent() {
574 this._controlValueAccessorChangeFn(this.value);
575 this.valueChange.emit(this.value);
576 this.change.emit(this._createChangeEvent());
577 }
578 /** Emits an input event when the current value is different from the last emitted value. */
579 _emitInputEvent() {
580 this.input.emit(this._createChangeEvent());
581 }
582 /** Updates the amount of space between ticks as a percentage of the width of the slider. */
583 _updateTickIntervalPercent() {
584 if (!this.tickInterval || !this._sliderDimensions) {
585 return;
586 }
587 if (this.tickInterval == 'auto') {
588 let trackSize = this.vertical ? this._sliderDimensions.height : this._sliderDimensions.width;
589 let pixelsPerStep = trackSize * this.step / (this.max - this.min);
590 let stepsPerTick = Math.ceil(MIN_AUTO_TICK_SEPARATION / pixelsPerStep);
591 let pixelsPerTick = stepsPerTick * this.step;
592 this._tickIntervalPercent = pixelsPerTick / trackSize;
593 }
594 else {
595 this._tickIntervalPercent = this.tickInterval * this.step / (this.max - this.min);
596 }
597 }
598 /** Creates a slider change object from the specified value. */
599 _createChangeEvent(value = this.value) {
600 let event = new MatSliderChange();
601 event.source = this;
602 event.value = value;
603 return event;
604 }
605 /** Calculates the percentage of the slider that a value is. */
606 _calculatePercentage(value) {
607 return ((value || 0) - this.min) / (this.max - this.min);
608 }
609 /** Calculates the value a percentage of the slider corresponds to. */
610 _calculateValue(percentage) {
611 return this.min + percentage * (this.max - this.min);
612 }
613 /** Return a number between two numbers. */
614 _clamp(value, min = 0, max = 1) {
615 return Math.max(min, Math.min(value, max));
616 }
617 /**
618 * Get the bounding client rect of the slider track element.
619 * The track is used rather than the native element to ignore the extra space that the thumb can
620 * take up.
621 */
622 _getSliderDimensions() {
623 return this._sliderWrapper ? this._sliderWrapper.nativeElement.getBoundingClientRect() : null;
624 }
625 /**
626 * Focuses the native element.
627 * Currently only used to allow a blur event to fire but will be used with keyboard input later.
628 */
629 _focusHostElement(options) {
630 this._elementRef.nativeElement.focus(options);
631 }
632 /** Blurs the native element. */
633 _blurHostElement() {
634 this._elementRef.nativeElement.blur();
635 }
636 /**
637 * Sets the model value. Implemented as part of ControlValueAccessor.
638 * @param value
639 */
640 writeValue(value) {
641 this.value = value;
642 }
643 /**
644 * Registers a callback to be triggered when the value has changed.
645 * Implemented as part of ControlValueAccessor.
646 * @param fn Callback to be registered.
647 */
648 registerOnChange(fn) {
649 this._controlValueAccessorChangeFn = fn;
650 }
651 /**
652 * Registers a callback to be triggered when the component is touched.
653 * Implemented as part of ControlValueAccessor.
654 * @param fn Callback to be registered.
655 */
656 registerOnTouched(fn) {
657 this.onTouched = fn;
658 }
659 /**
660 * Sets whether the component should be disabled.
661 * Implemented as part of ControlValueAccessor.
662 * @param isDisabled
663 */
664 setDisabledState(isDisabled) {
665 this.disabled = isDisabled;
666 }
667}
668MatSlider.decorators = [
669 { type: Component, args: [{
670 selector: 'mat-slider',
671 exportAs: 'matSlider',
672 providers: [MAT_SLIDER_VALUE_ACCESSOR],
673 host: {
674 '(focus)': '_onFocus()',
675 '(blur)': '_onBlur()',
676 '(keydown)': '_onKeydown($event)',
677 '(keyup)': '_onKeyup()',
678 '(mouseenter)': '_onMouseenter()',
679 // On Safari starting to slide temporarily triggers text selection mode which
680 // show the wrong cursor. We prevent it by stopping the `selectstart` event.
681 '(selectstart)': '$event.preventDefault()',
682 'class': 'mat-slider mat-focus-indicator',
683 'role': 'slider',
684 '[tabIndex]': 'tabIndex',
685 '[attr.aria-disabled]': 'disabled',
686 '[attr.aria-valuemax]': 'max',
687 '[attr.aria-valuemin]': 'min',
688 '[attr.aria-valuenow]': 'value',
689 // NVDA and Jaws appear to announce the `aria-valuenow` by calculating its percentage based
690 // on its value between `aria-valuemin` and `aria-valuemax`. Due to how decimals are handled,
691 // it can cause the slider to read out a very long value like 0.20000068 if the current value
692 // is 0.2 with a min of 0 and max of 1. We work around the issue by setting `aria-valuetext`
693 // to the same value that we set on the slider's thumb which will be truncated.
694 '[attr.aria-valuetext]': 'valueText == null ? displayValue : valueText',
695 '[attr.aria-orientation]': 'vertical ? "vertical" : "horizontal"',
696 '[class.mat-slider-disabled]': 'disabled',
697 '[class.mat-slider-has-ticks]': 'tickInterval',
698 '[class.mat-slider-horizontal]': '!vertical',
699 '[class.mat-slider-axis-inverted]': '_shouldInvertAxis()',
700 // Class binding which is only used by the test harness as there is no other
701 // way for the harness to detect if mouse coordinates need to be inverted.
702 '[class.mat-slider-invert-mouse-coords]': '_shouldInvertMouseCoords()',
703 '[class.mat-slider-sliding]': '_isSliding',
704 '[class.mat-slider-thumb-label-showing]': 'thumbLabel',
705 '[class.mat-slider-vertical]': 'vertical',
706 '[class.mat-slider-min-value]': '_isMinValue()',
707 '[class.mat-slider-hide-last-tick]': 'disabled || _isMinValue() && _getThumbGap() && _shouldInvertAxis()',
708 '[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"',
709 },
710 template: "<div class=\"mat-slider-wrapper\" #sliderWrapper>\n <div class=\"mat-slider-track-wrapper\">\n <div class=\"mat-slider-track-background\" [ngStyle]=\"_getTrackBackgroundStyles()\"></div>\n <div class=\"mat-slider-track-fill\" [ngStyle]=\"_getTrackFillStyles()\"></div>\n </div>\n <div class=\"mat-slider-ticks-container\" [ngStyle]=\"_getTicksContainerStyles()\">\n <div class=\"mat-slider-ticks\" [ngStyle]=\"_getTicksStyles()\"></div>\n </div>\n <div class=\"mat-slider-thumb-container\" [ngStyle]=\"_getThumbContainerStyles()\">\n <div class=\"mat-slider-focus-ring\"></div>\n <div class=\"mat-slider-thumb\"></div>\n <div class=\"mat-slider-thumb-label\">\n <span class=\"mat-slider-thumb-label-text\">{{displayValue}}</span>\n </div>\n </div>\n</div>\n",
711 inputs: ['disabled', 'color', 'tabIndex'],
712 encapsulation: ViewEncapsulation.None,
713 changeDetection: ChangeDetectionStrategy.OnPush,
714 styles: [".mat-slider{display:inline-block;position:relative;box-sizing:border-box;padding:8px;outline:none;vertical-align:middle}.mat-slider:not(.mat-slider-disabled):active,.mat-slider.mat-slider-sliding:not(.mat-slider-disabled){cursor:-webkit-grabbing;cursor:grabbing}.mat-slider-wrapper{-webkit-print-color-adjust:exact;color-adjust:exact;position:absolute}.mat-slider-track-wrapper{position:absolute;top:0;left:0;overflow:hidden}.mat-slider-track-fill{position:absolute;transform-origin:0 0;transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1),background-color 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-slider-track-background{position:absolute;transform-origin:100% 100%;transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1),background-color 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-slider-ticks-container{position:absolute;left:0;top:0;overflow:hidden}.mat-slider-ticks{-webkit-background-clip:content-box;background-clip:content-box;background-repeat:repeat;box-sizing:border-box;opacity:0;transition:opacity 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-slider-thumb-container{position:absolute;z-index:1;transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-slider-focus-ring{position:absolute;width:30px;height:30px;border-radius:50%;transform:scale(0);opacity:0;transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1),background-color 400ms cubic-bezier(0.25, 0.8, 0.25, 1),opacity 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-slider.cdk-keyboard-focused .mat-slider-focus-ring,.mat-slider.cdk-program-focused .mat-slider-focus-ring{transform:scale(1);opacity:1}.mat-slider:not(.mat-slider-disabled):not(.mat-slider-sliding) .mat-slider-thumb-label,.mat-slider:not(.mat-slider-disabled):not(.mat-slider-sliding) .mat-slider-thumb{cursor:-webkit-grab;cursor:grab}.mat-slider-thumb{position:absolute;right:-10px;bottom:-10px;box-sizing:border-box;width:20px;height:20px;border:3px solid transparent;border-radius:50%;transform:scale(0.7);transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1),background-color 400ms cubic-bezier(0.25, 0.8, 0.25, 1),border-color 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-slider-thumb-label{display:none;align-items:center;justify-content:center;position:absolute;width:28px;height:28px;border-radius:50%;transition:transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1),border-radius 400ms cubic-bezier(0.25, 0.8, 0.25, 1),background-color 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}.cdk-high-contrast-active .mat-slider-thumb-label{outline:solid 1px}.mat-slider-thumb-label-text{z-index:1;opacity:0;transition:opacity 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-slider-sliding .mat-slider-track-fill,.mat-slider-sliding .mat-slider-track-background,.mat-slider-sliding .mat-slider-thumb-container{transition-duration:0ms}.mat-slider-has-ticks .mat-slider-wrapper::after{content:\"\";position:absolute;border-width:0;border-style:solid;opacity:0;transition:opacity 400ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-slider-has-ticks.cdk-focused:not(.mat-slider-hide-last-tick) .mat-slider-wrapper::after,.mat-slider-has-ticks:hover:not(.mat-slider-hide-last-tick) .mat-slider-wrapper::after{opacity:1}.mat-slider-has-ticks.cdk-focused:not(.mat-slider-disabled) .mat-slider-ticks,.mat-slider-has-ticks:hover:not(.mat-slider-disabled) .mat-slider-ticks{opacity:1}.mat-slider-thumb-label-showing .mat-slider-focus-ring{display:none}.mat-slider-thumb-label-showing .mat-slider-thumb-label{display:flex}.mat-slider-axis-inverted .mat-slider-track-fill{transform-origin:100% 100%}.mat-slider-axis-inverted .mat-slider-track-background{transform-origin:0 0}.mat-slider:not(.mat-slider-disabled).cdk-focused.mat-slider-thumb-label-showing .mat-slider-thumb{transform:scale(0)}.mat-slider:not(.mat-slider-disabled).cdk-focused .mat-slider-thumb-label{border-radius:50% 50% 0}.mat-slider:not(.mat-slider-disabled).cdk-focused .mat-slider-thumb-label-text{opacity:1}.mat-slider:not(.mat-slider-disabled).cdk-mouse-focused .mat-slider-thumb,.mat-slider:not(.mat-slider-disabled).cdk-touch-focused .mat-slider-thumb,.mat-slider:not(.mat-slider-disabled).cdk-program-focused .mat-slider-thumb{border-width:2px;transform:scale(1)}.mat-slider-disabled .mat-slider-focus-ring{transform:scale(0);opacity:0}.mat-slider-disabled .mat-slider-thumb{border-width:4px;transform:scale(0.5)}.mat-slider-disabled .mat-slider-thumb-label{display:none}.mat-slider-horizontal{height:48px;min-width:128px}.mat-slider-horizontal .mat-slider-wrapper{height:2px;top:23px;left:8px;right:8px}.mat-slider-horizontal .mat-slider-wrapper::after{height:2px;border-left-width:2px;right:0;top:0}.mat-slider-horizontal .mat-slider-track-wrapper{height:2px;width:100%}.mat-slider-horizontal .mat-slider-track-fill{height:2px;width:100%;transform:scaleX(0)}.mat-slider-horizontal .mat-slider-track-background{height:2px;width:100%;transform:scaleX(1)}.mat-slider-horizontal .mat-slider-ticks-container{height:2px;width:100%}.cdk-high-contrast-active .mat-slider-horizontal .mat-slider-ticks-container{height:0;outline:solid 2px;top:1px}.mat-slider-horizontal .mat-slider-ticks{height:2px;width:100%}.mat-slider-horizontal .mat-slider-thumb-container{width:100%;height:0;top:50%}.mat-slider-horizontal .mat-slider-focus-ring{top:-15px;right:-15px}.mat-slider-horizontal .mat-slider-thumb-label{right:-14px;top:-40px;transform:translateY(26px) scale(0.01) rotate(45deg)}.mat-slider-horizontal .mat-slider-thumb-label-text{transform:rotate(-45deg)}.mat-slider-horizontal.cdk-focused .mat-slider-thumb-label{transform:rotate(45deg)}.cdk-high-contrast-active .mat-slider-horizontal.cdk-focused .mat-slider-thumb-label,.cdk-high-contrast-active .mat-slider-horizontal.cdk-focused .mat-slider-thumb-label-text{transform:none}.mat-slider-vertical{width:48px;min-height:128px}.mat-slider-vertical .mat-slider-wrapper{width:2px;top:8px;bottom:8px;left:23px}.mat-slider-vertical .mat-slider-wrapper::after{width:2px;border-top-width:2px;bottom:0;left:0}.mat-slider-vertical .mat-slider-track-wrapper{height:100%;width:2px}.mat-slider-vertical .mat-slider-track-fill{height:100%;width:2px;transform:scaleY(0)}.mat-slider-vertical .mat-slider-track-background{height:100%;width:2px;transform:scaleY(1)}.mat-slider-vertical .mat-slider-ticks-container{width:2px;height:100%}.cdk-high-contrast-active .mat-slider-vertical .mat-slider-ticks-container{width:0;outline:solid 2px;left:1px}.mat-slider-vertical .mat-slider-focus-ring{bottom:-15px;left:-15px}.mat-slider-vertical .mat-slider-ticks{width:2px;height:100%}.mat-slider-vertical .mat-slider-thumb-container{height:100%;width:0;left:50%}.mat-slider-vertical .mat-slider-thumb{-webkit-backface-visibility:hidden;backface-visibility:hidden}.mat-slider-vertical .mat-slider-thumb-label{bottom:-14px;left:-40px;transform:translateX(26px) scale(0.01) rotate(-45deg)}.mat-slider-vertical .mat-slider-thumb-label-text{transform:rotate(45deg)}.mat-slider-vertical.cdk-focused .mat-slider-thumb-label{transform:rotate(-45deg)}[dir=rtl] .mat-slider-wrapper::after{left:0;right:auto}[dir=rtl] .mat-slider-horizontal .mat-slider-track-fill{transform-origin:100% 100%}[dir=rtl] .mat-slider-horizontal .mat-slider-track-background{transform-origin:0 0}[dir=rtl] .mat-slider-horizontal.mat-slider-axis-inverted .mat-slider-track-fill{transform-origin:0 0}[dir=rtl] .mat-slider-horizontal.mat-slider-axis-inverted .mat-slider-track-background{transform-origin:100% 100%}.mat-slider._mat-animation-noopable .mat-slider-track-fill,.mat-slider._mat-animation-noopable .mat-slider-track-background,.mat-slider._mat-animation-noopable .mat-slider-ticks,.mat-slider._mat-animation-noopable .mat-slider-thumb-container,.mat-slider._mat-animation-noopable .mat-slider-focus-ring,.mat-slider._mat-animation-noopable .mat-slider-thumb,.mat-slider._mat-animation-noopable .mat-slider-thumb-label,.mat-slider._mat-animation-noopable .mat-slider-thumb-label-text,.mat-slider._mat-animation-noopable .mat-slider-has-ticks .mat-slider-wrapper::after{transition:none}\n"]
715 },] }
716];
717MatSlider.ctorParameters = () => [
718 { type: ElementRef },
719 { type: FocusMonitor },
720 { type: ChangeDetectorRef },
721 { type: Directionality, decorators: [{ type: Optional }] },
722 { type: String, decorators: [{ type: Attribute, args: ['tabindex',] }] },
723 { type: NgZone },
724 { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
725 { type: String, decorators: [{ type: Optional }, { type: Inject, args: [ANIMATION_MODULE_TYPE,] }] }
726];
727MatSlider.propDecorators = {
728 invert: [{ type: Input }],
729 max: [{ type: Input }],
730 min: [{ type: Input }],
731 step: [{ type: Input }],
732 thumbLabel: [{ type: Input }],
733 tickInterval: [{ type: Input }],
734 value: [{ type: Input }],
735 displayWith: [{ type: Input }],
736 valueText: [{ type: Input }],
737 vertical: [{ type: Input }],
738 change: [{ type: Output }],
739 input: [{ type: Output }],
740 valueChange: [{ type: Output }],
741 _sliderWrapper: [{ type: ViewChild, args: ['sliderWrapper',] }]
742};
743/** Returns whether an event is a touch event. */
744function isTouchEvent(event) {
745 // This function is called for every pixel that the user has dragged so we need it to be
746 // as fast as possible. Since we only bind mouse events and touch events, we can assume
747 // that if the event's name starts with `t`, it's a touch event.
748 return event.type[0] === 't';
749}
750/** Gets the coordinates of a touch or mouse event relative to the viewport. */
751function getPointerPositionOnPage(event, id) {
752 let point;
753 if (isTouchEvent(event)) {
754 // The `identifier` could be undefined if the browser doesn't support `TouchEvent.identifier`.
755 // If that's the case, attribute the first touch to all active sliders. This should still cover
756 // the most common case while only breaking multi-touch.
757 if (typeof id === 'number') {
758 point = findMatchingTouch(event.touches, id) || findMatchingTouch(event.changedTouches, id);
759 }
760 else {
761 // `touches` will be empty for start/end events so we have to fall back to `changedTouches`.
762 point = event.touches[0] || event.changedTouches[0];
763 }
764 }
765 else {
766 point = event;
767 }
768 return point ? { x: point.clientX, y: point.clientY } : undefined;
769}
770/** Finds a `Touch` with a specific ID in a `TouchList`. */
771function findMatchingTouch(touches, id) {
772 for (let i = 0; i < touches.length; i++) {
773 if (touches[i].identifier === id) {
774 return touches[i];
775 }
776 }
777 return undefined;
778}
779/** Gets the unique ID of a touch that matches a specific slider. */
780function getTouchIdForSlider(event, sliderHost) {
781 for (let i = 0; i < event.touches.length; i++) {
782 const target = event.touches[i].target;
783 if (sliderHost === target || sliderHost.contains(target)) {
784 return event.touches[i].identifier;
785 }
786 }
787 return undefined;
788}
789
790/**
791 * @license
792 * Copyright Google LLC All Rights Reserved.
793 *
794 * Use of this source code is governed by an MIT-style license that can be
795 * found in the LICENSE file at https://angular.io/license
796 */
797class MatSliderModule {
798}
799MatSliderModule.decorators = [
800 { type: NgModule, args: [{
801 imports: [CommonModule, MatCommonModule],
802 exports: [MatSlider, MatCommonModule],
803 declarations: [MatSlider],
804 },] }
805];
806
807/**
808 * @license
809 * Copyright Google LLC All Rights Reserved.
810 *
811 * Use of this source code is governed by an MIT-style license that can be
812 * found in the LICENSE file at https://angular.io/license
813 */
814
815/**
816 * Generated bundle index. Do not edit.
817 */
818
819export { MAT_SLIDER_VALUE_ACCESSOR, MatSlider, MatSliderChange, MatSliderModule };
820//# sourceMappingURL=slider.js.map
Note: See TracBrowser for help on using the repository browser.