UNPKG

@rp3e11/ngx-slider

Version:

Self-contained, mobile friendly slider component for Angular 13 based on angularjs-slider

1,082 lines (1,069 loc) 150 kB
import * as i0 from '@angular/core'; import { Directive, HostBinding, Component, Input, forwardRef, EventEmitter, ChangeDetectionStrategy, Output, ViewChild, ContentChild, HostListener, NgModule } from '@angular/core'; import * as i3 from '@angular/common'; import { CommonModule } from '@angular/common'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import { Subject } from 'rxjs'; import { throttleTime, tap, distinctUntilChanged, filter } from 'rxjs/operators'; import detectPassiveEvents from 'detect-passive-events'; /** Label type */ var LabelType; (function (LabelType) { /** Label above low pointer */ LabelType[LabelType["Low"] = 0] = "Low"; /** Label above high pointer */ LabelType[LabelType["High"] = 1] = "High"; /** Label for minimum slider value */ LabelType[LabelType["Floor"] = 2] = "Floor"; /** Label for maximum slider value */ LabelType[LabelType["Ceil"] = 3] = "Ceil"; /** Label below legend tick */ LabelType[LabelType["TickValue"] = 4] = "TickValue"; })(LabelType || (LabelType = {})); /** Slider options */ class Options { constructor() { /** Minimum value for a slider. Not applicable when using stepsArray. */ this.floor = 0; /** Maximum value for a slider. Not applicable when using stepsArray. */ this.ceil = null; /** Step between each value. Not applicable when using stepsArray. */ this.step = null; /** The minimum range authorized on the slider. Applies to range slider only. When using stepsArray, expressed as index into stepsArray. */ this.minRange = null; /** The maximum range authorized on the slider. Applies to range slider only. When using stepsArray, expressed as index into stepsArray. */ this.maxRange = null; /** Set to true to have a push behavior. When the min handle goes above the max, the max is moved as well (and vice-versa). The range between min and max is defined by the step option (defaults to 1) and can also be overriden by the minRange option. Applies to range slider only. */ this.pushRange = false; /** The minimum value authorized on the slider. When using stepsArray, expressed as index into stepsArray. */ this.minLimit = null; /** The maximum value authorized on the slider. When using stepsArray, expressed as index into stepsArray. */ this.maxLimit = null; /** Custom translate function. Use this if you want to translate values displayed on the slider. */ this.translate = null; /** Custom function for combining overlapping labels in range slider. It takes the min and max values (already translated with translate fuction) and should return how these two values should be combined. If not provided, the default function will join the two values with ' - ' as separator. */ this.combineLabels = null; /** Use to display legend under ticks (thus, it needs to be used along with showTicks or showTicksValues). The function will be called with each tick value and returned content will be displayed under the tick as a legend. If the returned value is null, then no legend is displayed under the corresponding tick.You can also directly provide the legend values in the stepsArray option. */ this.getLegend = null; /** If you want to display a slider with non linear/number steps. Just pass an array with each slider value and that's it; the floor, ceil and step settings of the slider will be computed automatically. By default, the value model and valueHigh model values will be the value of the selected item in the stepsArray. They can also be bound to the index of the selected item by setting the bindIndexForStepsArray option to true. */ this.stepsArray = null; /** Set to true to bind the index of the selected item to value model and valueHigh model. */ this.bindIndexForStepsArray = false; /** When set to true and using a range slider, the range can be dragged by the selection bar. Applies to range slider only. */ this.draggableRange = false; /** Same as draggableRange but the slider range can't be changed. Applies to range slider only. */ this.draggableRangeOnly = false; /** Set to true to always show the selection bar before the slider handle. */ this.showSelectionBar = false; /** Set to true to always show the selection bar after the slider handle. */ this.showSelectionBarEnd = false; /** Set a number to draw the selection bar between this value and the slider handle. When using stepsArray, expressed as index into stepsArray. */ this.showSelectionBarFromValue = null; /** Only for range slider. Set to true to visualize in different colour the areas on the left/right (top/bottom for vertical range slider) of selection bar between the handles. */ this.showOuterSelectionBars = false; /** Set to true to hide pointer labels */ this.hidePointerLabels = false; /** Set to true to hide min / max labels */ this.hideLimitLabels = false; /** Set to false to disable the auto-hiding behavior of the limit labels. */ this.autoHideLimitLabels = true; /** Set to true to make the slider read-only. */ this.readOnly = false; /** Set to true to disable the slider. */ this.disabled = false; /** Throttle interval for mouse events in milliseconds. * This is provided to avoid a flood of events when moving the slider with mouse. */ this.mouseEventsInterval = 50; /** Throttle interval for touch events in milliseconds. * This is provided to avoid a flood of events when moving the slider with touch gesture. */ this.touchEventsInterval = 50; /** Throttle interval for input changes (changes to bindings or reactive form inputs) * This is provided to avoid a flood of events on frequent input binding changes affecting performance. */ this.inputEventsInterval = 100; /** Throttle interval for output changes (signalling changes to output bindings and user callbacks) * This is provided to avoid a flood of outgoing events affecting Angular app performance. */ this.outputEventsInterval = 100; /** Set to true to display a tick for each step of the slider. */ this.showTicks = false; /** Set to true to display a tick and the step value for each step of the slider.. */ this.showTicksValues = false; /* The step between each tick to display. If not set, the step value is used. Not used when ticksArray is specified. */ this.tickStep = null; /* The step between displaying each tick step value. If not set, then tickStep or step is used, depending on which one is set. */ this.tickValueStep = null; /** Use to display ticks at specific positions. The array contains the index of the ticks that should be displayed. For example, [0, 1, 5] will display a tick for the first, second and sixth values. */ this.ticksArray = null; /** Used to display a tooltip when a tick is hovered. Set to a function that returns the tooltip content for a given value. */ this.ticksTooltip = null; /** Same as ticksTooltip but for ticks values. */ this.ticksValuesTooltip = null; /** Set to true to display the slider vertically. The slider will take the full height of its parent. Changing this value at runtime is not currently supported. */ this.vertical = false; /** Function that returns the current color of the selection bar. If your color won't change, don't use this option but set it through CSS. If the returned color depends on a model value (either value or valueHigh), you should use the argument passed to the function. Indeed, when the function is called, there is no certainty that the model has already been updated.*/ this.getSelectionBarColor = null; /** Function that returns the color of a tick. showTicks must be enabled. */ this.getTickColor = null; /** Function that returns the current color of a pointer. If your color won't change, don't use this option but set it through CSS. If the returned color depends on a model value (either value or valueHigh), you should use the argument passed to the function. Indeed, when the function is called, there is no certainty that the model has already been updated. To handle range slider pointers independently, you should evaluate pointerType within the given function where "min" stands for value model and "max" for valueHigh model values. */ this.getPointerColor = null; /** Handles are focusable (on click or with tab) and can be modified using the following keyboard controls: Left/bottom arrows: -1 Right/top arrows: +1 Page-down: -10% Page-up: +10% Home: minimum value End: maximum value */ this.keyboardSupport = true; /** If you display the slider in an element that uses transform: scale(0.5), set the scale value to 2 so that the slider is rendered properly and the events are handled correctly. */ this.scale = 1; /** Set to true to force the value(s) to be rounded to the step, even when modified from the outside. When set to false, if the model values are modified from outside the slider, they are not rounded and can be between two steps. */ this.enforceStep = true; /** Set to true to force the value(s) to be normalised to allowed range (floor to ceil), even when modified from the outside. When set to false, if the model values are modified from outside the slider, and they are outside allowed range, the slider may be rendered incorrectly. However, setting this to false may be useful if you want to perform custom normalisation. */ this.enforceRange = true; /** Set to true to force the value(s) to be rounded to the nearest step value, even when modified from the outside. When set to false, if the model values are modified from outside the slider, and they are outside allowed range, the slider may be rendered incorrectly. However, setting this to false may be useful if you want to perform custom normalisation. */ this.enforceStepsArray = true; /** Set to true to prevent to user from switching the min and max handles. Applies to range slider only. */ this.noSwitching = false; /** Set to true to only bind events on slider handles. */ this.onlyBindHandles = false; /** Set to true to show graphs right to left. If vertical is true it will be from top to bottom and left / right arrow functions reversed. */ this.rightToLeft = false; /** Set to true to reverse keyboard navigation: Right/top arrows: -1 Left/bottom arrows: +1 Page-up: -10% Page-down: +10% End: minimum value Home: maximum value */ this.reversedControls = false; /** Set to true to keep the slider labels inside the slider bounds. */ this.boundPointerLabels = true; /** Set to true to use a logarithmic scale to display the slider. */ this.logScale = false; /** Function that returns the position on the slider for a given value. The position must be a percentage between 0 and 1. The function should be monotonically increasing or decreasing; otherwise the slider may behave incorrectly. */ this.customValueToPosition = null; /** Function that returns the value for a given position on the slider. The position is a percentage between 0 and 1. The function should be monotonically increasing or decreasing; otherwise the slider may behave incorrectly. */ this.customPositionToValue = null; /** Precision limit for calculated values. Values used in calculations will be rounded to this number of significant digits to prevent accumulating small floating-point errors. */ this.precisionLimit = 12; /** Use to display the selection bar as a gradient. The given object must contain from and to properties which are colors. */ this.selectionBarGradient = null; /** Use to add a label directly to the slider for accessibility. Adds the aria-label attribute. */ this.ariaLabel = null; /** Use instead of ariaLabel to reference the id of an element which will be used to label the slider. Adds the aria-labelledby attribute. */ this.ariaLabelledBy = null; /** Use to add a label directly to the slider range for accessibility. Adds the aria-label attribute. */ this.ariaLabelHigh = null; /** Use instead of ariaLabelHigh to reference the id of an element which will be used to label the slider range. Adds the aria-labelledby attribute. */ this.ariaLabelledByHigh = null; /** Use to increase rendering performance. If the value is not provided, the slider calculates the with/height of the handle */ this.handleDimension = null; /** Use to increase rendering performance. If the value is not provided, the slider calculates the with/height of the bar */ this.barDimension = null; /** Enable/disable CSS animations */ this.animate = true; /** Enable/disable CSS animations while moving the slider */ this.animateOnMove = false; } } /** Pointer type */ var PointerType; (function (PointerType) { /** Low pointer */ PointerType[PointerType["Min"] = 0] = "Min"; /** High pointer */ PointerType[PointerType["Max"] = 1] = "Max"; })(PointerType || (PointerType = {})); class ChangeContext { } /** * Collection of functions to handle conversions/lookups of values */ class ValueHelper { static isNullOrUndefined(value) { return value === undefined || value === null; } static areArraysEqual(array1, array2) { if (array1.length !== array2.length) { return false; } for (let i = 0; i < array1.length; ++i) { if (array1[i] !== array2[i]) { return false; } } return true; } static linearValueToPosition(val, minVal, maxVal) { const range = maxVal - minVal; return (val - minVal) / range; } static logValueToPosition(val, minVal, maxVal) { val = Math.log(val); minVal = Math.log(minVal); maxVal = Math.log(maxVal); const range = maxVal - minVal; return (val - minVal) / range; } static linearPositionToValue(percent, minVal, maxVal) { return percent * (maxVal - minVal) + minVal; } static logPositionToValue(percent, minVal, maxVal) { minVal = Math.log(minVal); maxVal = Math.log(maxVal); const value = percent * (maxVal - minVal) + minVal; return Math.exp(value); } static findStepIndex(modelValue, stepsArray) { const differences = stepsArray.map((step) => Math.abs(modelValue - step.value)); let minDifferenceIndex = 0; for (let index = 0; index < stepsArray.length; index++) { if (differences[index] !== differences[minDifferenceIndex] && differences[index] < differences[minDifferenceIndex]) { minDifferenceIndex = index; } } return minDifferenceIndex; } } /** Helper with compatibility functions to support different browsers */ class CompatibilityHelper { /** Workaround for TouchEvent constructor sadly not being available on all browsers (e.g. Firefox, Safari) */ static isTouchEvent(event) { if (window.TouchEvent !== undefined) { return event instanceof TouchEvent; } return event.touches !== undefined; } /** Detect presence of ResizeObserver API */ static isResizeObserverAvailable() { return window.ResizeObserver !== undefined; } } /** Helper with mathematical functions */ class MathHelper { /* Round numbers to a given number of significant digits */ static roundToPrecisionLimit(value, precisionLimit) { return +(value.toPrecision(precisionLimit)); } static isModuloWithinPrecisionLimit(value, modulo, precisionLimit) { const limit = Math.pow(10, -precisionLimit); return Math.abs(value % modulo) <= limit || Math.abs(Math.abs(value % modulo) - modulo) <= limit; } static clampToRange(value, floor, ceil) { return Math.min(Math.max(value, floor), ceil); } } class EventListener { constructor() { this.eventName = null; this.events = null; this.eventsSubscription = null; this.teardownCallback = null; } } /** * Helper class to attach event listeners to DOM elements with debounce support using rxjs */ class EventListenerHelper { constructor(renderer) { this.renderer = renderer; } attachPassiveEventListener(nativeElement, eventName, callback, throttleInterval) { // Only use passive event listeners if the browser supports it if (detectPassiveEvents.hasSupport !== true) { return this.attachEventListener(nativeElement, eventName, callback, throttleInterval); } // Angular doesn't support passive event handlers (yet), so we need to roll our own code using native functions const listener = new EventListener(); listener.eventName = eventName; listener.events = new Subject(); const observerCallback = (event) => { listener.events.next(event); }; nativeElement.addEventListener(eventName, observerCallback, { passive: true, capture: false }); listener.teardownCallback = () => { nativeElement.removeEventListener(eventName, observerCallback, { passive: true, capture: false }); }; listener.eventsSubscription = listener.events .pipe((!ValueHelper.isNullOrUndefined(throttleInterval)) ? throttleTime(throttleInterval, undefined, { leading: true, trailing: true }) : tap(() => { }) // no-op ) .subscribe((event) => { callback(event); }); return listener; } detachEventListener(eventListener) { if (!ValueHelper.isNullOrUndefined(eventListener.eventsSubscription)) { eventListener.eventsSubscription.unsubscribe(); eventListener.eventsSubscription = null; } if (!ValueHelper.isNullOrUndefined(eventListener.events)) { eventListener.events.complete(); eventListener.events = null; } if (!ValueHelper.isNullOrUndefined(eventListener.teardownCallback)) { eventListener.teardownCallback(); eventListener.teardownCallback = null; } } attachEventListener(nativeElement, eventName, callback, throttleInterval) { const listener = new EventListener(); listener.eventName = eventName; listener.events = new Subject(); const observerCallback = (event) => { listener.events.next(event); }; listener.teardownCallback = this.renderer.listen(nativeElement, eventName, observerCallback); listener.eventsSubscription = listener.events .pipe((!ValueHelper.isNullOrUndefined(throttleInterval)) ? throttleTime(throttleInterval, undefined, { leading: true, trailing: true }) : tap(() => { }) // no-op ) .subscribe((event) => { callback(event); }); return listener; } } class SliderElementDirective { constructor(elemRef, renderer, changeDetectionRef) { this.elemRef = elemRef; this.renderer = renderer; this.changeDetectionRef = changeDetectionRef; this._position = 0; this._dimension = 0; this._alwaysHide = false; this._vertical = false; this._scale = 1; this.opacity = 1; this.visibility = 'visible'; this.left = ''; this.bottom = ''; this.height = ''; this.width = ''; this.eventListeners = []; this.eventListenerHelper = new EventListenerHelper(this.renderer); } get position() { return this._position; } get dimension() { return this._dimension; } get alwaysHide() { return this._alwaysHide; } get vertical() { return this._vertical; } get scale() { return this._scale; } setAlwaysHide(hide) { this._alwaysHide = hide; if (hide) { this.visibility = 'hidden'; } else { this.visibility = 'visible'; } } hide() { this.opacity = 0; } show() { if (this.alwaysHide) { return; } this.opacity = 1; } isVisible() { if (this.alwaysHide) { return false; } return this.opacity !== 0; } setVertical(vertical) { this._vertical = vertical; if (this._vertical) { this.left = ''; this.width = ''; } else { this.bottom = ''; this.height = ''; } } setScale(scale) { this._scale = scale; } // Set element left/top position depending on whether slider is horizontal or vertical setPosition(pos) { if (this._position !== pos && !this.isRefDestroyed()) { this.changeDetectionRef.markForCheck(); } this._position = pos; if (this._vertical) { this.bottom = Math.round(pos) + 'px'; } else { this.left = Math.round(pos) + 'px'; } } // Calculate element's width/height depending on whether slider is horizontal or vertical calculateDimension() { const val = this.getBoundingClientRect(); if (this.vertical) { this._dimension = (val.bottom - val.top) * this.scale; } else { this._dimension = (val.right - val.left) * this.scale; } } // Set element width/height depending on whether slider is horizontal or vertical setDimension(dim) { if (this._dimension !== dim && !this.isRefDestroyed()) { this.changeDetectionRef.markForCheck(); } this._dimension = dim; if (this._vertical) { this.height = Math.round(dim) + 'px'; } else { this.width = Math.round(dim) + 'px'; } } getBoundingClientRect() { return this.elemRef.nativeElement.getBoundingClientRect(); } on(eventName, callback, debounceInterval) { const listener = this.eventListenerHelper.attachEventListener(this.elemRef.nativeElement, eventName, callback, debounceInterval); this.eventListeners.push(listener); } onPassive(eventName, callback, debounceInterval) { const listener = this.eventListenerHelper.attachPassiveEventListener(this.elemRef.nativeElement, eventName, callback, debounceInterval); this.eventListeners.push(listener); } off(eventName) { let listenersToKeep; let listenersToRemove; if (!ValueHelper.isNullOrUndefined(eventName)) { listenersToKeep = this.eventListeners.filter((event) => event.eventName !== eventName); listenersToRemove = this.eventListeners.filter((event) => event.eventName === eventName); } else { listenersToKeep = []; listenersToRemove = this.eventListeners; } for (const listener of listenersToRemove) { this.eventListenerHelper.detachEventListener(listener); } this.eventListeners = listenersToKeep; } isRefDestroyed() { return ValueHelper.isNullOrUndefined(this.changeDetectionRef) || this.changeDetectionRef['destroyed']; } } SliderElementDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: SliderElementDirective, deps: [{ token: i0.ElementRef }, { token: i0.Renderer2 }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Directive }); SliderElementDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "13.0.3", type: SliderElementDirective, selector: "[ngxSliderElement]", host: { properties: { "style.opacity": "this.opacity", "style.visibility": "this.visibility", "style.left": "this.left", "style.bottom": "this.bottom", "style.height": "this.height", "style.width": "this.width" } }, ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: SliderElementDirective, decorators: [{ type: Directive, args: [{ selector: '[ngxSliderElement]' }] }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i0.Renderer2 }, { type: i0.ChangeDetectorRef }]; }, propDecorators: { opacity: [{ type: HostBinding, args: ['style.opacity'] }], visibility: [{ type: HostBinding, args: ['style.visibility'] }], left: [{ type: HostBinding, args: ['style.left'] }], bottom: [{ type: HostBinding, args: ['style.bottom'] }], height: [{ type: HostBinding, args: ['style.height'] }], width: [{ type: HostBinding, args: ['style.width'] }] } }); class SliderHandleDirective extends SliderElementDirective { constructor(elemRef, renderer, changeDetectionRef) { super(elemRef, renderer, changeDetectionRef); this.active = false; this.role = ""; this.tabindex = ""; this.ariaOrientation = ""; this.ariaLabel = ""; this.ariaLabelledBy = ""; this.ariaValueNow = ""; this.ariaValueText = ""; this.ariaValueMin = ""; this.ariaValueMax = ""; } focus() { this.elemRef.nativeElement.focus(); } } SliderHandleDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: SliderHandleDirective, deps: [{ token: i0.ElementRef }, { token: i0.Renderer2 }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Directive }); SliderHandleDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "13.0.3", type: SliderHandleDirective, selector: "[ngxSliderHandle]", host: { properties: { "class.ngx-slider-active": "this.active", "attr.role": "this.role", "attr.tabindex": "this.tabindex", "attr.aria-orientation": "this.ariaOrientation", "attr.aria-label": "this.ariaLabel", "attr.aria-labelledby": "this.ariaLabelledBy", "attr.aria-valuenow": "this.ariaValueNow", "attr.aria-valuetext": "this.ariaValueText", "attr.aria-valuemin": "this.ariaValueMin", "attr.aria-valuemax": "this.ariaValueMax" } }, usesInheritance: true, ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: SliderHandleDirective, decorators: [{ type: Directive, args: [{ selector: "[ngxSliderHandle]", }] }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i0.Renderer2 }, { type: i0.ChangeDetectorRef }]; }, propDecorators: { active: [{ type: HostBinding, args: ["class.ngx-slider-active"] }], role: [{ type: HostBinding, args: ["attr.role"] }], tabindex: [{ type: HostBinding, args: ["attr.tabindex"] }], ariaOrientation: [{ type: HostBinding, args: ["attr.aria-orientation"] }], ariaLabel: [{ type: HostBinding, args: ["attr.aria-label"] }], ariaLabelledBy: [{ type: HostBinding, args: ["attr.aria-labelledby"] }], ariaValueNow: [{ type: HostBinding, args: ["attr.aria-valuenow"] }], ariaValueText: [{ type: HostBinding, args: ["attr.aria-valuetext"] }], ariaValueMin: [{ type: HostBinding, args: ["attr.aria-valuemin"] }], ariaValueMax: [{ type: HostBinding, args: ["attr.aria-valuemax"] }] } }); class SliderLabelDirective extends SliderElementDirective { constructor(elemRef, renderer, changeDetectionRef) { super(elemRef, renderer, changeDetectionRef); this._value = null; } get value() { return this._value; } setValue(value) { let recalculateDimension = false; if (!this.alwaysHide && (ValueHelper.isNullOrUndefined(this.value) || this.value.length !== value.length || (this.value.length > 0 && this.dimension === 0))) { recalculateDimension = true; } this._value = value; this.elemRef.nativeElement.innerHTML = value; // Update dimension only when length of the label have changed if (recalculateDimension) { this.calculateDimension(); } } } SliderLabelDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: SliderLabelDirective, deps: [{ token: i0.ElementRef }, { token: i0.Renderer2 }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Directive }); SliderLabelDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "13.0.3", type: SliderLabelDirective, selector: "[ngxSliderLabel]", usesInheritance: true, ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: SliderLabelDirective, decorators: [{ type: Directive, args: [{ selector: '[ngxSliderLabel]' }] }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i0.Renderer2 }, { type: i0.ChangeDetectorRef }]; } }); class TooltipWrapperComponent { } TooltipWrapperComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: TooltipWrapperComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); TooltipWrapperComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.0.3", type: TooltipWrapperComponent, selector: "ngx-slider-tooltip-wrapper", inputs: { template: "template", tooltip: "tooltip", placement: "placement", content: "content" }, ngImport: i0, template: "<ng-container *ngIf=\"template\">\n <ng-template *ngTemplateOutlet=\"template; context: {tooltip: tooltip, placement: placement, content: content}\"></ng-template>\n</ng-container>\n\n<ng-container *ngIf=\"!template\">\n <div class=\"ngx-slider-inner-tooltip\" [attr.title]=\"tooltip\" [attr.data-tooltip-placement]=\"placement\">\n {{content}}\n </div>\n</ng-container>", styles: [".ngx-slider-inner-tooltip{height:100%}\n"], directives: [{ type: i3.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i3.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet"] }] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.3", ngImport: i0, type: TooltipWrapperComponent, decorators: [{ type: Component, args: [{ selector: 'ngx-slider-tooltip-wrapper', template: "<ng-container *ngIf=\"template\">\n <ng-template *ngTemplateOutlet=\"template; context: {tooltip: tooltip, placement: placement, content: content}\"></ng-template>\n</ng-container>\n\n<ng-container *ngIf=\"!template\">\n <div class=\"ngx-slider-inner-tooltip\" [attr.title]=\"tooltip\" [attr.data-tooltip-placement]=\"placement\">\n {{content}}\n </div>\n</ng-container>", styles: [".ngx-slider-inner-tooltip{height:100%}\n"] }] }], propDecorators: { template: [{ type: Input }], tooltip: [{ type: Input }], placement: [{ type: Input }], content: [{ type: Input }] } }); class Tick { constructor() { this.selected = false; this.style = {}; this.tooltip = null; this.tooltipPlacement = null; this.value = null; this.valueTooltip = null; this.valueTooltipPlacement = null; this.legend = null; } } class Dragging { constructor() { this.active = false; this.value = 0; this.difference = 0; this.position = 0; this.lowLimit = 0; this.highLimit = 0; } } class ModelValues { static compare(x, y) { if (ValueHelper.isNullOrUndefined(x) && ValueHelper.isNullOrUndefined(y)) { return false; } if (ValueHelper.isNullOrUndefined(x) !== ValueHelper.isNullOrUndefined(y)) { return false; } return x.value === y.value && x.highValue === y.highValue; } } class ModelChange extends ModelValues { static compare(x, y) { if (ValueHelper.isNullOrUndefined(x) && ValueHelper.isNullOrUndefined(y)) { return false; } if (ValueHelper.isNullOrUndefined(x) !== ValueHelper.isNullOrUndefined(y)) { return false; } return (x.value === y.value && x.highValue === y.highValue && x.forceChange === y.forceChange); } } class InputModelChange extends ModelChange { } class OutputModelChange extends ModelChange { } const NGX_SLIDER_CONTROL_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, /* tslint:disable-next-line: no-use-before-declare */ useExisting: forwardRef(() => SliderComponent), multi: true, }; class SliderComponent { constructor(renderer, elementRef, changeDetectionRef, zone) { this.renderer = renderer; this.elementRef = elementRef; this.changeDetectionRef = changeDetectionRef; this.zone = zone; // Model for low value of slider. For simple slider, this is the only input. For range slider, this is the low value. this.value = null; // Output for low value slider to support two-way bindings this.valueChange = new EventEmitter(); // Model for high value of slider. Not used in simple slider. For range slider, this is the high value. this.highValue = null; // Output for high value slider to support two-way bindings this.highValueChange = new EventEmitter(); // An object with all the other options of the slider. // Each option can be updated at runtime and the slider will automatically be re-rendered. this.options = new Options(); // Event emitted when user starts interaction with the slider this.userChangeStart = new EventEmitter(); // Event emitted on each change coming from user interaction this.userChange = new EventEmitter(); // Event emitted when user finishes interaction with the slider this.userChangeEnd = new EventEmitter(); // Set to true if init method already executed this.initHasRun = false; // Changes in model inputs are passed through this subject // These are all changes coming in from outside the component through input bindings or reactive form inputs this.inputModelChangeSubject = new Subject(); this.inputModelChangeSubscription = null; // Changes to model outputs are passed through this subject // These are all changes that need to be communicated to output emitters and registered callbacks this.outputModelChangeSubject = new Subject(); this.outputModelChangeSubscription = null; // Low value synced to model low value this.viewLowValue = null; // High value synced to model high value this.viewHighValue = null; // Options synced to model options, based on defaults this.viewOptions = new Options(); // Half of the width or height of the slider handles this.handleHalfDimension = 0; // Maximum position the slider handle can have this.maxHandlePosition = 0; // Which handle is currently tracked for move events this.currentTrackingPointer = null; // Internal variable to keep track of the focus element this.currentFocusPointer = null; // Used to call onStart on the first keydown event this.firstKeyDown = false; // Current touch id of touch event being handled this.touchId = null; // Values recorded when first dragging the bar this.dragging = new Dragging(); // Host element class bindings this.sliderElementVerticalClass = false; this.sliderElementAnimateClass = false; this.sliderElementWithLegendClass = false; this.sliderElementDisabledAttr = null; // CSS styles and class flags this.barStyle = {}; this.minPointerStyle = {}; this.maxPointerStyle = {}; this.fullBarTransparentClass = false; this.selectionBarDraggableClass = false; this.ticksUnderValuesClass = false; /* If tickStep is set or ticksArray is specified. In this case, ticks values should be displayed below the slider. */ this.intermediateTicks = false; // Ticks array as displayed in view this.ticks = []; // Event listeners this.eventListenerHelper = null; this.onMoveEventListener = null; this.onEndEventListener = null; // Whether currently moving the slider (between onStart() and onEnd()) this.moving = false; // Observer for slider element resize events this.resizeObserver = null; // Callbacks for reactive forms support this.onTouchedCallback = null; this.onChangeCallback = null; this.eventListenerHelper = new EventListenerHelper(this.renderer); } // Input event that triggers slider refresh (re-positioning of slider elements) set manualRefresh(manualRefresh) { this.unsubscribeManualRefresh(); this.manualRefreshSubscription = manualRefresh.subscribe(() => { setTimeout(() => this.calculateViewDimensionsAndDetectChanges()); }); } // Input event that triggers setting focus on given slider handle set triggerFocus(triggerFocus) { this.unsubscribeTriggerFocus(); this.triggerFocusSubscription = triggerFocus.subscribe((pointerType) => { this.focusPointer(pointerType); }); } // Slider type, true means range slider get range() { return (!ValueHelper.isNullOrUndefined(this.value) && !ValueHelper.isNullOrUndefined(this.highValue)); } // Whether to show/hide ticks get showTicks() { return this.viewOptions.showTicks; } // OnInit interface ngOnInit() { this.viewOptions = new Options(); Object.assign(this.viewOptions, this.options); // We need to run these two things first, before the rest of the init in ngAfterViewInit(), // because these two settings are set through @HostBinding and Angular change detection // mechanism doesn't like them changing in ngAfterViewInit() this.updateDisabledState(); this.updateVerticalState(); } // AfterViewInit interface ngAfterViewInit() { this.applyOptions(); this.subscribeInputModelChangeSubject(this.viewOptions.inputEventsInterval); this.subscribeOutputModelChangeSubject(this.viewOptions.outputEventsInterval); // Once we apply options, we need to normalise model values for the first time this.renormaliseModelValues(); this.viewLowValue = this.modelValueToViewValue(this.value); if (this.range) { this.viewHighValue = this.modelValueToViewValue(this.highValue); } else { this.viewHighValue = null; } this.updateVerticalState(); // need to run this again to cover changes to slider elements this.manageElementsStyle(); this.updateDisabledState(); this.calculateViewDimensions(); this.addAccessibility(); this.updateCeilLabel(); this.updateFloorLabel(); this.initHandles(); this.manageEventsBindings(); this.subscribeResizeObserver(); this.initHasRun = true; // Run change detection manually to resolve some issues when init procedure changes values used in the view if (!this.isRefDestroyed()) { this.changeDetectionRef.detectChanges(); } } // OnChanges interface ngOnChanges(changes) { // Always apply options first if (this.haveOptionsChanged(changes)) { this.onChangeOptions(); } // Then value changes if (this.haveValuesChanged(changes)) { this.inputModelChangeSubject.next({ value: this.value, highValue: this.highValue, forceChange: false, internalChange: false, }); } } haveOptionsChanged(changes) { var _a, _b, _c, _d; return (!ValueHelper.isNullOrUndefined(changes.options) && ((_a = changes.options.currentValue) === null || _a === void 0 ? void 0 : _a.floor) !== ((_b = changes.options.previousValue) === null || _b === void 0 ? void 0 : _b.floor) && ((_c = changes.options.currentValue) === null || _c === void 0 ? void 0 : _c.ceil) !== ((_d = changes.options.previousValue) === null || _d === void 0 ? void 0 : _d.ceil)); } haveValuesChanged(changes) { return ((!ValueHelper.isNullOrUndefined(changes.value) && changes.value.currentValue !== changes.value.previousValue) || (!ValueHelper.isNullOrUndefined(changes.highValue) && changes.highValue.currentValue !== changes.highValue.previousValue)); } // OnDestroy interface ngOnDestroy() { this.unbindEvents(); this.unsubscribeResizeObserver(); this.unsubscribeInputModelChangeSubject(); this.unsubscribeOutputModelChangeSubject(); this.unsubscribeManualRefresh(); this.unsubscribeTriggerFocus(); } // ControlValueAccessor interface writeValue(obj) { if (obj instanceof Array) { this.value = obj[0]; this.highValue = obj[1]; } else { this.value = obj; } // ngOnChanges() is not called in this instance, so we need to communicate the change manually this.inputModelChangeSubject.next({ value: this.value, highValue: this.highValue, forceChange: false, internalChange: false, }); } // ControlValueAccessor interface registerOnChange(onChangeCallback) { this.onChangeCallback = onChangeCallback; } // ControlValueAccessor interface registerOnTouched(onTouchedCallback) { this.onTouchedCallback = onTouchedCallback; } // ControlValueAccessor interface setDisabledState(isDisabled) { this.viewOptions.disabled = isDisabled; this.updateDisabledState(); } onResize(event) { this.calculateViewDimensionsAndDetectChanges(); } subscribeInputModelChangeSubject(interval) { this.inputModelChangeSubscription = this.inputModelChangeSubject .pipe(distinctUntilChanged(ModelChange.compare), // Hack to reset the status of the distinctUntilChanged() - if a "fake" event comes through with forceChange=true, // we forcefully by-pass distinctUntilChanged(), but otherwise drop the event filter((modelChange) => !modelChange.forceChange && !modelChange.internalChange), !ValueHelper.isNullOrUndefined(interval) ? throttleTime(interval, undefined, { leading: true, trailing: true }) : tap(() => { }) // no-op ) .subscribe((modelChange) => this.applyInputModelChange(modelChange)); } subscribeOutputModelChangeSubject(interval) { this.outputModelChangeSubscription = this.outputModelChangeSubject .pipe(distinctUntilChanged(ModelChange.compare), !ValueHelper.isNullOrUndefined(interval) ? throttleTime(interval, undefined, { leading: true, trailing: true }) : tap(() => { }) // no-op ) .subscribe((modelChange) => this.publishOutputModelChange(modelChange)); } subscribeResizeObserver() { if (CompatibilityHelper.isResizeObserverAvailable()) { this.resizeObserver = new ResizeObserver(() => this.calculateViewDimensionsAndDetectChanges()); this.resizeObserver.observe(this.elementRef.nativeElement); } } unsubscribeResizeObserver() { if (CompatibilityHelper.isResizeObserverAvailable() && this.resizeObserver !== null) { this.resizeObserver.disconnect(); this.resizeObserver = null; } } unsubscribeOnMove() { if (!ValueHelper.isNullOrUndefined(this.onMoveEventListener)) { this.eventListenerHelper.detachEventListener(this.onMoveEventListener); this.onMoveEventListener = null; } } unsubscribeOnEnd() { if (!ValueHelper.isNullOrUndefined(this.onEndEventListener)) { this.eventListenerHelper.detachEventListener(this.onEndEventListener); this.onEndEventListener = null; } } unsubscribeInputModelChangeSubject() { if (!ValueHelper.isNullOrUndefined(this.inputModelChangeSubscription)) { this.inputModelChangeSubscription.unsubscribe(); this.inputModelChangeSubscription = null; } } unsubscribeOutputModelChangeSubject() { if (!ValueHelper.isNullOrUndefined(this.outputModelChangeSubscription)) { this.outputModelChangeSubscription.unsubscribe(); this.outputModelChangeSubscription = null; } } unsubscribeManualRefresh() { if (!ValueHelper.isNullOrUndefined(this.manualRefreshSubscription)) { this.manualRefreshSubscription.unsubscribe(); this.manualRefreshSubscription = null; } } unsubscribeTriggerFocus() { if (!ValueHelper.isNullOrUndefined(this.triggerFocusSubscription)) { this.triggerFocusSubscription.unsubscribe(); this.triggerFocusSubscription = null; } } getPointerElement(pointerType) { if (pointerType === PointerType.Min) { return this.minHandleElement; } else if (pointerType === PointerType.Max) { return this.maxHandleElement; } return null; } getCurrentTrackingValue() { if (this.currentTrackingPointer === PointerType.Min) { return this.viewLowValue; } else if (this.currentTrackingPointer === PointerType.Max) { return this.viewHighValue; } return null; } modelValueToViewValue(modelValue) { if (ValueHelper.isNullOrUndefined(modelValue)) { return NaN; } if (!ValueHelper.isNullOrUndefined(this.viewOptions.stepsArray) && !this.viewOptions.bindIndexForStepsArray) { return ValueHelper.findStepIndex(+modelValue, this.viewOptions.stepsArray); } return +modelValue; } viewValueToModelValue(viewValue) { if (!ValueHelper.isNullOrUndefined(this.viewOptions.stepsArray) && !this.viewOptions.bindIndexForStepsArray) { return this.getStepValue(viewValue); } return viewValue; } getStepValue(sliderValue) { const step = this.viewOptions.stepsArray[sliderValue]; return !ValueHelper.isNullOrUndefined(step) ? step.value : NaN; } applyViewChange() { this.value = this.viewValueToModelValue(this.viewLowValue); if (this.range) { this.highValue = this.viewValueToModelValue(this.viewHighValue); } this.outputModelChangeSubject.next({ value: this.value, highValue: this.highValue, userEventInitiated: true, forceChange: false, }); // At this point all changes are applied and outputs are emitted, so we should be done. // However, input changes are communicated in different stream and we need to be ready to // act on the next input change even if it is exactly the same as last input change. // Therefore, we send a special event to reset the stream. this.inputModelChangeSubject.next({ value: this.value, highValue: this.highValue, forceChange: false, internalChange: true, }); } // Apply model change to the slider view applyInputModelChange(modelChange) { const normalisedMode