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.

1463 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 every `wait` milliseconds
  648. * @param {function} fn
  649. * @param {number} wait Time in milliseconds
  650. * @returns {function} Returns the throttled function
  651. */
  652. exports.throttle = function (fn, wait) {
  653. var timeout = null;
  654. var needExecution = false;
  655. return function throttled () {
  656. if (!timeout) {
  657. needExecution = false;
  658. fn();
  659. timeout = setTimeout(function() {
  660. timeout = null;
  661. if (needExecution) {
  662. throttled();
  663. }
  664. }, wait)
  665. }
  666. else {
  667. needExecution = true;
  668. }
  669. }
  670. };
  671. /**
  672. * Add and event listener. Works for all browsers
  673. * @param {Element} element An html element
  674. * @param {string} action The action, for example "click",
  675. * without the prefix "on"
  676. * @param {function} listener The callback function to be executed
  677. * @param {boolean} [useCapture]
  678. */
  679. exports.addEventListener = function (element, action, listener, useCapture) {
  680. if (element.addEventListener) {
  681. if (useCapture === undefined)
  682. useCapture = false;
  683. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  684. action = "DOMMouseScroll"; // For Firefox
  685. }
  686. element.addEventListener(action, listener, useCapture);
  687. } else {
  688. element.attachEvent("on" + action, listener); // IE browsers
  689. }
  690. };
  691. /**
  692. * Remove an event listener from an element
  693. * @param {Element} element An html dom element
  694. * @param {string} action The name of the event, for example "mousedown"
  695. * @param {function} listener The listener function
  696. * @param {boolean} [useCapture]
  697. */
  698. exports.removeEventListener = function (element, action, listener, useCapture) {
  699. if (element.removeEventListener) {
  700. // non-IE browsers
  701. if (useCapture === undefined)
  702. useCapture = false;
  703. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  704. action = "DOMMouseScroll"; // For Firefox
  705. }
  706. element.removeEventListener(action, listener, useCapture);
  707. } else {
  708. // IE browsers
  709. element.detachEvent("on" + action, listener);
  710. }
  711. };
  712. /**
  713. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  714. */
  715. exports.preventDefault = function (event) {
  716. if (!event)
  717. event = window.event;
  718. if (event.preventDefault) {
  719. event.preventDefault(); // non-IE browsers
  720. }
  721. else {
  722. event.returnValue = false; // IE browsers
  723. }
  724. };
  725. /**
  726. * Get HTML element which is the target of the event
  727. * @param {Event} event
  728. * @return {Element} target element
  729. */
  730. exports.getTarget = function (event) {
  731. // code from http://www.quirksmode.org/js/events_properties.html
  732. if (!event) {
  733. event = window.event;
  734. }
  735. var target;
  736. if (event.target) {
  737. target = event.target;
  738. }
  739. else if (event.srcElement) {
  740. target = event.srcElement;
  741. }
  742. if (target.nodeType != undefined && target.nodeType == 3) {
  743. // defeat Safari bug
  744. target = target.parentNode;
  745. }
  746. return target;
  747. };
  748. /**
  749. * Check if given element contains given parent somewhere in the DOM tree
  750. * @param {Element} element
  751. * @param {Element} parent
  752. */
  753. exports.hasParent = function (element, parent) {
  754. var e = element;
  755. while (e) {
  756. if (e === parent) {
  757. return true;
  758. }
  759. e = e.parentNode;
  760. }
  761. return false;
  762. };
  763. exports.option = {};
  764. /**
  765. * Convert a value into a boolean
  766. * @param {Boolean | function | undefined} value
  767. * @param {Boolean} [defaultValue]
  768. * @returns {Boolean} bool
  769. */
  770. exports.option.asBoolean = function (value, defaultValue) {
  771. if (typeof value == 'function') {
  772. value = value();
  773. }
  774. if (value != null) {
  775. return (value != false);
  776. }
  777. return defaultValue || null;
  778. };
  779. /**
  780. * Convert a value into a number
  781. * @param {Boolean | function | undefined} value
  782. * @param {Number} [defaultValue]
  783. * @returns {Number} number
  784. */
  785. exports.option.asNumber = function (value, defaultValue) {
  786. if (typeof value == 'function') {
  787. value = value();
  788. }
  789. if (value != null) {
  790. return Number(value) || defaultValue || null;
  791. }
  792. return defaultValue || null;
  793. };
  794. /**
  795. * Convert a value into a string
  796. * @param {String | function | undefined} value
  797. * @param {String} [defaultValue]
  798. * @returns {String} str
  799. */
  800. exports.option.asString = function (value, defaultValue) {
  801. if (typeof value == 'function') {
  802. value = value();
  803. }
  804. if (value != null) {
  805. return String(value);
  806. }
  807. return defaultValue || null;
  808. };
  809. /**
  810. * Convert a size or location into a string with pixels or a percentage
  811. * @param {String | Number | function | undefined} value
  812. * @param {String} [defaultValue]
  813. * @returns {String} size
  814. */
  815. exports.option.asSize = function (value, defaultValue) {
  816. if (typeof value == 'function') {
  817. value = value();
  818. }
  819. if (exports.isString(value)) {
  820. return value;
  821. }
  822. else if (exports.isNumber(value)) {
  823. return value + 'px';
  824. }
  825. else {
  826. return defaultValue || null;
  827. }
  828. };
  829. /**
  830. * Convert a value into a DOM element
  831. * @param {HTMLElement | function | undefined} value
  832. * @param {HTMLElement} [defaultValue]
  833. * @returns {HTMLElement | null} dom
  834. */
  835. exports.option.asElement = function (value, defaultValue) {
  836. if (typeof value == 'function') {
  837. value = value();
  838. }
  839. return value || defaultValue || null;
  840. };
  841. /**
  842. * http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
  843. *
  844. * @param {String} hex
  845. * @returns {{r: *, g: *, b: *}} | 255 range
  846. */
  847. exports.hexToRGB = function (hex) {
  848. // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  849. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  850. hex = hex.replace(shorthandRegex, function (m, r, g, b) {
  851. return r + r + g + g + b + b;
  852. });
  853. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  854. return result ? {
  855. r: parseInt(result[1], 16),
  856. g: parseInt(result[2], 16),
  857. b: parseInt(result[3], 16)
  858. } : null;
  859. };
  860. /**
  861. * This function takes color in hex format or rgb() or rgba() format and overrides the opacity. Returns rgba() string.
  862. * @param color
  863. * @param opacity
  864. * @returns {*}
  865. */
  866. exports.overrideOpacity = function (color, opacity) {
  867. if (color.indexOf("rgba") != -1) {
  868. return color;
  869. }
  870. else if (color.indexOf("rgb") != -1) {
  871. var rgb = color.substr(color.indexOf("(") + 1).replace(")", "").split(",");
  872. return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")"
  873. }
  874. else {
  875. var rgb = exports.hexToRGB(color);
  876. if (rgb == null) {
  877. return color;
  878. }
  879. else {
  880. return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + opacity + ")"
  881. }
  882. }
  883. }
  884. /**
  885. *
  886. * @param red 0 -- 255
  887. * @param green 0 -- 255
  888. * @param blue 0 -- 255
  889. * @returns {string}
  890. * @constructor
  891. */
  892. exports.RGBToHex = function (red, green, blue) {
  893. return "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);
  894. };
  895. /**
  896. * Parse a color property into an object with border, background, and
  897. * highlight colors
  898. * @param {Object | String} color
  899. * @return {Object} colorObject
  900. */
  901. exports.parseColor = function (color) {
  902. var c;
  903. if (exports.isString(color) === true) {
  904. if (exports.isValidRGB(color) === true) {
  905. var rgb = color.substr(4).substr(0, color.length - 5).split(',').map(function (value) { return parseInt(value) });
  906. color = exports.RGBToHex(rgb[0], rgb[1], rgb[2]);
  907. }
  908. if (exports.isValidHex(color) === true) {
  909. var hsv = exports.hexToHSV(color);
  910. var lighterColorHSV = { h: hsv.h, s: hsv.s * 0.8, v: Math.min(1, hsv.v * 1.02) };
  911. var darkerColorHSV = { h: hsv.h, s: Math.min(1, hsv.s * 1.25), v: hsv.v * 0.8 };
  912. var darkerColorHex = exports.HSVToHex(darkerColorHSV.h, darkerColorHSV.s, darkerColorHSV.v);
  913. var lighterColorHex = exports.HSVToHex(lighterColorHSV.h, lighterColorHSV.s, lighterColorHSV.v);
  914. c = {
  915. background: color,
  916. border: darkerColorHex,
  917. highlight: {
  918. background: lighterColorHex,
  919. border: darkerColorHex
  920. },
  921. hover: {
  922. background: lighterColorHex,
  923. border: darkerColorHex
  924. }
  925. };
  926. }
  927. else {
  928. c = {
  929. background: color,
  930. border: color,
  931. highlight: {
  932. background: color,
  933. border: color
  934. },
  935. hover: {
  936. background: color,
  937. border: color
  938. }
  939. };
  940. }
  941. }
  942. else {
  943. c = {};
  944. c.background = color.background || undefined;
  945. c.border = color.border || undefined;
  946. if (exports.isString(color.highlight)) {
  947. c.highlight = {
  948. border: color.highlight,
  949. background: color.highlight
  950. }
  951. }
  952. else {
  953. c.highlight = {};
  954. c.highlight.background = color.highlight && color.highlight.background || undefined;
  955. c.highlight.border = color.highlight && color.highlight.border || undefined;
  956. }
  957. if (exports.isString(color.hover)) {
  958. c.hover = {
  959. border: color.hover,
  960. background: color.hover
  961. }
  962. }
  963. else {
  964. c.hover = {};
  965. c.hover.background = color.hover && color.hover.background || undefined;
  966. c.hover.border = color.hover && color.hover.border || undefined;
  967. }
  968. }
  969. return c;
  970. };
  971. /**
  972. * http://www.javascripter.net/faq/rgb2hsv.htm
  973. *
  974. * @param red
  975. * @param green
  976. * @param blue
  977. * @returns {*}
  978. * @constructor
  979. */
  980. exports.RGBToHSV = function (red, green, blue) {
  981. red = red / 255; green = green / 255; blue = blue / 255;
  982. var minRGB = Math.min(red, Math.min(green, blue));
  983. var maxRGB = Math.max(red, Math.max(green, blue));
  984. // Black-gray-white
  985. if (minRGB == maxRGB) {
  986. return { h: 0, s: 0, v: minRGB };
  987. }
  988. // Colors other than black-gray-white:
  989. var d = (red == minRGB) ? green - blue : ((blue == minRGB) ? red - green : blue - red);
  990. var h = (red == minRGB) ? 3 : ((blue == minRGB) ? 1 : 5);
  991. var hue = 60 * (h - d / (maxRGB - minRGB)) / 360;
  992. var saturation = (maxRGB - minRGB) / maxRGB;
  993. var value = maxRGB;
  994. return { h: hue, s: saturation, v: value };
  995. };
  996. var cssUtil = {
  997. // split a string with css styles into an object with key/values
  998. split: function (cssText) {
  999. var styles = {};
  1000. cssText.split(';').forEach(function (style) {
  1001. if (style.trim() != '') {
  1002. var parts = style.split(':');
  1003. var key = parts[0].trim();
  1004. var value = parts[1].trim();
  1005. styles[key] = value;
  1006. }
  1007. });
  1008. return styles;
  1009. },
  1010. // build a css text string from an object with key/values
  1011. join: function (styles) {
  1012. return Object.keys(styles)
  1013. .map(function (key) {
  1014. return key + ': ' + styles[key];
  1015. })
  1016. .join('; ');
  1017. }
  1018. };
  1019. /**
  1020. * Append a string with css styles to an element
  1021. * @param {Element} element
  1022. * @param {String} cssText
  1023. */
  1024. exports.addCssText = function (element, cssText) {
  1025. var currentStyles = cssUtil.split(element.style.cssText);
  1026. var newStyles = cssUtil.split(cssText);
  1027. var styles = exports.extend(currentStyles, newStyles);
  1028. element.style.cssText = cssUtil.join(styles);
  1029. };
  1030. /**
  1031. * Remove a string with css styles from an element
  1032. * @param {Element} element
  1033. * @param {String} cssText
  1034. */
  1035. exports.removeCssText = function (element, cssText) {
  1036. var styles = cssUtil.split(element.style.cssText);
  1037. var removeStyles = cssUtil.split(cssText);
  1038. for (var key in removeStyles) {
  1039. if (removeStyles.hasOwnProperty(key)) {
  1040. delete styles[key];
  1041. }
  1042. }
  1043. element.style.cssText = cssUtil.join(styles);
  1044. };
  1045. /**
  1046. * https://gist.github.com/mjijackson/5311256
  1047. * @param h
  1048. * @param s
  1049. * @param v
  1050. * @returns {{r: number, g: number, b: number}}
  1051. * @constructor
  1052. */
  1053. exports.HSVToRGB = function (h, s, v) {
  1054. var r, g, b;
  1055. var i = Math.floor(h * 6);
  1056. var f = h * 6 - i;
  1057. var p = v * (1 - s);
  1058. var q = v * (1 - f * s);
  1059. var t = v * (1 - (1 - f) * s);
  1060. switch (i % 6) {
  1061. case 0: r = v, g = t, b = p; break;
  1062. case 1: r = q, g = v, b = p; break;
  1063. case 2: r = p, g = v, b = t; break;
  1064. case 3: r = p, g = q, b = v; break;
  1065. case 4: r = t, g = p, b = v; break;
  1066. case 5: r = v, g = p, b = q; break;
  1067. }
  1068. return { r: Math.floor(r * 255), g: Math.floor(g * 255), b: Math.floor(b * 255) };
  1069. };
  1070. exports.HSVToHex = function (h, s, v) {
  1071. var rgb = exports.HSVToRGB(h, s, v);
  1072. return exports.RGBToHex(rgb.r, rgb.g, rgb.b);
  1073. };
  1074. exports.hexToHSV = function (hex) {
  1075. var rgb = exports.hexToRGB(hex);
  1076. return exports.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1077. };
  1078. exports.isValidHex = function (hex) {
  1079. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1080. return isOk;
  1081. };
  1082. exports.isValidRGB = function (rgb) {
  1083. rgb = rgb.replace(" ", "");
  1084. var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb);
  1085. return isOk;
  1086. }
  1087. exports.isValidRGBA = function (rgba) {
  1088. rgba = rgba.replace(" ", "");
  1089. var isOk = /rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(.{1,3})\)/i.test(rgba);
  1090. return isOk;
  1091. }
  1092. /**
  1093. * This recursively redirects the prototype of JSON objects to the referenceObject
  1094. * This is used for default options.
  1095. *
  1096. * @param referenceObject
  1097. * @returns {*}
  1098. */
  1099. exports.selectiveBridgeObject = function (fields, referenceObject) {
  1100. if (typeof referenceObject == "object") {
  1101. var objectTo = Object.create(referenceObject);
  1102. for (var i = 0; i < fields.length; i++) {
  1103. if (referenceObject.hasOwnProperty(fields[i])) {
  1104. if (typeof referenceObject[fields[i]] == "object") {
  1105. objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]);
  1106. }
  1107. }
  1108. }
  1109. return objectTo;
  1110. }
  1111. else {
  1112. return null;
  1113. }
  1114. };
  1115. /**
  1116. * This recursively redirects the prototype of JSON objects to the referenceObject
  1117. * This is used for default options.
  1118. *
  1119. * @param referenceObject
  1120. * @returns {*}
  1121. */
  1122. exports.bridgeObject = function (referenceObject) {
  1123. if (typeof referenceObject == "object") {
  1124. var objectTo = Object.create(referenceObject);
  1125. for (var i in referenceObject) {
  1126. if (referenceObject.hasOwnProperty(i)) {
  1127. if (typeof referenceObject[i] == "object") {
  1128. objectTo[i] = exports.bridgeObject(referenceObject[i]);
  1129. }
  1130. }
  1131. }
  1132. return objectTo;
  1133. }
  1134. else {
  1135. return null;
  1136. }
  1137. };
  1138. /**
  1139. * This method provides a stable sort implementation, very fast for presorted data
  1140. *
  1141. * @param a the array
  1142. * @param a order comparator
  1143. * @returns {the array}
  1144. */
  1145. exports.insertSort = function (a,compare) {
  1146. for (var i = 0; i < a.length; i++) {
  1147. var k = a[i];
  1148. for (var j = i; j > 0 && compare(k,a[j - 1])<0; j--) {
  1149. a[j] = a[j - 1];
  1150. }
  1151. a[j] = k;
  1152. }
  1153. return a;
  1154. }
  1155. /**
  1156. * this is used to set the options of subobjects in the options object. A requirement of these subobjects
  1157. * is that they have an 'enabled' element which is optional for the user but mandatory for the program.
  1158. *
  1159. * @param [object] mergeTarget | this is either this.options or the options used for the groups.
  1160. * @param [object] options | options
  1161. * @param [String] option | this is the option key in the options argument
  1162. */
  1163. exports.mergeOptions = function (mergeTarget, options, option, allowDeletion = false, globalOptions = {}) {
  1164. if (options[option] === null) {
  1165. mergeTarget[option] = Object.create(globalOptions[option]);
  1166. }
  1167. else {
  1168. if (options[option] !== undefined) {
  1169. if (typeof options[option] === 'boolean') {
  1170. mergeTarget[option].enabled = options[option];
  1171. }
  1172. else {
  1173. if (options[option].enabled === undefined) {
  1174. mergeTarget[option].enabled = true;
  1175. }
  1176. for (var prop in options[option]) {
  1177. if (options[option].hasOwnProperty(prop)) {
  1178. mergeTarget[option][prop] = options[option][prop];
  1179. }
  1180. }
  1181. }
  1182. }
  1183. }
  1184. }
  1185. /**
  1186. * This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
  1187. * this function will then iterate in both directions over this sorted list to find all visible items.
  1188. *
  1189. * @param {Item[]} orderedItems | Items ordered by start
  1190. * @param {function} comparator | -1 is lower, 0 is equal, 1 is higher
  1191. * @param {String} field
  1192. * @param {String} field2
  1193. * @returns {number}
  1194. * @private
  1195. */
  1196. exports.binarySearchCustom = function (orderedItems, comparator, field, field2) {
  1197. var maxIterations = 10000;
  1198. var iteration = 0;
  1199. var low = 0;
  1200. var high = orderedItems.length - 1;
  1201. while (low <= high && iteration < maxIterations) {
  1202. var middle = Math.floor((low + high) / 2);
  1203. var item = orderedItems[middle];
  1204. var value = (field2 === undefined) ? item[field] : item[field][field2];
  1205. var searchResult = comparator(value);
  1206. if (searchResult == 0) { // jihaa, found a visible item!
  1207. return middle;
  1208. }
  1209. else if (searchResult == -1) { // it is too small --> increase low
  1210. low = middle + 1;
  1211. }
  1212. else { // it is too big --> decrease high
  1213. high = middle - 1;
  1214. }
  1215. iteration++;
  1216. }
  1217. return -1;
  1218. };
  1219. /**
  1220. * This function does a binary search for a specific value in a sorted array. If it does not exist but is in between of
  1221. * two values, we return either the one before or the one after, depending on user input
  1222. * If it is found, we return the index, else -1.
  1223. *
  1224. * @param {Array} orderedItems
  1225. * @param {{start: number, end: number}} target
  1226. * @param {String} field
  1227. * @param {String} sidePreference 'before' or 'after'
  1228. * @param {function} comparator an optional comparator, returning -1,0,1 for <,==,>.
  1229. * @returns {number}
  1230. * @private
  1231. */
  1232. exports.binarySearchValue = function (orderedItems, target, field, sidePreference, comparator) {
  1233. var maxIterations = 10000;
  1234. var iteration = 0;
  1235. var low = 0;
  1236. var high = orderedItems.length - 1;
  1237. var prevValue, value, nextValue, middle;
  1238. var comparator = comparator != undefined ? comparator : function (a, b) {
  1239. return a == b ? 0 : a < b ? -1 : 1
  1240. };
  1241. while (low <= high && iteration < maxIterations) {
  1242. // get a new guess
  1243. middle = Math.floor(0.5 * (high + low));
  1244. prevValue = orderedItems[Math.max(0, middle - 1)][field];
  1245. value = orderedItems[middle][field];
  1246. nextValue = orderedItems[Math.min(orderedItems.length - 1, middle + 1)][field];
  1247. if (comparator(value, target) == 0) { // we found the target
  1248. return middle;
  1249. }
  1250. else if (comparator(prevValue, target) < 0 && comparator(value, target) > 0) { // target is in between of the previous and the current
  1251. return sidePreference == 'before' ? Math.max(0, middle - 1) : middle;
  1252. }
  1253. else if (comparator(value, target) < 0 && comparator(nextValue, target) > 0) { // target is in between of the current and the next
  1254. return sidePreference == 'before' ? middle : Math.min(orderedItems.length - 1, middle + 1);
  1255. }
  1256. else { // didnt find the target, we need to change our boundaries.
  1257. if (comparator(value, target) < 0) { // it is too small --> increase low
  1258. low = middle + 1;
  1259. }
  1260. else { // it is too big --> decrease high
  1261. high = middle - 1;
  1262. }
  1263. }
  1264. iteration++;
  1265. }
  1266. // didnt find anything. Return -1.
  1267. return -1;
  1268. };
  1269. /*
  1270. * Easing Functions - inspired from http://gizma.com/easing/
  1271. * only considering the t value for the range [0, 1] => [0, 1]
  1272. * https://gist.github.com/gre/1650294
  1273. */
  1274. exports.easingFunctions = {
  1275. // no easing, no acceleration
  1276. linear: function (t) {
  1277. return t
  1278. },
  1279. // accelerating from zero velocity
  1280. easeInQuad: function (t) {
  1281. return t * t
  1282. },
  1283. // decelerating to zero velocity
  1284. easeOutQuad: function (t) {
  1285. return t * (2 - t)
  1286. },
  1287. // acceleration until halfway, then deceleration
  1288. easeInOutQuad: function (t) {
  1289. return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t
  1290. },
  1291. // accelerating from zero velocity
  1292. easeInCubic: function (t) {
  1293. return t * t * t
  1294. },
  1295. // decelerating to zero velocity
  1296. easeOutCubic: function (t) {
  1297. return (--t) * t * t + 1
  1298. },
  1299. // acceleration until halfway, then deceleration
  1300. easeInOutCubic: function (t) {
  1301. return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
  1302. },
  1303. // accelerating from zero velocity
  1304. easeInQuart: function (t) {
  1305. return t * t * t * t
  1306. },
  1307. // decelerating to zero velocity
  1308. easeOutQuart: function (t) {
  1309. return 1 - (--t) * t * t * t
  1310. },
  1311. // acceleration until halfway, then deceleration
  1312. easeInOutQuart: function (t) {
  1313. return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t
  1314. },
  1315. // accelerating from zero velocity
  1316. easeInQuint: function (t) {
  1317. return t * t * t * t * t
  1318. },
  1319. // decelerating to zero velocity
  1320. easeOutQuint: function (t) {
  1321. return 1 + (--t) * t * t * t * t
  1322. },
  1323. // acceleration until halfway, then deceleration
  1324. easeInOutQuint: function (t) {
  1325. return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t
  1326. }
  1327. };