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.

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