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.

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