admin-lte
Version:
Introduction ============
1,477 lines (1,251 loc) • 70.1 kB
JavaScript
/*! =========================================================
* bootstrap-slider.js
*
* Maintainers:
* Kyle Kemp
* - Twitter: @seiyria
* - Github: seiyria
* Rohit Kalkur
* - Twitter: @Rovolutionary
* - Github: rovolution
*
* =========================================================
*
* bootstrap-slider is released under the MIT License
* Copyright (c) 2019 Kyle Kemp, Rohit Kalkur, and contributors
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* ========================================================= */
/**
* Bridget makes jQuery widgets
* v1.0.1
* MIT license
*/
const windowIsDefined = (typeof window === "object");
(function(factory) {
if(typeof define === "function" && define.amd) {
define(["jquery"], factory);
}
else if(typeof module === "object" && module.exports) {
var jQuery;
try {
jQuery = require("jquery");
}
catch (err) {
jQuery = null;
}
module.exports = factory(jQuery);
}
else if(window) {
window.Slider = factory(window.jQuery);
}
}(function($) {
// Constants
const NAMESPACE_MAIN = 'slider';
const NAMESPACE_ALTERNATE = 'bootstrapSlider';
// Polyfill console methods
if (windowIsDefined && !window.console) {
window.console = {};
}
if (windowIsDefined && !window.console.log) {
window.console.log = function () { };
}
if (windowIsDefined && !window.console.warn) {
window.console.warn = function () { };
}
// Reference to Slider constructor
var Slider;
(function( $ ) {
'use strict';
// -------------------------- utils -------------------------- //
var slice = Array.prototype.slice;
function noop() {}
// -------------------------- definition -------------------------- //
function defineBridget( $ ) {
// bail if no jQuery
if ( !$ ) {
return;
}
// -------------------------- addOptionMethod -------------------------- //
/**
* adds option method -> $().plugin('option', {...})
* @param {Function} PluginClass - constructor class
*/
function addOptionMethod( PluginClass ) {
// don't overwrite original option method
if ( PluginClass.prototype.option ) {
return;
}
// option setter
PluginClass.prototype.option = function( opts ) {
// bail out if not an object
if ( !$.isPlainObject( opts ) ){
return;
}
this.options = $.extend( true, this.options, opts );
};
}
// -------------------------- plugin bridge -------------------------- //
// helper function for logging errors
// $.error breaks jQuery chaining
var logError = typeof console === 'undefined' ? noop :
function( message ) {
console.error( message );
};
/**
* jQuery plugin bridge, access methods like $elem.plugin('method')
* @param {String} namespace - plugin name
* @param {Function} PluginClass - constructor class
*/
function bridge( namespace, PluginClass ) {
// add to jQuery fn namespace
$.fn[ namespace ] = function( options ) {
if ( typeof options === 'string' ) {
// call plugin method when first argument is a string
// get arguments for method
var args = slice.call( arguments, 1 );
for ( var i=0, len = this.length; i < len; i++ ) {
var elem = this[i];
var instance = $.data( elem, namespace );
if ( !instance ) {
logError( "cannot call methods on " + namespace + " prior to initialization; " +
"attempted to call '" + options + "'" );
continue;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) {
logError( "no such method '" + options + "' for " + namespace + " instance" );
continue;
}
// trigger method with arguments
var returnValue = instance[ options ].apply( instance, args);
// break look and return first value if provided
if ( returnValue !== undefined && returnValue !== instance) {
return returnValue;
}
}
// return this if no return value
return this;
} else {
var objects = this.map( function() {
var instance = $.data( this, namespace );
if ( instance ) {
// apply options & init
instance.option( options );
instance._init();
} else {
// initialize new instance
instance = new PluginClass( this, options );
$.data( this, namespace, instance );
}
return $(this);
});
if(objects.length === 1) {
return objects[0];
}
return objects;
}
};
}
// -------------------------- bridget -------------------------- //
/**
* converts a Prototypical class into a proper jQuery plugin
* the class must have a ._init method
* @param {String} namespace - plugin name, used in $().pluginName
* @param {Function} PluginClass - constructor class
*/
$.bridget = function( namespace, PluginClass ) {
addOptionMethod( PluginClass );
bridge( namespace, PluginClass );
};
return $.bridget;
}
// get jquery from browser global
defineBridget( $ );
})( $ );
/*************************************************
BOOTSTRAP-SLIDER SOURCE CODE
**************************************************/
(function($) {
let autoRegisterNamespace;
var ErrorMsgs = {
formatInvalidInputErrorMsg : function(input) {
return "Invalid input value '" + input + "' passed in";
},
callingContextNotSliderInstance : "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method"
};
var SliderScale = {
linear: {
getValue: function(value, options) {
if (value < options.min) {
return options.min;
} else if (value > options.max) {
return options.max;
} else {
return value;
}
},
toValue: function(percentage) {
var rawValue = percentage/100 * (this.options.max - this.options.min);
var shouldAdjustWithBase = true;
if (this.options.ticks_positions.length > 0) {
var minv, maxv, minp, maxp = 0;
for (var i = 1; i < this.options.ticks_positions.length; i++) {
if (percentage <= this.options.ticks_positions[i]) {
minv = this.options.ticks[i-1];
minp = this.options.ticks_positions[i-1];
maxv = this.options.ticks[i];
maxp = this.options.ticks_positions[i];
break;
}
}
var partialPercentage = (percentage - minp) / (maxp - minp);
rawValue = minv + partialPercentage * (maxv - minv);
shouldAdjustWithBase = false;
}
var adjustment = shouldAdjustWithBase ? this.options.min : 0;
var value = adjustment + Math.round(rawValue / this.options.step) * this.options.step;
return SliderScale.linear.getValue(value, this.options);
},
toPercentage: function(value) {
if (this.options.max === this.options.min) {
return 0;
}
if (this.options.ticks_positions.length > 0) {
var minv, maxv, minp, maxp = 0;
for (var i = 0; i < this.options.ticks.length; i++) {
if (value <= this.options.ticks[i]) {
minv = (i > 0) ? this.options.ticks[i-1] : 0;
minp = (i > 0) ? this.options.ticks_positions[i-1] : 0;
maxv = this.options.ticks[i];
maxp = this.options.ticks_positions[i];
break;
}
}
if (i > 0) {
var partialPercentage = (value - minv) / (maxv - minv);
return minp + partialPercentage * (maxp - minp);
}
}
return 100 * (value - this.options.min) / (this.options.max - this.options.min);
}
},
logarithmic: {
/* Based on http://stackoverflow.com/questions/846221/logarithmic-slider */
toValue: function(percentage) {
var offset = 1 - this.options.min;
var min = Math.log(this.options.min + offset);
var max = Math.log(this.options.max + offset);
var value = Math.exp(min + (max - min) * percentage / 100) - offset;
if(Math.round(value) === max) {
return max;
}
value = this.options.min + Math.round((value - this.options.min) / this.options.step) * this.options.step;
/* Rounding to the nearest step could exceed the min or
* max, so clip to those values. */
return SliderScale.linear.getValue(value, this.options);
},
toPercentage: function(value) {
if (this.options.max === this.options.min) {
return 0;
} else {
var offset = 1 - this.options.min;
var max = Math.log(this.options.max + offset);
var min = Math.log(this.options.min + offset);
var v = Math.log(value + offset);
return 100 * (v - min) / (max - min);
}
}
}
};
/*************************************************
CONSTRUCTOR
**************************************************/
Slider = function(element, options) {
createNewSlider.call(this, element, options);
return this;
};
function createNewSlider(element, options) {
/*
The internal state object is used to store data about the current 'state' of slider.
This includes values such as the `value`, `enabled`, etc...
*/
this._state = {
value: null,
enabled: null,
offset: null,
size: null,
percentage: null,
inDrag: false,
over: false,
tickIndex: null
};
// The objects used to store the reference to the tick methods if ticks_tooltip is on
this.ticksCallbackMap = {};
this.handleCallbackMap = {};
if(typeof element === "string") {
this.element = document.querySelector(element);
} else if(element instanceof HTMLElement) {
this.element = element;
}
/*************************************************
Process Options
**************************************************/
options = options ? options : {};
var optionTypes = Object.keys(this.defaultOptions);
const isMinSet = options.hasOwnProperty('min');
const isMaxSet = options.hasOwnProperty('max');
for(var i = 0; i < optionTypes.length; i++) {
var optName = optionTypes[i];
// First check if an option was passed in via the constructor
var val = options[optName];
// If no data attrib, then check data atrributes
val = (typeof val !== 'undefined') ? val : getDataAttrib(this.element, optName);
// Finally, if nothing was specified, use the defaults
val = (val !== null) ? val : this.defaultOptions[optName];
// Set all options on the instance of the Slider
if(!this.options) {
this.options = {};
}
this.options[optName] = val;
}
this.ticksAreValid = Array.isArray(this.options.ticks) && this.options.ticks.length > 0;
// Lock to ticks only when ticks[] is defined and set
if (!this.ticksAreValid) {
this.options.lock_to_ticks = false;
}
// Check options.rtl
if(this.options.rtl==='auto'){
var computedStyle = window.getComputedStyle(this.element);
if (computedStyle != null) {
this.options.rtl = computedStyle.direction === 'rtl';
} else {
// Fix for Firefox bug in versions less than 62:
// https://bugzilla.mozilla.org/show_bug.cgi?id=548397
// https://bugzilla.mozilla.org/show_bug.cgi?id=1467722
this.options.rtl = this.element.style.direction === 'rtl';
}
}
/*
Validate `tooltip_position` against 'orientation`
- if `tooltip_position` is incompatible with orientation, swith it to a default compatible with specified `orientation`
-- default for "vertical" -> "right", "left" if rtl
-- default for "horizontal" -> "top"
*/
if(this.options.orientation === "vertical" && (this.options.tooltip_position === "top" || this.options.tooltip_position === "bottom")) {
if(this.options.rtl) {
this.options.tooltip_position = "left";
}else{
this.options.tooltip_position = "right";
}
}
else if(this.options.orientation === "horizontal" && (this.options.tooltip_position === "left" || this.options.tooltip_position === "right")) {
this.options.tooltip_position = "top";
}
function getDataAttrib(element, optName) {
var dataName = "data-slider-" + optName.replace(/_/g, '-');
var dataValString = element.getAttribute(dataName);
try {
return JSON.parse(dataValString);
}
catch(err) {
return dataValString;
}
}
/*************************************************
Create Markup
**************************************************/
var origWidth = this.element.style.width;
var updateSlider = false;
var parent = this.element.parentNode;
var sliderTrackSelection;
var sliderTrackLow, sliderTrackHigh;
var sliderMinHandle;
var sliderMaxHandle;
if (this.sliderElem) {
updateSlider = true;
} else {
/* Create elements needed for slider */
this.sliderElem = document.createElement("div");
this.sliderElem.className = "slider";
/* Create slider track elements */
var sliderTrack = document.createElement("div");
sliderTrack.className = "slider-track";
sliderTrackLow = document.createElement("div");
sliderTrackLow.className = "slider-track-low";
sliderTrackSelection = document.createElement("div");
sliderTrackSelection.className = "slider-selection";
sliderTrackHigh = document.createElement("div");
sliderTrackHigh.className = "slider-track-high";
sliderMinHandle = document.createElement("div");
sliderMinHandle.className = "slider-handle min-slider-handle";
sliderMinHandle.setAttribute('role', 'slider');
sliderMinHandle.setAttribute('aria-valuemin', this.options.min);
sliderMinHandle.setAttribute('aria-valuemax', this.options.max);
sliderMaxHandle = document.createElement("div");
sliderMaxHandle.className = "slider-handle max-slider-handle";
sliderMaxHandle.setAttribute('role', 'slider');
sliderMaxHandle.setAttribute('aria-valuemin', this.options.min);
sliderMaxHandle.setAttribute('aria-valuemax', this.options.max);
sliderTrack.appendChild(sliderTrackLow);
sliderTrack.appendChild(sliderTrackSelection);
sliderTrack.appendChild(sliderTrackHigh);
/* Create highlight range elements */
this.rangeHighlightElements = [];
const rangeHighlightsOpts = this.options.rangeHighlights;
if (Array.isArray(rangeHighlightsOpts) && rangeHighlightsOpts.length > 0) {
for (let j = 0; j < rangeHighlightsOpts.length; j++) {
var rangeHighlightElement = document.createElement("div");
const customClassString = rangeHighlightsOpts[j].class || "";
rangeHighlightElement.className = `slider-rangeHighlight slider-selection ${customClassString}`;
this.rangeHighlightElements.push(rangeHighlightElement);
sliderTrack.appendChild(rangeHighlightElement);
}
}
/* Add aria-labelledby to handle's */
var isLabelledbyArray = Array.isArray(this.options.labelledby);
if (isLabelledbyArray && this.options.labelledby[0]) {
sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby[0]);
}
if (isLabelledbyArray && this.options.labelledby[1]) {
sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby[1]);
}
if (!isLabelledbyArray && this.options.labelledby) {
sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby);
sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby);
}
/* Create ticks */
this.ticks = [];
if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
this.ticksContainer = document.createElement('div');
this.ticksContainer.className = 'slider-tick-container';
for (i = 0; i < this.options.ticks.length; i++) {
var tick = document.createElement('div');
tick.className = 'slider-tick';
if (this.options.ticks_tooltip) {
var tickListenerReference = this._addTickListener();
var enterCallback = tickListenerReference.addMouseEnter(this, tick, i);
var leaveCallback = tickListenerReference.addMouseLeave(this, tick);
this.ticksCallbackMap[i] = {
mouseEnter: enterCallback,
mouseLeave: leaveCallback
};
}
this.ticks.push(tick);
this.ticksContainer.appendChild(tick);
}
sliderTrackSelection.className += " tick-slider-selection";
}
this.tickLabels = [];
if (Array.isArray(this.options.ticks_labels) && this.options.ticks_labels.length > 0) {
this.tickLabelContainer = document.createElement('div');
this.tickLabelContainer.className = 'slider-tick-label-container';
for (i = 0; i < this.options.ticks_labels.length; i++) {
var label = document.createElement('div');
var noTickPositionsSpecified = this.options.ticks_positions.length === 0;
var tickLabelsIndex = (this.options.reversed && noTickPositionsSpecified) ? (this.options.ticks_labels.length - (i + 1)) : i;
label.className = 'slider-tick-label';
label.innerHTML = this.options.ticks_labels[tickLabelsIndex];
this.tickLabels.push(label);
this.tickLabelContainer.appendChild(label);
}
}
const createAndAppendTooltipSubElements = function(tooltipElem) {
var arrow = document.createElement("div");
arrow.className = "tooltip-arrow";
var inner = document.createElement("div");
inner.className = "tooltip-inner";
tooltipElem.appendChild(arrow);
tooltipElem.appendChild(inner);
};
/* Create tooltip elements */
const sliderTooltip = document.createElement("div");
sliderTooltip.className = "tooltip tooltip-main";
sliderTooltip.setAttribute('role', 'presentation');
createAndAppendTooltipSubElements(sliderTooltip);
const sliderTooltipMin = document.createElement("div");
sliderTooltipMin.className = "tooltip tooltip-min";
sliderTooltipMin.setAttribute('role', 'presentation');
createAndAppendTooltipSubElements(sliderTooltipMin);
const sliderTooltipMax = document.createElement("div");
sliderTooltipMax.className = "tooltip tooltip-max";
sliderTooltipMax.setAttribute('role', 'presentation');
createAndAppendTooltipSubElements(sliderTooltipMax);
/* Append components to sliderElem */
this.sliderElem.appendChild(sliderTrack);
this.sliderElem.appendChild(sliderTooltip);
this.sliderElem.appendChild(sliderTooltipMin);
this.sliderElem.appendChild(sliderTooltipMax);
if (this.tickLabelContainer) {
this.sliderElem.appendChild(this.tickLabelContainer);
}
if (this.ticksContainer) {
this.sliderElem.appendChild(this.ticksContainer);
}
this.sliderElem.appendChild(sliderMinHandle);
this.sliderElem.appendChild(sliderMaxHandle);
/* Append slider element to parent container, right before the original <input> element */
parent.insertBefore(this.sliderElem, this.element);
/* Hide original <input> element */
this.element.style.display = "none";
}
/* If JQuery exists, cache JQ references */
if($) {
this.$element = $(this.element);
this.$sliderElem = $(this.sliderElem);
}
/*************************************************
Setup
**************************************************/
this.eventToCallbackMap = {};
this.sliderElem.id = this.options.id;
this.touchCapable = 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);
this.touchX = 0;
this.touchY = 0;
this.tooltip = this.sliderElem.querySelector('.tooltip-main');
this.tooltipInner = this.tooltip.querySelector('.tooltip-inner');
this.tooltip_min = this.sliderElem.querySelector('.tooltip-min');
this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner');
this.tooltip_max = this.sliderElem.querySelector('.tooltip-max');
this.tooltipInner_max= this.tooltip_max.querySelector('.tooltip-inner');
if (SliderScale[this.options.scale]) {
this.options.scale = SliderScale[this.options.scale];
}
if (updateSlider === true) {
// Reset classes
this._removeClass(this.sliderElem, 'slider-horizontal');
this._removeClass(this.sliderElem, 'slider-vertical');
this._removeClass(this.sliderElem, 'slider-rtl');
this._removeClass(this.tooltip, 'hide');
this._removeClass(this.tooltip_min, 'hide');
this._removeClass(this.tooltip_max, 'hide');
// Undo existing inline styles for track
["left", "right", "top", "width", "height"].forEach(function(prop) {
this._removeProperty(this.trackLow, prop);
this._removeProperty(this.trackSelection, prop);
this._removeProperty(this.trackHigh, prop);
}, this);
// Undo inline styles on handles
[this.handle1, this.handle2].forEach(function(handle) {
this._removeProperty(handle, 'left');
this._removeProperty(handle, 'right');
this._removeProperty(handle, 'top');
}, this);
// Undo inline styles and classes on tooltips
[this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function(tooltip) {
this._removeProperty(tooltip, 'left');
this._removeProperty(tooltip, 'right');
this._removeProperty(tooltip, 'top');
this._removeClass(tooltip, 'right');
this._removeClass(tooltip, 'left');
this._removeClass(tooltip, 'top');
}, this);
}
if(this.options.orientation === 'vertical') {
this._addClass(this.sliderElem,'slider-vertical');
this.stylePos = 'top';
this.mousePos = 'pageY';
this.sizePos = 'offsetHeight';
} else {
this._addClass(this.sliderElem, 'slider-horizontal');
this.sliderElem.style.width = origWidth;
this.options.orientation = 'horizontal';
if(this.options.rtl) {
this.stylePos = 'right';
} else {
this.stylePos = 'left';
}
this.mousePos = 'clientX';
this.sizePos = 'offsetWidth';
}
// specific rtl class
if (this.options.rtl) {
this._addClass(this.sliderElem, 'slider-rtl');
}
this._setTooltipPosition();
/* In case ticks are specified, overwrite the min and max bounds */
if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
if (!isMaxSet) {
this.options.max = Math.max.apply(Math, this.options.ticks);
}
if (!isMinSet) {
this.options.min = Math.min.apply(Math, this.options.ticks);
}
}
if (Array.isArray(this.options.value)) {
this.options.range = true;
this._state.value = this.options.value;
}
else if (this.options.range) {
// User wants a range, but value is not an array
this._state.value = [this.options.value, this.options.max];
}
else {
this._state.value = this.options.value;
}
this.trackLow = sliderTrackLow || this.trackLow;
this.trackSelection = sliderTrackSelection || this.trackSelection;
this.trackHigh = sliderTrackHigh || this.trackHigh;
if (this.options.selection === 'none') {
this._addClass(this.trackLow, 'hide');
this._addClass(this.trackSelection, 'hide');
this._addClass(this.trackHigh, 'hide');
}
else if (this.options.selection === 'after' || this.options.selection === 'before') {
this._removeClass(this.trackLow, 'hide');
this._removeClass(this.trackSelection, 'hide');
this._removeClass(this.trackHigh, 'hide');
}
this.handle1 = sliderMinHandle || this.handle1;
this.handle2 = sliderMaxHandle || this.handle2;
if (updateSlider === true) {
// Reset classes
this._removeClass(this.handle1, 'round triangle');
this._removeClass(this.handle2, 'round triangle hide');
for (i = 0; i < this.ticks.length; i++) {
this._removeClass(this.ticks[i], 'round triangle hide');
}
}
var availableHandleModifiers = ['round', 'triangle', 'custom'];
var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1;
if (isValidHandleType) {
this._addClass(this.handle1, this.options.handle);
this._addClass(this.handle2, this.options.handle);
for (i = 0; i < this.ticks.length; i++) {
this._addClass(this.ticks[i], this.options.handle);
}
}
this._state.offset = this._offset(this.sliderElem);
this._state.size = this.sliderElem[this.sizePos];
this.setValue(this._state.value);
/******************************************
Bind Event Listeners
******************************************/
// Bind keyboard handlers
this.handle1Keydown = this._keydown.bind(this, 0);
this.handle1.addEventListener("keydown", this.handle1Keydown, false);
this.handle2Keydown = this._keydown.bind(this, 1);
this.handle2.addEventListener("keydown", this.handle2Keydown, false);
this.mousedown = this._mousedown.bind(this);
this.touchstart = this._touchstart.bind(this);
this.touchmove = this._touchmove.bind(this);
if (this.touchCapable) {
this.sliderElem.addEventListener("touchstart", this.touchstart, false);
this.sliderElem.addEventListener("touchmove", this.touchmove, false);
}
this.sliderElem.addEventListener("mousedown", this.mousedown, false);
// Bind window handlers
this.resize = this._resize.bind(this);
window.addEventListener("resize", this.resize, false);
// Bind tooltip-related handlers
if(this.options.tooltip === 'hide') {
this._addClass(this.tooltip, 'hide');
this._addClass(this.tooltip_min, 'hide');
this._addClass(this.tooltip_max, 'hide');
}
else if(this.options.tooltip === 'always') {
this._showTooltip();
this._alwaysShowTooltip = true;
}
else {
this.showTooltip = this._showTooltip.bind(this);
this.hideTooltip = this._hideTooltip.bind(this);
if (this.options.ticks_tooltip) {
var callbackHandle = this._addTickListener();
//create handle1 listeners and store references in map
var mouseEnter = callbackHandle.addMouseEnter(this, this.handle1);
var mouseLeave = callbackHandle.addMouseLeave(this, this.handle1);
this.handleCallbackMap.handle1 = {
mouseEnter: mouseEnter,
mouseLeave: mouseLeave
};
//create handle2 listeners and store references in map
mouseEnter = callbackHandle.addMouseEnter(this, this.handle2);
mouseLeave = callbackHandle.addMouseLeave(this, this.handle2);
this.handleCallbackMap.handle2 = {
mouseEnter: mouseEnter,
mouseLeave: mouseLeave
};
} else {
this.sliderElem.addEventListener("mouseenter", this.showTooltip, false);
this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false);
if (this.touchCapable) {
this.sliderElem.addEventListener("touchstart", this.showTooltip, false);
this.sliderElem.addEventListener("touchmove", this.showTooltip, false);
this.sliderElem.addEventListener("touchend", this.hideTooltip, false);
}
}
this.handle1.addEventListener("focus", this.showTooltip, false);
this.handle1.addEventListener("blur", this.hideTooltip, false);
this.handle2.addEventListener("focus", this.showTooltip, false);
this.handle2.addEventListener("blur", this.hideTooltip, false);
if (this.touchCapable) {
this.handle1.addEventListener("touchstart", this.showTooltip, false);
this.handle1.addEventListener("touchmove", this.showTooltip, false);
this.handle1.addEventListener("touchend", this.hideTooltip, false);
this.handle2.addEventListener("touchstart", this.showTooltip, false);
this.handle2.addEventListener("touchmove", this.showTooltip, false);
this.handle2.addEventListener("touchend", this.hideTooltip, false);
}
}
if(this.options.enabled) {
this.enable();
} else {
this.disable();
}
}
/*************************************************
INSTANCE PROPERTIES/METHODS
- Any methods bound to the prototype are considered
part of the plugin's `public` interface
**************************************************/
Slider.prototype = {
_init: function() {}, // NOTE: Must exist to support bridget
constructor: Slider,
defaultOptions: {
id: "",
min: 0,
max: 10,
step: 1,
precision: 0,
orientation: 'horizontal',
value: 5,
range: false,
selection: 'before',
tooltip: 'show',
tooltip_split: false,
lock_to_ticks: false,
handle: 'round',
reversed: false,
rtl: 'auto',
enabled: true,
formatter: function(val) {
if (Array.isArray(val)) {
return val[0] + " : " + val[1];
} else {
return val;
}
},
natural_arrow_keys: false,
ticks: [],
ticks_positions: [],
ticks_labels: [],
ticks_snap_bounds: 0,
ticks_tooltip: false,
scale: 'linear',
focus: false,
tooltip_position: null,
labelledby: null,
rangeHighlights: []
},
getElement: function() {
return this.sliderElem;
},
getValue: function() {
if (this.options.range) {
return this._state.value;
}
else {
return this._state.value[0];
}
},
setValue: function(val, triggerSlideEvent, triggerChangeEvent) {
if (!val) {
val = 0;
}
var oldValue = this.getValue();
this._state.value = this._validateInputValue(val);
var applyPrecision = this._applyPrecision.bind(this);
if (this.options.range) {
this._state.value[0] = applyPrecision(this._state.value[0]);
this._state.value[1] = applyPrecision(this._state.value[1]);
if (this.ticksAreValid && this.options.lock_to_ticks) {
this._state.value[0] = this.options.ticks[this._getClosestTickIndex(this._state.value[0])];
this._state.value[1] = this.options.ticks[this._getClosestTickIndex(this._state.value[1])];
}
this._state.value[0] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[0]));
this._state.value[1] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[1]));
}
else {
this._state.value = applyPrecision(this._state.value);
if (this.ticksAreValid && this.options.lock_to_ticks) {
this._state.value = this.options.ticks[this._getClosestTickIndex(this._state.value)];
}
this._state.value = [ Math.max(this.options.min, Math.min(this.options.max, this._state.value))];
this._addClass(this.handle2, 'hide');
if (this.options.selection === 'after') {
this._state.value[1] = this.options.max;
} else {
this._state.value[1] = this.options.min;
}
}
// Determine which ticks the handle(s) are set at (if applicable)
this._setTickIndex();
if (this.options.max > this.options.min) {
this._state.percentage = [
this._toPercentage(this._state.value[0]),
this._toPercentage(this._state.value[1]),
this.options.step * 100 / (this.options.max - this.options.min)
];
} else {
this._state.percentage = [0, 0, 100];
}
this._layout();
var newValue = this.options.range ? this._state.value : this._state.value[0];
this._setDataVal(newValue);
if(triggerSlideEvent === true) {
this._trigger('slide', newValue);
}
var hasChanged = false;
if (Array.isArray(newValue)) {
hasChanged = oldValue[0] !== newValue[0] || oldValue[1] !== newValue[1];
}
else {
hasChanged = oldValue !== newValue;
}
if( hasChanged && (triggerChangeEvent === true) ) {
this._trigger('change', {
oldValue: oldValue,
newValue: newValue
});
}
return this;
},
destroy: function(){
// Remove event handlers on slider elements
this._removeSliderEventHandlers();
// Remove the slider from the DOM
this.sliderElem.parentNode.removeChild(this.sliderElem);
/* Show original <input> element */
this.element.style.display = "";
// Clear out custom event bindings
this._cleanUpEventCallbacksMap();
// Remove data values
this.element.removeAttribute("data");
// Remove JQuery handlers/data
if($) {
this._unbindJQueryEventHandlers();
if (autoRegisterNamespace === NAMESPACE_MAIN) {
this.$element.removeData(autoRegisterNamespace);
}
this.$element.removeData(NAMESPACE_ALTERNATE);
}
},
disable: function() {
this._state.enabled = false;
this.handle1.removeAttribute("tabindex");
this.handle2.removeAttribute("tabindex");
this._addClass(this.sliderElem, 'slider-disabled');
this._trigger('slideDisabled');
return this;
},
enable: function() {
this._state.enabled = true;
this.handle1.setAttribute("tabindex", 0);
this.handle2.setAttribute("tabindex", 0);
this._removeClass(this.sliderElem, 'slider-disabled');
this._trigger('slideEnabled');
return this;
},
toggle: function() {
if(this._state.enabled) {
this.disable();
} else {
this.enable();
}
return this;
},
isEnabled: function() {
return this._state.enabled;
},
on: function(evt, callback) {
this._bindNonQueryEventHandler(evt, callback);
return this;
},
off: function(evt, callback) {
if($) {
this.$element.off(evt, callback);
this.$sliderElem.off(evt, callback);
} else {
this._unbindNonQueryEventHandler(evt, callback);
}
},
getAttribute: function(attribute) {
if(attribute) {
return this.options[attribute];
} else {
return this.options;
}
},
setAttribute: function(attribute, value) {
this.options[attribute] = value;
return this;
},
refresh: function(options) {
const currentValue = this.getValue();
this._removeSliderEventHandlers();
createNewSlider.call(this, this.element, this.options);
// Don't reset slider's value on refresh if `useCurrentValue` is true
if (options && options.useCurrentValue === true) {
this.setValue(currentValue);
}
if($) {
// Bind new instance of slider to the element
if (autoRegisterNamespace === NAMESPACE_MAIN) {
$.data(this.element, NAMESPACE_MAIN, this);
$.data(this.element, NAMESPACE_ALTERNATE, this);
}
else {
$.data(this.element, NAMESPACE_ALTERNATE, this);
}
}
return this;
},
relayout: function() {
this._resize();
return this;
},
/******************************+
HELPERS
- Any method that is not part of the public interface.
- Place it underneath this comment block and write its signature like so:
_fnName : function() {...}
********************************/
_removeTooltipListener: function(event, handler) {
this.handle1.removeEventListener(event, handler, false);
this.handle2.removeEventListener(event, handler, false);
},
_removeSliderEventHandlers: function() {
// Remove keydown event listeners
this.handle1.removeEventListener("keydown", this.handle1Keydown, false);
this.handle2.removeEventListener("keydown", this.handle2Keydown, false);
//remove the listeners from the ticks and handles if they had their own listeners
if (this.options.ticks_tooltip) {
var ticks = this.ticksContainer.getElementsByClassName('slider-tick');
for(var i = 0; i < ticks.length; i++ ){
ticks[i].removeEventListener('mouseenter', this.ticksCallbackMap[i].mouseEnter, false);
ticks[i].removeEventListener('mouseleave', this.ticksCallbackMap[i].mouseLeave, false);
}
if (this.handleCallbackMap.handle1 && this.handleCallbackMap.handle2) {
this.handle1.removeEventListener('mouseenter', this.handleCallbackMap.handle1.mouseEnter, false);
this.handle2.removeEventListener('mouseenter', this.handleCallbackMap.handle2.mouseEnter, false);
this.handle1.removeEventListener('mouseleave', this.handleCallbackMap.handle1.mouseLeave, false);
this.handle2.removeEventListener('mouseleave', this.handleCallbackMap.handle2.mouseLeave, false);
}
}
this.handleCallbackMap = null;
this.ticksCallbackMap = null;
if (this.showTooltip) {
this._removeTooltipListener("focus", this.showTooltip);
}
if (this.hideTooltip) {
this._removeTooltipListener("blur", this.hideTooltip);
}
// Remove event listeners from sliderElem
if (this.showTooltip) {
this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false);
}
if (this.hideTooltip) {
this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false);
}
this.sliderElem.removeEventListener("mousedown", this.mousedown, false);
if (this.touchCapable) {
// Remove touch event listeners from handles
if (this.showTooltip) {
this.handle1.removeEventListener("touchstart", this.showTooltip, false);
this.handle1.removeEventListener("touchmove", this.showTooltip, false);
this.handle2.removeEventListener("touchstart", this.showTooltip, false);
this.handle2.removeEventListener("touchmove", this.showTooltip, false);
}
if (this.hideTooltip) {
this.handle1.removeEventListener("touchend", this.hideTooltip, false);
this.handle2.removeEventListener("touchend", this.hideTooltip, false);
}
// Remove event listeners from sliderElem
if (this.showTooltip) {
this.sliderElem.removeEventListener("touchstart", this.showTooltip, false);
this.sliderElem.removeEventListener("touchmove", this.showTooltip, false);
}
if (this.hideTooltip) {
this.sliderElem.removeEventListener("touchend", this.hideTooltip, false);
}
this.sliderElem.removeEventListener("touchstart", this.touchstart, false);
this.sliderElem.removeEventListener("touchmove", this.touchmove, false);
}
// Remove window event listener
window.removeEventListener("resize", this.resize, false);
},
_bindNonQueryEventHandler: function(evt, callback) {
if(this.eventToCallbackMap[evt] === undefined) {
this.eventToCallbackMap[evt] = [];
}
this.eventToCallbackMap[evt].push(callback);
},
_unbindNonQueryEventHandler: function(evt, callback) {
var callbacks = this.eventToCallbackMap[evt];
if(callbacks !== undefined) {
for (var i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
callbacks.splice(i, 1);
break;
}
}
}
},
_cleanUpEventCallbacksMap: function() {
var eventNames = Object.keys(this.eventToCallbackMap);
for(var i = 0; i < eventNames.length; i++) {
var eventName = eventNames[i];
delete this.eventToCallbackMap[eventName];
}
},
_showTooltip: function() {
if (this.options.tooltip_split === false ){
this._addClass(this.tooltip, 'in');
this.tooltip_min.style.display = 'none';
this.tooltip_max.style.display = 'none';
} else {
this._addClass(this.tooltip_min, 'in');
this._addClass(this.tooltip_max, 'in');
this.tooltip.style.display = 'none';
}
this._state.over = true;
},
_hideTooltip: function() {
if (this._state.inDrag === false && this._alwaysShowTooltip !== true) {
this._removeClass(this.tooltip, 'in');
this._removeClass(this.tooltip_min, 'in');
this._removeClass(this.tooltip_max, 'in');
}
this._state.over = false;
},
_setToolTipOnMouseOver: function _setToolTipOnMouseOver(tempState){
let self = this;
var formattedTooltipVal = this.options.formatter(!tempState ? this._state.value[0]: tempState.value[0]);
var positionPercentages = !tempState ? getPositionPercentages(this._state, this.options.reversed) : getPositionPercentages(tempState, this.options.reversed);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = `${positionPercentages[0]}%`;
function getPositionPercentages(state, reversed){
if (reversed) {
return [100 - state.percentage[0], self.options.range ? 100 - state.percentage[1] : state.percentage[1]];
}
return [state.percentage[0], state.percentage[1]];
}
},
_copyState: function() {
return {
value: [ this._state.value[0], this._state.value[1] ],
enabled: this._state.enabled,
offset: this._state.offset,
size: this._state.size,
percentage: [ this._state.percentage[0], this._state.percentage[1], this._state.percentage[2] ],
inDrag: this._state.inDrag,
over: this._state.over,
// deleted or null'd keys
dragged: this._state.dragged,
keyCtrl: this._state.keyCtrl
};
},
_addTickListener: function _addTickListener() {
return {
addMouseEnter: function(reference, element, index){
var enter = function(){
let tempState = reference._copyState();
// Which handle is being hovered over?
let val = element === reference.handle1 ? tempState.value[0] : tempState.value[1];
let per;
// Setup value and percentage for tick's 'mouseenter'
if (index !== undefined) {
val = reference.options.ticks[index];
per = (reference.options.ticks_positions.length > 0 && reference.options.ticks_positions[index]) ||
reference._toPercentage(reference.options.ticks[index]);
}
else {
per = reference._toPercentage(val);
}
tempState.value[0] = val;
tempState.percentage[0] = per;
reference._setToolTipOnMouseOver(tempState);
reference._showTooltip();
};
element.addEventListener("mouseenter", enter, false);
return enter;
},
addMouseLeave: function(reference, element){
var leave = function(){
reference._hideTooltip();
};
element.addEventListener("mouseleave", leave, false);
return leave;
}
};
},
_layout: function() {
var positionPercentages;
var formattedValue;
if(this.options.reversed) {
positionPercentages = [ 100 - this._state.percentage[0], this.options.range ? 100 - this._state.percentage[1] : this._state.percentage[1]];
}
else {
positionPercentages = [ this._state.percentage[0], this._state.percentage[1] ];
}
this.handle1.style[this.stylePos] = `${positionPercentages[0]}%`;
this.handle1.setAttribute('aria-valuenow', this._state.value[0]);
formattedValue = this.options.formatter(this._state.value[0]);
if (isNaN(formattedValue)) {
this.handle1.setAttribute('aria-valuetext', formattedValue);
}
else {
this.handle1.removeAttribute('aria-valuetext');
}
this.handle2.style[this.stylePos] =`${positionPercentages[1]}%`;
this.handle2.setAttribute('aria-valuenow', this._state.value[1]);
formattedValue = this.options.formatter(this._state.value[1]);
if (isNaN(formattedValue)) {
this.handle2.setAttribute('aria-valuetext', formattedValue);
}
else {
this.handle2.removeAttribute('aria-valuetext');
}
/* Position highlight range elements */
if (this.rangeHighlightElements.length > 0 && Array.isArray(this.options.rangeHighlights) && this.options.rangeHighlights.length > 0) {
for (let i = 0; i < this.options.rangeHighlights.length; i++) {
var startPercent = this._toPercentage(this.options.rangeHighlights[i].start);
var endPercent = this._toPercentage(this.options.rangeHighlights[i].end);
if (this.options.reversed) {
var sp = 100-endPercent;
endPercent = 100-startPercent;
startPercent = sp;
}
var currentRange = this._createHighlightRange(startPercent, endPercent);
if (currentRange) {
if (this.options.orientation === 'vertical') {
this.rangeHighlightElements[i].style.top = `${currentRange.start}%`;
this.rangeHighlightElements[i].style.height = `${currentRange.size}%`;
} else {
if(this.options.rtl){
this.rangeHighlightElements[i].style.right = `${currentRange.start}%`;
} else {
this.rangeHighlightElements[i].style.left = `${currentRange.start}%`;
}
this.rangeHighlightElements[i].style.width = `${currentRange.size}%`;
}
} else {
this.rangeHighlightElements[i].style.display = "none";
}
}
}
/* Position ticks and labels */
if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
var styleSize = this.options.orientation === 'vertical' ? 'height' : 'width';
var styleMargin;
if( this.options.orientation === 'vertical' ){
styleMargin='marginTop';
}else {
if( this.options.rtl ){
styleMargin='marginRight';
} else {
styleMargin='marginLeft';
}
}
var labelSize = this._state.size / (this.options.ticks.length - 1);
if (this.tickLabelContainer) {
var extraMargin = 0;
if (this.options.ticks_positions.length === 0) {
if (this.options.orientation !== 'vertical') {
this.tickLabelContainer.style[styleMargin] = `${ -labelSize/2 }px`;
}
extraMargin = this.tickLabelContainer.offsetHeight;
} else {
/* Chidren are position absolute, calculate height by finding the max offsetHeight of a child */
for (i = 0 ; i < this.tickLabelContainer.childNodes.length; i++) {
if (this.tickLabelContainer.childNodes[i].offsetHeight > extraMargin) {
extraMargin = this.tickLabelContainer.childNodes[i].offsetHeight;
}
}
}
if (this.options.orientation === 'horizontal') {
this.sliderElem.style.marginBottom = `${ extraMargin }px`;
}
}
for (var i = 0; i < this.options.ticks.length; i++) {
var percentage = this.options.ticks_positions[i] || this._toPercentage(this.options.ticks[i]);
if (this.options.reversed) {
percentage = 100 - percentage;
}
this.ticks[i].style[this.stylePos] = `${ percentage }%`;
/* Set class labels to denote whether ticks are in the selection */
this._removeClass(this.ticks[i], 'in-selection');
if (!this.options.range) {
if (this.options.selection === 'after' && percentage >= positionPercentages[0]){
this._addClass(this.ticks[i], 'in-selection');
} else if (this.options.selection === 'before' && percentage <= positionPercentages[0]) {
this._addClass(this.ticks[i], 'in-selection');
}
} else if (percentage >= positionPercentages[0] && percentage <= positionPercentages[1]) {
this._addClass(this.ticks[i], 'in-selection');
}
if (this.tickLabels[i]) {
this.tickLabels[i].style[styleSize] = `${labelSize}px`;
if (this.options.orientation !== 'vertical' && this.options.ticks_positions[i] !== undefined) {
this.tickLabels[i].style.position = 'absolute';
this.tickLabels[i].style[this.stylePos] = `${percentage}%`;
this.tickLabels[i].style[styleMargin] = -labelSize/2 + 'px';
} else if (this.options.orientation === 'vertical') {
if(this.options.rtl){
this.tickLabels[i].style['marginRight'] = `${this.sliderElem.offsetWidth }px`;
}else{
this.tickLabels[i].style['marginLeft'] = `${this.sliderElem.offsetWidth }px`;
}
this.tickLabelContainer.style[styleMargin] = this.sliderElem.offsetWidth / 2 * -1 + 'px';
}
/* Set class labels to indicate tick labels are in the selection or selected */
this._removeClass(this.tickLabels[i], 'label-in-selection label-is-selection');
if (!this.options.range) {
if (this.options.selection === 'after' && percentage >= positionPercentages[0]) {
this._addClass(this.tickLabels[i], 'label-in-selection');
} else if (this.options.selection === 'before' && percentage <= positionPercentages[0]) {
this._addClass(this.tickLabels[i], 'label-in-selection');
}
if (percentage === positionPercentages[0]) {
this._addClass(this.tickLabels[i], 'label-is-selection');
}
} else if (percentage >= positionPercentages[0] && percentage <= positionPercentages[1]) {
this._addClass(this.tickLabels[i], 'label-in-selection');
if (percentage === positionPercentages[0] || positionPercentages[1]) {
this._addClass(this.tickLabels[i], 'label-is-selection');
}
}
}
}
}
var formattedTooltipVal;
if (this.options.range) {
formattedTooltipVal = this.options.formatter(this._state.value);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = `${ (positionPercentages[1] + positionPercentages[0])/2 }%`;
var innerTooltipMinText = this.options.formatter(this._state.value[0]);
this._setText(this.tooltipInner_min, innerTooltipMinText);
var innerTooltipMaxText = this.options.formatter(this._state.value[1]);
this._setText(this.tooltipInner_max, innerTooltipMaxText);
this.tooltip_min.style[this.stylePos] = `${ positionPercentages[0] }%`;
this.tooltip_max.style[this.stylePos] = `${ positionPercentages