Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

5578 lignes
311KB

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