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.

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