You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2200 lines
98 KiB

  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.noUiSlider = {}));
  5. }(this, (function (exports) { 'use strict';
  6. exports.PipsMode = void 0;
  7. (function (PipsMode) {
  8. PipsMode["Range"] = "range";
  9. PipsMode["Steps"] = "steps";
  10. PipsMode["Positions"] = "positions";
  11. PipsMode["Count"] = "count";
  12. PipsMode["Values"] = "values";
  13. })(exports.PipsMode || (exports.PipsMode = {}));
  14. exports.PipsType = void 0;
  15. (function (PipsType) {
  16. PipsType[PipsType["None"] = -1] = "None";
  17. PipsType[PipsType["NoValue"] = 0] = "NoValue";
  18. PipsType[PipsType["LargeValue"] = 1] = "LargeValue";
  19. PipsType[PipsType["SmallValue"] = 2] = "SmallValue";
  20. })(exports.PipsType || (exports.PipsType = {}));
  21. //region Helper Methods
  22. function isValidFormatter(entry) {
  23. return isValidPartialFormatter(entry) && typeof entry.from === "function";
  24. }
  25. function isValidPartialFormatter(entry) {
  26. // partial formatters only need a to function and not a from function
  27. return typeof entry === "object" && typeof entry.to === "function";
  28. }
  29. function removeElement(el) {
  30. el.parentElement.removeChild(el);
  31. }
  32. function isSet(value) {
  33. return value !== null && value !== undefined;
  34. }
  35. // Bindable version
  36. function preventDefault(e) {
  37. e.preventDefault();
  38. }
  39. // Removes duplicates from an array.
  40. function unique(array) {
  41. return array.filter(function (a) {
  42. return !this[a] ? (this[a] = true) : false;
  43. }, {});
  44. }
  45. // Round a value to the closest 'to'.
  46. function closest(value, to) {
  47. return Math.round(value / to) * to;
  48. }
  49. // Current position of an element relative to the document.
  50. function offset(elem, orientation) {
  51. var rect = elem.getBoundingClientRect();
  52. var doc = elem.ownerDocument;
  53. var docElem = doc.documentElement;
  54. var pageOffset = getPageOffset(doc);
  55. // getBoundingClientRect contains left scroll in Chrome on Android.
  56. // I haven't found a feature detection that proves this. Worst case
  57. // scenario on mis-match: the 'tap' feature on horizontal sliders breaks.
  58. if (/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)) {
  59. pageOffset.x = 0;
  60. }
  61. return orientation ? rect.top + pageOffset.y - docElem.clientTop : rect.left + pageOffset.x - docElem.clientLeft;
  62. }
  63. // Checks whether a value is numerical.
  64. function isNumeric(a) {
  65. return typeof a === "number" && !isNaN(a) && isFinite(a);
  66. }
  67. // Sets a class and removes it after [duration] ms.
  68. function addClassFor(element, className, duration) {
  69. if (duration > 0) {
  70. addClass(element, className);
  71. setTimeout(function () {
  72. removeClass(element, className);
  73. }, duration);
  74. }
  75. }
  76. // Limits a value to 0 - 100
  77. function limit(a) {
  78. return Math.max(Math.min(a, 100), 0);
  79. }
  80. // Wraps a variable as an array, if it isn't one yet.
  81. // Note that an input array is returned by reference!
  82. function asArray(a) {
  83. return Array.isArray(a) ? a : [a];
  84. }
  85. // Counts decimals
  86. function countDecimals(numStr) {
  87. numStr = String(numStr);
  88. var pieces = numStr.split(".");
  89. return pieces.length > 1 ? pieces[1].length : 0;
  90. }
  91. // http://youmightnotneedjquery.com/#add_class
  92. function addClass(el, className) {
  93. if (el.classList && !/\s/.test(className)) {
  94. el.classList.add(className);
  95. }
  96. else {
  97. el.className += " " + className;
  98. }
  99. }
  100. // http://youmightnotneedjquery.com/#remove_class
  101. function removeClass(el, className) {
  102. if (el.classList && !/\s/.test(className)) {
  103. el.classList.remove(className);
  104. }
  105. else {
  106. el.className = el.className.replace(new RegExp("(^|\\b)" + className.split(" ").join("|") + "(\\b|$)", "gi"), " ");
  107. }
  108. }
  109. // https://plainjs.com/javascript/attributes/adding-removing-and-testing-for-classes-9/
  110. function hasClass(el, className) {
  111. return el.classList ? el.classList.contains(className) : new RegExp("\\b" + className + "\\b").test(el.className);
  112. }
  113. // https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes
  114. function getPageOffset(doc) {
  115. var supportPageOffset = window.pageXOffset !== undefined;
  116. var isCSS1Compat = (doc.compatMode || "") === "CSS1Compat";
  117. var x = supportPageOffset
  118. ? window.pageXOffset
  119. : isCSS1Compat
  120. ? doc.documentElement.scrollLeft
  121. : doc.body.scrollLeft;
  122. var y = supportPageOffset
  123. ? window.pageYOffset
  124. : isCSS1Compat
  125. ? doc.documentElement.scrollTop
  126. : doc.body.scrollTop;
  127. return {
  128. x: x,
  129. y: y
  130. };
  131. }
  132. // we provide a function to compute constants instead
  133. // of accessing window.* as soon as the module needs it
  134. // so that we do not compute anything if not needed
  135. function getActions() {
  136. // Determine the events to bind. IE11 implements pointerEvents without
  137. // a prefix, which breaks compatibility with the IE10 implementation.
  138. return window.navigator.pointerEnabled
  139. ? {
  140. start: "pointerdown",
  141. move: "pointermove",
  142. end: "pointerup"
  143. }
  144. : window.navigator.msPointerEnabled
  145. ? {
  146. start: "MSPointerDown",
  147. move: "MSPointerMove",
  148. end: "MSPointerUp"
  149. }
  150. : {
  151. start: "mousedown touchstart",
  152. move: "mousemove touchmove",
  153. end: "mouseup touchend"
  154. };
  155. }
  156. // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  157. // Issue #785
  158. function getSupportsPassive() {
  159. var supportsPassive = false;
  160. /* eslint-disable */
  161. try {
  162. var opts = Object.defineProperty({}, "passive", {
  163. get: function () {
  164. supportsPassive = true;
  165. }
  166. });
  167. // @ts-ignore
  168. window.addEventListener("test", null, opts);
  169. }
  170. catch (e) { }
  171. /* eslint-enable */
  172. return supportsPassive;
  173. }
  174. function getSupportsTouchActionNone() {
  175. return window.CSS && CSS.supports && CSS.supports("touch-action", "none");
  176. }
  177. //endregion
  178. //region Range Calculation
  179. // Determine the size of a sub-range in relation to a full range.
  180. function subRangeRatio(pa, pb) {
  181. return 100 / (pb - pa);
  182. }
  183. // (percentage) How many percent is this value of this range?
  184. function fromPercentage(range, value, startRange) {
  185. return (value * 100) / (range[startRange + 1] - range[startRange]);
  186. }
  187. // (percentage) Where is this value on this range?
  188. function toPercentage(range, value) {
  189. return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0], 0);
  190. }
  191. // (value) How much is this percentage on this range?
  192. function isPercentage(range, value) {
  193. return (value * (range[1] - range[0])) / 100 + range[0];
  194. }
  195. function getJ(value, arr) {
  196. var j = 1;
  197. while (value >= arr[j]) {
  198. j += 1;
  199. }
  200. return j;
  201. }
  202. // (percentage) Input a value, find where, on a scale of 0-100, it applies.
  203. function toStepping(xVal, xPct, value) {
  204. if (value >= xVal.slice(-1)[0]) {
  205. return 100;
  206. }
  207. var j = getJ(value, xVal);
  208. var va = xVal[j - 1];
  209. var vb = xVal[j];
  210. var pa = xPct[j - 1];
  211. var pb = xPct[j];
  212. return pa + toPercentage([va, vb], value) / subRangeRatio(pa, pb);
  213. }
  214. // (value) Input a percentage, find where it is on the specified range.
  215. function fromStepping(xVal, xPct, value) {
  216. // There is no range group that fits 100
  217. if (value >= 100) {
  218. return xVal.slice(-1)[0];
  219. }
  220. var j = getJ(value, xPct);
  221. var va = xVal[j - 1];
  222. var vb = xVal[j];
  223. var pa = xPct[j - 1];
  224. var pb = xPct[j];
  225. return isPercentage([va, vb], (value - pa) * subRangeRatio(pa, pb));
  226. }
  227. // (percentage) Get the step that applies at a certain value.
  228. function getStep(xPct, xSteps, snap, value) {
  229. if (value === 100) {
  230. return value;
  231. }
  232. var j = getJ(value, xPct);
  233. var a = xPct[j - 1];
  234. var b = xPct[j];
  235. // If 'snap' is set, steps are used as fixed points on the slider.
  236. if (snap) {
  237. // Find the closest position, a or b.
  238. if (value - a > (b - a) / 2) {
  239. return b;
  240. }
  241. return a;
  242. }
  243. if (!xSteps[j - 1]) {
  244. return value;
  245. }
  246. return xPct[j - 1] + closest(value - xPct[j - 1], xSteps[j - 1]);
  247. }
  248. //endregion
  249. //region Spectrum
  250. var Spectrum = /** @class */ (function () {
  251. function Spectrum(entry, snap, singleStep) {
  252. this.xPct = [];
  253. this.xVal = [];
  254. this.xSteps = [];
  255. this.xNumSteps = [];
  256. this.xHighestCompleteStep = [];
  257. this.xSteps = [singleStep || false];
  258. this.xNumSteps = [false];
  259. this.snap = snap;
  260. var index;
  261. var ordered = [];
  262. // Map the object keys to an array.
  263. Object.keys(entry).forEach(function (index) {
  264. ordered.push([asArray(entry[index]), index]);
  265. });
  266. // Sort all entries by value (numeric sort).
  267. ordered.sort(function (a, b) {
  268. return a[0][0] - b[0][0];
  269. });
  270. // Convert all entries to subranges.
  271. for (index = 0; index < ordered.length; index++) {
  272. this.handleEntryPoint(ordered[index][1], ordered[index][0]);
  273. }
  274. // Store the actual step values.
  275. // xSteps is sorted in the same order as xPct and xVal.
  276. this.xNumSteps = this.xSteps.slice(0);
  277. // Convert all numeric steps to the percentage of the subrange they represent.
  278. for (index = 0; index < this.xNumSteps.length; index++) {
  279. this.handleStepPoint(index, this.xNumSteps[index]);
  280. }
  281. }
  282. Spectrum.prototype.getDistance = function (value) {
  283. var index;
  284. var distances = [];
  285. for (index = 0; index < this.xNumSteps.length - 1; index++) {
  286. // last "range" can't contain step size as it is purely an endpoint.
  287. var step = this.xNumSteps[index];
  288. if (step && (value / step) % 1 !== 0) {
  289. throw new Error("noUiSlider: 'limit', 'margin' and 'padding' of " +
  290. this.xPct[index] +
  291. "% range must be divisible by step.");
  292. }
  293. // Calculate percentual distance in current range of limit, margin or padding
  294. distances[index] = fromPercentage(this.xVal, value, index);
  295. }
  296. return distances;
  297. };
  298. // Calculate the percentual distance over the whole scale of ranges.
  299. // direction: 0 = backwards / 1 = forwards
  300. Spectrum.prototype.getAbsoluteDistance = function (value, distances, direction) {
  301. var xPct_index = 0;
  302. // Calculate range where to start calculation
  303. if (value < this.xPct[this.xPct.length - 1]) {
  304. while (value > this.xPct[xPct_index + 1]) {
  305. xPct_index++;
  306. }
  307. }
  308. else if (value === this.xPct[this.xPct.length - 1]) {
  309. xPct_index = this.xPct.length - 2;
  310. }
  311. // If looking backwards and the value is exactly at a range separator then look one range further
  312. if (!direction && value === this.xPct[xPct_index + 1]) {
  313. xPct_index++;
  314. }
  315. if (distances === null) {
  316. distances = [];
  317. }
  318. var start_factor;
  319. var rest_factor = 1;
  320. var rest_rel_distance = distances[xPct_index];
  321. var range_pct = 0;
  322. var rel_range_distance = 0;
  323. var abs_distance_counter = 0;
  324. var range_counter = 0;
  325. // Calculate what part of the start range the value is
  326. if (direction) {
  327. start_factor = (value - this.xPct[xPct_index]) / (this.xPct[xPct_index + 1] - this.xPct[xPct_index]);
  328. }
  329. else {
  330. start_factor = (this.xPct[xPct_index + 1] - value) / (this.xPct[xPct_index + 1] - this.xPct[xPct_index]);
  331. }
  332. // Do until the complete distance across ranges is calculated
  333. while (rest_rel_distance > 0) {
  334. // Calculate the percentage of total range
  335. range_pct = this.xPct[xPct_index + 1 + range_counter] - this.xPct[xPct_index + range_counter];
  336. // Detect if the margin, padding or limit is larger then the current range and calculate
  337. if (distances[xPct_index + range_counter] * rest_factor + 100 - start_factor * 100 > 100) {
  338. // If larger then take the percentual distance of the whole range
  339. rel_range_distance = range_pct * start_factor;
  340. // Rest factor of relative percentual distance still to be calculated
  341. rest_factor = (rest_rel_distance - 100 * start_factor) / distances[xPct_index + range_counter];
  342. // Set start factor to 1 as for next range it does not apply.
  343. start_factor = 1;
  344. }
  345. else {
  346. // If smaller or equal then take the percentual distance of the calculate percentual part of that range
  347. rel_range_distance = ((distances[xPct_index + range_counter] * range_pct) / 100) * rest_factor;
  348. // No rest left as the rest fits in current range
  349. rest_factor = 0;
  350. }
  351. if (direction) {
  352. abs_distance_counter = abs_distance_counter - rel_range_distance;
  353. // Limit range to first range when distance becomes outside of minimum range
  354. if (this.xPct.length + range_counter >= 1) {
  355. range_counter--;
  356. }
  357. }
  358. else {
  359. abs_distance_counter = abs_distance_counter + rel_range_distance;
  360. // Limit range to last range when distance becomes outside of maximum range
  361. if (this.xPct.length - range_counter >= 1) {
  362. range_counter++;
  363. }
  364. }
  365. // Rest of relative percentual distance still to be calculated
  366. rest_rel_distance = distances[xPct_index + range_counter] * rest_factor;
  367. }
  368. return value + abs_distance_counter;
  369. };
  370. Spectrum.prototype.toStepping = function (value) {
  371. value = toStepping(this.xVal, this.xPct, value);
  372. return value;
  373. };
  374. Spectrum.prototype.fromStepping = function (value) {
  375. return fromStepping(this.xVal, this.xPct, value);
  376. };
  377. Spectrum.prototype.getStep = function (value) {
  378. value = getStep(this.xPct, this.xSteps, this.snap, value);
  379. return value;
  380. };
  381. Spectrum.prototype.getDefaultStep = function (value, isDown, size) {
  382. var j = getJ(value, this.xPct);
  383. // When at the top or stepping down, look at the previous sub-range
  384. if (value === 100 || (isDown && value === this.xPct[j - 1])) {
  385. j = Math.max(j - 1, 1);
  386. }
  387. return (this.xVal[j] - this.xVal[j - 1]) / size;
  388. };
  389. Spectrum.prototype.getNearbySteps = function (value) {
  390. var j = getJ(value, this.xPct);
  391. return {
  392. stepBefore: {
  393. startValue: this.xVal[j - 2],
  394. step: this.xNumSteps[j - 2],
  395. highestStep: this.xHighestCompleteStep[j - 2]
  396. },
  397. thisStep: {
  398. startValue: this.xVal[j - 1],
  399. step: this.xNumSteps[j - 1],
  400. highestStep: this.xHighestCompleteStep[j - 1]
  401. },
  402. stepAfter: {
  403. startValue: this.xVal[j],
  404. step: this.xNumSteps[j],
  405. highestStep: this.xHighestCompleteStep[j]
  406. }
  407. };
  408. };
  409. Spectrum.prototype.countStepDecimals = function () {
  410. var stepDecimals = this.xNumSteps.map(countDecimals);
  411. return Math.max.apply(null, stepDecimals);
  412. };
  413. // Outside testing
  414. Spectrum.prototype.convert = function (value) {
  415. return this.getStep(this.toStepping(value));
  416. };
  417. Spectrum.prototype.handleEntryPoint = function (index, value) {
  418. var percentage;
  419. // Covert min/max syntax to 0 and 100.
  420. if (index === "min") {
  421. percentage = 0;
  422. }
  423. else if (index === "max") {
  424. percentage = 100;
  425. }
  426. else {
  427. percentage = parseFloat(index);
  428. }
  429. // Check for correct input.
  430. if (!isNumeric(percentage) || !isNumeric(value[0])) {
  431. throw new Error("noUiSlider: 'range' value isn't numeric.");
  432. }
  433. // Store values.
  434. this.xPct.push(percentage);
  435. this.xVal.push(value[0]);
  436. var value1 = Number(value[1]);
  437. // NaN will evaluate to false too, but to keep
  438. // logging clear, set step explicitly. Make sure
  439. // not to override the 'step' setting with false.
  440. if (!percentage) {
  441. if (!isNaN(value1)) {
  442. this.xSteps[0] = value1;
  443. }
  444. }
  445. else {
  446. this.xSteps.push(isNaN(value1) ? false : value1);
  447. }
  448. this.xHighestCompleteStep.push(0);
  449. };
  450. Spectrum.prototype.handleStepPoint = function (i, n) {
  451. // Ignore 'false' stepping.
  452. if (!n) {
  453. return;
  454. }
  455. // Step over zero-length ranges (#948);
  456. if (this.xVal[i] === this.xVal[i + 1]) {
  457. this.xSteps[i] = this.xHighestCompleteStep[i] = this.xVal[i];
  458. return;
  459. }
  460. // Factor to range ratio
  461. this.xSteps[i] =
  462. fromPercentage([this.xVal[i], this.xVal[i + 1]], n, 0) / subRangeRatio(this.xPct[i], this.xPct[i + 1]);
  463. var totalSteps = (this.xVal[i + 1] - this.xVal[i]) / this.xNumSteps[i];
  464. var highestStep = Math.ceil(Number(totalSteps.toFixed(3)) - 1);
  465. var step = this.xVal[i] + this.xNumSteps[i] * highestStep;
  466. this.xHighestCompleteStep[i] = step;
  467. };
  468. return Spectrum;
  469. }());
  470. //endregion
  471. //region Options
  472. /* Every input option is tested and parsed. This will prevent
  473. endless validation in internal methods. These tests are
  474. structured with an item for every option available. An
  475. option can be marked as required by setting the 'r' flag.
  476. The testing function is provided with three arguments:
  477. - The provided value for the option;
  478. - A reference to the options object;
  479. - The name for the option;
  480. The testing function returns false when an error is detected,
  481. or true when everything is OK. It can also modify the option
  482. object, to make sure all values can be correctly looped elsewhere. */
  483. //region Defaults
  484. var defaultFormatter = {
  485. to: function (value) {
  486. return value === undefined ? "" : value.toFixed(2);
  487. },
  488. from: Number
  489. };
  490. var cssClasses = {
  491. target: "target",
  492. base: "base",
  493. origin: "origin",
  494. handle: "handle",
  495. handleLower: "handle-lower",
  496. handleUpper: "handle-upper",
  497. touchArea: "touch-area",
  498. horizontal: "horizontal",
  499. vertical: "vertical",
  500. background: "background",
  501. connect: "connect",
  502. connects: "connects",
  503. ltr: "ltr",
  504. rtl: "rtl",
  505. textDirectionLtr: "txt-dir-ltr",
  506. textDirectionRtl: "txt-dir-rtl",
  507. draggable: "draggable",
  508. drag: "state-drag",
  509. tap: "state-tap",
  510. active: "active",
  511. tooltip: "tooltip",
  512. pips: "pips",
  513. pipsHorizontal: "pips-horizontal",
  514. pipsVertical: "pips-vertical",
  515. marker: "marker",
  516. markerHorizontal: "marker-horizontal",
  517. markerVertical: "marker-vertical",
  518. markerNormal: "marker-normal",
  519. markerLarge: "marker-large",
  520. markerSub: "marker-sub",
  521. value: "value",
  522. valueHorizontal: "value-horizontal",
  523. valueVertical: "value-vertical",
  524. valueNormal: "value-normal",
  525. valueLarge: "value-large",
  526. valueSub: "value-sub"
  527. };
  528. // Namespaces of internal event listeners
  529. var INTERNAL_EVENT_NS = {
  530. tooltips: ".__tooltips",
  531. aria: ".__aria"
  532. };
  533. //endregion
  534. function testStep(parsed, entry) {
  535. if (!isNumeric(entry)) {
  536. throw new Error("noUiSlider: 'step' is not numeric.");
  537. }
  538. // The step option can still be used to set stepping
  539. // for linear sliders. Overwritten if set in 'range'.
  540. parsed.singleStep = entry;
  541. }
  542. function testKeyboardPageMultiplier(parsed, entry) {
  543. if (!isNumeric(entry)) {
  544. throw new Error("noUiSlider: 'keyboardPageMultiplier' is not numeric.");
  545. }
  546. parsed.keyboardPageMultiplier = entry;
  547. }
  548. function testKeyboardDefaultStep(parsed, entry) {
  549. if (!isNumeric(entry)) {
  550. throw new Error("noUiSlider: 'keyboardDefaultStep' is not numeric.");
  551. }
  552. parsed.keyboardDefaultStep = entry;
  553. }
  554. function testRange(parsed, entry) {
  555. // Filter incorrect input.
  556. if (typeof entry !== "object" || Array.isArray(entry)) {
  557. throw new Error("noUiSlider: 'range' is not an object.");
  558. }
  559. // Catch missing start or end.
  560. if (entry.min === undefined || entry.max === undefined) {
  561. throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");
  562. }
  563. // Catch equal start or end.
  564. if (entry.min === entry.max) {
  565. throw new Error("noUiSlider: 'range' 'min' and 'max' cannot be equal.");
  566. }
  567. parsed.spectrum = new Spectrum(entry, parsed.snap || false, parsed.singleStep);
  568. }
  569. function testStart(parsed, entry) {
  570. entry = asArray(entry);
  571. // Validate input. Values aren't tested, as the public .val method
  572. // will always provide a valid location.
  573. if (!Array.isArray(entry) || !entry.length) {
  574. throw new Error("noUiSlider: 'start' option is incorrect.");
  575. }
  576. // Store the number of handles.
  577. parsed.handles = entry.length;
  578. // When the slider is initialized, the .val method will
  579. // be called with the start options.
  580. parsed.start = entry;
  581. }
  582. function testSnap(parsed, entry) {
  583. if (typeof entry !== "boolean") {
  584. throw new Error("noUiSlider: 'snap' option must be a boolean.");
  585. }
  586. // Enforce 100% stepping within subranges.
  587. parsed.snap = entry;
  588. }
  589. function testAnimate(parsed, entry) {
  590. if (typeof entry !== "boolean") {
  591. throw new Error("noUiSlider: 'animate' option must be a boolean.");
  592. }
  593. // Enforce 100% stepping within subranges.
  594. parsed.animate = entry;
  595. }
  596. function testAnimationDuration(parsed, entry) {
  597. if (typeof entry !== "number") {
  598. throw new Error("noUiSlider: 'animationDuration' option must be a number.");
  599. }
  600. parsed.animationDuration = entry;
  601. }
  602. function testConnect(parsed, entry) {
  603. var connect = [false];
  604. var i;
  605. // Map legacy options
  606. if (entry === "lower") {
  607. entry = [true, false];
  608. }
  609. else if (entry === "upper") {
  610. entry = [false, true];
  611. }
  612. // Handle boolean options
  613. if (entry === true || entry === false) {
  614. for (i = 1; i < parsed.handles; i++) {
  615. connect.push(entry);
  616. }
  617. connect.push(false);
  618. }
  619. // Reject invalid input
  620. else if (!Array.isArray(entry) || !entry.length || entry.length !== parsed.handles + 1) {
  621. throw new Error("noUiSlider: 'connect' option doesn't match handle count.");
  622. }
  623. else {
  624. connect = entry;
  625. }
  626. parsed.connect = connect;
  627. }
  628. function testOrientation(parsed, entry) {
  629. // Set orientation to an a numerical value for easy
  630. // array selection.
  631. switch (entry) {
  632. case "horizontal":
  633. parsed.ort = 0;
  634. break;
  635. case "vertical":
  636. parsed.ort = 1;
  637. break;
  638. default:
  639. throw new Error("noUiSlider: 'orientation' option is invalid.");
  640. }
  641. }
  642. function testMargin(parsed, entry) {
  643. if (!isNumeric(entry)) {
  644. throw new Error("noUiSlider: 'margin' option must be numeric.");
  645. }
  646. // Issue #582
  647. if (entry === 0) {
  648. return;
  649. }
  650. parsed.margin = parsed.spectrum.getDistance(entry);
  651. }
  652. function testLimit(parsed, entry) {
  653. if (!isNumeric(entry)) {
  654. throw new Error("noUiSlider: 'limit' option must be numeric.");
  655. }
  656. parsed.limit = parsed.spectrum.getDistance(entry);
  657. if (!parsed.limit || parsed.handles < 2) {
  658. throw new Error("noUiSlider: 'limit' option is only supported on linear sliders with 2 or more handles.");
  659. }
  660. }
  661. function testPadding(parsed, entry) {
  662. var index;
  663. if (!isNumeric(entry) && !Array.isArray(entry)) {
  664. throw new Error("noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers.");
  665. }
  666. if (Array.isArray(entry) && !(entry.length === 2 || isNumeric(entry[0]) || isNumeric(entry[1]))) {
  667. throw new Error("noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers.");
  668. }
  669. if (entry === 0) {
  670. return;
  671. }
  672. if (!Array.isArray(entry)) {
  673. entry = [entry, entry];
  674. }
  675. // 'getDistance' returns false for invalid values.
  676. parsed.padding = [parsed.spectrum.getDistance(entry[0]), parsed.spectrum.getDistance(entry[1])];
  677. for (index = 0; index < parsed.spectrum.xNumSteps.length - 1; index++) {
  678. // last "range" can't contain step size as it is purely an endpoint.
  679. if (parsed.padding[0][index] < 0 || parsed.padding[1][index] < 0) {
  680. throw new Error("noUiSlider: 'padding' option must be a positive number(s).");
  681. }
  682. }
  683. var totalPadding = entry[0] + entry[1];
  684. var firstValue = parsed.spectrum.xVal[0];
  685. var lastValue = parsed.spectrum.xVal[parsed.spectrum.xVal.length - 1];
  686. if (totalPadding / (lastValue - firstValue) > 1) {
  687. throw new Error("noUiSlider: 'padding' option must not exceed 100% of the range.");
  688. }
  689. }
  690. function testDirection(parsed, entry) {
  691. // Set direction as a numerical value for easy parsing.
  692. // Invert connection for RTL sliders, so that the proper
  693. // handles get the connect/background classes.
  694. switch (entry) {
  695. case "ltr":
  696. parsed.dir = 0;
  697. break;
  698. case "rtl":
  699. parsed.dir = 1;
  700. break;
  701. default:
  702. throw new Error("noUiSlider: 'direction' option was not recognized.");
  703. }
  704. }
  705. function testBehaviour(parsed, entry) {
  706. // Make sure the input is a string.
  707. if (typeof entry !== "string") {
  708. throw new Error("noUiSlider: 'behaviour' must be a string containing options.");
  709. }
  710. // Check if the string contains any keywords.
  711. // None are required.
  712. var tap = entry.indexOf("tap") >= 0;
  713. var drag = entry.indexOf("drag") >= 0;
  714. var fixed = entry.indexOf("fixed") >= 0;
  715. var snap = entry.indexOf("snap") >= 0;
  716. var hover = entry.indexOf("hover") >= 0;
  717. var unconstrained = entry.indexOf("unconstrained") >= 0;
  718. if (fixed) {
  719. if (parsed.handles !== 2) {
  720. throw new Error("noUiSlider: 'fixed' behaviour must be used with 2 handles");
  721. }
  722. // Use margin to enforce fixed state
  723. testMargin(parsed, parsed.start[1] - parsed.start[0]);
  724. }
  725. if (unconstrained && (parsed.margin || parsed.limit)) {
  726. throw new Error("noUiSlider: 'unconstrained' behaviour cannot be used with margin or limit");
  727. }
  728. parsed.events = {
  729. tap: tap || snap,
  730. drag: drag,
  731. fixed: fixed,
  732. snap: snap,
  733. hover: hover,
  734. unconstrained: unconstrained
  735. };
  736. }
  737. function testTooltips(parsed, entry) {
  738. if (entry === false) {
  739. return;
  740. }
  741. if (entry === true || isValidPartialFormatter(entry)) {
  742. parsed.tooltips = [];
  743. for (var i = 0; i < parsed.handles; i++) {
  744. parsed.tooltips.push(entry);
  745. }
  746. }
  747. else {
  748. entry = asArray(entry);
  749. if (entry.length !== parsed.handles) {
  750. throw new Error("noUiSlider: must pass a formatter for all handles.");
  751. }
  752. entry.forEach(function (formatter) {
  753. if (typeof formatter !== "boolean" && !isValidPartialFormatter(formatter)) {
  754. throw new Error("noUiSlider: 'tooltips' must be passed a formatter or 'false'.");
  755. }
  756. });
  757. parsed.tooltips = entry;
  758. }
  759. }
  760. function testAriaFormat(parsed, entry) {
  761. if (!isValidPartialFormatter(entry)) {
  762. throw new Error("noUiSlider: 'ariaFormat' requires 'to' method.");
  763. }
  764. parsed.ariaFormat = entry;
  765. }
  766. function testFormat(parsed, entry) {
  767. if (!isValidFormatter(entry)) {
  768. throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.");
  769. }
  770. parsed.format = entry;
  771. }
  772. function testKeyboardSupport(parsed, entry) {
  773. if (typeof entry !== "boolean") {
  774. throw new Error("noUiSlider: 'keyboardSupport' option must be a boolean.");
  775. }
  776. parsed.keyboardSupport = entry;
  777. }
  778. function testDocumentElement(parsed, entry) {
  779. // This is an advanced option. Passed values are used without validation.
  780. parsed.documentElement = entry;
  781. }
  782. function testCssPrefix(parsed, entry) {
  783. if (typeof entry !== "string" && entry !== false) {
  784. throw new Error("noUiSlider: 'cssPrefix' must be a string or `false`.");
  785. }
  786. parsed.cssPrefix = entry;
  787. }
  788. function testCssClasses(parsed, entry) {
  789. if (typeof entry !== "object") {
  790. throw new Error("noUiSlider: 'cssClasses' must be an object.");
  791. }
  792. if (typeof parsed.cssPrefix === "string") {
  793. parsed.cssClasses = {};
  794. Object.keys(entry).forEach(function (key) {
  795. parsed.cssClasses[key] = parsed.cssPrefix + entry[key];
  796. });
  797. }
  798. else {
  799. parsed.cssClasses = entry;
  800. }
  801. }
  802. // Test all developer settings and parse to assumption-safe values.
  803. function testOptions(options) {
  804. // To prove a fix for #537, freeze options here.
  805. // If the object is modified, an error will be thrown.
  806. // Object.freeze(options);
  807. var parsed = {
  808. margin: null,
  809. limit: null,
  810. padding: null,
  811. animate: true,
  812. animationDuration: 300,
  813. ariaFormat: defaultFormatter,
  814. format: defaultFormatter
  815. };
  816. // Tests are executed in the order they are presented here.
  817. var tests = {
  818. step: { r: false, t: testStep },
  819. keyboardPageMultiplier: { r: false, t: testKeyboardPageMultiplier },
  820. keyboardDefaultStep: { r: false, t: testKeyboardDefaultStep },
  821. start: { r: true, t: testStart },
  822. connect: { r: true, t: testConnect },
  823. direction: { r: true, t: testDirection },
  824. snap: { r: false, t: testSnap },
  825. animate: { r: false, t: testAnimate },
  826. animationDuration: { r: false, t: testAnimationDuration },
  827. range: { r: true, t: testRange },
  828. orientation: { r: false, t: testOrientation },
  829. margin: { r: false, t: testMargin },
  830. limit: { r: false, t: testLimit },
  831. padding: { r: false, t: testPadding },
  832. behaviour: { r: true, t: testBehaviour },
  833. ariaFormat: { r: false, t: testAriaFormat },
  834. format: { r: false, t: testFormat },
  835. tooltips: { r: false, t: testTooltips },
  836. keyboardSupport: { r: true, t: testKeyboardSupport },
  837. documentElement: { r: false, t: testDocumentElement },
  838. cssPrefix: { r: true, t: testCssPrefix },
  839. cssClasses: { r: true, t: testCssClasses }
  840. };
  841. var defaults = {
  842. connect: false,
  843. direction: "ltr",
  844. behaviour: "tap",
  845. orientation: "horizontal",
  846. keyboardSupport: true,
  847. cssPrefix: "noUi-",
  848. cssClasses: cssClasses,
  849. keyboardPageMultiplier: 5,
  850. keyboardDefaultStep: 10
  851. };
  852. // AriaFormat defaults to regular format, if any.
  853. if (options.format && !options.ariaFormat) {
  854. options.ariaFormat = options.format;
  855. }
  856. // Run all options through a testing mechanism to ensure correct
  857. // input. It should be noted that options might get modified to
  858. // be handled properly. E.g. wrapping integers in arrays.
  859. Object.keys(tests).forEach(function (name) {
  860. // If the option isn't set, but it is required, throw an error.
  861. if (!isSet(options[name]) && defaults[name] === undefined) {
  862. if (tests[name].r) {
  863. throw new Error("noUiSlider: '" + name + "' is required.");
  864. }
  865. return;
  866. }
  867. tests[name].t(parsed, !isSet(options[name]) ? defaults[name] : options[name]);
  868. });
  869. // Forward pips options
  870. parsed.pips = options.pips;
  871. // All recent browsers accept unprefixed transform.
  872. // We need -ms- for IE9 and -webkit- for older Android;
  873. // Assume use of -webkit- if unprefixed and -ms- are not supported.
  874. // https://caniuse.com/#feat=transforms2d
  875. var d = document.createElement("div");
  876. var msPrefix = d.style.msTransform !== undefined;
  877. var noPrefix = d.style.transform !== undefined;
  878. parsed.transformRule = noPrefix ? "transform" : msPrefix ? "msTransform" : "webkitTransform";
  879. // Pips don't move, so we can place them using left/top.
  880. var styles = [["left", "top"], ["right", "bottom"]];
  881. parsed.style = styles[parsed.dir][parsed.ort];
  882. return parsed;
  883. }
  884. //endregion
  885. function scope(target, options, originalOptions) {
  886. var actions = getActions();
  887. var supportsTouchActionNone = getSupportsTouchActionNone();
  888. var supportsPassive = supportsTouchActionNone && getSupportsPassive();
  889. // All variables local to 'scope' are prefixed with 'scope_'
  890. // Slider DOM Nodes
  891. var scope_Target = target;
  892. var scope_Base;
  893. var scope_Handles;
  894. var scope_Connects;
  895. var scope_Pips;
  896. var scope_Tooltips;
  897. // Slider state values
  898. var scope_Spectrum = options.spectrum;
  899. var scope_Values = [];
  900. var scope_Locations = [];
  901. var scope_HandleNumbers = [];
  902. var scope_ActiveHandlesCount = 0;
  903. var scope_Events = {};
  904. // Document Nodes
  905. var scope_Document = target.ownerDocument;
  906. var scope_DocumentElement = options.documentElement || scope_Document.documentElement;
  907. var scope_Body = scope_Document.body;
  908. // For horizontal sliders in standard ltr documents,
  909. // make .noUi-origin overflow to the left so the document doesn't scroll.
  910. var scope_DirOffset = scope_Document.dir === "rtl" || options.ort === 1 ? 0 : 100;
  911. // Creates a node, adds it to target, returns the new node.
  912. function addNodeTo(addTarget, className) {
  913. var div = scope_Document.createElement("div");
  914. if (className) {
  915. addClass(div, className);
  916. }
  917. addTarget.appendChild(div);
  918. return div;
  919. }
  920. // Append a origin to the base
  921. function addOrigin(base, handleNumber) {
  922. var origin = addNodeTo(base, options.cssClasses.origin);
  923. var handle = addNodeTo(origin, options.cssClasses.handle);
  924. addNodeTo(handle, options.cssClasses.touchArea);
  925. handle.setAttribute("data-handle", String(handleNumber));
  926. if (options.keyboardSupport) {
  927. // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
  928. // 0 = focusable and reachable
  929. handle.setAttribute("tabindex", "0");
  930. handle.addEventListener("keydown", function (event) {
  931. return eventKeydown(event, handleNumber);
  932. });
  933. }
  934. handle.setAttribute("role", "slider");
  935. handle.setAttribute("aria-orientation", options.ort ? "vertical" : "horizontal");
  936. if (handleNumber === 0) {
  937. addClass(handle, options.cssClasses.handleLower);
  938. }
  939. else if (handleNumber === options.handles - 1) {
  940. addClass(handle, options.cssClasses.handleUpper);
  941. }
  942. return origin;
  943. }
  944. // Insert nodes for connect elements
  945. function addConnect(base, add) {
  946. if (!add) {
  947. return false;
  948. }
  949. return addNodeTo(base, options.cssClasses.connect);
  950. }
  951. // Add handles to the slider base.
  952. function addElements(connectOptions, base) {
  953. var connectBase = addNodeTo(base, options.cssClasses.connects);
  954. scope_Handles = [];
  955. scope_Connects = [];
  956. scope_Connects.push(addConnect(connectBase, connectOptions[0]));
  957. // [::::O====O====O====]
  958. // connectOptions = [0, 1, 1, 1]
  959. for (var i = 0; i < options.handles; i++) {
  960. // Keep a list of all added handles.
  961. scope_Handles.push(addOrigin(base, i));
  962. scope_HandleNumbers[i] = i;
  963. scope_Connects.push(addConnect(connectBase, connectOptions[i + 1]));
  964. }
  965. }
  966. // Initialize a single slider.
  967. function addSlider(addTarget) {
  968. // Apply classes and data to the target.
  969. addClass(addTarget, options.cssClasses.target);
  970. if (options.dir === 0) {
  971. addClass(addTarget, options.cssClasses.ltr);
  972. }
  973. else {
  974. addClass(addTarget, options.cssClasses.rtl);
  975. }
  976. if (options.ort === 0) {
  977. addClass(addTarget, options.cssClasses.horizontal);
  978. }
  979. else {
  980. addClass(addTarget, options.cssClasses.vertical);
  981. }
  982. var textDirection = getComputedStyle(addTarget).direction;
  983. if (textDirection === "rtl") {
  984. addClass(addTarget, options.cssClasses.textDirectionRtl);
  985. }
  986. else {
  987. addClass(addTarget, options.cssClasses.textDirectionLtr);
  988. }
  989. return addNodeTo(addTarget, options.cssClasses.base);
  990. }
  991. function addTooltip(handle, handleNumber) {
  992. if (!options.tooltips || !options.tooltips[handleNumber]) {
  993. return false;
  994. }
  995. return addNodeTo(handle.firstChild, options.cssClasses.tooltip);
  996. }
  997. function isSliderDisabled() {
  998. return scope_Target.hasAttribute("disabled");
  999. }
  1000. // Disable the slider dragging if any handle is disabled
  1001. function isHandleDisabled(handleNumber) {
  1002. var handleOrigin = scope_Handles[handleNumber];
  1003. return handleOrigin.hasAttribute("disabled");
  1004. }
  1005. function removeTooltips() {
  1006. if (scope_Tooltips) {
  1007. removeEvent("update" + INTERNAL_EVENT_NS.tooltips);
  1008. scope_Tooltips.forEach(function (tooltip) {
  1009. if (tooltip) {
  1010. removeElement(tooltip);
  1011. }
  1012. });
  1013. scope_Tooltips = null;
  1014. }
  1015. }
  1016. // The tooltips option is a shorthand for using the 'update' event.
  1017. function tooltips() {
  1018. removeTooltips();
  1019. // Tooltips are added with options.tooltips in original order.
  1020. scope_Tooltips = scope_Handles.map(addTooltip);
  1021. bindEvent("update" + INTERNAL_EVENT_NS.tooltips, function (values, handleNumber, unencoded) {
  1022. if (!scope_Tooltips || !options.tooltips) {
  1023. return;
  1024. }
  1025. if (scope_Tooltips[handleNumber] === false) {
  1026. return;
  1027. }
  1028. var formattedValue = values[handleNumber];
  1029. if (options.tooltips[handleNumber] !== true) {
  1030. formattedValue = options.tooltips[handleNumber].to(unencoded[handleNumber]);
  1031. }
  1032. scope_Tooltips[handleNumber].innerHTML = formattedValue;
  1033. });
  1034. }
  1035. function aria() {
  1036. removeEvent("update" + INTERNAL_EVENT_NS.aria);
  1037. bindEvent("update" + INTERNAL_EVENT_NS.aria, function (values, handleNumber, unencoded, tap, positions) {
  1038. // Update Aria Values for all handles, as a change in one changes min and max values for the next.
  1039. scope_HandleNumbers.forEach(function (index) {
  1040. var handle = scope_Handles[index];
  1041. var min = checkHandlePosition(scope_Locations, index, 0, true, true, true);
  1042. var max = checkHandlePosition(scope_Locations, index, 100, true, true, true);
  1043. var now = positions[index];
  1044. // Formatted value for display
  1045. var text = String(options.ariaFormat.to(unencoded[index]));
  1046. // Map to slider range values
  1047. min = scope_Spectrum.fromStepping(min).toFixed(1);
  1048. max = scope_Spectrum.fromStepping(max).toFixed(1);
  1049. now = scope_Spectrum.fromStepping(now).toFixed(1);
  1050. handle.children[0].setAttribute("aria-valuemin", min);
  1051. handle.children[0].setAttribute("aria-valuemax", max);
  1052. handle.children[0].setAttribute("aria-valuenow", now);
  1053. handle.children[0].setAttribute("aria-valuetext", text);
  1054. });
  1055. });
  1056. }
  1057. function getGroup(pips) {
  1058. // Use the range.
  1059. if (pips.mode === exports.PipsMode.Range || pips.mode === exports.PipsMode.Steps) {
  1060. return scope_Spectrum.xVal;
  1061. }
  1062. if (pips.mode === exports.PipsMode.Count) {
  1063. if (pips.values < 2) {
  1064. throw new Error("noUiSlider: 'values' (>= 2) required for mode 'count'.");
  1065. }
  1066. // Divide 0 - 100 in 'count' parts.
  1067. var interval = pips.values - 1;
  1068. var spread = 100 / interval;
  1069. var values = [];
  1070. // List these parts and have them handled as 'positions'.
  1071. while (interval--) {
  1072. values[interval] = interval * spread;
  1073. }
  1074. values.push(100);
  1075. return mapToRange(values, pips.stepped);
  1076. }
  1077. if (pips.mode === exports.PipsMode.Positions) {
  1078. // Map all percentages to on-range values.
  1079. return mapToRange(pips.values, pips.stepped);
  1080. }
  1081. if (pips.mode === exports.PipsMode.Values) {
  1082. // If the value must be stepped, it needs to be converted to a percentage first.
  1083. if (pips.stepped) {
  1084. return pips.values.map(function (value) {
  1085. // Convert to percentage, apply step, return to value.
  1086. return scope_Spectrum.fromStepping(scope_Spectrum.getStep(scope_Spectrum.toStepping(value)));
  1087. });
  1088. }
  1089. // Otherwise, we can simply use the values.
  1090. return pips.values;
  1091. }
  1092. return []; // pips.mode = never
  1093. }
  1094. function mapToRange(values, stepped) {
  1095. return values.map(function (value) {
  1096. return scope_Spectrum.fromStepping(stepped ? scope_Spectrum.getStep(value) : value);
  1097. });
  1098. }
  1099. function generateSpread(pips) {
  1100. function safeIncrement(value, increment) {
  1101. // Avoid floating point variance by dropping the smallest decimal places.
  1102. return Number((value + increment).toFixed(7));
  1103. }
  1104. var group = getGroup(pips);
  1105. var indexes = {};
  1106. var firstInRange = scope_Spectrum.xVal[0];
  1107. var lastInRange = scope_Spectrum.xVal[scope_Spectrum.xVal.length - 1];
  1108. var ignoreFirst = false;
  1109. var ignoreLast = false;
  1110. var prevPct = 0;
  1111. // Create a copy of the group, sort it and filter away all duplicates.
  1112. group = unique(group.slice().sort(function (a, b) {
  1113. return a - b;
  1114. }));
  1115. // Make sure the range starts with the first element.
  1116. if (group[0] !== firstInRange) {
  1117. group.unshift(firstInRange);
  1118. ignoreFirst = true;
  1119. }
  1120. // Likewise for the last one.
  1121. if (group[group.length - 1] !== lastInRange) {
  1122. group.push(lastInRange);
  1123. ignoreLast = true;
  1124. }
  1125. group.forEach(function (current, index) {
  1126. // Get the current step and the lower + upper positions.
  1127. var step;
  1128. var i;
  1129. var q;
  1130. var low = current;
  1131. var high = group[index + 1];
  1132. var newPct;
  1133. var pctDifference;
  1134. var pctPos;
  1135. var type;
  1136. var steps;
  1137. var realSteps;
  1138. var stepSize;
  1139. var isSteps = pips.mode === exports.PipsMode.Steps;
  1140. // When using 'steps' mode, use the provided steps.
  1141. // Otherwise, we'll step on to the next subrange.
  1142. if (isSteps) {
  1143. step = scope_Spectrum.xNumSteps[index];
  1144. }
  1145. // Default to a 'full' step.
  1146. if (!step) {
  1147. step = high - low;
  1148. }
  1149. // If high is undefined we are at the last subrange. Make sure it iterates once (#1088)
  1150. if (high === undefined) {
  1151. high = low;
  1152. }
  1153. // Make sure step isn't 0, which would cause an infinite loop (#654)
  1154. step = Math.max(step, 0.0000001);
  1155. // Find all steps in the subrange.
  1156. for (i = low; i <= high; i = safeIncrement(i, step)) {
  1157. // Get the percentage value for the current step,
  1158. // calculate the size for the subrange.
  1159. newPct = scope_Spectrum.toStepping(i);
  1160. pctDifference = newPct - prevPct;
  1161. steps = pctDifference / (pips.density || 1);
  1162. realSteps = Math.round(steps);
  1163. // This ratio represents the amount of percentage-space a point indicates.
  1164. // For a density 1 the points/percentage = 1. For density 2, that percentage needs to be re-divided.
  1165. // Round the percentage offset to an even number, then divide by two
  1166. // to spread the offset on both sides of the range.
  1167. stepSize = pctDifference / realSteps;
  1168. // Divide all points evenly, adding the correct number to this subrange.
  1169. // Run up to <= so that 100% gets a point, event if ignoreLast is set.
  1170. for (q = 1; q <= realSteps; q += 1) {
  1171. // The ratio between the rounded value and the actual size might be ~1% off.
  1172. // Correct the percentage offset by the number of points
  1173. // per subrange. density = 1 will result in 100 points on the
  1174. // full range, 2 for 50, 4 for 25, etc.
  1175. pctPos = prevPct + q * stepSize;
  1176. indexes[pctPos.toFixed(5)] = [scope_Spectrum.fromStepping(pctPos), 0];
  1177. }
  1178. // Determine the point type.
  1179. type = group.indexOf(i) > -1 ? exports.PipsType.LargeValue : isSteps ? exports.PipsType.SmallValue : exports.PipsType.NoValue;
  1180. // Enforce the 'ignoreFirst' option by overwriting the type for 0.
  1181. if (!index && ignoreFirst && i !== high) {
  1182. type = 0;
  1183. }
  1184. if (!(i === high && ignoreLast)) {
  1185. // Mark the 'type' of this point. 0 = plain, 1 = real value, 2 = step value.
  1186. indexes[newPct.toFixed(5)] = [i, type];
  1187. }
  1188. // Update the percentage count.
  1189. prevPct = newPct;
  1190. }
  1191. });
  1192. return indexes;
  1193. }
  1194. function addMarking(spread, filterFunc, formatter) {
  1195. var _a, _b;
  1196. var element = scope_Document.createElement("div");
  1197. var valueSizeClasses = (_a = {},
  1198. _a[exports.PipsType.None] = "",
  1199. _a[exports.PipsType.NoValue] = options.cssClasses.valueNormal,
  1200. _a[exports.PipsType.LargeValue] = options.cssClasses.valueLarge,
  1201. _a[exports.PipsType.SmallValue] = options.cssClasses.valueSub,
  1202. _a);
  1203. var markerSizeClasses = (_b = {},
  1204. _b[exports.PipsType.None] = "",
  1205. _b[exports.PipsType.NoValue] = options.cssClasses.markerNormal,
  1206. _b[exports.PipsType.LargeValue] = options.cssClasses.markerLarge,
  1207. _b[exports.PipsType.SmallValue] = options.cssClasses.markerSub,
  1208. _b);
  1209. var valueOrientationClasses = [options.cssClasses.valueHorizontal, options.cssClasses.valueVertical];
  1210. var markerOrientationClasses = [options.cssClasses.markerHorizontal, options.cssClasses.markerVertical];
  1211. addClass(element, options.cssClasses.pips);
  1212. addClass(element, options.ort === 0 ? options.cssClasses.pipsHorizontal : options.cssClasses.pipsVertical);
  1213. function getClasses(type, source) {
  1214. var a = source === options.cssClasses.value;
  1215. var orientationClasses = a ? valueOrientationClasses : markerOrientationClasses;
  1216. var sizeClasses = a ? valueSizeClasses : markerSizeClasses;
  1217. return source + " " + orientationClasses[options.ort] + " " + sizeClasses[type];
  1218. }
  1219. function addSpread(offset, value, type) {
  1220. // Apply the filter function, if it is set.
  1221. type = filterFunc ? filterFunc(value, type) : type;
  1222. if (type === exports.PipsType.None) {
  1223. return;
  1224. }
  1225. // Add a marker for every point
  1226. var node = addNodeTo(element, false);
  1227. node.className = getClasses(type, options.cssClasses.marker);
  1228. node.style[options.style] = offset + "%";
  1229. // Values are only appended for points marked '1' or '2'.
  1230. if (type > exports.PipsType.NoValue) {
  1231. node = addNodeTo(element, false);
  1232. node.className = getClasses(type, options.cssClasses.value);
  1233. node.setAttribute("data-value", String(value));
  1234. node.style[options.style] = offset + "%";
  1235. node.innerHTML = String(formatter.to(value));
  1236. }
  1237. }
  1238. // Append all points.
  1239. Object.keys(spread).forEach(function (offset) {
  1240. addSpread(offset, spread[offset][0], spread[offset][1]);
  1241. });
  1242. return element;
  1243. }
  1244. function removePips() {
  1245. if (scope_Pips) {
  1246. removeElement(scope_Pips);
  1247. scope_Pips = null;
  1248. }
  1249. }
  1250. function pips(pips) {
  1251. // Fix #669
  1252. removePips();
  1253. var spread = generateSpread(pips);
  1254. var filter = pips.filter;
  1255. var format = pips.format || {
  1256. to: function (value) {
  1257. return String(Math.round(value));
  1258. }
  1259. };
  1260. scope_Pips = scope_Target.appendChild(addMarking(spread, filter, format));
  1261. return scope_Pips;
  1262. }
  1263. // Shorthand for base dimensions.
  1264. function baseSize() {
  1265. var rect = scope_Base.getBoundingClientRect();
  1266. var alt = ("offset" + ["Width", "Height"][options.ort]);
  1267. return options.ort === 0 ? rect.width || scope_Base[alt] : rect.height || scope_Base[alt];
  1268. }
  1269. // Handler for attaching events trough a proxy.
  1270. function attachEvent(events, element, callback, data) {
  1271. // This function can be used to 'filter' events to the slider.
  1272. // element is a node, not a nodeList
  1273. var method = function (event) {
  1274. var e = fixEvent(event, data.pageOffset, data.target || element);
  1275. // fixEvent returns false if this event has a different target
  1276. // when handling (multi-) touch events;
  1277. if (!e) {
  1278. return false;
  1279. }
  1280. // doNotReject is passed by all end events to make sure released touches
  1281. // are not rejected, leaving the slider "stuck" to the cursor;
  1282. if (isSliderDisabled() && !data.doNotReject) {
  1283. return false;
  1284. }
  1285. // Stop if an active 'tap' transition is taking place.
  1286. if (hasClass(scope_Target, options.cssClasses.tap) && !data.doNotReject) {
  1287. return false;
  1288. }
  1289. // Ignore right or middle clicks on start #454
  1290. if (events === actions.start && e.buttons !== undefined && e.buttons > 1) {
  1291. return false;
  1292. }
  1293. // Ignore right or middle clicks on start #454
  1294. if (data.hover && e.buttons) {
  1295. return false;
  1296. }
  1297. // 'supportsPassive' is only true if a browser also supports touch-action: none in CSS.
  1298. // iOS safari does not, so it doesn't get to benefit from passive scrolling. iOS does support
  1299. // touch-action: manipulation, but that allows panning, which breaks
  1300. // sliders after zooming/on non-responsive pages.
  1301. // See: https://bugs.webkit.org/show_bug.cgi?id=133112
  1302. if (!supportsPassive) {
  1303. e.preventDefault();
  1304. }
  1305. e.calcPoint = e.points[options.ort];
  1306. // Call the event handler with the event [ and additional data ].
  1307. callback(e, data);
  1308. return;
  1309. };
  1310. var methods = [];
  1311. // Bind a closure on the target for every event type.
  1312. events.split(" ").forEach(function (eventName) {
  1313. element.addEventListener(eventName, method, supportsPassive ? { passive: true } : false);
  1314. methods.push([eventName, method]);
  1315. });
  1316. return methods;
  1317. }
  1318. // Provide a clean event with standardized offset values.
  1319. function fixEvent(e, pageOffset, eventTarget) {
  1320. // Filter the event to register the type, which can be
  1321. // touch, mouse or pointer. Offset changes need to be
  1322. // made on an event specific basis.
  1323. var touch = e.type.indexOf("touch") === 0;
  1324. var mouse = e.type.indexOf("mouse") === 0;
  1325. var pointer = e.type.indexOf("pointer") === 0;
  1326. var x = 0;
  1327. var y = 0;
  1328. // IE10 implemented pointer events with a prefix;
  1329. if (e.type.indexOf("MSPointer") === 0) {
  1330. pointer = true;
  1331. }
  1332. // Erroneous events seem to be passed in occasionally on iOS/iPadOS after user finishes interacting with
  1333. // the slider. They appear to be of type MouseEvent, yet they don't have usual properties set. Ignore
  1334. // events that have no touches or buttons associated with them. (#1057, #1079, #1095)
  1335. if (e.type === "mousedown" && !e.buttons && !e.touches) {
  1336. return false;
  1337. }
  1338. // The only thing one handle should be concerned about is the touches that originated on top of it.
  1339. if (touch) {
  1340. // Returns true if a touch originated on the target.
  1341. var isTouchOnTarget = function (checkTouch) {
  1342. var target = checkTouch.target;
  1343. return (target === eventTarget ||
  1344. eventTarget.contains(target) ||
  1345. (e.composed && e.composedPath().shift() === eventTarget));
  1346. };
  1347. // In the case of touchstart events, we need to make sure there is still no more than one
  1348. // touch on the target so we look amongst all touches.
  1349. if (e.type === "touchstart") {
  1350. var targetTouches = Array.prototype.filter.call(e.touches, isTouchOnTarget);
  1351. // Do not support more than one touch per handle.
  1352. if (targetTouches.length > 1) {
  1353. return false;
  1354. }
  1355. x = targetTouches[0].pageX;
  1356. y = targetTouches[0].pageY;
  1357. }
  1358. else {
  1359. // In the other cases, find on changedTouches is enough.
  1360. var targetTouch = Array.prototype.find.call(e.changedTouches, isTouchOnTarget);
  1361. // Cancel if the target touch has not moved.
  1362. if (!targetTouch) {
  1363. return false;
  1364. }
  1365. x = targetTouch.pageX;
  1366. y = targetTouch.pageY;
  1367. }
  1368. }
  1369. pageOffset = pageOffset || getPageOffset(scope_Document);
  1370. if (mouse || pointer) {
  1371. x = e.clientX + pageOffset.x;
  1372. y = e.clientY + pageOffset.y;
  1373. }
  1374. e.pageOffset = pageOffset;
  1375. e.points = [x, y];
  1376. e.cursor = mouse || pointer; // Fix #435
  1377. return e;
  1378. }
  1379. // Translate a coordinate in the document to a percentage on the slider
  1380. function calcPointToPercentage(calcPoint) {
  1381. var location = calcPoint - offset(scope_Base, options.ort);
  1382. var proposal = (location * 100) / baseSize();
  1383. // Clamp proposal between 0% and 100%
  1384. // Out-of-bound coordinates may occur when .noUi-base pseudo-elements
  1385. // are used (e.g. contained handles feature)
  1386. proposal = limit(proposal);
  1387. return options.dir ? 100 - proposal : proposal;
  1388. }
  1389. // Find handle closest to a certain percentage on the slider
  1390. function getClosestHandle(clickedPosition) {
  1391. var smallestDifference = 100;
  1392. var handleNumber = false;
  1393. scope_Handles.forEach(function (handle, index) {
  1394. // Disabled handles are ignored
  1395. if (isHandleDisabled(index)) {
  1396. return;
  1397. }
  1398. var handlePosition = scope_Locations[index];
  1399. var differenceWithThisHandle = Math.abs(handlePosition - clickedPosition);
  1400. // Initial state
  1401. var clickAtEdge = differenceWithThisHandle === 100 && smallestDifference === 100;
  1402. // Difference with this handle is smaller than the previously checked handle
  1403. var isCloser = differenceWithThisHandle < smallestDifference;
  1404. var isCloserAfter = differenceWithThisHandle <= smallestDifference && clickedPosition > handlePosition;
  1405. if (isCloser || isCloserAfter || clickAtEdge) {
  1406. handleNumber = index;
  1407. smallestDifference = differenceWithThisHandle;
  1408. }
  1409. });
  1410. return handleNumber;
  1411. }
  1412. // Fire 'end' when a mouse or pen leaves the document.
  1413. function documentLeave(event, data) {
  1414. if (event.type === "mouseout" &&
  1415. event.target.nodeName === "HTML" &&
  1416. event.relatedTarget === null) {
  1417. eventEnd(event, data);
  1418. }
  1419. }
  1420. // Handle movement on document for handle and range drag.
  1421. function eventMove(event, data) {
  1422. // Fix #498
  1423. // Check value of .buttons in 'start' to work around a bug in IE10 mobile (data.buttonsProperty).
  1424. // https://connect.microsoft.com/IE/feedback/details/927005/mobile-ie10-windows-phone-buttons-property-of-pointermove-event-always-zero
  1425. // IE9 has .buttons and .which zero on mousemove.
  1426. // Firefox breaks the spec MDN defines.
  1427. if (navigator.appVersion.indexOf("MSIE 9") === -1 && event.buttons === 0 && data.buttonsProperty !== 0) {
  1428. return eventEnd(event, data);
  1429. }
  1430. // Check if we are moving up or down
  1431. var movement = (options.dir ? -1 : 1) * (event.calcPoint - data.startCalcPoint);
  1432. // Convert the movement into a percentage of the slider width/height
  1433. var proposal = (movement * 100) / data.baseSize;
  1434. moveHandles(movement > 0, proposal, data.locations, data.handleNumbers, data.connect);
  1435. }
  1436. // Unbind move events on document, call callbacks.
  1437. function eventEnd(event, data) {
  1438. // The handle is no longer active, so remove the class.
  1439. if (data.handle) {
  1440. removeClass(data.handle, options.cssClasses.active);
  1441. scope_ActiveHandlesCount -= 1;
  1442. }
  1443. // Unbind the move and end events, which are added on 'start'.
  1444. data.listeners.forEach(function (c) {
  1445. scope_DocumentElement.removeEventListener(c[0], c[1]);
  1446. });
  1447. if (scope_ActiveHandlesCount === 0) {
  1448. // Remove dragging class.
  1449. removeClass(scope_Target, options.cssClasses.drag);
  1450. setZindex();
  1451. // Remove cursor styles and text-selection events bound to the body.
  1452. if (event.cursor) {
  1453. scope_Body.style.cursor = "";
  1454. scope_Body.removeEventListener("selectstart", preventDefault);
  1455. }
  1456. }
  1457. data.handleNumbers.forEach(function (handleNumber) {
  1458. fireEvent("change", handleNumber);
  1459. fireEvent("set", handleNumber);
  1460. fireEvent("end", handleNumber);
  1461. });
  1462. }
  1463. // Bind move events on document.
  1464. function eventStart(event, data) {
  1465. // Ignore event if any handle is disabled
  1466. if (data.handleNumbers.some(isHandleDisabled)) {
  1467. return;
  1468. }
  1469. var handle;
  1470. if (data.handleNumbers.length === 1) {
  1471. var handleOrigin = scope_Handles[data.handleNumbers[0]];
  1472. handle = handleOrigin.children[0];
  1473. scope_ActiveHandlesCount += 1;
  1474. // Mark the handle as 'active' so it can be styled.
  1475. addClass(handle, options.cssClasses.active);
  1476. }
  1477. // A drag should never propagate up to the 'tap' event.
  1478. event.stopPropagation();
  1479. // Record the event listeners.
  1480. var listeners = [];
  1481. // Attach the move and end events.
  1482. var moveEvent = attachEvent(actions.move, scope_DocumentElement, eventMove, {
  1483. // The event target has changed so we need to propagate the original one so that we keep
  1484. // relying on it to extract target touches.
  1485. target: event.target,
  1486. handle: handle,
  1487. connect: data.connect,
  1488. listeners: listeners,
  1489. startCalcPoint: event.calcPoint,
  1490. baseSize: baseSize(),
  1491. pageOffset: event.pageOffset,
  1492. handleNumbers: data.handleNumbers,
  1493. buttonsProperty: event.buttons,
  1494. locations: scope_Locations.slice()
  1495. });
  1496. var endEvent = attachEvent(actions.end, scope_DocumentElement, eventEnd, {
  1497. target: event.target,
  1498. handle: handle,
  1499. listeners: listeners,
  1500. doNotReject: true,
  1501. handleNumbers: data.handleNumbers
  1502. });
  1503. var outEvent = attachEvent("mouseout", scope_DocumentElement, documentLeave, {
  1504. target: event.target,
  1505. handle: handle,
  1506. listeners: listeners,
  1507. doNotReject: true,
  1508. handleNumbers: data.handleNumbers
  1509. });
  1510. // We want to make sure we pushed the listeners in the listener list rather than creating
  1511. // a new one as it has already been passed to the event handlers.
  1512. listeners.push.apply(listeners, moveEvent.concat(endEvent, outEvent));
  1513. // Text selection isn't an issue on touch devices,
  1514. // so adding cursor styles can be skipped.
  1515. if (event.cursor) {
  1516. // Prevent the 'I' cursor and extend the range-drag cursor.
  1517. scope_Body.style.cursor = getComputedStyle(event.target).cursor;
  1518. // Mark the target with a dragging state.
  1519. if (scope_Handles.length > 1) {
  1520. addClass(scope_Target, options.cssClasses.drag);
  1521. }
  1522. // Prevent text selection when dragging the handles.
  1523. // In noUiSlider <= 9.2.0, this was handled by calling preventDefault on mouse/touch start/move,
  1524. // which is scroll blocking. The selectstart event is supported by FireFox starting from version 52,
  1525. // meaning the only holdout is iOS Safari. This doesn't matter: text selection isn't triggered there.
  1526. // The 'cursor' flag is false.
  1527. // See: http://caniuse.com/#search=selectstart
  1528. scope_Body.addEventListener("selectstart", preventDefault, false);
  1529. }
  1530. data.handleNumbers.forEach(function (handleNumber) {
  1531. fireEvent("start", handleNumber);
  1532. });
  1533. }
  1534. // Move closest handle to tapped location.
  1535. function eventTap(event) {
  1536. // The tap event shouldn't propagate up
  1537. event.stopPropagation();
  1538. var proposal = calcPointToPercentage(event.calcPoint);
  1539. var handleNumber = getClosestHandle(proposal);
  1540. // Tackle the case that all handles are 'disabled'.
  1541. if (handleNumber === false) {
  1542. return;
  1543. }
  1544. // Flag the slider as it is now in a transitional state.
  1545. // Transition takes a configurable amount of ms (default 300). Re-enable the slider after that.
  1546. if (!options.events.snap) {
  1547. addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
  1548. }
  1549. setHandle(handleNumber, proposal, true, true);
  1550. setZindex();
  1551. fireEvent("slide", handleNumber, true);
  1552. fireEvent("update", handleNumber, true);
  1553. fireEvent("change", handleNumber, true);
  1554. fireEvent("set", handleNumber, true);
  1555. if (options.events.snap) {
  1556. eventStart(event, { handleNumbers: [handleNumber] });
  1557. }
  1558. }
  1559. // Fires a 'hover' event for a hovered mouse/pen position.
  1560. function eventHover(event) {
  1561. var proposal = calcPointToPercentage(event.calcPoint);
  1562. var to = scope_Spectrum.getStep(proposal);
  1563. var value = scope_Spectrum.fromStepping(to);
  1564. Object.keys(scope_Events).forEach(function (targetEvent) {
  1565. if ("hover" === targetEvent.split(".")[0]) {
  1566. scope_Events[targetEvent].forEach(function (callback) {
  1567. callback.call(scope_Self, value);
  1568. });
  1569. }
  1570. });
  1571. }
  1572. // Handles keydown on focused handles
  1573. // Don't move the document when pressing arrow keys on focused handles
  1574. function eventKeydown(event, handleNumber) {
  1575. if (isSliderDisabled() || isHandleDisabled(handleNumber)) {
  1576. return false;
  1577. }
  1578. var horizontalKeys = ["Left", "Right"];
  1579. var verticalKeys = ["Down", "Up"];
  1580. var largeStepKeys = ["PageDown", "PageUp"];
  1581. var edgeKeys = ["Home", "End"];
  1582. if (options.dir && !options.ort) {
  1583. // On an right-to-left slider, the left and right keys act inverted
  1584. horizontalKeys.reverse();
  1585. }
  1586. else if (options.ort && !options.dir) {
  1587. // On a top-to-bottom slider, the up and down keys act inverted
  1588. verticalKeys.reverse();
  1589. largeStepKeys.reverse();
  1590. }
  1591. // Strip "Arrow" for IE compatibility. https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
  1592. var key = event.key.replace("Arrow", "");
  1593. var isLargeDown = key === largeStepKeys[0];
  1594. var isLargeUp = key === largeStepKeys[1];
  1595. var isDown = key === verticalKeys[0] || key === horizontalKeys[0] || isLargeDown;
  1596. var isUp = key === verticalKeys[1] || key === horizontalKeys[1] || isLargeUp;
  1597. var isMin = key === edgeKeys[0];
  1598. var isMax = key === edgeKeys[1];
  1599. if (!isDown && !isUp && !isMin && !isMax) {
  1600. return true;
  1601. }
  1602. event.preventDefault();
  1603. var to;
  1604. if (isUp || isDown) {
  1605. var multiplier = options.keyboardPageMultiplier;
  1606. var direction = isDown ? 0 : 1;
  1607. var steps = getNextStepsForHandle(handleNumber);
  1608. var step = steps[direction];
  1609. // At the edge of a slider, do nothing
  1610. if (step === null) {
  1611. return false;
  1612. }
  1613. // No step set, use the default of 10% of the sub-range
  1614. if (step === false) {
  1615. step = scope_Spectrum.getDefaultStep(scope_Locations[handleNumber], isDown, options.keyboardDefaultStep);
  1616. }
  1617. if (isLargeUp || isLargeDown) {
  1618. step *= multiplier;
  1619. }
  1620. // Step over zero-length ranges (#948);
  1621. step = Math.max(step, 0.0000001);
  1622. // Decrement for down steps
  1623. step = (isDown ? -1 : 1) * step;
  1624. to = scope_Values[handleNumber] + step;
  1625. }
  1626. else if (isMax) {
  1627. // End key
  1628. to = options.spectrum.xVal[options.spectrum.xVal.length - 1];
  1629. }
  1630. else {
  1631. // Home key
  1632. to = options.spectrum.xVal[0];
  1633. }
  1634. setHandle(handleNumber, scope_Spectrum.toStepping(to), true, true);
  1635. fireEvent("slide", handleNumber);
  1636. fireEvent("update", handleNumber);
  1637. fireEvent("change", handleNumber);
  1638. fireEvent("set", handleNumber);
  1639. return false;
  1640. }
  1641. // Attach events to several slider parts.
  1642. function bindSliderEvents(behaviour) {
  1643. // Attach the standard drag event to the handles.
  1644. if (!behaviour.fixed) {
  1645. scope_Handles.forEach(function (handle, index) {
  1646. // These events are only bound to the visual handle
  1647. // element, not the 'real' origin element.
  1648. attachEvent(actions.start, handle.children[0], eventStart, {
  1649. handleNumbers: [index]
  1650. });
  1651. });
  1652. }
  1653. // Attach the tap event to the slider base.
  1654. if (behaviour.tap) {
  1655. attachEvent(actions.start, scope_Base, eventTap, {});
  1656. }
  1657. // Fire hover events
  1658. if (behaviour.hover) {
  1659. attachEvent(actions.move, scope_Base, eventHover, {
  1660. hover: true
  1661. });
  1662. }
  1663. // Make the range draggable.
  1664. if (behaviour.drag) {
  1665. scope_Connects.forEach(function (connect, index) {
  1666. if (connect === false || index === 0 || index === scope_Connects.length - 1) {
  1667. return;
  1668. }
  1669. var handleBefore = scope_Handles[index - 1];
  1670. var handleAfter = scope_Handles[index];
  1671. var eventHolders = [connect];
  1672. addClass(connect, options.cssClasses.draggable);
  1673. // When the range is fixed, the entire range can
  1674. // be dragged by the handles. The handle in the first
  1675. // origin will propagate the start event upward,
  1676. // but it needs to be bound manually on the other.
  1677. if (behaviour.fixed) {
  1678. eventHolders.push(handleBefore.children[0]);
  1679. eventHolders.push(handleAfter.children[0]);
  1680. }
  1681. eventHolders.forEach(function (eventHolder) {
  1682. attachEvent(actions.start, eventHolder, eventStart, {
  1683. handles: [handleBefore, handleAfter],
  1684. handleNumbers: [index - 1, index],
  1685. connect: connect
  1686. });
  1687. });
  1688. });
  1689. }
  1690. }
  1691. // Attach an event to this slider, possibly including a namespace
  1692. function bindEvent(namespacedEvent, callback) {
  1693. scope_Events[namespacedEvent] = scope_Events[namespacedEvent] || [];
  1694. scope_Events[namespacedEvent].push(callback);
  1695. // If the event bound is 'update,' fire it immediately for all handles.
  1696. if (namespacedEvent.split(".")[0] === "update") {
  1697. scope_Handles.forEach(function (a, index) {
  1698. fireEvent("update", index);
  1699. });
  1700. }
  1701. }
  1702. function isInternalNamespace(namespace) {
  1703. return namespace === INTERNAL_EVENT_NS.aria || namespace === INTERNAL_EVENT_NS.tooltips;
  1704. }
  1705. // Undo attachment of event
  1706. function removeEvent(namespacedEvent) {
  1707. var event = namespacedEvent && namespacedEvent.split(".")[0];
  1708. var namespace = event ? namespacedEvent.substring(event.length) : namespacedEvent;
  1709. Object.keys(scope_Events).forEach(function (bind) {
  1710. var tEvent = bind.split(".")[0];
  1711. var tNamespace = bind.substring(tEvent.length);
  1712. if ((!event || event === tEvent) && (!namespace || namespace === tNamespace)) {
  1713. // only delete protected internal event if intentional
  1714. if (!isInternalNamespace(tNamespace) || namespace === tNamespace) {
  1715. delete scope_Events[bind];
  1716. }
  1717. }
  1718. });
  1719. }
  1720. // External event handling
  1721. function fireEvent(eventName, handleNumber, tap) {
  1722. Object.keys(scope_Events).forEach(function (targetEvent) {
  1723. var eventType = targetEvent.split(".")[0];
  1724. if (eventName === eventType) {
  1725. scope_Events[targetEvent].forEach(function (callback) {
  1726. callback.call(
  1727. // Use the slider public API as the scope ('this')
  1728. scope_Self,
  1729. // Return values as array, so arg_1[arg_2] is always valid.
  1730. scope_Values.map(options.format.to),
  1731. // Handle index, 0 or 1
  1732. handleNumber,
  1733. // Un-formatted slider values
  1734. scope_Values.slice(),
  1735. // Event is fired by tap, true or false
  1736. tap || false,
  1737. // Left offset of the handle, in relation to the slider
  1738. scope_Locations.slice(),
  1739. // add the slider public API to an accessible parameter when this is unavailable
  1740. scope_Self);
  1741. });
  1742. }
  1743. });
  1744. }
  1745. // Split out the handle positioning logic so the Move event can use it, too
  1746. function checkHandlePosition(reference, handleNumber, to, lookBackward, lookForward, getValue) {
  1747. var distance;
  1748. // For sliders with multiple handles, limit movement to the other handle.
  1749. // Apply the margin option by adding it to the handle positions.
  1750. if (scope_Handles.length > 1 && !options.events.unconstrained) {
  1751. if (lookBackward && handleNumber > 0) {
  1752. distance = scope_Spectrum.getAbsoluteDistance(reference[handleNumber - 1], options.margin, false);
  1753. to = Math.max(to, distance);
  1754. }
  1755. if (lookForward && handleNumber < scope_Handles.length - 1) {
  1756. distance = scope_Spectrum.getAbsoluteDistance(reference[handleNumber + 1], options.margin, true);
  1757. to = Math.min(to, distance);
  1758. }
  1759. }
  1760. // The limit option has the opposite effect, limiting handles to a
  1761. // maximum distance from another. Limit must be > 0, as otherwise
  1762. // handles would be unmovable.
  1763. if (scope_Handles.length > 1 && options.limit) {
  1764. if (lookBackward && handleNumber > 0) {
  1765. distance = scope_Spectrum.getAbsoluteDistance(reference[handleNumber - 1], options.limit, false);
  1766. to = Math.min(to, distance);
  1767. }
  1768. if (lookForward && handleNumber < scope_Handles.length - 1) {
  1769. distance = scope_Spectrum.getAbsoluteDistance(reference[handleNumber + 1], options.limit, true);
  1770. to = Math.max(to, distance);
  1771. }
  1772. }
  1773. // The padding option keeps the handles a certain distance from the
  1774. // edges of the slider. Padding must be > 0.
  1775. if (options.padding) {
  1776. if (handleNumber === 0) {
  1777. distance = scope_Spectrum.getAbsoluteDistance(0, options.padding[0], false);
  1778. to = Math.max(to, distance);
  1779. }
  1780. if (handleNumber === scope_Handles.length - 1) {
  1781. distance = scope_Spectrum.getAbsoluteDistance(100, options.padding[1], true);
  1782. to = Math.min(to, distance);
  1783. }
  1784. }
  1785. to = scope_Spectrum.getStep(to);
  1786. // Limit percentage to the 0 - 100 range
  1787. to = limit(to);
  1788. // Return false if handle can't move
  1789. if (to === reference[handleNumber] && !getValue) {
  1790. return false;
  1791. }
  1792. return to;
  1793. }
  1794. // Uses slider orientation to create CSS rules. a = base value;
  1795. function inRuleOrder(v, a) {
  1796. var o = options.ort;
  1797. return (o ? a : v) + ", " + (o ? v : a);
  1798. }
  1799. // Moves handle(s) by a percentage
  1800. // (bool, % to move, [% where handle started, ...], [index in scope_Handles, ...])
  1801. function moveHandles(upward, proposal, locations, handleNumbers, connect) {
  1802. var proposals = locations.slice();
  1803. // Store first handle now, so we still have it in case handleNumbers is reversed
  1804. var firstHandle = handleNumbers[0];
  1805. var b = [!upward, upward];
  1806. var f = [upward, !upward];
  1807. // Copy handleNumbers so we don't change the dataset
  1808. handleNumbers = handleNumbers.slice();
  1809. // Check to see which handle is 'leading'.
  1810. // If that one can't move the second can't either.
  1811. if (upward) {
  1812. handleNumbers.reverse();
  1813. }
  1814. // Step 1: get the maximum percentage that any of the handles can move
  1815. if (handleNumbers.length > 1) {
  1816. handleNumbers.forEach(function (handleNumber, o) {
  1817. var to = checkHandlePosition(proposals, handleNumber, proposals[handleNumber] + proposal, b[o], f[o], false);
  1818. // Stop if one of the handles can't move.
  1819. if (to === false) {
  1820. proposal = 0;
  1821. }
  1822. else {
  1823. proposal = to - proposals[handleNumber];
  1824. proposals[handleNumber] = to;
  1825. }
  1826. });
  1827. }
  1828. // If using one handle, check backward AND forward
  1829. else {
  1830. b = f = [true];
  1831. }
  1832. var state = false;
  1833. // Step 2: Try to set the handles with the found percentage
  1834. handleNumbers.forEach(function (handleNumber, o) {
  1835. state = setHandle(handleNumber, locations[handleNumber] + proposal, b[o], f[o]) || state;
  1836. });
  1837. // Step 3: If a handle moved, fire events
  1838. if (state) {
  1839. handleNumbers.forEach(function (handleNumber) {
  1840. fireEvent("update", handleNumber);
  1841. fireEvent("slide", handleNumber);
  1842. });
  1843. // If target is a connect, then fire drag event
  1844. if (connect != undefined) {
  1845. fireEvent("drag", firstHandle);
  1846. }
  1847. }
  1848. }
  1849. // Takes a base value and an offset. This offset is used for the connect bar size.
  1850. // In the initial design for this feature, the origin element was 1% wide.
  1851. // Unfortunately, a rounding bug in Chrome makes it impossible to implement this feature
  1852. // in this manner: https://bugs.chromium.org/p/chromium/issues/detail?id=798223
  1853. function transformDirection(a, b) {
  1854. return options.dir ? 100 - a - b : a;
  1855. }
  1856. // Updates scope_Locations and scope_Values, updates visual state
  1857. function updateHandlePosition(handleNumber, to) {
  1858. // Update locations.
  1859. scope_Locations[handleNumber] = to;
  1860. // Convert the value to the slider stepping/range.
  1861. scope_Values[handleNumber] = scope_Spectrum.fromStepping(to);
  1862. var translation = 10 * (transformDirection(to, 0) - scope_DirOffset);
  1863. var translateRule = "translate(" + inRuleOrder(translation + "%", "0") + ")";
  1864. scope_Handles[handleNumber].style[options.transformRule] = translateRule;
  1865. updateConnect(handleNumber);
  1866. updateConnect(handleNumber + 1);
  1867. }
  1868. // Handles before the slider middle are stacked later = higher,
  1869. // Handles after the middle later is lower
  1870. // [[7] [8] .......... | .......... [5] [4]
  1871. function setZindex() {
  1872. scope_HandleNumbers.forEach(function (handleNumber) {
  1873. var dir = scope_Locations[handleNumber] > 50 ? -1 : 1;
  1874. var zIndex = 3 + (scope_Handles.length + dir * handleNumber);
  1875. scope_Handles[handleNumber].style.zIndex = String(zIndex);
  1876. });
  1877. }
  1878. // Test suggested values and apply margin, step.
  1879. // if exactInput is true, don't run checkHandlePosition, then the handle can be placed in between steps (#436)
  1880. function setHandle(handleNumber, to, lookBackward, lookForward, exactInput) {
  1881. if (!exactInput) {
  1882. to = checkHandlePosition(scope_Locations, handleNumber, to, lookBackward, lookForward, false);
  1883. }
  1884. if (to === false) {
  1885. return false;
  1886. }
  1887. updateHandlePosition(handleNumber, to);
  1888. return true;
  1889. }
  1890. // Updates style attribute for connect nodes
  1891. function updateConnect(index) {
  1892. // Skip connects set to false
  1893. if (!scope_Connects[index]) {
  1894. return;
  1895. }
  1896. var l = 0;
  1897. var h = 100;
  1898. if (index !== 0) {
  1899. l = scope_Locations[index - 1];
  1900. }
  1901. if (index !== scope_Connects.length - 1) {
  1902. h = scope_Locations[index];
  1903. }
  1904. // We use two rules:
  1905. // 'translate' to change the left/top offset;
  1906. // 'scale' to change the width of the element;
  1907. // As the element has a width of 100%, a translation of 100% is equal to 100% of the parent (.noUi-base)
  1908. var connectWidth = h - l;
  1909. var translateRule = "translate(" + inRuleOrder(transformDirection(l, connectWidth) + "%", "0") + ")";
  1910. var scaleRule = "scale(" + inRuleOrder(connectWidth / 100, "1") + ")";
  1911. scope_Connects[index].style[options.transformRule] =
  1912. translateRule + " " + scaleRule;
  1913. }
  1914. // Parses value passed to .set method. Returns current value if not parse-able.
  1915. function resolveToValue(to, handleNumber) {
  1916. // Setting with null indicates an 'ignore'.
  1917. // Inputting 'false' is invalid.
  1918. if (to === null || to === false || to === undefined) {
  1919. return scope_Locations[handleNumber];
  1920. }
  1921. // If a formatted number was passed, attempt to decode it.
  1922. if (typeof to === "number") {
  1923. to = String(to);
  1924. }
  1925. to = options.format.from(to);
  1926. if (to !== false) {
  1927. to = scope_Spectrum.toStepping(to);
  1928. }
  1929. // If parsing the number failed, use the current value.
  1930. if (to === false || isNaN(to)) {
  1931. return scope_Locations[handleNumber];
  1932. }
  1933. return to;
  1934. }
  1935. // Set the slider value.
  1936. function valueSet(input, fireSetEvent, exactInput) {
  1937. var values = asArray(input);
  1938. var isInit = scope_Locations[0] === undefined;
  1939. // Event fires by default
  1940. fireSetEvent = fireSetEvent === undefined ? true : fireSetEvent;
  1941. // Animation is optional.
  1942. // Make sure the initial values were set before using animated placement.
  1943. if (options.animate && !isInit) {
  1944. addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
  1945. }
  1946. // First pass, without lookAhead but with lookBackward. Values are set from left to right.
  1947. scope_HandleNumbers.forEach(function (handleNumber) {
  1948. setHandle(handleNumber, resolveToValue(values[handleNumber], handleNumber), true, false, exactInput);
  1949. });
  1950. var i = scope_HandleNumbers.length === 1 ? 0 : 1;
  1951. // Secondary passes. Now that all base values are set, apply constraints.
  1952. // Iterate all handles to ensure constraints are applied for the entire slider (Issue #1009)
  1953. for (; i < scope_HandleNumbers.length; ++i) {
  1954. scope_HandleNumbers.forEach(function (handleNumber) {
  1955. setHandle(handleNumber, scope_Locations[handleNumber], true, true, exactInput);
  1956. });
  1957. }
  1958. setZindex();
  1959. scope_HandleNumbers.forEach(function (handleNumber) {
  1960. fireEvent("update", handleNumber);
  1961. // Fire the event only for handles that received a new value, as per #579
  1962. if (values[handleNumber] !== null && fireSetEvent) {
  1963. fireEvent("set", handleNumber);
  1964. }
  1965. });
  1966. }
  1967. // Reset slider to initial values
  1968. function valueReset(fireSetEvent) {
  1969. valueSet(options.start, fireSetEvent);
  1970. }
  1971. // Set value for a single handle
  1972. function valueSetHandle(handleNumber, value, fireSetEvent, exactInput) {
  1973. // Ensure numeric input
  1974. handleNumber = Number(handleNumber);
  1975. if (!(handleNumber >= 0 && handleNumber < scope_HandleNumbers.length)) {
  1976. throw new Error("noUiSlider: invalid handle number, got: " + handleNumber);
  1977. }
  1978. // Look both backward and forward, since we don't want this handle to "push" other handles (#960);
  1979. // The exactInput argument can be used to ignore slider stepping (#436)
  1980. setHandle(handleNumber, resolveToValue(value, handleNumber), true, true, exactInput);
  1981. fireEvent("update", handleNumber);
  1982. if (fireSetEvent) {
  1983. fireEvent("set", handleNumber);
  1984. }
  1985. }
  1986. // Get the slider value.
  1987. function valueGet(unencoded) {
  1988. if (unencoded === void 0) { unencoded = false; }
  1989. if (unencoded) {
  1990. // return a copy of the raw values
  1991. return scope_Values.length === 1 ? scope_Values[0] : scope_Values.slice(0);
  1992. }
  1993. var values = scope_Values.map(options.format.to);
  1994. // If only one handle is used, return a single value.
  1995. if (values.length === 1) {
  1996. return values[0];
  1997. }
  1998. return values;
  1999. }
  2000. // Removes classes from the root and empties it.
  2001. function destroy() {
  2002. // remove protected internal listeners
  2003. removeEvent(INTERNAL_EVENT_NS.aria);
  2004. removeEvent(INTERNAL_EVENT_NS.tooltips);
  2005. Object.keys(options.cssClasses).forEach(function (key) {
  2006. removeClass(scope_Target, options.cssClasses[key]);
  2007. });
  2008. while (scope_Target.firstChild) {
  2009. scope_Target.removeChild(scope_Target.firstChild);
  2010. }
  2011. delete scope_Target.noUiSlider;
  2012. }
  2013. function getNextStepsForHandle(handleNumber) {
  2014. var location = scope_Locations[handleNumber];
  2015. var nearbySteps = scope_Spectrum.getNearbySteps(location);
  2016. var value = scope_Values[handleNumber];
  2017. var increment = nearbySteps.thisStep.step;
  2018. var decrement = null;
  2019. // If snapped, directly use defined step value
  2020. if (options.snap) {
  2021. return [
  2022. value - nearbySteps.stepBefore.startValue || null,
  2023. nearbySteps.stepAfter.startValue - value || null
  2024. ];
  2025. }
  2026. // If the next value in this step moves into the next step,
  2027. // the increment is the start of the next step - the current value
  2028. if (increment !== false) {
  2029. if (value + increment > nearbySteps.stepAfter.startValue) {
  2030. increment = nearbySteps.stepAfter.startValue - value;
  2031. }
  2032. }
  2033. // If the value is beyond the starting point
  2034. if (value > nearbySteps.thisStep.startValue) {
  2035. decrement = nearbySteps.thisStep.step;
  2036. }
  2037. else if (nearbySteps.stepBefore.step === false) {
  2038. decrement = false;
  2039. }
  2040. // If a handle is at the start of a step, it always steps back into the previous step first
  2041. else {
  2042. decrement = value - nearbySteps.stepBefore.highestStep;
  2043. }
  2044. // Now, if at the slider edges, there is no in/decrement
  2045. if (location === 100) {
  2046. increment = null;
  2047. }
  2048. else if (location === 0) {
  2049. decrement = null;
  2050. }
  2051. // As per #391, the comparison for the decrement step can have some rounding issues.
  2052. var stepDecimals = scope_Spectrum.countStepDecimals();
  2053. // Round per #391
  2054. if (increment !== null && increment !== false) {
  2055. increment = Number(increment.toFixed(stepDecimals));
  2056. }
  2057. if (decrement !== null && decrement !== false) {
  2058. decrement = Number(decrement.toFixed(stepDecimals));
  2059. }
  2060. return [decrement, increment];
  2061. }
  2062. // Get the current step size for the slider.
  2063. function getNextSteps() {
  2064. return scope_HandleNumbers.map(getNextStepsForHandle);
  2065. }
  2066. // Updatable: margin, limit, padding, step, range, animate, snap
  2067. function updateOptions(optionsToUpdate, fireSetEvent) {
  2068. // Spectrum is created using the range, snap, direction and step options.
  2069. // 'snap' and 'step' can be updated.
  2070. // If 'snap' and 'step' are not passed, they should remain unchanged.
  2071. var v = valueGet();
  2072. var updateAble = [
  2073. "margin",
  2074. "limit",
  2075. "padding",
  2076. "range",
  2077. "animate",
  2078. "snap",
  2079. "step",
  2080. "format",
  2081. "pips",
  2082. "tooltips"
  2083. ];
  2084. // Only change options that we're actually passed to update.
  2085. updateAble.forEach(function (name) {
  2086. // Check for undefined. null removes the value.
  2087. if (optionsToUpdate[name] !== undefined) {
  2088. originalOptions[name] = optionsToUpdate[name];
  2089. }
  2090. });
  2091. var newOptions = testOptions(originalOptions);
  2092. // Load new options into the slider state
  2093. updateAble.forEach(function (name) {
  2094. if (optionsToUpdate[name] !== undefined) {
  2095. options[name] = newOptions[name];
  2096. }
  2097. });
  2098. scope_Spectrum = newOptions.spectrum;
  2099. // Limit, margin and padding depend on the spectrum but are stored outside of it. (#677)
  2100. options.margin = newOptions.margin;
  2101. options.limit = newOptions.limit;
  2102. options.padding = newOptions.padding;
  2103. // Update pips, removes existing.
  2104. if (options.pips) {
  2105. pips(options.pips);
  2106. }
  2107. else {
  2108. removePips();
  2109. }
  2110. // Update tooltips, removes existing.
  2111. if (options.tooltips) {
  2112. tooltips();
  2113. }
  2114. else {
  2115. removeTooltips();
  2116. }
  2117. // Invalidate the current positioning so valueSet forces an update.
  2118. scope_Locations = [];
  2119. valueSet(isSet(optionsToUpdate.start) ? optionsToUpdate.start : v, fireSetEvent);
  2120. }
  2121. // Initialization steps
  2122. function setupSlider() {
  2123. // Create the base element, initialize HTML and set classes.
  2124. // Add handles and connect elements.
  2125. scope_Base = addSlider(scope_Target);
  2126. addElements(options.connect, scope_Base);
  2127. // Attach user events.
  2128. bindSliderEvents(options.events);
  2129. // Use the public value method to set the start values.
  2130. valueSet(options.start);
  2131. if (options.pips) {
  2132. pips(options.pips);
  2133. }
  2134. if (options.tooltips) {
  2135. tooltips();
  2136. }
  2137. aria();
  2138. }
  2139. setupSlider();
  2140. var scope_Self = {
  2141. destroy: destroy,
  2142. steps: getNextSteps,
  2143. on: bindEvent,
  2144. off: removeEvent,
  2145. get: valueGet,
  2146. set: valueSet,
  2147. setHandle: valueSetHandle,
  2148. reset: valueReset,
  2149. // Exposed for unit testing, don't use this in your application.
  2150. __moveHandles: function (upward, proposal, handleNumbers) {
  2151. moveHandles(upward, proposal, scope_Locations, handleNumbers);
  2152. },
  2153. options: originalOptions,
  2154. updateOptions: updateOptions,
  2155. target: scope_Target,
  2156. removePips: removePips,
  2157. removeTooltips: removeTooltips,
  2158. getTooltips: function () {
  2159. return scope_Tooltips;
  2160. },
  2161. getOrigins: function () {
  2162. return scope_Handles;
  2163. },
  2164. pips: pips // Issue #594
  2165. };
  2166. return scope_Self;
  2167. }
  2168. // Run the standard initializer
  2169. function initialize(target, originalOptions) {
  2170. if (!target || !target.nodeName) {
  2171. throw new Error("noUiSlider: create requires a single element, got: " + target);
  2172. }
  2173. // Throw an error if the slider was already initialized.
  2174. if (target.noUiSlider) {
  2175. throw new Error("noUiSlider: Slider was already initialized.");
  2176. }
  2177. // Test the options and create the slider environment;
  2178. var options = testOptions(originalOptions);
  2179. var api = scope(target, options, originalOptions);
  2180. target.noUiSlider = api;
  2181. return api;
  2182. }
  2183. var nouislider = {
  2184. // Exposed for unit testing, don't use this in your application.
  2185. __spectrum: Spectrum,
  2186. // A reference to the default classes, allows global changes.
  2187. // Use the cssClasses option for changes to one slider.
  2188. cssClasses: cssClasses,
  2189. create: initialize
  2190. };
  2191. exports.create = initialize;
  2192. exports.cssClasses = cssClasses;
  2193. exports.default = nouislider;
  2194. Object.defineProperty(exports, '__esModule', { value: true });
  2195. })));