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.

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