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.

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