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.

1273 lines
33 KiB

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