@angular-slider/ngx-slider
Version:
Self-contained, mobile friendly slider component for Angular based on angularjs-slider
1,165 lines (1,152 loc) • 153 kB
JavaScript
import * as i0 from '@angular/core';
import { InjectionToken, Directive, HostBinding, Inject, Optional, Component, Input, forwardRef, EventEmitter, ChangeDetectionStrategy, Output, ViewChild, ContentChild, HostListener, NgModule } from '@angular/core';
import * as i1 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 { supportsPassiveEvents } 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 {
/** Minimum value for a slider.
Not applicable when using stepsArray. */
floor = 0;
/** Maximum value for a slider.
Not applicable when using stepsArray. */
ceil = null;
/** Step between each value.
Not applicable when using stepsArray. */
step = 1;
/** The minimum range authorized on the slider.
Applies to range slider only.
When using stepsArray, expressed as index into stepsArray. */
minRange = null;
/** The maximum range authorized on the slider.
Applies to range slider only.
When using stepsArray, expressed as index into stepsArray. */
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. */
pushRange = false;
/** The minimum value authorized on the slider.
When using stepsArray, expressed as index into stepsArray. */
minLimit = null;
/** The maximum value authorized on the slider.
When using stepsArray, expressed as index into stepsArray. */
maxLimit = null;
/** Custom translate function. Use this if you want to translate values displayed
on the slider. */
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. */
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. */
getLegend = null;
/** Use to display a custom legend of a stepItem from stepsArray.
It will be the same as getLegend but for stepsArray. */
getStepLegend = 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. */
stepsArray = null;
/** Set to true to bind the index of the selected item to value model and valueHigh model. */
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. */
draggableRange = false;
/** Same as draggableRange but the slider range can't be changed.
Applies to range slider only. */
draggableRangeOnly = false;
/** Set to true to always show the selection bar before the slider handle. */
showSelectionBar = false;
/** Set to true to always show the selection bar after the slider handle. */
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. */
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. */
showOuterSelectionBars = false;
/** Set to true to hide pointer labels */
hidePointerLabels = false;
/** Set to true to hide min / max labels */
hideLimitLabels = false;
/** Set to false to disable the auto-hiding behavior of the limit labels. */
autoHideLimitLabels = true;
/** Set to true to make the slider read-only. */
readOnly = false;
/** Set to true to disable the slider. */
disabled = false;
/** Set to true to display a tick for each step of the slider. */
showTicks = false;
/** Set to true to display a tick and the step value for each step of the slider.. */
showTicksValues = false;
/* The step between each tick to display. If not set, the step value is used.
Not used when ticksArray is specified. */
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. */
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. */
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. */
ticksTooltip = null;
/** Same as ticksTooltip but for ticks values. */
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. */
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.*/
getSelectionBarColor = null;
/** Function that returns the color of a tick. showTicks must be enabled. */
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. */
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
*/
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. */
scale = 1;
/** If you display the slider in an element that uses transform: rotate(90deg), set the rotate value to 90
so that the slider is rendered properly and the events are handled correctly. Value is in degrees. */
rotate = 0;
/** 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. */
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. */
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. */
enforceStepsArray = true;
/** Set to true to prevent to user from switching the min and max handles. Applies to range slider only. */
noSwitching = false;
/** Set to true to only bind events on slider handles. */
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. */
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
*/
reversedControls = false;
/** Set to true to keep the slider labels inside the slider bounds. */
boundPointerLabels = true;
/** Set to true to use a logarithmic scale to display the slider. */
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. */
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. */
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. */
precisionLimit = 12;
/** Use to display the selection bar as a gradient.
The given object must contain from and to properties which are colors. */
selectionBarGradient = null;
/** Use to add a label directly to the slider for accessibility. Adds the aria-label attribute. */
ariaLabel = 'ngx-slider';
/** Use instead of ariaLabel to reference the id of an element which will be used to label the slider.
Adds the aria-labelledby attribute. */
ariaLabelledBy = null;
/** Use to add a label directly to the slider range for accessibility. Adds the aria-label attribute. */
ariaLabelHigh = 'ngx-slider-max';
/** 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. */
ariaLabelledByHigh = null;
/** Use to increase rendering performance. If the value is not provided, the slider calculates the with/height of the handle */
handleDimension = null;
/** Use to increase rendering performance. If the value is not provided, the slider calculates the with/height of the bar */
barDimension = null;
/** Enable/disable CSS animations */
animate = true;
/** Enable/disable CSS animations while moving the slider */
animateOnMove = false;
}
const AllowUnsafeHtmlInSlider = new InjectionToken('AllowUnsafeHtmlInSlider');
/** Pointer type */
var PointerType;
(function (PointerType) {
/** Low pointer */
PointerType[PointerType["Min"] = 0] = "Min";
/** High pointer */
PointerType[PointerType["Max"] = 1] = "Max";
})(PointerType || (PointerType = {}));
class ChangeContext {
value;
highValue;
pointerType;
}
/**
* 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 {
eventName = null;
events = null;
eventsSubscription = null;
teardownCallback = null;
}
/**
* Helper class to attach event listeners to DOM elements with debounce support using rxjs
*/
class EventListenerHelper {
renderer;
constructor(renderer) {
this.renderer = renderer;
}
attachPassiveEventListener(nativeElement, eventName, callback, throttleInterval) {
// Only use passive event listeners if the browser supports it
if (supportsPassiveEvents !== 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 {
elemRef;
renderer;
changeDetectionRef;
_position = 0;
get position() {
return this._position;
}
_dimension = 0;
get dimension() {
return this._dimension;
}
_alwaysHide = false;
get alwaysHide() {
return this._alwaysHide;
}
_vertical = false;
get vertical() {
return this._vertical;
}
_scale = 1;
get scale() {
return this._scale;
}
_rotate = 0;
get rotate() {
return this._rotate;
}
opacity = 1;
visibility = 'visible';
left = '';
bottom = '';
height = '';
width = '';
transform = '';
eventListenerHelper;
eventListeners = [];
constructor(elemRef, renderer, changeDetectionRef) {
this.elemRef = elemRef;
this.renderer = renderer;
this.changeDetectionRef = changeDetectionRef;
this.eventListenerHelper = new EventListenerHelper(this.renderer);
}
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;
}
setRotate(rotate) {
this._rotate = rotate;
this.transform = 'rotate(' + rotate + 'deg)';
}
getRotate() {
return this._rotate;
}
// 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'];
}
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: SliderElementDirective, deps: [{ token: i0.ElementRef }, { token: i0.Renderer2 }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Directive });
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.1.3", type: SliderElementDirective, isStandalone: false, 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", "style.transform": "this.transform" } }, ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: SliderElementDirective, decorators: [{
type: Directive,
args: [{
selector: '[ngxSliderElement]',
standalone: false
}]
}], ctorParameters: () => [{ 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']
}], transform: [{
type: HostBinding,
args: ['style.transform']
}] } });
class SliderHandleDirective extends SliderElementDirective {
active = false;
role = '';
tabindex = '';
ariaOrientation = '';
ariaLabel = '';
ariaLabelledBy = '';
ariaValueNow = '';
ariaValueText = '';
ariaValueMin = '';
ariaValueMax = '';
focus() {
this.elemRef.nativeElement.focus();
}
focusIfNeeded() {
if (document.activeElement !== this.elemRef.nativeElement) {
this.elemRef.nativeElement.focus();
}
}
constructor(elemRef, renderer, changeDetectionRef) {
super(elemRef, renderer, changeDetectionRef);
}
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: SliderHandleDirective, deps: [{ token: i0.ElementRef }, { token: i0.Renderer2 }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Directive });
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.1.3", type: SliderHandleDirective, isStandalone: false, 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: "19.1.3", ngImport: i0, type: SliderHandleDirective, decorators: [{
type: Directive,
args: [{
selector: '[ngxSliderHandle]',
standalone: false
}]
}], ctorParameters: () => [{ 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 {
allowUnsafeHtmlInSlider;
_value = null;
get value() {
return this._value;
}
constructor(elemRef, renderer, changeDetectionRef, allowUnsafeHtmlInSlider) {
super(elemRef, renderer, changeDetectionRef);
this.allowUnsafeHtmlInSlider = allowUnsafeHtmlInSlider;
}
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;
if (this.allowUnsafeHtmlInSlider === false) {
this.elemRef.nativeElement.innerText = value;
}
else {
this.elemRef.nativeElement.innerHTML = value;
}
// Update dimension only when length of the label have changed
if (recalculateDimension) {
this.calculateDimension();
}
}
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: SliderLabelDirective, deps: [{ token: i0.ElementRef }, { token: i0.Renderer2 }, { token: i0.ChangeDetectorRef }, { token: AllowUnsafeHtmlInSlider, optional: true }], target: i0.ɵɵFactoryTarget.Directive });
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.1.3", type: SliderLabelDirective, isStandalone: false, selector: "[ngxSliderLabel]", usesInheritance: true, ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: SliderLabelDirective, decorators: [{
type: Directive,
args: [{
selector: '[ngxSliderLabel]',
standalone: false
}]
}], ctorParameters: () => [{ type: i0.ElementRef }, { type: i0.Renderer2 }, { type: i0.ChangeDetectorRef }, { type: undefined, decorators: [{
type: Inject,
args: [AllowUnsafeHtmlInSlider]
}, {
type: Optional
}] }] });
class TooltipWrapperComponent {
template;
tooltip;
placement;
content;
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: TooltipWrapperComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "19.1.3", type: TooltipWrapperComponent, isStandalone: false, 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"], dependencies: [{ kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: TooltipWrapperComponent, decorators: [{
type: Component,
args: [{ selector: 'ngx-slider-tooltip-wrapper', standalone: false, 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 {
selected = false;
style = {};
tooltip = null;
tooltipPlacement = null;
value = null;
valueTooltip = null;
valueTooltipPlacement = null;
legend = null;
}
class Dragging {
active = false;
value = 0;
difference = 0;
position = 0;
lowLimit = 0;
highLimit = 0;
}
class ModelValues {
value;
highValue;
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 {
// Flag used to by-pass distinctUntilChanged() filter on input values
// (sometimes there is a need to pass values through even though the model values have not changed)
forceChange;
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 {
controlAccessorChange;
internalChange;
}
class OutputModelChange extends ModelChange {
controlAccessorChange;
userEventInitiated;
}
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 {
renderer;
elementRef;
changeDetectionRef;
zone;
allowUnsafeHtmlInSlider;
// Add ngx-slider class to the host element - this is static, should never change
sliderElementNgxSliderClass = true;
// Model for low value of slider. For simple slider, this is the only input. For range slider, this is the low value.
value = null;
// Output for low value slider to support two-way bindings
valueChange = new EventEmitter();
// Model for high value of slider. Not used in simple slider. For range slider, this is the high value.
highValue = null;
// Output for high value slider to support two-way bindings
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.
options = new Options();
// Event emitted when user starts interaction with the slider
userChangeStart = new EventEmitter();
// Event emitted on each change coming from user interaction
userChange = new EventEmitter();
// Event emitted when user finishes interaction with the slider
userChangeEnd = new EventEmitter();
manualRefreshSubscription;
// Input event that triggers slider refresh (re-positioning of slider elements)
set manualRefresh(manualRefresh) {
this.unsubscribeManualRefresh();
this.manualRefreshSubscription = manualRefresh.subscribe(() => {
setTimeout(() => this.calculateViewDimensionsAndDetectChanges());
});
}
triggerFocusSubscription;
// Input event that triggers setting focus on given slider handle
set triggerFocus(triggerFocus) {
this.unsubscribeTriggerFocus();
this.triggerFocusSubscription = triggerFocus.subscribe((pointerType) => {
this.focusPointer(pointerType);
});
}
cancelUserChangeSubscription;
set cancelUserChange(cancelUserChange) {
this.unsubscribeCancelUserChange();
this.cancelUserChangeSubscription = cancelUserChange.subscribe(() => {
if (this.moving) {
this.positionTrackingHandle(this.preStartHandleValue);
this.forceEnd(true);
}
});
}
// Slider type, true means range slider
get range() {
return (!ValueHelper.isNullOrUndefined(this.value) &&
!ValueHelper.isNullOrUndefined(this.highValue));
}
// Set to true if init method already executed
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
inputModelChangeSubject = new Subject();
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
outputModelChangeSubject = new Subject();
outputModelChangeSubscription = null;
// Low value synced to model low value
viewLowValue = null;
// High value synced to model high value
viewHighValue = null;
// Options synced to model options, based on defaults
viewOptions = new Options();
// Half of the width or height of the slider handles
handleHalfDimension = 0;
// Maximum position the slider handle can have
maxHandlePosition = 0;
// Which handle is currently tracked for move events
currentTrackingPointer = null;
// Internal variable to keep track of the focus element
currentFocusPointer = null;
// Used to call onStart on the first keydown event
firstKeyDown = false;
// Current touch id of touch event being handled
touchId = null;
// Values recorded when first dragging the bar
dragging = new Dragging();
// Value of hanlde at the beginning of onStart()
preStartHandleValue = null;
/* Slider DOM elements */
// Left selection bar outside two handles
leftOuterSelectionBarElement;
// Right selection bar outside two handles
rightOuterSelectionBarElement;
// The whole slider bar
fullBarElement;
// Highlight between two handles
selectionBarElement;
// Left slider handle
minHandleElement;
// Right slider handle
maxHandleElement;
// Floor label
floorLabelElement;
// Ceiling label
ceilLabelElement;
// Label above the low value
minHandleLabelElement;
// Label above the high value
maxHandleLabelElement;
// Combined label
combinedLabelElement;
// The ticks
ticksElement;
// Optional custom template for displaying tooltips
tooltipTemplate;
// Host element class bindings
sliderElementVerticalClass = false;
sliderElementAnimateClass = false;
sliderElementWithLegendClass = false;
sliderElementDisabledAttr = null;
sliderElementAriaLabel = 'ngx-slider';
// CSS styles and class flags
barStyle = {};
minPointerStyle = {};
maxPointerStyle = {};
fullBarTransparentClass = false;
selectionBarDraggableClass = false;
ticksUnderValuesClass = false;
// Whether to show/hide ticks
get showTicks() {
return this.viewOptions.showTicks;
}
/* If tickStep is set or ticksArray is specified.
In this case, ticks values should be displayed below the slider. */
intermediateTicks = false;
// Ticks array as displayed in view
ticks = [];
// Event listeners
eventListenerHelper = null;
onMoveEventListener = null;
onEndEventListener = null;
// Whether currently moving the slider (between onStart() and onEnd())
moving = false;
// Observer for slider element resize events
resizeObserver = null;
// Callbacks for reactive forms support
onTouchedCallback = null;
onChangeCallback = null;
constructor(renderer, elementRef, changeDetectionRef, zone, allowUnsafeHtmlInSlider) {
this.renderer = renderer;
this.elementRef = elementRef;
this.changeDetectionRef = changeDetectionRef;
this.zone = zone;
this.allowUnsafeHtmlInSlider = allowUnsafeHtmlInSlider;
this.eventListenerHelper = new EventListenerHelper(this.renderer);
}
// 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();
this.updateAriaLabel();
}
// AfterViewInit interface
ngAfterViewInit() {
this.applyOptions();
this.subscribeInputModelChangeSubject();
this.subscribeOutputModelChangeSubject();
// 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.updateAriaLabel();
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 (!ValueHelper.isNullOrUndefined(changes.options) &&
JSON.stringify(changes.options.previousValue) !==
JSON.stringify(changes.options.currentValue)) {
this.onChangeOptions();
}
// Then value changes
if (!ValueHelper.isNullOrUndefined(changes.value) ||
!ValueHelper.isNullOrUndefined(changes.highValue)) {
this.inputModelChangeSubject.next({
value: this.value,
highValue: this.highValue,
controlAccessorChange: false,
forceChange: false,
internalChange: false,
});
}
}
// 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,
controlAccessorChange: true,
});
}
// ControlValueAccessor interface
registerOnChange(onChangeCallback) {
this.onChangeCallback = onChangeCallback;
}
// ControlValueAccessor interface
registerOnTouched(onTouchedCallback) {
this.onTouchedCallback = onTouchedCallback;
}
// ControlValueAccessor interface
setDisabledState(isDisabled) {
this.viewOptions.disabled = isDisabled;
this.updateDisabledState();
if (this.initHasRun) {
this.manageEventsBindings();
}
}
setAriaLabel(ariaLabel) {
this.viewOptions.ariaLabel = ariaLabel;
this.updateAriaLabel();
}
onResize(event) {
this.calculateViewDimensionsAndDetectChanges();
}
subscribeInputModelChangeSubject() {
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))
.subscribe((modelChange) => this.applyInputModelChange(modelChange));
}
subscribeOutputModelChangeSubject() {
this.outputModelChangeSubscription = this.outputModelChangeSubject
.pipe(distinctUntilChanged(ModelChange.compare))
.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;
}
}
unsubscribeCancelUserChange() {
if (!ValueHelper.isNullOrUndefined(this.cancelUserChangeSubscription)) {
this.cancelUserChangeSubscription.unsubscribe();
this.cancelUserChangeSubscription = 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,
controlAccessorChange: false,
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