vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1479 lines
38 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
  1. // utility functions
  2. // first check if moment.js is already loaded in the browser window, if so,
  3. // use this instance. Else, load via commonjs.
  4. var moment = require('./module/moment');
  5. var uuid = require('./module/uuid');
  6. /**
  7. * Test whether given object is a number
  8. * @param {*} object
  9. * @return {Boolean} isNumber
  10. */
  11. exports.isNumber = function (object) {
  12. return (object instanceof Number || typeof object == 'number');
  13. };
  14. /**
  15. * Remove everything in the DOM object
  16. * @param DOMobject
  17. */
  18. exports.recursiveDOMDelete = function (DOMobject) {
  19. if (DOMobject) {
  20. while (DOMobject.hasChildNodes() === true) {
  21. exports.recursiveDOMDelete(DOMobject.firstChild);
  22. DOMobject.removeChild(DOMobject.firstChild);
  23. }
  24. }
  25. };
  26. /**
  27. * this function gives you a range between 0 and 1 based on the min and max values in the set, the total sum of all values and the current value.
  28. *
  29. * @param min
  30. * @param max
  31. * @param total
  32. * @param value
  33. * @returns {number}
  34. */
  35. exports.giveRange = function (min, max, total, value) {
  36. if (max == min) {
  37. return 0.5;
  38. }
  39. else {
  40. var scale = 1 / (max - min);
  41. return Math.max(0, (value - min) * scale);
  42. }
  43. }
  44. /**
  45. * Test whether given object is a string
  46. * @param {*} object
  47. * @return {Boolean} isString
  48. */
  49. exports.isString = function (object) {
  50. return (object instanceof String || typeof object == 'string');
  51. };
  52. /**
  53. * Test whether given object is a Date, or a String containing a Date
  54. * @param {Date | String} object
  55. * @return {Boolean} isDate
  56. */
  57. exports.isDate = function (object) {
  58. if (object instanceof Date) {
  59. return true;
  60. }
  61. else if (exports.isString(object)) {
  62. // test whether this string contains a date
  63. var match = ASPDateRegex.exec(object);
  64. if (match) {
  65. return true;
  66. }
  67. else if (!isNaN(Date.parse(object))) {
  68. return true;
  69. }
  70. }
  71. return false;
  72. };
  73. /**
  74. * Create a semi UUID
  75. * source: http://stackoverflow.com/a/105074/1262753
  76. * @return {String} uuid
  77. */
  78. exports.randomUUID = function () {
  79. return uuid.v4();
  80. };
  81. /**
  82. * assign all keys of an object that are not nested objects to a certain value (used for color objects).
  83. * @param obj
  84. * @param value
  85. */
  86. exports.assignAllKeys = function (obj, value) {
  87. for (var prop in obj) {
  88. if (obj.hasOwnProperty(prop)) {
  89. if (typeof obj[prop] !== 'object') {
  90. obj[prop] = value;
  91. }
  92. }
  93. }
  94. }
  95. /**
  96. * Fill an object with a possibly partially defined other object. Only copies values if the a object has an object requiring values.
  97. * That means an object is not created on a property if only the b object has it.
  98. * @param obj
  99. * @param value
  100. */
  101. exports.fillIfDefined = function (a, b, allowDeletion = false) {
  102. for (var prop in a) {
  103. if (b[prop] !== undefined) {
  104. if (typeof b[prop] !== 'object') {
  105. if ((b[prop] === undefined || b[prop] === null) && a[prop] !== undefined && allowDeletion === true) {
  106. delete a[prop];
  107. }
  108. else {
  109. a[prop] = b[prop];
  110. }
  111. }
  112. else {
  113. if (typeof a[prop] === 'object') {
  114. exports.fillIfDefined(a[prop], b[prop], allowDeletion);
  115. }
  116. }
  117. }
  118. }
  119. }
  120. /**
  121. * Extend object a with the properties of object b or a series of objects
  122. * Only properties with defined values are copied
  123. * @param {Object} a
  124. * @param {... Object} b
  125. * @return {Object} a
  126. */
  127. exports.protoExtend = function (a, b) {
  128. for (var i = 1; i < arguments.length; i++) {
  129. var other = arguments[i];
  130. for (var prop in other) {
  131. a[prop] = other[prop];
  132. }
  133. }
  134. return a;
  135. };
  136. /**
  137. * Extend object a with the properties of object b or a series of objects
  138. * Only properties with defined values are copied
  139. * @param {Object} a
  140. * @param {... Object} b
  141. * @return {Object} a
  142. */
  143. exports.extend = function (a, b) {
  144. for (var i = 1; i < arguments.length; i++) {
  145. var other = arguments[i];
  146. for (var prop in other) {
  147. if (other.hasOwnProperty(prop)) {
  148. a[prop] = other[prop];
  149. }
  150. }
  151. }
  152. return a;
  153. };
  154. /**
  155. * Extend object a with selected properties of object b or a series of objects
  156. * Only properties with defined values are copied
  157. * @param {Array.<String>} props
  158. * @param {Object} a
  159. * @param {Object} b
  160. * @return {Object} a
  161. */
  162. exports.selectiveExtend = function (props, a, b) {
  163. if (!Array.isArray(props)) {
  164. throw new Error('Array with property names expected as first argument');
  165. }
  166. for (var i = 2; i < arguments.length; i++) {
  167. var other = arguments[i];
  168. for (var p = 0; p < props.length; p++) {
  169. var prop = props[p];
  170. if (other.hasOwnProperty(prop)) {
  171. a[prop] = other[prop];
  172. }
  173. }
  174. }
  175. return a;
  176. };
  177. /**
  178. * Extend object a with selected properties of object b or a series of objects
  179. * Only properties with defined values are copied
  180. * @param {Array.<String>} props
  181. * @param {Object} a
  182. * @param {Object} b
  183. * @return {Object} a
  184. */
  185. exports.selectiveDeepExtend = function (props, a, b, allowDeletion = false) {
  186. // TODO: add support for Arrays to deepExtend
  187. if (Array.isArray(b)) {
  188. throw new TypeError('Arrays are not supported by deepExtend');
  189. }
  190. for (var i = 2; i < arguments.length; i++) {
  191. var other = arguments[i];
  192. for (var p = 0; p < props.length; p++) {
  193. var prop = props[p];
  194. if (other.hasOwnProperty(prop)) {
  195. if (b[prop] && b[prop].constructor === Object) {
  196. if (a[prop] === undefined) {
  197. a[prop] = {};
  198. }
  199. if (a[prop].constructor === Object) {
  200. exports.deepExtend(a[prop], b[prop], false, allowDeletion);
  201. }
  202. else {
  203. if ((b[prop] === null) && a[prop] !== undefined && allowDeletion === true) {
  204. delete a[prop];
  205. }
  206. else {
  207. a[prop] = b[prop];
  208. }
  209. }
  210. } else if (Array.isArray(b[prop])) {
  211. throw new TypeError('Arrays are not supported by deepExtend');
  212. } else {
  213. if ((b[prop] === null) && a[prop] !== undefined && allowDeletion === true) {
  214. delete a[prop];
  215. }
  216. else {
  217. a[prop] = b[prop];
  218. }
  219. }
  220. }
  221. }
  222. }
  223. return a;
  224. };
  225. /**
  226. * Extend object a with selected properties of object b or a series of objects
  227. * Only properties with defined values are copied
  228. * @param {Array.<String>} props
  229. * @param {Object} a
  230. * @param {Object} b
  231. * @return {Object} a
  232. */
  233. exports.selectiveNotDeepExtend = function (props, a, b, allowDeletion = false) {
  234. // TODO: add support for Arrays to deepExtend
  235. if (Array.isArray(b)) {
  236. throw new TypeError('Arrays are not supported by deepExtend');
  237. }
  238. for (var prop in b) {
  239. if (b.hasOwnProperty(prop)) {
  240. if (props.indexOf(prop) == -1) {
  241. if (b[prop] && b[prop].constructor === Object) {
  242. if (a[prop] === undefined) {
  243. a[prop] = {};
  244. }
  245. if (a[prop].constructor === Object) {
  246. exports.deepExtend(a[prop], b[prop]);
  247. }
  248. else {
  249. if ((b[prop] === null) && a[prop] !== undefined && allowDeletion === true) {
  250. delete a[prop];
  251. }
  252. else {
  253. a[prop] = b[prop];
  254. }
  255. }
  256. } else if (Array.isArray(b[prop])) {
  257. a[prop] = [];
  258. for (let i = 0; i < b[prop].length; i++) {
  259. a[prop].push(b[prop][i]);
  260. }
  261. } else {
  262. if ((b[prop] === null) && a[prop] !== undefined && allowDeletion === true) {
  263. delete a[prop];
  264. }
  265. else {
  266. a[prop] = b[prop];
  267. }
  268. }
  269. }
  270. }
  271. }
  272. return a;
  273. };
  274. /**
  275. * Deep extend an object a with the properties of object b
  276. * @param {Object} a
  277. * @param {Object} b
  278. * @param [Boolean] protoExtend --> optional parameter. If true, the prototype values will also be extended.
  279. * (ie. the options objects that inherit from others will also get the inherited options)
  280. * @param [Boolean] global --> optional parameter. If true, the values of fields that are null will not deleted
  281. * @returns {Object}
  282. */
  283. exports.deepExtend = function (a, b, protoExtend, allowDeletion) {
  284. for (var prop in b) {
  285. if (b.hasOwnProperty(prop) || protoExtend === true) {
  286. if (b[prop] && b[prop].constructor === Object) {
  287. if (a[prop] === undefined) {
  288. a[prop] = {};
  289. }
  290. if (a[prop].constructor === Object) {
  291. exports.deepExtend(a[prop], b[prop], protoExtend);
  292. }
  293. else {
  294. if ((b[prop] === null) && a[prop] !== undefined && allowDeletion === true) {
  295. delete a[prop];
  296. }
  297. else {
  298. a[prop] = b[prop];
  299. }
  300. }
  301. } else if (Array.isArray(b[prop])) {
  302. a[prop] = [];
  303. for (let i = 0; i < b[prop].length; i++) {
  304. a[prop].push(b[prop][i]);
  305. }
  306. } else {
  307. if ((b[prop] === null) && a[prop] !== undefined && allowDeletion === true) {
  308. delete a[prop];
  309. }
  310. else {
  311. a[prop] = b[prop];
  312. }
  313. }
  314. }
  315. }
  316. return a;
  317. };
  318. /**
  319. * Test whether all elements in two arrays are equal.
  320. * @param {Array} a
  321. * @param {Array} b
  322. * @return {boolean} Returns true if both arrays have the same length and same
  323. * elements.
  324. */
  325. exports.equalArray = function (a, b) {
  326. if (a.length != b.length) return false;
  327. for (var i = 0, len = a.length; i < len; i++) {
  328. if (a[i] != b[i]) return false;
  329. }
  330. return true;
  331. };
  332. /**
  333. * Convert an object to another type
  334. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  335. * @param {String | undefined} type Name of the type. Available types:
  336. * 'Boolean', 'Number', 'String',
  337. * 'Date', 'Moment', ISODate', 'ASPDate'.
  338. * @return {*} object
  339. * @throws Error
  340. */
  341. exports.convert = function (object, type) {
  342. var match;
  343. if (object === undefined) {
  344. return undefined;
  345. }
  346. if (object === null) {
  347. return null;
  348. }
  349. if (!type) {
  350. return object;
  351. }
  352. if (!(typeof type === 'string') && !(type instanceof String)) {
  353. throw new Error('Type must be a string');
  354. }
  355. //noinspection FallthroughInSwitchStatementJS
  356. switch (type) {
  357. case 'boolean':
  358. case 'Boolean':
  359. return Boolean(object);
  360. case 'number':
  361. case 'Number':
  362. return Number(object.valueOf());
  363. case 'string':
  364. case 'String':
  365. return String(object);
  366. case 'Date':
  367. if (exports.isNumber(object)) {
  368. return new Date(object);
  369. }
  370. if (object instanceof Date) {
  371. return new Date(object.valueOf());
  372. }
  373. else if (moment.isMoment(object)) {
  374. return new Date(object.valueOf());
  375. }
  376. if (exports.isString(object)) {
  377. match = ASPDateRegex.exec(object);
  378. if (match) {
  379. // object is an ASP date
  380. return new Date(Number(match[1])); // parse number
  381. }
  382. else {
  383. return moment(new Date(object)).toDate(); // parse string
  384. }
  385. }
  386. else {
  387. throw new Error(
  388. 'Cannot convert object of type ' + exports.getType(object) +
  389. ' to type Date');
  390. }
  391. case 'Moment':
  392. if (exports.isNumber(object)) {
  393. return moment(object);
  394. }
  395. if (object instanceof Date) {
  396. return moment(object.valueOf());
  397. }
  398. else if (moment.isMoment(object)) {
  399. return moment(object);
  400. }
  401. if (exports.isString(object)) {
  402. match = ASPDateRegex.exec(object);
  403. if (match) {
  404. // object is an ASP date
  405. return moment(Number(match[1])); // parse number
  406. }
  407. else {
  408. return moment(object); // parse string
  409. }
  410. }
  411. else {
  412. throw new Error(
  413. 'Cannot convert object of type ' + exports.getType(object) +
  414. ' to type Date');
  415. }
  416. case 'ISODate':
  417. if (exports.isNumber(object)) {
  418. return new Date(object);
  419. }
  420. else if (object instanceof Date) {
  421. return object.toISOString();
  422. }
  423. else if (moment.isMoment(object)) {
  424. return object.toDate().toISOString();
  425. }
  426. else if (exports.isString(object)) {
  427. match = ASPDateRegex.exec(object);
  428. if (match) {
  429. // object is an ASP date
  430. return new Date(Number(match[1])).toISOString(); // parse number
  431. }
  432. else {
  433. return new Date(object).toISOString(); // parse string
  434. }
  435. }
  436. else {
  437. throw new Error(
  438. 'Cannot convert object of type ' + exports.getType(object) +
  439. ' to type ISODate');
  440. }
  441. case 'ASPDate':
  442. if (exports.isNumber(object)) {
  443. return '/Date(' + object + ')/';
  444. }
  445. else if (object instanceof Date) {
  446. return '/Date(' + object.valueOf() + ')/';
  447. }
  448. else if (exports.isString(object)) {
  449. match = ASPDateRegex.exec(object);
  450. var value;
  451. if (match) {
  452. // object is an ASP date
  453. value = new Date(Number(match[1])).valueOf(); // parse number
  454. }
  455. else {
  456. value = new Date(object).valueOf(); // parse string
  457. }
  458. return '/Date(' + value + ')/';
  459. }
  460. else {
  461. throw new Error(
  462. 'Cannot convert object of type ' + exports.getType(object) +
  463. ' to type ASPDate');
  464. }
  465. default:
  466. throw new Error('Unknown type "' + type + '"');
  467. }
  468. };
  469. // parse ASP.Net Date pattern,
  470. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  471. // code from http://momentjs.com/
  472. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  473. /**
  474. * Get the type of an object, for example exports.getType([]) returns 'Array'
  475. * @param {*} object
  476. * @return {String} type
  477. */
  478. exports.getType = function (object) {
  479. var type = typeof object;
  480. if (type == 'object') {
  481. if (object === null) {
  482. return 'null';
  483. }
  484. if (object instanceof Boolean) {
  485. return 'Boolean';
  486. }
  487. if (object instanceof Number) {
  488. return 'Number';
  489. }
  490. if (object instanceof String) {
  491. return 'String';
  492. }
  493. if (Array.isArray(object)) {
  494. return 'Array';
  495. }
  496. if (object instanceof Date) {
  497. return 'Date';
  498. }
  499. return 'Object';
  500. }
  501. else if (type == 'number') {
  502. return 'Number';
  503. }
  504. else if (type == 'boolean') {
  505. return 'Boolean';
  506. }
  507. else if (type == 'string') {
  508. return 'String';
  509. }
  510. else if (type === undefined) {
  511. return 'undefined';
  512. }
  513. return type;
  514. };
  515. /**
  516. * Used to extend an array and copy it. This is used to propagate paths recursively.
  517. *
  518. * @param arr
  519. * @param newValue
  520. * @returns {Array}
  521. */
  522. exports.copyAndExtendArray = function (arr, newValue) {
  523. let newArr = [];
  524. for (let i = 0; i < arr.length; i++) {
  525. newArr.push(arr[i]);
  526. }
  527. newArr.push(newValue);
  528. return newArr;
  529. }
  530. /**
  531. * Used to extend an array and copy it. This is used to propagate paths recursively.
  532. *
  533. * @param arr
  534. * @param newValue
  535. * @returns {Array}
  536. */
  537. exports.copyArray = function (arr) {
  538. let newArr = [];
  539. for (let i = 0; i < arr.length; i++) {
  540. newArr.push(arr[i]);
  541. }
  542. return newArr;
  543. }
  544. /**
  545. * Retrieve the absolute left value of a DOM element
  546. * @param {Element} elem A dom element, for example a div
  547. * @return {number} left The absolute left position of this element
  548. * in the browser page.
  549. */
  550. exports.getAbsoluteLeft = function (elem) {
  551. return elem.getBoundingClientRect().left;
  552. };
  553. exports.getAbsoluteRight = function (elem) {
  554. return elem.getBoundingClientRect().right;
  555. };
  556. /**
  557. * Retrieve the absolute top value of a DOM element
  558. * @param {Element} elem A dom element, for example a div
  559. * @return {number} top The absolute top position of this element
  560. * in the browser page.
  561. */
  562. exports.getAbsoluteTop = function (elem) {
  563. return elem.getBoundingClientRect().top;
  564. };
  565. /**
  566. * add a className to the given elements style
  567. * @param {Element} elem
  568. * @param {String} className
  569. */
  570. exports.addClassName = function (elem, className) {
  571. var classes = elem.className.split(' ');
  572. if (classes.indexOf(className) == -1) {
  573. classes.push(className); // add the class to the array
  574. elem.className = classes.join(' ');
  575. }
  576. };
  577. /**
  578. * add a className to the given elements style
  579. * @param {Element} elem
  580. * @param {String} className
  581. */
  582. exports.removeClassName = function (elem, className) {
  583. var classes = elem.className.split(' ');
  584. var index = classes.indexOf(className);
  585. if (index != -1) {
  586. classes.splice(index, 1); // remove the class from the array
  587. elem.className = classes.join(' ');
  588. }
  589. };
  590. /**
  591. * For each method for both arrays and objects.
  592. * In case of an array, the built-in Array.forEach() is applied.
  593. * In case of an Object, the method loops over all properties of the object.
  594. * @param {Object | Array} object An Object or Array
  595. * @param {function} callback Callback method, called for each item in
  596. * the object or array with three parameters:
  597. * callback(value, index, object)
  598. */
  599. exports.forEach = function (object, callback) {
  600. var i,
  601. len;
  602. if (Array.isArray(object)) {
  603. // array
  604. for (i = 0, len = object.length; i < len; i++) {
  605. callback(object[i], i, object);
  606. }
  607. }
  608. else {
  609. // object
  610. for (i in object) {
  611. if (object.hasOwnProperty(i)) {
  612. callback(object[i], i, object);
  613. }
  614. }
  615. }
  616. };
  617. /**
  618. * Convert an object into an array: all objects properties are put into the
  619. * array. The resulting array is unordered.
  620. * @param {Object} object
  621. * @param {Array} array
  622. */
  623. exports.toArray = function (object) {
  624. var array = [];
  625. for (var prop in object) {
  626. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  627. }
  628. return array;
  629. };
  630. /**
  631. * Update a property in an object
  632. * @param {Object} object
  633. * @param {String} key
  634. * @param {*} value
  635. * @return {Boolean} changed
  636. */
  637. exports.updateProperty = function (object, key, value) {
  638. if (object[key] !== value) {
  639. object[key] = value;
  640. return true;
  641. }
  642. else {
  643. return false;
  644. }
  645. };
  646. /**
  647. * Throttle the given function to be only executed once per animation frame
  648. * @param {function} fn
  649. * @returns {function} Returns the throttled function
  650. */
  651. exports.throttle = function (fn) {
  652. var scheduled = false;
  653. return function throttled () {
  654. if (!scheduled) {
  655. scheduled = true;
  656. requestAnimationFrame(function () {
  657. scheduled = false;
  658. fn();
  659. });
  660. }
  661. }
  662. };
  663. /**
  664. * Add and event listener. Works for all browsers
  665. * @param {Element} element An html element
  666. * @param {string} action The action, for example "click",
  667. * without the prefix "on"
  668. * @param {function} listener The callback function to be executed
  669. * @param {boolean} [useCapture]
  670. */
  671. exports.addEventListener = function (element, action, listener, useCapture) {
  672. if (element.addEventListener) {
  673. if (useCapture === undefined)
  674. useCapture = false;
  675. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  676. action = "DOMMouseScroll"; // For Firefox
  677. }
  678. element.addEventListener(action, listener, useCapture);
  679. } else {
  680. element.attachEvent("on" + action, listener); // IE browsers
  681. }
  682. };
  683. /**
  684. * Remove an event listener from an element
  685. * @param {Element} element An html dom element
  686. * @param {string} action The name of the event, for example "mousedown"
  687. * @param {function} listener The listener function
  688. * @param {boolean} [useCapture]
  689. */
  690. exports.removeEventListener = function (element, action, listener, useCapture) {
  691. if (element.removeEventListener) {
  692. // non-IE browsers
  693. if (useCapture === undefined)
  694. useCapture = false;
  695. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  696. action = "DOMMouseScroll"; // For Firefox
  697. }
  698. element.removeEventListener(action, listener, useCapture);
  699. } else {
  700. // IE browsers
  701. element.detachEvent("on" + action, listener);
  702. }
  703. };
  704. /**
  705. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  706. */
  707. exports.preventDefault = function (event) {
  708. if (!event)
  709. event = window.event;
  710. if (event.preventDefault) {
  711. event.preventDefault(); // non-IE browsers
  712. }
  713. else {
  714. event.returnValue = false; // IE browsers
  715. }
  716. };
  717. /**
  718. * Get HTML element which is the target of the event
  719. * @param {Event} event
  720. * @return {Element} target element
  721. */
  722. exports.getTarget = function (event) {
  723. // code from http://www.quirksmode.org/js/events_properties.html
  724. if (!event) {
  725. event = window.event;
  726. }
  727. var target;
  728. if (event.target) {
  729. target = event.target;
  730. }
  731. else if (event.srcElement) {
  732. target = event.srcElement;
  733. }
  734. if (target.nodeType != undefined && target.nodeType == 3) {
  735. // defeat Safari bug
  736. target = target.parentNode;
  737. }
  738. return target;
  739. };
  740. /**
  741. * Check if given element contains given parent somewhere in the DOM tree
  742. * @param {Element} element
  743. * @param {Element} parent
  744. */
  745. exports.hasParent = function (element, parent) {
  746. var e = element;
  747. while (e) {
  748. if (e === parent) {
  749. return true;
  750. }
  751. e = e.parentNode;
  752. }
  753. return false;
  754. };
  755. exports.option = {};
  756. /**
  757. * Convert a value into a boolean
  758. * @param {Boolean | function | undefined} value
  759. * @param {Boolean} [defaultValue]
  760. * @returns {Boolean} bool
  761. */
  762. exports.option.asBoolean = function (value, defaultValue) {
  763. if (typeof value == 'function') {
  764. value = value();
  765. }
  766. if (value != null) {
  767. return (value != false);
  768. }
  769. return defaultValue || null;
  770. };
  771. /**
  772. * Convert a value into a number
  773. * @param {Boolean | function | undefined} value
  774. * @param {Number} [defaultValue]
  775. * @returns {Number} number
  776. */
  777. exports.option.asNumber = function (value, defaultValue) {
  778. if (typeof value == 'function') {
  779. value = value();
  780. }
  781. if (value != null) {
  782. return Number(value) || defaultValue || null;
  783. }
  784. return defaultValue || null;
  785. };
  786. /**
  787. * Convert a value into a string
  788. * @param {String | function | undefined} value
  789. * @param {String} [defaultValue]
  790. * @returns {String} str
  791. */
  792. exports.option.asString = function (value, defaultValue) {
  793. if (typeof value == 'function') {
  794. value = value();
  795. }
  796. if (value != null) {
  797. return String(value);
  798. }
  799. return defaultValue || null;
  800. };
  801. /**
  802. * Convert a size or location into a string with pixels or a percentage
  803. * @param {String | Number | function | undefined} value
  804. * @param {String} [defaultValue]
  805. * @returns {String} size
  806. */
  807. exports.option.asSize = function (value, defaultValue) {
  808. if (typeof value == 'function') {
  809. value = value();
  810. }
  811. if (exports.isString(value)) {
  812. return value;
  813. }
  814. else if (exports.isNumber(value)) {
  815. return value + 'px';
  816. }
  817. else {
  818. return defaultValue || null;
  819. }
  820. };
  821. /**
  822. * Convert a value into a DOM element
  823. * @param {HTMLElement | function | undefined} value
  824. * @param {HTMLElement} [defaultValue]
  825. * @returns {HTMLElement | null} dom
  826. */
  827. exports.option.asElement = function (value, defaultValue) {
  828. if (typeof value == 'function') {
  829. value = value();
  830. }
  831. return value || defaultValue || null;
  832. };
  833. /**
  834. * http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
  835. *
  836. * @param {String} hex
  837. * @returns {{r: *, g: *, b: *}} | 255 range
  838. */
  839. exports.hexToRGB = function (hex) {
  840. // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  841. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  842. hex = hex.replace(shorthandRegex, function (m, r, g, b) {
  843. return r + r + g + g + b + b;
  844. });
  845. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  846. return result ? {
  847. r: parseInt(result[1], 16),
  848. g: parseInt(result[2], 16),
  849. b: parseInt(result[3], 16)
  850. } : null;
  851. };
  852. /**
  853. * This function takes color in hex format or rgb() or rgba() format and overrides the opacity. Returns rgba() string.
  854. * @param color
  855. * @param opacity
  856. * @returns {*}
  857. */
  858. exports.overrideOpacity = function (color, opacity) {
  859. if (color.indexOf("rgba") != -1) {
  860. return color;
  861. }
  862. else if (color.indexOf("rgb") != -1) {
  863. var rgb = color.substr(color.indexOf("(") + 1).replace(")", "").split(",");
  864. return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")"
  865. }
  866. else {
  867. var rgb = exports.hexToRGB(color);
  868. if (rgb == null) {
  869. return color;
  870. }
  871. else {
  872. return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + opacity + ")"
  873. }
  874. }
  875. }
  876. /**
  877. *
  878. * @param red 0 -- 255
  879. * @param green 0 -- 255
  880. * @param blue 0 -- 255
  881. * @returns {string}
  882. * @constructor
  883. */
  884. exports.RGBToHex = function (red, green, blue) {
  885. return "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);
  886. };
  887. /**
  888. * Parse a color property into an object with border, background, and
  889. * highlight colors
  890. * @param {Object | String} color
  891. * @return {Object} colorObject
  892. */
  893. exports.parseColor = function (color) {
  894. var c;
  895. if (exports.isString(color) === true) {
  896. if (exports.isValidRGB(color) === true) {
  897. var rgb = color.substr(4).substr(0, color.length - 5).split(',').map(function (value) { return parseInt(value) });
  898. color = exports.RGBToHex(rgb[0], rgb[1], rgb[2]);
  899. }
  900. if (exports.isValidHex(color) === true) {
  901. var hsv = exports.hexToHSV(color);
  902. var lighterColorHSV = { h: hsv.h, s: hsv.s * 0.8, v: Math.min(1, hsv.v * 1.02) };
  903. var darkerColorHSV = { h: hsv.h, s: Math.min(1, hsv.s * 1.25), v: hsv.v * 0.8 };
  904. var darkerColorHex = exports.HSVToHex(darkerColorHSV.h, darkerColorHSV.s, darkerColorHSV.v);
  905. var lighterColorHex = exports.HSVToHex(lighterColorHSV.h, lighterColorHSV.s, lighterColorHSV.v);
  906. c = {
  907. background: color,
  908. border: darkerColorHex,
  909. highlight: {
  910. background: lighterColorHex,
  911. border: darkerColorHex
  912. },
  913. hover: {
  914. background: lighterColorHex,
  915. border: darkerColorHex
  916. }
  917. };
  918. }
  919. else {
  920. c = {
  921. background: color,
  922. border: color,
  923. highlight: {
  924. background: color,
  925. border: color
  926. },
  927. hover: {
  928. background: color,
  929. border: color
  930. }
  931. };
  932. }
  933. }
  934. else {
  935. c = {};
  936. c.background = color.background || undefined;
  937. c.border = color.border || undefined;
  938. if (exports.isString(color.highlight)) {
  939. c.highlight = {
  940. border: color.highlight,
  941. background: color.highlight
  942. }
  943. }
  944. else {
  945. c.highlight = {};
  946. c.highlight.background = color.highlight && color.highlight.background || undefined;
  947. c.highlight.border = color.highlight && color.highlight.border || undefined;
  948. }
  949. if (exports.isString(color.hover)) {
  950. c.hover = {
  951. border: color.hover,
  952. background: color.hover
  953. }
  954. }
  955. else {
  956. c.hover = {};
  957. c.hover.background = color.hover && color.hover.background || undefined;
  958. c.hover.border = color.hover && color.hover.border || undefined;
  959. }
  960. }
  961. return c;
  962. };
  963. /**
  964. * http://www.javascripter.net/faq/rgb2hsv.htm
  965. *
  966. * @param red
  967. * @param green
  968. * @param blue
  969. * @returns {*}
  970. * @constructor
  971. */
  972. exports.RGBToHSV = function (red, green, blue) {
  973. red = red / 255; green = green / 255; blue = blue / 255;
  974. var minRGB = Math.min(red, Math.min(green, blue));
  975. var maxRGB = Math.max(red, Math.max(green, blue));
  976. // Black-gray-white
  977. if (minRGB == maxRGB) {
  978. return { h: 0, s: 0, v: minRGB };
  979. }
  980. // Colors other than black-gray-white:
  981. var d = (red == minRGB) ? green - blue : ((blue == minRGB) ? red - green : blue - red);
  982. var h = (red == minRGB) ? 3 : ((blue == minRGB) ? 1 : 5);
  983. var hue = 60 * (h - d / (maxRGB - minRGB)) / 360;
  984. var saturation = (maxRGB - minRGB) / maxRGB;
  985. var value = maxRGB;
  986. return { h: hue, s: saturation, v: value };
  987. };
  988. var cssUtil = {
  989. // split a string with css styles into an object with key/values
  990. split: function (cssText) {
  991. var styles = {};
  992. cssText.split(';').forEach(function (style) {
  993. if (style.trim() != '') {
  994. var parts = style.split(':');
  995. var key = parts[0].trim();
  996. var value = parts[1].trim();
  997. styles[key] = value;
  998. }
  999. });
  1000. return styles;
  1001. },
  1002. // build a css text string from an object with key/values
  1003. join: function (styles) {
  1004. return Object.keys(styles)
  1005. .map(function (key) {
  1006. return key + ': ' + styles[key];
  1007. })
  1008. .join('; ');
  1009. }
  1010. };
  1011. /**
  1012. * Append a string with css styles to an element
  1013. * @param {Element} element
  1014. * @param {String} cssText
  1015. */
  1016. exports.addCssText = function (element, cssText) {
  1017. var currentStyles = cssUtil.split(element.style.cssText);
  1018. var newStyles = cssUtil.split(cssText);
  1019. var styles = exports.extend(currentStyles, newStyles);
  1020. element.style.cssText = cssUtil.join(styles);
  1021. };
  1022. /**
  1023. * Remove a string with css styles from an element
  1024. * @param {Element} element
  1025. * @param {String} cssText
  1026. */
  1027. exports.removeCssText = function (element, cssText) {
  1028. var styles = cssUtil.split(element.style.cssText);
  1029. var removeStyles = cssUtil.split(cssText);
  1030. for (var key in removeStyles) {
  1031. if (removeStyles.hasOwnProperty(key)) {
  1032. delete styles[key];
  1033. }
  1034. }
  1035. element.style.cssText = cssUtil.join(styles);
  1036. };
  1037. /**
  1038. * https://gist.github.com/mjijackson/5311256
  1039. * @param h
  1040. * @param s
  1041. * @param v
  1042. * @returns {{r: number, g: number, b: number}}
  1043. * @constructor
  1044. */
  1045. exports.HSVToRGB = function (h, s, v) {
  1046. var r, g, b;
  1047. var i = Math.floor(h * 6);
  1048. var f = h * 6 - i;
  1049. var p = v * (1 - s);
  1050. var q = v * (1 - f * s);
  1051. var t = v * (1 - (1 - f) * s);
  1052. switch (i % 6) {
  1053. case 0: r = v, g = t, b = p; break;
  1054. case 1: r = q, g = v, b = p; break;
  1055. case 2: r = p, g = v, b = t; break;
  1056. case 3: r = p, g = q, b = v; break;
  1057. case 4: r = t, g = p, b = v; break;
  1058. case 5: r = v, g = p, b = q; break;
  1059. }
  1060. return { r: Math.floor(r * 255), g: Math.floor(g * 255), b: Math.floor(b * 255) };
  1061. };
  1062. exports.HSVToHex = function (h, s, v) {
  1063. var rgb = exports.HSVToRGB(h, s, v);
  1064. return exports.RGBToHex(rgb.r, rgb.g, rgb.b);
  1065. };
  1066. exports.hexToHSV = function (hex) {
  1067. var rgb = exports.hexToRGB(hex);
  1068. return exports.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1069. };
  1070. exports.isValidHex = function (hex) {
  1071. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1072. return isOk;
  1073. };
  1074. exports.isValidRGB = function (rgb) {
  1075. rgb = rgb.replace(" ", "");
  1076. var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb);
  1077. return isOk;
  1078. }
  1079. exports.isValidRGBA = function (rgba) {
  1080. rgba = rgba.replace(" ", "");
  1081. var isOk = /rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(.{1,3})\)/i.test(rgba);
  1082. return isOk;
  1083. }
  1084. /**
  1085. * This recursively redirects the prototype of JSON objects to the referenceObject
  1086. * This is used for default options.
  1087. *
  1088. * @param referenceObject
  1089. * @returns {*}
  1090. */
  1091. exports.selectiveBridgeObject = function (fields, referenceObject) {
  1092. if (typeof referenceObject == "object") {
  1093. var objectTo = Object.create(referenceObject);
  1094. for (var i = 0; i < fields.length; i++) {
  1095. if (referenceObject.hasOwnProperty(fields[i])) {
  1096. if (typeof referenceObject[fields[i]] == "object") {
  1097. objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]);
  1098. }
  1099. }
  1100. }
  1101. return objectTo;
  1102. }
  1103. else {
  1104. return null;
  1105. }
  1106. };
  1107. /**
  1108. * This recursively redirects the prototype of JSON objects to the referenceObject
  1109. * This is used for default options.
  1110. *
  1111. * @param referenceObject
  1112. * @returns {*}
  1113. */
  1114. exports.bridgeObject = function (referenceObject) {
  1115. if (typeof referenceObject == "object") {
  1116. var objectTo = Object.create(referenceObject);
  1117. for (var i in referenceObject) {
  1118. if (referenceObject.hasOwnProperty(i)) {
  1119. if (typeof referenceObject[i] == "object") {
  1120. objectTo[i] = exports.bridgeObject(referenceObject[i]);
  1121. }
  1122. }
  1123. }
  1124. return objectTo;
  1125. }
  1126. else {
  1127. return null;
  1128. }
  1129. };
  1130. /**
  1131. * This method provides a stable sort implementation, very fast for presorted data
  1132. *
  1133. * @param a the array
  1134. * @param a order comparator
  1135. * @returns {the array}
  1136. */
  1137. exports.insertSort = function (a,compare) {
  1138. for (var i = 0; i < a.length; i++) {
  1139. var k = a[i];
  1140. for (var j = i; j > 0 && compare(k,a[j - 1])<0; j--) {
  1141. a[j] = a[j - 1];
  1142. }
  1143. a[j] = k;
  1144. }
  1145. return a;
  1146. }
  1147. /**
  1148. * this is used to set the options of subobjects in the options object. A requirement of these subobjects
  1149. * is that they have an 'enabled' element which is optional for the user but mandatory for the program.
  1150. *
  1151. * @param [object] mergeTarget | this is either this.options or the options used for the groups.
  1152. * @param [object] options | options
  1153. * @param [String] option | this is the option key in the options argument
  1154. */
  1155. exports.mergeOptions = function (mergeTarget, options, option, allowDeletion = false, globalOptions = {}) {
  1156. if (options[option] === null) {
  1157. mergeTarget[option] = Object.create(globalOptions[option]);
  1158. }
  1159. else {
  1160. if (options[option] !== undefined) {
  1161. if (typeof options[option] === 'boolean') {
  1162. mergeTarget[option].enabled = options[option];
  1163. }
  1164. else {
  1165. if (options[option].enabled === undefined) {
  1166. mergeTarget[option].enabled = true;
  1167. }
  1168. for (var prop in options[option]) {
  1169. if (options[option].hasOwnProperty(prop)) {
  1170. mergeTarget[option][prop] = options[option][prop];
  1171. }
  1172. }
  1173. }
  1174. }
  1175. }
  1176. }
  1177. /**
  1178. * This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
  1179. * this function will then iterate in both directions over this sorted list to find all visible items.
  1180. *
  1181. * @param {Item[]} orderedItems | Items ordered by start
  1182. * @param {function} comparator | -1 is lower, 0 is equal, 1 is higher
  1183. * @param {String} field
  1184. * @param {String} field2
  1185. * @returns {number}
  1186. * @private
  1187. */
  1188. exports.binarySearchCustom = function (orderedItems, comparator, field, field2) {
  1189. var maxIterations = 10000;
  1190. var iteration = 0;
  1191. var low = 0;
  1192. var high = orderedItems.length - 1;
  1193. while (low <= high && iteration < maxIterations) {
  1194. var middle = Math.floor((low + high) / 2);
  1195. var item = orderedItems[middle];
  1196. var value = (field2 === undefined) ? item[field] : item[field][field2];
  1197. var searchResult = comparator(value);
  1198. if (searchResult == 0) { // jihaa, found a visible item!
  1199. return middle;
  1200. }
  1201. else if (searchResult == -1) { // it is too small --> increase low
  1202. low = middle + 1;
  1203. }
  1204. else { // it is too big --> decrease high
  1205. high = middle - 1;
  1206. }
  1207. iteration++;
  1208. }
  1209. return -1;
  1210. };
  1211. /**
  1212. * This function does a binary search for a specific value in a sorted array. If it does not exist but is in between of
  1213. * two values, we return either the one before or the one after, depending on user input
  1214. * If it is found, we return the index, else -1.
  1215. *
  1216. * @param {Array} orderedItems
  1217. * @param {{start: number, end: number}} target
  1218. * @param {String} field
  1219. * @param {String} sidePreference 'before' or 'after'
  1220. * @param {function} comparator an optional comparator, returning -1,0,1 for <,==,>.
  1221. * @returns {number}
  1222. * @private
  1223. */
  1224. exports.binarySearchValue = function (orderedItems, target, field, sidePreference, comparator) {
  1225. var maxIterations = 10000;
  1226. var iteration = 0;
  1227. var low = 0;
  1228. var high = orderedItems.length - 1;
  1229. var prevValue, value, nextValue, middle;
  1230. var comparator = comparator != undefined ? comparator : function (a, b) {
  1231. return a == b ? 0 : a < b ? -1 : 1
  1232. };
  1233. while (low <= high && iteration < maxIterations) {
  1234. // get a new guess
  1235. middle = Math.floor(0.5 * (high + low));
  1236. prevValue = orderedItems[Math.max(0, middle - 1)][field];
  1237. value = orderedItems[middle][field];
  1238. nextValue = orderedItems[Math.min(orderedItems.length - 1, middle + 1)][field];
  1239. if (comparator(value, target) == 0) { // we found the target
  1240. return middle;
  1241. }
  1242. else if (comparator(prevValue, target) < 0 && comparator(value, target) > 0) { // target is in between of the previous and the current
  1243. return sidePreference == 'before' ? Math.max(0, middle - 1) : middle;
  1244. }
  1245. else if (comparator(value, target) < 0 && comparator(nextValue, target) > 0) { // target is in between of the current and the next
  1246. return sidePreference == 'before' ? middle : Math.min(orderedItems.length - 1, middle + 1);
  1247. }
  1248. else { // didnt find the target, we need to change our boundaries.
  1249. if (comparator(value, target) < 0) { // it is too small --> increase low
  1250. low = middle + 1;
  1251. }
  1252. else { // it is too big --> decrease high
  1253. high = middle - 1;
  1254. }
  1255. }
  1256. iteration++;
  1257. }
  1258. // didnt find anything. Return -1.
  1259. return -1;
  1260. };
  1261. /*
  1262. * Easing Functions - inspired from http://gizma.com/easing/
  1263. * only considering the t value for the range [0, 1] => [0, 1]
  1264. * https://gist.github.com/gre/1650294
  1265. */
  1266. exports.easingFunctions = {
  1267. // no easing, no acceleration
  1268. linear: function (t) {
  1269. return t
  1270. },
  1271. // accelerating from zero velocity
  1272. easeInQuad: function (t) {
  1273. return t * t
  1274. },
  1275. // decelerating to zero velocity
  1276. easeOutQuad: function (t) {
  1277. return t * (2 - t)
  1278. },
  1279. // acceleration until halfway, then deceleration
  1280. easeInOutQuad: function (t) {
  1281. return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t
  1282. },
  1283. // accelerating from zero velocity
  1284. easeInCubic: function (t) {
  1285. return t * t * t
  1286. },
  1287. // decelerating to zero velocity
  1288. easeOutCubic: function (t) {
  1289. return (--t) * t * t + 1
  1290. },
  1291. // acceleration until halfway, then deceleration
  1292. easeInOutCubic: function (t) {
  1293. return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
  1294. },
  1295. // accelerating from zero velocity
  1296. easeInQuart: function (t) {
  1297. return t * t * t * t
  1298. },
  1299. // decelerating to zero velocity
  1300. easeOutQuart: function (t) {
  1301. return 1 - (--t) * t * t * t
  1302. },
  1303. // acceleration until halfway, then deceleration
  1304. easeInOutQuart: function (t) {
  1305. return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t
  1306. },
  1307. // accelerating from zero velocity
  1308. easeInQuint: function (t) {
  1309. return t * t * t * t * t
  1310. },
  1311. // decelerating to zero velocity
  1312. easeOutQuint: function (t) {
  1313. return 1 + (--t) * t * t * t * t
  1314. },
  1315. // acceleration until halfway, then deceleration
  1316. easeInOutQuint: function (t) {
  1317. return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t
  1318. }
  1319. };
  1320. exports.getScrollBarWidth = function () {
  1321. var inner = document.createElement('p');
  1322. inner.style.width = "100%";
  1323. inner.style.height = "200px";
  1324. var outer = document.createElement('div');
  1325. outer.style.position = "absolute";
  1326. outer.style.top = "0px";
  1327. outer.style.left = "0px";
  1328. outer.style.visibility = "hidden";
  1329. outer.style.width = "200px";
  1330. outer.style.height = "150px";
  1331. outer.style.overflow = "hidden";
  1332. outer.appendChild (inner);
  1333. document.body.appendChild (outer);
  1334. var w1 = inner.offsetWidth;
  1335. outer.style.overflow = 'scroll';
  1336. var w2 = inner.offsetWidth;
  1337. if (w1 == w2) w2 = outer.clientWidth;
  1338. document.body.removeChild (outer);
  1339. return (w1 - w2);
  1340. };