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.

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