nouislider
Version:
noUiSlider is a lightweight JavaScript range slider.
1,280 lines (1,278 loc) • 96.4 kB
JavaScript
"use strict";
export var PipsMode;
(function (PipsMode) {
PipsMode["Range"] = "range";
PipsMode["Steps"] = "steps";
PipsMode["Positions"] = "positions";
PipsMode["Count"] = "count";
PipsMode["Values"] = "values";
})(PipsMode || (PipsMode = {}));
export var PipsType;
(function (PipsType) {
PipsType[PipsType["None"] = -1] = "None";
PipsType[PipsType["NoValue"] = 0] = "NoValue";
PipsType[PipsType["LargeValue"] = 1] = "LargeValue";
PipsType[PipsType["SmallValue"] = 2] = "SmallValue";
})(PipsType || (PipsType = {}));
//region Helper Methods
function isValidFormatter(entry) {
return isValidPartialFormatter(entry) && typeof entry.from === "function";
}
function isValidPartialFormatter(entry) {
// partial formatters only need a to function and not a from function
return typeof entry === "object" && typeof entry.to === "function";
}
function removeElement(el) {
el.parentElement.removeChild(el);
}
function isSet(value) {
return value !== null && value !== undefined;
}
// Bindable version
function preventDefault(e) {
e.preventDefault();
}
// Removes duplicates from an array.
function unique(array) {
return array.filter(function (a) {
return !this[a] ? (this[a] = true) : false;
}, {});
}
// Round a value to the closest 'to'.
function closest(value, to) {
return Math.round(value / to) * to;
}
// Current position of an element relative to the document.
function offset(elem, orientation) {
var rect = elem.getBoundingClientRect();
var doc = elem.ownerDocument;
var docElem = doc.documentElement;
var pageOffset = getPageOffset(doc);
// getBoundingClientRect contains left scroll in Chrome on Android.
// I haven't found a feature detection that proves this. Worst case
// scenario on mis-match: the 'tap' feature on horizontal sliders breaks.
if (/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)) {
pageOffset.x = 0;
}
return orientation ? rect.top + pageOffset.y - docElem.clientTop : rect.left + pageOffset.x - docElem.clientLeft;
}
// Checks whether a value is numerical.
function isNumeric(a) {
return typeof a === "number" && !isNaN(a) && isFinite(a);
}
// Sets a class and removes it after [duration] ms.
function addClassFor(element, className, duration) {
if (duration > 0) {
addClass(element, className);
setTimeout(function () {
removeClass(element, className);
}, duration);
}
}
// Limits a value to 0 - 100
function limit(a) {
return Math.max(Math.min(a, 100), 0);
}
// Wraps a variable as an array, if it isn't one yet.
// Note that an input array is returned by reference!
function asArray(a) {
return Array.isArray(a) ? a : [a];
}
// Counts decimals
function countDecimals(numStr) {
numStr = String(numStr);
var pieces = numStr.split(".");
return pieces.length > 1 ? pieces[1].length : 0;
}
// http://youmightnotneedjquery.com/#add_class
function addClass(el, className) {
if (el.classList && !/\s/.test(className)) {
el.classList.add(className);
}
else {
el.className += " " + className;
}
}
// http://youmightnotneedjquery.com/#remove_class
function removeClass(el, className) {
if (el.classList && !/\s/.test(className)) {
el.classList.remove(className);
}
else {
el.className = el.className.replace(new RegExp("(^|\\b)" + className.split(" ").join("|") + "(\\b|$)", "gi"), " ");
}
}
// https://plainjs.com/javascript/attributes/adding-removing-and-testing-for-classes-9/
function hasClass(el, className) {
return el.classList ? el.classList.contains(className) : new RegExp("\\b" + className + "\\b").test(el.className);
}
// https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes
function getPageOffset(doc) {
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = (doc.compatMode || "") === "CSS1Compat";
var x = supportPageOffset
? window.pageXOffset
: isCSS1Compat
? doc.documentElement.scrollLeft
: doc.body.scrollLeft;
var y = supportPageOffset
? window.pageYOffset
: isCSS1Compat
? doc.documentElement.scrollTop
: doc.body.scrollTop;
return {
x: x,
y: y,
};
}
// we provide a function to compute constants instead
// of accessing window.* as soon as the module needs it
// so that we do not compute anything if not needed
function getActions() {
// Determine the events to bind. IE11 implements pointerEvents without
// a prefix, which breaks compatibility with the IE10 implementation.
return window.navigator.pointerEnabled
? {
start: "pointerdown",
move: "pointermove",
end: "pointerup",
}
: window.navigator.msPointerEnabled
? {
start: "MSPointerDown",
move: "MSPointerMove",
end: "MSPointerUp",
}
: {
start: "mousedown touchstart",
move: "mousemove touchmove",
end: "mouseup touchend",
};
}
// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
// Issue #785
function getSupportsPassive() {
var supportsPassive = false;
/* eslint-disable */
try {
var opts = Object.defineProperty({}, "passive", {
get: function () {
supportsPassive = true;
},
});
// @ts-ignore
window.addEventListener("test", null, opts);
}
catch (e) { }
/* eslint-enable */
return supportsPassive;
}
function getSupportsTouchActionNone() {
return window.CSS && CSS.supports && CSS.supports("touch-action", "none");
}
//endregion
//region Range Calculation
// Determine the size of a sub-range in relation to a full range.
function subRangeRatio(pa, pb) {
return 100 / (pb - pa);
}
// (percentage) How many percent is this value of this range?
function fromPercentage(range, value, startRange) {
return (value * 100) / (range[startRange + 1] - range[startRange]);
}
// (percentage) Where is this value on this range?
function toPercentage(range, value) {
return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0], 0);
}
// (value) How much is this percentage on this range?
function isPercentage(range, value) {
return (value * (range[1] - range[0])) / 100 + range[0];
}
function getJ(value, arr) {
var j = 1;
while (value >= arr[j]) {
j += 1;
}
return j;
}
// (percentage) Input a value, find where, on a scale of 0-100, it applies.
function toStepping(xVal, xPct, value) {
if (value >= xVal.slice(-1)[0]) {
return 100;
}
var j = getJ(value, xVal);
var va = xVal[j - 1];
var vb = xVal[j];
var pa = xPct[j - 1];
var pb = xPct[j];
return pa + toPercentage([va, vb], value) / subRangeRatio(pa, pb);
}
// (value) Input a percentage, find where it is on the specified range.
function fromStepping(xVal, xPct, value) {
// There is no range group that fits 100
if (value >= 100) {
return xVal.slice(-1)[0];
}
var j = getJ(value, xPct);
var va = xVal[j - 1];
var vb = xVal[j];
var pa = xPct[j - 1];
var pb = xPct[j];
return isPercentage([va, vb], (value - pa) * subRangeRatio(pa, pb));
}
// (percentage) Get the step that applies at a certain value.
function getStep(xPct, xSteps, snap, value) {
if (value === 100) {
return value;
}
var j = getJ(value, xPct);
var a = xPct[j - 1];
var b = xPct[j];
// If 'snap' is set, steps are used as fixed points on the slider.
if (snap) {
// Find the closest position, a or b.
if (value - a > (b - a) / 2) {
return b;
}
return a;
}
if (!xSteps[j - 1]) {
return value;
}
return xPct[j - 1] + closest(value - xPct[j - 1], xSteps[j - 1]);
}
//endregion
//region Spectrum
var Spectrum = /** @class */ (function () {
function Spectrum(entry, snap, singleStep) {
this.xPct = [];
this.xVal = [];
this.xSteps = [];
this.xNumSteps = [];
this.xHighestCompleteStep = [];
this.xSteps = [singleStep || false];
this.xNumSteps = [false];
this.snap = snap;
var index;
var ordered = [];
// Map the object keys to an array.
Object.keys(entry).forEach(function (index) {
ordered.push([asArray(entry[index]), index]);
});
// Sort all entries by value (numeric sort).
ordered.sort(function (a, b) {
return a[0][0] - b[0][0];
});
// Convert all entries to subranges.
for (index = 0; index < ordered.length; index++) {
this.handleEntryPoint(ordered[index][1], ordered[index][0]);
}
// Store the actual step values.
// xSteps is sorted in the same order as xPct and xVal.
this.xNumSteps = this.xSteps.slice(0);
// Convert all numeric steps to the percentage of the subrange they represent.
for (index = 0; index < this.xNumSteps.length; index++) {
this.handleStepPoint(index, this.xNumSteps[index]);
}
}
Spectrum.prototype.getDistance = function (value) {
var distances = [];
for (var index = 0; index < this.xNumSteps.length - 1; index++) {
distances[index] = fromPercentage(this.xVal, value, index);
}
return distances;
};
// Calculate the percentual distance over the whole scale of ranges.
// direction: 0 = backwards / 1 = forwards
Spectrum.prototype.getAbsoluteDistance = function (value, distances, direction) {
var xPct_index = 0;
// Calculate range where to start calculation
if (value < this.xPct[this.xPct.length - 1]) {
while (value > this.xPct[xPct_index + 1]) {
xPct_index++;
}
}
else if (value === this.xPct[this.xPct.length - 1]) {
xPct_index = this.xPct.length - 2;
}
// If looking backwards and the value is exactly at a range separator then look one range further
if (!direction && value === this.xPct[xPct_index + 1]) {
xPct_index++;
}
if (distances === null) {
distances = [];
}
var start_factor;
var rest_factor = 1;
var rest_rel_distance = distances[xPct_index];
var range_pct = 0;
var rel_range_distance = 0;
var abs_distance_counter = 0;
var range_counter = 0;
// Calculate what part of the start range the value is
if (direction) {
start_factor = (value - this.xPct[xPct_index]) / (this.xPct[xPct_index + 1] - this.xPct[xPct_index]);
}
else {
start_factor = (this.xPct[xPct_index + 1] - value) / (this.xPct[xPct_index + 1] - this.xPct[xPct_index]);
}
// Do until the complete distance across ranges is calculated
while (rest_rel_distance > 0) {
// Calculate the percentage of total range
range_pct = this.xPct[xPct_index + 1 + range_counter] - this.xPct[xPct_index + range_counter];
// Detect if the margin, padding or limit is larger then the current range and calculate
if (distances[xPct_index + range_counter] * rest_factor + 100 - start_factor * 100 > 100) {
// If larger then take the percentual distance of the whole range
rel_range_distance = range_pct * start_factor;
// Rest factor of relative percentual distance still to be calculated
rest_factor = (rest_rel_distance - 100 * start_factor) / distances[xPct_index + range_counter];
// Set start factor to 1 as for next range it does not apply.
start_factor = 1;
}
else {
// If smaller or equal then take the percentual distance of the calculate percentual part of that range
rel_range_distance = ((distances[xPct_index + range_counter] * range_pct) / 100) * rest_factor;
// No rest left as the rest fits in current range
rest_factor = 0;
}
if (direction) {
abs_distance_counter = abs_distance_counter - rel_range_distance;
// Limit range to first range when distance becomes outside of minimum range
if (this.xPct.length + range_counter >= 1) {
range_counter--;
}
}
else {
abs_distance_counter = abs_distance_counter + rel_range_distance;
// Limit range to last range when distance becomes outside of maximum range
if (this.xPct.length - range_counter >= 1) {
range_counter++;
}
}
// Rest of relative percentual distance still to be calculated
rest_rel_distance = distances[xPct_index + range_counter] * rest_factor;
}
return value + abs_distance_counter;
};
Spectrum.prototype.toStepping = function (value) {
value = toStepping(this.xVal, this.xPct, value);
return value;
};
Spectrum.prototype.fromStepping = function (value) {
return fromStepping(this.xVal, this.xPct, value);
};
Spectrum.prototype.getStep = function (value) {
value = getStep(this.xPct, this.xSteps, this.snap, value);
return value;
};
Spectrum.prototype.getDefaultStep = function (value, isDown, size) {
var j = getJ(value, this.xPct);
// When at the top or stepping down, look at the previous sub-range
if (value === 100 || (isDown && value === this.xPct[j - 1])) {
j = Math.max(j - 1, 1);
}
return (this.xVal[j] - this.xVal[j - 1]) / size;
};
Spectrum.prototype.getNearbySteps = function (value) {
var j = getJ(value, this.xPct);
return {
stepBefore: {
startValue: this.xVal[j - 2],
step: this.xNumSteps[j - 2],
highestStep: this.xHighestCompleteStep[j - 2],
},
thisStep: {
startValue: this.xVal[j - 1],
step: this.xNumSteps[j - 1],
highestStep: this.xHighestCompleteStep[j - 1],
},
stepAfter: {
startValue: this.xVal[j],
step: this.xNumSteps[j],
highestStep: this.xHighestCompleteStep[j],
},
};
};
Spectrum.prototype.countStepDecimals = function () {
var stepDecimals = this.xNumSteps.map(countDecimals);
return Math.max.apply(null, stepDecimals);
};
Spectrum.prototype.hasNoSize = function () {
return this.xVal[0] === this.xVal[this.xVal.length - 1];
};
// Outside testing
Spectrum.prototype.convert = function (value) {
return this.getStep(this.toStepping(value));
};
Spectrum.prototype.handleEntryPoint = function (index, value) {
var percentage;
// Covert min/max syntax to 0 and 100.
if (index === "min") {
percentage = 0;
}
else if (index === "max") {
percentage = 100;
}
else {
percentage = parseFloat(index);
}
// Check for correct input.
if (!isNumeric(percentage) || !isNumeric(value[0])) {
throw new Error("noUiSlider: 'range' value isn't numeric.");
}
// Store values.
this.xPct.push(percentage);
this.xVal.push(value[0]);
var value1 = Number(value[1]);
// NaN will evaluate to false too, but to keep
// logging clear, set step explicitly. Make sure
// not to override the 'step' setting with false.
if (!percentage) {
if (!isNaN(value1)) {
this.xSteps[0] = value1;
}
}
else {
this.xSteps.push(isNaN(value1) ? false : value1);
}
this.xHighestCompleteStep.push(0);
};
Spectrum.prototype.handleStepPoint = function (i, n) {
// Ignore 'false' stepping.
if (!n) {
return;
}
// Step over zero-length ranges (#948);
if (this.xVal[i] === this.xVal[i + 1]) {
this.xSteps[i] = this.xHighestCompleteStep[i] = this.xVal[i];
return;
}
// Factor to range ratio
this.xSteps[i] =
fromPercentage([this.xVal[i], this.xVal[i + 1]], n, 0) / subRangeRatio(this.xPct[i], this.xPct[i + 1]);
var totalSteps = (this.xVal[i + 1] - this.xVal[i]) / this.xNumSteps[i];
var highestStep = Math.ceil(Number(totalSteps.toFixed(3)) - 1);
var step = this.xVal[i] + this.xNumSteps[i] * highestStep;
this.xHighestCompleteStep[i] = step;
};
return Spectrum;
}());
//endregion
//region Options
/* Every input option is tested and parsed. This will prevent
endless validation in internal methods. These tests are
structured with an item for every option available. An
option can be marked as required by setting the 'r' flag.
The testing function is provided with three arguments:
- The provided value for the option;
- A reference to the options object;
- The name for the option;
The testing function returns false when an error is detected,
or true when everything is OK. It can also modify the option
object, to make sure all values can be correctly looped elsewhere. */
//region Defaults
var defaultFormatter = {
to: function (value) {
return value === undefined ? "" : value.toFixed(2);
},
from: Number,
};
var cssClasses = {
target: "target",
base: "base",
origin: "origin",
handle: "handle",
handleLower: "handle-lower",
handleUpper: "handle-upper",
touchArea: "touch-area",
horizontal: "horizontal",
vertical: "vertical",
background: "background",
connect: "connect",
connects: "connects",
ltr: "ltr",
rtl: "rtl",
textDirectionLtr: "txt-dir-ltr",
textDirectionRtl: "txt-dir-rtl",
draggable: "draggable",
drag: "state-drag",
tap: "state-tap",
active: "active",
tooltip: "tooltip",
pips: "pips",
pipsHorizontal: "pips-horizontal",
pipsVertical: "pips-vertical",
marker: "marker",
markerHorizontal: "marker-horizontal",
markerVertical: "marker-vertical",
markerNormal: "marker-normal",
markerLarge: "marker-large",
markerSub: "marker-sub",
value: "value",
valueHorizontal: "value-horizontal",
valueVertical: "value-vertical",
valueNormal: "value-normal",
valueLarge: "value-large",
valueSub: "value-sub",
};
// Namespaces of internal event listeners
var INTERNAL_EVENT_NS = {
tooltips: ".__tooltips",
aria: ".__aria",
};
//endregion
function testStep(parsed, entry) {
if (!isNumeric(entry)) {
throw new Error("noUiSlider: 'step' is not numeric.");
}
// The step option can still be used to set stepping
// for linear sliders. Overwritten if set in 'range'.
parsed.singleStep = entry;
}
function testKeyboardPageMultiplier(parsed, entry) {
if (!isNumeric(entry)) {
throw new Error("noUiSlider: 'keyboardPageMultiplier' is not numeric.");
}
parsed.keyboardPageMultiplier = entry;
}
function testKeyboardMultiplier(parsed, entry) {
if (!isNumeric(entry)) {
throw new Error("noUiSlider: 'keyboardMultiplier' is not numeric.");
}
parsed.keyboardMultiplier = entry;
}
function testKeyboardDefaultStep(parsed, entry) {
if (!isNumeric(entry)) {
throw new Error("noUiSlider: 'keyboardDefaultStep' is not numeric.");
}
parsed.keyboardDefaultStep = entry;
}
function testRange(parsed, entry) {
// Filter incorrect input.
if (typeof entry !== "object" || Array.isArray(entry)) {
throw new Error("noUiSlider: 'range' is not an object.");
}
// Catch missing start or end.
if (entry.min === undefined || entry.max === undefined) {
throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");
}
parsed.spectrum = new Spectrum(entry, parsed.snap || false, parsed.singleStep);
}
function testStart(parsed, entry) {
entry = asArray(entry);
// Validate input. Values aren't tested, as the public .val method
// will always provide a valid location.
if (!Array.isArray(entry) || !entry.length) {
throw new Error("noUiSlider: 'start' option is incorrect.");
}
// Store the number of handles.
parsed.handles = entry.length;
// When the slider is initialized, the .val method will
// be called with the start options.
parsed.start = entry;
}
function testSnap(parsed, entry) {
if (typeof entry !== "boolean") {
throw new Error("noUiSlider: 'snap' option must be a boolean.");
}
// Enforce 100% stepping within subranges.
parsed.snap = entry;
}
function testAnimate(parsed, entry) {
if (typeof entry !== "boolean") {
throw new Error("noUiSlider: 'animate' option must be a boolean.");
}
// Enforce 100% stepping within subranges.
parsed.animate = entry;
}
function testAnimationDuration(parsed, entry) {
if (typeof entry !== "number") {
throw new Error("noUiSlider: 'animationDuration' option must be a number.");
}
parsed.animationDuration = entry;
}
function testConnect(parsed, entry) {
var connect = [false];
var i;
// Map legacy options
if (entry === "lower") {
entry = [true, false];
}
else if (entry === "upper") {
entry = [false, true];
}
// Handle boolean options
if (entry === true || entry === false) {
for (i = 1; i < parsed.handles; i++) {
connect.push(entry);
}
connect.push(false);
}
// Reject invalid input
else if (!Array.isArray(entry) || !entry.length || entry.length !== parsed.handles + 1) {
throw new Error("noUiSlider: 'connect' option doesn't match handle count.");
}
else {
connect = entry;
}
parsed.connect = connect;
}
function testOrientation(parsed, entry) {
// Set orientation to an a numerical value for easy
// array selection.
switch (entry) {
case "horizontal":
parsed.ort = 0;
break;
case "vertical":
parsed.ort = 1;
break;
default:
throw new Error("noUiSlider: 'orientation' option is invalid.");
}
}
function testMargin(parsed, entry) {
if (!isNumeric(entry)) {
throw new Error("noUiSlider: 'margin' option must be numeric.");
}
// Issue #582
if (entry === 0) {
return;
}
parsed.margin = parsed.spectrum.getDistance(entry);
}
function testLimit(parsed, entry) {
if (!isNumeric(entry)) {
throw new Error("noUiSlider: 'limit' option must be numeric.");
}
parsed.limit = parsed.spectrum.getDistance(entry);
if (!parsed.limit || parsed.handles < 2) {
throw new Error("noUiSlider: 'limit' option is only supported on linear sliders with 2 or more handles.");
}
}
function testPadding(parsed, entry) {
var index;
if (!isNumeric(entry) && !Array.isArray(entry)) {
throw new Error("noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers.");
}
if (Array.isArray(entry) && !(entry.length === 2 || isNumeric(entry[0]) || isNumeric(entry[1]))) {
throw new Error("noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers.");
}
if (entry === 0) {
return;
}
if (!Array.isArray(entry)) {
entry = [entry, entry];
}
// 'getDistance' returns false for invalid values.
parsed.padding = [parsed.spectrum.getDistance(entry[0]), parsed.spectrum.getDistance(entry[1])];
for (index = 0; index < parsed.spectrum.xNumSteps.length - 1; index++) {
// last "range" can't contain step size as it is purely an endpoint.
if (parsed.padding[0][index] < 0 || parsed.padding[1][index] < 0) {
throw new Error("noUiSlider: 'padding' option must be a positive number(s).");
}
}
var totalPadding = entry[0] + entry[1];
var firstValue = parsed.spectrum.xVal[0];
var lastValue = parsed.spectrum.xVal[parsed.spectrum.xVal.length - 1];
if (totalPadding / (lastValue - firstValue) > 1) {
throw new Error("noUiSlider: 'padding' option must not exceed 100% of the range.");
}
}
function testDirection(parsed, entry) {
// Set direction as a numerical value for easy parsing.
// Invert connection for RTL sliders, so that the proper
// handles get the connect/background classes.
switch (entry) {
case "ltr":
parsed.dir = 0;
break;
case "rtl":
parsed.dir = 1;
break;
default:
throw new Error("noUiSlider: 'direction' option was not recognized.");
}
}
function testBehaviour(parsed, entry) {
// Make sure the input is a string.
if (typeof entry !== "string") {
throw new Error("noUiSlider: 'behaviour' must be a string containing options.");
}
// Check if the string contains any keywords.
// None are required.
var tap = entry.indexOf("tap") >= 0;
var drag = entry.indexOf("drag") >= 0;
var fixed = entry.indexOf("fixed") >= 0;
var snap = entry.indexOf("snap") >= 0;
var hover = entry.indexOf("hover") >= 0;
var unconstrained = entry.indexOf("unconstrained") >= 0;
var invertConnects = entry.indexOf("invert-connects") >= 0;
var dragAll = entry.indexOf("drag-all") >= 0;
var smoothSteps = entry.indexOf("smooth-steps") >= 0;
if (fixed) {
if (parsed.handles !== 2) {
throw new Error("noUiSlider: 'fixed' behaviour must be used with 2 handles");
}
// Use margin to enforce fixed state
testMargin(parsed, parsed.start[1] - parsed.start[0]);
}
if (invertConnects && parsed.handles !== 2) {
throw new Error("noUiSlider: 'invert-connects' behaviour must be used with 2 handles");
}
if (unconstrained && (parsed.margin || parsed.limit)) {
throw new Error("noUiSlider: 'unconstrained' behaviour cannot be used with margin or limit");
}
parsed.events = {
tap: tap || snap,
drag: drag,
dragAll: dragAll,
smoothSteps: smoothSteps,
fixed: fixed,
snap: snap,
hover: hover,
unconstrained: unconstrained,
invertConnects: invertConnects,
};
}
function testTooltips(parsed, entry) {
if (entry === false) {
return;
}
if (entry === true || isValidPartialFormatter(entry)) {
parsed.tooltips = [];
for (var i = 0; i < parsed.handles; i++) {
parsed.tooltips.push(entry);
}
}
else {
entry = asArray(entry);
if (entry.length !== parsed.handles) {
throw new Error("noUiSlider: must pass a formatter for all handles.");
}
entry.forEach(function (formatter) {
if (typeof formatter !== "boolean" && !isValidPartialFormatter(formatter)) {
throw new Error("noUiSlider: 'tooltips' must be passed a formatter or 'false'.");
}
});
parsed.tooltips = entry;
}
}
function testHandleAttributes(parsed, entry) {
if (entry.length !== parsed.handles) {
throw new Error("noUiSlider: must pass a attributes for all handles.");
}
parsed.handleAttributes = entry;
}
function testAriaFormat(parsed, entry) {
if (!isValidPartialFormatter(entry)) {
throw new Error("noUiSlider: 'ariaFormat' requires 'to' method.");
}
parsed.ariaFormat = entry;
}
function testFormat(parsed, entry) {
if (!isValidFormatter(entry)) {
throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.");
}
parsed.format = entry;
}
function testKeyboardSupport(parsed, entry) {
if (typeof entry !== "boolean") {
throw new Error("noUiSlider: 'keyboardSupport' option must be a boolean.");
}
parsed.keyboardSupport = entry;
}
function testDocumentElement(parsed, entry) {
// This is an advanced option. Passed values are used without validation.
parsed.documentElement = entry;
}
function testCssPrefix(parsed, entry) {
if (typeof entry !== "string" && entry !== false) {
throw new Error("noUiSlider: 'cssPrefix' must be a string or `false`.");
}
parsed.cssPrefix = entry;
}
function testCssClasses(parsed, entry) {
if (typeof entry !== "object") {
throw new Error("noUiSlider: 'cssClasses' must be an object.");
}
if (typeof parsed.cssPrefix === "string") {
parsed.cssClasses = {};
Object.keys(entry).forEach(function (key) {
parsed.cssClasses[key] = parsed.cssPrefix + entry[key];
});
}
else {
parsed.cssClasses = entry;
}
}
// Test all developer settings and parse to assumption-safe values.
function testOptions(options) {
// To prove a fix for #537, freeze options here.
// If the object is modified, an error will be thrown.
// Object.freeze(options);
var parsed = {
margin: null,
limit: null,
padding: null,
animate: true,
animationDuration: 300,
ariaFormat: defaultFormatter,
format: defaultFormatter,
};
// Tests are executed in the order they are presented here.
var tests = {
step: { r: false, t: testStep },
keyboardPageMultiplier: { r: false, t: testKeyboardPageMultiplier },
keyboardMultiplier: { r: false, t: testKeyboardMultiplier },
keyboardDefaultStep: { r: false, t: testKeyboardDefaultStep },
start: { r: true, t: testStart },
connect: { r: true, t: testConnect },
direction: { r: true, t: testDirection },
snap: { r: false, t: testSnap },
animate: { r: false, t: testAnimate },
animationDuration: { r: false, t: testAnimationDuration },
range: { r: true, t: testRange },
orientation: { r: false, t: testOrientation },
margin: { r: false, t: testMargin },
limit: { r: false, t: testLimit },
padding: { r: false, t: testPadding },
behaviour: { r: true, t: testBehaviour },
ariaFormat: { r: false, t: testAriaFormat },
format: { r: false, t: testFormat },
tooltips: { r: false, t: testTooltips },
keyboardSupport: { r: true, t: testKeyboardSupport },
documentElement: { r: false, t: testDocumentElement },
cssPrefix: { r: true, t: testCssPrefix },
cssClasses: { r: true, t: testCssClasses },
handleAttributes: { r: false, t: testHandleAttributes },
};
var defaults = {
connect: false,
direction: "ltr",
behaviour: "tap",
orientation: "horizontal",
keyboardSupport: true,
cssPrefix: "noUi-",
cssClasses: cssClasses,
keyboardPageMultiplier: 5,
keyboardMultiplier: 1,
keyboardDefaultStep: 10,
};
// AriaFormat defaults to regular format, if any.
if (options.format && !options.ariaFormat) {
options.ariaFormat = options.format;
}
// Run all options through a testing mechanism to ensure correct
// input. It should be noted that options might get modified to
// be handled properly. E.g. wrapping integers in arrays.
Object.keys(tests).forEach(function (name) {
// If the option isn't set, but it is required, throw an error.
if (!isSet(options[name]) && defaults[name] === undefined) {
if (tests[name].r) {
throw new Error("noUiSlider: '" + name + "' is required.");
}
return;
}
tests[name].t(parsed, !isSet(options[name]) ? defaults[name] : options[name]);
});
// Forward pips options
parsed.pips = options.pips;
// All recent browsers accept unprefixed transform.
// We need -ms- for IE9 and -webkit- for older Android;
// Assume use of -webkit- if unprefixed and -ms- are not supported.
// https://caniuse.com/#feat=transforms2d
var d = document.createElement("div");
var msPrefix = d.style.msTransform !== undefined;
var noPrefix = d.style.transform !== undefined;
parsed.transformRule = noPrefix ? "transform" : msPrefix ? "msTransform" : "webkitTransform";
// Pips don't move, so we can place them using left/top.
var styles = [
["left", "top"],
["right", "bottom"],
];
parsed.style = styles[parsed.dir][parsed.ort];
return parsed;
}
//endregion
function scope(target, options, originalOptions) {
var actions = getActions();
var supportsTouchActionNone = getSupportsTouchActionNone();
var supportsPassive = supportsTouchActionNone && getSupportsPassive();
// All variables local to 'scope' are prefixed with 'scope_'
// Slider DOM Nodes
var scope_Target = target;
var scope_Base;
var scope_ConnectBase;
var scope_Handles;
var scope_Connects;
var scope_Pips;
var scope_Tooltips;
// Slider state values
var scope_Spectrum = options.spectrum;
var scope_Values = [];
var scope_Locations = [];
var scope_HandleNumbers = [];
var scope_ActiveHandlesCount = 0;
var scope_Events = {};
var scope_ConnectsInverted = false;
// Document Nodes
var scope_Document = target.ownerDocument;
var scope_DocumentElement = options.documentElement || scope_Document.documentElement;
var scope_Body = scope_Document.body;
// For horizontal sliders in standard ltr documents,
// make .noUi-origin overflow to the left so the document doesn't scroll.
var scope_DirOffset = scope_Document.dir === "rtl" || options.ort === 1 ? 0 : 100;
// Creates a node, adds it to target, returns the new node.
function addNodeTo(addTarget, className) {
var div = scope_Document.createElement("div");
if (className) {
addClass(div, className);
}
addTarget.appendChild(div);
return div;
}
// Append a origin to the base
function addOrigin(base, handleNumber) {
var origin = addNodeTo(base, options.cssClasses.origin);
var handle = addNodeTo(origin, options.cssClasses.handle);
addNodeTo(handle, options.cssClasses.touchArea);
handle.setAttribute("data-handle", String(handleNumber));
if (options.keyboardSupport) {
// https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
// 0 = focusable and reachable
handle.setAttribute("tabindex", "0");
handle.addEventListener("keydown", function (event) {
return eventKeydown(event, handleNumber);
});
}
if (options.handleAttributes !== undefined) {
var attributes_1 = options.handleAttributes[handleNumber];
Object.keys(attributes_1).forEach(function (attribute) {
handle.setAttribute(attribute, attributes_1[attribute]);
});
}
handle.setAttribute("role", "slider");
handle.setAttribute("aria-orientation", options.ort ? "vertical" : "horizontal");
if (handleNumber === 0) {
addClass(handle, options.cssClasses.handleLower);
}
else if (handleNumber === options.handles - 1) {
addClass(handle, options.cssClasses.handleUpper);
}
origin.handle = handle;
return origin;
}
// Insert nodes for connect elements
function addConnect(base, add) {
if (!add) {
return false;
}
return addNodeTo(base, options.cssClasses.connect);
}
// Add handles to the slider base.
function addElements(connectOptions, base) {
scope_ConnectBase = addNodeTo(base, options.cssClasses.connects);
scope_Handles = [];
scope_Connects = [];
scope_Connects.push(addConnect(scope_ConnectBase, connectOptions[0]));
// [::::O====O====O====]
// connectOptions = [0, 1, 1, 1]
for (var i = 0; i < options.handles; i++) {
// Keep a list of all added handles.
scope_Handles.push(addOrigin(base, i));
scope_HandleNumbers[i] = i;
scope_Connects.push(addConnect(scope_ConnectBase, connectOptions[i + 1]));
}
}
// Initialize a single slider.
function addSlider(addTarget) {
// Apply classes and data to the target.
addClass(addTarget, options.cssClasses.target);
if (options.dir === 0) {
addClass(addTarget, options.cssClasses.ltr);
}
else {
addClass(addTarget, options.cssClasses.rtl);
}
if (options.ort === 0) {
addClass(addTarget, options.cssClasses.horizontal);
}
else {
addClass(addTarget, options.cssClasses.vertical);
}
var textDirection = getComputedStyle(addTarget).direction;
if (textDirection === "rtl") {
addClass(addTarget, options.cssClasses.textDirectionRtl);
}
else {
addClass(addTarget, options.cssClasses.textDirectionLtr);
}
return addNodeTo(addTarget, options.cssClasses.base);
}
function addTooltip(handle, handleNumber) {
if (!options.tooltips || !options.tooltips[handleNumber]) {
return false;
}
return addNodeTo(handle.firstChild, options.cssClasses.tooltip);
}
function isSliderDisabled() {
return scope_Target.hasAttribute("disabled");
}
// Disable the slider dragging if any handle is disabled
function isHandleDisabled(handleNumber) {
var handleOrigin = scope_Handles[handleNumber];
return handleOrigin.hasAttribute("disabled");
}
function disable(handleNumber) {
if (handleNumber !== null && handleNumber !== undefined) {
scope_Handles[handleNumber].setAttribute("disabled", "");
scope_Handles[handleNumber].handle.removeAttribute("tabindex");
}
else {
scope_Target.setAttribute("disabled", "");
scope_Handles.forEach(function (handle) {
handle.handle.removeAttribute("tabindex");
});
}
}
function enable(handleNumber) {
if (handleNumber !== null && handleNumber !== undefined) {
scope_Handles[handleNumber].removeAttribute("disabled");
scope_Handles[handleNumber].handle.setAttribute("tabindex", "0");
}
else {
scope_Target.removeAttribute("disabled");
scope_Handles.forEach(function (handle) {
handle.removeAttribute("disabled");
handle.handle.setAttribute("tabindex", "0");
});
}
}
function removeTooltips() {
if (scope_Tooltips) {
removeEvent("update" + INTERNAL_EVENT_NS.tooltips);
scope_Tooltips.forEach(function (tooltip) {
if (tooltip) {
removeElement(tooltip);
}
});
scope_Tooltips = null;
}
}
// The tooltips option is a shorthand for using the 'update' event.
function tooltips() {
removeTooltips();
// Tooltips are added with options.tooltips in original order.
scope_Tooltips = scope_Handles.map(addTooltip);
bindEvent("update" + INTERNAL_EVENT_NS.tooltips, function (values, handleNumber, unencoded) {
if (!scope_Tooltips || !options.tooltips) {
return;
}
if (scope_Tooltips[handleNumber] === false) {
return;
}
var formattedValue = values[handleNumber];
if (options.tooltips[handleNumber] !== true) {
formattedValue = options.tooltips[handleNumber].to(unencoded[handleNumber]);
}
scope_Tooltips[handleNumber].innerHTML = formattedValue;
});
}
function aria() {
removeEvent("update" + INTERNAL_EVENT_NS.aria);
bindEvent("update" + INTERNAL_EVENT_NS.aria, function (values, handleNumber, unencoded, tap, positions) {
// Update Aria Values for all handles, as a change in one changes min and max values for the next.
scope_HandleNumbers.forEach(function (index) {
var handle = scope_Handles[index];
var min = checkHandlePosition(scope_Locations, index, 0, true, true, true);
var max = checkHandlePosition(scope_Locations, index, 100, true, true, true);
var now = positions[index];
// Formatted value for display
var text = String(options.ariaFormat.to(unencoded[index]));
// Map to slider range values
min = scope_Spectrum.fromStepping(min).toFixed(1);
max = scope_Spectrum.fromStepping(max).toFixed(1);
now = scope_Spectrum.fromStepping(now).toFixed(1);
handle.children[0].setAttribute("aria-valuemin", min);
handle.children[0].setAttribute("aria-valuemax", max);
handle.children[0].setAttribute("aria-valuenow", now);
handle.children[0].setAttribute("aria-valuetext", text);
});
});
}
function getGroup(pips) {
// Use the range.
if (pips.mode === PipsMode.Range || pips.mode === PipsMode.Steps) {
return scope_Spectrum.xVal;
}
if (pips.mode === PipsMode.Count) {
if (pips.values < 2) {
throw new Error("noUiSlider: 'values' (>= 2) required for mode 'count'.");
}
// Divide 0 - 100 in 'count' parts.
var interval = pips.values - 1;
var spread = 100 / interval;
var values = [];
// List these parts and have them handled as 'positions'.
while (interval--) {
values[interval] = interval * spread;
}
values.push(100);
return mapToRange(values, pips.stepped);
}
if (pips.mode === PipsMode.Positions) {
// Map all percentages to on-range values.
return mapToRange(pips.values, pips.stepped);
}
if (pips.mode === PipsMode.Values) {
// If the value must be stepped, it needs to be converted to a percentage first.
if (pips.stepped) {
return pips.values.map(function (value) {
// Convert to percentage, apply step, return to value.
return scope_Spectrum.fromStepping(scope_Spectrum.getStep(scope_Spectrum.toStepping(value)));
});
}
// Otherwise, we can simply use the values.
return pips.values;
}
return []; // pips.mode = never
}
function mapToRange(values, stepped) {
return values.map(function (value) {
return scope_Spectrum.fromStepping(stepped ? scope_Spectrum.getStep(value) : value);
});
}
function generateSpread(pips) {
function safeIncrement(value, increment) {
// Avoid floating point variance by dropping the smallest decimal places.
return Number((value + increment).toFixed(7));
}
var group = getGroup(pips);
var indexes = {};
var firstInRange = scope_Spectrum.xVal[0];
var lastInRange = scope_Spectrum.xVal[scope_Spectrum.xVal.length - 1];
var ignoreFirst = false;
var ignoreLast = false;
var prevPct = 0;
// Create a copy of the group, sort it and filter away all duplicates.
group = unique(group.slice().sort(function (a, b) {
return a - b;
}));
// Make sure the range starts with the first element.
if (group[0] !== firstInRange) {
group.unshift(firstInRange);
ignoreFirst = true;
}
// Likewise for the last one.
if (group[group.length - 1] !== lastInRange) {
group.push(lastInRange);
ignoreLast = true;
}
group.forEach(function (current, index) {
// Get the current step and the lower + upper positions.
var step;
var i;
var q;
var low = current;
var high = group[index + 1];
var newPct;
var pctDifference;
var pctPos;
var type;
var steps;
var realSteps;
var stepSize;
var isSteps = pips.mode === PipsMode.Steps;
// When using 'steps' mode, use the provided steps.
// Otherwise, we'll step on to the next subrange.
if (isSteps) {
step = scope_Spectrum.xNumSteps[index];
}
// Default to a 'full' step.
if (!step) {
step = high - low;
}
// If high is undefined we are at the last subrange. Make sure it iterates once (#1088)
if (high === undefined) {
high = low;
}
// Make sure step isn't 0, which would cause an infinite loop (#654)
step = Math.max(step, 0.0000001);
// Find all steps in the subrange.
for (i = low; i <= high; i = safeIncrement(i, step)) {
// Get the percentage value for the current step,
// calculate the size for the subrange.
newPct = scope_Spectrum.toStepping(i);
pctDifference = newPct - prevPct;
steps = pctDifference / (pips.density || 1);
realSteps = Math.round(steps);
// This ratio represents the amount of percentage-space a point indicates.
// For a density 1 the points/percentage = 1. For density 2, that percentage needs to be re-divided.
// Round the percentage offset to an even number, then divide by two
// to spread the offset on both sides of the range.
stepSize = pctDifference / realSteps;
// Divide all points evenly, adding the correct number to this subrange.
// Run up to <= so that 100% gets a point, event if ignoreLast is set.
for (q = 1; q <= realSteps; q += 1) {
// The ratio between the rounded value and the actual size might be ~1% off.
// Correct the percentage offset by the number of points
// per subrange. density = 1 will result in 100 points on the
// full range, 2 for 50, 4 for 25, etc.
pctPos = prevPct + q * stepSize;
indexes[pctPos.toFixed(5)] = [scope_Spectrum.fromStepping(pctPos), 0];
}
// Determine the point type.
type = group.indexOf(i) > -1 ? PipsType.LargeValue : isSteps ? PipsType.SmallValue : PipsType.NoValue;
// Enforce the 'ignoreFirst' option by overwriting the type for 0.
if (!index && ignoreFirst && i !== high) {
type = 0;
}
if (!(i === high && ignoreLast)) {
// Mark the 'type' of this point. 0 = plain, 1 = real value, 2 = step value.
indexes[newPct.toFixed(5)] = [i, type];
}
// Update the percentage count.
prevPct = newPct;
}
});
return indexes;
}
function addMarking(spread, filterFunc, formatter) {
var _a, _b;
var element = scope_Document.createElement("div");
var valueSizeClasses = (_a = {},
_a[PipsType.None] = "",
_a[PipsType.NoValue] = options.cssClasses.valueNormal,
_a[PipsType.LargeValue] = options.cssClasses.valueLarge,
_a[PipsType.SmallValue] = options.cssClasses.valueSub,
_a);
var markerSizeClasses = (_b = {},
_b[PipsType.None] = "",
_b[PipsType.NoValue] = options.cssClasses.markerNormal,
_b[PipsType.LargeValue] = options.cssClasses.markerLarge,
_b[PipsType.SmallValue] = options.cssClasses.markerSub,
_b);
var valueOrientationClasses = [options.cssClasses.valueHorizontal, options.cssClasses.valueVertical];
var markerOrientationClasses = [options.cssClasses.markerHorizontal, options.cssClasses.markerVertical];
addClass(element, options.cssClasses.pips);
addClass(element, options.ort === 0 ? options.cssClasses.pipsHorizontal : options.cssClasses.pipsVertical);
function getClasses(type, source) {
var a = source === options.cssClasses.value;
var orientationClasses = a ? valueOrientationClasses : markerOrientationClasses;
var sizeClasses = a ? valueSizeClasses : markerSizeClasses;
return source + " " + orientationClasses[options.ort] + " " + sizeClasses[type];
}
function addSpread(offset, value, type) {
// Apply the filter function, if it is set.
type = filterFunc ? filterFunc(value, type) : type;
if (type === PipsType.None) {
return;
}
// Add a marker for every point
var node = addNodeTo(element, false);
node.className = getClasses(type, options.cssClasses.marker);
node.style[options.style] = offset + "%";
// Values are only appended for points marked '1' or '2'.
if (type > PipsType.NoValue) {
node = addNodeTo(element, false);