nouislider.js 89 KB

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