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.

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