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.

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