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.

1362 lines
35 KiB

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