您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

6661 行
354KB

  1. /*!
  2. * OverlayScrollbars
  3. * https://github.com/KingSora/OverlayScrollbars
  4. *
  5. * Version: 1.13.0
  6. *
  7. * Copyright KingSora | Rene Haas.
  8. * https://github.com/KingSora
  9. *
  10. * Released under the MIT license.
  11. * Date: 02.08.2020
  12. */
  13. (function (global, factory) {
  14. if (typeof define === 'function' && define.amd)
  15. define(function () { return factory(global, global.document, undefined); });
  16. else if (typeof module === 'object' && typeof module.exports === 'object')
  17. module.exports = factory(global, global.document, undefined);
  18. else
  19. factory(global, global.document, undefined);
  20. }(typeof window !== 'undefined' ? window : this,
  21. function (window, document, undefined) {
  22. 'use strict';
  23. var PLUGINNAME = 'OverlayScrollbars';
  24. var TYPES = {
  25. o: 'object',
  26. f: 'function',
  27. a: 'array',
  28. s: 'string',
  29. b: 'boolean',
  30. n: 'number',
  31. u: 'undefined',
  32. z: 'null'
  33. //d : 'date',
  34. //e : 'error',
  35. //r : 'regexp',
  36. //y : 'symbol'
  37. };
  38. var LEXICON = {
  39. c: 'class',
  40. s: 'style',
  41. i: 'id',
  42. l: 'length',
  43. p: 'prototype',
  44. ti: 'tabindex',
  45. oH: 'offsetHeight',
  46. cH: 'clientHeight',
  47. sH: 'scrollHeight',
  48. oW: 'offsetWidth',
  49. cW: 'clientWidth',
  50. sW: 'scrollWidth',
  51. hOP: 'hasOwnProperty',
  52. bCR: 'getBoundingClientRect'
  53. };
  54. var VENDORS = (function () {
  55. //https://developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix
  56. var jsCache = {};
  57. var cssCache = {};
  58. var cssPrefixes = ['-webkit-', '-moz-', '-o-', '-ms-'];
  59. var jsPrefixes = ['WebKit', 'Moz', 'O', 'MS'];
  60. function firstLetterToUpper(str) {
  61. return str.charAt(0).toUpperCase() + str.slice(1);
  62. }
  63. return {
  64. _cssPrefixes: cssPrefixes,
  65. _jsPrefixes: jsPrefixes,
  66. _cssProperty: function (name) {
  67. var result = cssCache[name];
  68. if (cssCache[LEXICON.hOP](name))
  69. return result;
  70. var uppercasedName = firstLetterToUpper(name);
  71. var elmStyle = document.createElement('div')[LEXICON.s];
  72. var resultPossibilities;
  73. var i = 0;
  74. var v;
  75. var currVendorWithoutDashes;
  76. for (; i < cssPrefixes.length; i++) {
  77. currVendorWithoutDashes = cssPrefixes[i].replace(/-/g, '');
  78. resultPossibilities = [
  79. name, //transition
  80. cssPrefixes[i] + name, //-webkit-transition
  81. currVendorWithoutDashes + uppercasedName, //webkitTransition
  82. firstLetterToUpper(currVendorWithoutDashes) + uppercasedName //WebkitTransition
  83. ];
  84. for (v = 0; v < resultPossibilities[LEXICON.l]; v++) {
  85. if (elmStyle[resultPossibilities[v]] !== undefined) {
  86. result = resultPossibilities[v];
  87. break;
  88. }
  89. }
  90. }
  91. cssCache[name] = result;
  92. return result;
  93. },
  94. _cssPropertyValue: function (property, values, suffix) {
  95. var name = property + ' ' + values;
  96. var result = cssCache[name];
  97. if (cssCache[LEXICON.hOP](name))
  98. return result;
  99. var dummyStyle = document.createElement('div')[LEXICON.s];
  100. var possbleValues = values.split(' ');
  101. var preparedSuffix = suffix || '';
  102. var i = 0;
  103. var v = -1;
  104. var prop;
  105. for (; i < possbleValues[LEXICON.l]; i++) {
  106. for (; v < VENDORS._cssPrefixes[LEXICON.l]; v++) {
  107. prop = v < 0 ? possbleValues[i] : VENDORS._cssPrefixes[v] + possbleValues[i];
  108. dummyStyle.cssText = property + ':' + prop + preparedSuffix;
  109. if (dummyStyle[LEXICON.l]) {
  110. result = prop;
  111. break;
  112. }
  113. }
  114. }
  115. cssCache[name] = result;
  116. return result;
  117. },
  118. _jsAPI: function (name, isInterface, fallback) {
  119. var i = 0;
  120. var result = jsCache[name];
  121. if (!jsCache[LEXICON.hOP](name)) {
  122. result = window[name];
  123. for (; i < jsPrefixes[LEXICON.l]; i++)
  124. result = result || window[(isInterface ? jsPrefixes[i] : jsPrefixes[i].toLowerCase()) + firstLetterToUpper(name)];
  125. jsCache[name] = result;
  126. }
  127. return result || fallback;
  128. }
  129. }
  130. })();
  131. var COMPATIBILITY = (function () {
  132. function windowSize(x) {
  133. return x ? window.innerWidth || document.documentElement[LEXICON.cW] || document.body[LEXICON.cW] : window.innerHeight || document.documentElement[LEXICON.cH] || document.body[LEXICON.cH];
  134. }
  135. function bind(func, thisObj) {
  136. if (typeof func != TYPES.f) {
  137. throw "Can't bind function!";
  138. // closest thing possible to the ECMAScript 5
  139. // internal IsCallable function
  140. //throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
  141. }
  142. var proto = LEXICON.p;
  143. var aArgs = Array[proto].slice.call(arguments, 2);
  144. var fNOP = function () { };
  145. var fBound = function () { return func.apply(this instanceof fNOP ? this : thisObj, aArgs.concat(Array[proto].slice.call(arguments))); };
  146. if (func[proto])
  147. fNOP[proto] = func[proto]; // Function.prototype doesn't have a prototype property
  148. fBound[proto] = new fNOP();
  149. return fBound;
  150. }
  151. return {
  152. /**
  153. * Gets the current window width.
  154. * @returns {Number|number} The current window width in pixel.
  155. */
  156. wW: bind(windowSize, 0, true),
  157. /**
  158. * Gets the current window height.
  159. * @returns {Number|number} The current window height in pixel.
  160. */
  161. wH: bind(windowSize, 0),
  162. /**
  163. * Gets the MutationObserver Object or undefined if not supported.
  164. * @returns {MutationObserver|*|undefined} The MutationsObserver Object or undefined.
  165. */
  166. mO: bind(VENDORS._jsAPI, 0, 'MutationObserver', true),
  167. /**
  168. * Gets the ResizeObserver Object or undefined if not supported.
  169. * @returns {MutationObserver|*|undefined} The ResizeObserver Object or undefined.
  170. */
  171. rO: bind(VENDORS._jsAPI, 0, 'ResizeObserver', true),
  172. /**
  173. * Gets the RequestAnimationFrame method or it's corresponding polyfill.
  174. * @returns {*|Function} The RequestAnimationFrame method or it's corresponding polyfill.
  175. */
  176. rAF: bind(VENDORS._jsAPI, 0, 'requestAnimationFrame', false, function (func) { return window.setTimeout(func, 1000 / 60); }),
  177. /**
  178. * Gets the CancelAnimationFrame method or it's corresponding polyfill.
  179. * @returns {*|Function} The CancelAnimationFrame method or it's corresponding polyfill.
  180. */
  181. cAF: bind(VENDORS._jsAPI, 0, 'cancelAnimationFrame', false, function (id) { return window.clearTimeout(id); }),
  182. /**
  183. * Gets the current time.
  184. * @returns {number} The current time.
  185. */
  186. now: function () {
  187. return Date.now && Date.now() || new Date().getTime();
  188. },
  189. /**
  190. * Stops the propagation of the given event.
  191. * @param event The event of which the propagation shall be stoped.
  192. */
  193. stpP: function (event) {
  194. if (event.stopPropagation)
  195. event.stopPropagation();
  196. else
  197. event.cancelBubble = true;
  198. },
  199. /**
  200. * Prevents the default action of the given event.
  201. * @param event The event of which the default action shall be prevented.
  202. */
  203. prvD: function (event) {
  204. if (event.preventDefault && event.cancelable)
  205. event.preventDefault();
  206. else
  207. event.returnValue = false;
  208. },
  209. /**
  210. * Gets the pageX and pageY values of the given mouse event.
  211. * @param event The mouse event of which the pageX and pageX shall be got.
  212. * @returns {{x: number, y: number}} x = pageX value, y = pageY value.
  213. */
  214. page: function (event) {
  215. event = event.originalEvent || event;
  216. var strPage = 'page';
  217. var strClient = 'client';
  218. var strX = 'X';
  219. var strY = 'Y';
  220. var target = event.target || event.srcElement || document;
  221. var eventDoc = target.ownerDocument || document;
  222. var doc = eventDoc.documentElement;
  223. var body = eventDoc.body;
  224. //if touch event return return pageX/Y of it
  225. if (event.touches !== undefined) {
  226. var touch = event.touches[0];
  227. return {
  228. x: touch[strPage + strX],
  229. y: touch[strPage + strY]
  230. }
  231. }
  232. // Calculate pageX/Y if not native supported
  233. if (!event[strPage + strX] && event[strClient + strX] && event[strClient + strX] != null) {
  234. return {
  235. x: event[strClient + strX] +
  236. (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
  237. (doc && doc.clientLeft || body && body.clientLeft || 0),
  238. y: event[strClient + strY] +
  239. (doc && doc.scrollTop || body && body.scrollTop || 0) -
  240. (doc && doc.clientTop || body && body.clientTop || 0)
  241. }
  242. }
  243. return {
  244. x: event[strPage + strX],
  245. y: event[strPage + strY]
  246. };
  247. },
  248. /**
  249. * Gets the clicked mouse button of the given mouse event.
  250. * @param event The mouse event of which the clicked button shal be got.
  251. * @returns {number} The number of the clicked mouse button. (0 : none | 1 : leftButton | 2 : middleButton | 3 : rightButton)
  252. */
  253. mBtn: function (event) {
  254. var button = event.button;
  255. if (!event.which && button !== undefined)
  256. return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  257. else
  258. return event.which;
  259. },
  260. /**
  261. * Checks whether a item is in the given array and returns its index.
  262. * @param item The item of which the position in the array shall be determined.
  263. * @param arr The array.
  264. * @returns {number} The zero based index of the item or -1 if the item isn't in the array.
  265. */
  266. inA: function (item, arr) {
  267. for (var i = 0; i < arr[LEXICON.l]; i++)
  268. //Sometiems in IE a "SCRIPT70" Permission denied error occurs if HTML elements in a iFrame are compared
  269. try {
  270. if (arr[i] === item)
  271. return i;
  272. }
  273. catch (e) { }
  274. return -1;
  275. },
  276. /**
  277. * Returns true if the given value is a array.
  278. * @param arr The potential array.
  279. * @returns {boolean} True if the given value is a array, false otherwise.
  280. */
  281. isA: function (arr) {
  282. var def = Array.isArray;
  283. return def ? def(arr) : this.type(arr) == TYPES.a;
  284. },
  285. /**
  286. * Determine the internal JavaScript [[Class]] of the given object.
  287. * @param obj The object of which the type shall be determined.
  288. * @returns {string} The type of the given object.
  289. */
  290. type: function (obj) {
  291. if (obj === undefined)
  292. return obj + '';
  293. if (obj === null)
  294. return obj + '';
  295. return Object[LEXICON.p].toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();
  296. },
  297. bind: bind
  298. /**
  299. * Gets the vendor-prefixed CSS property by the given name.
  300. * For example the given name is "transform" and you're using a old Firefox browser then the returned value would be "-moz-transform".
  301. * If the browser doesn't need a vendor-prefix, then the returned string is the given name.
  302. * If the browser doesn't support the given property name at all (not even with a vendor-prefix) the returned value is null.
  303. * @param propName The unprefixed CSS property name.
  304. * @returns {string|null} The vendor-prefixed CSS property or null if the browser doesn't support the given CSS property.
  305. cssProp: function(propName) {
  306. return VENDORS._cssProperty(propName);
  307. }
  308. */
  309. }
  310. })();
  311. var MATH = Math;
  312. var JQUERY = window.jQuery;
  313. var EASING = (function () {
  314. var _easingsMath = {
  315. p: MATH.PI,
  316. c: MATH.cos,
  317. s: MATH.sin,
  318. w: MATH.pow,
  319. t: MATH.sqrt,
  320. n: MATH.asin,
  321. a: MATH.abs,
  322. o: 1.70158
  323. };
  324. /*
  325. x : current percent (0 - 1),
  326. t : current time (duration * percent),
  327. b : start value (from),
  328. c : end value (to),
  329. d : duration
  330. easingName : function(x, t, b, c, d) { return easedValue; }
  331. */
  332. return {
  333. swing: function (x, t, b, c, d) {
  334. return 0.5 - _easingsMath.c(x * _easingsMath.p) / 2;
  335. },
  336. linear: function (x, t, b, c, d) {
  337. return x;
  338. },
  339. easeInQuad: function (x, t, b, c, d) {
  340. return c * (t /= d) * t + b;
  341. },
  342. easeOutQuad: function (x, t, b, c, d) {
  343. return -c * (t /= d) * (t - 2) + b;
  344. },
  345. easeInOutQuad: function (x, t, b, c, d) {
  346. return ((t /= d / 2) < 1) ? c / 2 * t * t + b : -c / 2 * ((--t) * (t - 2) - 1) + b;
  347. },
  348. easeInCubic: function (x, t, b, c, d) {
  349. return c * (t /= d) * t * t + b;
  350. },
  351. easeOutCubic: function (x, t, b, c, d) {
  352. return c * ((t = t / d - 1) * t * t + 1) + b;
  353. },
  354. easeInOutCubic: function (x, t, b, c, d) {
  355. return ((t /= d / 2) < 1) ? c / 2 * t * t * t + b : c / 2 * ((t -= 2) * t * t + 2) + b;
  356. },
  357. easeInQuart: function (x, t, b, c, d) {
  358. return c * (t /= d) * t * t * t + b;
  359. },
  360. easeOutQuart: function (x, t, b, c, d) {
  361. return -c * ((t = t / d - 1) * t * t * t - 1) + b;
  362. },
  363. easeInOutQuart: function (x, t, b, c, d) {
  364. return ((t /= d / 2) < 1) ? c / 2 * t * t * t * t + b : -c / 2 * ((t -= 2) * t * t * t - 2) + b;
  365. },
  366. easeInQuint: function (x, t, b, c, d) {
  367. return c * (t /= d) * t * t * t * t + b;
  368. },
  369. easeOutQuint: function (x, t, b, c, d) {
  370. return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
  371. },
  372. easeInOutQuint: function (x, t, b, c, d) {
  373. return ((t /= d / 2) < 1) ? c / 2 * t * t * t * t * t + b : c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
  374. },
  375. easeInSine: function (x, t, b, c, d) {
  376. return -c * _easingsMath.c(t / d * (_easingsMath.p / 2)) + c + b;
  377. },
  378. easeOutSine: function (x, t, b, c, d) {
  379. return c * _easingsMath.s(t / d * (_easingsMath.p / 2)) + b;
  380. },
  381. easeInOutSine: function (x, t, b, c, d) {
  382. return -c / 2 * (_easingsMath.c(_easingsMath.p * t / d) - 1) + b;
  383. },
  384. easeInExpo: function (x, t, b, c, d) {
  385. return (t == 0) ? b : c * _easingsMath.w(2, 10 * (t / d - 1)) + b;
  386. },
  387. easeOutExpo: function (x, t, b, c, d) {
  388. return (t == d) ? b + c : c * (-_easingsMath.w(2, -10 * t / d) + 1) + b;
  389. },
  390. easeInOutExpo: function (x, t, b, c, d) {
  391. if (t == 0) return b;
  392. if (t == d) return b + c;
  393. if ((t /= d / 2) < 1) return c / 2 * _easingsMath.w(2, 10 * (t - 1)) + b;
  394. return c / 2 * (-_easingsMath.w(2, -10 * --t) + 2) + b;
  395. },
  396. easeInCirc: function (x, t, b, c, d) {
  397. return -c * (_easingsMath.t(1 - (t /= d) * t) - 1) + b;
  398. },
  399. easeOutCirc: function (x, t, b, c, d) {
  400. return c * _easingsMath.t(1 - (t = t / d - 1) * t) + b;
  401. },
  402. easeInOutCirc: function (x, t, b, c, d) {
  403. return ((t /= d / 2) < 1) ? -c / 2 * (_easingsMath.t(1 - t * t) - 1) + b : c / 2 * (_easingsMath.t(1 - (t -= 2) * t) + 1) + b;
  404. },
  405. easeInElastic: function (x, t, b, c, d) {
  406. var s = _easingsMath.o; var p = 0; var a = c;
  407. if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
  408. if (a < _easingsMath.a(c)) { a = c; s = p / 4; }
  409. else s = p / (2 * _easingsMath.p) * _easingsMath.n(c / a);
  410. return -(a * _easingsMath.w(2, 10 * (t -= 1)) * _easingsMath.s((t * d - s) * (2 * _easingsMath.p) / p)) + b;
  411. },
  412. easeOutElastic: function (x, t, b, c, d) {
  413. var s = _easingsMath.o; var p = 0; var a = c;
  414. if (t == 0) return b;
  415. if ((t /= d) == 1) return b + c;
  416. if (!p) p = d * .3;
  417. if (a < _easingsMath.a(c)) { a = c; s = p / 4; }
  418. else s = p / (2 * _easingsMath.p) * _easingsMath.n(c / a);
  419. return a * _easingsMath.w(2, -10 * t) * _easingsMath.s((t * d - s) * (2 * _easingsMath.p) / p) + c + b;
  420. },
  421. easeInOutElastic: function (x, t, b, c, d) {
  422. var s = _easingsMath.o; var p = 0; var a = c;
  423. if (t == 0) return b;
  424. if ((t /= d / 2) == 2) return b + c;
  425. if (!p) p = d * (.3 * 1.5);
  426. if (a < _easingsMath.a(c)) { a = c; s = p / 4; }
  427. else s = p / (2 * _easingsMath.p) * _easingsMath.n(c / a);
  428. if (t < 1) return -.5 * (a * _easingsMath.w(2, 10 * (t -= 1)) * _easingsMath.s((t * d - s) * (2 * _easingsMath.p) / p)) + b;
  429. return a * _easingsMath.w(2, -10 * (t -= 1)) * _easingsMath.s((t * d - s) * (2 * _easingsMath.p) / p) * .5 + c + b;
  430. },
  431. easeInBack: function (x, t, b, c, d, s) {
  432. s = s || _easingsMath.o;
  433. return c * (t /= d) * t * ((s + 1) * t - s) + b;
  434. },
  435. easeOutBack: function (x, t, b, c, d, s) {
  436. s = s || _easingsMath.o;
  437. return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
  438. },
  439. easeInOutBack: function (x, t, b, c, d, s) {
  440. s = s || _easingsMath.o;
  441. return ((t /= d / 2) < 1) ? c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b : c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
  442. },
  443. easeInBounce: function (x, t, b, c, d) {
  444. return c - this.easeOutBounce(x, d - t, 0, c, d) + b;
  445. },
  446. easeOutBounce: function (x, t, b, c, d) {
  447. var o = 7.5625;
  448. if ((t /= d) < (1 / 2.75)) {
  449. return c * (o * t * t) + b;
  450. } else if (t < (2 / 2.75)) {
  451. return c * (o * (t -= (1.5 / 2.75)) * t + .75) + b;
  452. } else if (t < (2.5 / 2.75)) {
  453. return c * (o * (t -= (2.25 / 2.75)) * t + .9375) + b;
  454. } else {
  455. return c * (o * (t -= (2.625 / 2.75)) * t + .984375) + b;
  456. }
  457. },
  458. easeInOutBounce: function (x, t, b, c, d) {
  459. return (t < d / 2) ? this.easeInBounce(x, t * 2, 0, c, d) * .5 + b : this.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b;
  460. }
  461. };
  462. /*
  463. *
  464. * TERMS OF USE - EASING EQUATIONS
  465. *
  466. * Open source under the BSD License.
  467. *
  468. * Copyright © 2001 Robert Penner
  469. * All rights reserved.
  470. *
  471. * Redistribution and use in source and binary forms, with or without modification,
  472. * are permitted provided that the following conditions are met:
  473. *
  474. * Redistributions of source code must retain the above copyright notice, this list of
  475. * conditions and the following disclaimer.
  476. * Redistributions in binary form must reproduce the above copyright notice, this list
  477. * of conditions and the following disclaimer in the documentation and/or other materials
  478. * provided with the distribution.
  479. *
  480. * Neither the name of the author nor the names of contributors may be used to endorse
  481. * or promote products derived from this software without specific prior written permission.
  482. *
  483. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
  484. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  485. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  486. * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  487. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  488. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  489. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  490. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  491. * OF THE POSSIBILITY OF SUCH DAMAGE.
  492. *
  493. */
  494. })();
  495. var FRAMEWORK = (function () {
  496. var _rnothtmlwhite = (/[^\x20\t\r\n\f]+/g);
  497. var _strSpace = ' ';
  498. var _strEmpty = '';
  499. var _strScrollLeft = 'scrollLeft';
  500. var _strScrollTop = 'scrollTop';
  501. var _animations = [];
  502. var _type = COMPATIBILITY.type;
  503. var _cssNumber = {
  504. animationIterationCount: true,
  505. columnCount: true,
  506. fillOpacity: true,
  507. flexGrow: true,
  508. flexShrink: true,
  509. fontWeight: true,
  510. lineHeight: true,
  511. opacity: true,
  512. order: true,
  513. orphans: true,
  514. widows: true,
  515. zIndex: true,
  516. zoom: true
  517. };
  518. function extend() {
  519. var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {},
  520. i = 1,
  521. length = arguments[LEXICON.l],
  522. deep = false;
  523. // Handle a deep copy situation
  524. if (_type(target) == TYPES.b) {
  525. deep = target;
  526. target = arguments[1] || {};
  527. // skip the boolean and the target
  528. i = 2;
  529. }
  530. // Handle case when target is a string or something (possible in deep copy)
  531. if (_type(target) != TYPES.o && !_type(target) == TYPES.f) {
  532. target = {};
  533. }
  534. // extend jQuery itself if only one argument is passed
  535. if (length === i) {
  536. target = FakejQuery;
  537. --i;
  538. }
  539. for (; i < length; i++) {
  540. // Only deal with non-null/undefined values
  541. if ((options = arguments[i]) != null) {
  542. // Extend the base object
  543. for (name in options) {
  544. src = target[name];
  545. copy = options[name];
  546. // Prevent never-ending loop
  547. if (target === copy) {
  548. continue;
  549. }
  550. // Recurse if we're merging plain objects or arrays
  551. if (deep && copy && (isPlainObject(copy) || (copyIsArray = COMPATIBILITY.isA(copy)))) {
  552. if (copyIsArray) {
  553. copyIsArray = false;
  554. clone = src && COMPATIBILITY.isA(src) ? src : [];
  555. } else {
  556. clone = src && isPlainObject(src) ? src : {};
  557. }
  558. // Never move original objects, clone them
  559. target[name] = extend(deep, clone, copy);
  560. // Don't bring in undefined values
  561. } else if (copy !== undefined) {
  562. target[name] = copy;
  563. }
  564. }
  565. }
  566. }
  567. // Return the modified object
  568. return target;
  569. };
  570. function inArray(item, arr, fromIndex) {
  571. for (var i = fromIndex || 0; i < arr[LEXICON.l]; i++)
  572. if (arr[i] === item)
  573. return i;
  574. return -1;
  575. }
  576. function isFunction(obj) {
  577. return _type(obj) == TYPES.f;
  578. };
  579. function isEmptyObject(obj) {
  580. for (var name in obj)
  581. return false;
  582. return true;
  583. };
  584. function isPlainObject(obj) {
  585. if (!obj || _type(obj) != TYPES.o)
  586. return false;
  587. var key;
  588. var proto = LEXICON.p;
  589. var hasOwnProperty = Object[proto].hasOwnProperty;
  590. var hasOwnConstructor = hasOwnProperty.call(obj, 'constructor');
  591. var hasIsPrototypeOf = obj.constructor && obj.constructor[proto] && hasOwnProperty.call(obj.constructor[proto], 'isPrototypeOf');
  592. if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
  593. return false;
  594. }
  595. for (key in obj) { /**/ }
  596. return _type(key) == TYPES.u || hasOwnProperty.call(obj, key);
  597. };
  598. function each(obj, callback) {
  599. var i = 0;
  600. if (isArrayLike(obj)) {
  601. for (; i < obj[LEXICON.l]; i++) {
  602. if (callback.call(obj[i], i, obj[i]) === false)
  603. break;
  604. }
  605. }
  606. else {
  607. for (i in obj) {
  608. if (callback.call(obj[i], i, obj[i]) === false)
  609. break;
  610. }
  611. }
  612. return obj;
  613. };
  614. function isArrayLike(obj) {
  615. var length = !!obj && [LEXICON.l] in obj && obj[LEXICON.l];
  616. var t = _type(obj);
  617. return isFunction(t) ? false : (t == TYPES.a || length === 0 || _type(length) == TYPES.n && length > 0 && (length - 1) in obj);
  618. }
  619. function stripAndCollapse(value) {
  620. var tokens = value.match(_rnothtmlwhite) || [];
  621. return tokens.join(_strSpace);
  622. }
  623. function matches(elem, selector) {
  624. var nodeList = (elem.parentNode || document).querySelectorAll(selector) || [];
  625. var i = nodeList[LEXICON.l];
  626. while (i--)
  627. if (nodeList[i] == elem)
  628. return true;
  629. return false;
  630. }
  631. function insertAdjacentElement(el, strategy, child) {
  632. if (COMPATIBILITY.isA(child)) {
  633. for (var i = 0; i < child[LEXICON.l]; i++)
  634. insertAdjacentElement(el, strategy, child[i]);
  635. }
  636. else if (_type(child) == TYPES.s)
  637. el.insertAdjacentHTML(strategy, child);
  638. else
  639. el.insertAdjacentElement(strategy, child.nodeType ? child : child[0]);
  640. }
  641. function setCSSVal(el, prop, val) {
  642. try {
  643. if (el[LEXICON.s][prop] !== undefined)
  644. el[LEXICON.s][prop] = parseCSSVal(prop, val);
  645. } catch (e) { }
  646. }
  647. function parseCSSVal(prop, val) {
  648. if (!_cssNumber[prop.toLowerCase()] && _type(val) == TYPES.n)
  649. val += 'px';
  650. return val;
  651. }
  652. function startNextAnimationInQ(animObj, removeFromQ) {
  653. var index;
  654. var nextAnim;
  655. if (removeFromQ !== false)
  656. animObj.q.splice(0, 1);
  657. if (animObj.q[LEXICON.l] > 0) {
  658. nextAnim = animObj.q[0];
  659. animate(animObj.el, nextAnim.props, nextAnim.duration, nextAnim.easing, nextAnim.complete, true);
  660. }
  661. else {
  662. index = inArray(animObj, _animations);
  663. if (index > -1)
  664. _animations.splice(index, 1);
  665. }
  666. }
  667. function setAnimationValue(el, prop, value) {
  668. if (prop === _strScrollLeft || prop === _strScrollTop)
  669. el[prop] = value;
  670. else
  671. setCSSVal(el, prop, value);
  672. }
  673. function animate(el, props, options, easing, complete, guaranteedNext) {
  674. var hasOptions = isPlainObject(options);
  675. var from = {};
  676. var to = {};
  677. var i = 0;
  678. var key;
  679. var animObj;
  680. var start;
  681. var progress;
  682. var step;
  683. var specialEasing;
  684. var duration;
  685. if (hasOptions) {
  686. easing = options.easing;
  687. start = options.start;
  688. progress = options.progress;
  689. step = options.step;
  690. specialEasing = options.specialEasing;
  691. complete = options.complete;
  692. duration = options.duration;
  693. }
  694. else
  695. duration = options;
  696. specialEasing = specialEasing || {};
  697. duration = duration || 400;
  698. easing = easing || 'swing';
  699. guaranteedNext = guaranteedNext || false;
  700. for (; i < _animations[LEXICON.l]; i++) {
  701. if (_animations[i].el === el) {
  702. animObj = _animations[i];
  703. break;
  704. }
  705. }
  706. if (!animObj) {
  707. animObj = {
  708. el: el,
  709. q: []
  710. };
  711. _animations.push(animObj);
  712. }
  713. for (key in props) {
  714. if (key === _strScrollLeft || key === _strScrollTop)
  715. from[key] = el[key];
  716. else
  717. from[key] = FakejQuery(el).css(key);
  718. }
  719. for (key in from) {
  720. if (from[key] !== props[key] && props[key] !== undefined)
  721. to[key] = props[key];
  722. }
  723. if (!isEmptyObject(to)) {
  724. var timeNow;
  725. var end;
  726. var percent;
  727. var fromVal;
  728. var toVal;
  729. var easedVal;
  730. var timeStart;
  731. var frame;
  732. var elapsed;
  733. var qPos = guaranteedNext ? 0 : inArray(qObj, animObj.q);
  734. var qObj = {
  735. props: to,
  736. duration: hasOptions ? options : duration,
  737. easing: easing,
  738. complete: complete
  739. };
  740. if (qPos === -1) {
  741. qPos = animObj.q[LEXICON.l];
  742. animObj.q.push(qObj);
  743. }
  744. if (qPos === 0) {
  745. if (duration > 0) {
  746. timeStart = COMPATIBILITY.now();
  747. frame = function () {
  748. timeNow = COMPATIBILITY.now();
  749. elapsed = (timeNow - timeStart);
  750. end = qObj.stop || elapsed >= duration;
  751. percent = 1 - ((MATH.max(0, timeStart + duration - timeNow) / duration) || 0);
  752. for (key in to) {
  753. fromVal = parseFloat(from[key]);
  754. toVal = parseFloat(to[key]);
  755. easedVal = (toVal - fromVal) * EASING[specialEasing[key] || easing](percent, percent * duration, 0, 1, duration) + fromVal;
  756. setAnimationValue(el, key, easedVal);
  757. if (isFunction(step)) {
  758. step(easedVal, {
  759. elem: el,
  760. prop: key,
  761. start: fromVal,
  762. now: easedVal,
  763. end: toVal,
  764. pos: percent,
  765. options: {
  766. easing: easing,
  767. speacialEasing: specialEasing,
  768. duration: duration,
  769. complete: complete,
  770. step: step
  771. },
  772. startTime: timeStart
  773. });
  774. }
  775. }
  776. if (isFunction(progress))
  777. progress({}, percent, MATH.max(0, duration - elapsed));
  778. if (end) {
  779. startNextAnimationInQ(animObj);
  780. if (isFunction(complete))
  781. complete();
  782. }
  783. else
  784. qObj.frame = COMPATIBILITY.rAF()(frame);
  785. };
  786. qObj.frame = COMPATIBILITY.rAF()(frame);
  787. }
  788. else {
  789. for (key in to)
  790. setAnimationValue(el, key, to[key]);
  791. startNextAnimationInQ(animObj);
  792. }
  793. }
  794. }
  795. else if (guaranteedNext)
  796. startNextAnimationInQ(animObj);
  797. }
  798. function stop(el, clearQ, jumpToEnd) {
  799. var animObj;
  800. var qObj;
  801. var key;
  802. var i = 0;
  803. for (; i < _animations[LEXICON.l]; i++) {
  804. animObj = _animations[i];
  805. if (animObj.el === el) {
  806. if (animObj.q[LEXICON.l] > 0) {
  807. qObj = animObj.q[0];
  808. qObj.stop = true;
  809. COMPATIBILITY.cAF()(qObj.frame);
  810. animObj.q.splice(0, 1);
  811. if (jumpToEnd)
  812. for (key in qObj.props)
  813. setAnimationValue(el, key, qObj.props[key]);
  814. if (clearQ)
  815. animObj.q = [];
  816. else
  817. startNextAnimationInQ(animObj, false);
  818. }
  819. break;
  820. }
  821. }
  822. }
  823. function elementIsVisible(el) {
  824. return !!(el[LEXICON.oW] || el[LEXICON.oH] || el.getClientRects()[LEXICON.l]);
  825. }
  826. function FakejQuery(selector) {
  827. if (arguments[LEXICON.l] === 0)
  828. return this;
  829. var base = new FakejQuery();
  830. var elements = selector;
  831. var i = 0;
  832. var elms;
  833. var el;
  834. if (_type(selector) == TYPES.s) {
  835. elements = [];
  836. if (selector.charAt(0) === '<') {
  837. el = document.createElement('div');
  838. el.innerHTML = selector;
  839. elms = el.children;
  840. }
  841. else {
  842. elms = document.querySelectorAll(selector);
  843. }
  844. for (; i < elms[LEXICON.l]; i++)
  845. elements.push(elms[i]);
  846. }
  847. if (elements) {
  848. if (_type(elements) != TYPES.s && (!isArrayLike(elements) || elements === window || elements === elements.self))
  849. elements = [elements];
  850. for (i = 0; i < elements[LEXICON.l]; i++)
  851. base[i] = elements[i];
  852. base[LEXICON.l] = elements[LEXICON.l];
  853. }
  854. return base;
  855. };
  856. FakejQuery[LEXICON.p] = {
  857. //EVENTS:
  858. on: function (eventName, handler) {
  859. eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty];
  860. var eventNameLength = eventName[LEXICON.l];
  861. var i = 0;
  862. var el;
  863. return this.each(function () {
  864. el = this;
  865. try {
  866. if (el.addEventListener) {
  867. for (; i < eventNameLength; i++)
  868. el.addEventListener(eventName[i], handler);
  869. }
  870. else if (el.detachEvent) {
  871. for (; i < eventNameLength; i++)
  872. el.attachEvent('on' + eventName[i], handler);
  873. }
  874. } catch (e) { }
  875. });
  876. },
  877. off: function (eventName, handler) {
  878. eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty];
  879. var eventNameLength = eventName[LEXICON.l];
  880. var i = 0;
  881. var el;
  882. return this.each(function () {
  883. el = this;
  884. try {
  885. if (el.removeEventListener) {
  886. for (; i < eventNameLength; i++)
  887. el.removeEventListener(eventName[i], handler);
  888. }
  889. else if (el.detachEvent) {
  890. for (; i < eventNameLength; i++)
  891. el.detachEvent('on' + eventName[i], handler);
  892. }
  893. } catch (e) { }
  894. });
  895. },
  896. one: function (eventName, handler) {
  897. eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty];
  898. return this.each(function () {
  899. var el = FakejQuery(this);
  900. FakejQuery.each(eventName, function (i, oneEventName) {
  901. var oneHandler = function (e) {
  902. handler.call(this, e);
  903. el.off(oneEventName, oneHandler);
  904. };
  905. el.on(oneEventName, oneHandler);
  906. });
  907. });
  908. },
  909. trigger: function (eventName) {
  910. var el;
  911. var event;
  912. return this.each(function () {
  913. el = this;
  914. if (document.createEvent) {
  915. event = document.createEvent('HTMLEvents');
  916. event.initEvent(eventName, true, false);
  917. el.dispatchEvent(event);
  918. }
  919. else {
  920. el.fireEvent('on' + eventName);
  921. }
  922. });
  923. },
  924. //DOM NODE INSERTING / REMOVING:
  925. append: function (child) {
  926. return this.each(function () { insertAdjacentElement(this, 'beforeend', child); });
  927. },
  928. prepend: function (child) {
  929. return this.each(function () { insertAdjacentElement(this, 'afterbegin', child); });
  930. },
  931. before: function (child) {
  932. return this.each(function () { insertAdjacentElement(this, 'beforebegin', child); });
  933. },
  934. after: function (child) {
  935. return this.each(function () { insertAdjacentElement(this, 'afterend', child); });
  936. },
  937. remove: function () {
  938. return this.each(function () {
  939. var el = this;
  940. var parentNode = el.parentNode;
  941. if (parentNode != null)
  942. parentNode.removeChild(el);
  943. });
  944. },
  945. unwrap: function () {
  946. var parents = [];
  947. var i;
  948. var el;
  949. var parent;
  950. this.each(function () {
  951. parent = this.parentNode;
  952. if (inArray(parent, parents) === - 1)
  953. parents.push(parent);
  954. });
  955. for (i = 0; i < parents[LEXICON.l]; i++) {
  956. el = parents[i];
  957. parent = el.parentNode;
  958. while (el.firstChild)
  959. parent.insertBefore(el.firstChild, el);
  960. parent.removeChild(el);
  961. }
  962. return this;
  963. },
  964. wrapAll: function (wrapperHTML) {
  965. var i;
  966. var nodes = this;
  967. var wrapper = FakejQuery(wrapperHTML)[0];
  968. var deepest = wrapper;
  969. var parent = nodes[0].parentNode;
  970. var previousSibling = nodes[0].previousSibling;
  971. while (deepest.childNodes[LEXICON.l] > 0)
  972. deepest = deepest.childNodes[0];
  973. for (i = 0; nodes[LEXICON.l] - i; deepest.firstChild === nodes[0] && i++)
  974. deepest.appendChild(nodes[i]);
  975. var nextSibling = previousSibling ? previousSibling.nextSibling : parent.firstChild;
  976. parent.insertBefore(wrapper, nextSibling);
  977. return this;
  978. },
  979. wrapInner: function (wrapperHTML) {
  980. return this.each(function () {
  981. var el = FakejQuery(this);
  982. var contents = el.contents();
  983. if (contents[LEXICON.l])
  984. contents.wrapAll(wrapperHTML);
  985. else
  986. el.append(wrapperHTML);
  987. });
  988. },
  989. wrap: function (wrapperHTML) {
  990. return this.each(function () { FakejQuery(this).wrapAll(wrapperHTML); });
  991. },
  992. //DOM NODE MANIPULATION / INFORMATION:
  993. css: function (styles, val) {
  994. var el;
  995. var key;
  996. var cptStyle;
  997. var getCptStyle = window.getComputedStyle;
  998. if (_type(styles) == TYPES.s) {
  999. if (val === undefined) {
  1000. el = this[0];
  1001. cptStyle = getCptStyle ? getCptStyle(el, null) : el.currentStyle[styles];
  1002. //https://bugzilla.mozilla.org/show_bug.cgi?id=548397 can be null sometimes if iframe with display: none (firefox only!)
  1003. return getCptStyle ? cptStyle != null ? cptStyle.getPropertyValue(styles) : el[LEXICON.s][styles] : cptStyle;
  1004. }
  1005. else {
  1006. return this.each(function () {
  1007. setCSSVal(this, styles, val);
  1008. });
  1009. }
  1010. }
  1011. else {
  1012. return this.each(function () {
  1013. for (key in styles)
  1014. setCSSVal(this, key, styles[key]);
  1015. });
  1016. }
  1017. },
  1018. hasClass: function (className) {
  1019. var elem, i = 0;
  1020. var classNamePrepared = _strSpace + className + _strSpace;
  1021. var classList;
  1022. while ((elem = this[i++])) {
  1023. classList = elem.classList;
  1024. if (classList && classList.contains(className))
  1025. return true;
  1026. else if (elem.nodeType === 1 && (_strSpace + stripAndCollapse(elem.className + _strEmpty) + _strSpace).indexOf(classNamePrepared) > -1)
  1027. return true;
  1028. }
  1029. return false;
  1030. },
  1031. addClass: function (className) {
  1032. var classes;
  1033. var elem;
  1034. var cur;
  1035. var curValue;
  1036. var clazz;
  1037. var finalValue;
  1038. var supportClassList;
  1039. var elmClassList;
  1040. var i = 0;
  1041. var v = 0;
  1042. if (className) {
  1043. classes = className.match(_rnothtmlwhite) || [];
  1044. while ((elem = this[i++])) {
  1045. elmClassList = elem.classList;
  1046. if (supportClassList === undefined)
  1047. supportClassList = elmClassList !== undefined;
  1048. if (supportClassList) {
  1049. while ((clazz = classes[v++]))
  1050. elmClassList.add(clazz);
  1051. }
  1052. else {
  1053. curValue = elem.className + _strEmpty;
  1054. cur = elem.nodeType === 1 && (_strSpace + stripAndCollapse(curValue) + _strSpace);
  1055. if (cur) {
  1056. while ((clazz = classes[v++]))
  1057. if (cur.indexOf(_strSpace + clazz + _strSpace) < 0)
  1058. cur += clazz + _strSpace;
  1059. finalValue = stripAndCollapse(cur);
  1060. if (curValue !== finalValue)
  1061. elem.className = finalValue;
  1062. }
  1063. }
  1064. }
  1065. }
  1066. return this;
  1067. },
  1068. removeClass: function (className) {
  1069. var classes;
  1070. var elem;
  1071. var cur;
  1072. var curValue;
  1073. var clazz;
  1074. var finalValue;
  1075. var supportClassList;
  1076. var elmClassList;
  1077. var i = 0;
  1078. var v = 0;
  1079. if (className) {
  1080. classes = className.match(_rnothtmlwhite) || [];
  1081. while ((elem = this[i++])) {
  1082. elmClassList = elem.classList;
  1083. if (supportClassList === undefined)
  1084. supportClassList = elmClassList !== undefined;
  1085. if (supportClassList) {
  1086. while ((clazz = classes[v++]))
  1087. elmClassList.remove(clazz);
  1088. }
  1089. else {
  1090. curValue = elem.className + _strEmpty;
  1091. cur = elem.nodeType === 1 && (_strSpace + stripAndCollapse(curValue) + _strSpace);
  1092. if (cur) {
  1093. while ((clazz = classes[v++]))
  1094. while (cur.indexOf(_strSpace + clazz + _strSpace) > -1)
  1095. cur = cur.replace(_strSpace + clazz + _strSpace, _strSpace);
  1096. finalValue = stripAndCollapse(cur);
  1097. if (curValue !== finalValue)
  1098. elem.className = finalValue;
  1099. }
  1100. }
  1101. }
  1102. }
  1103. return this;
  1104. },
  1105. hide: function () {
  1106. return this.each(function () { this[LEXICON.s].display = 'none'; });
  1107. },
  1108. show: function () {
  1109. return this.each(function () { this[LEXICON.s].display = 'block'; });
  1110. },
  1111. attr: function (attrName, value) {
  1112. var i = 0;
  1113. var el;
  1114. while (el = this[i++]) {
  1115. if (value === undefined)
  1116. return el.getAttribute(attrName);
  1117. el.setAttribute(attrName, value);
  1118. }
  1119. return this;
  1120. },
  1121. removeAttr: function (attrName) {
  1122. return this.each(function () { this.removeAttribute(attrName); });
  1123. },
  1124. offset: function () {
  1125. var el = this[0];
  1126. var rect = el[LEXICON.bCR]();
  1127. var scrollLeft = window.pageXOffset || document.documentElement[_strScrollLeft];
  1128. var scrollTop = window.pageYOffset || document.documentElement[_strScrollTop];
  1129. return {
  1130. top: rect.top + scrollTop,
  1131. left: rect.left + scrollLeft
  1132. };
  1133. },
  1134. position: function () {
  1135. var el = this[0];
  1136. return {
  1137. top: el.offsetTop,
  1138. left: el.offsetLeft
  1139. };
  1140. },
  1141. scrollLeft: function (value) {
  1142. var i = 0;
  1143. var el;
  1144. while (el = this[i++]) {
  1145. if (value === undefined)
  1146. return el[_strScrollLeft];
  1147. el[_strScrollLeft] = value;
  1148. }
  1149. return this;
  1150. },
  1151. scrollTop: function (value) {
  1152. var i = 0;
  1153. var el;
  1154. while (el = this[i++]) {
  1155. if (value === undefined)
  1156. return el[_strScrollTop];
  1157. el[_strScrollTop] = value;
  1158. }
  1159. return this;
  1160. },
  1161. val: function (value) {
  1162. var el = this[0];
  1163. if (!value)
  1164. return el.value;
  1165. el.value = value;
  1166. return this;
  1167. },
  1168. //DOM TRAVERSAL / FILTERING:
  1169. first: function () {
  1170. return this.eq(0);
  1171. },
  1172. last: function () {
  1173. return this.eq(-1);
  1174. },
  1175. eq: function (index) {
  1176. return FakejQuery(this[index >= 0 ? index : this[LEXICON.l] + index]);
  1177. },
  1178. find: function (selector) {
  1179. var children = [];
  1180. var i;
  1181. this.each(function () {
  1182. var el = this;
  1183. var ch = el.querySelectorAll(selector);
  1184. for (i = 0; i < ch[LEXICON.l]; i++)
  1185. children.push(ch[i]);
  1186. });
  1187. return FakejQuery(children);
  1188. },
  1189. children: function (selector) {
  1190. var children = [];
  1191. var el;
  1192. var ch;
  1193. var i;
  1194. this.each(function () {
  1195. ch = this.children;
  1196. for (i = 0; i < ch[LEXICON.l]; i++) {
  1197. el = ch[i];
  1198. if (selector) {
  1199. if ((el.matches && el.matches(selector)) || matches(el, selector))
  1200. children.push(el);
  1201. }
  1202. else
  1203. children.push(el);
  1204. }
  1205. });
  1206. return FakejQuery(children);
  1207. },
  1208. parent: function (selector) {
  1209. var parents = [];
  1210. var parent;
  1211. this.each(function () {
  1212. parent = this.parentNode;
  1213. if (selector ? FakejQuery(parent).is(selector) : true)
  1214. parents.push(parent);
  1215. });
  1216. return FakejQuery(parents);
  1217. },
  1218. is: function (selector) {
  1219. var el;
  1220. var i;
  1221. for (i = 0; i < this[LEXICON.l]; i++) {
  1222. el = this[i];
  1223. if (selector === ':visible')
  1224. return elementIsVisible(el);
  1225. if (selector === ':hidden')
  1226. return !elementIsVisible(el);
  1227. if ((el.matches && el.matches(selector)) || matches(el, selector))
  1228. return true;
  1229. }
  1230. return false;
  1231. },
  1232. contents: function () {
  1233. var contents = [];
  1234. var childs;
  1235. var i;
  1236. this.each(function () {
  1237. childs = this.childNodes;
  1238. for (i = 0; i < childs[LEXICON.l]; i++)
  1239. contents.push(childs[i]);
  1240. });
  1241. return FakejQuery(contents);
  1242. },
  1243. each: function (callback) {
  1244. return each(this, callback);
  1245. },
  1246. //ANIMATION:
  1247. animate: function (props, duration, easing, complete) {
  1248. return this.each(function () { animate(this, props, duration, easing, complete); });
  1249. },
  1250. stop: function (clearQ, jump) {
  1251. return this.each(function () { stop(this, clearQ, jump); });
  1252. }
  1253. };
  1254. extend(FakejQuery, {
  1255. extend: extend,
  1256. inArray: inArray,
  1257. isEmptyObject: isEmptyObject,
  1258. isPlainObject: isPlainObject,
  1259. each: each
  1260. });
  1261. return FakejQuery;
  1262. })();
  1263. var INSTANCES = (function () {
  1264. var _targets = [];
  1265. var _instancePropertyString = '__overlayScrollbars__';
  1266. /**
  1267. * Register, unregister or get a certain (or all) instances.
  1268. * Register: Pass the target and the instance.
  1269. * Unregister: Pass the target and null.
  1270. * Get Instance: Pass the target from which the instance shall be got.
  1271. * Get Targets: Pass no arguments.
  1272. * @param target The target to which the instance shall be registered / from which the instance shall be unregistered / the instance shall be got
  1273. * @param instance The instance.
  1274. * @returns {*|void} Returns the instance from the given target.
  1275. */
  1276. return function (target, instance) {
  1277. var argLen = arguments[LEXICON.l];
  1278. if (argLen < 1) {
  1279. //return all targets
  1280. return _targets;
  1281. }
  1282. else {
  1283. if (instance) {
  1284. //register instance
  1285. target[_instancePropertyString] = instance;
  1286. _targets.push(target);
  1287. }
  1288. else {
  1289. var index = COMPATIBILITY.inA(target, _targets);
  1290. if (index > -1) {
  1291. if (argLen > 1) {
  1292. //unregister instance
  1293. delete target[_instancePropertyString];
  1294. _targets.splice(index, 1);
  1295. }
  1296. else {
  1297. //get instance from target
  1298. return _targets[index][_instancePropertyString];
  1299. }
  1300. }
  1301. }
  1302. }
  1303. }
  1304. })();
  1305. var PLUGIN = (function () {
  1306. var _plugin;
  1307. var _pluginsGlobals;
  1308. var _pluginsAutoUpdateLoop;
  1309. var _pluginsExtensions = [];
  1310. var _pluginsOptions = (function () {
  1311. var type = COMPATIBILITY.type;
  1312. var possibleTemplateTypes = [
  1313. TYPES.b, //boolean
  1314. TYPES.n, //number
  1315. TYPES.s, //string
  1316. TYPES.a, //array
  1317. TYPES.o, //object
  1318. TYPES.f, //function
  1319. TYPES.z //null
  1320. ];
  1321. var restrictedStringsSplit = ' ';
  1322. var restrictedStringsPossibilitiesSplit = ':';
  1323. var classNameAllowedValues = [TYPES.z, TYPES.s];
  1324. var numberAllowedValues = TYPES.n;
  1325. var booleanNullAllowedValues = [TYPES.z, TYPES.b];
  1326. var booleanTrueTemplate = [true, TYPES.b];
  1327. var booleanFalseTemplate = [false, TYPES.b];
  1328. var callbackTemplate = [null, [TYPES.z, TYPES.f]];
  1329. var updateOnLoadTemplate = [['img'], [TYPES.s, TYPES.a, TYPES.z]];
  1330. var inheritedAttrsTemplate = [['style', 'class'], [TYPES.s, TYPES.a, TYPES.z]];
  1331. var resizeAllowedValues = 'n:none b:both h:horizontal v:vertical';
  1332. var overflowBehaviorAllowedValues = 'v-h:visible-hidden v-s:visible-scroll s:scroll h:hidden';
  1333. var scrollbarsVisibilityAllowedValues = 'v:visible h:hidden a:auto';
  1334. var scrollbarsAutoHideAllowedValues = 'n:never s:scroll l:leave m:move';
  1335. var optionsDefaultsAndTemplate = {
  1336. className: ['os-theme-dark', classNameAllowedValues], //null || string
  1337. resize: ['none', resizeAllowedValues], //none || both || horizontal || vertical || n || b || h || v
  1338. sizeAutoCapable: booleanTrueTemplate, //true || false
  1339. clipAlways: booleanTrueTemplate, //true || false
  1340. normalizeRTL: booleanTrueTemplate, //true || false
  1341. paddingAbsolute: booleanFalseTemplate, //true || false
  1342. autoUpdate: [null, booleanNullAllowedValues], //true || false || null
  1343. autoUpdateInterval: [33, numberAllowedValues], //number
  1344. updateOnLoad: updateOnLoadTemplate, //string || array || null
  1345. nativeScrollbarsOverlaid: {
  1346. showNativeScrollbars: booleanFalseTemplate, //true || false
  1347. initialize: booleanTrueTemplate //true || false
  1348. },
  1349. overflowBehavior: {
  1350. x: ['scroll', overflowBehaviorAllowedValues], //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s
  1351. y: ['scroll', overflowBehaviorAllowedValues] //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s
  1352. },
  1353. scrollbars: {
  1354. visibility: ['auto', scrollbarsVisibilityAllowedValues], //visible || hidden || auto || v || h || a
  1355. autoHide: ['never', scrollbarsAutoHideAllowedValues], //never || scroll || leave || move || n || s || l || m
  1356. autoHideDelay: [800, numberAllowedValues], //number
  1357. dragScrolling: booleanTrueTemplate, //true || false
  1358. clickScrolling: booleanFalseTemplate, //true || false
  1359. touchSupport: booleanTrueTemplate, //true || false
  1360. snapHandle: booleanFalseTemplate //true || false
  1361. },
  1362. textarea: {
  1363. dynWidth: booleanFalseTemplate, //true || false
  1364. dynHeight: booleanFalseTemplate, //true || false
  1365. inheritedAttrs: inheritedAttrsTemplate //string || array || null
  1366. },
  1367. callbacks: {
  1368. onInitialized: callbackTemplate, //null || function
  1369. onInitializationWithdrawn: callbackTemplate, //null || function
  1370. onDestroyed: callbackTemplate, //null || function
  1371. onScrollStart: callbackTemplate, //null || function
  1372. onScroll: callbackTemplate, //null || function
  1373. onScrollStop: callbackTemplate, //null || function
  1374. onOverflowChanged: callbackTemplate, //null || function
  1375. onOverflowAmountChanged: callbackTemplate, //null || function
  1376. onDirectionChanged: callbackTemplate, //null || function
  1377. onContentSizeChanged: callbackTemplate, //null || function
  1378. onHostSizeChanged: callbackTemplate, //null || function
  1379. onUpdated: callbackTemplate //null || function
  1380. }
  1381. };
  1382. var convert = function (template) {
  1383. var recursive = function (obj) {
  1384. var key;
  1385. var val;
  1386. var valType;
  1387. for (key in obj) {
  1388. if (!obj[LEXICON.hOP](key))
  1389. continue;
  1390. val = obj[key];
  1391. valType = type(val);
  1392. if (valType == TYPES.a)
  1393. obj[key] = val[template ? 1 : 0];
  1394. else if (valType == TYPES.o)
  1395. obj[key] = recursive(val);
  1396. }
  1397. return obj;
  1398. };
  1399. return recursive(FRAMEWORK.extend(true, {}, optionsDefaultsAndTemplate));
  1400. };
  1401. return {
  1402. _defaults: convert(),
  1403. _template: convert(true),
  1404. /**
  1405. * Validates the passed object by the passed template.
  1406. * @param obj The object which shall be validated.
  1407. * @param template The template which defines the allowed values and types.
  1408. * @param writeErrors True if errors shall be logged to the console.
  1409. * @param diffObj If a object is passed then only valid differences to this object will be returned.
  1410. * @returns {{}} A object which contains two objects called "default" and "prepared" which contains only the valid properties of the passed original object and discards not different values compared to the passed diffObj.
  1411. */
  1412. _validate: function (obj, template, writeErrors, diffObj) {
  1413. var validatedOptions = {};
  1414. var validatedOptionsPrepared = {};
  1415. var objectCopy = FRAMEWORK.extend(true, {}, obj);
  1416. var inArray = FRAMEWORK.inArray;
  1417. var isEmptyObj = FRAMEWORK.isEmptyObject;
  1418. var checkObjectProps = function (data, template, diffData, validatedOptions, validatedOptionsPrepared, prevPropName) {
  1419. for (var prop in template) {
  1420. if (template[LEXICON.hOP](prop) && data[LEXICON.hOP](prop)) {
  1421. var isValid = false;
  1422. var isDiff = false;
  1423. var templateValue = template[prop];
  1424. var templateValueType = type(templateValue);
  1425. var templateIsComplex = templateValueType == TYPES.o;
  1426. var templateTypes = !COMPATIBILITY.isA(templateValue) ? [templateValue] : templateValue;
  1427. var dataDiffValue = diffData[prop];
  1428. var dataValue = data[prop];
  1429. var dataValueType = type(dataValue);
  1430. var propPrefix = prevPropName ? prevPropName + '.' : '';
  1431. var error = "The option \"" + propPrefix + prop + "\" wasn't set, because";
  1432. var errorPossibleTypes = [];
  1433. var errorRestrictedStrings = [];
  1434. var restrictedStringValuesSplit;
  1435. var restrictedStringValuesPossibilitiesSplit;
  1436. var isRestrictedValue;
  1437. var mainPossibility;
  1438. var currType;
  1439. var i;
  1440. var v;
  1441. var j;
  1442. dataDiffValue = dataDiffValue === undefined ? {} : dataDiffValue;
  1443. //if the template has a object as value, it means that the options are complex (verschachtelt)
  1444. if (templateIsComplex && dataValueType == TYPES.o) {
  1445. validatedOptions[prop] = {};
  1446. validatedOptionsPrepared[prop] = {};
  1447. checkObjectProps(dataValue, templateValue, dataDiffValue, validatedOptions[prop], validatedOptionsPrepared[prop], propPrefix + prop);
  1448. FRAMEWORK.each([data, validatedOptions, validatedOptionsPrepared], function (index, value) {
  1449. if (isEmptyObj(value[prop])) {
  1450. delete value[prop];
  1451. }
  1452. });
  1453. }
  1454. else if (!templateIsComplex) {
  1455. for (i = 0; i < templateTypes[LEXICON.l]; i++) {
  1456. currType = templateTypes[i];
  1457. templateValueType = type(currType);
  1458. //if currtype is string and starts with restrictedStringPrefix and end with restrictedStringSuffix
  1459. isRestrictedValue = templateValueType == TYPES.s && inArray(currType, possibleTemplateTypes) === -1;
  1460. if (isRestrictedValue) {
  1461. errorPossibleTypes.push(TYPES.s);
  1462. //split it into a array which contains all possible values for example: ["y:yes", "n:no", "m:maybe"]
  1463. restrictedStringValuesSplit = currType.split(restrictedStringsSplit);
  1464. errorRestrictedStrings = errorRestrictedStrings.concat(restrictedStringValuesSplit);
  1465. for (v = 0; v < restrictedStringValuesSplit[LEXICON.l]; v++) {
  1466. //split the possible values into their possibiliteis for example: ["y", "yes"] -> the first is always the mainPossibility
  1467. restrictedStringValuesPossibilitiesSplit = restrictedStringValuesSplit[v].split(restrictedStringsPossibilitiesSplit);
  1468. mainPossibility = restrictedStringValuesPossibilitiesSplit[0];
  1469. for (j = 0; j < restrictedStringValuesPossibilitiesSplit[LEXICON.l]; j++) {
  1470. //if any possibility matches with the dataValue, its valid
  1471. if (dataValue === restrictedStringValuesPossibilitiesSplit[j]) {
  1472. isValid = true;
  1473. break;
  1474. }
  1475. }
  1476. if (isValid)
  1477. break;
  1478. }
  1479. }
  1480. else {
  1481. errorPossibleTypes.push(currType);
  1482. if (dataValueType === currType) {
  1483. isValid = true;
  1484. break;
  1485. }
  1486. }
  1487. }
  1488. if (isValid) {
  1489. isDiff = dataValue !== dataDiffValue;
  1490. if (isDiff)
  1491. validatedOptions[prop] = dataValue;
  1492. if (isRestrictedValue ? inArray(dataDiffValue, restrictedStringValuesPossibilitiesSplit) < 0 : isDiff)
  1493. validatedOptionsPrepared[prop] = isRestrictedValue ? mainPossibility : dataValue;
  1494. }
  1495. else if (writeErrors) {
  1496. console.warn(error + " it doesn't accept the type [ " + dataValueType.toUpperCase() + " ] with the value of \"" + dataValue + "\".\r\n" +
  1497. "Accepted types are: [ " + errorPossibleTypes.join(', ').toUpperCase() + " ]." +
  1498. (errorRestrictedStrings[length] > 0 ? "\r\nValid strings are: [ " + errorRestrictedStrings.join(', ').split(restrictedStringsPossibilitiesSplit).join(', ') + " ]." : ''));
  1499. }
  1500. delete data[prop];
  1501. }
  1502. }
  1503. }
  1504. };
  1505. checkObjectProps(objectCopy, template, diffObj || {}, validatedOptions, validatedOptionsPrepared);
  1506. //add values which aren't specified in the template to the finished validated object to prevent them from being discarded
  1507. /*
  1508. if(keepForeignProps) {
  1509. FRAMEWORK.extend(true, validatedOptions, objectCopy);
  1510. FRAMEWORK.extend(true, validatedOptionsPrepared, objectCopy);
  1511. }
  1512. */
  1513. if (!isEmptyObj(objectCopy) && writeErrors)
  1514. console.warn('The following options are discarded due to invalidity:\r\n' + window.JSON.stringify(objectCopy, null, 2));
  1515. return {
  1516. _default: validatedOptions,
  1517. _prepared: validatedOptionsPrepared
  1518. };
  1519. }
  1520. }
  1521. }());
  1522. /**
  1523. * Initializes the object which contains global information about the plugin and each instance of it.
  1524. */
  1525. function initOverlayScrollbarsStatics() {
  1526. if (!_pluginsGlobals)
  1527. _pluginsGlobals = new OverlayScrollbarsGlobals(_pluginsOptions._defaults);
  1528. if (!_pluginsAutoUpdateLoop)
  1529. _pluginsAutoUpdateLoop = new OverlayScrollbarsAutoUpdateLoop(_pluginsGlobals);
  1530. }
  1531. /**
  1532. * The global object for the OverlayScrollbars objects. It contains resources which every OverlayScrollbars object needs. This object is initialized only once: if the first OverlayScrollbars object gets initialized.
  1533. * @param defaultOptions
  1534. * @constructor
  1535. */
  1536. function OverlayScrollbarsGlobals(defaultOptions) {
  1537. var _base = this;
  1538. var strOverflow = 'overflow';
  1539. var strHidden = 'hidden';
  1540. var strScroll = 'scroll';
  1541. var bodyElement = FRAMEWORK('body');
  1542. var scrollbarDummyElement = FRAMEWORK('<div id="os-dummy-scrollbar-size"><div></div></div>');
  1543. var scrollbarDummyElement0 = scrollbarDummyElement[0];
  1544. var dummyContainerChild = FRAMEWORK(scrollbarDummyElement.children('div').eq(0));
  1545. bodyElement.append(scrollbarDummyElement);
  1546. scrollbarDummyElement.hide().show(); //fix IE8 bug (incorrect measuring)
  1547. var nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement0);
  1548. var nativeScrollbarIsOverlaid = {
  1549. x: nativeScrollbarSize.x === 0,
  1550. y: nativeScrollbarSize.y === 0
  1551. };
  1552. var msie = (function () {
  1553. var ua = window.navigator.userAgent;
  1554. var strIndexOf = 'indexOf';
  1555. var strSubString = 'substring';
  1556. var msie = ua[strIndexOf]('MSIE ');
  1557. var trident = ua[strIndexOf]('Trident/');
  1558. var edge = ua[strIndexOf]('Edge/');
  1559. var rv = ua[strIndexOf]('rv:');
  1560. var result;
  1561. var parseIntFunc = parseInt;
  1562. // IE 10 or older => return version number
  1563. if (msie > 0)
  1564. result = parseIntFunc(ua[strSubString](msie + 5, ua[strIndexOf]('.', msie)), 10);
  1565. // IE 11 => return version number
  1566. else if (trident > 0)
  1567. result = parseIntFunc(ua[strSubString](rv + 3, ua[strIndexOf]('.', rv)), 10);
  1568. // Edge (IE 12+) => return version number
  1569. else if (edge > 0)
  1570. result = parseIntFunc(ua[strSubString](edge + 5, ua[strIndexOf]('.', edge)), 10);
  1571. // other browser
  1572. return result;
  1573. })();
  1574. FRAMEWORK.extend(_base, {
  1575. defaultOptions: defaultOptions,
  1576. msie: msie,
  1577. autoUpdateLoop: false,
  1578. autoUpdateRecommended: !COMPATIBILITY.mO(),
  1579. nativeScrollbarSize: nativeScrollbarSize,
  1580. nativeScrollbarIsOverlaid: nativeScrollbarIsOverlaid,
  1581. nativeScrollbarStyling: (function () {
  1582. var result = false;
  1583. scrollbarDummyElement.addClass('os-viewport-native-scrollbars-invisible');
  1584. try {
  1585. result = (scrollbarDummyElement.css('scrollbar-width') === 'none' && (msie > 9 || !msie)) || window.getComputedStyle(scrollbarDummyElement0, '::-webkit-scrollbar').getPropertyValue('display') === 'none';
  1586. } catch (ex) { }
  1587. //fix opera bug: scrollbar styles will only appear if overflow value is scroll or auto during the activation of the style.
  1588. //and set overflow to scroll
  1589. //scrollbarDummyElement.css(strOverflow, strHidden).hide().css(strOverflow, strScroll).show();
  1590. //return (scrollbarDummyElement0[LEXICON.oH] - scrollbarDummyElement0[LEXICON.cH]) === 0 && (scrollbarDummyElement0[LEXICON.oW] - scrollbarDummyElement0[LEXICON.cW]) === 0;
  1591. return result;
  1592. })(),
  1593. overlayScrollbarDummySize: { x: 30, y: 30 },
  1594. cssCalc: VENDORS._cssPropertyValue('width', 'calc', '(1px)') || null,
  1595. restrictedMeasuring: (function () {
  1596. //https://bugzilla.mozilla.org/show_bug.cgi?id=1439305
  1597. //since 1.11.0 always false -> fixed via CSS (hopefully)
  1598. scrollbarDummyElement.css(strOverflow, strHidden);
  1599. var scrollSize = {
  1600. w: scrollbarDummyElement0[LEXICON.sW],
  1601. h: scrollbarDummyElement0[LEXICON.sH]
  1602. };
  1603. scrollbarDummyElement.css(strOverflow, 'visible');
  1604. var scrollSize2 = {
  1605. w: scrollbarDummyElement0[LEXICON.sW],
  1606. h: scrollbarDummyElement0[LEXICON.sH]
  1607. };
  1608. return (scrollSize.w - scrollSize2.w) !== 0 || (scrollSize.h - scrollSize2.h) !== 0;
  1609. })(),
  1610. rtlScrollBehavior: (function () {
  1611. scrollbarDummyElement.css({ 'overflow-y': strHidden, 'overflow-x': strScroll, 'direction': 'rtl' }).scrollLeft(0);
  1612. var dummyContainerOffset = scrollbarDummyElement.offset();
  1613. var dummyContainerChildOffset = dummyContainerChild.offset();
  1614. //https://github.com/KingSora/OverlayScrollbars/issues/187
  1615. scrollbarDummyElement.scrollLeft(-999);
  1616. var dummyContainerChildOffsetAfterScroll = dummyContainerChild.offset();
  1617. return {
  1618. //origin direction = determines if the zero scroll position is on the left or right side
  1619. //'i' means 'invert' (i === true means that the axis must be inverted to be correct)
  1620. //true = on the left side
  1621. //false = on the right side
  1622. i: dummyContainerOffset.left === dummyContainerChildOffset.left,
  1623. //negative = determines if the maximum scroll is positive or negative
  1624. //'n' means 'negate' (n === true means that the axis must be negated to be correct)
  1625. //true = negative
  1626. //false = positive
  1627. n: dummyContainerChildOffset.left !== dummyContainerChildOffsetAfterScroll.left
  1628. };
  1629. })(),
  1630. supportTransform: !!VENDORS._cssProperty('transform'),
  1631. supportTransition: !!VENDORS._cssProperty('transition'),
  1632. supportPassiveEvents: (function () {
  1633. var supportsPassive = false;
  1634. try {
  1635. window.addEventListener('test', null, Object.defineProperty({}, 'passive', {
  1636. get: function () {
  1637. supportsPassive = true;
  1638. }
  1639. }));
  1640. } catch (e) { }
  1641. return supportsPassive;
  1642. })(),
  1643. supportResizeObserver: !!COMPATIBILITY.rO(),
  1644. supportMutationObserver: !!COMPATIBILITY.mO()
  1645. });
  1646. scrollbarDummyElement.removeAttr(LEXICON.s).remove();
  1647. //Catch zoom event:
  1648. (function () {
  1649. if (nativeScrollbarIsOverlaid.x && nativeScrollbarIsOverlaid.y)
  1650. return;
  1651. var abs = MATH.abs;
  1652. var windowWidth = COMPATIBILITY.wW();
  1653. var windowHeight = COMPATIBILITY.wH();
  1654. var windowDpr = getWindowDPR();
  1655. var onResize = function () {
  1656. if (INSTANCES().length > 0) {
  1657. var newW = COMPATIBILITY.wW();
  1658. var newH = COMPATIBILITY.wH();
  1659. var deltaW = newW - windowWidth;
  1660. var deltaH = newH - windowHeight;
  1661. if (deltaW === 0 && deltaH === 0)
  1662. return;
  1663. var deltaWRatio = MATH.round(newW / (windowWidth / 100.0));
  1664. var deltaHRatio = MATH.round(newH / (windowHeight / 100.0));
  1665. var absDeltaW = abs(deltaW);
  1666. var absDeltaH = abs(deltaH);
  1667. var absDeltaWRatio = abs(deltaWRatio);
  1668. var absDeltaHRatio = abs(deltaHRatio);
  1669. var newDPR = getWindowDPR();
  1670. var deltaIsBigger = absDeltaW > 2 && absDeltaH > 2;
  1671. var difference = !differenceIsBiggerThanOne(absDeltaWRatio, absDeltaHRatio);
  1672. var dprChanged = newDPR !== windowDpr && windowDpr > 0;
  1673. var isZoom = deltaIsBigger && difference && dprChanged;
  1674. var oldScrollbarSize = _base.nativeScrollbarSize;
  1675. var newScrollbarSize;
  1676. if (isZoom) {
  1677. bodyElement.append(scrollbarDummyElement);
  1678. newScrollbarSize = _base.nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement[0]);
  1679. scrollbarDummyElement.remove();
  1680. if (oldScrollbarSize.x !== newScrollbarSize.x || oldScrollbarSize.y !== newScrollbarSize.y) {
  1681. FRAMEWORK.each(INSTANCES(), function () {
  1682. if (INSTANCES(this))
  1683. INSTANCES(this).update('zoom');
  1684. });
  1685. }
  1686. }
  1687. windowWidth = newW;
  1688. windowHeight = newH;
  1689. windowDpr = newDPR;
  1690. }
  1691. };
  1692. function differenceIsBiggerThanOne(valOne, valTwo) {
  1693. var absValOne = abs(valOne);
  1694. var absValTwo = abs(valTwo);
  1695. return !(absValOne === absValTwo || absValOne + 1 === absValTwo || absValOne - 1 === absValTwo);
  1696. }
  1697. function getWindowDPR() {
  1698. var dDPI = window.screen.deviceXDPI || 0;
  1699. var sDPI = window.screen.logicalXDPI || 1;
  1700. return window.devicePixelRatio || (dDPI / sDPI);
  1701. }
  1702. FRAMEWORK(window).on('resize', onResize);
  1703. })();
  1704. function calcNativeScrollbarSize(measureElement) {
  1705. return {
  1706. x: measureElement[LEXICON.oH] - measureElement[LEXICON.cH],
  1707. y: measureElement[LEXICON.oW] - measureElement[LEXICON.cW]
  1708. };
  1709. }
  1710. }
  1711. /**
  1712. * The object which manages the auto update loop for all OverlayScrollbars objects. This object is initialized only once: if the first OverlayScrollbars object gets initialized.
  1713. * @constructor
  1714. */
  1715. function OverlayScrollbarsAutoUpdateLoop(globals) {
  1716. var _base = this;
  1717. var _inArray = FRAMEWORK.inArray;
  1718. var _getNow = COMPATIBILITY.now;
  1719. var _strAutoUpdate = 'autoUpdate';
  1720. var _strAutoUpdateInterval = _strAutoUpdate + 'Interval';
  1721. var _strLength = LEXICON.l;
  1722. var _loopingInstances = [];
  1723. var _loopingInstancesIntervalCache = [];
  1724. var _loopIsActive = false;
  1725. var _loopIntervalDefault = 33;
  1726. var _loopInterval = _loopIntervalDefault;
  1727. var _loopTimeOld = _getNow();
  1728. var _loopID;
  1729. /**
  1730. * The auto update loop which will run every 50 milliseconds or less if the update interval of a instance is lower than 50 milliseconds.
  1731. */
  1732. var loop = function () {
  1733. if (_loopingInstances[_strLength] > 0 && _loopIsActive) {
  1734. _loopID = COMPATIBILITY.rAF()(function () {
  1735. loop();
  1736. });
  1737. var timeNew = _getNow();
  1738. var timeDelta = timeNew - _loopTimeOld;
  1739. var lowestInterval;
  1740. var instance;
  1741. var instanceOptions;
  1742. var instanceAutoUpdateAllowed;
  1743. var instanceAutoUpdateInterval;
  1744. var now;
  1745. if (timeDelta > _loopInterval) {
  1746. _loopTimeOld = timeNew - (timeDelta % _loopInterval);
  1747. lowestInterval = _loopIntervalDefault;
  1748. for (var i = 0; i < _loopingInstances[_strLength]; i++) {
  1749. instance = _loopingInstances[i];
  1750. if (instance !== undefined) {
  1751. instanceOptions = instance.options();
  1752. instanceAutoUpdateAllowed = instanceOptions[_strAutoUpdate];
  1753. instanceAutoUpdateInterval = MATH.max(1, instanceOptions[_strAutoUpdateInterval]);
  1754. now = _getNow();
  1755. if ((instanceAutoUpdateAllowed === true || instanceAutoUpdateAllowed === null) && (now - _loopingInstancesIntervalCache[i]) > instanceAutoUpdateInterval) {
  1756. instance.update('auto');
  1757. _loopingInstancesIntervalCache[i] = new Date(now += instanceAutoUpdateInterval);
  1758. }
  1759. lowestInterval = MATH.max(1, MATH.min(lowestInterval, instanceAutoUpdateInterval));
  1760. }
  1761. }
  1762. _loopInterval = lowestInterval;
  1763. }
  1764. } else {
  1765. _loopInterval = _loopIntervalDefault;
  1766. }
  1767. };
  1768. /**
  1769. * Add OverlayScrollbars instance to the auto update loop. Only successful if the instance isn't already added.
  1770. * @param instance The instance which shall be updated in a loop automatically.
  1771. */
  1772. _base.add = function (instance) {
  1773. if (_inArray(instance, _loopingInstances) === -1) {
  1774. _loopingInstances.push(instance);
  1775. _loopingInstancesIntervalCache.push(_getNow());
  1776. if (_loopingInstances[_strLength] > 0 && !_loopIsActive) {
  1777. _loopIsActive = true;
  1778. globals.autoUpdateLoop = _loopIsActive;
  1779. loop();
  1780. }
  1781. }
  1782. };
  1783. /**
  1784. * Remove OverlayScrollbars instance from the auto update loop. Only successful if the instance was added before.
  1785. * @param instance The instance which shall be updated in a loop automatically.
  1786. */
  1787. _base.remove = function (instance) {
  1788. var index = _inArray(instance, _loopingInstances);
  1789. if (index > -1) {
  1790. //remove from loopingInstances list
  1791. _loopingInstancesIntervalCache.splice(index, 1);
  1792. _loopingInstances.splice(index, 1);
  1793. //correct update loop behavior
  1794. if (_loopingInstances[_strLength] === 0 && _loopIsActive) {
  1795. _loopIsActive = false;
  1796. globals.autoUpdateLoop = _loopIsActive;
  1797. if (_loopID !== undefined) {
  1798. COMPATIBILITY.cAF()(_loopID);
  1799. _loopID = -1;
  1800. }
  1801. }
  1802. }
  1803. };
  1804. }
  1805. /**
  1806. * A object which manages the scrollbars visibility of the target element.
  1807. * @param pluginTargetElement The element from which the scrollbars shall be hidden.
  1808. * @param options The custom options.
  1809. * @param extensions The custom extensions.
  1810. * @param globals
  1811. * @param autoUpdateLoop
  1812. * @returns {*}
  1813. * @constructor
  1814. */
  1815. function OverlayScrollbarsInstance(pluginTargetElement, options, extensions, globals, autoUpdateLoop) {
  1816. //shortcuts
  1817. var type = COMPATIBILITY.type;
  1818. var inArray = FRAMEWORK.inArray;
  1819. var each = FRAMEWORK.each;
  1820. //make correct instanceof
  1821. var _base = new _plugin();
  1822. var _frameworkProto = FRAMEWORK[LEXICON.p];
  1823. //if passed element is no HTML element: skip and return
  1824. if (!isHTMLElement(pluginTargetElement))
  1825. return;
  1826. //if passed element is already initialized: set passed options if there are any and return its instance
  1827. if (INSTANCES(pluginTargetElement)) {
  1828. var inst = INSTANCES(pluginTargetElement);
  1829. inst.options(options);
  1830. return inst;
  1831. }
  1832. //globals:
  1833. var _nativeScrollbarIsOverlaid;
  1834. var _overlayScrollbarDummySize;
  1835. var _rtlScrollBehavior;
  1836. var _autoUpdateRecommended;
  1837. var _msieVersion;
  1838. var _nativeScrollbarStyling;
  1839. var _cssCalc;
  1840. var _nativeScrollbarSize;
  1841. var _supportTransition;
  1842. var _supportTransform;
  1843. var _supportPassiveEvents;
  1844. var _supportResizeObserver;
  1845. var _supportMutationObserver;
  1846. var _restrictedMeasuring;
  1847. //general readonly:
  1848. var _initialized;
  1849. var _destroyed;
  1850. var _isTextarea;
  1851. var _isBody;
  1852. var _documentMixed;
  1853. var _domExists;
  1854. //general:
  1855. var _isBorderBox;
  1856. var _sizeAutoObserverAdded;
  1857. var _paddingX;
  1858. var _paddingY;
  1859. var _borderX;
  1860. var _borderY;
  1861. var _marginX;
  1862. var _marginY;
  1863. var _isRTL;
  1864. var _sleeping;
  1865. var _contentBorderSize = {};
  1866. var _scrollHorizontalInfo = {};
  1867. var _scrollVerticalInfo = {};
  1868. var _viewportSize = {};
  1869. var _nativeScrollbarMinSize = {};
  1870. //naming:
  1871. var _strMinusHidden = '-hidden';
  1872. var _strMarginMinus = 'margin-';
  1873. var _strPaddingMinus = 'padding-';
  1874. var _strBorderMinus = 'border-';
  1875. var _strTop = 'top';
  1876. var _strRight = 'right';
  1877. var _strBottom = 'bottom';
  1878. var _strLeft = 'left';
  1879. var _strMinMinus = 'min-';
  1880. var _strMaxMinus = 'max-';
  1881. var _strWidth = 'width';
  1882. var _strHeight = 'height';
  1883. var _strFloat = 'float';
  1884. var _strEmpty = '';
  1885. var _strAuto = 'auto';
  1886. var _strSync = 'sync';
  1887. var _strScroll = 'scroll';
  1888. var _strHundredPercent = '100%';
  1889. var _strX = 'x';
  1890. var _strY = 'y';
  1891. var _strDot = '.';
  1892. var _strSpace = ' ';
  1893. var _strScrollbar = 'scrollbar';
  1894. var _strMinusHorizontal = '-horizontal';
  1895. var _strMinusVertical = '-vertical';
  1896. var _strScrollLeft = _strScroll + 'Left';
  1897. var _strScrollTop = _strScroll + 'Top';
  1898. var _strMouseTouchDownEvent = 'mousedown touchstart';
  1899. var _strMouseTouchUpEvent = 'mouseup touchend touchcancel';
  1900. var _strMouseTouchMoveEvent = 'mousemove touchmove';
  1901. var _strMouseEnter = 'mouseenter';
  1902. var _strMouseLeave = 'mouseleave';
  1903. var _strKeyDownEvent = 'keydown';
  1904. var _strKeyUpEvent = 'keyup';
  1905. var _strSelectStartEvent = 'selectstart';
  1906. var _strTransitionEndEvent = 'transitionend webkitTransitionEnd oTransitionEnd';
  1907. var _strResizeObserverProperty = '__overlayScrollbarsRO__';
  1908. //class names:
  1909. var _cassNamesPrefix = 'os-';
  1910. var _classNameHTMLElement = _cassNamesPrefix + 'html';
  1911. var _classNameHostElement = _cassNamesPrefix + 'host';
  1912. var _classNameHostElementForeign = _classNameHostElement + '-foreign';
  1913. var _classNameHostTextareaElement = _classNameHostElement + '-textarea';
  1914. var _classNameHostScrollbarHorizontalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusHorizontal + _strMinusHidden;
  1915. var _classNameHostScrollbarVerticalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusVertical + _strMinusHidden;
  1916. var _classNameHostTransition = _classNameHostElement + '-transition';
  1917. var _classNameHostRTL = _classNameHostElement + '-rtl';
  1918. var _classNameHostResizeDisabled = _classNameHostElement + '-resize-disabled';
  1919. var _classNameHostScrolling = _classNameHostElement + '-scrolling';
  1920. var _classNameHostOverflow = _classNameHostElement + '-overflow';
  1921. var _classNameHostOverflow = _classNameHostElement + '-overflow';
  1922. var _classNameHostOverflowX = _classNameHostOverflow + '-x';
  1923. var _classNameHostOverflowY = _classNameHostOverflow + '-y';
  1924. var _classNameTextareaElement = _cassNamesPrefix + 'textarea';
  1925. var _classNameTextareaCoverElement = _classNameTextareaElement + '-cover';
  1926. var _classNamePaddingElement = _cassNamesPrefix + 'padding';
  1927. var _classNameViewportElement = _cassNamesPrefix + 'viewport';
  1928. var _classNameViewportNativeScrollbarsInvisible = _classNameViewportElement + '-native-scrollbars-invisible';
  1929. var _classNameViewportNativeScrollbarsOverlaid = _classNameViewportElement + '-native-scrollbars-overlaid';
  1930. var _classNameContentElement = _cassNamesPrefix + 'content';
  1931. var _classNameContentArrangeElement = _cassNamesPrefix + 'content-arrange';
  1932. var _classNameContentGlueElement = _cassNamesPrefix + 'content-glue';
  1933. var _classNameSizeAutoObserverElement = _cassNamesPrefix + 'size-auto-observer';
  1934. var _classNameResizeObserverElement = _cassNamesPrefix + 'resize-observer';
  1935. var _classNameResizeObserverItemElement = _cassNamesPrefix + 'resize-observer-item';
  1936. var _classNameResizeObserverItemFinalElement = _classNameResizeObserverItemElement + '-final';
  1937. var _classNameTextInherit = _cassNamesPrefix + 'text-inherit';
  1938. var _classNameScrollbar = _cassNamesPrefix + _strScrollbar;
  1939. var _classNameScrollbarTrack = _classNameScrollbar + '-track';
  1940. var _classNameScrollbarTrackOff = _classNameScrollbarTrack + '-off';
  1941. var _classNameScrollbarHandle = _classNameScrollbar + '-handle';
  1942. var _classNameScrollbarHandleOff = _classNameScrollbarHandle + '-off';
  1943. var _classNameScrollbarUnusable = _classNameScrollbar + '-unusable';
  1944. var _classNameScrollbarAutoHidden = _classNameScrollbar + '-' + _strAuto + _strMinusHidden;
  1945. var _classNameScrollbarCorner = _classNameScrollbar + '-corner';
  1946. var _classNameScrollbarCornerResize = _classNameScrollbarCorner + '-resize';
  1947. var _classNameScrollbarCornerResizeB = _classNameScrollbarCornerResize + '-both';
  1948. var _classNameScrollbarCornerResizeH = _classNameScrollbarCornerResize + _strMinusHorizontal;
  1949. var _classNameScrollbarCornerResizeV = _classNameScrollbarCornerResize + _strMinusVertical;
  1950. var _classNameScrollbarHorizontal = _classNameScrollbar + _strMinusHorizontal;
  1951. var _classNameScrollbarVertical = _classNameScrollbar + _strMinusVertical;
  1952. var _classNameDragging = _cassNamesPrefix + 'dragging';
  1953. var _classNameThemeNone = _cassNamesPrefix + 'theme-none';
  1954. var _classNamesDynamicDestroy = [
  1955. _classNameViewportNativeScrollbarsInvisible,
  1956. _classNameViewportNativeScrollbarsOverlaid,
  1957. _classNameScrollbarTrackOff,
  1958. _classNameScrollbarHandleOff,
  1959. _classNameScrollbarUnusable,
  1960. _classNameScrollbarAutoHidden,
  1961. _classNameScrollbarCornerResize,
  1962. _classNameScrollbarCornerResizeB,
  1963. _classNameScrollbarCornerResizeH,
  1964. _classNameScrollbarCornerResizeV,
  1965. _classNameDragging].join(_strSpace);
  1966. //callbacks:
  1967. var _callbacksInitQeueue = [];
  1968. //attrs viewport shall inherit from target
  1969. var _viewportAttrsFromTarget = [LEXICON.ti];
  1970. //options:
  1971. var _defaultOptions;
  1972. var _currentOptions;
  1973. var _currentPreparedOptions;
  1974. //extensions:
  1975. var _extensions = {};
  1976. var _extensionsPrivateMethods = 'added removed on contract';
  1977. //update
  1978. var _lastUpdateTime;
  1979. var _swallowedUpdateHints = {};
  1980. var _swallowedUpdateTimeout;
  1981. var _swallowUpdateLag = 42;
  1982. var _updateOnLoadEventName = 'load';
  1983. var _updateOnLoadElms = [];
  1984. //DOM elements:
  1985. var _windowElement;
  1986. var _documentElement;
  1987. var _htmlElement;
  1988. var _bodyElement;
  1989. var _targetElement; //the target element of this OverlayScrollbars object
  1990. var _hostElement; //the host element of this OverlayScrollbars object -> may be the same as targetElement
  1991. var _sizeAutoObserverElement; //observes size auto changes
  1992. var _sizeObserverElement; //observes size and padding changes
  1993. var _paddingElement; //manages the padding
  1994. var _viewportElement; //is the viewport of our scrollbar model
  1995. var _contentElement; //the element which holds the content
  1996. var _contentArrangeElement; //is needed for correct sizing of the content element (only if native scrollbars are overlays)
  1997. var _contentGlueElement; //has always the size of the content element
  1998. var _textareaCoverElement; //only applied if target is a textarea element. Used for correct size calculation and for prevention of uncontrolled scrolling
  1999. var _scrollbarCornerElement;
  2000. var _scrollbarHorizontalElement;
  2001. var _scrollbarHorizontalTrackElement;
  2002. var _scrollbarHorizontalHandleElement;
  2003. var _scrollbarVerticalElement;
  2004. var _scrollbarVerticalTrackElement;
  2005. var _scrollbarVerticalHandleElement;
  2006. var _windowElementNative;
  2007. var _documentElementNative;
  2008. var _targetElementNative;
  2009. var _hostElementNative;
  2010. var _sizeAutoObserverElementNative;
  2011. var _sizeObserverElementNative;
  2012. var _paddingElementNative;
  2013. var _viewportElementNative;
  2014. var _contentElementNative;
  2015. //Cache:
  2016. var _hostSizeCache;
  2017. var _contentScrollSizeCache;
  2018. var _arrangeContentSizeCache;
  2019. var _hasOverflowCache;
  2020. var _hideOverflowCache;
  2021. var _widthAutoCache;
  2022. var _heightAutoCache;
  2023. var _cssBoxSizingCache;
  2024. var _cssPaddingCache;
  2025. var _cssBorderCache;
  2026. var _cssMarginCache;
  2027. var _cssDirectionCache;
  2028. var _cssDirectionDetectedCache;
  2029. var _paddingAbsoluteCache;
  2030. var _clipAlwaysCache;
  2031. var _contentGlueSizeCache;
  2032. var _overflowBehaviorCache;
  2033. var _overflowAmountCache;
  2034. var _ignoreOverlayScrollbarHidingCache;
  2035. var _autoUpdateCache;
  2036. var _sizeAutoCapableCache;
  2037. var _contentElementScrollSizeChangeDetectedCache;
  2038. var _hostElementSizeChangeDetectedCache;
  2039. var _scrollbarsVisibilityCache;
  2040. var _scrollbarsAutoHideCache;
  2041. var _scrollbarsClickScrollingCache;
  2042. var _scrollbarsDragScrollingCache;
  2043. var _resizeCache;
  2044. var _normalizeRTLCache;
  2045. var _classNameCache;
  2046. var _oldClassName;
  2047. var _textareaAutoWrappingCache;
  2048. var _textareaInfoCache;
  2049. var _textareaSizeCache;
  2050. var _textareaDynHeightCache;
  2051. var _textareaDynWidthCache;
  2052. var _bodyMinSizeCache;
  2053. var _updateAutoCache = {};
  2054. //MutationObserver:
  2055. var _mutationObserverHost;
  2056. var _mutationObserverContent;
  2057. var _mutationObserverHostCallback;
  2058. var _mutationObserverContentCallback;
  2059. var _mutationObserversConnected;
  2060. var _mutationObserverAttrsTextarea = ['wrap', 'cols', 'rows'];
  2061. var _mutationObserverAttrsHost = [LEXICON.i, LEXICON.c, LEXICON.s, 'open'].concat(_viewportAttrsFromTarget);
  2062. //events:
  2063. var _destroyEvents = [];
  2064. //textarea:
  2065. var _textareaHasFocus;
  2066. //scrollbars:
  2067. var _scrollbarsAutoHideTimeoutId;
  2068. var _scrollbarsAutoHideMoveTimeoutId;
  2069. var _scrollbarsAutoHideDelay;
  2070. var _scrollbarsAutoHideNever;
  2071. var _scrollbarsAutoHideScroll;
  2072. var _scrollbarsAutoHideMove;
  2073. var _scrollbarsAutoHideLeave;
  2074. var _scrollbarsHandleHovered;
  2075. var _scrollbarsHandlesDefineScrollPos;
  2076. //resize
  2077. var _resizeNone;
  2078. var _resizeBoth;
  2079. var _resizeHorizontal;
  2080. var _resizeVertical;
  2081. //==== Event Listener ====//
  2082. /**
  2083. * Adds or removes a event listener from the given element.
  2084. * @param element The element to which the event listener shall be applied or removed.
  2085. * @param eventNames The name(s) of the events.
  2086. * @param listener The method which shall be called.
  2087. * @param remove True if the handler shall be removed, false or undefined if the handler shall be added.
  2088. * @param passiveOrOptions The options for the event.
  2089. */
  2090. function setupResponsiveEventListener(element, eventNames, listener, remove, passiveOrOptions) {
  2091. var collected = COMPATIBILITY.isA(eventNames) && COMPATIBILITY.isA(listener);
  2092. var method = remove ? 'removeEventListener' : 'addEventListener';
  2093. var onOff = remove ? 'off' : 'on';
  2094. var events = collected ? false : eventNames.split(_strSpace)
  2095. var i = 0;
  2096. var passiveOrOptionsIsObj = FRAMEWORK.isPlainObject(passiveOrOptions);
  2097. var passive = (_supportPassiveEvents && (passiveOrOptionsIsObj ? (passiveOrOptions._passive) : passiveOrOptions)) || false;
  2098. var capture = passiveOrOptionsIsObj && (passiveOrOptions._capture || false);
  2099. var nativeParam = _supportPassiveEvents ? {
  2100. passive: passive,
  2101. capture: capture,
  2102. } : capture;
  2103. if (collected) {
  2104. for (; i < eventNames[LEXICON.l]; i++)
  2105. setupResponsiveEventListener(element, eventNames[i], listener[i], remove, passiveOrOptions);
  2106. }
  2107. else {
  2108. for (; i < events[LEXICON.l]; i++) {
  2109. if(_supportPassiveEvents) {
  2110. element[0][method](events[i], listener, nativeParam);
  2111. }
  2112. else {
  2113. element[onOff](events[i], listener);
  2114. }
  2115. }
  2116. }
  2117. }
  2118. function addDestroyEventListener(element, eventNames, listener, passive) {
  2119. setupResponsiveEventListener(element, eventNames, listener, false, passive);
  2120. _destroyEvents.push(COMPATIBILITY.bind(setupResponsiveEventListener, 0, element, eventNames, listener, true, passive));
  2121. }
  2122. //==== Resize Observer ====//
  2123. /**
  2124. * Adds or removes a resize observer from the given element.
  2125. * @param targetElement The element to which the resize observer shall be added or removed.
  2126. * @param onElementResizedCallback The callback which is fired every time the resize observer registers a size change or false / undefined if the resizeObserver shall be removed.
  2127. */
  2128. function setupResizeObserver(targetElement, onElementResizedCallback) {
  2129. if (targetElement) {
  2130. var resizeObserver = COMPATIBILITY.rO();
  2131. var strAnimationStartEvent = 'animationstart mozAnimationStart webkitAnimationStart MSAnimationStart';
  2132. var strChildNodes = 'childNodes';
  2133. var constScroll = 3333333;
  2134. var callback = function () {
  2135. targetElement[_strScrollTop](constScroll)[_strScrollLeft](_isRTL ? _rtlScrollBehavior.n ? -constScroll : _rtlScrollBehavior.i ? 0 : constScroll : constScroll);
  2136. onElementResizedCallback();
  2137. };
  2138. //add resize observer:
  2139. if (onElementResizedCallback) {
  2140. if (_supportResizeObserver) {
  2141. var element = targetElement.addClass('observed').append(generateDiv(_classNameResizeObserverElement)).contents()[0];
  2142. var observer = element[_strResizeObserverProperty] = new resizeObserver(callback);
  2143. observer.observe(element);
  2144. }
  2145. else {
  2146. if (_msieVersion > 9 || !_autoUpdateRecommended) {
  2147. targetElement.prepend(
  2148. generateDiv(_classNameResizeObserverElement,
  2149. generateDiv({ c: _classNameResizeObserverItemElement, dir: 'ltr' },
  2150. generateDiv(_classNameResizeObserverItemElement,
  2151. generateDiv(_classNameResizeObserverItemFinalElement)
  2152. ) +
  2153. generateDiv(_classNameResizeObserverItemElement,
  2154. generateDiv({ c: _classNameResizeObserverItemFinalElement, style: 'width: 200%; height: 200%' })
  2155. )
  2156. )
  2157. )
  2158. );
  2159. var observerElement = targetElement[0][strChildNodes][0][strChildNodes][0];
  2160. var shrinkElement = FRAMEWORK(observerElement[strChildNodes][1]);
  2161. var expandElement = FRAMEWORK(observerElement[strChildNodes][0]);
  2162. var expandElementChild = FRAMEWORK(expandElement[0][strChildNodes][0]);
  2163. var widthCache = observerElement[LEXICON.oW];
  2164. var heightCache = observerElement[LEXICON.oH];
  2165. var isDirty;
  2166. var rAFId;
  2167. var currWidth;
  2168. var currHeight;
  2169. var factor = 2;
  2170. var nativeScrollbarSize = globals.nativeScrollbarSize; //care don't make changes to this object!!!
  2171. var reset = function () {
  2172. /*
  2173. var sizeResetWidth = observerElement[LEXICON.oW] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
  2174. var sizeResetHeight = observerElement[LEXICON.oH] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
  2175. var expandChildCSS = {};
  2176. expandChildCSS[_strWidth] = sizeResetWidth;
  2177. expandChildCSS[_strHeight] = sizeResetHeight;
  2178. expandElementChild.css(expandChildCSS);
  2179. expandElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
  2180. shrinkElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
  2181. */
  2182. expandElement[_strScrollLeft](constScroll)[_strScrollTop](constScroll);
  2183. shrinkElement[_strScrollLeft](constScroll)[_strScrollTop](constScroll);
  2184. };
  2185. var onResized = function () {
  2186. rAFId = 0;
  2187. if (!isDirty)
  2188. return;
  2189. widthCache = currWidth;
  2190. heightCache = currHeight;
  2191. callback();
  2192. };
  2193. var onScroll = function (event) {
  2194. currWidth = observerElement[LEXICON.oW];
  2195. currHeight = observerElement[LEXICON.oH];
  2196. isDirty = currWidth != widthCache || currHeight != heightCache;
  2197. if (event && isDirty && !rAFId) {
  2198. COMPATIBILITY.cAF()(rAFId);
  2199. rAFId = COMPATIBILITY.rAF()(onResized);
  2200. }
  2201. else if (!event)
  2202. onResized();
  2203. reset();
  2204. if (event) {
  2205. COMPATIBILITY.prvD(event);
  2206. COMPATIBILITY.stpP(event);
  2207. }
  2208. return false;
  2209. };
  2210. var expandChildCSS = {};
  2211. var observerElementCSS = {};
  2212. setTopRightBottomLeft(observerElementCSS, _strEmpty, [
  2213. -((nativeScrollbarSize.y + 1) * factor),
  2214. nativeScrollbarSize.x * -factor,
  2215. nativeScrollbarSize.y * -factor,
  2216. -((nativeScrollbarSize.x + 1) * factor)
  2217. ]);
  2218. FRAMEWORK(observerElement).css(observerElementCSS);
  2219. expandElement.on(_strScroll, onScroll);
  2220. shrinkElement.on(_strScroll, onScroll);
  2221. targetElement.on(strAnimationStartEvent, function () {
  2222. onScroll(false);
  2223. });
  2224. //lets assume that the divs will never be that large and a constant value is enough
  2225. expandChildCSS[_strWidth] = constScroll;
  2226. expandChildCSS[_strHeight] = constScroll;
  2227. expandElementChild.css(expandChildCSS);
  2228. reset();
  2229. }
  2230. else {
  2231. var attachEvent = _documentElementNative.attachEvent;
  2232. var isIE = _msieVersion !== undefined;
  2233. if (attachEvent) {
  2234. targetElement.prepend(generateDiv(_classNameResizeObserverElement));
  2235. findFirst(targetElement, _strDot + _classNameResizeObserverElement)[0].attachEvent('onresize', callback);
  2236. }
  2237. else {
  2238. var obj = _documentElementNative.createElement(TYPES.o);
  2239. obj.setAttribute(LEXICON.ti, '-1');
  2240. obj.setAttribute(LEXICON.c, _classNameResizeObserverElement);
  2241. obj.onload = function () {
  2242. var wnd = this.contentDocument.defaultView;
  2243. wnd.addEventListener('resize', callback);
  2244. wnd.document.documentElement.style.display = 'none';
  2245. };
  2246. obj.type = 'text/html';
  2247. if (isIE)
  2248. targetElement.prepend(obj);
  2249. obj.data = 'about:blank';
  2250. if (!isIE)
  2251. targetElement.prepend(obj);
  2252. targetElement.on(strAnimationStartEvent, callback);
  2253. }
  2254. }
  2255. }
  2256. if (targetElement[0] === _sizeObserverElementNative) {
  2257. var directionChanged = function () {
  2258. var dir = _hostElement.css('direction');
  2259. var css = {};
  2260. var scrollLeftValue = 0;
  2261. var result = false;
  2262. if (dir !== _cssDirectionDetectedCache) {
  2263. if (dir === 'ltr') {
  2264. css[_strLeft] = 0;
  2265. css[_strRight] = _strAuto;
  2266. scrollLeftValue = constScroll;
  2267. }
  2268. else {
  2269. css[_strLeft] = _strAuto;
  2270. css[_strRight] = 0;
  2271. scrollLeftValue = _rtlScrollBehavior.n ? -constScroll : _rtlScrollBehavior.i ? 0 : constScroll;
  2272. }
  2273. //execution order is important for IE!!!
  2274. _sizeObserverElement.children().eq(0).css(css);
  2275. _sizeObserverElement[_strScrollLeft](scrollLeftValue)[_strScrollTop](constScroll);
  2276. _cssDirectionDetectedCache = dir;
  2277. result = true;
  2278. }
  2279. return result;
  2280. };
  2281. directionChanged();
  2282. addDestroyEventListener(targetElement, _strScroll, function (event) {
  2283. if (directionChanged())
  2284. update();
  2285. COMPATIBILITY.prvD(event);
  2286. COMPATIBILITY.stpP(event);
  2287. return false;
  2288. });
  2289. }
  2290. }
  2291. //remove resize observer:
  2292. else {
  2293. if (_supportResizeObserver) {
  2294. var element = targetElement.contents()[0];
  2295. var resizeObserverObj = element[_strResizeObserverProperty];
  2296. if (resizeObserverObj) {
  2297. resizeObserverObj.disconnect();
  2298. delete element[_strResizeObserverProperty];
  2299. }
  2300. }
  2301. else {
  2302. remove(targetElement.children(_strDot + _classNameResizeObserverElement).eq(0));
  2303. }
  2304. }
  2305. }
  2306. }
  2307. /**
  2308. * Freezes or unfreezes the given resize observer.
  2309. * @param targetElement The element to which the target resize observer is applied.
  2310. * @param freeze True if the resize observer shall be frozen, false otherwise.
  2311. function freezeResizeObserver(targetElement, freeze) {
  2312. if (targetElement !== undefined) {
  2313. if(freeze) {
  2314. if (_supportResizeObserver) {
  2315. var element = targetElement.contents()[0];
  2316. element[_strResizeObserverProperty].unobserve(element);
  2317. }
  2318. else {
  2319. targetElement = targetElement.children(_strDot + _classNameResizeObserverElement).eq(0);
  2320. var w = targetElement.css(_strWidth);
  2321. var h = targetElement.css(_strHeight);
  2322. var css = {};
  2323. css[_strWidth] = w;
  2324. css[_strHeight] = h;
  2325. targetElement.css(css);
  2326. }
  2327. }
  2328. else {
  2329. if (_supportResizeObserver) {
  2330. var element = targetElement.contents()[0];
  2331. element[_strResizeObserverProperty].observe(element);
  2332. }
  2333. else {
  2334. var css = { };
  2335. css[_strHeight] = _strEmpty;
  2336. css[_strWidth] = _strEmpty;
  2337. targetElement.children(_strDot + _classNameResizeObserverElement).eq(0).css(css);
  2338. }
  2339. }
  2340. }
  2341. }
  2342. */
  2343. //==== Mutation Observers ====//
  2344. /**
  2345. * Creates MutationObservers for the host and content Element if they are supported.
  2346. */
  2347. function createMutationObservers() {
  2348. if (_supportMutationObserver) {
  2349. var mutationObserverContentLag = 11;
  2350. var mutationObserver = COMPATIBILITY.mO();
  2351. var contentLastUpdate = COMPATIBILITY.now();
  2352. var mutationTarget;
  2353. var mutationAttrName;
  2354. var mutationIsClass;
  2355. var oldMutationVal;
  2356. var newClassVal;
  2357. var hostClassNameRegex;
  2358. var contentTimeout;
  2359. var now;
  2360. var sizeAuto;
  2361. var action;
  2362. _mutationObserverHostCallback = function (mutations) {
  2363. var doUpdate = false;
  2364. var doUpdateForce = false;
  2365. var mutation;
  2366. var mutatedAttrs = [];
  2367. if (_initialized && !_sleeping) {
  2368. each(mutations, function () {
  2369. mutation = this;
  2370. mutationTarget = mutation.target;
  2371. mutationAttrName = mutation.attributeName;
  2372. mutationIsClass = mutationAttrName === LEXICON.c;
  2373. oldMutationVal = mutation.oldValue;
  2374. newClassVal = mutationTarget.className;
  2375. if (_domExists && mutationIsClass && !doUpdateForce) {
  2376. // if old class value contains _classNameHostElementForeign and new class value doesn't
  2377. if (oldMutationVal.indexOf(_classNameHostElementForeign) > -1 && newClassVal.indexOf(_classNameHostElementForeign) < 0) {
  2378. hostClassNameRegex = createHostClassNameRegExp(true);
  2379. _hostElementNative.className = newClassVal.split(_strSpace).concat(oldMutationVal.split(_strSpace).filter(function (name) {
  2380. return name.match(hostClassNameRegex);
  2381. })).join(_strSpace);
  2382. doUpdate = doUpdateForce = true;
  2383. }
  2384. }
  2385. if (!doUpdate) {
  2386. doUpdate = mutationIsClass
  2387. ? hostClassNamesChanged(oldMutationVal, newClassVal)
  2388. : mutationAttrName === LEXICON.s
  2389. ? oldMutationVal !== mutationTarget[LEXICON.s].cssText
  2390. : true;
  2391. }
  2392. mutatedAttrs.push(mutationAttrName);
  2393. });
  2394. updateViewportAttrsFromTarget(mutatedAttrs);
  2395. if (doUpdate)
  2396. _base.update(doUpdateForce || _strAuto);
  2397. }
  2398. return doUpdate;
  2399. };
  2400. _mutationObserverContentCallback = function (mutations) {
  2401. var doUpdate = false;
  2402. var mutation;
  2403. if (_initialized && !_sleeping) {
  2404. each(mutations, function () {
  2405. mutation = this;
  2406. doUpdate = isUnknownMutation(mutation);
  2407. return !doUpdate;
  2408. });
  2409. if (doUpdate) {
  2410. now = COMPATIBILITY.now();
  2411. sizeAuto = (_heightAutoCache || _widthAutoCache);
  2412. action = function () {
  2413. if (!_destroyed) {
  2414. contentLastUpdate = now;
  2415. //if cols, rows or wrap attr was changed
  2416. if (_isTextarea)
  2417. textareaUpdate();
  2418. if (sizeAuto)
  2419. update();
  2420. else
  2421. _base.update(_strAuto);
  2422. }
  2423. };
  2424. clearTimeout(contentTimeout);
  2425. if (mutationObserverContentLag <= 0 || now - contentLastUpdate > mutationObserverContentLag || !sizeAuto)
  2426. action();
  2427. else
  2428. contentTimeout = setTimeout(action, mutationObserverContentLag);
  2429. }
  2430. }
  2431. return doUpdate;
  2432. }
  2433. _mutationObserverHost = new mutationObserver(_mutationObserverHostCallback);
  2434. _mutationObserverContent = new mutationObserver(_mutationObserverContentCallback);
  2435. }
  2436. }
  2437. /**
  2438. * Connects the MutationObservers if they are supported.
  2439. */
  2440. function connectMutationObservers() {
  2441. if (_supportMutationObserver && !_mutationObserversConnected) {
  2442. _mutationObserverHost.observe(_hostElementNative, {
  2443. attributes: true,
  2444. attributeOldValue: true,
  2445. attributeFilter: _mutationObserverAttrsHost
  2446. });
  2447. _mutationObserverContent.observe(_isTextarea ? _targetElementNative : _contentElementNative, {
  2448. attributes: true,
  2449. attributeOldValue: true,
  2450. subtree: !_isTextarea,
  2451. childList: !_isTextarea,
  2452. characterData: !_isTextarea,
  2453. attributeFilter: _isTextarea ? _mutationObserverAttrsTextarea : _mutationObserverAttrsHost
  2454. });
  2455. _mutationObserversConnected = true;
  2456. }
  2457. }
  2458. /**
  2459. * Disconnects the MutationObservers if they are supported.
  2460. */
  2461. function disconnectMutationObservers() {
  2462. if (_supportMutationObserver && _mutationObserversConnected) {
  2463. _mutationObserverHost.disconnect();
  2464. _mutationObserverContent.disconnect();
  2465. _mutationObserversConnected = false;
  2466. }
  2467. }
  2468. //==== Events of elements ====//
  2469. /**
  2470. * This method gets called every time the host element gets resized. IMPORTANT: Padding changes are detected too!!
  2471. * It refreshes the hostResizedEventArgs and the hostSizeResizeCache.
  2472. * If there are any size changes, the update method gets called.
  2473. */
  2474. function hostOnResized() {
  2475. if (!_sleeping) {
  2476. var changed;
  2477. var hostSize = {
  2478. w: _sizeObserverElementNative[LEXICON.sW],
  2479. h: _sizeObserverElementNative[LEXICON.sH]
  2480. };
  2481. changed = checkCache(hostSize, _hostElementSizeChangeDetectedCache);
  2482. _hostElementSizeChangeDetectedCache = hostSize;
  2483. if (changed)
  2484. update({ _hostSizeChanged: true });
  2485. }
  2486. }
  2487. /**
  2488. * The mouse enter event of the host element. This event is only needed for the autoHide feature.
  2489. */
  2490. function hostOnMouseEnter() {
  2491. if (_scrollbarsAutoHideLeave)
  2492. refreshScrollbarsAutoHide(true);
  2493. }
  2494. /**
  2495. * The mouse leave event of the host element. This event is only needed for the autoHide feature.
  2496. */
  2497. function hostOnMouseLeave() {
  2498. if (_scrollbarsAutoHideLeave && !_bodyElement.hasClass(_classNameDragging))
  2499. refreshScrollbarsAutoHide(false);
  2500. }
  2501. /**
  2502. * The mouse move event of the host element. This event is only needed for the autoHide "move" feature.
  2503. */
  2504. function hostOnMouseMove() {
  2505. if (_scrollbarsAutoHideMove) {
  2506. refreshScrollbarsAutoHide(true);
  2507. clearTimeout(_scrollbarsAutoHideMoveTimeoutId);
  2508. _scrollbarsAutoHideMoveTimeoutId = setTimeout(function () {
  2509. if (_scrollbarsAutoHideMove && !_destroyed)
  2510. refreshScrollbarsAutoHide(false);
  2511. }, 100);
  2512. }
  2513. }
  2514. /**
  2515. * Prevents text from deselection if attached to the document element on the mousedown event of a DOM element.
  2516. * @param event The select start event.
  2517. */
  2518. function documentOnSelectStart(event) {
  2519. COMPATIBILITY.prvD(event);
  2520. return false;
  2521. }
  2522. /**
  2523. * A callback which will be called after a element has loaded.
  2524. */
  2525. function updateOnLoadCallback(event) {
  2526. var elm = FRAMEWORK(event.target);
  2527. eachUpdateOnLoad(function (i, updateOnLoadSelector) {
  2528. if (elm.is(updateOnLoadSelector)) {
  2529. update({ _contentSizeChanged: true });
  2530. }
  2531. });
  2532. }
  2533. /**
  2534. * Adds or removes mouse & touch events of the host element. (for handling auto-hiding of the scrollbars)
  2535. * @param destroy Indicates whether the events shall be added or removed.
  2536. */
  2537. function setupHostMouseTouchEvents(destroy) {
  2538. if (!destroy)
  2539. setupHostMouseTouchEvents(true);
  2540. setupResponsiveEventListener(_hostElement,
  2541. _strMouseTouchMoveEvent.split(_strSpace)[0],
  2542. hostOnMouseMove,
  2543. (!_scrollbarsAutoHideMove || destroy), true);
  2544. setupResponsiveEventListener(_hostElement,
  2545. [_strMouseEnter, _strMouseLeave],
  2546. [hostOnMouseEnter, hostOnMouseLeave],
  2547. (!_scrollbarsAutoHideLeave || destroy), true);
  2548. //if the plugin is initialized and the mouse is over the host element, make the scrollbars visible
  2549. if (!_initialized && !destroy)
  2550. _hostElement.one('mouseover', hostOnMouseEnter);
  2551. }
  2552. //==== Update Detection ====//
  2553. /**
  2554. * Measures the min width and min height of the body element and refreshes the related cache.
  2555. * @returns {boolean} True if the min width or min height has changed, false otherwise.
  2556. */
  2557. function bodyMinSizeChanged() {
  2558. var bodyMinSize = {};
  2559. if (_isBody && _contentArrangeElement) {
  2560. bodyMinSize.w = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strWidth));
  2561. bodyMinSize.h = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strHeight));
  2562. bodyMinSize.c = checkCache(bodyMinSize, _bodyMinSizeCache);
  2563. bodyMinSize.f = true; //flag for "measured at least once"
  2564. }
  2565. _bodyMinSizeCache = bodyMinSize;
  2566. return !!bodyMinSize.c;
  2567. }
  2568. /**
  2569. * Returns true if the class names really changed (new class without plugin host prefix)
  2570. * @param oldClassNames The old ClassName string or array.
  2571. * @param newClassNames The new ClassName string or array.
  2572. * @returns {boolean} True if the class names has really changed, false otherwise.
  2573. */
  2574. function hostClassNamesChanged(oldClassNames, newClassNames) {
  2575. var currClasses = typeof newClassNames == TYPES.s ? newClassNames.split(_strSpace) : [];
  2576. var oldClasses = typeof oldClassNames == TYPES.s ? oldClassNames.split(_strSpace) : [];
  2577. var diff = getArrayDifferences(oldClasses, currClasses);
  2578. // remove none theme from diff list to prevent update
  2579. var idx = inArray(_classNameThemeNone, diff);
  2580. var i;
  2581. var regex;
  2582. if (idx > -1)
  2583. diff.splice(idx, 1);
  2584. if (diff[LEXICON.l] > 0) {
  2585. regex = createHostClassNameRegExp(true, true);
  2586. for (i = 0; i < diff.length; i++) {
  2587. if (!diff[i].match(regex)) {
  2588. return true;
  2589. }
  2590. }
  2591. }
  2592. return false;
  2593. }
  2594. /**
  2595. * Returns true if the given mutation is not from a from the plugin generated element. If the target element is a textarea the mutation is always unknown.
  2596. * @param mutation The mutation which shall be checked.
  2597. * @returns {boolean} True if the mutation is from a unknown element, false otherwise.
  2598. */
  2599. function isUnknownMutation(mutation) {
  2600. var attributeName = mutation.attributeName;
  2601. var mutationTarget = mutation.target;
  2602. var mutationType = mutation.type;
  2603. var strClosest = 'closest';
  2604. if (mutationTarget === _contentElementNative)
  2605. return attributeName === null;
  2606. if (mutationType === 'attributes' && (attributeName === LEXICON.c || attributeName === LEXICON.s) && !_isTextarea) {
  2607. //ignore className changes by the plugin
  2608. if (attributeName === LEXICON.c && FRAMEWORK(mutationTarget).hasClass(_classNameHostElement))
  2609. return hostClassNamesChanged(mutation.oldValue, mutationTarget.className);
  2610. //only do it of browser support it natively
  2611. if (typeof mutationTarget[strClosest] != TYPES.f)
  2612. return true;
  2613. if (mutationTarget[strClosest](_strDot + _classNameResizeObserverElement) !== null ||
  2614. mutationTarget[strClosest](_strDot + _classNameScrollbar) !== null ||
  2615. mutationTarget[strClosest](_strDot + _classNameScrollbarCorner) !== null)
  2616. return false;
  2617. }
  2618. return true;
  2619. }
  2620. /**
  2621. * Returns true if the content size was changed since the last time this method was called.
  2622. * @returns {boolean} True if the content size was changed, false otherwise.
  2623. */
  2624. function updateAutoContentSizeChanged() {
  2625. if (_sleeping)
  2626. return false;
  2627. var contentMeasureElement = getContentMeasureElement();
  2628. var textareaValueLength = _isTextarea && _widthAutoCache && !_textareaAutoWrappingCache ? _targetElement.val().length : 0;
  2629. var setCSS = !_mutationObserversConnected && _widthAutoCache && !_isTextarea;
  2630. var css = {};
  2631. var float;
  2632. var bodyMinSizeC;
  2633. var changed;
  2634. var contentElementScrollSize;
  2635. if (setCSS) {
  2636. float = _contentElement.css(_strFloat);
  2637. css[_strFloat] = _isRTL ? _strRight : _strLeft;
  2638. css[_strWidth] = _strAuto;
  2639. _contentElement.css(css);
  2640. }
  2641. contentElementScrollSize = {
  2642. w: contentMeasureElement[LEXICON.sW] + textareaValueLength,
  2643. h: contentMeasureElement[LEXICON.sH] + textareaValueLength
  2644. };
  2645. if (setCSS) {
  2646. css[_strFloat] = float;
  2647. css[_strWidth] = _strHundredPercent;
  2648. _contentElement.css(css);
  2649. }
  2650. bodyMinSizeC = bodyMinSizeChanged();
  2651. changed = checkCache(contentElementScrollSize, _contentElementScrollSizeChangeDetectedCache);
  2652. _contentElementScrollSizeChangeDetectedCache = contentElementScrollSize;
  2653. return changed || bodyMinSizeC;
  2654. }
  2655. /**
  2656. * Returns true when a attribute which the MutationObserver would observe has changed.
  2657. * @returns {boolean} True if one of the attributes which a MutationObserver would observe has changed, false or undefined otherwise.
  2658. */
  2659. function meaningfulAttrsChanged() {
  2660. if (_sleeping || _mutationObserversConnected)
  2661. return;
  2662. var elem;
  2663. var curr;
  2664. var cache;
  2665. var changedAttrs = [];
  2666. var checks = [
  2667. {
  2668. _elem: _hostElement,
  2669. _attrs: _mutationObserverAttrsHost.concat(':visible')
  2670. },
  2671. {
  2672. _elem: _isTextarea ? _targetElement : undefined,
  2673. _attrs: _mutationObserverAttrsTextarea
  2674. }
  2675. ];
  2676. each(checks, function (index, check) {
  2677. elem = check._elem;
  2678. if (elem) {
  2679. each(check._attrs, function (index, attr) {
  2680. curr = attr.charAt(0) === ':' ? elem.is(attr) : elem.attr(attr);
  2681. cache = _updateAutoCache[attr];
  2682. if (checkCache(curr, cache)) {
  2683. changedAttrs.push(attr);
  2684. }
  2685. _updateAutoCache[attr] = curr;
  2686. });
  2687. }
  2688. });
  2689. updateViewportAttrsFromTarget(changedAttrs);
  2690. return changedAttrs[LEXICON.l] > 0;
  2691. }
  2692. /**
  2693. * Checks is a CSS Property of a child element is affecting the scroll size of the content.
  2694. * @param propertyName The CSS property name.
  2695. * @returns {boolean} True if the property is affecting the content scroll size, false otherwise.
  2696. */
  2697. function isSizeAffectingCSSProperty(propertyName) {
  2698. if (!_initialized)
  2699. return true;
  2700. var flexGrow = 'flex-grow';
  2701. var flexShrink = 'flex-shrink';
  2702. var flexBasis = 'flex-basis';
  2703. var affectingPropsX = [
  2704. _strWidth,
  2705. _strMinMinus + _strWidth,
  2706. _strMaxMinus + _strWidth,
  2707. _strMarginMinus + _strLeft,
  2708. _strMarginMinus + _strRight,
  2709. _strLeft,
  2710. _strRight,
  2711. 'font-weight',
  2712. 'word-spacing',
  2713. flexGrow,
  2714. flexShrink,
  2715. flexBasis
  2716. ];
  2717. var affectingPropsXContentBox = [
  2718. _strPaddingMinus + _strLeft,
  2719. _strPaddingMinus + _strRight,
  2720. _strBorderMinus + _strLeft + _strWidth,
  2721. _strBorderMinus + _strRight + _strWidth
  2722. ];
  2723. var affectingPropsY = [
  2724. _strHeight,
  2725. _strMinMinus + _strHeight,
  2726. _strMaxMinus + _strHeight,
  2727. _strMarginMinus + _strTop,
  2728. _strMarginMinus + _strBottom,
  2729. _strTop,
  2730. _strBottom,
  2731. 'line-height',
  2732. flexGrow,
  2733. flexShrink,
  2734. flexBasis
  2735. ];
  2736. var affectingPropsYContentBox = [
  2737. _strPaddingMinus + _strTop,
  2738. _strPaddingMinus + _strBottom,
  2739. _strBorderMinus + _strTop + _strWidth,
  2740. _strBorderMinus + _strBottom + _strWidth
  2741. ];
  2742. var _strS = 's';
  2743. var _strVS = 'v-s';
  2744. var checkX = _overflowBehaviorCache.x === _strS || _overflowBehaviorCache.x === _strVS;
  2745. var checkY = _overflowBehaviorCache.y === _strS || _overflowBehaviorCache.y === _strVS;
  2746. var sizeIsAffected = false;
  2747. var checkPropertyName = function (arr, name) {
  2748. for (var i = 0; i < arr[LEXICON.l]; i++) {
  2749. if (arr[i] === name)
  2750. return true;
  2751. }
  2752. return false;
  2753. };
  2754. if (checkY) {
  2755. sizeIsAffected = checkPropertyName(affectingPropsY, propertyName);
  2756. if (!sizeIsAffected && !_isBorderBox)
  2757. sizeIsAffected = checkPropertyName(affectingPropsYContentBox, propertyName);
  2758. }
  2759. if (checkX && !sizeIsAffected) {
  2760. sizeIsAffected = checkPropertyName(affectingPropsX, propertyName);
  2761. if (!sizeIsAffected && !_isBorderBox)
  2762. sizeIsAffected = checkPropertyName(affectingPropsXContentBox, propertyName);
  2763. }
  2764. return sizeIsAffected;
  2765. }
  2766. //==== Update ====//
  2767. /**
  2768. * Sets the attribute values of the viewport element to the values from the target element.
  2769. * The value of a attribute is only set if the attribute is whitelisted.
  2770. * @attrs attrs The array of attributes which shall be set or undefined if all whitelisted shall be set.
  2771. */
  2772. function updateViewportAttrsFromTarget(attrs) {
  2773. attrs = attrs || _viewportAttrsFromTarget;
  2774. each(attrs, function (index, attr) {
  2775. if (COMPATIBILITY.inA(attr, _viewportAttrsFromTarget) > -1) {
  2776. var targetAttr = _targetElement.attr(attr);
  2777. if (type(targetAttr) == TYPES.s) {
  2778. _viewportElement.attr(attr, targetAttr);
  2779. }
  2780. else {
  2781. _viewportElement.removeAttr(attr);
  2782. }
  2783. }
  2784. });
  2785. }
  2786. /**
  2787. * Updates the variables and size of the textarea element, and manages the scroll on new line or new character.
  2788. */
  2789. function textareaUpdate() {
  2790. if (!_sleeping) {
  2791. var wrapAttrOff = !_textareaAutoWrappingCache;
  2792. var minWidth = _viewportSize.w;
  2793. var minHeight = _viewportSize.h;
  2794. var css = {};
  2795. var doMeasure = _widthAutoCache || wrapAttrOff;
  2796. var origWidth;
  2797. var width;
  2798. var origHeight;
  2799. var height;
  2800. //reset min size
  2801. css[_strMinMinus + _strWidth] = _strEmpty;
  2802. css[_strMinMinus + _strHeight] = _strEmpty;
  2803. //set width auto
  2804. css[_strWidth] = _strAuto;
  2805. _targetElement.css(css);
  2806. //measure width
  2807. origWidth = _targetElementNative[LEXICON.oW];
  2808. width = doMeasure ? MATH.max(origWidth, _targetElementNative[LEXICON.sW] - 1) : 1;
  2809. /*width += (_widthAutoCache ? _marginX + (!_isBorderBox ? wrapAttrOff ? 0 : _paddingX + _borderX : 0) : 0);*/
  2810. //set measured width
  2811. css[_strWidth] = _widthAutoCache ? _strAuto /*width*/ : _strHundredPercent;
  2812. css[_strMinMinus + _strWidth] = _strHundredPercent;
  2813. //set height auto
  2814. css[_strHeight] = _strAuto;
  2815. _targetElement.css(css);
  2816. //measure height
  2817. origHeight = _targetElementNative[LEXICON.oH];
  2818. height = MATH.max(origHeight, _targetElementNative[LEXICON.sH] - 1);
  2819. //append correct size values
  2820. css[_strWidth] = width;
  2821. css[_strHeight] = height;
  2822. _textareaCoverElement.css(css);
  2823. //apply min width / min height to prevent textarea collapsing
  2824. css[_strMinMinus + _strWidth] = minWidth /*+ (!_isBorderBox && _widthAutoCache ? _paddingX + _borderX : 0)*/;
  2825. css[_strMinMinus + _strHeight] = minHeight /*+ (!_isBorderBox && _heightAutoCache ? _paddingY + _borderY : 0)*/;
  2826. _targetElement.css(css);
  2827. return {
  2828. _originalWidth: origWidth,
  2829. _originalHeight: origHeight,
  2830. _dynamicWidth: width,
  2831. _dynamicHeight: height
  2832. };
  2833. }
  2834. }
  2835. /**
  2836. * Updates the plugin and DOM to the current options.
  2837. * This method should only be called if a update is 100% required.
  2838. * @param updateHints A objects which contains hints for this update:
  2839. * {
  2840. * _hostSizeChanged : boolean,
  2841. * _contentSizeChanged : boolean,
  2842. * _force : boolean, == preventSwallowing
  2843. * _changedOptions : { }, == preventSwallowing && preventSleep
  2844. * }
  2845. */
  2846. function update(updateHints) {
  2847. clearTimeout(_swallowedUpdateTimeout);
  2848. updateHints = updateHints || {};
  2849. _swallowedUpdateHints._hostSizeChanged |= updateHints._hostSizeChanged;
  2850. _swallowedUpdateHints._contentSizeChanged |= updateHints._contentSizeChanged;
  2851. _swallowedUpdateHints._force |= updateHints._force;
  2852. var now = COMPATIBILITY.now();
  2853. var hostSizeChanged = !!_swallowedUpdateHints._hostSizeChanged;
  2854. var contentSizeChanged = !!_swallowedUpdateHints._contentSizeChanged;
  2855. var force = !!_swallowedUpdateHints._force;
  2856. var changedOptions = updateHints._changedOptions;
  2857. var swallow = _swallowUpdateLag > 0 && _initialized && !_destroyed && !force && !changedOptions && (now - _lastUpdateTime) < _swallowUpdateLag && (!_heightAutoCache && !_widthAutoCache);
  2858. var displayIsHidden;
  2859. if (swallow)
  2860. _swallowedUpdateTimeout = setTimeout(update, _swallowUpdateLag);
  2861. //abort update due to:
  2862. //destroyed
  2863. //swallowing
  2864. //sleeping
  2865. //host is hidden or has false display
  2866. if (_destroyed || swallow || (_sleeping && !changedOptions) || (_initialized && !force && (displayIsHidden = _hostElement.is(':hidden'))) || _hostElement.css('display') === 'inline')
  2867. return;
  2868. _lastUpdateTime = now;
  2869. _swallowedUpdateHints = {};
  2870. //if scrollbar styling is possible and native scrollbars aren't overlaid the scrollbar styling will be applied which hides the native scrollbars completely.
  2871. if (_nativeScrollbarStyling && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) {
  2872. //native scrollbars are hidden, so change the values to zero
  2873. _nativeScrollbarSize.x = 0;
  2874. _nativeScrollbarSize.y = 0;
  2875. }
  2876. else {
  2877. //refresh native scrollbar size (in case of zoom)
  2878. _nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize);
  2879. }
  2880. // Scrollbar padding is needed for firefox, because firefox hides scrollbar automatically if the size of the div is too small.
  2881. // The calculation: [scrollbar size +3 *3]
  2882. // (+3 because of possible decoration e.g. borders, margins etc., but only if native scrollbar is NOT a overlaid scrollbar)
  2883. // (*3 because (1)increase / (2)decrease -button and (3)resize handle)
  2884. _nativeScrollbarMinSize = {
  2885. x: (_nativeScrollbarSize.x + (_nativeScrollbarIsOverlaid.x ? 0 : 3)) * 3,
  2886. y: (_nativeScrollbarSize.y + (_nativeScrollbarIsOverlaid.y ? 0 : 3)) * 3
  2887. };
  2888. changedOptions = changedOptions || {};
  2889. //freezeResizeObserver(_sizeObserverElement, true);
  2890. //freezeResizeObserver(_sizeAutoObserverElement, true);
  2891. var checkCacheAutoForce = function () {
  2892. return checkCache.apply(this, [].slice.call(arguments).concat([force]));
  2893. };
  2894. //save current scroll offset
  2895. var currScroll = {
  2896. x: _viewportElement[_strScrollLeft](),
  2897. y: _viewportElement[_strScrollTop]()
  2898. };
  2899. var currentPreparedOptionsScrollbars = _currentPreparedOptions.scrollbars;
  2900. var currentPreparedOptionsTextarea = _currentPreparedOptions.textarea;
  2901. //scrollbars visibility:
  2902. var scrollbarsVisibility = currentPreparedOptionsScrollbars.visibility;
  2903. var scrollbarsVisibilityChanged = checkCacheAutoForce(scrollbarsVisibility, _scrollbarsVisibilityCache);
  2904. //scrollbars autoHide:
  2905. var scrollbarsAutoHide = currentPreparedOptionsScrollbars.autoHide;
  2906. var scrollbarsAutoHideChanged = checkCacheAutoForce(scrollbarsAutoHide, _scrollbarsAutoHideCache);
  2907. //scrollbars click scrolling
  2908. var scrollbarsClickScrolling = currentPreparedOptionsScrollbars.clickScrolling;
  2909. var scrollbarsClickScrollingChanged = checkCacheAutoForce(scrollbarsClickScrolling, _scrollbarsClickScrollingCache);
  2910. //scrollbars drag scrolling
  2911. var scrollbarsDragScrolling = currentPreparedOptionsScrollbars.dragScrolling;
  2912. var scrollbarsDragScrollingChanged = checkCacheAutoForce(scrollbarsDragScrolling, _scrollbarsDragScrollingCache);
  2913. //className
  2914. var className = _currentPreparedOptions.className;
  2915. var classNameChanged = checkCacheAutoForce(className, _classNameCache);
  2916. //resize
  2917. var resize = _currentPreparedOptions.resize;
  2918. var resizeChanged = checkCacheAutoForce(resize, _resizeCache) && !_isBody; //body can't be resized since the window itself acts as resize possibility.
  2919. //paddingAbsolute
  2920. var paddingAbsolute = _currentPreparedOptions.paddingAbsolute;
  2921. var paddingAbsoluteChanged = checkCacheAutoForce(paddingAbsolute, _paddingAbsoluteCache);
  2922. //clipAlways
  2923. var clipAlways = _currentPreparedOptions.clipAlways;
  2924. var clipAlwaysChanged = checkCacheAutoForce(clipAlways, _clipAlwaysCache);
  2925. //sizeAutoCapable
  2926. var sizeAutoCapable = _currentPreparedOptions.sizeAutoCapable && !_isBody; //body can never be size auto, because it shall be always as big as the viewport.
  2927. var sizeAutoCapableChanged = checkCacheAutoForce(sizeAutoCapable, _sizeAutoCapableCache);
  2928. //showNativeScrollbars
  2929. var ignoreOverlayScrollbarHiding = _currentPreparedOptions.nativeScrollbarsOverlaid.showNativeScrollbars;
  2930. var ignoreOverlayScrollbarHidingChanged = checkCacheAutoForce(ignoreOverlayScrollbarHiding, _ignoreOverlayScrollbarHidingCache);
  2931. //autoUpdate
  2932. var autoUpdate = _currentPreparedOptions.autoUpdate;
  2933. var autoUpdateChanged = checkCacheAutoForce(autoUpdate, _autoUpdateCache);
  2934. //overflowBehavior
  2935. var overflowBehavior = _currentPreparedOptions.overflowBehavior;
  2936. var overflowBehaviorChanged = checkCacheAutoForce(overflowBehavior, _overflowBehaviorCache, force);
  2937. //dynWidth:
  2938. var textareaDynWidth = currentPreparedOptionsTextarea.dynWidth;
  2939. var textareaDynWidthChanged = checkCacheAutoForce(_textareaDynWidthCache, textareaDynWidth);
  2940. //dynHeight:
  2941. var textareaDynHeight = currentPreparedOptionsTextarea.dynHeight;
  2942. var textareaDynHeightChanged = checkCacheAutoForce(_textareaDynHeightCache, textareaDynHeight);
  2943. //scrollbars visibility
  2944. _scrollbarsAutoHideNever = scrollbarsAutoHide === 'n';
  2945. _scrollbarsAutoHideScroll = scrollbarsAutoHide === 's';
  2946. _scrollbarsAutoHideMove = scrollbarsAutoHide === 'm';
  2947. _scrollbarsAutoHideLeave = scrollbarsAutoHide === 'l';
  2948. //scrollbars autoHideDelay
  2949. _scrollbarsAutoHideDelay = currentPreparedOptionsScrollbars.autoHideDelay;
  2950. //old className
  2951. _oldClassName = _classNameCache;
  2952. //resize
  2953. _resizeNone = resize === 'n';
  2954. _resizeBoth = resize === 'b';
  2955. _resizeHorizontal = resize === 'h';
  2956. _resizeVertical = resize === 'v';
  2957. //normalizeRTL
  2958. _normalizeRTLCache = _currentPreparedOptions.normalizeRTL;
  2959. //ignore overlay scrollbar hiding
  2960. ignoreOverlayScrollbarHiding = ignoreOverlayScrollbarHiding && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y);
  2961. //refresh options cache
  2962. _scrollbarsVisibilityCache = scrollbarsVisibility;
  2963. _scrollbarsAutoHideCache = scrollbarsAutoHide;
  2964. _scrollbarsClickScrollingCache = scrollbarsClickScrolling;
  2965. _scrollbarsDragScrollingCache = scrollbarsDragScrolling;
  2966. _classNameCache = className;
  2967. _resizeCache = resize;
  2968. _paddingAbsoluteCache = paddingAbsolute;
  2969. _clipAlwaysCache = clipAlways;
  2970. _sizeAutoCapableCache = sizeAutoCapable;
  2971. _ignoreOverlayScrollbarHidingCache = ignoreOverlayScrollbarHiding;
  2972. _autoUpdateCache = autoUpdate;
  2973. _overflowBehaviorCache = extendDeep({}, overflowBehavior);
  2974. _textareaDynWidthCache = textareaDynWidth;
  2975. _textareaDynHeightCache = textareaDynHeight;
  2976. _hasOverflowCache = _hasOverflowCache || { x: false, y: false };
  2977. //set correct class name to the host element
  2978. if (classNameChanged) {
  2979. removeClass(_hostElement, _oldClassName + _strSpace + _classNameThemeNone);
  2980. addClass(_hostElement, className !== undefined && className !== null && className.length > 0 ? className : _classNameThemeNone);
  2981. }
  2982. //set correct auto Update
  2983. if (autoUpdateChanged) {
  2984. if (autoUpdate === true || (autoUpdate === null && _autoUpdateRecommended)) {
  2985. disconnectMutationObservers();
  2986. autoUpdateLoop.add(_base);
  2987. }
  2988. else {
  2989. autoUpdateLoop.remove(_base);
  2990. connectMutationObservers();
  2991. }
  2992. }
  2993. //activate or deactivate size auto capability
  2994. if (sizeAutoCapableChanged) {
  2995. if (sizeAutoCapable) {
  2996. if (_contentGlueElement) {
  2997. _contentGlueElement.show();
  2998. }
  2999. else {
  3000. _contentGlueElement = FRAMEWORK(generateDiv(_classNameContentGlueElement));
  3001. _paddingElement.before(_contentGlueElement);
  3002. }
  3003. if (_sizeAutoObserverAdded) {
  3004. _sizeAutoObserverElement.show();
  3005. }
  3006. else {
  3007. _sizeAutoObserverElement = FRAMEWORK(generateDiv(_classNameSizeAutoObserverElement));
  3008. _sizeAutoObserverElementNative = _sizeAutoObserverElement[0];
  3009. _contentGlueElement.before(_sizeAutoObserverElement);
  3010. var oldSize = { w: -1, h: -1 };
  3011. setupResizeObserver(_sizeAutoObserverElement, function () {
  3012. var newSize = {
  3013. w: _sizeAutoObserverElementNative[LEXICON.oW],
  3014. h: _sizeAutoObserverElementNative[LEXICON.oH]
  3015. };
  3016. if (checkCache(newSize, oldSize)) {
  3017. if (_initialized && (_heightAutoCache && newSize.h > 0) || (_widthAutoCache && newSize.w > 0)) {
  3018. update();
  3019. }
  3020. else if (_initialized && (!_heightAutoCache && newSize.h === 0) || (!_widthAutoCache && newSize.w === 0)) {
  3021. update();
  3022. }
  3023. }
  3024. oldSize = newSize;
  3025. });
  3026. _sizeAutoObserverAdded = true;
  3027. //fix heightAuto detector bug if height is fixed but contentHeight is 0.
  3028. //the probability this bug will ever happen is very very low, thats why its ok if we use calc which isn't supported in IE8.
  3029. if (_cssCalc !== null)
  3030. _sizeAutoObserverElement.css(_strHeight, _cssCalc + '(100% + 1px)');
  3031. }
  3032. }
  3033. else {
  3034. if (_sizeAutoObserverAdded)
  3035. _sizeAutoObserverElement.hide();
  3036. if (_contentGlueElement)
  3037. _contentGlueElement.hide();
  3038. }
  3039. }
  3040. //if force, update all resizeObservers too
  3041. if (force) {
  3042. _sizeObserverElement.find('*').trigger(_strScroll);
  3043. if (_sizeAutoObserverAdded)
  3044. _sizeAutoObserverElement.find('*').trigger(_strScroll);
  3045. }
  3046. //display hidden:
  3047. displayIsHidden = displayIsHidden === undefined ? _hostElement.is(':hidden') : displayIsHidden;
  3048. //textarea AutoWrapping:
  3049. var textareaAutoWrapping = _isTextarea ? _targetElement.attr('wrap') !== 'off' : false;
  3050. var textareaAutoWrappingChanged = checkCacheAutoForce(textareaAutoWrapping, _textareaAutoWrappingCache);
  3051. //detect direction:
  3052. var cssDirection = _hostElement.css('direction');
  3053. var cssDirectionChanged = checkCacheAutoForce(cssDirection, _cssDirectionCache);
  3054. //detect box-sizing:
  3055. var boxSizing = _hostElement.css('box-sizing');
  3056. var boxSizingChanged = checkCacheAutoForce(boxSizing, _cssBoxSizingCache);
  3057. //detect padding:
  3058. var padding = getTopRightBottomLeftHost(_strPaddingMinus);
  3059. //width + height auto detecting var:
  3060. var sizeAutoObserverElementBCRect;
  3061. //exception occurs in IE8 sometimes (unknown exception)
  3062. try {
  3063. sizeAutoObserverElementBCRect = _sizeAutoObserverAdded ? _sizeAutoObserverElementNative[LEXICON.bCR]() : null;
  3064. } catch (ex) {
  3065. return;
  3066. }
  3067. _isRTL = cssDirection === 'rtl';
  3068. _isBorderBox = (boxSizing === 'border-box');
  3069. var isRTLLeft = _isRTL ? _strLeft : _strRight;
  3070. var isRTLRight = _isRTL ? _strRight : _strLeft;
  3071. //detect width auto:
  3072. var widthAutoResizeDetection = false;
  3073. var widthAutoObserverDetection = (_sizeAutoObserverAdded && (_hostElement.css(_strFloat) !== 'none' /*|| _isTextarea */)) ? (MATH.round(sizeAutoObserverElementBCRect.right - sizeAutoObserverElementBCRect.left) === 0) && (!paddingAbsolute ? (_hostElementNative[LEXICON.cW] - _paddingX) > 0 : true) : false;
  3074. if (sizeAutoCapable && !widthAutoObserverDetection) {
  3075. var tmpCurrHostWidth = _hostElementNative[LEXICON.oW];
  3076. var tmpCurrContentGlueWidth = _contentGlueElement.css(_strWidth);
  3077. _contentGlueElement.css(_strWidth, _strAuto);
  3078. var tmpNewHostWidth = _hostElementNative[LEXICON.oW];
  3079. _contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth);
  3080. widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth;
  3081. if (!widthAutoResizeDetection) {
  3082. _contentGlueElement.css(_strWidth, tmpCurrHostWidth + 1);
  3083. tmpNewHostWidth = _hostElementNative[LEXICON.oW];
  3084. _contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth);
  3085. widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth;
  3086. }
  3087. }
  3088. var widthAuto = (widthAutoObserverDetection || widthAutoResizeDetection) && sizeAutoCapable && !displayIsHidden;
  3089. var widthAutoChanged = checkCacheAutoForce(widthAuto, _widthAutoCache);
  3090. var wasWidthAuto = !widthAuto && _widthAutoCache;
  3091. //detect height auto:
  3092. var heightAuto = _sizeAutoObserverAdded && sizeAutoCapable && !displayIsHidden ? (MATH.round(sizeAutoObserverElementBCRect.bottom - sizeAutoObserverElementBCRect.top) === 0) /* && (!paddingAbsolute && (_msieVersion > 9 || !_msieVersion) ? true : true) */ : false;
  3093. var heightAutoChanged = checkCacheAutoForce(heightAuto, _heightAutoCache);
  3094. var wasHeightAuto = !heightAuto && _heightAutoCache;
  3095. //detect border:
  3096. //we need the border only if border box and auto size
  3097. var updateBorderX = (widthAuto && _isBorderBox) || !_isBorderBox;
  3098. var updateBorderY = (heightAuto && _isBorderBox) || !_isBorderBox;
  3099. var border = getTopRightBottomLeftHost(_strBorderMinus, '-' + _strWidth, !updateBorderX, !updateBorderY)
  3100. //detect margin:
  3101. var margin = getTopRightBottomLeftHost(_strMarginMinus);
  3102. //vars to apply correct css
  3103. var contentElementCSS = {};
  3104. var contentGlueElementCSS = {};
  3105. //funcs
  3106. var getHostSize = function () {
  3107. //has to be clientSize because offsetSize respect borders
  3108. return {
  3109. w: _hostElementNative[LEXICON.cW],
  3110. h: _hostElementNative[LEXICON.cH]
  3111. };
  3112. };
  3113. var getViewportSize = function () {
  3114. //viewport size is padding container because it never has padding, margin and a border
  3115. //determine zoom rounding error -> sometimes scrollWidth/Height is smaller than clientWidth/Height
  3116. //if this happens add the difference to the viewportSize to compensate the rounding error
  3117. return {
  3118. w: _paddingElementNative[LEXICON.oW] + MATH.max(0, _contentElementNative[LEXICON.cW] - _contentElementNative[LEXICON.sW]),
  3119. h: _paddingElementNative[LEXICON.oH] + MATH.max(0, _contentElementNative[LEXICON.cH] - _contentElementNative[LEXICON.sH])
  3120. };
  3121. };
  3122. //set info for padding
  3123. var paddingAbsoluteX = _paddingX = padding.l + padding.r;
  3124. var paddingAbsoluteY = _paddingY = padding.t + padding.b;
  3125. paddingAbsoluteX *= paddingAbsolute ? 1 : 0;
  3126. paddingAbsoluteY *= paddingAbsolute ? 1 : 0;
  3127. padding.c = checkCacheAutoForce(padding, _cssPaddingCache);
  3128. //set info for border
  3129. _borderX = border.l + border.r;
  3130. _borderY = border.t + border.b;
  3131. border.c = checkCacheAutoForce(border, _cssBorderCache);
  3132. //set info for margin
  3133. _marginX = margin.l + margin.r;
  3134. _marginY = margin.t + margin.b;
  3135. margin.c = checkCacheAutoForce(margin, _cssMarginCache);
  3136. //refresh cache
  3137. _textareaAutoWrappingCache = textareaAutoWrapping;
  3138. _cssDirectionCache = cssDirection;
  3139. _cssBoxSizingCache = boxSizing;
  3140. _widthAutoCache = widthAuto;
  3141. _heightAutoCache = heightAuto;
  3142. _cssPaddingCache = padding;
  3143. _cssBorderCache = border;
  3144. _cssMarginCache = margin;
  3145. //IEFix direction changed
  3146. if (cssDirectionChanged && _sizeAutoObserverAdded)
  3147. _sizeAutoObserverElement.css(_strFloat, isRTLRight);
  3148. //apply padding:
  3149. if (padding.c || cssDirectionChanged || paddingAbsoluteChanged || widthAutoChanged || heightAutoChanged || boxSizingChanged || sizeAutoCapableChanged) {
  3150. var paddingElementCSS = {};
  3151. var textareaCSS = {};
  3152. var paddingValues = [padding.t, padding.r, padding.b, padding.l];
  3153. setTopRightBottomLeft(contentGlueElementCSS, _strMarginMinus, [-padding.t, -padding.r, -padding.b, -padding.l]);
  3154. if (paddingAbsolute) {
  3155. setTopRightBottomLeft(paddingElementCSS, _strEmpty, paddingValues);
  3156. setTopRightBottomLeft(_isTextarea ? textareaCSS : contentElementCSS, _strPaddingMinus);
  3157. }
  3158. else {
  3159. setTopRightBottomLeft(paddingElementCSS, _strEmpty);
  3160. setTopRightBottomLeft(_isTextarea ? textareaCSS : contentElementCSS, _strPaddingMinus, paddingValues);
  3161. }
  3162. _paddingElement.css(paddingElementCSS);
  3163. _targetElement.css(textareaCSS);
  3164. }
  3165. //viewport size is padding container because it never has padding, margin and a border.
  3166. _viewportSize = getViewportSize();
  3167. //update Textarea
  3168. var textareaSize = _isTextarea ? textareaUpdate() : false;
  3169. var textareaSizeChanged = _isTextarea && checkCacheAutoForce(textareaSize, _textareaSizeCache);
  3170. var textareaDynOrigSize = _isTextarea && textareaSize ? {
  3171. w: textareaDynWidth ? textareaSize._dynamicWidth : textareaSize._originalWidth,
  3172. h: textareaDynHeight ? textareaSize._dynamicHeight : textareaSize._originalHeight
  3173. } : {};
  3174. _textareaSizeCache = textareaSize;
  3175. //fix height auto / width auto in cooperation with current padding & boxSizing behavior:
  3176. if (heightAuto && (heightAutoChanged || paddingAbsoluteChanged || boxSizingChanged || padding.c || border.c)) {
  3177. contentElementCSS[_strHeight] = _strAuto;
  3178. }
  3179. else if (heightAutoChanged || paddingAbsoluteChanged) {
  3180. contentElementCSS[_strHeight] = _strHundredPercent;
  3181. }
  3182. if (widthAuto && (widthAutoChanged || paddingAbsoluteChanged || boxSizingChanged || padding.c || border.c || cssDirectionChanged)) {
  3183. contentElementCSS[_strWidth] = _strAuto;
  3184. contentGlueElementCSS[_strMaxMinus + _strWidth] = _strHundredPercent; //IE Fix
  3185. }
  3186. else if (widthAutoChanged || paddingAbsoluteChanged) {
  3187. contentElementCSS[_strWidth] = _strHundredPercent;
  3188. contentElementCSS[_strFloat] = _strEmpty;
  3189. contentGlueElementCSS[_strMaxMinus + _strWidth] = _strEmpty; //IE Fix
  3190. }
  3191. if (widthAuto) {
  3192. //textareaDynOrigSize.w || _strAuto :: doesnt works because applied margin will shift width
  3193. contentGlueElementCSS[_strWidth] = _strAuto;
  3194. contentElementCSS[_strWidth] = VENDORS._cssPropertyValue(_strWidth, 'max-content intrinsic') || _strAuto;
  3195. contentElementCSS[_strFloat] = isRTLRight;
  3196. }
  3197. else {
  3198. contentGlueElementCSS[_strWidth] = _strEmpty;
  3199. }
  3200. if (heightAuto) {
  3201. //textareaDynOrigSize.h || _contentElementNative[LEXICON.cH] :: use for anti scroll jumping
  3202. contentGlueElementCSS[_strHeight] = textareaDynOrigSize.h || _contentElementNative[LEXICON.cH];
  3203. }
  3204. else {
  3205. contentGlueElementCSS[_strHeight] = _strEmpty;
  3206. }
  3207. if (sizeAutoCapable)
  3208. _contentGlueElement.css(contentGlueElementCSS);
  3209. _contentElement.css(contentElementCSS);
  3210. //CHECKPOINT HERE ~
  3211. contentElementCSS = {};
  3212. contentGlueElementCSS = {};
  3213. //if [content(host) client / scroll size, or target element direction, or content(host) max-sizes] changed, or force is true
  3214. if (hostSizeChanged || contentSizeChanged || textareaSizeChanged || cssDirectionChanged || boxSizingChanged || paddingAbsoluteChanged || widthAutoChanged || widthAuto || heightAutoChanged || heightAuto || ignoreOverlayScrollbarHidingChanged || overflowBehaviorChanged || clipAlwaysChanged || resizeChanged || scrollbarsVisibilityChanged || scrollbarsAutoHideChanged || scrollbarsDragScrollingChanged || scrollbarsClickScrollingChanged || textareaDynWidthChanged || textareaDynHeightChanged || textareaAutoWrappingChanged) {
  3215. var strOverflow = 'overflow';
  3216. var strOverflowX = strOverflow + '-x';
  3217. var strOverflowY = strOverflow + '-y';
  3218. var strHidden = 'hidden';
  3219. var strVisible = 'visible';
  3220. //Reset the viewport (very important for natively overlaid scrollbars and zoom change
  3221. //don't change the overflow prop as it is very expensive and affects performance !A LOT!
  3222. if (!_nativeScrollbarStyling) {
  3223. var viewportElementResetCSS = {};
  3224. var resetXTmp = _hasOverflowCache.y && _hideOverflowCache.ys && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.y ? _viewportElement.css(isRTLLeft) : -_nativeScrollbarSize.y) : 0;
  3225. var resetBottomTmp = _hasOverflowCache.x && _hideOverflowCache.xs && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.x ? _viewportElement.css(_strBottom) : -_nativeScrollbarSize.x) : 0;
  3226. setTopRightBottomLeft(viewportElementResetCSS, _strEmpty);
  3227. _viewportElement.css(viewportElementResetCSS);
  3228. }
  3229. //measure several sizes:
  3230. var contentMeasureElement = getContentMeasureElement();
  3231. //in Firefox content element has to have overflow hidden, else element margins aren't calculated properly, this element prevents this bug, but only if scrollbars aren't overlaid
  3232. var contentSize = {
  3233. //use clientSize because natively overlaidScrollbars add borders
  3234. w: textareaDynOrigSize.w || contentMeasureElement[LEXICON.cW],
  3235. h: textareaDynOrigSize.h || contentMeasureElement[LEXICON.cH]
  3236. };
  3237. var scrollSize = {
  3238. w: contentMeasureElement[LEXICON.sW],
  3239. h: contentMeasureElement[LEXICON.sH]
  3240. };
  3241. //apply the correct viewport style and measure viewport size
  3242. if (!_nativeScrollbarStyling) {
  3243. viewportElementResetCSS[_strBottom] = wasHeightAuto ? _strEmpty : resetBottomTmp;
  3244. viewportElementResetCSS[isRTLLeft] = wasWidthAuto ? _strEmpty : resetXTmp;
  3245. _viewportElement.css(viewportElementResetCSS);
  3246. }
  3247. _viewportSize = getViewportSize();
  3248. //measure and correct several sizes
  3249. var hostSize = getHostSize();
  3250. var hostAbsoluteRectSize = {
  3251. w: hostSize.w - _marginX - _borderX - (_isBorderBox ? 0 : _paddingX),
  3252. h: hostSize.h - _marginY - _borderY - (_isBorderBox ? 0 : _paddingY)
  3253. };
  3254. var contentGlueSize = {
  3255. //client/scrollSize + AbsolutePadding -> because padding is only applied to the paddingElement if its absolute, so you have to add it manually
  3256. //hostSize is clientSize -> so padding should be added manually, right? FALSE! Because content glue is inside hostElement, so we don't have to worry about padding
  3257. w: MATH.max((widthAuto ? contentSize.w : scrollSize.w) + paddingAbsoluteX, hostAbsoluteRectSize.w),
  3258. h: MATH.max((heightAuto ? contentSize.h : scrollSize.h) + paddingAbsoluteY, hostAbsoluteRectSize.h)
  3259. };
  3260. contentGlueSize.c = checkCacheAutoForce(contentGlueSize, _contentGlueSizeCache);
  3261. _contentGlueSizeCache = contentGlueSize;
  3262. //apply correct contentGlue size
  3263. if (sizeAutoCapable) {
  3264. //size contentGlue correctly to make sure the element has correct size if the sizing switches to auto
  3265. if (contentGlueSize.c || (heightAuto || widthAuto)) {
  3266. contentGlueElementCSS[_strWidth] = contentGlueSize.w;
  3267. contentGlueElementCSS[_strHeight] = contentGlueSize.h;
  3268. //textarea-sizes are already calculated correctly at this point
  3269. if (!_isTextarea) {
  3270. contentSize = {
  3271. //use clientSize because natively overlaidScrollbars add borders
  3272. w: contentMeasureElement[LEXICON.cW],
  3273. h: contentMeasureElement[LEXICON.cH]
  3274. };
  3275. }
  3276. }
  3277. var textareaCoverCSS = {};
  3278. var setContentGlueElementCSSfunction = function (horizontal) {
  3279. var scrollbarVars = getScrollbarVars(horizontal);
  3280. var wh = scrollbarVars._w_h;
  3281. var strWH = scrollbarVars._width_height;
  3282. var autoSize = horizontal ? widthAuto : heightAuto;
  3283. var borderSize = horizontal ? _borderX : _borderY;
  3284. var paddingSize = horizontal ? _paddingX : _paddingY;
  3285. var marginSize = horizontal ? _marginX : _marginY;
  3286. var viewportSize = _viewportSize[wh] - borderSize - marginSize - (_isBorderBox ? 0 : paddingSize);
  3287. //make contentGlue size -1 if element is not auto sized, to make sure that a resize event happens when the element shrinks
  3288. if (!autoSize || (!autoSize && border.c))
  3289. contentGlueElementCSS[strWH] = hostAbsoluteRectSize[wh] - 1;
  3290. //if size is auto and host is smaller than size as min size, make content glue size -1 to make sure size changes will be detected (this is only needed if padding is 0)
  3291. if (autoSize && (contentSize[wh] < viewportSize) && (horizontal && _isTextarea ? !textareaAutoWrapping : true)) {
  3292. if (_isTextarea)
  3293. textareaCoverCSS[strWH] = parseToZeroOrNumber(_textareaCoverElement.css(strWH)) - 1;
  3294. contentGlueElementCSS[strWH] -= 1;
  3295. }
  3296. //make sure content glue size is at least 1
  3297. if (contentSize[wh] > 0)
  3298. contentGlueElementCSS[strWH] = MATH.max(1, contentGlueElementCSS[strWH]);
  3299. };
  3300. setContentGlueElementCSSfunction(true);
  3301. setContentGlueElementCSSfunction(false);
  3302. if (_isTextarea)
  3303. _textareaCoverElement.css(textareaCoverCSS);
  3304. _contentGlueElement.css(contentGlueElementCSS);
  3305. }
  3306. if (widthAuto)
  3307. contentElementCSS[_strWidth] = _strHundredPercent;
  3308. if (widthAuto && !_isBorderBox && !_mutationObserversConnected)
  3309. contentElementCSS[_strFloat] = 'none';
  3310. //apply and reset content style
  3311. _contentElement.css(contentElementCSS);
  3312. contentElementCSS = {};
  3313. //measure again, but this time all correct sizes:
  3314. var contentScrollSize = {
  3315. w: contentMeasureElement[LEXICON.sW],
  3316. h: contentMeasureElement[LEXICON.sH],
  3317. };
  3318. contentScrollSize.c = contentSizeChanged = checkCacheAutoForce(contentScrollSize, _contentScrollSizeCache);
  3319. _contentScrollSizeCache = contentScrollSize;
  3320. //refresh viewport size after correct measuring
  3321. _viewportSize = getViewportSize();
  3322. hostSize = getHostSize();
  3323. hostSizeChanged = checkCacheAutoForce(hostSize, _hostSizeCache);
  3324. _hostSizeCache = hostSize;
  3325. var hideOverflowForceTextarea = _isTextarea && (_viewportSize.w === 0 || _viewportSize.h === 0);
  3326. var previousOverflowAmount = _overflowAmountCache;
  3327. var overflowBehaviorIsVS = {};
  3328. var overflowBehaviorIsVH = {};
  3329. var overflowBehaviorIsS = {};
  3330. var overflowAmount = {};
  3331. var hasOverflow = {};
  3332. var hideOverflow = {};
  3333. var canScroll = {};
  3334. var viewportRect = _paddingElementNative[LEXICON.bCR]();
  3335. var setOverflowVariables = function (horizontal) {
  3336. var scrollbarVars = getScrollbarVars(horizontal);
  3337. var scrollbarVarsInverted = getScrollbarVars(!horizontal);
  3338. var xyI = scrollbarVarsInverted._x_y;
  3339. var xy = scrollbarVars._x_y;
  3340. var wh = scrollbarVars._w_h;
  3341. var widthHeight = scrollbarVars._width_height;
  3342. var scrollMax = _strScroll + scrollbarVars._Left_Top + 'Max';
  3343. var fractionalOverflowAmount = viewportRect[widthHeight] ? MATH.abs(viewportRect[widthHeight] - _viewportSize[wh]) : 0;
  3344. var checkFractionalOverflowAmount = previousOverflowAmount && previousOverflowAmount[xy] > 0 && _viewportElementNative[scrollMax] === 0;
  3345. overflowBehaviorIsVS[xy] = overflowBehavior[xy] === 'v-s';
  3346. overflowBehaviorIsVH[xy] = overflowBehavior[xy] === 'v-h';
  3347. overflowBehaviorIsS[xy] = overflowBehavior[xy] === 's';
  3348. overflowAmount[xy] = MATH.max(0, MATH.round((contentScrollSize[wh] - _viewportSize[wh]) * 100) / 100);
  3349. overflowAmount[xy] *= (hideOverflowForceTextarea || (checkFractionalOverflowAmount && fractionalOverflowAmount > 0 && fractionalOverflowAmount < 1)) ? 0 : 1;
  3350. hasOverflow[xy] = overflowAmount[xy] > 0;
  3351. //hideOverflow:
  3352. //x || y : true === overflow is hidden by "overflow: scroll" OR "overflow: hidden"
  3353. //xs || ys : true === overflow is hidden by "overflow: scroll"
  3354. hideOverflow[xy] = overflowBehaviorIsVS[xy] || overflowBehaviorIsVH[xy] ? (hasOverflow[xyI] && !overflowBehaviorIsVS[xyI] && !overflowBehaviorIsVH[xyI]) : hasOverflow[xy];
  3355. hideOverflow[xy + 's'] = hideOverflow[xy] ? (overflowBehaviorIsS[xy] || overflowBehaviorIsVS[xy]) : false;
  3356. canScroll[xy] = hasOverflow[xy] && hideOverflow[xy + 's'];
  3357. };
  3358. setOverflowVariables(true);
  3359. setOverflowVariables(false);
  3360. overflowAmount.c = checkCacheAutoForce(overflowAmount, _overflowAmountCache);
  3361. _overflowAmountCache = overflowAmount;
  3362. hasOverflow.c = checkCacheAutoForce(hasOverflow, _hasOverflowCache);
  3363. _hasOverflowCache = hasOverflow;
  3364. hideOverflow.c = checkCacheAutoForce(hideOverflow, _hideOverflowCache);
  3365. _hideOverflowCache = hideOverflow;
  3366. //if native scrollbar is overlay at x OR y axis, prepare DOM
  3367. if (_nativeScrollbarIsOverlaid.x || _nativeScrollbarIsOverlaid.y) {
  3368. var borderDesign = 'px solid transparent';
  3369. var contentArrangeElementCSS = {};
  3370. var arrangeContent = {};
  3371. var arrangeChanged = force;
  3372. var setContentElementCSS;
  3373. if (hasOverflow.x || hasOverflow.y) {
  3374. arrangeContent.w = _nativeScrollbarIsOverlaid.y && hasOverflow.y ? contentScrollSize.w + _overlayScrollbarDummySize.y : _strEmpty;
  3375. arrangeContent.h = _nativeScrollbarIsOverlaid.x && hasOverflow.x ? contentScrollSize.h + _overlayScrollbarDummySize.x : _strEmpty;
  3376. arrangeChanged = checkCacheAutoForce(arrangeContent, _arrangeContentSizeCache);
  3377. _arrangeContentSizeCache = arrangeContent;
  3378. }
  3379. if (hasOverflow.c || hideOverflow.c || contentScrollSize.c || cssDirectionChanged || widthAutoChanged || heightAutoChanged || widthAuto || heightAuto || ignoreOverlayScrollbarHidingChanged) {
  3380. contentElementCSS[_strMarginMinus + isRTLRight] = contentElementCSS[_strBorderMinus + isRTLRight] = _strEmpty;
  3381. setContentElementCSS = function (horizontal) {
  3382. var scrollbarVars = getScrollbarVars(horizontal);
  3383. var scrollbarVarsInverted = getScrollbarVars(!horizontal);
  3384. var xy = scrollbarVars._x_y;
  3385. var strDirection = horizontal ? _strBottom : isRTLLeft;
  3386. var invertedAutoSize = horizontal ? heightAuto : widthAuto;
  3387. if (_nativeScrollbarIsOverlaid[xy] && hasOverflow[xy] && hideOverflow[xy + 's']) {
  3388. contentElementCSS[_strMarginMinus + strDirection] = invertedAutoSize ? (ignoreOverlayScrollbarHiding ? _strEmpty : _overlayScrollbarDummySize[xy]) : _strEmpty;
  3389. contentElementCSS[_strBorderMinus + strDirection] = ((horizontal ? !invertedAutoSize : true) && !ignoreOverlayScrollbarHiding) ? (_overlayScrollbarDummySize[xy] + borderDesign) : _strEmpty;
  3390. }
  3391. else {
  3392. arrangeContent[scrollbarVarsInverted._w_h] =
  3393. contentElementCSS[_strMarginMinus + strDirection] =
  3394. contentElementCSS[_strBorderMinus + strDirection] = _strEmpty;
  3395. arrangeChanged = true;
  3396. }
  3397. };
  3398. if (_nativeScrollbarStyling) {
  3399. addRemoveClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible, !ignoreOverlayScrollbarHiding)
  3400. }
  3401. else {
  3402. setContentElementCSS(true);
  3403. setContentElementCSS(false);
  3404. }
  3405. }
  3406. if (ignoreOverlayScrollbarHiding) {
  3407. arrangeContent.w = arrangeContent.h = _strEmpty;
  3408. arrangeChanged = true;
  3409. }
  3410. if (arrangeChanged && !_nativeScrollbarStyling) {
  3411. contentArrangeElementCSS[_strWidth] = hideOverflow.y ? arrangeContent.w : _strEmpty;
  3412. contentArrangeElementCSS[_strHeight] = hideOverflow.x ? arrangeContent.h : _strEmpty;
  3413. if (!_contentArrangeElement) {
  3414. _contentArrangeElement = FRAMEWORK(generateDiv(_classNameContentArrangeElement));
  3415. _viewportElement.prepend(_contentArrangeElement);
  3416. }
  3417. _contentArrangeElement.css(contentArrangeElementCSS);
  3418. }
  3419. _contentElement.css(contentElementCSS);
  3420. }
  3421. var viewportElementCSS = {};
  3422. var paddingElementCSS = {};
  3423. var setViewportCSS;
  3424. if (hostSizeChanged || hasOverflow.c || hideOverflow.c || contentScrollSize.c || overflowBehaviorChanged || boxSizingChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged || clipAlwaysChanged || heightAutoChanged) {
  3425. viewportElementCSS[isRTLRight] = _strEmpty;
  3426. setViewportCSS = function (horizontal) {
  3427. var scrollbarVars = getScrollbarVars(horizontal);
  3428. var scrollbarVarsInverted = getScrollbarVars(!horizontal);
  3429. var xy = scrollbarVars._x_y;
  3430. var XY = scrollbarVars._X_Y;
  3431. var strDirection = horizontal ? _strBottom : isRTLLeft;
  3432. var reset = function () {
  3433. viewportElementCSS[strDirection] = _strEmpty;
  3434. _contentBorderSize[scrollbarVarsInverted._w_h] = 0;
  3435. };
  3436. if (hasOverflow[xy] && hideOverflow[xy + 's']) {
  3437. viewportElementCSS[strOverflow + XY] = _strScroll;
  3438. if (ignoreOverlayScrollbarHiding || _nativeScrollbarStyling) {
  3439. reset();
  3440. }
  3441. else {
  3442. viewportElementCSS[strDirection] = -(_nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[xy] : _nativeScrollbarSize[xy]);
  3443. _contentBorderSize[scrollbarVarsInverted._w_h] = _nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[scrollbarVarsInverted._x_y] : 0;
  3444. }
  3445. } else {
  3446. viewportElementCSS[strOverflow + XY] = _strEmpty;
  3447. reset();
  3448. }
  3449. };
  3450. setViewportCSS(true);
  3451. setViewportCSS(false);
  3452. // if the scroll container is too small and if there is any overflow with no overlay scrollbar (and scrollbar styling isn't possible),
  3453. // make viewport element greater in size (Firefox hide Scrollbars fix)
  3454. // because firefox starts hiding scrollbars on too small elements
  3455. // with this behavior the overflow calculation may be incorrect or the scrollbars would appear suddenly
  3456. // https://bugzilla.mozilla.org/show_bug.cgi?id=292284
  3457. if (!_nativeScrollbarStyling
  3458. && (_viewportSize.h < _nativeScrollbarMinSize.x || _viewportSize.w < _nativeScrollbarMinSize.y)
  3459. && ((hasOverflow.x && hideOverflow.x && !_nativeScrollbarIsOverlaid.x) || (hasOverflow.y && hideOverflow.y && !_nativeScrollbarIsOverlaid.y))) {
  3460. viewportElementCSS[_strPaddingMinus + _strTop] = _nativeScrollbarMinSize.x;
  3461. viewportElementCSS[_strMarginMinus + _strTop] = -_nativeScrollbarMinSize.x;
  3462. viewportElementCSS[_strPaddingMinus + isRTLRight] = _nativeScrollbarMinSize.y;
  3463. viewportElementCSS[_strMarginMinus + isRTLRight] = -_nativeScrollbarMinSize.y;
  3464. }
  3465. else {
  3466. viewportElementCSS[_strPaddingMinus + _strTop] =
  3467. viewportElementCSS[_strMarginMinus + _strTop] =
  3468. viewportElementCSS[_strPaddingMinus + isRTLRight] =
  3469. viewportElementCSS[_strMarginMinus + isRTLRight] = _strEmpty;
  3470. }
  3471. viewportElementCSS[_strPaddingMinus + isRTLLeft] =
  3472. viewportElementCSS[_strMarginMinus + isRTLLeft] = _strEmpty;
  3473. //if there is any overflow (x OR y axis) and this overflow shall be hidden, make overflow hidden, else overflow visible
  3474. if ((hasOverflow.x && hideOverflow.x) || (hasOverflow.y && hideOverflow.y) || hideOverflowForceTextarea) {
  3475. //only hide if is Textarea
  3476. if (_isTextarea && hideOverflowForceTextarea) {
  3477. paddingElementCSS[strOverflowX] =
  3478. paddingElementCSS[strOverflowY] = strHidden;
  3479. }
  3480. }
  3481. else {
  3482. if (!clipAlways || (overflowBehaviorIsVH.x || overflowBehaviorIsVS.x || overflowBehaviorIsVH.y || overflowBehaviorIsVS.y)) {
  3483. //only un-hide if Textarea
  3484. if (_isTextarea) {
  3485. paddingElementCSS[strOverflowX] =
  3486. paddingElementCSS[strOverflowY] = _strEmpty;
  3487. }
  3488. viewportElementCSS[strOverflowX] =
  3489. viewportElementCSS[strOverflowY] = strVisible;
  3490. }
  3491. }
  3492. _paddingElement.css(paddingElementCSS);
  3493. _viewportElement.css(viewportElementCSS);
  3494. viewportElementCSS = {};
  3495. //force soft redraw in webkit because without the scrollbars will may appear because DOM wont be redrawn under special conditions
  3496. if ((hasOverflow.c || boxSizingChanged || widthAutoChanged || heightAutoChanged) && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) {
  3497. var elementStyle = _contentElementNative[LEXICON.s];
  3498. var dump;
  3499. elementStyle.webkitTransform = 'scale(1)';
  3500. elementStyle.display = 'run-in';
  3501. dump = _contentElementNative[LEXICON.oH];
  3502. elementStyle.display = _strEmpty; //|| dump; //use dump to prevent it from deletion if minify
  3503. elementStyle.webkitTransform = _strEmpty;
  3504. }
  3505. /*
  3506. //force hard redraw in webkit if native overlaid scrollbars shall appear
  3507. if (ignoreOverlayScrollbarHidingChanged && ignoreOverlayScrollbarHiding) {
  3508. _hostElement.hide();
  3509. var dump = _hostElementNative[LEXICON.oH];
  3510. _hostElement.show();
  3511. }
  3512. */
  3513. }
  3514. //change to direction RTL and width auto Bugfix in Webkit
  3515. //without this fix, the DOM still thinks the scrollbar is LTR and thus the content is shifted to the left
  3516. contentElementCSS = {};
  3517. if (cssDirectionChanged || widthAutoChanged || heightAutoChanged) {
  3518. if (_isRTL && widthAuto) {
  3519. var floatTmp = _contentElement.css(_strFloat);
  3520. var posLeftWithoutFloat = MATH.round(_contentElement.css(_strFloat, _strEmpty).css(_strLeft, _strEmpty).position().left);
  3521. _contentElement.css(_strFloat, floatTmp);
  3522. var posLeftWithFloat = MATH.round(_contentElement.position().left);
  3523. if (posLeftWithoutFloat !== posLeftWithFloat)
  3524. contentElementCSS[_strLeft] = posLeftWithoutFloat;
  3525. }
  3526. else {
  3527. contentElementCSS[_strLeft] = _strEmpty;
  3528. }
  3529. }
  3530. _contentElement.css(contentElementCSS);
  3531. //handle scroll position
  3532. if (_isTextarea && contentSizeChanged) {
  3533. var textareaInfo = getTextareaInfo();
  3534. if (textareaInfo) {
  3535. var textareaRowsChanged = _textareaInfoCache === undefined ? true : textareaInfo._rows !== _textareaInfoCache._rows;
  3536. var cursorRow = textareaInfo._cursorRow;
  3537. var cursorCol = textareaInfo._cursorColumn;
  3538. var widestRow = textareaInfo._widestRow;
  3539. var lastRow = textareaInfo._rows;
  3540. var lastCol = textareaInfo._columns;
  3541. var cursorPos = textareaInfo._cursorPosition;
  3542. var cursorMax = textareaInfo._cursorMax;
  3543. var cursorIsLastPosition = (cursorPos >= cursorMax && _textareaHasFocus);
  3544. var textareaScrollAmount = {
  3545. x: (!textareaAutoWrapping && (cursorCol === lastCol && cursorRow === widestRow)) ? _overflowAmountCache.x : -1,
  3546. y: (textareaAutoWrapping ? cursorIsLastPosition || textareaRowsChanged && (previousOverflowAmount ? (currScroll.y === previousOverflowAmount.y) : false) : (cursorIsLastPosition || textareaRowsChanged) && cursorRow === lastRow) ? _overflowAmountCache.y : -1
  3547. };
  3548. currScroll.x = textareaScrollAmount.x > -1 ? (_isRTL && _normalizeRTLCache && _rtlScrollBehavior.i ? 0 : textareaScrollAmount.x) : currScroll.x; //if inverted, scroll to 0 -> normalized this means to max scroll offset.
  3549. currScroll.y = textareaScrollAmount.y > -1 ? textareaScrollAmount.y : currScroll.y;
  3550. }
  3551. _textareaInfoCache = textareaInfo;
  3552. }
  3553. if (_isRTL && _rtlScrollBehavior.i && _nativeScrollbarIsOverlaid.y && hasOverflow.x && _normalizeRTLCache)
  3554. currScroll.x += _contentBorderSize.w || 0;
  3555. if (widthAuto)
  3556. _hostElement[_strScrollLeft](0);
  3557. if (heightAuto)
  3558. _hostElement[_strScrollTop](0);
  3559. _viewportElement[_strScrollLeft](currScroll.x)[_strScrollTop](currScroll.y);
  3560. //scrollbars management:
  3561. var scrollbarsVisibilityVisible = scrollbarsVisibility === 'v';
  3562. var scrollbarsVisibilityHidden = scrollbarsVisibility === 'h';
  3563. var scrollbarsVisibilityAuto = scrollbarsVisibility === 'a';
  3564. var refreshScrollbarsVisibility = function (showX, showY) {
  3565. showY = showY === undefined ? showX : showY;
  3566. refreshScrollbarAppearance(true, showX, canScroll.x)
  3567. refreshScrollbarAppearance(false, showY, canScroll.y)
  3568. };
  3569. //manage class name which indicates scrollable overflow
  3570. addRemoveClass(_hostElement, _classNameHostOverflow, hideOverflow.x || hideOverflow.y);
  3571. addRemoveClass(_hostElement, _classNameHostOverflowX, hideOverflow.x);
  3572. addRemoveClass(_hostElement, _classNameHostOverflowY, hideOverflow.y);
  3573. //add or remove rtl class name for styling purposes except when its body, then the scrollbar stays
  3574. if (cssDirectionChanged && !_isBody) {
  3575. addRemoveClass(_hostElement, _classNameHostRTL, _isRTL);
  3576. }
  3577. //manage the resize feature (CSS3 resize "polyfill" for this plugin)
  3578. if (_isBody)
  3579. addClass(_hostElement, _classNameHostResizeDisabled);
  3580. if (resizeChanged) {
  3581. addRemoveClass(_hostElement, _classNameHostResizeDisabled, _resizeNone);
  3582. addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResize, !_resizeNone);
  3583. addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeB, _resizeBoth);
  3584. addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeH, _resizeHorizontal);
  3585. addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeV, _resizeVertical);
  3586. }
  3587. //manage the scrollbars general visibility + the scrollbar interactivity (unusable class name)
  3588. if (scrollbarsVisibilityChanged || overflowBehaviorChanged || hideOverflow.c || hasOverflow.c || ignoreOverlayScrollbarHidingChanged) {
  3589. if (ignoreOverlayScrollbarHiding) {
  3590. if (ignoreOverlayScrollbarHidingChanged) {
  3591. removeClass(_hostElement, _classNameHostScrolling);
  3592. if (ignoreOverlayScrollbarHiding) {
  3593. refreshScrollbarsVisibility(false);
  3594. }
  3595. }
  3596. }
  3597. else if (scrollbarsVisibilityAuto) {
  3598. refreshScrollbarsVisibility(canScroll.x, canScroll.y);
  3599. }
  3600. else if (scrollbarsVisibilityVisible) {
  3601. refreshScrollbarsVisibility(true);
  3602. }
  3603. else if (scrollbarsVisibilityHidden) {
  3604. refreshScrollbarsVisibility(false);
  3605. }
  3606. }
  3607. //manage the scrollbars auto hide feature (auto hide them after specific actions)
  3608. if (scrollbarsAutoHideChanged || ignoreOverlayScrollbarHidingChanged) {
  3609. setupHostMouseTouchEvents(!_scrollbarsAutoHideLeave && !_scrollbarsAutoHideMove);
  3610. refreshScrollbarsAutoHide(_scrollbarsAutoHideNever, !_scrollbarsAutoHideNever);
  3611. }
  3612. //manage scrollbars handle length & offset - don't remove!
  3613. if (hostSizeChanged || overflowAmount.c || heightAutoChanged || widthAutoChanged || resizeChanged || boxSizingChanged || paddingAbsoluteChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged) {
  3614. refreshScrollbarHandleLength(true);
  3615. refreshScrollbarHandleOffset(true);
  3616. refreshScrollbarHandleLength(false);
  3617. refreshScrollbarHandleOffset(false);
  3618. }
  3619. //manage interactivity
  3620. if (scrollbarsClickScrollingChanged)
  3621. refreshScrollbarsInteractive(true, scrollbarsClickScrolling);
  3622. if (scrollbarsDragScrollingChanged)
  3623. refreshScrollbarsInteractive(false, scrollbarsDragScrolling);
  3624. //callbacks:
  3625. dispatchCallback('onDirectionChanged', {
  3626. isRTL: _isRTL,
  3627. dir: cssDirection
  3628. }, cssDirectionChanged);
  3629. dispatchCallback('onHostSizeChanged', {
  3630. width: _hostSizeCache.w,
  3631. height: _hostSizeCache.h
  3632. }, hostSizeChanged);
  3633. dispatchCallback('onContentSizeChanged', {
  3634. width: _contentScrollSizeCache.w,
  3635. height: _contentScrollSizeCache.h
  3636. }, contentSizeChanged);
  3637. dispatchCallback('onOverflowChanged', {
  3638. x: hasOverflow.x,
  3639. y: hasOverflow.y,
  3640. xScrollable: hideOverflow.xs,
  3641. yScrollable: hideOverflow.ys,
  3642. clipped: hideOverflow.x || hideOverflow.y
  3643. }, hasOverflow.c || hideOverflow.c);
  3644. dispatchCallback('onOverflowAmountChanged', {
  3645. x: overflowAmount.x,
  3646. y: overflowAmount.y
  3647. }, overflowAmount.c);
  3648. }
  3649. //fix body min size
  3650. if (_isBody && _bodyMinSizeCache && (_hasOverflowCache.c || _bodyMinSizeCache.c)) {
  3651. //its possible that no min size was measured until now, because the content arrange element was just added now, in this case, measure now the min size.
  3652. if (!_bodyMinSizeCache.f)
  3653. bodyMinSizeChanged();
  3654. if (_nativeScrollbarIsOverlaid.y && _hasOverflowCache.x)
  3655. _contentElement.css(_strMinMinus + _strWidth, _bodyMinSizeCache.w + _overlayScrollbarDummySize.y);
  3656. if (_nativeScrollbarIsOverlaid.x && _hasOverflowCache.y)
  3657. _contentElement.css(_strMinMinus + _strHeight, _bodyMinSizeCache.h + _overlayScrollbarDummySize.x);
  3658. _bodyMinSizeCache.c = false;
  3659. }
  3660. if (_initialized && changedOptions.updateOnLoad) {
  3661. updateElementsOnLoad();
  3662. }
  3663. //freezeResizeObserver(_sizeObserverElement, false);
  3664. //freezeResizeObserver(_sizeAutoObserverElement, false);
  3665. dispatchCallback('onUpdated', { forced: force });
  3666. }
  3667. /**
  3668. * Updates the found elements of which the load event shall be handled.
  3669. */
  3670. function updateElementsOnLoad() {
  3671. if (!_isTextarea) {
  3672. eachUpdateOnLoad(function (i, updateOnLoadSelector) {
  3673. _contentElement.find(updateOnLoadSelector).each(function (i, el) {
  3674. // if element doesn't have a updateOnLoadCallback applied
  3675. if (COMPATIBILITY.inA(el, _updateOnLoadElms) < 0) {
  3676. _updateOnLoadElms.push(el);
  3677. FRAMEWORK(el)
  3678. .off(_updateOnLoadEventName, updateOnLoadCallback)
  3679. .on(_updateOnLoadEventName, updateOnLoadCallback);
  3680. }
  3681. });
  3682. });
  3683. }
  3684. }
  3685. //==== Options ====//
  3686. /**
  3687. * Sets new options but doesn't call the update method.
  3688. * @param newOptions The object which contains the new options.
  3689. * @returns {*} A object which contains the changed options.
  3690. */
  3691. function setOptions(newOptions) {
  3692. var validatedOpts = _pluginsOptions._validate(newOptions, _pluginsOptions._template, true, _currentOptions)
  3693. _currentOptions = extendDeep({}, _currentOptions, validatedOpts._default);
  3694. _currentPreparedOptions = extendDeep({}, _currentPreparedOptions, validatedOpts._prepared);
  3695. return validatedOpts._prepared;
  3696. }
  3697. //==== Structure ====//
  3698. /**
  3699. * Builds or destroys the wrapper and helper DOM elements.
  3700. * @param destroy Indicates whether the DOM shall be build or destroyed.
  3701. */
  3702. /**
  3703. * Builds or destroys the wrapper and helper DOM elements.
  3704. * @param destroy Indicates whether the DOM shall be build or destroyed.
  3705. */
  3706. function setupStructureDOM(destroy) {
  3707. var strParent = 'parent';
  3708. var classNameResizeObserverHost = 'os-resize-observer-host';
  3709. var classNameTextareaElementFull = _classNameTextareaElement + _strSpace + _classNameTextInherit;
  3710. var textareaClass = _isTextarea ? _strSpace + _classNameTextInherit : _strEmpty;
  3711. var adoptAttrs = _currentPreparedOptions.textarea.inheritedAttrs;
  3712. var adoptAttrsMap = {};
  3713. var applyAdoptedAttrs = function () {
  3714. var applyAdoptedAttrsElm = destroy ? _targetElement : _hostElement;
  3715. each(adoptAttrsMap, function (key, value) {
  3716. if (type(value) == TYPES.s) {
  3717. if (key == LEXICON.c)
  3718. applyAdoptedAttrsElm.addClass(value);
  3719. else
  3720. applyAdoptedAttrsElm.attr(key, value);
  3721. }
  3722. });
  3723. };
  3724. var hostElementClassNames = [
  3725. _classNameHostElement,
  3726. _classNameHostElementForeign,
  3727. _classNameHostTextareaElement,
  3728. _classNameHostResizeDisabled,
  3729. _classNameHostRTL,
  3730. _classNameHostScrollbarHorizontalHidden,
  3731. _classNameHostScrollbarVerticalHidden,
  3732. _classNameHostTransition,
  3733. _classNameHostScrolling,
  3734. _classNameHostOverflow,
  3735. _classNameHostOverflowX,
  3736. _classNameHostOverflowY,
  3737. _classNameThemeNone,
  3738. _classNameTextareaElement,
  3739. _classNameTextInherit,
  3740. _classNameCache].join(_strSpace);
  3741. var hostElementCSS = {};
  3742. //get host element as first element, because that's the most upper element and required for the other elements
  3743. _hostElement = _hostElement || (_isTextarea ? (_domExists ? _targetElement[strParent]()[strParent]()[strParent]()[strParent]() : FRAMEWORK(generateDiv(_classNameHostTextareaElement))) : _targetElement);
  3744. _contentElement = _contentElement || selectOrGenerateDivByClass(_classNameContentElement + textareaClass);
  3745. _viewportElement = _viewportElement || selectOrGenerateDivByClass(_classNameViewportElement + textareaClass);
  3746. _paddingElement = _paddingElement || selectOrGenerateDivByClass(_classNamePaddingElement + textareaClass);
  3747. _sizeObserverElement = _sizeObserverElement || selectOrGenerateDivByClass(classNameResizeObserverHost);
  3748. _textareaCoverElement = _textareaCoverElement || (_isTextarea ? selectOrGenerateDivByClass(_classNameTextareaCoverElement) : undefined);
  3749. //add this class to workaround class changing issues with UI frameworks especially Vue
  3750. if (_domExists)
  3751. addClass(_hostElement, _classNameHostElementForeign);
  3752. //on destroy, remove all generated class names from the host element before collecting the adopted attributes
  3753. //to prevent adopting generated class names
  3754. if (destroy)
  3755. removeClass(_hostElement, hostElementClassNames);
  3756. //collect all adopted attributes
  3757. adoptAttrs = type(adoptAttrs) == TYPES.s ? adoptAttrs.split(_strSpace) : adoptAttrs;
  3758. if (COMPATIBILITY.isA(adoptAttrs) && _isTextarea) {
  3759. each(adoptAttrs, function (i, v) {
  3760. if (type(v) == TYPES.s) {
  3761. adoptAttrsMap[v] = destroy ? _hostElement.attr(v) : _targetElement.attr(v);
  3762. }
  3763. });
  3764. }
  3765. if (!destroy) {
  3766. if (_isTextarea) {
  3767. if (!_currentPreparedOptions.sizeAutoCapable) {
  3768. hostElementCSS[_strWidth] = _targetElement.css(_strWidth);
  3769. hostElementCSS[_strHeight] = _targetElement.css(_strHeight);
  3770. }
  3771. if (!_domExists)
  3772. _targetElement.addClass(_classNameTextInherit).wrap(_hostElement);
  3773. //jQuery clones elements in wrap functions, so we have to select them again
  3774. _hostElement = _targetElement[strParent]().css(hostElementCSS);
  3775. }
  3776. if (!_domExists) {
  3777. //add the correct class to the target element
  3778. addClass(_targetElement, _isTextarea ? classNameTextareaElementFull : _classNameHostElement);
  3779. //wrap the content into the generated elements to create the required DOM
  3780. _hostElement.wrapInner(_contentElement)
  3781. .wrapInner(_viewportElement)
  3782. .wrapInner(_paddingElement)
  3783. .prepend(_sizeObserverElement);
  3784. //jQuery clones elements in wrap functions, so we have to select them again
  3785. _contentElement = findFirst(_hostElement, _strDot + _classNameContentElement);
  3786. _viewportElement = findFirst(_hostElement, _strDot + _classNameViewportElement);
  3787. _paddingElement = findFirst(_hostElement, _strDot + _classNamePaddingElement);
  3788. if (_isTextarea) {
  3789. _contentElement.prepend(_textareaCoverElement);
  3790. applyAdoptedAttrs();
  3791. }
  3792. }
  3793. if (_nativeScrollbarStyling)
  3794. addClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible);
  3795. if (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)
  3796. addClass(_viewportElement, _classNameViewportNativeScrollbarsOverlaid);
  3797. if (_isBody)
  3798. addClass(_htmlElement, _classNameHTMLElement);
  3799. _sizeObserverElementNative = _sizeObserverElement[0];
  3800. _hostElementNative = _hostElement[0];
  3801. _paddingElementNative = _paddingElement[0];
  3802. _viewportElementNative = _viewportElement[0];
  3803. _contentElementNative = _contentElement[0];
  3804. updateViewportAttrsFromTarget();
  3805. }
  3806. else {
  3807. if (_domExists && _initialized) {
  3808. //clear size observer
  3809. _sizeObserverElement.children().remove();
  3810. //remove the style property and classes from already generated elements
  3811. each([_paddingElement, _viewportElement, _contentElement, _textareaCoverElement], function (i, elm) {
  3812. if (elm) {
  3813. removeClass(elm.removeAttr(LEXICON.s), _classNamesDynamicDestroy);
  3814. }
  3815. });
  3816. //add classes to the host element which was removed previously to match the expected DOM
  3817. addClass(_hostElement, _isTextarea ? _classNameHostTextareaElement : _classNameHostElement);
  3818. }
  3819. else {
  3820. //remove size observer
  3821. remove(_sizeObserverElement);
  3822. //unwrap the content to restore DOM
  3823. _contentElement.contents()
  3824. .unwrap()
  3825. .unwrap()
  3826. .unwrap();
  3827. if (_isTextarea) {
  3828. _targetElement.unwrap();
  3829. remove(_hostElement);
  3830. remove(_textareaCoverElement);
  3831. applyAdoptedAttrs();
  3832. }
  3833. }
  3834. if (_isTextarea)
  3835. _targetElement.removeAttr(LEXICON.s);
  3836. if (_isBody)
  3837. removeClass(_htmlElement, _classNameHTMLElement);
  3838. }
  3839. }
  3840. /**
  3841. * Adds or removes all wrapper elements interactivity events.
  3842. * @param destroy Indicates whether the Events shall be added or removed.
  3843. */
  3844. function setupStructureEvents() {
  3845. var textareaKeyDownRestrictedKeyCodes = [
  3846. 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 123, //F1 to F12
  3847. 33, 34, //page up, page down
  3848. 37, 38, 39, 40, //left, up, right, down arrows
  3849. 16, 17, 18, 19, 20, 144 //Shift, Ctrl, Alt, Pause, CapsLock, NumLock
  3850. ];
  3851. var textareaKeyDownKeyCodesList = [];
  3852. var textareaUpdateIntervalID;
  3853. var scrollStopTimeoutId;
  3854. var scrollStopDelay = 175;
  3855. var strFocus = 'focus';
  3856. function updateTextarea(doClearInterval) {
  3857. textareaUpdate();
  3858. _base.update(_strAuto);
  3859. if (doClearInterval && _autoUpdateRecommended)
  3860. clearInterval(textareaUpdateIntervalID);
  3861. }
  3862. function textareaOnScroll(event) {
  3863. _targetElement[_strScrollLeft](_rtlScrollBehavior.i && _normalizeRTLCache ? 9999999 : 0);
  3864. _targetElement[_strScrollTop](0);
  3865. COMPATIBILITY.prvD(event);
  3866. COMPATIBILITY.stpP(event);
  3867. return false;
  3868. }
  3869. function textareaOnDrop(event) {
  3870. setTimeout(function () {
  3871. if (!_destroyed)
  3872. updateTextarea();
  3873. }, 50);
  3874. }
  3875. function textareaOnFocus() {
  3876. _textareaHasFocus = true;
  3877. addClass(_hostElement, strFocus);
  3878. }
  3879. function textareaOnFocusout() {
  3880. _textareaHasFocus = false;
  3881. textareaKeyDownKeyCodesList = [];
  3882. removeClass(_hostElement, strFocus);
  3883. updateTextarea(true);
  3884. }
  3885. function textareaOnKeyDown(event) {
  3886. var keyCode = event.keyCode;
  3887. if (inArray(keyCode, textareaKeyDownRestrictedKeyCodes) < 0) {
  3888. if (!textareaKeyDownKeyCodesList[LEXICON.l]) {
  3889. updateTextarea();
  3890. textareaUpdateIntervalID = setInterval(updateTextarea, 1000 / 60);
  3891. }
  3892. if (inArray(keyCode, textareaKeyDownKeyCodesList) < 0)
  3893. textareaKeyDownKeyCodesList.push(keyCode);
  3894. }
  3895. }
  3896. function textareaOnKeyUp(event) {
  3897. var keyCode = event.keyCode;
  3898. var index = inArray(keyCode, textareaKeyDownKeyCodesList);
  3899. if (inArray(keyCode, textareaKeyDownRestrictedKeyCodes) < 0) {
  3900. if (index > -1)
  3901. textareaKeyDownKeyCodesList.splice(index, 1);
  3902. if (!textareaKeyDownKeyCodesList[LEXICON.l])
  3903. updateTextarea(true);
  3904. }
  3905. }
  3906. function contentOnTransitionEnd(event) {
  3907. if (_autoUpdateCache === true)
  3908. return;
  3909. event = event.originalEvent || event;
  3910. if (isSizeAffectingCSSProperty(event.propertyName))
  3911. _base.update(_strAuto);
  3912. }
  3913. function viewportOnScroll(event) {
  3914. if (!_sleeping) {
  3915. if (scrollStopTimeoutId !== undefined)
  3916. clearTimeout(scrollStopTimeoutId);
  3917. else {
  3918. if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
  3919. refreshScrollbarsAutoHide(true);
  3920. if (!nativeOverlayScrollbarsAreActive())
  3921. addClass(_hostElement, _classNameHostScrolling);
  3922. dispatchCallback('onScrollStart', event);
  3923. }
  3924. //if a scrollbars handle gets dragged, the mousemove event is responsible for refreshing the handle offset
  3925. //because if CSS scroll-snap is used, the handle offset gets only refreshed on every snap point
  3926. //this looks laggy & clunky, it looks much better if the offset refreshes with the mousemove
  3927. if (!_scrollbarsHandlesDefineScrollPos) {
  3928. refreshScrollbarHandleOffset(true);
  3929. refreshScrollbarHandleOffset(false);
  3930. }
  3931. dispatchCallback('onScroll', event);
  3932. scrollStopTimeoutId = setTimeout(function () {
  3933. if (!_destroyed) {
  3934. //OnScrollStop:
  3935. clearTimeout(scrollStopTimeoutId);
  3936. scrollStopTimeoutId = undefined;
  3937. if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
  3938. refreshScrollbarsAutoHide(false);
  3939. if (!nativeOverlayScrollbarsAreActive())
  3940. removeClass(_hostElement, _classNameHostScrolling);
  3941. dispatchCallback('onScrollStop', event);
  3942. }
  3943. }, scrollStopDelay);
  3944. }
  3945. }
  3946. if (_isTextarea) {
  3947. if (_msieVersion > 9 || !_autoUpdateRecommended) {
  3948. addDestroyEventListener(_targetElement, 'input', updateTextarea);
  3949. }
  3950. else {
  3951. addDestroyEventListener(_targetElement,
  3952. [_strKeyDownEvent, _strKeyUpEvent],
  3953. [textareaOnKeyDown, textareaOnKeyUp]);
  3954. }
  3955. addDestroyEventListener(_targetElement,
  3956. [_strScroll, 'drop', strFocus, strFocus + 'out'],
  3957. [textareaOnScroll, textareaOnDrop, textareaOnFocus, textareaOnFocusout]);
  3958. }
  3959. else {
  3960. addDestroyEventListener(_contentElement, _strTransitionEndEvent, contentOnTransitionEnd);
  3961. }
  3962. addDestroyEventListener(_viewportElement, _strScroll, viewportOnScroll, true);
  3963. }
  3964. //==== Scrollbars ====//
  3965. /**
  3966. * Builds or destroys all scrollbar DOM elements (scrollbar, track, handle)
  3967. * @param destroy Indicates whether the DOM shall be build or destroyed.
  3968. */
  3969. function setupScrollbarsDOM(destroy) {
  3970. var selectOrGenerateScrollbarDOM = function (isHorizontal) {
  3971. var scrollbarClassName = isHorizontal ? _classNameScrollbarHorizontal : _classNameScrollbarVertical;
  3972. var scrollbar = selectOrGenerateDivByClass(_classNameScrollbar + _strSpace + scrollbarClassName, true);
  3973. var track = selectOrGenerateDivByClass(_classNameScrollbarTrack, scrollbar);
  3974. var handle = selectOrGenerateDivByClass(_classNameScrollbarHandle, scrollbar);
  3975. if (!_domExists && !destroy) {
  3976. scrollbar.append(track);
  3977. track.append(handle);
  3978. }
  3979. return {
  3980. _scrollbar: scrollbar,
  3981. _track: track,
  3982. _handle: handle
  3983. };
  3984. };
  3985. function resetScrollbarDOM(isHorizontal) {
  3986. var scrollbarVars = getScrollbarVars(isHorizontal);
  3987. var scrollbar = scrollbarVars._scrollbar;
  3988. var track = scrollbarVars._track;
  3989. var handle = scrollbarVars._handle;
  3990. if (_domExists && _initialized) {
  3991. each([scrollbar, track, handle], function (i, elm) {
  3992. removeClass(elm.removeAttr(LEXICON.s), _classNamesDynamicDestroy);
  3993. });
  3994. }
  3995. else {
  3996. remove(scrollbar || selectOrGenerateScrollbarDOM(isHorizontal)._scrollbar);
  3997. }
  3998. }
  3999. var horizontalElements;
  4000. var verticalElements;
  4001. if (!destroy) {
  4002. horizontalElements = selectOrGenerateScrollbarDOM(true);
  4003. verticalElements = selectOrGenerateScrollbarDOM();
  4004. _scrollbarHorizontalElement = horizontalElements._scrollbar;
  4005. _scrollbarHorizontalTrackElement = horizontalElements._track;
  4006. _scrollbarHorizontalHandleElement = horizontalElements._handle;
  4007. _scrollbarVerticalElement = verticalElements._scrollbar;
  4008. _scrollbarVerticalTrackElement = verticalElements._track;
  4009. _scrollbarVerticalHandleElement = verticalElements._handle;
  4010. if (!_domExists) {
  4011. _paddingElement.after(_scrollbarVerticalElement);
  4012. _paddingElement.after(_scrollbarHorizontalElement);
  4013. }
  4014. }
  4015. else {
  4016. resetScrollbarDOM(true);
  4017. resetScrollbarDOM();
  4018. }
  4019. }
  4020. /**
  4021. * Initializes all scrollbar interactivity events. (track and handle dragging, clicking, scrolling)
  4022. * @param isHorizontal True if the target scrollbar is the horizontal scrollbar, false if the target scrollbar is the vertical scrollbar.
  4023. */
  4024. function setupScrollbarEvents(isHorizontal) {
  4025. var scrollbarVars = getScrollbarVars(isHorizontal);
  4026. var scrollbarVarsInfo = scrollbarVars._info;
  4027. var insideIFrame = _windowElementNative.top !== _windowElementNative;
  4028. var xy = scrollbarVars._x_y;
  4029. var XY = scrollbarVars._X_Y;
  4030. var scroll = _strScroll + scrollbarVars._Left_Top;
  4031. var strActive = 'active';
  4032. var strSnapHandle = 'snapHandle';
  4033. var strClickEvent = 'click';
  4034. var scrollDurationFactor = 1;
  4035. var increaseDecreaseScrollAmountKeyCodes = [16, 17]; //shift, ctrl
  4036. var trackTimeout;
  4037. var mouseDownScroll;
  4038. var mouseDownOffset;
  4039. var mouseDownInvertedScale;
  4040. function getPointerPosition(event) {
  4041. return _msieVersion && insideIFrame ? event['screen' + XY] : COMPATIBILITY.page(event)[xy]; //use screen coordinates in EDGE & IE because the page values are incorrect in frames.
  4042. }
  4043. function getPreparedScrollbarsOption(name) {
  4044. return _currentPreparedOptions.scrollbars[name];
  4045. }
  4046. function increaseTrackScrollAmount() {
  4047. scrollDurationFactor = 0.5;
  4048. }
  4049. function decreaseTrackScrollAmount() {
  4050. scrollDurationFactor = 1;
  4051. }
  4052. function stopClickEventPropagation(event) {
  4053. COMPATIBILITY.stpP(event);
  4054. }
  4055. function documentKeyDown(event) {
  4056. if (inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1)
  4057. increaseTrackScrollAmount();
  4058. }
  4059. function documentKeyUp(event) {
  4060. if (inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1)
  4061. decreaseTrackScrollAmount();
  4062. }
  4063. function onMouseTouchDownContinue(event) {
  4064. var originalEvent = event.originalEvent || event;
  4065. var isTouchEvent = originalEvent.touches !== undefined;
  4066. return _sleeping || _destroyed || nativeOverlayScrollbarsAreActive() || !_scrollbarsDragScrollingCache || (isTouchEvent && !getPreparedScrollbarsOption('touchSupport')) ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;
  4067. }
  4068. function documentDragMove(event) {
  4069. if (onMouseTouchDownContinue(event)) {
  4070. var trackLength = scrollbarVarsInfo._trackLength;
  4071. var handleLength = scrollbarVarsInfo._handleLength;
  4072. var scrollRange = scrollbarVarsInfo._maxScroll;
  4073. var scrollRaw = (getPointerPosition(event) - mouseDownOffset) * mouseDownInvertedScale;
  4074. var scrollDeltaPercent = scrollRaw / (trackLength - handleLength);
  4075. var scrollDelta = (scrollRange * scrollDeltaPercent);
  4076. scrollDelta = isFinite(scrollDelta) ? scrollDelta : 0;
  4077. if (_isRTL && isHorizontal && !_rtlScrollBehavior.i)
  4078. scrollDelta *= -1;
  4079. _viewportElement[scroll](MATH.round(mouseDownScroll + scrollDelta));
  4080. if (_scrollbarsHandlesDefineScrollPos)
  4081. refreshScrollbarHandleOffset(isHorizontal, mouseDownScroll + scrollDelta);
  4082. if (!_supportPassiveEvents)
  4083. COMPATIBILITY.prvD(event);
  4084. }
  4085. else
  4086. documentMouseTouchUp(event);
  4087. }
  4088. function documentMouseTouchUp(event) {
  4089. event = event || event.originalEvent;
  4090. setupResponsiveEventListener(_documentElement,
  4091. [_strMouseTouchMoveEvent, _strMouseTouchUpEvent, _strKeyDownEvent, _strKeyUpEvent, _strSelectStartEvent],
  4092. [documentDragMove, documentMouseTouchUp, documentKeyDown, documentKeyUp, documentOnSelectStart],
  4093. true);
  4094. COMPATIBILITY.rAF()(function() {
  4095. setupResponsiveEventListener(_documentElement, strClickEvent, stopClickEventPropagation, true, { _capture: true });
  4096. });
  4097. if (_scrollbarsHandlesDefineScrollPos)
  4098. refreshScrollbarHandleOffset(isHorizontal, true);
  4099. _scrollbarsHandlesDefineScrollPos = false;
  4100. removeClass(_bodyElement, _classNameDragging);
  4101. removeClass(scrollbarVars._handle, strActive);
  4102. removeClass(scrollbarVars._track, strActive);
  4103. removeClass(scrollbarVars._scrollbar, strActive);
  4104. mouseDownScroll = undefined;
  4105. mouseDownOffset = undefined;
  4106. mouseDownInvertedScale = 1;
  4107. decreaseTrackScrollAmount();
  4108. if (trackTimeout !== undefined) {
  4109. _base.scrollStop();
  4110. clearTimeout(trackTimeout);
  4111. trackTimeout = undefined;
  4112. }
  4113. if (event) {
  4114. var rect = _hostElementNative[LEXICON.bCR]();
  4115. var mouseInsideHost = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;
  4116. //if mouse is outside host element
  4117. if (!mouseInsideHost)
  4118. hostOnMouseLeave();
  4119. if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
  4120. refreshScrollbarsAutoHide(false);
  4121. }
  4122. }
  4123. function onHandleMouseTouchDown(event) {
  4124. if (onMouseTouchDownContinue(event))
  4125. onHandleMouseTouchDownAction(event);
  4126. }
  4127. function onHandleMouseTouchDownAction(event) {
  4128. mouseDownScroll = _viewportElement[scroll]();
  4129. mouseDownScroll = isNaN(mouseDownScroll) ? 0 : mouseDownScroll;
  4130. if (_isRTL && isHorizontal && !_rtlScrollBehavior.n || !_isRTL)
  4131. mouseDownScroll = mouseDownScroll < 0 ? 0 : mouseDownScroll;
  4132. mouseDownInvertedScale = getHostElementInvertedScale()[xy];
  4133. mouseDownOffset = getPointerPosition(event);
  4134. _scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption(strSnapHandle);
  4135. addClass(_bodyElement, _classNameDragging);
  4136. addClass(scrollbarVars._handle, strActive);
  4137. addClass(scrollbarVars._scrollbar, strActive);
  4138. setupResponsiveEventListener(_documentElement,
  4139. [_strMouseTouchMoveEvent, _strMouseTouchUpEvent, _strSelectStartEvent],
  4140. [documentDragMove, documentMouseTouchUp, documentOnSelectStart]);
  4141. COMPATIBILITY.rAF()(function() {
  4142. setupResponsiveEventListener(_documentElement, strClickEvent, stopClickEventPropagation, false, { _capture: true });
  4143. });
  4144. if (_msieVersion || !_documentMixed)
  4145. COMPATIBILITY.prvD(event);
  4146. COMPATIBILITY.stpP(event);
  4147. }
  4148. function onTrackMouseTouchDown(event) {
  4149. if (onMouseTouchDownContinue(event)) {
  4150. var handleToViewportRatio = scrollbarVars._info._handleLength / Math.round(MATH.min(1, _viewportSize[scrollbarVars._w_h] / _contentScrollSizeCache[scrollbarVars._w_h]) * scrollbarVars._info._trackLength);
  4151. var scrollDistance = MATH.round(_viewportSize[scrollbarVars._w_h] * handleToViewportRatio);
  4152. var scrollBaseDuration = 270 * handleToViewportRatio;
  4153. var scrollFirstIterationDelay = 400 * handleToViewportRatio;
  4154. var trackOffset = scrollbarVars._track.offset()[scrollbarVars._left_top];
  4155. var ctrlKey = event.ctrlKey;
  4156. var instantScroll = event.shiftKey;
  4157. var instantScrollTransition = instantScroll && ctrlKey;
  4158. var isFirstIteration = true;
  4159. var easing = 'linear';
  4160. var decreaseScroll;
  4161. var finishedCondition;
  4162. var scrollActionFinsished = function (transition) {
  4163. if (_scrollbarsHandlesDefineScrollPos)
  4164. refreshScrollbarHandleOffset(isHorizontal, transition);
  4165. };
  4166. var scrollActionInstantFinished = function () {
  4167. scrollActionFinsished();
  4168. onHandleMouseTouchDownAction(event);
  4169. };
  4170. var scrollAction = function () {
  4171. if (!_destroyed) {
  4172. var mouseOffset = (mouseDownOffset - trackOffset) * mouseDownInvertedScale;
  4173. var handleOffset = scrollbarVarsInfo._handleOffset;
  4174. var trackLength = scrollbarVarsInfo._trackLength;
  4175. var handleLength = scrollbarVarsInfo._handleLength;
  4176. var scrollRange = scrollbarVarsInfo._maxScroll;
  4177. var currScroll = scrollbarVarsInfo._currentScroll;
  4178. var scrollDuration = scrollBaseDuration * scrollDurationFactor;
  4179. var timeoutDelay = isFirstIteration ? MATH.max(scrollFirstIterationDelay, scrollDuration) : scrollDuration;
  4180. var instantScrollPosition = scrollRange * ((mouseOffset - (handleLength / 2)) / (trackLength - handleLength)); // 100% * positionPercent
  4181. var rtlIsNormal = _isRTL && isHorizontal && ((!_rtlScrollBehavior.i && !_rtlScrollBehavior.n) || _normalizeRTLCache);
  4182. var decreaseScrollCondition = rtlIsNormal ? handleOffset < mouseOffset : handleOffset > mouseOffset;
  4183. var scrollObj = {};
  4184. var animationObj = {
  4185. easing: easing,
  4186. step: function (now) {
  4187. if (_scrollbarsHandlesDefineScrollPos) {
  4188. _viewportElement[scroll](now); //https://github.com/jquery/jquery/issues/4340
  4189. refreshScrollbarHandleOffset(isHorizontal, now);
  4190. }
  4191. }
  4192. };
  4193. instantScrollPosition = isFinite(instantScrollPosition) ? instantScrollPosition : 0;
  4194. instantScrollPosition = _isRTL && isHorizontal && !_rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition;
  4195. //_base.scrollStop();
  4196. if (instantScroll) {
  4197. _viewportElement[scroll](instantScrollPosition); //scroll instantly to new position
  4198. if (instantScrollTransition) {
  4199. //get the scroll position after instant scroll (in case CSS Snap Points are used) to get the correct snapped scroll position
  4200. //and the animation stops at the correct point
  4201. instantScrollPosition = _viewportElement[scroll]();
  4202. //scroll back to the position before instant scrolling so animation can be performed
  4203. _viewportElement[scroll](currScroll);
  4204. instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition;
  4205. instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.n ? -instantScrollPosition : instantScrollPosition;
  4206. scrollObj[xy] = instantScrollPosition;
  4207. _base.scroll(scrollObj, extendDeep(animationObj, {
  4208. duration: 130,
  4209. complete: scrollActionInstantFinished
  4210. }));
  4211. }
  4212. else
  4213. scrollActionInstantFinished();
  4214. }
  4215. else {
  4216. decreaseScroll = isFirstIteration ? decreaseScrollCondition : decreaseScroll;
  4217. finishedCondition = rtlIsNormal
  4218. ? (decreaseScroll ? handleOffset + handleLength >= mouseOffset : handleOffset <= mouseOffset)
  4219. : (decreaseScroll ? handleOffset <= mouseOffset : handleOffset + handleLength >= mouseOffset);
  4220. if (finishedCondition) {
  4221. clearTimeout(trackTimeout);
  4222. _base.scrollStop();
  4223. trackTimeout = undefined;
  4224. scrollActionFinsished(true);
  4225. }
  4226. else {
  4227. trackTimeout = setTimeout(scrollAction, timeoutDelay);
  4228. scrollObj[xy] = (decreaseScroll ? '-=' : '+=') + scrollDistance;
  4229. _base.scroll(scrollObj, extendDeep(animationObj, {
  4230. duration: scrollDuration
  4231. }));
  4232. }
  4233. isFirstIteration = false;
  4234. }
  4235. }
  4236. };
  4237. if (ctrlKey)
  4238. increaseTrackScrollAmount();
  4239. mouseDownInvertedScale = getHostElementInvertedScale()[xy];
  4240. mouseDownOffset = COMPATIBILITY.page(event)[xy];
  4241. _scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption(strSnapHandle);
  4242. addClass(_bodyElement, _classNameDragging);
  4243. addClass(scrollbarVars._track, strActive);
  4244. addClass(scrollbarVars._scrollbar, strActive);
  4245. setupResponsiveEventListener(_documentElement,
  4246. [_strMouseTouchUpEvent, _strKeyDownEvent, _strKeyUpEvent, _strSelectStartEvent],
  4247. [documentMouseTouchUp, documentKeyDown, documentKeyUp, documentOnSelectStart]);
  4248. scrollAction();
  4249. COMPATIBILITY.prvD(event);
  4250. COMPATIBILITY.stpP(event);
  4251. }
  4252. }
  4253. function onTrackMouseTouchEnter(event) {
  4254. //make sure both scrollbars will stay visible if one scrollbar is hovered if autoHide is "scroll" or "move".
  4255. _scrollbarsHandleHovered = true;
  4256. if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
  4257. refreshScrollbarsAutoHide(true);
  4258. }
  4259. function onTrackMouseTouchLeave(event) {
  4260. _scrollbarsHandleHovered = false;
  4261. if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
  4262. refreshScrollbarsAutoHide(false);
  4263. }
  4264. function onScrollbarMouseTouchDown(event) {
  4265. COMPATIBILITY.stpP(event);
  4266. }
  4267. addDestroyEventListener(scrollbarVars._handle,
  4268. _strMouseTouchDownEvent,
  4269. onHandleMouseTouchDown);
  4270. addDestroyEventListener(scrollbarVars._track,
  4271. [_strMouseTouchDownEvent, _strMouseEnter, _strMouseLeave],
  4272. [onTrackMouseTouchDown, onTrackMouseTouchEnter, onTrackMouseTouchLeave]);
  4273. addDestroyEventListener(scrollbarVars._scrollbar,
  4274. _strMouseTouchDownEvent,
  4275. onScrollbarMouseTouchDown);
  4276. if (_supportTransition) {
  4277. addDestroyEventListener(scrollbarVars._scrollbar, _strTransitionEndEvent, function (event) {
  4278. if (event.target !== scrollbarVars._scrollbar[0])
  4279. return;
  4280. refreshScrollbarHandleLength(isHorizontal);
  4281. refreshScrollbarHandleOffset(isHorizontal);
  4282. });
  4283. }
  4284. }
  4285. /**
  4286. * Shows or hides the given scrollbar and applied a class name which indicates if the scrollbar is scrollable or not.
  4287. * @param isHorizontal True if the horizontal scrollbar is the target, false if the vertical scrollbar is the target.
  4288. * @param shallBeVisible True if the scrollbar shall be shown, false if hidden.
  4289. * @param canScroll True if the scrollbar is scrollable, false otherwise.
  4290. */
  4291. function refreshScrollbarAppearance(isHorizontal, shallBeVisible, canScroll) {
  4292. var scrollbarHiddenClassName = isHorizontal ? _classNameHostScrollbarHorizontalHidden : _classNameHostScrollbarVerticalHidden;
  4293. var scrollbarElement = isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement;
  4294. addRemoveClass(_hostElement, scrollbarHiddenClassName, !shallBeVisible);
  4295. addRemoveClass(scrollbarElement, _classNameScrollbarUnusable, !canScroll);
  4296. }
  4297. /**
  4298. * Autoshows / autohides both scrollbars with.
  4299. * @param shallBeVisible True if the scrollbars shall be autoshown (only the case if they are hidden by a autohide), false if the shall be auto hidden.
  4300. * @param delayfree True if the scrollbars shall be hidden without a delay, false or undefined otherwise.
  4301. */
  4302. function refreshScrollbarsAutoHide(shallBeVisible, delayfree) {
  4303. clearTimeout(_scrollbarsAutoHideTimeoutId);
  4304. if (shallBeVisible) {
  4305. //if(_hasOverflowCache.x && _hideOverflowCache.xs)
  4306. removeClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden);
  4307. //if(_hasOverflowCache.y && _hideOverflowCache.ys)
  4308. removeClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden);
  4309. }
  4310. else {
  4311. var anyActive;
  4312. var strActive = 'active';
  4313. var hide = function () {
  4314. if (!_scrollbarsHandleHovered && !_destroyed) {
  4315. anyActive = _scrollbarHorizontalHandleElement.hasClass(strActive) || _scrollbarVerticalHandleElement.hasClass(strActive);
  4316. if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave))
  4317. addClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden);
  4318. if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave))
  4319. addClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden);
  4320. }
  4321. };
  4322. if (_scrollbarsAutoHideDelay > 0 && delayfree !== true)
  4323. _scrollbarsAutoHideTimeoutId = setTimeout(hide, _scrollbarsAutoHideDelay);
  4324. else
  4325. hide();
  4326. }
  4327. }
  4328. /**
  4329. * Refreshes the handle length of the given scrollbar.
  4330. * @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed.
  4331. */
  4332. function refreshScrollbarHandleLength(isHorizontal) {
  4333. var handleCSS = {};
  4334. var scrollbarVars = getScrollbarVars(isHorizontal);
  4335. var scrollbarVarsInfo = scrollbarVars._info;
  4336. var digit = 1000000;
  4337. //get and apply intended handle length
  4338. var handleRatio = MATH.min(1, _viewportSize[scrollbarVars._w_h] / _contentScrollSizeCache[scrollbarVars._w_h]);
  4339. handleCSS[scrollbarVars._width_height] = (MATH.floor(handleRatio * 100 * digit) / digit) + '%'; //the last * digit / digit is for flooring to the 4th digit
  4340. if (!nativeOverlayScrollbarsAreActive())
  4341. scrollbarVars._handle.css(handleCSS);
  4342. //measure the handle length to respect min & max length
  4343. scrollbarVarsInfo._handleLength = scrollbarVars._handle[0]['offset' + scrollbarVars._Width_Height];
  4344. scrollbarVarsInfo._handleLengthRatio = handleRatio;
  4345. }
  4346. /**
  4347. * Refreshes the handle offset of the given scrollbar.
  4348. * @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed.
  4349. * @param scrollOrTransition The scroll position of the given scrollbar axis to which the handle shall be moved or a boolean which indicates whether a transition shall be applied. If undefined or boolean if the current scroll-offset is taken. (if isHorizontal ? scrollLeft : scrollTop)
  4350. */
  4351. function refreshScrollbarHandleOffset(isHorizontal, scrollOrTransition) {
  4352. var transition = type(scrollOrTransition) == TYPES.b;
  4353. var transitionDuration = 250;
  4354. var isRTLisHorizontal = _isRTL && isHorizontal;
  4355. var scrollbarVars = getScrollbarVars(isHorizontal);
  4356. var scrollbarVarsInfo = scrollbarVars._info;
  4357. var strTranslateBrace = 'translate(';
  4358. var strTransform = VENDORS._cssProperty('transform');
  4359. var strTransition = VENDORS._cssProperty('transition');
  4360. var nativeScroll = isHorizontal ? _viewportElement[_strScrollLeft]() : _viewportElement[_strScrollTop]();
  4361. var currentScroll = scrollOrTransition === undefined || transition ? nativeScroll : scrollOrTransition;
  4362. //measure the handle length to respect min & max length
  4363. var handleLength = scrollbarVarsInfo._handleLength;
  4364. var trackLength = scrollbarVars._track[0]['offset' + scrollbarVars._Width_Height];
  4365. var handleTrackDiff = trackLength - handleLength;
  4366. var handleCSS = {};
  4367. var transformOffset;
  4368. var translateValue;
  4369. //DONT use the variable '_contentScrollSizeCache[scrollbarVars._w_h]' instead of '_viewportElement[0]['scroll' + scrollbarVars._Width_Height]'
  4370. // because its a bit behind during the small delay when content size updates
  4371. //(delay = mutationObserverContentLag, if its 0 then this var could be used)
  4372. var maxScroll = (_viewportElementNative[_strScroll + scrollbarVars._Width_Height] - _viewportElementNative['client' + scrollbarVars._Width_Height]) * (_rtlScrollBehavior.n && isRTLisHorizontal ? -1 : 1); //* -1 if rtl scroll max is negative
  4373. var getScrollRatio = function (base) {
  4374. return isNaN(base / maxScroll) ? 0 : MATH.max(0, MATH.min(1, base / maxScroll));
  4375. };
  4376. var getHandleOffset = function (scrollRatio) {
  4377. var offset = handleTrackDiff * scrollRatio;
  4378. offset = isNaN(offset) ? 0 : offset;
  4379. offset = (isRTLisHorizontal && !_rtlScrollBehavior.i) ? (trackLength - handleLength - offset) : offset;
  4380. offset = MATH.max(0, offset);
  4381. return offset;
  4382. };
  4383. var scrollRatio = getScrollRatio(nativeScroll);
  4384. var unsnappedScrollRatio = getScrollRatio(currentScroll);
  4385. var handleOffset = getHandleOffset(unsnappedScrollRatio);
  4386. var snappedHandleOffset = getHandleOffset(scrollRatio);
  4387. scrollbarVarsInfo._maxScroll = maxScroll;
  4388. scrollbarVarsInfo._currentScroll = nativeScroll;
  4389. scrollbarVarsInfo._currentScrollRatio = scrollRatio;
  4390. if (_supportTransform) {
  4391. transformOffset = isRTLisHorizontal ? -(trackLength - handleLength - handleOffset) : handleOffset; //in px
  4392. //transformOffset = (transformOffset / trackLength * 100) * (trackLength / handleLength); //in %
  4393. translateValue = isHorizontal ? strTranslateBrace + transformOffset + 'px, 0)' : strTranslateBrace + '0, ' + transformOffset + 'px)';
  4394. handleCSS[strTransform] = translateValue;
  4395. //apply or clear up transition
  4396. if (_supportTransition)
  4397. handleCSS[strTransition] = transition && MATH.abs(handleOffset - scrollbarVarsInfo._handleOffset) > 1 ? getCSSTransitionString(scrollbarVars._handle) + ', ' + (strTransform + _strSpace + transitionDuration + 'ms') : _strEmpty;
  4398. }
  4399. else
  4400. handleCSS[scrollbarVars._left_top] = handleOffset;
  4401. //only apply css if offset has changed and overflow exists.
  4402. if (!nativeOverlayScrollbarsAreActive()) {
  4403. scrollbarVars._handle.css(handleCSS);
  4404. //clear up transition
  4405. if (_supportTransform && _supportTransition && transition) {
  4406. scrollbarVars._handle.one(_strTransitionEndEvent, function () {
  4407. if (!_destroyed)
  4408. scrollbarVars._handle.css(strTransition, _strEmpty);
  4409. });
  4410. }
  4411. }
  4412. scrollbarVarsInfo._handleOffset = handleOffset;
  4413. scrollbarVarsInfo._snappedHandleOffset = snappedHandleOffset;
  4414. scrollbarVarsInfo._trackLength = trackLength;
  4415. }
  4416. /**
  4417. * Refreshes the interactivity of the given scrollbar element.
  4418. * @param isTrack True if the track element is the target, false if the handle element is the target.
  4419. * @param value True for interactivity false for no interactivity.
  4420. */
  4421. function refreshScrollbarsInteractive(isTrack, value) {
  4422. var action = value ? 'removeClass' : 'addClass';
  4423. var element1 = isTrack ? _scrollbarHorizontalTrackElement : _scrollbarHorizontalHandleElement;
  4424. var element2 = isTrack ? _scrollbarVerticalTrackElement : _scrollbarVerticalHandleElement;
  4425. var className = isTrack ? _classNameScrollbarTrackOff : _classNameScrollbarHandleOff;
  4426. element1[action](className);
  4427. element2[action](className);
  4428. }
  4429. /**
  4430. * Returns a object which is used for fast access for specific variables.
  4431. * @param isHorizontal True if the horizontal scrollbar vars shall be accessed, false if the vertical scrollbar vars shall be accessed.
  4432. * @returns {{wh: string, WH: string, lt: string, _wh: string, _lt: string, t: *, h: *, c: {}, s: *}}
  4433. */
  4434. function getScrollbarVars(isHorizontal) {
  4435. return {
  4436. _width_height: isHorizontal ? _strWidth : _strHeight,
  4437. _Width_Height: isHorizontal ? 'Width' : 'Height',
  4438. _left_top: isHorizontal ? _strLeft : _strTop,
  4439. _Left_Top: isHorizontal ? 'Left' : 'Top',
  4440. _x_y: isHorizontal ? _strX : _strY,
  4441. _X_Y: isHorizontal ? 'X' : 'Y',
  4442. _w_h: isHorizontal ? 'w' : 'h',
  4443. _l_t: isHorizontal ? 'l' : 't',
  4444. _track: isHorizontal ? _scrollbarHorizontalTrackElement : _scrollbarVerticalTrackElement,
  4445. _handle: isHorizontal ? _scrollbarHorizontalHandleElement : _scrollbarVerticalHandleElement,
  4446. _scrollbar: isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement,
  4447. _info: isHorizontal ? _scrollHorizontalInfo : _scrollVerticalInfo
  4448. };
  4449. }
  4450. //==== Scrollbar Corner ====//
  4451. /**
  4452. * Builds or destroys the scrollbar corner DOM element.
  4453. * @param destroy Indicates whether the DOM shall be build or destroyed.
  4454. */
  4455. function setupScrollbarCornerDOM(destroy) {
  4456. _scrollbarCornerElement = _scrollbarCornerElement || selectOrGenerateDivByClass(_classNameScrollbarCorner, true);
  4457. if (!destroy) {
  4458. if (!_domExists) {
  4459. _hostElement.append(_scrollbarCornerElement);
  4460. }
  4461. }
  4462. else {
  4463. if (_domExists && _initialized) {
  4464. removeClass(_scrollbarCornerElement.removeAttr(LEXICON.s), _classNamesDynamicDestroy);
  4465. }
  4466. else {
  4467. remove(_scrollbarCornerElement);
  4468. }
  4469. }
  4470. }
  4471. /**
  4472. * Initializes all scrollbar corner interactivity events.
  4473. */
  4474. function setupScrollbarCornerEvents() {
  4475. var insideIFrame = _windowElementNative.top !== _windowElementNative;
  4476. var mouseDownPosition = {};
  4477. var mouseDownSize = {};
  4478. var mouseDownInvertedScale = {};
  4479. var reconnectMutationObserver;
  4480. function documentDragMove(event) {
  4481. if (onMouseTouchDownContinue(event)) {
  4482. var pageOffset = getCoordinates(event);
  4483. var hostElementCSS = {};
  4484. if (_resizeHorizontal || _resizeBoth)
  4485. hostElementCSS[_strWidth] = (mouseDownSize.w + (pageOffset.x - mouseDownPosition.x) * mouseDownInvertedScale.x);
  4486. if (_resizeVertical || _resizeBoth)
  4487. hostElementCSS[_strHeight] = (mouseDownSize.h + (pageOffset.y - mouseDownPosition.y) * mouseDownInvertedScale.y);
  4488. _hostElement.css(hostElementCSS);
  4489. COMPATIBILITY.stpP(event);
  4490. }
  4491. else {
  4492. documentMouseTouchUp(event);
  4493. }
  4494. }
  4495. function documentMouseTouchUp(event) {
  4496. var eventIsTrusted = event !== undefined;
  4497. setupResponsiveEventListener(_documentElement,
  4498. [_strSelectStartEvent, _strMouseTouchMoveEvent, _strMouseTouchUpEvent],
  4499. [documentOnSelectStart, documentDragMove, documentMouseTouchUp],
  4500. true);
  4501. removeClass(_bodyElement, _classNameDragging);
  4502. if (_scrollbarCornerElement.releaseCapture)
  4503. _scrollbarCornerElement.releaseCapture();
  4504. if (eventIsTrusted) {
  4505. if (reconnectMutationObserver)
  4506. connectMutationObservers();
  4507. _base.update(_strAuto);
  4508. }
  4509. reconnectMutationObserver = false;
  4510. }
  4511. function onMouseTouchDownContinue(event) {
  4512. var originalEvent = event.originalEvent || event;
  4513. var isTouchEvent = originalEvent.touches !== undefined;
  4514. return _sleeping || _destroyed ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;
  4515. }
  4516. function getCoordinates(event) {
  4517. return _msieVersion && insideIFrame ? { x: event.screenX, y: event.screenY } : COMPATIBILITY.page(event);
  4518. }
  4519. addDestroyEventListener(_scrollbarCornerElement, _strMouseTouchDownEvent, function (event) {
  4520. if (onMouseTouchDownContinue(event) && !_resizeNone) {
  4521. if (_mutationObserversConnected) {
  4522. reconnectMutationObserver = true;
  4523. disconnectMutationObservers();
  4524. }
  4525. mouseDownPosition = getCoordinates(event);
  4526. mouseDownSize.w = _hostElementNative[LEXICON.oW] - (!_isBorderBox ? _paddingX : 0);
  4527. mouseDownSize.h = _hostElementNative[LEXICON.oH] - (!_isBorderBox ? _paddingY : 0);
  4528. mouseDownInvertedScale = getHostElementInvertedScale();
  4529. setupResponsiveEventListener(_documentElement,
  4530. [_strSelectStartEvent, _strMouseTouchMoveEvent, _strMouseTouchUpEvent],
  4531. [documentOnSelectStart, documentDragMove, documentMouseTouchUp]);
  4532. addClass(_bodyElement, _classNameDragging);
  4533. if (_scrollbarCornerElement.setCapture)
  4534. _scrollbarCornerElement.setCapture();
  4535. COMPATIBILITY.prvD(event);
  4536. COMPATIBILITY.stpP(event);
  4537. }
  4538. });
  4539. }
  4540. //==== Utils ====//
  4541. /**
  4542. * Calls the callback with the given name. The Context of this callback is always _base (this).
  4543. * @param name The name of the target which shall be called.
  4544. * @param args The args with which the callback shall be called.
  4545. * @param dependent Boolean which decides whether the callback shall be fired, undefined is like a "true" value.
  4546. */
  4547. function dispatchCallback(name, args, dependent) {
  4548. if (dependent === false)
  4549. return;
  4550. if (_initialized) {
  4551. var callback = _currentPreparedOptions.callbacks[name];
  4552. var extensionOnName = name;
  4553. var ext;
  4554. if (extensionOnName.substr(0, 2) === 'on')
  4555. extensionOnName = extensionOnName.substr(2, 1).toLowerCase() + extensionOnName.substr(3);
  4556. if (type(callback) == TYPES.f)
  4557. callback.call(_base, args);
  4558. each(_extensions, function () {
  4559. ext = this;
  4560. if (type(ext.on) == TYPES.f)
  4561. ext.on(extensionOnName, args);
  4562. });
  4563. }
  4564. else if (!_destroyed)
  4565. _callbacksInitQeueue.push({ n: name, a: args });
  4566. }
  4567. /**
  4568. * Sets the "top, right, bottom, left" properties, with a given prefix, of the given css object.
  4569. * @param targetCSSObject The css object to which the values shall be applied.
  4570. * @param prefix The prefix of the "top, right, bottom, left" css properties. (example: 'padding-' is a valid prefix)
  4571. * @param values A array of values which shall be applied to the "top, right, bottom, left" -properties. The array order is [top, right, bottom, left].
  4572. * If this argument is undefined the value '' (empty string) will be applied to all properties.
  4573. */
  4574. function setTopRightBottomLeft(targetCSSObject, prefix, values) {
  4575. prefix = prefix || _strEmpty;
  4576. values = values || [_strEmpty, _strEmpty, _strEmpty, _strEmpty];
  4577. targetCSSObject[prefix + _strTop] = values[0];
  4578. targetCSSObject[prefix + _strRight] = values[1];
  4579. targetCSSObject[prefix + _strBottom] = values[2];
  4580. targetCSSObject[prefix + _strLeft] = values[3];
  4581. }
  4582. /**
  4583. * Gets the "top, right, bottom, left" CSS properties of the CSS property with the given prefix from the host element.
  4584. * @param prefix The prefix of the "top, right, bottom, left" css properties. (example: 'padding-' is a valid prefix)
  4585. * @param suffix The suffix of the "top, right, bottom, left" css properties. (example: 'border-' is a valid prefix with '-width' is a valid suffix)
  4586. * @param zeroX True if the x axis shall be 0.
  4587. * @param zeroY True if the y axis shall be 0.
  4588. * @returns {{}} The object which contains the numbers of the read CSS properties.
  4589. */
  4590. function getTopRightBottomLeftHost(prefix, suffix, zeroX, zeroY) {
  4591. suffix = suffix || _strEmpty;
  4592. prefix = prefix || _strEmpty;
  4593. return {
  4594. t: zeroY ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strTop + suffix)),
  4595. r: zeroX ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strRight + suffix)),
  4596. b: zeroY ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strBottom + suffix)),
  4597. l: zeroX ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strLeft + suffix))
  4598. };
  4599. }
  4600. /**
  4601. * Returns the computed CSS transition string from the given element.
  4602. * @param element The element from which the transition string shall be returned.
  4603. * @returns {string} The CSS transition string from the given element.
  4604. */
  4605. function getCSSTransitionString(element) {
  4606. var transitionStr = VENDORS._cssProperty('transition');
  4607. var assembledValue = element.css(transitionStr);
  4608. if (assembledValue)
  4609. return assembledValue;
  4610. var regExpString = '\\s*(' + '([^,(]+(\\(.+?\\))?)+' + ')[\\s,]*';
  4611. var regExpMain = new RegExp(regExpString);
  4612. var regExpValidate = new RegExp('^(' + regExpString + ')+$');
  4613. var properties = 'property duration timing-function delay'.split(' ');
  4614. var result = [];
  4615. var strResult;
  4616. var valueArray;
  4617. var i = 0;
  4618. var j;
  4619. var splitCssStyleByComma = function (str) {
  4620. strResult = [];
  4621. if (!str.match(regExpValidate))
  4622. return str;
  4623. while (str.match(regExpMain)) {
  4624. strResult.push(RegExp.$1);
  4625. str = str.replace(regExpMain, _strEmpty);
  4626. }
  4627. return strResult;
  4628. };
  4629. for (; i < properties[LEXICON.l]; i++) {
  4630. valueArray = splitCssStyleByComma(element.css(transitionStr + '-' + properties[i]));
  4631. for (j = 0; j < valueArray[LEXICON.l]; j++)
  4632. result[j] = (result[j] ? result[j] + _strSpace : _strEmpty) + valueArray[j];
  4633. }
  4634. return result.join(', ');
  4635. }
  4636. /**
  4637. * Generates a Regular Expression which matches with a string which starts with 'os-host'.
  4638. * @param {boolean} withCurrClassNameOption The Regular Expression also matches if the string is the current ClassName option (multiple values splitted by space possible).
  4639. * @param {boolean} withOldClassNameOption The Regular Expression also matches if the string is the old ClassName option (multiple values splitted by space possible).
  4640. */
  4641. function createHostClassNameRegExp(withCurrClassNameOption, withOldClassNameOption) {
  4642. var i;
  4643. var split;
  4644. var appendix;
  4645. var appendClasses = function (classes, condition) {
  4646. appendix = '';
  4647. if (condition && typeof classes == TYPES.s) {
  4648. split = classes.split(_strSpace);
  4649. for (i = 0; i < split[LEXICON.l]; i++)
  4650. appendix += '|' + split[i] + '$';
  4651. // split[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&') for escaping regex characters
  4652. }
  4653. return appendix;
  4654. };
  4655. return new RegExp(
  4656. '(^' + _classNameHostElement + '([-_].+|)$)' +
  4657. appendClasses(_classNameCache, withCurrClassNameOption) +
  4658. appendClasses(_oldClassName, withOldClassNameOption), 'g');
  4659. }
  4660. /**
  4661. * Calculates the host-elements inverted scale. (invertedScale = 1 / scale)
  4662. * @returns {{x: number, y: number}} The scale of the host-element.
  4663. */
  4664. function getHostElementInvertedScale() {
  4665. var rect = _paddingElementNative[LEXICON.bCR]();
  4666. return {
  4667. x: _supportTransform ? 1 / (MATH.round(rect.width) / _paddingElementNative[LEXICON.oW]) || 1 : 1,
  4668. y: _supportTransform ? 1 / (MATH.round(rect.height) / _paddingElementNative[LEXICON.oH]) || 1 : 1
  4669. };
  4670. }
  4671. /**
  4672. * Checks whether the given object is a HTMLElement.
  4673. * @param o The object which shall be checked.
  4674. * @returns {boolean} True the given object is a HTMLElement, false otherwise.
  4675. */
  4676. function isHTMLElement(o) {
  4677. var strOwnerDocument = 'ownerDocument';
  4678. var strHTMLElement = 'HTMLElement';
  4679. var wnd = o && o[strOwnerDocument] ? (o[strOwnerDocument].parentWindow || window) : window;
  4680. return (
  4681. typeof wnd[strHTMLElement] == TYPES.o ? o instanceof wnd[strHTMLElement] : //DOM2
  4682. o && typeof o == TYPES.o && o !== null && o.nodeType === 1 && typeof o.nodeName == TYPES.s
  4683. );
  4684. }
  4685. /**
  4686. * Compares 2 arrays and returns the differences between them as a array.
  4687. * @param a1 The first array which shall be compared.
  4688. * @param a2 The second array which shall be compared.
  4689. * @returns {Array} The differences between the two arrays.
  4690. */
  4691. function getArrayDifferences(a1, a2) {
  4692. var a = [];
  4693. var diff = [];
  4694. var i;
  4695. var k;
  4696. for (i = 0; i < a1.length; i++)
  4697. a[a1[i]] = true;
  4698. for (i = 0; i < a2.length; i++) {
  4699. if (a[a2[i]])
  4700. delete a[a2[i]];
  4701. else
  4702. a[a2[i]] = true;
  4703. }
  4704. for (k in a)
  4705. diff.push(k);
  4706. return diff;
  4707. }
  4708. /**
  4709. * Returns Zero or the number to which the value can be parsed.
  4710. * @param value The value which shall be parsed.
  4711. * @param toFloat Indicates whether the number shall be parsed to a float.
  4712. */
  4713. function parseToZeroOrNumber(value, toFloat) {
  4714. var num = toFloat ? parseFloat(value) : parseInt(value, 10);
  4715. return isNaN(num) ? 0 : num;
  4716. }
  4717. /**
  4718. * Gets several information of the textarea and returns them as a object or undefined if the browser doesn't support it.
  4719. * @returns {{cursorRow: Number, cursorCol, rows: Number, cols: number, wRow: number, pos: number, max : number}} or undefined if not supported.
  4720. */
  4721. function getTextareaInfo() {
  4722. //read needed values
  4723. var textareaCursorPosition = _targetElementNative.selectionStart;
  4724. if (textareaCursorPosition === undefined)
  4725. return;
  4726. var textareaValue = _targetElement.val();
  4727. var textareaLength = textareaValue[LEXICON.l];
  4728. var textareaRowSplit = textareaValue.split('\n');
  4729. var textareaLastRow = textareaRowSplit[LEXICON.l];
  4730. var textareaCurrentCursorRowSplit = textareaValue.substr(0, textareaCursorPosition).split('\n');
  4731. var widestRow = 0;
  4732. var textareaLastCol = 0;
  4733. var cursorRow = textareaCurrentCursorRowSplit[LEXICON.l];
  4734. var cursorCol = textareaCurrentCursorRowSplit[textareaCurrentCursorRowSplit[LEXICON.l] - 1][LEXICON.l];
  4735. var rowCols;
  4736. var i;
  4737. //get widest Row and the last column of the textarea
  4738. for (i = 0; i < textareaRowSplit[LEXICON.l]; i++) {
  4739. rowCols = textareaRowSplit[i][LEXICON.l];
  4740. if (rowCols > textareaLastCol) {
  4741. widestRow = i + 1;
  4742. textareaLastCol = rowCols;
  4743. }
  4744. }
  4745. return {
  4746. _cursorRow: cursorRow, //cursorRow
  4747. _cursorColumn: cursorCol, //cursorCol
  4748. _rows: textareaLastRow, //rows
  4749. _columns: textareaLastCol, //cols
  4750. _widestRow: widestRow, //wRow
  4751. _cursorPosition: textareaCursorPosition, //pos
  4752. _cursorMax: textareaLength //max
  4753. };
  4754. }
  4755. /**
  4756. * Determines whether native overlay scrollbars are active.
  4757. * @returns {boolean} True if native overlay scrollbars are active, false otherwise.
  4758. */
  4759. function nativeOverlayScrollbarsAreActive() {
  4760. return (_ignoreOverlayScrollbarHidingCache && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y));
  4761. }
  4762. /**
  4763. * Gets the element which is used to measure the content size.
  4764. * @returns {*} TextareaCover if target element is textarea else the ContentElement.
  4765. */
  4766. function getContentMeasureElement() {
  4767. return _isTextarea ? _textareaCoverElement[0] : _contentElementNative;
  4768. }
  4769. /**
  4770. * Generates a string which represents a HTML div with the given classes or attributes.
  4771. * @param classesOrAttrs The class of the div as string or a object which represents the attributes of the div. (The class attribute can also be written as "className".)
  4772. * @param content The content of the div as string.
  4773. * @returns {string} The concated string which represents a HTML div and its content.
  4774. */
  4775. function generateDiv(classesOrAttrs, content) {
  4776. return '<div ' + (classesOrAttrs ? type(classesOrAttrs) == TYPES.s ?
  4777. 'class="' + classesOrAttrs + '"' :
  4778. (function () {
  4779. var key;
  4780. var attrs = _strEmpty;
  4781. if (FRAMEWORK.isPlainObject(classesOrAttrs)) {
  4782. for (key in classesOrAttrs)
  4783. attrs += (key === 'c' ? 'class' : key) + '="' + classesOrAttrs[key] + '" ';
  4784. }
  4785. return attrs;
  4786. })() :
  4787. _strEmpty) +
  4788. '>' +
  4789. (content || _strEmpty) +
  4790. '</div>';
  4791. }
  4792. /**
  4793. * Selects or generates a div with the given class attribute.
  4794. * @param className The class names (divided by spaces) of the div which shall be selected or generated.
  4795. * @param selectParentOrOnlyChildren The parent element from which of the element shall be selected. (if undefined or boolean its hostElement)
  4796. * If its a boolean it decides whether only the children of the host element shall be selected.
  4797. * @returns {*} The generated or selected element.
  4798. */
  4799. function selectOrGenerateDivByClass(className, selectParentOrOnlyChildren) {
  4800. var onlyChildren = type(selectParentOrOnlyChildren) == TYPES.b;
  4801. var selectParent = onlyChildren ? _hostElement : (selectParentOrOnlyChildren || _hostElement);
  4802. return (_domExists && !selectParent[LEXICON.l])
  4803. ? null
  4804. : _domExists
  4805. ? selectParent[onlyChildren ? 'children' : 'find'](_strDot + className.replace(/\s/g, _strDot)).eq(0)
  4806. : FRAMEWORK(generateDiv(className))
  4807. }
  4808. /**
  4809. * Gets the value of the given property from the given object.
  4810. * @param obj The object from which the property value shall be got.
  4811. * @param path The property of which the value shall be got.
  4812. * @returns {*} Returns the value of the searched property or undefined of the property wasn't found.
  4813. */
  4814. function getObjectPropVal(obj, path) {
  4815. var splits = path.split(_strDot);
  4816. var i = 0;
  4817. var val;
  4818. for (; i < splits.length; i++) {
  4819. if (!obj[LEXICON.hOP](splits[i]))
  4820. return;
  4821. val = obj[splits[i]];
  4822. if (i < splits.length && type(val) == TYPES.o)
  4823. obj = val;
  4824. }
  4825. return val;
  4826. }
  4827. /**
  4828. * Sets the value of the given property from the given object.
  4829. * @param obj The object from which the property value shall be set.
  4830. * @param path The property of which the value shall be set.
  4831. * @param val The value of the property which shall be set.
  4832. */
  4833. function setObjectPropVal(obj, path, val) {
  4834. var splits = path.split(_strDot);
  4835. var splitsLength = splits.length;
  4836. var i = 0;
  4837. var extendObj = {};
  4838. var extendObjRoot = extendObj;
  4839. for (; i < splitsLength; i++)
  4840. extendObj = extendObj[splits[i]] = i + 1 < splitsLength ? {} : val;
  4841. FRAMEWORK.extend(obj, extendObjRoot, true);
  4842. }
  4843. /**
  4844. * Runs a action for each selector inside the updateOnLoad option.
  4845. * @param {Function} action The action for each updateOnLoad selector, the arguments the function takes is the index and the value (the selector).
  4846. */
  4847. function eachUpdateOnLoad(action) {
  4848. var updateOnLoad = _currentPreparedOptions.updateOnLoad;
  4849. updateOnLoad = type(updateOnLoad) == TYPES.s ? updateOnLoad.split(_strSpace) : updateOnLoad;
  4850. if (COMPATIBILITY.isA(updateOnLoad) && !_destroyed) {
  4851. each(updateOnLoad, action);
  4852. }
  4853. }
  4854. //==== Utils Cache ====//
  4855. /**
  4856. * Compares two values or objects and returns true if they aren't equal.
  4857. * @param current The first value or object which shall be compared.
  4858. * @param cache The second value or object which shall be compared.
  4859. * @param force If true the returned value is always true.
  4860. * @returns {boolean} True if both values or objects aren't equal or force is true, false otherwise.
  4861. */
  4862. function checkCache(current, cache, force) {
  4863. if (force)
  4864. return force;
  4865. if (type(current) == TYPES.o && type(cache) == TYPES.o) {
  4866. for (var prop in current) {
  4867. if (prop !== 'c') {
  4868. if (current[LEXICON.hOP](prop) && cache[LEXICON.hOP](prop)) {
  4869. if (checkCache(current[prop], cache[prop]))
  4870. return true;
  4871. }
  4872. else {
  4873. return true;
  4874. }
  4875. }
  4876. }
  4877. }
  4878. else {
  4879. return current !== cache;
  4880. }
  4881. return false;
  4882. }
  4883. //==== Shortcuts ====//
  4884. /**
  4885. * jQuery extend method shortcut with a appended "true" as first argument.
  4886. */
  4887. function extendDeep() {
  4888. return FRAMEWORK.extend.apply(this, [true].concat([].slice.call(arguments)));
  4889. }
  4890. /**
  4891. * jQuery addClass method shortcut.
  4892. */
  4893. function addClass(el, classes) {
  4894. return _frameworkProto.addClass.call(el, classes);
  4895. }
  4896. /**
  4897. * jQuery removeClass method shortcut.
  4898. */
  4899. function removeClass(el, classes) {
  4900. return _frameworkProto.removeClass.call(el, classes);
  4901. }
  4902. /**
  4903. * Adds or removes the given classes dependent on the boolean value. True for add, false for remove.
  4904. */
  4905. function addRemoveClass(el, classes, doAdd) {
  4906. return doAdd ? addClass(el, classes) : removeClass(el, classes);
  4907. }
  4908. /**
  4909. * jQuery remove method shortcut.
  4910. */
  4911. function remove(el) {
  4912. return _frameworkProto.remove.call(el);
  4913. }
  4914. /**
  4915. * Finds the first child element with the given selector of the given element.
  4916. * @param el The root element from which the selector shall be valid.
  4917. * @param selector The selector of the searched element.
  4918. * @returns {*} The first element which is a child of the given element and matches the givens selector.
  4919. */
  4920. function findFirst(el, selector) {
  4921. return _frameworkProto.find.call(el, selector).eq(0);
  4922. }
  4923. //==== API ====//
  4924. /**
  4925. * Puts the instance to sleep. It wont respond to any changes in the DOM and won't update. Scrollbar Interactivity is also disabled as well as the resize handle.
  4926. * This behavior can be reset by calling the update method.
  4927. */
  4928. _base.sleep = function () {
  4929. _sleeping = true;
  4930. };
  4931. /**
  4932. * Updates the plugin and DOM to the current options.
  4933. * This method should only be called if a update is 100% required.
  4934. * @param force True if every property shall be updated and the cache shall be ignored.
  4935. * !INTERNAL USAGE! : force can be a string "auto", "sync" or "zoom" too
  4936. * if "auto" then before a real update the content size and host element attributes gets checked, and if they changed only then the update method will be called.
  4937. * if "sync" then the async update process (MutationObserver or UpdateLoop) gets synchronized and a corresponding update takes place if one was needed due to pending changes.
  4938. * if "zoom" then a update takes place where it's assumed that content and host size changed
  4939. * @returns {boolean|undefined}
  4940. * If force is "sync" then a boolean is returned which indicates whether a update was needed due to pending changes.
  4941. * If force is "auto" then a boolean is returned whether a update was needed due to attribute or size changes.
  4942. * undefined otherwise.
  4943. */
  4944. _base.update = function (force) {
  4945. if (_destroyed)
  4946. return;
  4947. var attrsChanged;
  4948. var contentSizeC;
  4949. var isString = type(force) == TYPES.s;
  4950. var doUpdateAuto;
  4951. var mutHost;
  4952. var mutContent;
  4953. if (isString) {
  4954. if (force === _strAuto) {
  4955. attrsChanged = meaningfulAttrsChanged();
  4956. contentSizeC = updateAutoContentSizeChanged();
  4957. doUpdateAuto = attrsChanged || contentSizeC;
  4958. if (doUpdateAuto) {
  4959. update({
  4960. _contentSizeChanged: contentSizeC,
  4961. _changedOptions: _initialized ? undefined : _currentPreparedOptions
  4962. });
  4963. }
  4964. }
  4965. else if (force === _strSync) {
  4966. if (_mutationObserversConnected) {
  4967. mutHost = _mutationObserverHostCallback(_mutationObserverHost.takeRecords());
  4968. mutContent = _mutationObserverContentCallback(_mutationObserverContent.takeRecords());
  4969. }
  4970. else {
  4971. mutHost = _base.update(_strAuto);
  4972. }
  4973. }
  4974. else if (force === 'zoom') {
  4975. update({
  4976. _hostSizeChanged: true,
  4977. _contentSizeChanged: true
  4978. });
  4979. }
  4980. }
  4981. else {
  4982. force = _sleeping || force;
  4983. _sleeping = false;
  4984. if (!_base.update(_strSync) || force)
  4985. update({ _force: force });
  4986. }
  4987. updateElementsOnLoad();
  4988. return doUpdateAuto || mutHost || mutContent;
  4989. };
  4990. /**
  4991. Gets or sets the current options. The update method will be called automatically if new options were set.
  4992. * @param newOptions If new options are given, then the new options will be set, if new options aren't given (undefined or a not a plain object) then the current options will be returned.
  4993. * @param value If new options is a property path string, then this value will be used to set the option to which the property path string leads.
  4994. * @returns {*}
  4995. */
  4996. _base.options = function (newOptions, value) {
  4997. var option = {};
  4998. var changedOps;
  4999. //return current options if newOptions are undefined or empty
  5000. if (FRAMEWORK.isEmptyObject(newOptions) || !FRAMEWORK.isPlainObject(newOptions)) {
  5001. if (type(newOptions) == TYPES.s) {
  5002. if (arguments.length > 1) {
  5003. setObjectPropVal(option, newOptions, value);
  5004. changedOps = setOptions(option);
  5005. }
  5006. else
  5007. return getObjectPropVal(_currentOptions, newOptions);
  5008. }
  5009. else
  5010. return _currentOptions;
  5011. }
  5012. else {
  5013. changedOps = setOptions(newOptions);
  5014. }
  5015. if (!FRAMEWORK.isEmptyObject(changedOps)) {
  5016. update({ _changedOptions: changedOps });
  5017. }
  5018. };
  5019. /**
  5020. * Restore the DOM, disconnects all observers, remove all resize observers and put the instance to sleep.
  5021. */
  5022. _base.destroy = function () {
  5023. if (_destroyed)
  5024. return;
  5025. //remove this instance from auto update loop
  5026. autoUpdateLoop.remove(_base);
  5027. //disconnect all mutation observers
  5028. disconnectMutationObservers();
  5029. //remove all resize observers
  5030. setupResizeObserver(_sizeObserverElement);
  5031. setupResizeObserver(_sizeAutoObserverElement);
  5032. //remove all extensions
  5033. for (var extName in _extensions)
  5034. _base.removeExt(extName);
  5035. //remove all 'destroy' events
  5036. while (_destroyEvents[LEXICON.l] > 0)
  5037. _destroyEvents.pop()();
  5038. //remove all events from host element
  5039. setupHostMouseTouchEvents(true);
  5040. //remove all helper / detection elements
  5041. if (_contentGlueElement)
  5042. remove(_contentGlueElement);
  5043. if (_contentArrangeElement)
  5044. remove(_contentArrangeElement);
  5045. if (_sizeAutoObserverAdded)
  5046. remove(_sizeAutoObserverElement);
  5047. //remove all generated DOM
  5048. setupScrollbarsDOM(true);
  5049. setupScrollbarCornerDOM(true);
  5050. setupStructureDOM(true);
  5051. //remove all generated image load events
  5052. for (var i = 0; i < _updateOnLoadElms[LEXICON.l]; i++)
  5053. FRAMEWORK(_updateOnLoadElms[i]).off(_updateOnLoadEventName, updateOnLoadCallback);
  5054. _updateOnLoadElms = undefined;
  5055. _destroyed = true;
  5056. _sleeping = true;
  5057. //remove this instance from the instances list
  5058. INSTANCES(pluginTargetElement, 0);
  5059. dispatchCallback('onDestroyed');
  5060. //remove all properties and methods
  5061. //for (var property in _base)
  5062. // delete _base[property];
  5063. //_base = undefined;
  5064. };
  5065. /**
  5066. * Scrolls to a given position or element.
  5067. * @param coordinates
  5068. * 1. Can be "coordinates" which looks like:
  5069. * { x : ?, y : ? } OR Object with x and y properties
  5070. * { left : ?, top : ? } OR Object with left and top properties
  5071. * { l : ?, t : ? } OR Object with l and t properties
  5072. * [ ?, ? ] OR Array where the first two element are the coordinates (first is x, second is y)
  5073. * ? A single value which stays for both axis
  5074. * A value can be a number, a string or a calculation.
  5075. *
  5076. * Operators:
  5077. * [NONE] The current scroll will be overwritten by the value.
  5078. * '+=' The value will be added to the current scroll offset
  5079. * '-=' The value will be subtracted from the current scroll offset
  5080. * '*=' The current scroll wil be multiplicated by the value.
  5081. * '/=' The current scroll wil be divided by the value.
  5082. *
  5083. * Units:
  5084. * [NONE] The value is the final scroll amount. final = (value * 1)
  5085. * 'px' Same as none
  5086. * '%' The value is dependent on the current scroll value. final = ((currentScrollValue / 100) * value)
  5087. * 'vw' The value is multiplicated by the viewport width. final = (value * viewportWidth)
  5088. * 'vh' The value is multiplicated by the viewport height. final = (value * viewportHeight)
  5089. *
  5090. * example final values:
  5091. * 200, '200px', '50%', '1vw', '1vh', '+=200', '/=1vw', '*=2px', '-=5vh', '+=33%', '+= 50% - 2px', '-= 1vw - 50%'
  5092. *
  5093. * 2. Can be a HTML or jQuery element:
  5094. * The final scroll offset is the offset (without margin) of the given HTML / jQuery element.
  5095. *
  5096. * 3. Can be a object with a HTML or jQuery element with additional settings:
  5097. * {
  5098. * el : [HTMLElement, jQuery element], MUST be specified, else this object isn't valid.
  5099. * scroll : [string, array, object], Default value is 'always'.
  5100. * block : [string, array, object], Default value is 'begin'.
  5101. * margin : [number, boolean, array, object] Default value is false.
  5102. * }
  5103. *
  5104. * Possible scroll settings are:
  5105. * 'always' Scrolls always.
  5106. * 'ifneeded' Scrolls only if the element isnt fully in view.
  5107. * 'never' Scrolls never.
  5108. *
  5109. * Possible block settings are:
  5110. * 'begin' Both axis shall be docked to the "begin" edge. - The element will be docked to the top and left edge of the viewport.
  5111. * 'end' Both axis shall be docked to the "end" edge. - The element will be docked to the bottom and right edge of the viewport. (If direction is RTL to the bottom and left edge.)
  5112. * 'center' Both axis shall be docked to "center". - The element will be centered in the viewport.
  5113. * 'nearest' The element will be docked to the nearest edge(s).
  5114. *
  5115. * Possible margin settings are: -- The actual margin of the element wont be affect, this option affects only the final scroll offset.
  5116. * [BOOLEAN] If true the css margin of the element will be used, if false no margin will be used.
  5117. * [NUMBER] The margin will be used for all edges.
  5118. *
  5119. * @param duration The duration of the scroll animation, OR a jQuery animation configuration object.
  5120. * @param easing The animation easing.
  5121. * @param complete The animation complete callback.
  5122. * @returns {{
  5123. * position: {x: number, y: number},
  5124. * ratio: {x: number, y: number},
  5125. * max: {x: number, y: number},
  5126. * handleOffset: {x: number, y: number},
  5127. * handleLength: {x: number, y: number},
  5128. * handleLengthRatio: {x: number, y: number}, t
  5129. * rackLength: {x: number, y: number},
  5130. * isRTL: boolean,
  5131. * isRTLNormalized: boolean
  5132. * }}
  5133. */
  5134. _base.scroll = function (coordinates, duration, easing, complete) {
  5135. if (arguments.length === 0 || coordinates === undefined) {
  5136. var infoX = _scrollHorizontalInfo;
  5137. var infoY = _scrollVerticalInfo;
  5138. var normalizeInvert = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.i;
  5139. var normalizeNegate = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.n;
  5140. var scrollX = infoX._currentScroll;
  5141. var scrollXRatio = infoX._currentScrollRatio;
  5142. var maxScrollX = infoX._maxScroll;
  5143. scrollXRatio = normalizeInvert ? 1 - scrollXRatio : scrollXRatio;
  5144. scrollX = normalizeInvert ? maxScrollX - scrollX : scrollX;
  5145. scrollX *= normalizeNegate ? -1 : 1;
  5146. maxScrollX *= normalizeNegate ? -1 : 1;
  5147. return {
  5148. position: {
  5149. x: scrollX,
  5150. y: infoY._currentScroll
  5151. },
  5152. ratio: {
  5153. x: scrollXRatio,
  5154. y: infoY._currentScrollRatio
  5155. },
  5156. max: {
  5157. x: maxScrollX,
  5158. y: infoY._maxScroll
  5159. },
  5160. handleOffset: {
  5161. x: infoX._handleOffset,
  5162. y: infoY._handleOffset
  5163. },
  5164. handleLength: {
  5165. x: infoX._handleLength,
  5166. y: infoY._handleLength
  5167. },
  5168. handleLengthRatio: {
  5169. x: infoX._handleLengthRatio,
  5170. y: infoY._handleLengthRatio
  5171. },
  5172. trackLength: {
  5173. x: infoX._trackLength,
  5174. y: infoY._trackLength
  5175. },
  5176. snappedHandleOffset: {
  5177. x: infoX._snappedHandleOffset,
  5178. y: infoY._snappedHandleOffset
  5179. },
  5180. isRTL: _isRTL,
  5181. isRTLNormalized: _normalizeRTLCache
  5182. };
  5183. }
  5184. _base.update(_strSync);
  5185. var normalizeRTL = _normalizeRTLCache;
  5186. var coordinatesXAxisProps = [_strX, _strLeft, 'l'];
  5187. var coordinatesYAxisProps = [_strY, _strTop, 't'];
  5188. var coordinatesOperators = ['+=', '-=', '*=', '/='];
  5189. var durationIsObject = type(duration) == TYPES.o;
  5190. var completeCallback = durationIsObject ? duration.complete : complete;
  5191. var i;
  5192. var finalScroll = {};
  5193. var specialEasing = {};
  5194. var doScrollLeft;
  5195. var doScrollTop;
  5196. var animationOptions;
  5197. var strEnd = 'end';
  5198. var strBegin = 'begin';
  5199. var strCenter = 'center';
  5200. var strNearest = 'nearest';
  5201. var strAlways = 'always';
  5202. var strNever = 'never';
  5203. var strIfNeeded = 'ifneeded';
  5204. var strLength = LEXICON.l;
  5205. var settingsAxis;
  5206. var settingsScroll;
  5207. var settingsBlock;
  5208. var settingsMargin;
  5209. var finalElement;
  5210. var elementObjSettingsAxisValues = [_strX, _strY, 'xy', 'yx'];
  5211. var elementObjSettingsBlockValues = [strBegin, strEnd, strCenter, strNearest];
  5212. var elementObjSettingsScrollValues = [strAlways, strNever, strIfNeeded];
  5213. var coordinatesIsElementObj = coordinates[LEXICON.hOP]('el');
  5214. var possibleElement = coordinatesIsElementObj ? coordinates.el : coordinates;
  5215. var possibleElementIsJQuery = possibleElement instanceof FRAMEWORK || JQUERY ? possibleElement instanceof JQUERY : false;
  5216. var possibleElementIsHTMLElement = possibleElementIsJQuery ? false : isHTMLElement(possibleElement);
  5217. var updateScrollbarInfos = function () {
  5218. if (doScrollLeft)
  5219. refreshScrollbarHandleOffset(true);
  5220. if (doScrollTop)
  5221. refreshScrollbarHandleOffset(false);
  5222. };
  5223. var proxyCompleteCallback = type(completeCallback) != TYPES.f ? undefined : function () {
  5224. updateScrollbarInfos();
  5225. completeCallback();
  5226. };
  5227. function checkSettingsStringValue(currValue, allowedValues) {
  5228. for (i = 0; i < allowedValues[strLength]; i++) {
  5229. if (currValue === allowedValues[i])
  5230. return true;
  5231. }
  5232. return false;
  5233. }
  5234. function getRawScroll(isX, coordinates) {
  5235. var coordinateProps = isX ? coordinatesXAxisProps : coordinatesYAxisProps;
  5236. coordinates = type(coordinates) == TYPES.s || type(coordinates) == TYPES.n ? [coordinates, coordinates] : coordinates;
  5237. if (COMPATIBILITY.isA(coordinates))
  5238. return isX ? coordinates[0] : coordinates[1];
  5239. else if (type(coordinates) == TYPES.o) {
  5240. //decides RTL normalization "hack" with .n
  5241. //normalizeRTL = type(coordinates.n) == TYPES.b ? coordinates.n : normalizeRTL;
  5242. for (i = 0; i < coordinateProps[strLength]; i++)
  5243. if (coordinateProps[i] in coordinates)
  5244. return coordinates[coordinateProps[i]];
  5245. }
  5246. }
  5247. function getFinalScroll(isX, rawScroll) {
  5248. var isString = type(rawScroll) == TYPES.s;
  5249. var operator;
  5250. var amount;
  5251. var scrollInfo = isX ? _scrollHorizontalInfo : _scrollVerticalInfo;
  5252. var currScroll = scrollInfo._currentScroll;
  5253. var maxScroll = scrollInfo._maxScroll;
  5254. var mult = ' * ';
  5255. var finalValue;
  5256. var isRTLisX = _isRTL && isX;
  5257. var normalizeShortcuts = isRTLisX && _rtlScrollBehavior.n && !normalizeRTL;
  5258. var strReplace = 'replace';
  5259. var evalFunc = eval;
  5260. var possibleOperator;
  5261. if (isString) {
  5262. //check operator
  5263. if (rawScroll[strLength] > 2) {
  5264. possibleOperator = rawScroll.substr(0, 2);
  5265. if (inArray(possibleOperator, coordinatesOperators) > -1)
  5266. operator = possibleOperator;
  5267. }
  5268. //calculate units and shortcuts
  5269. rawScroll = operator ? rawScroll.substr(2) : rawScroll;
  5270. rawScroll = rawScroll
  5271. [strReplace](/min/g, 0) //'min' = 0%
  5272. [strReplace](/</g, 0) //'<' = 0%
  5273. [strReplace](/max/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'max' = 100%
  5274. [strReplace](/>/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'>' = 100%
  5275. [strReplace](/px/g, _strEmpty)
  5276. [strReplace](/%/g, mult + (maxScroll * (isRTLisX && _rtlScrollBehavior.n ? -1 : 1) / 100.0))
  5277. [strReplace](/vw/g, mult + _viewportSize.w)
  5278. [strReplace](/vh/g, mult + _viewportSize.h);
  5279. amount = parseToZeroOrNumber(isNaN(rawScroll) ? parseToZeroOrNumber(evalFunc(rawScroll), true).toFixed() : rawScroll);
  5280. }
  5281. else {
  5282. amount = rawScroll;
  5283. }
  5284. if (amount !== undefined && !isNaN(amount) && type(amount) == TYPES.n) {
  5285. var normalizeIsRTLisX = normalizeRTL && isRTLisX;
  5286. var operatorCurrScroll = currScroll * (normalizeIsRTLisX && _rtlScrollBehavior.n ? -1 : 1);
  5287. var invert = normalizeIsRTLisX && _rtlScrollBehavior.i;
  5288. var negate = normalizeIsRTLisX && _rtlScrollBehavior.n;
  5289. operatorCurrScroll = invert ? (maxScroll - operatorCurrScroll) : operatorCurrScroll;
  5290. switch (operator) {
  5291. case '+=':
  5292. finalValue = operatorCurrScroll + amount;
  5293. break;
  5294. case '-=':
  5295. finalValue = operatorCurrScroll - amount;
  5296. break;
  5297. case '*=':
  5298. finalValue = operatorCurrScroll * amount;
  5299. break;
  5300. case '/=':
  5301. finalValue = operatorCurrScroll / amount;
  5302. break;
  5303. default:
  5304. finalValue = amount;
  5305. break;
  5306. }
  5307. finalValue = invert ? maxScroll - finalValue : finalValue;
  5308. finalValue *= negate ? -1 : 1;
  5309. finalValue = isRTLisX && _rtlScrollBehavior.n ? MATH.min(0, MATH.max(maxScroll, finalValue)) : MATH.max(0, MATH.min(maxScroll, finalValue));
  5310. }
  5311. return finalValue === currScroll ? undefined : finalValue;
  5312. }
  5313. function getPerAxisValue(value, valueInternalType, defaultValue, allowedValues) {
  5314. var resultDefault = [defaultValue, defaultValue];
  5315. var valueType = type(value);
  5316. var valueArrLength;
  5317. var valueArrItem;
  5318. //value can be [ string, or array of two strings ]
  5319. if (valueType == valueInternalType) {
  5320. value = [value, value];
  5321. }
  5322. else if (valueType == TYPES.a) {
  5323. valueArrLength = value[strLength];
  5324. if (valueArrLength > 2 || valueArrLength < 1)
  5325. value = resultDefault;
  5326. else {
  5327. if (valueArrLength === 1)
  5328. value[1] = defaultValue;
  5329. for (i = 0; i < valueArrLength; i++) {
  5330. valueArrItem = value[i];
  5331. if (type(valueArrItem) != valueInternalType || !checkSettingsStringValue(valueArrItem, allowedValues)) {
  5332. value = resultDefault;
  5333. break;
  5334. }
  5335. }
  5336. }
  5337. }
  5338. else if (valueType == TYPES.o)
  5339. value = [value[_strX] || defaultValue, value[_strY] || defaultValue];
  5340. else
  5341. value = resultDefault;
  5342. return { x: value[0], y: value[1] };
  5343. }
  5344. function generateMargin(marginTopRightBottomLeftArray) {
  5345. var result = [];
  5346. var currValue;
  5347. var currValueType;
  5348. var valueDirections = [_strTop, _strRight, _strBottom, _strLeft];
  5349. for (i = 0; i < marginTopRightBottomLeftArray[strLength]; i++) {
  5350. if (i === valueDirections[strLength])
  5351. break;
  5352. currValue = marginTopRightBottomLeftArray[i];
  5353. currValueType = type(currValue);
  5354. if (currValueType == TYPES.b)
  5355. result.push(currValue ? parseToZeroOrNumber(finalElement.css(_strMarginMinus + valueDirections[i])) : 0);
  5356. else
  5357. result.push(currValueType == TYPES.n ? currValue : 0);
  5358. }
  5359. return result;
  5360. }
  5361. if (possibleElementIsJQuery || possibleElementIsHTMLElement) {
  5362. //get settings
  5363. var margin = coordinatesIsElementObj ? coordinates.margin : 0;
  5364. var axis = coordinatesIsElementObj ? coordinates.axis : 0;
  5365. var scroll = coordinatesIsElementObj ? coordinates.scroll : 0;
  5366. var block = coordinatesIsElementObj ? coordinates.block : 0;
  5367. var marginDefault = [0, 0, 0, 0];
  5368. var marginType = type(margin);
  5369. var marginLength;
  5370. finalElement = possibleElementIsJQuery ? possibleElement : FRAMEWORK(possibleElement);
  5371. if (finalElement[strLength] > 0) {
  5372. //margin can be [ boolean, number, array of 2, array of 4, object ]
  5373. if (marginType == TYPES.n || marginType == TYPES.b)
  5374. margin = generateMargin([margin, margin, margin, margin]);
  5375. else if (marginType == TYPES.a) {
  5376. marginLength = margin[strLength];
  5377. if (marginLength === 2)
  5378. margin = generateMargin([margin[0], margin[1], margin[0], margin[1]]);
  5379. else if (marginLength >= 4)
  5380. margin = generateMargin(margin);
  5381. else
  5382. margin = marginDefault;
  5383. }
  5384. else if (marginType == TYPES.o)
  5385. margin = generateMargin([margin[_strTop], margin[_strRight], margin[_strBottom], margin[_strLeft]]);
  5386. else
  5387. margin = marginDefault;
  5388. //block = type(block) === TYPES.b ? block ? [ strNearest, strBegin ] : [ strNearest, strEnd ] : block;
  5389. settingsAxis = checkSettingsStringValue(axis, elementObjSettingsAxisValues) ? axis : 'xy';
  5390. settingsScroll = getPerAxisValue(scroll, TYPES.s, strAlways, elementObjSettingsScrollValues);
  5391. settingsBlock = getPerAxisValue(block, TYPES.s, strBegin, elementObjSettingsBlockValues);
  5392. settingsMargin = margin;
  5393. var viewportScroll = {
  5394. l: _scrollHorizontalInfo._currentScroll,
  5395. t: _scrollVerticalInfo._currentScroll
  5396. };
  5397. // use padding element instead of viewport element because padding element has never padding, margin or position applied.
  5398. var viewportOffset = _paddingElement.offset();
  5399. //get coordinates
  5400. var elementOffset = finalElement.offset();
  5401. var doNotScroll = {
  5402. x: settingsScroll.x == strNever || settingsAxis == _strY,
  5403. y: settingsScroll.y == strNever || settingsAxis == _strX
  5404. };
  5405. elementOffset[_strTop] -= settingsMargin[0];
  5406. elementOffset[_strLeft] -= settingsMargin[3];
  5407. var elementScrollCoordinates = {
  5408. x: MATH.round(elementOffset[_strLeft] - viewportOffset[_strLeft] + viewportScroll.l),
  5409. y: MATH.round(elementOffset[_strTop] - viewportOffset[_strTop] + viewportScroll.t)
  5410. };
  5411. if (_isRTL) {
  5412. if (!_rtlScrollBehavior.n && !_rtlScrollBehavior.i)
  5413. elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + viewportScroll.l);
  5414. if (_rtlScrollBehavior.n && normalizeRTL)
  5415. elementScrollCoordinates.x *= -1;
  5416. if (_rtlScrollBehavior.i && normalizeRTL)
  5417. elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + (_scrollHorizontalInfo._maxScroll - viewportScroll.l));
  5418. }
  5419. //measuring is required
  5420. if (settingsBlock.x != strBegin || settingsBlock.y != strBegin || settingsScroll.x == strIfNeeded || settingsScroll.y == strIfNeeded || _isRTL) {
  5421. var measuringElm = finalElement[0];
  5422. var rawElementSize = _supportTransform ? measuringElm[LEXICON.bCR]() : {
  5423. width: measuringElm[LEXICON.oW],
  5424. height: measuringElm[LEXICON.oH]
  5425. };
  5426. var elementSize = {
  5427. w: rawElementSize[_strWidth] + settingsMargin[3] + settingsMargin[1],
  5428. h: rawElementSize[_strHeight] + settingsMargin[0] + settingsMargin[2]
  5429. };
  5430. var finalizeBlock = function (isX) {
  5431. var vars = getScrollbarVars(isX);
  5432. var wh = vars._w_h;
  5433. var lt = vars._left_top;
  5434. var xy = vars._x_y;
  5435. var blockIsEnd = settingsBlock[xy] == (isX ? _isRTL ? strBegin : strEnd : strEnd);
  5436. var blockIsCenter = settingsBlock[xy] == strCenter;
  5437. var blockIsNearest = settingsBlock[xy] == strNearest;
  5438. var scrollNever = settingsScroll[xy] == strNever;
  5439. var scrollIfNeeded = settingsScroll[xy] == strIfNeeded;
  5440. var vpSize = _viewportSize[wh];
  5441. var vpOffset = viewportOffset[lt];
  5442. var elSize = elementSize[wh];
  5443. var elOffset = elementOffset[lt];
  5444. var divide = blockIsCenter ? 2 : 1;
  5445. var elementCenterOffset = elOffset + (elSize / 2);
  5446. var viewportCenterOffset = vpOffset + (vpSize / 2);
  5447. var isInView =
  5448. elSize <= vpSize
  5449. && elOffset >= vpOffset
  5450. && elOffset + elSize <= vpOffset + vpSize;
  5451. if (scrollNever)
  5452. doNotScroll[xy] = true;
  5453. else if (!doNotScroll[xy]) {
  5454. if (blockIsNearest || scrollIfNeeded) {
  5455. doNotScroll[xy] = scrollIfNeeded ? isInView : false;
  5456. blockIsEnd = elSize < vpSize ? elementCenterOffset > viewportCenterOffset : elementCenterOffset < viewportCenterOffset;
  5457. }
  5458. elementScrollCoordinates[xy] -= blockIsEnd || blockIsCenter ? ((vpSize / divide) - (elSize / divide)) * (isX && _isRTL && normalizeRTL ? -1 : 1) : 0;
  5459. }
  5460. };
  5461. finalizeBlock(true);
  5462. finalizeBlock(false);
  5463. }
  5464. if (doNotScroll.y)
  5465. delete elementScrollCoordinates.y;
  5466. if (doNotScroll.x)
  5467. delete elementScrollCoordinates.x;
  5468. coordinates = elementScrollCoordinates;
  5469. }
  5470. }
  5471. finalScroll[_strScrollLeft] = getFinalScroll(true, getRawScroll(true, coordinates));
  5472. finalScroll[_strScrollTop] = getFinalScroll(false, getRawScroll(false, coordinates));
  5473. doScrollLeft = finalScroll[_strScrollLeft] !== undefined;
  5474. doScrollTop = finalScroll[_strScrollTop] !== undefined;
  5475. if ((doScrollLeft || doScrollTop) && (duration > 0 || durationIsObject)) {
  5476. if (durationIsObject) {
  5477. duration.complete = proxyCompleteCallback;
  5478. _viewportElement.animate(finalScroll, duration);
  5479. }
  5480. else {
  5481. animationOptions = {
  5482. duration: duration,
  5483. complete: proxyCompleteCallback
  5484. };
  5485. if (COMPATIBILITY.isA(easing) || FRAMEWORK.isPlainObject(easing)) {
  5486. specialEasing[_strScrollLeft] = easing[0] || easing.x;
  5487. specialEasing[_strScrollTop] = easing[1] || easing.y;
  5488. animationOptions.specialEasing = specialEasing;
  5489. }
  5490. else {
  5491. animationOptions.easing = easing;
  5492. }
  5493. _viewportElement.animate(finalScroll, animationOptions);
  5494. }
  5495. }
  5496. else {
  5497. if (doScrollLeft)
  5498. _viewportElement[_strScrollLeft](finalScroll[_strScrollLeft]);
  5499. if (doScrollTop)
  5500. _viewportElement[_strScrollTop](finalScroll[_strScrollTop]);
  5501. updateScrollbarInfos();
  5502. }
  5503. };
  5504. /**
  5505. * Stops all scroll animations.
  5506. * @returns {*} The current OverlayScrollbars instance (for chaining).
  5507. */
  5508. _base.scrollStop = function (param1, param2, param3) {
  5509. _viewportElement.stop(param1, param2, param3);
  5510. return _base;
  5511. };
  5512. /**
  5513. * Returns all relevant elements.
  5514. * @param elementName The name of the element which shall be returned.
  5515. * @returns {{target: *, host: *, padding: *, viewport: *, content: *, scrollbarHorizontal: {scrollbar: *, track: *, handle: *}, scrollbarVertical: {scrollbar: *, track: *, handle: *}, scrollbarCorner: *} | *}
  5516. */
  5517. _base.getElements = function (elementName) {
  5518. var obj = {
  5519. target: _targetElementNative,
  5520. host: _hostElementNative,
  5521. padding: _paddingElementNative,
  5522. viewport: _viewportElementNative,
  5523. content: _contentElementNative,
  5524. scrollbarHorizontal: {
  5525. scrollbar: _scrollbarHorizontalElement[0],
  5526. track: _scrollbarHorizontalTrackElement[0],
  5527. handle: _scrollbarHorizontalHandleElement[0]
  5528. },
  5529. scrollbarVertical: {
  5530. scrollbar: _scrollbarVerticalElement[0],
  5531. track: _scrollbarVerticalTrackElement[0],
  5532. handle: _scrollbarVerticalHandleElement[0]
  5533. },
  5534. scrollbarCorner: _scrollbarCornerElement[0]
  5535. };
  5536. return type(elementName) == TYPES.s ? getObjectPropVal(obj, elementName) : obj;
  5537. };
  5538. /**
  5539. * Returns a object which describes the current state of this instance.
  5540. * @param stateProperty A specific property from the state object which shall be returned.
  5541. * @returns {{widthAuto, heightAuto, overflowAmount, hideOverflow, hasOverflow, contentScrollSize, viewportSize, hostSize, autoUpdate} | *}
  5542. */
  5543. _base.getState = function (stateProperty) {
  5544. function prepare(obj) {
  5545. if (!FRAMEWORK.isPlainObject(obj))
  5546. return obj;
  5547. var extended = extendDeep({}, obj);
  5548. var changePropertyName = function (from, to) {
  5549. if (extended[LEXICON.hOP](from)) {
  5550. extended[to] = extended[from];
  5551. delete extended[from];
  5552. }
  5553. };
  5554. changePropertyName('w', _strWidth); //change w to width
  5555. changePropertyName('h', _strHeight); //change h to height
  5556. delete extended.c; //delete c (the 'changed' prop)
  5557. return extended;
  5558. };
  5559. var obj = {
  5560. destroyed: !!prepare(_destroyed),
  5561. sleeping: !!prepare(_sleeping),
  5562. autoUpdate: prepare(!_mutationObserversConnected),
  5563. widthAuto: prepare(_widthAutoCache),
  5564. heightAuto: prepare(_heightAutoCache),
  5565. padding: prepare(_cssPaddingCache),
  5566. overflowAmount: prepare(_overflowAmountCache),
  5567. hideOverflow: prepare(_hideOverflowCache),
  5568. hasOverflow: prepare(_hasOverflowCache),
  5569. contentScrollSize: prepare(_contentScrollSizeCache),
  5570. viewportSize: prepare(_viewportSize),
  5571. hostSize: prepare(_hostSizeCache),
  5572. documentMixed: prepare(_documentMixed)
  5573. };
  5574. return type(stateProperty) == TYPES.s ? getObjectPropVal(obj, stateProperty) : obj;
  5575. };
  5576. /**
  5577. * Gets all or specific extension instance.
  5578. * @param extName The name of the extension from which the instance shall be got.
  5579. * @returns {{}} The instance of the extension with the given name or undefined if the instance couldn't be found.
  5580. */
  5581. _base.ext = function (extName) {
  5582. var result;
  5583. var privateMethods = _extensionsPrivateMethods.split(' ');
  5584. var i = 0;
  5585. if (type(extName) == TYPES.s) {
  5586. if (_extensions[LEXICON.hOP](extName)) {
  5587. result = extendDeep({}, _extensions[extName]);
  5588. for (; i < privateMethods.length; i++)
  5589. delete result[privateMethods[i]];
  5590. }
  5591. }
  5592. else {
  5593. result = {};
  5594. for (i in _extensions)
  5595. result[i] = extendDeep({}, _base.ext(i));
  5596. }
  5597. return result;
  5598. };
  5599. /**
  5600. * Adds a extension to this instance.
  5601. * @param extName The name of the extension which shall be added.
  5602. * @param extensionOptions The extension options which shall be used.
  5603. * @returns {{}} The instance of the added extension or undefined if the extension couldn't be added properly.
  5604. */
  5605. _base.addExt = function (extName, extensionOptions) {
  5606. var registeredExtensionObj = _plugin.extension(extName);
  5607. var instance;
  5608. var instanceAdded;
  5609. var instanceContract;
  5610. var contractResult;
  5611. var contractFulfilled = true;
  5612. if (registeredExtensionObj) {
  5613. if (!_extensions[LEXICON.hOP](extName)) {
  5614. instance = registeredExtensionObj.extensionFactory.call(_base,
  5615. extendDeep({}, registeredExtensionObj.defaultOptions),
  5616. FRAMEWORK,
  5617. COMPATIBILITY);
  5618. if (instance) {
  5619. instanceContract = instance.contract;
  5620. if (type(instanceContract) == TYPES.f) {
  5621. contractResult = instanceContract(window);
  5622. contractFulfilled = type(contractResult) == TYPES.b ? contractResult : contractFulfilled;
  5623. }
  5624. if (contractFulfilled) {
  5625. _extensions[extName] = instance;
  5626. instanceAdded = instance.added;
  5627. if (type(instanceAdded) == TYPES.f)
  5628. instanceAdded(extensionOptions);
  5629. return _base.ext(extName);
  5630. }
  5631. }
  5632. }
  5633. else
  5634. return _base.ext(extName);
  5635. }
  5636. else
  5637. console.warn("A extension with the name \"" + extName + "\" isn't registered.");
  5638. };
  5639. /**
  5640. * Removes a extension from this instance.
  5641. * @param extName The name of the extension which shall be removed.
  5642. * @returns {boolean} True if the extension was removed, false otherwise e.g. if the extension wasn't added before.
  5643. */
  5644. _base.removeExt = function (extName) {
  5645. var instance = _extensions[extName];
  5646. var instanceRemoved;
  5647. if (instance) {
  5648. delete _extensions[extName];
  5649. instanceRemoved = instance.removed;
  5650. if (type(instanceRemoved) == TYPES.f)
  5651. instanceRemoved();
  5652. return true;
  5653. }
  5654. return false;
  5655. };
  5656. /**
  5657. * Constructs the plugin.
  5658. * @param targetElement The element to which the plugin shall be applied.
  5659. * @param options The initial options of the plugin.
  5660. * @param extensions The extension(s) which shall be added right after the initialization.
  5661. * @returns {boolean} True if the plugin was successfully initialized, false otherwise.
  5662. */
  5663. function construct(targetElement, options, extensions) {
  5664. _defaultOptions = globals.defaultOptions;
  5665. _nativeScrollbarStyling = globals.nativeScrollbarStyling;
  5666. _nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize);
  5667. _nativeScrollbarIsOverlaid = extendDeep({}, globals.nativeScrollbarIsOverlaid);
  5668. _overlayScrollbarDummySize = extendDeep({}, globals.overlayScrollbarDummySize);
  5669. _rtlScrollBehavior = extendDeep({}, globals.rtlScrollBehavior);
  5670. //parse & set options but don't update
  5671. setOptions(extendDeep({}, _defaultOptions, options));
  5672. _cssCalc = globals.cssCalc;
  5673. _msieVersion = globals.msie;
  5674. _autoUpdateRecommended = globals.autoUpdateRecommended;
  5675. _supportTransition = globals.supportTransition;
  5676. _supportTransform = globals.supportTransform;
  5677. _supportPassiveEvents = globals.supportPassiveEvents;
  5678. _supportResizeObserver = globals.supportResizeObserver;
  5679. _supportMutationObserver = globals.supportMutationObserver;
  5680. _restrictedMeasuring = globals.restrictedMeasuring;
  5681. _documentElement = FRAMEWORK(targetElement.ownerDocument);
  5682. _documentElementNative = _documentElement[0];
  5683. _windowElement = FRAMEWORK(_documentElementNative.defaultView || _documentElementNative.parentWindow);
  5684. _windowElementNative = _windowElement[0];
  5685. _htmlElement = findFirst(_documentElement, 'html');
  5686. _bodyElement = findFirst(_htmlElement, 'body');
  5687. _targetElement = FRAMEWORK(targetElement);
  5688. _targetElementNative = _targetElement[0];
  5689. _isTextarea = _targetElement.is('textarea');
  5690. _isBody = _targetElement.is('body');
  5691. _documentMixed = _documentElementNative !== document;
  5692. /* On a div Element The if checks only whether:
  5693. * - the targetElement has the class "os-host"
  5694. * - the targetElement has a a child with the class "os-padding"
  5695. *
  5696. * If that's the case, its assumed the DOM has already the following structure:
  5697. * (The ".os-host" element is the targetElement)
  5698. *
  5699. * <div class="os-host">
  5700. * <div class="os-resize-observer-host"></div>
  5701. * <div class="os-padding">
  5702. * <div class="os-viewport">
  5703. * <div class="os-content"></div>
  5704. * </div>
  5705. * </div>
  5706. * <div class="os-scrollbar os-scrollbar-horizontal ">
  5707. * <div class="os-scrollbar-track">
  5708. * <div class="os-scrollbar-handle"></div>
  5709. * </div>
  5710. * </div>
  5711. * <div class="os-scrollbar os-scrollbar-vertical">
  5712. * <div class="os-scrollbar-track">
  5713. * <div class="os-scrollbar-handle"></div>
  5714. * </div>
  5715. * </div>
  5716. * <div class="os-scrollbar-corner"></div>
  5717. * </div>
  5718. *
  5719. * =====================================================================================
  5720. *
  5721. * On a Textarea Element The if checks only whether:
  5722. * - the targetElement has the class "os-textarea"
  5723. * - the targetElement is inside a element with the class "os-content"
  5724. *
  5725. * If that's the case, its assumed the DOM has already the following structure:
  5726. * (The ".os-textarea" (textarea) element is the targetElement)
  5727. *
  5728. * <div class="os-host-textarea">
  5729. * <div class="os-resize-observer-host"></div>
  5730. * <div class="os-padding os-text-inherit">
  5731. * <div class="os-viewport os-text-inherit">
  5732. * <div class="os-content os-text-inherit">
  5733. * <div class="os-textarea-cover"></div>
  5734. * <textarea class="os-textarea os-text-inherit"></textarea>
  5735. * </div>
  5736. * </div>
  5737. * </div>
  5738. * <div class="os-scrollbar os-scrollbar-horizontal ">
  5739. * <div class="os-scrollbar-track">
  5740. * <div class="os-scrollbar-handle"></div>
  5741. * </div>
  5742. * </div>
  5743. * <div class="os-scrollbar os-scrollbar-vertical">
  5744. * <div class="os-scrollbar-track">
  5745. * <div class="os-scrollbar-handle"></div>
  5746. * </div>
  5747. * </div>
  5748. * <div class="os-scrollbar-corner"></div>
  5749. * </div>
  5750. */
  5751. _domExists = _isTextarea
  5752. ? _targetElement.hasClass(_classNameTextareaElement) && _targetElement.parent().hasClass(_classNameContentElement)
  5753. : _targetElement.hasClass(_classNameHostElement) && _targetElement.children(_strDot + _classNamePaddingElement)[LEXICON.l];
  5754. var initBodyScroll;
  5755. var bodyMouseTouchDownListener;
  5756. //check if the plugin hasn't to be initialized
  5757. if (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y && !_currentPreparedOptions.nativeScrollbarsOverlaid.initialize) {
  5758. dispatchCallback('onInitializationWithdrawn');
  5759. if (_domExists) {
  5760. setupStructureDOM(true);
  5761. setupScrollbarsDOM(true);
  5762. setupScrollbarCornerDOM(true);
  5763. }
  5764. _destroyed = true;
  5765. _sleeping = true;
  5766. return _base;
  5767. }
  5768. if (_isBody) {
  5769. initBodyScroll = {};
  5770. initBodyScroll.l = MATH.max(_targetElement[_strScrollLeft](), _htmlElement[_strScrollLeft](), _windowElement[_strScrollLeft]());
  5771. initBodyScroll.t = MATH.max(_targetElement[_strScrollTop](), _htmlElement[_strScrollTop](), _windowElement[_strScrollTop]());
  5772. bodyMouseTouchDownListener = function () {
  5773. _viewportElement.removeAttr(LEXICON.ti);
  5774. setupResponsiveEventListener(_viewportElement, _strMouseTouchDownEvent, bodyMouseTouchDownListener, true, true);
  5775. }
  5776. }
  5777. //build OverlayScrollbars DOM
  5778. setupStructureDOM();
  5779. setupScrollbarsDOM();
  5780. setupScrollbarCornerDOM();
  5781. //create OverlayScrollbars events
  5782. setupStructureEvents();
  5783. setupScrollbarEvents(true);
  5784. setupScrollbarEvents(false);
  5785. setupScrollbarCornerEvents();
  5786. //create mutation observers
  5787. createMutationObservers();
  5788. //build resize observer for the host element
  5789. setupResizeObserver(_sizeObserverElement, hostOnResized);
  5790. if (_isBody) {
  5791. //apply the body scroll to handle it right in the update method
  5792. _viewportElement[_strScrollLeft](initBodyScroll.l)[_strScrollTop](initBodyScroll.t);
  5793. //set the focus on the viewport element so you dont have to click on the page to use keyboard keys (up / down / space) for scrolling
  5794. if (document.activeElement == targetElement && _viewportElementNative.focus) {
  5795. //set a tabindex to make the viewportElement focusable
  5796. _viewportElement.attr(LEXICON.ti, '-1');
  5797. _viewportElementNative.focus();
  5798. /* the tabindex has to be removed due to;
  5799. * If you set the tabindex attribute on an <div>, then its child content cannot be scrolled with the arrow keys unless you set tabindex on the content, too
  5800. * https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
  5801. */
  5802. setupResponsiveEventListener(_viewportElement, _strMouseTouchDownEvent, bodyMouseTouchDownListener, false, true);
  5803. }
  5804. }
  5805. //update for the first time & initialize cache
  5806. _base.update(_strAuto);
  5807. //the plugin is initialized now!
  5808. _initialized = true;
  5809. dispatchCallback('onInitialized');
  5810. //call all callbacks which would fire before the initialized was complete
  5811. each(_callbacksInitQeueue, function (index, value) { dispatchCallback(value.n, value.a); });
  5812. _callbacksInitQeueue = [];
  5813. //add extensions
  5814. if (type(extensions) == TYPES.s)
  5815. extensions = [extensions];
  5816. if (COMPATIBILITY.isA(extensions))
  5817. each(extensions, function (index, value) { _base.addExt(value); });
  5818. else if (FRAMEWORK.isPlainObject(extensions))
  5819. each(extensions, function (key, value) { _base.addExt(key, value); });
  5820. //add the transition class for transitions AFTER the first update & AFTER the applied extensions (for preventing unwanted transitions)
  5821. setTimeout(function () {
  5822. if (_supportTransition && !_destroyed)
  5823. addClass(_hostElement, _classNameHostTransition);
  5824. }, 333);
  5825. return _base;
  5826. }
  5827. if (_plugin.valid(construct(pluginTargetElement, options, extensions))) {
  5828. INSTANCES(pluginTargetElement, _base);
  5829. }
  5830. return _base;
  5831. }
  5832. /**
  5833. * Initializes a new OverlayScrollbarsInstance object or changes options if already initialized or returns the current instance.
  5834. * @param pluginTargetElements The elements to which the Plugin shall be initialized.
  5835. * @param options The custom options with which the plugin shall be initialized.
  5836. * @param extensions The extension(s) which shall be added right after initialization.
  5837. * @returns {*}
  5838. */
  5839. _plugin = window[PLUGINNAME] = function (pluginTargetElements, options, extensions) {
  5840. if (arguments[LEXICON.l] === 0)
  5841. return this;
  5842. var arr = [];
  5843. var optsIsPlainObj = FRAMEWORK.isPlainObject(options);
  5844. var inst;
  5845. var result;
  5846. //pluginTargetElements is null or undefined
  5847. if (!pluginTargetElements)
  5848. return optsIsPlainObj || !options ? result : arr;
  5849. /*
  5850. pluginTargetElements will be converted to:
  5851. 1. A jQueryElement Array
  5852. 2. A HTMLElement Array
  5853. 3. A Array with a single HTML Element
  5854. so pluginTargetElements is always a array.
  5855. */
  5856. pluginTargetElements = pluginTargetElements[LEXICON.l] != undefined ? pluginTargetElements : [pluginTargetElements[0] || pluginTargetElements];
  5857. initOverlayScrollbarsStatics();
  5858. if (pluginTargetElements[LEXICON.l] > 0) {
  5859. if (optsIsPlainObj) {
  5860. FRAMEWORK.each(pluginTargetElements, function (i, v) {
  5861. inst = v;
  5862. if (inst !== undefined)
  5863. arr.push(OverlayScrollbarsInstance(inst, options, extensions, _pluginsGlobals, _pluginsAutoUpdateLoop));
  5864. });
  5865. }
  5866. else {
  5867. FRAMEWORK.each(pluginTargetElements, function (i, v) {
  5868. inst = INSTANCES(v);
  5869. if ((options === '!' && _plugin.valid(inst)) || (COMPATIBILITY.type(options) == TYPES.f && options(v, inst)))
  5870. arr.push(inst);
  5871. else if (options === undefined)
  5872. arr.push(inst);
  5873. });
  5874. }
  5875. result = arr[LEXICON.l] === 1 ? arr[0] : arr;
  5876. }
  5877. return result;
  5878. };
  5879. /**
  5880. * Returns a object which contains global information about the plugin and each instance of it.
  5881. * The returned object is just a copy, that means that changes to the returned object won't have any effect to the original object.
  5882. */
  5883. _plugin.globals = function () {
  5884. initOverlayScrollbarsStatics();
  5885. var globals = FRAMEWORK.extend(true, {}, _pluginsGlobals);
  5886. delete globals['msie'];
  5887. return globals;
  5888. };
  5889. /**
  5890. * Gets or Sets the default options for each new plugin initialization.
  5891. * @param newDefaultOptions The object with which the default options shall be extended.
  5892. */
  5893. _plugin.defaultOptions = function (newDefaultOptions) {
  5894. initOverlayScrollbarsStatics();
  5895. var currDefaultOptions = _pluginsGlobals.defaultOptions;
  5896. if (newDefaultOptions === undefined)
  5897. return FRAMEWORK.extend(true, {}, currDefaultOptions);
  5898. //set the new default options
  5899. _pluginsGlobals.defaultOptions = FRAMEWORK.extend(true, {}, currDefaultOptions, _pluginsOptions._validate(newDefaultOptions, _pluginsOptions._template, true, currDefaultOptions)._default);
  5900. };
  5901. /**
  5902. * Checks whether the passed instance is a non-destroyed OverlayScrollbars instance.
  5903. * @param osInstance The potential OverlayScrollbars instance which shall be checked.
  5904. * @returns {boolean} True if the passed value is a non-destroyed OverlayScrollbars instance, false otherwise.
  5905. */
  5906. _plugin.valid = function (osInstance) {
  5907. return osInstance instanceof _plugin && !osInstance.getState().destroyed;
  5908. };
  5909. /**
  5910. * Registers, Unregisters or returns a extension.
  5911. * Register: Pass the name and the extension. (defaultOptions is optional)
  5912. * Unregister: Pass the name and anything except a function as extension parameter.
  5913. * Get extension: Pass the name of the extension which shall be got.
  5914. * Get all extensions: Pass no arguments.
  5915. * @param extensionName The name of the extension which shall be registered, unregistered or returned.
  5916. * @param extension A function which generates the instance of the extension or anything other to remove a already registered extension.
  5917. * @param defaultOptions The default options which shall be used for the registered extension.
  5918. */
  5919. _plugin.extension = function (extensionName, extension, defaultOptions) {
  5920. var extNameTypeString = COMPATIBILITY.type(extensionName) == TYPES.s;
  5921. var argLen = arguments[LEXICON.l];
  5922. var i = 0;
  5923. if (argLen < 1 || !extNameTypeString) {
  5924. //return a copy of all extension objects
  5925. return FRAMEWORK.extend(true, { length: _pluginsExtensions[LEXICON.l] }, _pluginsExtensions);
  5926. }
  5927. else if (extNameTypeString) {
  5928. if (COMPATIBILITY.type(extension) == TYPES.f) {
  5929. //register extension
  5930. _pluginsExtensions.push({
  5931. name: extensionName,
  5932. extensionFactory: extension,
  5933. defaultOptions: defaultOptions
  5934. });
  5935. }
  5936. else {
  5937. for (; i < _pluginsExtensions[LEXICON.l]; i++) {
  5938. if (_pluginsExtensions[i].name === extensionName) {
  5939. if (argLen > 1)
  5940. _pluginsExtensions.splice(i, 1); //remove extension
  5941. else
  5942. return FRAMEWORK.extend(true, {}, _pluginsExtensions[i]); //return extension with the given name
  5943. }
  5944. }
  5945. }
  5946. }
  5947. };
  5948. return _plugin;
  5949. })();
  5950. if (JQUERY && JQUERY.fn) {
  5951. /**
  5952. * The jQuery initialization interface.
  5953. * @param options The initial options for the construction of the plugin. To initialize the plugin, this option has to be a object! If it isn't a object, the instance(s) are returned and the plugin wont be initialized.
  5954. * @param extensions The extension(s) which shall be added right after initialization.
  5955. * @returns {*} After initialization it returns the jQuery element array, else it returns the instance(s) of the elements which are selected.
  5956. */
  5957. JQUERY.fn.overlayScrollbars = function (options, extensions) {
  5958. var _elements = this;
  5959. if (JQUERY.isPlainObject(options)) {
  5960. JQUERY.each(_elements, function () { PLUGIN(this, options, extensions); });
  5961. return _elements;
  5962. }
  5963. else
  5964. return PLUGIN(_elements, options);
  5965. };
  5966. }
  5967. return PLUGIN;
  5968. }
  5969. ));