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.

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