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.

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