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.

35664 lines
1.1 MiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 3.12.0
  8. * @date 2015-04-07
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Vis.js is dual licensed under both
  14. *
  15. * * The Apache 2.0 License
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * and
  19. *
  20. * * The MIT License
  21. * http://opensource.org/licenses/MIT
  22. *
  23. * Vis.js may be distributed under either license.
  24. */
  25. "use strict";
  26. (function webpackUniversalModuleDefinition(root, factory) {
  27. if(typeof exports === 'object' && typeof module === 'object')
  28. module.exports = factory();
  29. else if(typeof define === 'function' && define.amd)
  30. define(factory);
  31. else if(typeof exports === 'object')
  32. exports["vis"] = factory();
  33. else
  34. root["vis"] = factory();
  35. })(this, function() {
  36. return /******/ (function(modules) { // webpackBootstrap
  37. /******/ // The module cache
  38. /******/ var installedModules = {};
  39. /******/ // The require function
  40. /******/ function __webpack_require__(moduleId) {
  41. /******/ // Check if module is in cache
  42. /******/ if(installedModules[moduleId])
  43. /******/ return installedModules[moduleId].exports;
  44. /******/ // Create a new module (and put it into the cache)
  45. /******/ var module = installedModules[moduleId] = {
  46. /******/ exports: {},
  47. /******/ id: moduleId,
  48. /******/ loaded: false
  49. /******/ };
  50. /******/ // Execute the module function
  51. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  52. /******/ // Flag the module as loaded
  53. /******/ module.loaded = true;
  54. /******/ // Return the exports of the module
  55. /******/ return module.exports;
  56. /******/ }
  57. /******/ // expose the modules object (__webpack_modules__)
  58. /******/ __webpack_require__.m = modules;
  59. /******/ // expose the module cache
  60. /******/ __webpack_require__.c = installedModules;
  61. /******/ // __webpack_public_path__
  62. /******/ __webpack_require__.p = "";
  63. /******/ // Load entry module and return exports
  64. /******/ return __webpack_require__(0);
  65. /******/ })
  66. /************************************************************************/
  67. /******/ ([
  68. /* 0 */
  69. /***/ function(module, exports, __webpack_require__) {
  70. // utils
  71. exports.util = __webpack_require__(1);
  72. exports.DOMutil = __webpack_require__(2);
  73. // data
  74. exports.DataSet = __webpack_require__(3);
  75. exports.DataView = __webpack_require__(4);
  76. exports.Queue = __webpack_require__(5);
  77. // Graph3d
  78. exports.Graph3d = __webpack_require__(6);
  79. exports.graph3d = {
  80. Camera: __webpack_require__(7),
  81. Filter: __webpack_require__(8),
  82. Point2d: __webpack_require__(9),
  83. Point3d: __webpack_require__(10),
  84. Slider: __webpack_require__(11),
  85. StepNumber: __webpack_require__(12)
  86. };
  87. // Timeline
  88. exports.Timeline = __webpack_require__(13);
  89. exports.Graph2d = __webpack_require__(14);
  90. exports.timeline = {
  91. DateUtil: __webpack_require__(15),
  92. DataStep: __webpack_require__(16),
  93. Range: __webpack_require__(17),
  94. stack: __webpack_require__(18),
  95. TimeStep: __webpack_require__(19),
  96. components: {
  97. items: {
  98. Item: __webpack_require__(20),
  99. BackgroundItem: __webpack_require__(21),
  100. BoxItem: __webpack_require__(22),
  101. PointItem: __webpack_require__(23),
  102. RangeItem: __webpack_require__(24)
  103. },
  104. Component: __webpack_require__(25),
  105. CurrentTime: __webpack_require__(26),
  106. CustomTime: __webpack_require__(27),
  107. DataAxis: __webpack_require__(28),
  108. GraphGroup: __webpack_require__(29),
  109. Group: __webpack_require__(30),
  110. BackgroundGroup: __webpack_require__(31),
  111. ItemSet: __webpack_require__(32),
  112. Legend: __webpack_require__(33),
  113. LineGraph: __webpack_require__(34),
  114. TimeAxis: __webpack_require__(35)
  115. }
  116. };
  117. // Network
  118. exports.Network = __webpack_require__(36);
  119. exports.network = {
  120. Edge: __webpack_require__(37),
  121. Groups: __webpack_require__(38),
  122. Images: __webpack_require__(39),
  123. Node: __webpack_require__(40),
  124. Popup: __webpack_require__(41),
  125. dotparser: __webpack_require__(42),
  126. gephiParser: __webpack_require__(43)
  127. };
  128. // Deprecated since v3.0.0
  129. exports.Graph = function () {
  130. throw new Error('Graph is renamed to Network. Please create a graph as new vis.Network(...)');
  131. };
  132. // bundled external libraries
  133. exports.moment = __webpack_require__(44);
  134. exports.hammer = __webpack_require__(45);
  135. /***/ },
  136. /* 1 */
  137. /***/ function(module, exports, __webpack_require__) {
  138. // utility functions
  139. // first check if moment.js is already loaded in the browser window, if so,
  140. // use this instance. Else, load via commonjs.
  141. var moment = __webpack_require__(44);
  142. /**
  143. * Test whether given object is a number
  144. * @param {*} object
  145. * @return {Boolean} isNumber
  146. */
  147. exports.isNumber = function(object) {
  148. return (object instanceof Number || typeof object == 'number');
  149. };
  150. /**
  151. * 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.
  152. *
  153. * @param min
  154. * @param max
  155. * @param total
  156. * @param value
  157. * @returns {number}
  158. */
  159. exports.giveRange = function(min,max,total,value) {
  160. if (max == min) {
  161. return 0.5;
  162. }
  163. else {
  164. var scale = 1 / (max - min);
  165. return Math.max(0,(value - min)*scale);
  166. }
  167. }
  168. /**
  169. * Test whether given object is a string
  170. * @param {*} object
  171. * @return {Boolean} isString
  172. */
  173. exports.isString = function(object) {
  174. return (object instanceof String || typeof object == 'string');
  175. };
  176. /**
  177. * Test whether given object is a Date, or a String containing a Date
  178. * @param {Date | String} object
  179. * @return {Boolean} isDate
  180. */
  181. exports.isDate = function(object) {
  182. if (object instanceof Date) {
  183. return true;
  184. }
  185. else if (exports.isString(object)) {
  186. // test whether this string contains a date
  187. var match = ASPDateRegex.exec(object);
  188. if (match) {
  189. return true;
  190. }
  191. else if (!isNaN(Date.parse(object))) {
  192. return true;
  193. }
  194. }
  195. return false;
  196. };
  197. /**
  198. * Test whether given object is an instance of google.visualization.DataTable
  199. * @param {*} object
  200. * @return {Boolean} isDataTable
  201. */
  202. exports.isDataTable = function(object) {
  203. return (typeof (google) !== 'undefined') &&
  204. (google.visualization) &&
  205. (google.visualization.DataTable) &&
  206. (object instanceof google.visualization.DataTable);
  207. };
  208. /**
  209. * Create a semi UUID
  210. * source: http://stackoverflow.com/a/105074/1262753
  211. * @return {String} uuid
  212. */
  213. exports.randomUUID = function() {
  214. var S4 = function () {
  215. return Math.floor(
  216. Math.random() * 0x10000 /* 65536 */
  217. ).toString(16);
  218. };
  219. return (
  220. S4() + S4() + '-' +
  221. S4() + '-' +
  222. S4() + '-' +
  223. S4() + '-' +
  224. S4() + S4() + S4()
  225. );
  226. };
  227. /**
  228. * Extend object a with the properties of object b or a series of objects
  229. * Only properties with defined values are copied
  230. * @param {Object} a
  231. * @param {... Object} b
  232. * @return {Object} a
  233. */
  234. exports.extend = function (a, b) {
  235. for (var i = 1, len = arguments.length; i < len; i++) {
  236. var other = arguments[i];
  237. for (var prop in other) {
  238. if (other.hasOwnProperty(prop)) {
  239. a[prop] = other[prop];
  240. }
  241. }
  242. }
  243. return a;
  244. };
  245. /**
  246. * Extend object a with selected properties of object b or a series of objects
  247. * Only properties with defined values are copied
  248. * @param {Array.<String>} props
  249. * @param {Object} a
  250. * @param {... Object} b
  251. * @return {Object} a
  252. */
  253. exports.selectiveExtend = function (props, a, b) {
  254. if (!Array.isArray(props)) {
  255. throw new Error('Array with property names expected as first argument');
  256. }
  257. for (var i = 2; i < arguments.length; i++) {
  258. var other = arguments[i];
  259. for (var p = 0; p < props.length; p++) {
  260. var prop = props[p];
  261. if (other.hasOwnProperty(prop)) {
  262. a[prop] = other[prop];
  263. }
  264. }
  265. }
  266. return a;
  267. };
  268. /**
  269. * Extend object a with selected properties of object b or a series of objects
  270. * Only properties with defined values are copied
  271. * @param {Array.<String>} props
  272. * @param {Object} a
  273. * @param {... Object} b
  274. * @return {Object} a
  275. */
  276. exports.selectiveDeepExtend = function (props, a, b) {
  277. // TODO: add support for Arrays to deepExtend
  278. if (Array.isArray(b)) {
  279. throw new TypeError('Arrays are not supported by deepExtend');
  280. }
  281. for (var i = 2; i < arguments.length; i++) {
  282. var other = arguments[i];
  283. for (var p = 0; p < props.length; p++) {
  284. var prop = props[p];
  285. if (other.hasOwnProperty(prop)) {
  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]);
  292. }
  293. else {
  294. a[prop] = b[prop];
  295. }
  296. } else if (Array.isArray(b[prop])) {
  297. throw new TypeError('Arrays are not supported by deepExtend');
  298. } else {
  299. a[prop] = b[prop];
  300. }
  301. }
  302. }
  303. }
  304. return a;
  305. };
  306. /**
  307. * Extend object a with selected properties of object b or a series of objects
  308. * Only properties with defined values are copied
  309. * @param {Array.<String>} props
  310. * @param {Object} a
  311. * @param {... Object} b
  312. * @return {Object} a
  313. */
  314. exports.selectiveNotDeepExtend = function (props, a, b) {
  315. // TODO: add support for Arrays to deepExtend
  316. if (Array.isArray(b)) {
  317. throw new TypeError('Arrays are not supported by deepExtend');
  318. }
  319. for (var prop in b) {
  320. if (b.hasOwnProperty(prop)) {
  321. if (props.indexOf(prop) == -1) {
  322. if (b[prop] && b[prop].constructor === Object) {
  323. if (a[prop] === undefined) {
  324. a[prop] = {};
  325. }
  326. if (a[prop].constructor === Object) {
  327. exports.deepExtend(a[prop], b[prop]);
  328. }
  329. else {
  330. a[prop] = b[prop];
  331. }
  332. } else if (Array.isArray(b[prop])) {
  333. throw new TypeError('Arrays are not supported by deepExtend');
  334. } else {
  335. a[prop] = b[prop];
  336. }
  337. }
  338. }
  339. }
  340. return a;
  341. };
  342. /**
  343. * Deep extend an object a with the properties of object b
  344. * @param {Object} a
  345. * @param {Object} b
  346. * @returns {Object}
  347. */
  348. exports.deepExtend = function(a, b) {
  349. // TODO: add support for Arrays to deepExtend
  350. if (Array.isArray(b)) {
  351. throw new TypeError('Arrays are not supported by deepExtend');
  352. }
  353. for (var prop in b) {
  354. if (b.hasOwnProperty(prop)) {
  355. if (b[prop] && b[prop].constructor === Object) {
  356. if (a[prop] === undefined) {
  357. a[prop] = {};
  358. }
  359. if (a[prop].constructor === Object) {
  360. exports.deepExtend(a[prop], b[prop]);
  361. }
  362. else {
  363. a[prop] = b[prop];
  364. }
  365. } else if (Array.isArray(b[prop])) {
  366. throw new TypeError('Arrays are not supported by deepExtend');
  367. } else {
  368. a[prop] = b[prop];
  369. }
  370. }
  371. }
  372. return a;
  373. };
  374. /**
  375. * Test whether all elements in two arrays are equal.
  376. * @param {Array} a
  377. * @param {Array} b
  378. * @return {boolean} Returns true if both arrays have the same length and same
  379. * elements.
  380. */
  381. exports.equalArray = function (a, b) {
  382. if (a.length != b.length) return false;
  383. for (var i = 0, len = a.length; i < len; i++) {
  384. if (a[i] != b[i]) return false;
  385. }
  386. return true;
  387. };
  388. /**
  389. * Convert an object to another type
  390. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  391. * @param {String | undefined} type Name of the type. Available types:
  392. * 'Boolean', 'Number', 'String',
  393. * 'Date', 'Moment', ISODate', 'ASPDate'.
  394. * @return {*} object
  395. * @throws Error
  396. */
  397. exports.convert = function(object, type) {
  398. var match;
  399. if (object === undefined) {
  400. return undefined;
  401. }
  402. if (object === null) {
  403. return null;
  404. }
  405. if (!type) {
  406. return object;
  407. }
  408. if (!(typeof type === 'string') && !(type instanceof String)) {
  409. throw new Error('Type must be a string');
  410. }
  411. //noinspection FallthroughInSwitchStatementJS
  412. switch (type) {
  413. case 'boolean':
  414. case 'Boolean':
  415. return Boolean(object);
  416. case 'number':
  417. case 'Number':
  418. return Number(object.valueOf());
  419. case 'string':
  420. case 'String':
  421. return String(object);
  422. case 'Date':
  423. if (exports.isNumber(object)) {
  424. return new Date(object);
  425. }
  426. if (object instanceof Date) {
  427. return new Date(object.valueOf());
  428. }
  429. else if (moment.isMoment(object)) {
  430. return new Date(object.valueOf());
  431. }
  432. if (exports.isString(object)) {
  433. match = ASPDateRegex.exec(object);
  434. if (match) {
  435. // object is an ASP date
  436. return new Date(Number(match[1])); // parse number
  437. }
  438. else {
  439. return moment(object).toDate(); // parse string
  440. }
  441. }
  442. else {
  443. throw new Error(
  444. 'Cannot convert object of type ' + exports.getType(object) +
  445. ' to type Date');
  446. }
  447. case 'Moment':
  448. if (exports.isNumber(object)) {
  449. return moment(object);
  450. }
  451. if (object instanceof Date) {
  452. return moment(object.valueOf());
  453. }
  454. else if (moment.isMoment(object)) {
  455. return moment(object);
  456. }
  457. if (exports.isString(object)) {
  458. match = ASPDateRegex.exec(object);
  459. if (match) {
  460. // object is an ASP date
  461. return moment(Number(match[1])); // parse number
  462. }
  463. else {
  464. return moment(object); // parse string
  465. }
  466. }
  467. else {
  468. throw new Error(
  469. 'Cannot convert object of type ' + exports.getType(object) +
  470. ' to type Date');
  471. }
  472. case 'ISODate':
  473. if (exports.isNumber(object)) {
  474. return new Date(object);
  475. }
  476. else if (object instanceof Date) {
  477. return object.toISOString();
  478. }
  479. else if (moment.isMoment(object)) {
  480. return object.toDate().toISOString();
  481. }
  482. else if (exports.isString(object)) {
  483. match = ASPDateRegex.exec(object);
  484. if (match) {
  485. // object is an ASP date
  486. return new Date(Number(match[1])).toISOString(); // parse number
  487. }
  488. else {
  489. return new Date(object).toISOString(); // parse string
  490. }
  491. }
  492. else {
  493. throw new Error(
  494. 'Cannot convert object of type ' + exports.getType(object) +
  495. ' to type ISODate');
  496. }
  497. case 'ASPDate':
  498. if (exports.isNumber(object)) {
  499. return '/Date(' + object + ')/';
  500. }
  501. else if (object instanceof Date) {
  502. return '/Date(' + object.valueOf() + ')/';
  503. }
  504. else if (exports.isString(object)) {
  505. match = ASPDateRegex.exec(object);
  506. var value;
  507. if (match) {
  508. // object is an ASP date
  509. value = new Date(Number(match[1])).valueOf(); // parse number
  510. }
  511. else {
  512. value = new Date(object).valueOf(); // parse string
  513. }
  514. return '/Date(' + value + ')/';
  515. }
  516. else {
  517. throw new Error(
  518. 'Cannot convert object of type ' + exports.getType(object) +
  519. ' to type ASPDate');
  520. }
  521. default:
  522. throw new Error('Unknown type "' + type + '"');
  523. }
  524. };
  525. // parse ASP.Net Date pattern,
  526. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  527. // code from http://momentjs.com/
  528. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  529. /**
  530. * Get the type of an object, for example exports.getType([]) returns 'Array'
  531. * @param {*} object
  532. * @return {String} type
  533. */
  534. exports.getType = function(object) {
  535. var type = typeof object;
  536. if (type == 'object') {
  537. if (object == null) {
  538. return 'null';
  539. }
  540. if (object instanceof Boolean) {
  541. return 'Boolean';
  542. }
  543. if (object instanceof Number) {
  544. return 'Number';
  545. }
  546. if (object instanceof String) {
  547. return 'String';
  548. }
  549. if (Array.isArray(object)) {
  550. return 'Array';
  551. }
  552. if (object instanceof Date) {
  553. return 'Date';
  554. }
  555. return 'Object';
  556. }
  557. else if (type == 'number') {
  558. return 'Number';
  559. }
  560. else if (type == 'boolean') {
  561. return 'Boolean';
  562. }
  563. else if (type == 'string') {
  564. return 'String';
  565. }
  566. return type;
  567. };
  568. /**
  569. * Retrieve the absolute left value of a DOM element
  570. * @param {Element} elem A dom element, for example a div
  571. * @return {number} left The absolute left position of this element
  572. * in the browser page.
  573. */
  574. exports.getAbsoluteLeft = function(elem) {
  575. return elem.getBoundingClientRect().left + window.pageXOffset;
  576. };
  577. /**
  578. * Retrieve the absolute top value of a DOM element
  579. * @param {Element} elem A dom element, for example a div
  580. * @return {number} top The absolute top position of this element
  581. * in the browser page.
  582. */
  583. exports.getAbsoluteTop = function(elem) {
  584. return elem.getBoundingClientRect().top + window.pageYOffset;
  585. };
  586. /**
  587. * add a className to the given elements style
  588. * @param {Element} elem
  589. * @param {String} className
  590. */
  591. exports.addClassName = function(elem, className) {
  592. var classes = elem.className.split(' ');
  593. if (classes.indexOf(className) == -1) {
  594. classes.push(className); // add the class to the array
  595. elem.className = classes.join(' ');
  596. }
  597. };
  598. /**
  599. * add a className to the given elements style
  600. * @param {Element} elem
  601. * @param {String} className
  602. */
  603. exports.removeClassName = function(elem, className) {
  604. var classes = elem.className.split(' ');
  605. var index = classes.indexOf(className);
  606. if (index != -1) {
  607. classes.splice(index, 1); // remove the class from the array
  608. elem.className = classes.join(' ');
  609. }
  610. };
  611. /**
  612. * For each method for both arrays and objects.
  613. * In case of an array, the built-in Array.forEach() is applied.
  614. * In case of an Object, the method loops over all properties of the object.
  615. * @param {Object | Array} object An Object or Array
  616. * @param {function} callback Callback method, called for each item in
  617. * the object or array with three parameters:
  618. * callback(value, index, object)
  619. */
  620. exports.forEach = function(object, callback) {
  621. var i,
  622. len;
  623. if (Array.isArray(object)) {
  624. // array
  625. for (i = 0, len = object.length; i < len; i++) {
  626. callback(object[i], i, object);
  627. }
  628. }
  629. else {
  630. // object
  631. for (i in object) {
  632. if (object.hasOwnProperty(i)) {
  633. callback(object[i], i, object);
  634. }
  635. }
  636. }
  637. };
  638. /**
  639. * Convert an object into an array: all objects properties are put into the
  640. * array. The resulting array is unordered.
  641. * @param {Object} object
  642. * @param {Array} array
  643. */
  644. exports.toArray = function(object) {
  645. var array = [];
  646. for (var prop in object) {
  647. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  648. }
  649. return array;
  650. }
  651. /**
  652. * Update a property in an object
  653. * @param {Object} object
  654. * @param {String} key
  655. * @param {*} value
  656. * @return {Boolean} changed
  657. */
  658. exports.updateProperty = function(object, key, value) {
  659. if (object[key] !== value) {
  660. object[key] = value;
  661. return true;
  662. }
  663. else {
  664. return false;
  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("rgb") != -1) {
  864. var rgb = color.substr(color.indexOf("(")+1).replace(")","").split(",");
  865. return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")"
  866. }
  867. else {
  868. var rgb = exports.hexToRGB(color);
  869. if (rgb == null) {
  870. return color;
  871. }
  872. else {
  873. return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + opacity + ")"
  874. }
  875. }
  876. }
  877. /**
  878. *
  879. * @param red 0 -- 255
  880. * @param green 0 -- 255
  881. * @param blue 0 -- 255
  882. * @returns {string}
  883. * @constructor
  884. */
  885. exports.RGBToHex = function(red,green,blue) {
  886. return "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);
  887. };
  888. /**
  889. * Parse a color property into an object with border, background, and
  890. * highlight colors
  891. * @param {Object | String} color
  892. * @return {Object} colorObject
  893. */
  894. exports.parseColor = function(color) {
  895. var c;
  896. if (exports.isString(color)) {
  897. if (exports.isValidRGB(color)) {
  898. var rgb = color.substr(4).substr(0,color.length-5).split(',');
  899. color = exports.RGBToHex(rgb[0],rgb[1],rgb[2]);
  900. }
  901. if (exports.isValidHex(color)) {
  902. var hsv = exports.hexToHSV(color);
  903. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  904. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  905. var darkerColorHex = exports.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  906. var lighterColorHex = exports.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  907. c = {
  908. background: color,
  909. border:darkerColorHex,
  910. highlight: {
  911. background:lighterColorHex,
  912. border:darkerColorHex
  913. },
  914. hover: {
  915. background:lighterColorHex,
  916. border:darkerColorHex
  917. }
  918. };
  919. }
  920. else {
  921. c = {
  922. background:color,
  923. border:color,
  924. highlight: {
  925. background:color,
  926. border:color
  927. },
  928. hover: {
  929. background:color,
  930. border:color
  931. }
  932. };
  933. }
  934. }
  935. else {
  936. c = {};
  937. c.background = color.background || 'white';
  938. c.border = color.border || c.background;
  939. if (exports.isString(color.highlight)) {
  940. c.highlight = {
  941. border: color.highlight,
  942. background: color.highlight
  943. }
  944. }
  945. else {
  946. c.highlight = {};
  947. c.highlight.background = color.highlight && color.highlight.background || c.background;
  948. c.highlight.border = color.highlight && color.highlight.border || c.border;
  949. }
  950. if (exports.isString(color.hover)) {
  951. c.hover = {
  952. border: color.hover,
  953. background: color.hover
  954. }
  955. }
  956. else {
  957. c.hover = {};
  958. c.hover.background = color.hover && color.hover.background || c.background;
  959. c.hover.border = color.hover && color.hover.border || c.border;
  960. }
  961. }
  962. return c;
  963. };
  964. /**
  965. * http://www.javascripter.net/faq/rgb2hsv.htm
  966. *
  967. * @param red
  968. * @param green
  969. * @param blue
  970. * @returns {*}
  971. * @constructor
  972. */
  973. exports.RGBToHSV = function(red,green,blue) {
  974. red=red/255; green=green/255; blue=blue/255;
  975. var minRGB = Math.min(red,Math.min(green,blue));
  976. var maxRGB = Math.max(red,Math.max(green,blue));
  977. // Black-gray-white
  978. if (minRGB == maxRGB) {
  979. return {h:0,s:0,v:minRGB};
  980. }
  981. // Colors other than black-gray-white:
  982. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  983. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  984. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  985. var saturation = (maxRGB - minRGB)/maxRGB;
  986. var value = maxRGB;
  987. return {h:hue,s:saturation,v:value};
  988. };
  989. var cssUtil = {
  990. // split a string with css styles into an object with key/values
  991. split: function (cssText) {
  992. var styles = {};
  993. cssText.split(';').forEach(function (style) {
  994. if (style.trim() != '') {
  995. var parts = style.split(':');
  996. var key = parts[0].trim();
  997. var value = parts[1].trim();
  998. styles[key] = value;
  999. }
  1000. });
  1001. return styles;
  1002. },
  1003. // build a css text string from an object with key/values
  1004. join: function (styles) {
  1005. return Object.keys(styles)
  1006. .map(function (key) {
  1007. return key + ': ' + styles[key];
  1008. })
  1009. .join('; ');
  1010. }
  1011. };
  1012. /**
  1013. * Append a string with css styles to an element
  1014. * @param {Element} element
  1015. * @param {String} cssText
  1016. */
  1017. exports.addCssText = function (element, cssText) {
  1018. var currentStyles = cssUtil.split(element.style.cssText);
  1019. var newStyles = cssUtil.split(cssText);
  1020. var styles = exports.extend(currentStyles, newStyles);
  1021. element.style.cssText = cssUtil.join(styles);
  1022. };
  1023. /**
  1024. * Remove a string with css styles from an element
  1025. * @param {Element} element
  1026. * @param {String} cssText
  1027. */
  1028. exports.removeCssText = function (element, cssText) {
  1029. var styles = cssUtil.split(element.style.cssText);
  1030. var removeStyles = cssUtil.split(cssText);
  1031. for (var key in removeStyles) {
  1032. if (removeStyles.hasOwnProperty(key)) {
  1033. delete styles[key];
  1034. }
  1035. }
  1036. element.style.cssText = cssUtil.join(styles);
  1037. };
  1038. /**
  1039. * https://gist.github.com/mjijackson/5311256
  1040. * @param h
  1041. * @param s
  1042. * @param v
  1043. * @returns {{r: number, g: number, b: number}}
  1044. * @constructor
  1045. */
  1046. exports.HSVToRGB = function(h, s, v) {
  1047. var r, g, b;
  1048. var i = Math.floor(h * 6);
  1049. var f = h * 6 - i;
  1050. var p = v * (1 - s);
  1051. var q = v * (1 - f * s);
  1052. var t = v * (1 - (1 - f) * s);
  1053. switch (i % 6) {
  1054. case 0: r = v, g = t, b = p; break;
  1055. case 1: r = q, g = v, b = p; break;
  1056. case 2: r = p, g = v, b = t; break;
  1057. case 3: r = p, g = q, b = v; break;
  1058. case 4: r = t, g = p, b = v; break;
  1059. case 5: r = v, g = p, b = q; break;
  1060. }
  1061. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1062. };
  1063. exports.HSVToHex = function(h, s, v) {
  1064. var rgb = exports.HSVToRGB(h, s, v);
  1065. return exports.RGBToHex(rgb.r, rgb.g, rgb.b);
  1066. };
  1067. exports.hexToHSV = function(hex) {
  1068. var rgb = exports.hexToRGB(hex);
  1069. return exports.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1070. };
  1071. exports.isValidHex = function(hex) {
  1072. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1073. return isOk;
  1074. };
  1075. exports.isValidRGB = function(rgb) {
  1076. rgb = rgb.replace(" ","");
  1077. var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb);
  1078. return isOk;
  1079. }
  1080. /**
  1081. * This recursively redirects the prototype of JSON objects to the referenceObject
  1082. * This is used for default options.
  1083. *
  1084. * @param referenceObject
  1085. * @returns {*}
  1086. */
  1087. exports.selectiveBridgeObject = function(fields, referenceObject) {
  1088. if (typeof referenceObject == "object") {
  1089. var objectTo = Object.create(referenceObject);
  1090. for (var i = 0; i < fields.length; i++) {
  1091. if (referenceObject.hasOwnProperty(fields[i])) {
  1092. if (typeof referenceObject[fields[i]] == "object") {
  1093. objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]);
  1094. }
  1095. }
  1096. }
  1097. return objectTo;
  1098. }
  1099. else {
  1100. return null;
  1101. }
  1102. };
  1103. /**
  1104. * This recursively redirects the prototype of JSON objects to the referenceObject
  1105. * This is used for default options.
  1106. *
  1107. * @param referenceObject
  1108. * @returns {*}
  1109. */
  1110. exports.bridgeObject = function(referenceObject) {
  1111. if (typeof referenceObject == "object") {
  1112. var objectTo = Object.create(referenceObject);
  1113. for (var i in referenceObject) {
  1114. if (referenceObject.hasOwnProperty(i)) {
  1115. if (typeof referenceObject[i] == "object") {
  1116. objectTo[i] = exports.bridgeObject(referenceObject[i]);
  1117. }
  1118. }
  1119. }
  1120. return objectTo;
  1121. }
  1122. else {
  1123. return null;
  1124. }
  1125. };
  1126. /**
  1127. * this is used to set the options of subobjects in the options object. A requirement of these subobjects
  1128. * is that they have an 'enabled' element which is optional for the user but mandatory for the program.
  1129. *
  1130. * @param [object] mergeTarget | this is either this.options or the options used for the groups.
  1131. * @param [object] options | options
  1132. * @param [String] option | this is the option key in the options argument
  1133. * @private
  1134. */
  1135. exports.mergeOptions = function (mergeTarget, options, option) {
  1136. if (options[option] !== undefined) {
  1137. if (typeof options[option] == 'boolean') {
  1138. mergeTarget[option].enabled = options[option];
  1139. }
  1140. else {
  1141. mergeTarget[option].enabled = true;
  1142. for (var prop in options[option]) {
  1143. if (options[option].hasOwnProperty(prop)) {
  1144. mergeTarget[option][prop] = options[option][prop];
  1145. }
  1146. }
  1147. }
  1148. }
  1149. }
  1150. /**
  1151. * This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
  1152. * this function will then iterate in both directions over this sorted list to find all visible items.
  1153. *
  1154. * @param {Item[]} orderedItems | Items ordered by start
  1155. * @param {function} searchFunction | -1 is lower, 0 is found, 1 is higher
  1156. * @param {String} field
  1157. * @param {String} field2
  1158. * @returns {number}
  1159. * @private
  1160. */
  1161. exports.binarySearchCustom = function(orderedItems, searchFunction, field, field2) {
  1162. var maxIterations = 10000;
  1163. var iteration = 0;
  1164. var low = 0;
  1165. var high = orderedItems.length - 1;
  1166. while (low <= high && iteration < maxIterations) {
  1167. var middle = Math.floor((low + high) / 2);
  1168. var item = orderedItems[middle];
  1169. var value = (field2 === undefined) ? item[field] : item[field][field2];
  1170. var searchResult = searchFunction(value);
  1171. if (searchResult == 0) { // jihaa, found a visible item!
  1172. return middle;
  1173. }
  1174. else if (searchResult == -1) { // it is too small --> increase low
  1175. low = middle + 1;
  1176. }
  1177. else { // it is too big --> decrease high
  1178. high = middle - 1;
  1179. }
  1180. iteration++;
  1181. }
  1182. return -1;
  1183. };
  1184. /**
  1185. * This function does a binary search for a specific value in a sorted array. If it does not exist but is in between of
  1186. * two values, we return either the one before or the one after, depending on user input
  1187. * If it is found, we return the index, else -1.
  1188. *
  1189. * @param {Array} orderedItems
  1190. * @param {{start: number, end: number}} target
  1191. * @param {String} field
  1192. * @param {String} sidePreference 'before' or 'after'
  1193. * @returns {number}
  1194. * @private
  1195. */
  1196. exports.binarySearchValue = function(orderedItems, target, field, sidePreference) {
  1197. var maxIterations = 10000;
  1198. var iteration = 0;
  1199. var low = 0;
  1200. var high = orderedItems.length - 1;
  1201. var prevValue, value, nextValue, middle;
  1202. while (low <= high && iteration < maxIterations) {
  1203. // get a new guess
  1204. middle = Math.floor(0.5*(high+low));
  1205. prevValue = orderedItems[Math.max(0,middle - 1)][field];
  1206. value = orderedItems[middle][field];
  1207. nextValue = orderedItems[Math.min(orderedItems.length-1,middle + 1)][field];
  1208. if (value == target) { // we found the target
  1209. return middle;
  1210. }
  1211. else if (prevValue < target && value > target) { // target is in between of the previous and the current
  1212. return sidePreference == 'before' ? Math.max(0,middle - 1) : middle;
  1213. }
  1214. else if (value < target && nextValue > target) { // target is in between of the current and the next
  1215. return sidePreference == 'before' ? middle : Math.min(orderedItems.length-1,middle + 1);
  1216. }
  1217. else { // didnt find the target, we need to change our boundaries.
  1218. if (value < target) { // it is too small --> increase low
  1219. low = middle + 1;
  1220. }
  1221. else { // it is too big --> decrease high
  1222. high = middle - 1;
  1223. }
  1224. }
  1225. iteration++;
  1226. }
  1227. // didnt find anything. Return -1.
  1228. return -1;
  1229. };
  1230. /**
  1231. * Quadratic ease-in-out
  1232. * http://gizma.com/easing/
  1233. * @param {number} t Current time
  1234. * @param {number} start Start value
  1235. * @param {number} end End value
  1236. * @param {number} duration Duration
  1237. * @returns {number} Value corresponding with current time
  1238. */
  1239. exports.easeInOutQuad = function (t, start, end, duration) {
  1240. var change = end - start;
  1241. t /= duration/2;
  1242. if (t < 1) return change/2*t*t + start;
  1243. t--;
  1244. return -change/2 * (t*(t-2) - 1) + start;
  1245. };
  1246. /*
  1247. * Easing Functions - inspired from http://gizma.com/easing/
  1248. * only considering the t value for the range [0, 1] => [0, 1]
  1249. * https://gist.github.com/gre/1650294
  1250. */
  1251. exports.easingFunctions = {
  1252. // no easing, no acceleration
  1253. linear: function (t) {
  1254. return t
  1255. },
  1256. // accelerating from zero velocity
  1257. easeInQuad: function (t) {
  1258. return t * t
  1259. },
  1260. // decelerating to zero velocity
  1261. easeOutQuad: function (t) {
  1262. return t * (2 - t)
  1263. },
  1264. // acceleration until halfway, then deceleration
  1265. easeInOutQuad: function (t) {
  1266. return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t
  1267. },
  1268. // accelerating from zero velocity
  1269. easeInCubic: function (t) {
  1270. return t * t * t
  1271. },
  1272. // decelerating to zero velocity
  1273. easeOutCubic: function (t) {
  1274. return (--t) * t * t + 1
  1275. },
  1276. // acceleration until halfway, then deceleration
  1277. easeInOutCubic: function (t) {
  1278. return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
  1279. },
  1280. // accelerating from zero velocity
  1281. easeInQuart: function (t) {
  1282. return t * t * t * t
  1283. },
  1284. // decelerating to zero velocity
  1285. easeOutQuart: function (t) {
  1286. return 1 - (--t) * t * t * t
  1287. },
  1288. // acceleration until halfway, then deceleration
  1289. easeInOutQuart: function (t) {
  1290. return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t
  1291. },
  1292. // accelerating from zero velocity
  1293. easeInQuint: function (t) {
  1294. return t * t * t * t * t
  1295. },
  1296. // decelerating to zero velocity
  1297. easeOutQuint: function (t) {
  1298. return 1 + (--t) * t * t * t * t
  1299. },
  1300. // acceleration until halfway, then deceleration
  1301. easeInOutQuint: function (t) {
  1302. return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t
  1303. }
  1304. };
  1305. /***/ },
  1306. /* 2 */
  1307. /***/ function(module, exports, __webpack_require__) {
  1308. // DOM utility methods
  1309. /**
  1310. * this prepares the JSON container for allocating SVG elements
  1311. * @param JSONcontainer
  1312. * @private
  1313. */
  1314. exports.prepareElements = function(JSONcontainer) {
  1315. // cleanup the redundant svgElements;
  1316. for (var elementType in JSONcontainer) {
  1317. if (JSONcontainer.hasOwnProperty(elementType)) {
  1318. JSONcontainer[elementType].redundant = JSONcontainer[elementType].used;
  1319. JSONcontainer[elementType].used = [];
  1320. }
  1321. }
  1322. };
  1323. /**
  1324. * this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from
  1325. * which to remove the redundant elements.
  1326. *
  1327. * @param JSONcontainer
  1328. * @private
  1329. */
  1330. exports.cleanupElements = function(JSONcontainer) {
  1331. // cleanup the redundant svgElements;
  1332. for (var elementType in JSONcontainer) {
  1333. if (JSONcontainer.hasOwnProperty(elementType)) {
  1334. if (JSONcontainer[elementType].redundant) {
  1335. for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) {
  1336. JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]);
  1337. }
  1338. JSONcontainer[elementType].redundant = [];
  1339. }
  1340. }
  1341. }
  1342. };
  1343. /**
  1344. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  1345. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  1346. *
  1347. * @param elementType
  1348. * @param JSONcontainer
  1349. * @param svgContainer
  1350. * @returns {*}
  1351. * @private
  1352. */
  1353. exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
  1354. var element;
  1355. // allocate SVG element, if it doesnt yet exist, create one.
  1356. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
  1357. // check if there is an redundant element
  1358. if (JSONcontainer[elementType].redundant.length > 0) {
  1359. element = JSONcontainer[elementType].redundant[0];
  1360. JSONcontainer[elementType].redundant.shift();
  1361. }
  1362. else {
  1363. // create a new element and add it to the SVG
  1364. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  1365. svgContainer.appendChild(element);
  1366. }
  1367. }
  1368. else {
  1369. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  1370. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  1371. JSONcontainer[elementType] = {used: [], redundant: []};
  1372. svgContainer.appendChild(element);
  1373. }
  1374. JSONcontainer[elementType].used.push(element);
  1375. return element;
  1376. };
  1377. /**
  1378. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  1379. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  1380. *
  1381. * @param elementType
  1382. * @param JSONcontainer
  1383. * @param DOMContainer
  1384. * @returns {*}
  1385. * @private
  1386. */
  1387. exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer, insertBefore) {
  1388. var element;
  1389. // allocate DOM element, if it doesnt yet exist, create one.
  1390. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
  1391. // check if there is an redundant element
  1392. if (JSONcontainer[elementType].redundant.length > 0) {
  1393. element = JSONcontainer[elementType].redundant[0];
  1394. JSONcontainer[elementType].redundant.shift();
  1395. }
  1396. else {
  1397. // create a new element and add it to the SVG
  1398. element = document.createElement(elementType);
  1399. if (insertBefore !== undefined) {
  1400. DOMContainer.insertBefore(element, insertBefore);
  1401. }
  1402. else {
  1403. DOMContainer.appendChild(element);
  1404. }
  1405. }
  1406. }
  1407. else {
  1408. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  1409. element = document.createElement(elementType);
  1410. JSONcontainer[elementType] = {used: [], redundant: []};
  1411. if (insertBefore !== undefined) {
  1412. DOMContainer.insertBefore(element, insertBefore);
  1413. }
  1414. else {
  1415. DOMContainer.appendChild(element);
  1416. }
  1417. }
  1418. JSONcontainer[elementType].used.push(element);
  1419. return element;
  1420. };
  1421. /**
  1422. * draw a point object. this is a seperate function because it can also be called by the legend.
  1423. * The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions
  1424. * as well.
  1425. *
  1426. * @param x
  1427. * @param y
  1428. * @param group
  1429. * @param JSONcontainer
  1430. * @param svgContainer
  1431. * @param labelObj
  1432. * @returns {*}
  1433. */
  1434. exports.drawPoint = function(x, y, group, JSONcontainer, svgContainer, labelObj) {
  1435. var point;
  1436. if (group.options.drawPoints.style == 'circle') {
  1437. point = exports.getSVGElement('circle',JSONcontainer,svgContainer);
  1438. point.setAttributeNS(null, "cx", x);
  1439. point.setAttributeNS(null, "cy", y);
  1440. point.setAttributeNS(null, "r", 0.5 * group.options.drawPoints.size);
  1441. }
  1442. else {
  1443. point = exports.getSVGElement('rect',JSONcontainer,svgContainer);
  1444. point.setAttributeNS(null, "x", x - 0.5*group.options.drawPoints.size);
  1445. point.setAttributeNS(null, "y", y - 0.5*group.options.drawPoints.size);
  1446. point.setAttributeNS(null, "width", group.options.drawPoints.size);
  1447. point.setAttributeNS(null, "height", group.options.drawPoints.size);
  1448. }
  1449. if(group.options.drawPoints.styles !== undefined) {
  1450. point.setAttributeNS(null, "style", group.group.options.drawPoints.styles);
  1451. }
  1452. point.setAttributeNS(null, "class", group.className + " point");
  1453. //handle label
  1454. var label = exports.getSVGElement('text',JSONcontainer,svgContainer);
  1455. if (labelObj){
  1456. if (labelObj.xOffset) {
  1457. x = x + labelObj.xOffset;
  1458. }
  1459. if (labelObj.yOffset) {
  1460. y = y + labelObj.yOffset;
  1461. }
  1462. if (labelObj.content) {
  1463. label.textContent = labelObj.content;
  1464. }
  1465. if (labelObj.className) {
  1466. label.setAttributeNS(null, "class", labelObj.className + " label");
  1467. }
  1468. }
  1469. label.setAttributeNS(null, "x", x);
  1470. label.setAttributeNS(null, "y", y);
  1471. return point;
  1472. };
  1473. /**
  1474. * draw a bar SVG element centered on the X coordinate
  1475. *
  1476. * @param x
  1477. * @param y
  1478. * @param className
  1479. */
  1480. exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer) {
  1481. if (height != 0) {
  1482. if (height < 0) {
  1483. height *= -1;
  1484. y -= height;
  1485. }
  1486. var rect = exports.getSVGElement('rect',JSONcontainer, svgContainer);
  1487. rect.setAttributeNS(null, "x", x - 0.5 * width);
  1488. rect.setAttributeNS(null, "y", y);
  1489. rect.setAttributeNS(null, "width", width);
  1490. rect.setAttributeNS(null, "height", height);
  1491. rect.setAttributeNS(null, "class", className);
  1492. }
  1493. };
  1494. /***/ },
  1495. /* 3 */
  1496. /***/ function(module, exports, __webpack_require__) {
  1497. var util = __webpack_require__(1);
  1498. var Queue = __webpack_require__(5);
  1499. /**
  1500. * DataSet
  1501. *
  1502. * Usage:
  1503. * var dataSet = new DataSet({
  1504. * fieldId: '_id',
  1505. * type: {
  1506. * // ...
  1507. * }
  1508. * });
  1509. *
  1510. * dataSet.add(item);
  1511. * dataSet.add(data);
  1512. * dataSet.update(item);
  1513. * dataSet.update(data);
  1514. * dataSet.remove(id);
  1515. * dataSet.remove(ids);
  1516. * var data = dataSet.get();
  1517. * var data = dataSet.get(id);
  1518. * var data = dataSet.get(ids);
  1519. * var data = dataSet.get(ids, options, data);
  1520. * dataSet.clear();
  1521. *
  1522. * A data set can:
  1523. * - add/remove/update data
  1524. * - gives triggers upon changes in the data
  1525. * - can import/export data in various data formats
  1526. *
  1527. * @param {Array | DataTable} [data] Optional array with initial data
  1528. * @param {Object} [options] Available options:
  1529. * {String} fieldId Field name of the id in the
  1530. * items, 'id' by default.
  1531. * {Object.<String, String} type
  1532. * A map with field names as key,
  1533. * and the field type as value.
  1534. * {Object} queue Queue changes to the DataSet,
  1535. * flush them all at once.
  1536. * Queue options:
  1537. * - {number} delay Delay in ms, null by default
  1538. * - {number} max Maximum number of entries in the queue, Infinity by default
  1539. * @constructor DataSet
  1540. */
  1541. // TODO: add a DataSet constructor DataSet(data, options)
  1542. function DataSet (data, options) {
  1543. // correctly read optional arguments
  1544. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  1545. options = data;
  1546. data = null;
  1547. }
  1548. this._options = options || {};
  1549. this._data = {}; // map with data indexed by id
  1550. this.length = 0; // number of items in the DataSet
  1551. this._fieldId = this._options.fieldId || 'id'; // name of the field containing id
  1552. this._type = {}; // internal field types (NOTE: this can differ from this._options.type)
  1553. // all variants of a Date are internally stored as Date, so we can convert
  1554. // from everything to everything (also from ISODate to Number for example)
  1555. if (this._options.type) {
  1556. for (var field in this._options.type) {
  1557. if (this._options.type.hasOwnProperty(field)) {
  1558. var value = this._options.type[field];
  1559. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1560. this._type[field] = 'Date';
  1561. }
  1562. else {
  1563. this._type[field] = value;
  1564. }
  1565. }
  1566. }
  1567. }
  1568. // TODO: deprecated since version 1.1.1 (or 2.0.0?)
  1569. if (this._options.convert) {
  1570. throw new Error('Option "convert" is deprecated. Use "type" instead.');
  1571. }
  1572. this._subscribers = {}; // event subscribers
  1573. // add initial data when provided
  1574. if (data) {
  1575. this.add(data);
  1576. }
  1577. this.setOptions(options);
  1578. }
  1579. /**
  1580. * @param {Object} [options] Available options:
  1581. * {Object} queue Queue changes to the DataSet,
  1582. * flush them all at once.
  1583. * Queue options:
  1584. * - {number} delay Delay in ms, null by default
  1585. * - {number} max Maximum number of entries in the queue, Infinity by default
  1586. * @param options
  1587. */
  1588. DataSet.prototype.setOptions = function(options) {
  1589. if (options && options.queue !== undefined) {
  1590. if (options.queue === false) {
  1591. // delete queue if loaded
  1592. if (this._queue) {
  1593. this._queue.destroy();
  1594. delete this._queue;
  1595. }
  1596. }
  1597. else {
  1598. // create queue and update its options
  1599. if (!this._queue) {
  1600. this._queue = Queue.extend(this, {
  1601. replace: ['add', 'update', 'remove']
  1602. });
  1603. }
  1604. if (typeof options.queue === 'object') {
  1605. this._queue.setOptions(options.queue);
  1606. }
  1607. }
  1608. }
  1609. };
  1610. /**
  1611. * Subscribe to an event, add an event listener
  1612. * @param {String} event Event name. Available events: 'put', 'update',
  1613. * 'remove'
  1614. * @param {function} callback Callback method. Called with three parameters:
  1615. * {String} event
  1616. * {Object | null} params
  1617. * {String | Number} senderId
  1618. */
  1619. DataSet.prototype.on = function(event, callback) {
  1620. var subscribers = this._subscribers[event];
  1621. if (!subscribers) {
  1622. subscribers = [];
  1623. this._subscribers[event] = subscribers;
  1624. }
  1625. subscribers.push({
  1626. callback: callback
  1627. });
  1628. };
  1629. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1630. DataSet.prototype.subscribe = DataSet.prototype.on;
  1631. /**
  1632. * Unsubscribe from an event, remove an event listener
  1633. * @param {String} event
  1634. * @param {function} callback
  1635. */
  1636. DataSet.prototype.off = function(event, callback) {
  1637. var subscribers = this._subscribers[event];
  1638. if (subscribers) {
  1639. this._subscribers[event] = subscribers.filter(function (listener) {
  1640. return (listener.callback != callback);
  1641. });
  1642. }
  1643. };
  1644. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1645. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1646. /**
  1647. * Trigger an event
  1648. * @param {String} event
  1649. * @param {Object | null} params
  1650. * @param {String} [senderId] Optional id of the sender.
  1651. * @private
  1652. */
  1653. DataSet.prototype._trigger = function (event, params, senderId) {
  1654. if (event == '*') {
  1655. throw new Error('Cannot trigger event *');
  1656. }
  1657. var subscribers = [];
  1658. if (event in this._subscribers) {
  1659. subscribers = subscribers.concat(this._subscribers[event]);
  1660. }
  1661. if ('*' in this._subscribers) {
  1662. subscribers = subscribers.concat(this._subscribers['*']);
  1663. }
  1664. for (var i = 0; i < subscribers.length; i++) {
  1665. var subscriber = subscribers[i];
  1666. if (subscriber.callback) {
  1667. subscriber.callback(event, params, senderId || null);
  1668. }
  1669. }
  1670. };
  1671. /**
  1672. * Add data.
  1673. * Adding an item will fail when there already is an item with the same id.
  1674. * @param {Object | Array | DataTable} data
  1675. * @param {String} [senderId] Optional sender id
  1676. * @return {Array} addedIds Array with the ids of the added items
  1677. */
  1678. DataSet.prototype.add = function (data, senderId) {
  1679. var addedIds = [],
  1680. id,
  1681. me = this;
  1682. if (Array.isArray(data)) {
  1683. // Array
  1684. for (var i = 0, len = data.length; i < len; i++) {
  1685. id = me._addItem(data[i]);
  1686. addedIds.push(id);
  1687. }
  1688. }
  1689. else if (util.isDataTable(data)) {
  1690. // Google DataTable
  1691. var columns = this._getColumnNames(data);
  1692. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1693. var item = {};
  1694. for (var col = 0, cols = columns.length; col < cols; col++) {
  1695. var field = columns[col];
  1696. item[field] = data.getValue(row, col);
  1697. }
  1698. id = me._addItem(item);
  1699. addedIds.push(id);
  1700. }
  1701. }
  1702. else if (data instanceof Object) {
  1703. // Single item
  1704. id = me._addItem(data);
  1705. addedIds.push(id);
  1706. }
  1707. else {
  1708. throw new Error('Unknown dataType');
  1709. }
  1710. if (addedIds.length) {
  1711. this._trigger('add', {items: addedIds}, senderId);
  1712. }
  1713. return addedIds;
  1714. };
  1715. /**
  1716. * Update existing items. When an item does not exist, it will be created
  1717. * @param {Object | Array | DataTable} data
  1718. * @param {String} [senderId] Optional sender id
  1719. * @return {Array} updatedIds The ids of the added or updated items
  1720. */
  1721. DataSet.prototype.update = function (data, senderId) {
  1722. var addedIds = [];
  1723. var updatedIds = [];
  1724. var updatedData = [];
  1725. var me = this;
  1726. var fieldId = me._fieldId;
  1727. var addOrUpdate = function (item) {
  1728. var id = item[fieldId];
  1729. if (me._data[id]) {
  1730. // update item
  1731. id = me._updateItem(item);
  1732. updatedIds.push(id);
  1733. updatedData.push(item);
  1734. }
  1735. else {
  1736. // add new item
  1737. id = me._addItem(item);
  1738. addedIds.push(id);
  1739. }
  1740. };
  1741. if (Array.isArray(data)) {
  1742. // Array
  1743. for (var i = 0, len = data.length; i < len; i++) {
  1744. addOrUpdate(data[i]);
  1745. }
  1746. }
  1747. else if (util.isDataTable(data)) {
  1748. // Google DataTable
  1749. var columns = this._getColumnNames(data);
  1750. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1751. var item = {};
  1752. for (var col = 0, cols = columns.length; col < cols; col++) {
  1753. var field = columns[col];
  1754. item[field] = data.getValue(row, col);
  1755. }
  1756. addOrUpdate(item);
  1757. }
  1758. }
  1759. else if (data instanceof Object) {
  1760. // Single item
  1761. addOrUpdate(data);
  1762. }
  1763. else {
  1764. throw new Error('Unknown dataType');
  1765. }
  1766. if (addedIds.length) {
  1767. this._trigger('add', {items: addedIds}, senderId);
  1768. }
  1769. if (updatedIds.length) {
  1770. this._trigger('update', {items: updatedIds, data: updatedData}, senderId);
  1771. }
  1772. return addedIds.concat(updatedIds);
  1773. };
  1774. /**
  1775. * Get a data item or multiple items.
  1776. *
  1777. * Usage:
  1778. *
  1779. * get()
  1780. * get(options: Object)
  1781. * get(options: Object, data: Array | DataTable)
  1782. *
  1783. * get(id: Number | String)
  1784. * get(id: Number | String, options: Object)
  1785. * get(id: Number | String, options: Object, data: Array | DataTable)
  1786. *
  1787. * get(ids: Number[] | String[])
  1788. * get(ids: Number[] | String[], options: Object)
  1789. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1790. *
  1791. * Where:
  1792. *
  1793. * {Number | String} id The id of an item
  1794. * {Number[] | String{}} ids An array with ids of items
  1795. * {Object} options An Object with options. Available options:
  1796. * {String} [returnType] Type of data to be
  1797. * returned. Can be 'DataTable' or 'Array' (default)
  1798. * {Object.<String, String>} [type]
  1799. * {String[]} [fields] field names to be returned
  1800. * {function} [filter] filter items
  1801. * {String | function} [order] Order the items by
  1802. * a field name or custom sort function.
  1803. * {Array | DataTable} [data] If provided, items will be appended to this
  1804. * array or table. Required in case of Google
  1805. * DataTable.
  1806. *
  1807. * @throws Error
  1808. */
  1809. DataSet.prototype.get = function (args) {
  1810. var me = this;
  1811. // parse the arguments
  1812. var id, ids, options, data;
  1813. var firstType = util.getType(arguments[0]);
  1814. if (firstType == 'String' || firstType == 'Number') {
  1815. // get(id [, options] [, data])
  1816. id = arguments[0];
  1817. options = arguments[1];
  1818. data = arguments[2];
  1819. }
  1820. else if (firstType == 'Array') {
  1821. // get(ids [, options] [, data])
  1822. ids = arguments[0];
  1823. options = arguments[1];
  1824. data = arguments[2];
  1825. }
  1826. else {
  1827. // get([, options] [, data])
  1828. options = arguments[0];
  1829. data = arguments[1];
  1830. }
  1831. // determine the return type
  1832. var returnType;
  1833. if (options && options.returnType) {
  1834. var allowedValues = ["DataTable", "Array", "Object"];
  1835. returnType = allowedValues.indexOf(options.returnType) == -1 ? "Array" : options.returnType;
  1836. if (data && (returnType != util.getType(data))) {
  1837. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1838. 'does not correspond with specified options.type (' + options.type + ')');
  1839. }
  1840. if (returnType == 'DataTable' && !util.isDataTable(data)) {
  1841. throw new Error('Parameter "data" must be a DataTable ' +
  1842. 'when options.type is "DataTable"');
  1843. }
  1844. }
  1845. else if (data) {
  1846. returnType = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1847. }
  1848. else {
  1849. returnType = 'Array';
  1850. }
  1851. // build options
  1852. var type = options && options.type || this._options.type;
  1853. var filter = options && options.filter;
  1854. var items = [], item, itemId, i, len;
  1855. // convert items
  1856. if (id != undefined) {
  1857. // return a single item
  1858. item = me._getItem(id, type);
  1859. if (filter && !filter(item)) {
  1860. item = null;
  1861. }
  1862. }
  1863. else if (ids != undefined) {
  1864. // return a subset of items
  1865. for (i = 0, len = ids.length; i < len; i++) {
  1866. item = me._getItem(ids[i], type);
  1867. if (!filter || filter(item)) {
  1868. items.push(item);
  1869. }
  1870. }
  1871. }
  1872. else {
  1873. // return all items
  1874. for (itemId in this._data) {
  1875. if (this._data.hasOwnProperty(itemId)) {
  1876. item = me._getItem(itemId, type);
  1877. if (!filter || filter(item)) {
  1878. items.push(item);
  1879. }
  1880. }
  1881. }
  1882. }
  1883. // order the results
  1884. if (options && options.order && id == undefined) {
  1885. this._sort(items, options.order);
  1886. }
  1887. // filter fields of the items
  1888. if (options && options.fields) {
  1889. var fields = options.fields;
  1890. if (id != undefined) {
  1891. item = this._filterFields(item, fields);
  1892. }
  1893. else {
  1894. for (i = 0, len = items.length; i < len; i++) {
  1895. items[i] = this._filterFields(items[i], fields);
  1896. }
  1897. }
  1898. }
  1899. // return the results
  1900. if (returnType == 'DataTable') {
  1901. var columns = this._getColumnNames(data);
  1902. if (id != undefined) {
  1903. // append a single item to the data table
  1904. me._appendRow(data, columns, item);
  1905. }
  1906. else {
  1907. // copy the items to the provided data table
  1908. for (i = 0; i < items.length; i++) {
  1909. me._appendRow(data, columns, items[i]);
  1910. }
  1911. }
  1912. return data;
  1913. }
  1914. else if (returnType == "Object") {
  1915. var result = {};
  1916. for (i = 0; i < items.length; i++) {
  1917. result[items[i].id] = items[i];
  1918. }
  1919. return result;
  1920. }
  1921. else {
  1922. // return an array
  1923. if (id != undefined) {
  1924. // a single item
  1925. return item;
  1926. }
  1927. else {
  1928. // multiple items
  1929. if (data) {
  1930. // copy the items to the provided array
  1931. for (i = 0, len = items.length; i < len; i++) {
  1932. data.push(items[i]);
  1933. }
  1934. return data;
  1935. }
  1936. else {
  1937. // just return our array
  1938. return items;
  1939. }
  1940. }
  1941. }
  1942. };
  1943. /**
  1944. * Get ids of all items or from a filtered set of items.
  1945. * @param {Object} [options] An Object with options. Available options:
  1946. * {function} [filter] filter items
  1947. * {String | function} [order] Order the items by
  1948. * a field name or custom sort function.
  1949. * @return {Array} ids
  1950. */
  1951. DataSet.prototype.getIds = function (options) {
  1952. var data = this._data,
  1953. filter = options && options.filter,
  1954. order = options && options.order,
  1955. type = options && options.type || this._options.type,
  1956. i,
  1957. len,
  1958. id,
  1959. item,
  1960. items,
  1961. ids = [];
  1962. if (filter) {
  1963. // get filtered items
  1964. if (order) {
  1965. // create ordered list
  1966. items = [];
  1967. for (id in data) {
  1968. if (data.hasOwnProperty(id)) {
  1969. item = this._getItem(id, type);
  1970. if (filter(item)) {
  1971. items.push(item);
  1972. }
  1973. }
  1974. }
  1975. this._sort(items, order);
  1976. for (i = 0, len = items.length; i < len; i++) {
  1977. ids[i] = items[i][this._fieldId];
  1978. }
  1979. }
  1980. else {
  1981. // create unordered list
  1982. for (id in data) {
  1983. if (data.hasOwnProperty(id)) {
  1984. item = this._getItem(id, type);
  1985. if (filter(item)) {
  1986. ids.push(item[this._fieldId]);
  1987. }
  1988. }
  1989. }
  1990. }
  1991. }
  1992. else {
  1993. // get all items
  1994. if (order) {
  1995. // create an ordered list
  1996. items = [];
  1997. for (id in data) {
  1998. if (data.hasOwnProperty(id)) {
  1999. items.push(data[id]);
  2000. }
  2001. }
  2002. this._sort(items, order);
  2003. for (i = 0, len = items.length; i < len; i++) {
  2004. ids[i] = items[i][this._fieldId];
  2005. }
  2006. }
  2007. else {
  2008. // create unordered list
  2009. for (id in data) {
  2010. if (data.hasOwnProperty(id)) {
  2011. item = data[id];
  2012. ids.push(item[this._fieldId]);
  2013. }
  2014. }
  2015. }
  2016. }
  2017. return ids;
  2018. };
  2019. /**
  2020. * Returns the DataSet itself. Is overwritten for example by the DataView,
  2021. * which returns the DataSet it is connected to instead.
  2022. */
  2023. DataSet.prototype.getDataSet = function () {
  2024. return this;
  2025. };
  2026. /**
  2027. * Execute a callback function for every item in the dataset.
  2028. * @param {function} callback
  2029. * @param {Object} [options] Available options:
  2030. * {Object.<String, String>} [type]
  2031. * {String[]} [fields] filter fields
  2032. * {function} [filter] filter items
  2033. * {String | function} [order] Order the items by
  2034. * a field name or custom sort function.
  2035. */
  2036. DataSet.prototype.forEach = function (callback, options) {
  2037. var filter = options && options.filter,
  2038. type = options && options.type || this._options.type,
  2039. data = this._data,
  2040. item,
  2041. id;
  2042. if (options && options.order) {
  2043. // execute forEach on ordered list
  2044. var items = this.get(options);
  2045. for (var i = 0, len = items.length; i < len; i++) {
  2046. item = items[i];
  2047. id = item[this._fieldId];
  2048. callback(item, id);
  2049. }
  2050. }
  2051. else {
  2052. // unordered
  2053. for (id in data) {
  2054. if (data.hasOwnProperty(id)) {
  2055. item = this._getItem(id, type);
  2056. if (!filter || filter(item)) {
  2057. callback(item, id);
  2058. }
  2059. }
  2060. }
  2061. }
  2062. };
  2063. /**
  2064. * Map every item in the dataset.
  2065. * @param {function} callback
  2066. * @param {Object} [options] Available options:
  2067. * {Object.<String, String>} [type]
  2068. * {String[]} [fields] filter fields
  2069. * {function} [filter] filter items
  2070. * {String | function} [order] Order the items by
  2071. * a field name or custom sort function.
  2072. * @return {Object[]} mappedItems
  2073. */
  2074. DataSet.prototype.map = function (callback, options) {
  2075. var filter = options && options.filter,
  2076. type = options && options.type || this._options.type,
  2077. mappedItems = [],
  2078. data = this._data,
  2079. item;
  2080. // convert and filter items
  2081. for (var id in data) {
  2082. if (data.hasOwnProperty(id)) {
  2083. item = this._getItem(id, type);
  2084. if (!filter || filter(item)) {
  2085. mappedItems.push(callback(item, id));
  2086. }
  2087. }
  2088. }
  2089. // order items
  2090. if (options && options.order) {
  2091. this._sort(mappedItems, options.order);
  2092. }
  2093. return mappedItems;
  2094. };
  2095. /**
  2096. * Filter the fields of an item
  2097. * @param {Object | null} item
  2098. * @param {String[]} fields Field names
  2099. * @return {Object | null} filteredItem or null if no item is provided
  2100. * @private
  2101. */
  2102. DataSet.prototype._filterFields = function (item, fields) {
  2103. if (!item) { // item is null
  2104. return item;
  2105. }
  2106. var filteredItem = {};
  2107. if(Array.isArray(fields)){
  2108. for (var field in item) {
  2109. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  2110. filteredItem[field] = item[field];
  2111. }
  2112. }
  2113. }else{
  2114. for (var field in item) {
  2115. if (item.hasOwnProperty(field) && fields.hasOwnProperty(field)) {
  2116. filteredItem[fields[field]] = item[field];
  2117. }
  2118. }
  2119. }
  2120. return filteredItem;
  2121. };
  2122. /**
  2123. * Sort the provided array with items
  2124. * @param {Object[]} items
  2125. * @param {String | function} order A field name or custom sort function.
  2126. * @private
  2127. */
  2128. DataSet.prototype._sort = function (items, order) {
  2129. if (util.isString(order)) {
  2130. // order by provided field name
  2131. var name = order; // field name
  2132. items.sort(function (a, b) {
  2133. var av = a[name];
  2134. var bv = b[name];
  2135. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  2136. });
  2137. }
  2138. else if (typeof order === 'function') {
  2139. // order by sort function
  2140. items.sort(order);
  2141. }
  2142. // TODO: extend order by an Object {field:String, direction:String}
  2143. // where direction can be 'asc' or 'desc'
  2144. else {
  2145. throw new TypeError('Order must be a function or a string');
  2146. }
  2147. };
  2148. /**
  2149. * Remove an object by pointer or by id
  2150. * @param {String | Number | Object | Array} id Object or id, or an array with
  2151. * objects or ids to be removed
  2152. * @param {String} [senderId] Optional sender id
  2153. * @return {Array} removedIds
  2154. */
  2155. DataSet.prototype.remove = function (id, senderId) {
  2156. var removedIds = [],
  2157. i, len, removedId;
  2158. if (Array.isArray(id)) {
  2159. for (i = 0, len = id.length; i < len; i++) {
  2160. removedId = this._remove(id[i]);
  2161. if (removedId != null) {
  2162. removedIds.push(removedId);
  2163. }
  2164. }
  2165. }
  2166. else {
  2167. removedId = this._remove(id);
  2168. if (removedId != null) {
  2169. removedIds.push(removedId);
  2170. }
  2171. }
  2172. if (removedIds.length) {
  2173. this._trigger('remove', {items: removedIds}, senderId);
  2174. }
  2175. return removedIds;
  2176. };
  2177. /**
  2178. * Remove an item by its id
  2179. * @param {Number | String | Object} id id or item
  2180. * @returns {Number | String | null} id
  2181. * @private
  2182. */
  2183. DataSet.prototype._remove = function (id) {
  2184. if (util.isNumber(id) || util.isString(id)) {
  2185. if (this._data[id]) {
  2186. delete this._data[id];
  2187. this.length--;
  2188. return id;
  2189. }
  2190. }
  2191. else if (id instanceof Object) {
  2192. var itemId = id[this._fieldId];
  2193. if (itemId && this._data[itemId]) {
  2194. delete this._data[itemId];
  2195. this.length--;
  2196. return itemId;
  2197. }
  2198. }
  2199. return null;
  2200. };
  2201. /**
  2202. * Clear the data
  2203. * @param {String} [senderId] Optional sender id
  2204. * @return {Array} removedIds The ids of all removed items
  2205. */
  2206. DataSet.prototype.clear = function (senderId) {
  2207. var ids = Object.keys(this._data);
  2208. this._data = {};
  2209. this.length = 0;
  2210. this._trigger('remove', {items: ids}, senderId);
  2211. return ids;
  2212. };
  2213. /**
  2214. * Find the item with maximum value of a specified field
  2215. * @param {String} field
  2216. * @return {Object | null} item Item containing max value, or null if no items
  2217. */
  2218. DataSet.prototype.max = function (field) {
  2219. var data = this._data,
  2220. max = null,
  2221. maxField = null;
  2222. for (var id in data) {
  2223. if (data.hasOwnProperty(id)) {
  2224. var item = data[id];
  2225. var itemField = item[field];
  2226. if (itemField != null && (!max || itemField > maxField)) {
  2227. max = item;
  2228. maxField = itemField;
  2229. }
  2230. }
  2231. }
  2232. return max;
  2233. };
  2234. /**
  2235. * Find the item with minimum value of a specified field
  2236. * @param {String} field
  2237. * @return {Object | null} item Item containing max value, or null if no items
  2238. */
  2239. DataSet.prototype.min = function (field) {
  2240. var data = this._data,
  2241. min = null,
  2242. minField = null;
  2243. for (var id in data) {
  2244. if (data.hasOwnProperty(id)) {
  2245. var item = data[id];
  2246. var itemField = item[field];
  2247. if (itemField != null && (!min || itemField < minField)) {
  2248. min = item;
  2249. minField = itemField;
  2250. }
  2251. }
  2252. }
  2253. return min;
  2254. };
  2255. /**
  2256. * Find all distinct values of a specified field
  2257. * @param {String} field
  2258. * @return {Array} values Array containing all distinct values. If data items
  2259. * do not contain the specified field are ignored.
  2260. * The returned array is unordered.
  2261. */
  2262. DataSet.prototype.distinct = function (field) {
  2263. var data = this._data;
  2264. var values = [];
  2265. var fieldType = this._options.type && this._options.type[field] || null;
  2266. var count = 0;
  2267. var i;
  2268. for (var prop in data) {
  2269. if (data.hasOwnProperty(prop)) {
  2270. var item = data[prop];
  2271. var value = item[field];
  2272. var exists = false;
  2273. for (i = 0; i < count; i++) {
  2274. if (values[i] == value) {
  2275. exists = true;
  2276. break;
  2277. }
  2278. }
  2279. if (!exists && (value !== undefined)) {
  2280. values[count] = value;
  2281. count++;
  2282. }
  2283. }
  2284. }
  2285. if (fieldType) {
  2286. for (i = 0; i < values.length; i++) {
  2287. values[i] = util.convert(values[i], fieldType);
  2288. }
  2289. }
  2290. return values;
  2291. };
  2292. /**
  2293. * Add a single item. Will fail when an item with the same id already exists.
  2294. * @param {Object} item
  2295. * @return {String} id
  2296. * @private
  2297. */
  2298. DataSet.prototype._addItem = function (item) {
  2299. var id = item[this._fieldId];
  2300. if (id != undefined) {
  2301. // check whether this id is already taken
  2302. if (this._data[id]) {
  2303. // item already exists
  2304. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  2305. }
  2306. }
  2307. else {
  2308. // generate an id
  2309. id = util.randomUUID();
  2310. item[this._fieldId] = id;
  2311. }
  2312. var d = {};
  2313. for (var field in item) {
  2314. if (item.hasOwnProperty(field)) {
  2315. var fieldType = this._type[field]; // type may be undefined
  2316. d[field] = util.convert(item[field], fieldType);
  2317. }
  2318. }
  2319. this._data[id] = d;
  2320. this.length++;
  2321. return id;
  2322. };
  2323. /**
  2324. * Get an item. Fields can be converted to a specific type
  2325. * @param {String} id
  2326. * @param {Object.<String, String>} [types] field types to convert
  2327. * @return {Object | null} item
  2328. * @private
  2329. */
  2330. DataSet.prototype._getItem = function (id, types) {
  2331. var field, value;
  2332. // get the item from the dataset
  2333. var raw = this._data[id];
  2334. if (!raw) {
  2335. return null;
  2336. }
  2337. // convert the items field types
  2338. var converted = {};
  2339. if (types) {
  2340. for (field in raw) {
  2341. if (raw.hasOwnProperty(field)) {
  2342. value = raw[field];
  2343. converted[field] = util.convert(value, types[field]);
  2344. }
  2345. }
  2346. }
  2347. else {
  2348. // no field types specified, no converting needed
  2349. for (field in raw) {
  2350. if (raw.hasOwnProperty(field)) {
  2351. value = raw[field];
  2352. converted[field] = value;
  2353. }
  2354. }
  2355. }
  2356. return converted;
  2357. };
  2358. /**
  2359. * Update a single item: merge with existing item.
  2360. * Will fail when the item has no id, or when there does not exist an item
  2361. * with the same id.
  2362. * @param {Object} item
  2363. * @return {String} id
  2364. * @private
  2365. */
  2366. DataSet.prototype._updateItem = function (item) {
  2367. var id = item[this._fieldId];
  2368. if (id == undefined) {
  2369. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  2370. }
  2371. var d = this._data[id];
  2372. if (!d) {
  2373. // item doesn't exist
  2374. throw new Error('Cannot update item: no item with id ' + id + ' found');
  2375. }
  2376. // merge with current item
  2377. for (var field in item) {
  2378. if (item.hasOwnProperty(field)) {
  2379. var fieldType = this._type[field]; // type may be undefined
  2380. d[field] = util.convert(item[field], fieldType);
  2381. }
  2382. }
  2383. return id;
  2384. };
  2385. /**
  2386. * Get an array with the column names of a Google DataTable
  2387. * @param {DataTable} dataTable
  2388. * @return {String[]} columnNames
  2389. * @private
  2390. */
  2391. DataSet.prototype._getColumnNames = function (dataTable) {
  2392. var columns = [];
  2393. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  2394. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  2395. }
  2396. return columns;
  2397. };
  2398. /**
  2399. * Append an item as a row to the dataTable
  2400. * @param dataTable
  2401. * @param columns
  2402. * @param item
  2403. * @private
  2404. */
  2405. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  2406. var row = dataTable.addRow();
  2407. for (var col = 0, cols = columns.length; col < cols; col++) {
  2408. var field = columns[col];
  2409. dataTable.setValue(row, col, item[field]);
  2410. }
  2411. };
  2412. module.exports = DataSet;
  2413. /***/ },
  2414. /* 4 */
  2415. /***/ function(module, exports, __webpack_require__) {
  2416. var util = __webpack_require__(1);
  2417. var DataSet = __webpack_require__(3);
  2418. /**
  2419. * DataView
  2420. *
  2421. * a dataview offers a filtered view on a dataset or an other dataview.
  2422. *
  2423. * @param {DataSet | DataView} data
  2424. * @param {Object} [options] Available options: see method get
  2425. *
  2426. * @constructor DataView
  2427. */
  2428. function DataView (data, options) {
  2429. this._data = null;
  2430. this._ids = {}; // ids of the items currently in memory (just contains a boolean true)
  2431. this.length = 0; // number of items in the DataView
  2432. this._options = options || {};
  2433. this._fieldId = 'id'; // name of the field containing id
  2434. this._subscribers = {}; // event subscribers
  2435. var me = this;
  2436. this.listener = function () {
  2437. me._onEvent.apply(me, arguments);
  2438. };
  2439. this.setData(data);
  2440. }
  2441. // TODO: implement a function .config() to dynamically update things like configured filter
  2442. // and trigger changes accordingly
  2443. /**
  2444. * Set a data source for the view
  2445. * @param {DataSet | DataView} data
  2446. */
  2447. DataView.prototype.setData = function (data) {
  2448. var ids, i, len;
  2449. if (this._data) {
  2450. // unsubscribe from current dataset
  2451. if (this._data.unsubscribe) {
  2452. this._data.unsubscribe('*', this.listener);
  2453. }
  2454. // trigger a remove of all items in memory
  2455. ids = [];
  2456. for (var id in this._ids) {
  2457. if (this._ids.hasOwnProperty(id)) {
  2458. ids.push(id);
  2459. }
  2460. }
  2461. this._ids = {};
  2462. this.length = 0;
  2463. this._trigger('remove', {items: ids});
  2464. }
  2465. this._data = data;
  2466. if (this._data) {
  2467. // update fieldId
  2468. this._fieldId = this._options.fieldId ||
  2469. (this._data && this._data.options && this._data.options.fieldId) ||
  2470. 'id';
  2471. // trigger an add of all added items
  2472. ids = this._data.getIds({filter: this._options && this._options.filter});
  2473. for (i = 0, len = ids.length; i < len; i++) {
  2474. id = ids[i];
  2475. this._ids[id] = true;
  2476. }
  2477. this.length = ids.length;
  2478. this._trigger('add', {items: ids});
  2479. // subscribe to new dataset
  2480. if (this._data.on) {
  2481. this._data.on('*', this.listener);
  2482. }
  2483. }
  2484. };
  2485. /**
  2486. * Refresh the DataView. Useful when the DataView has a filter function
  2487. * containing a variable parameter.
  2488. */
  2489. DataView.prototype.refresh = function () {
  2490. var id;
  2491. var ids = this._data.getIds({filter: this._options && this._options.filter});
  2492. var newIds = {};
  2493. var added = [];
  2494. var removed = [];
  2495. // check for additions
  2496. for (var i = 0; i < ids.length; i++) {
  2497. id = ids[i];
  2498. newIds[id] = true;
  2499. if (!this._ids[id]) {
  2500. added.push(id);
  2501. this._ids[id] = true;
  2502. this.length++;
  2503. }
  2504. }
  2505. // check for removals
  2506. for (id in this._ids) {
  2507. if (this._ids.hasOwnProperty(id)) {
  2508. if (!newIds[id]) {
  2509. removed.push(id);
  2510. delete this._ids[id];
  2511. this.length--;
  2512. }
  2513. }
  2514. }
  2515. // trigger events
  2516. if (added.length) {
  2517. this._trigger('add', {items: added});
  2518. }
  2519. if (removed.length) {
  2520. this._trigger('remove', {items: removed});
  2521. }
  2522. };
  2523. /**
  2524. * Get data from the data view
  2525. *
  2526. * Usage:
  2527. *
  2528. * get()
  2529. * get(options: Object)
  2530. * get(options: Object, data: Array | DataTable)
  2531. *
  2532. * get(id: Number)
  2533. * get(id: Number, options: Object)
  2534. * get(id: Number, options: Object, data: Array | DataTable)
  2535. *
  2536. * get(ids: Number[])
  2537. * get(ids: Number[], options: Object)
  2538. * get(ids: Number[], options: Object, data: Array | DataTable)
  2539. *
  2540. * Where:
  2541. *
  2542. * {Number | String} id The id of an item
  2543. * {Number[] | String{}} ids An array with ids of items
  2544. * {Object} options An Object with options. Available options:
  2545. * {String} [type] Type of data to be returned. Can
  2546. * be 'DataTable' or 'Array' (default)
  2547. * {Object.<String, String>} [convert]
  2548. * {String[]} [fields] field names to be returned
  2549. * {function} [filter] filter items
  2550. * {String | function} [order] Order the items by
  2551. * a field name or custom sort function.
  2552. * {Array | DataTable} [data] If provided, items will be appended to this
  2553. * array or table. Required in case of Google
  2554. * DataTable.
  2555. * @param args
  2556. */
  2557. DataView.prototype.get = function (args) {
  2558. var me = this;
  2559. // parse the arguments
  2560. var ids, options, data;
  2561. var firstType = util.getType(arguments[0]);
  2562. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2563. // get(id(s) [, options] [, data])
  2564. ids = arguments[0]; // can be a single id or an array with ids
  2565. options = arguments[1];
  2566. data = arguments[2];
  2567. }
  2568. else {
  2569. // get([, options] [, data])
  2570. options = arguments[0];
  2571. data = arguments[1];
  2572. }
  2573. // extend the options with the default options and provided options
  2574. var viewOptions = util.extend({}, this._options, options);
  2575. // create a combined filter method when needed
  2576. if (this._options.filter && options && options.filter) {
  2577. viewOptions.filter = function (item) {
  2578. return me._options.filter(item) && options.filter(item);
  2579. }
  2580. }
  2581. // build up the call to the linked data set
  2582. var getArguments = [];
  2583. if (ids != undefined) {
  2584. getArguments.push(ids);
  2585. }
  2586. getArguments.push(viewOptions);
  2587. getArguments.push(data);
  2588. return this._data && this._data.get.apply(this._data, getArguments);
  2589. };
  2590. /**
  2591. * Get ids of all items or from a filtered set of items.
  2592. * @param {Object} [options] An Object with options. Available options:
  2593. * {function} [filter] filter items
  2594. * {String | function} [order] Order the items by
  2595. * a field name or custom sort function.
  2596. * @return {Array} ids
  2597. */
  2598. DataView.prototype.getIds = function (options) {
  2599. var ids;
  2600. if (this._data) {
  2601. var defaultFilter = this._options.filter;
  2602. var filter;
  2603. if (options && options.filter) {
  2604. if (defaultFilter) {
  2605. filter = function (item) {
  2606. return defaultFilter(item) && options.filter(item);
  2607. }
  2608. }
  2609. else {
  2610. filter = options.filter;
  2611. }
  2612. }
  2613. else {
  2614. filter = defaultFilter;
  2615. }
  2616. ids = this._data.getIds({
  2617. filter: filter,
  2618. order: options && options.order
  2619. });
  2620. }
  2621. else {
  2622. ids = [];
  2623. }
  2624. return ids;
  2625. };
  2626. /**
  2627. * Get the DataSet to which this DataView is connected. In case there is a chain
  2628. * of multiple DataViews, the root DataSet of this chain is returned.
  2629. * @return {DataSet} dataSet
  2630. */
  2631. DataView.prototype.getDataSet = function () {
  2632. var dataSet = this;
  2633. while (dataSet instanceof DataView) {
  2634. dataSet = dataSet._data;
  2635. }
  2636. return dataSet || null;
  2637. };
  2638. /**
  2639. * Event listener. Will propagate all events from the connected data set to
  2640. * the subscribers of the DataView, but will filter the items and only trigger
  2641. * when there are changes in the filtered data set.
  2642. * @param {String} event
  2643. * @param {Object | null} params
  2644. * @param {String} senderId
  2645. * @private
  2646. */
  2647. DataView.prototype._onEvent = function (event, params, senderId) {
  2648. var i, len, id, item;
  2649. var ids = params && params.items;
  2650. var data = this._data;
  2651. var updatedData = [];
  2652. var added = [];
  2653. var updated = [];
  2654. var removed = [];
  2655. if (ids && data) {
  2656. switch (event) {
  2657. case 'add':
  2658. // filter the ids of the added items
  2659. for (i = 0, len = ids.length; i < len; i++) {
  2660. id = ids[i];
  2661. item = this.get(id);
  2662. if (item) {
  2663. this._ids[id] = true;
  2664. added.push(id);
  2665. }
  2666. }
  2667. break;
  2668. case 'update':
  2669. // determine the event from the views viewpoint: an updated
  2670. // item can be added, updated, or removed from this view.
  2671. for (i = 0, len = ids.length; i < len; i++) {
  2672. id = ids[i];
  2673. item = this.get(id);
  2674. if (item) {
  2675. if (this._ids[id]) {
  2676. updated.push(id);
  2677. updatedData.push(params.data[i]);
  2678. }
  2679. else {
  2680. this._ids[id] = true;
  2681. added.push(id);
  2682. }
  2683. }
  2684. else {
  2685. if (this._ids[id]) {
  2686. delete this._ids[id];
  2687. removed.push(id);
  2688. }
  2689. else {
  2690. // nothing interesting for me :-(
  2691. }
  2692. }
  2693. }
  2694. break;
  2695. case 'remove':
  2696. // filter the ids of the removed items
  2697. for (i = 0, len = ids.length; i < len; i++) {
  2698. id = ids[i];
  2699. if (this._ids[id]) {
  2700. delete this._ids[id];
  2701. removed.push(id);
  2702. }
  2703. }
  2704. break;
  2705. }
  2706. this.length += added.length - removed.length;
  2707. if (added.length) {
  2708. this._trigger('add', {items: added}, senderId);
  2709. }
  2710. if (updated.length) {
  2711. this._trigger('update', {items: updated, data: updatedData}, senderId);
  2712. }
  2713. if (removed.length) {
  2714. this._trigger('remove', {items: removed}, senderId);
  2715. }
  2716. }
  2717. };
  2718. // copy subscription functionality from DataSet
  2719. DataView.prototype.on = DataSet.prototype.on;
  2720. DataView.prototype.off = DataSet.prototype.off;
  2721. DataView.prototype._trigger = DataSet.prototype._trigger;
  2722. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2723. DataView.prototype.subscribe = DataView.prototype.on;
  2724. DataView.prototype.unsubscribe = DataView.prototype.off;
  2725. module.exports = DataView;
  2726. /***/ },
  2727. /* 5 */
  2728. /***/ function(module, exports, __webpack_require__) {
  2729. /**
  2730. * A queue
  2731. * @param {Object} options
  2732. * Available options:
  2733. * - delay: number When provided, the queue will be flushed
  2734. * automatically after an inactivity of this delay
  2735. * in milliseconds.
  2736. * Default value is null.
  2737. * - max: number When the queue exceeds the given maximum number
  2738. * of entries, the queue is flushed automatically.
  2739. * Default value of max is Infinity.
  2740. * @constructor
  2741. */
  2742. function Queue(options) {
  2743. // options
  2744. this.delay = null;
  2745. this.max = Infinity;
  2746. // properties
  2747. this._queue = [];
  2748. this._timeout = null;
  2749. this._extended = null;
  2750. this.setOptions(options);
  2751. }
  2752. /**
  2753. * Update the configuration of the queue
  2754. * @param {Object} options
  2755. * Available options:
  2756. * - delay: number When provided, the queue will be flushed
  2757. * automatically after an inactivity of this delay
  2758. * in milliseconds.
  2759. * Default value is null.
  2760. * - max: number When the queue exceeds the given maximum number
  2761. * of entries, the queue is flushed automatically.
  2762. * Default value of max is Infinity.
  2763. * @param options
  2764. */
  2765. Queue.prototype.setOptions = function (options) {
  2766. if (options && typeof options.delay !== 'undefined') {
  2767. this.delay = options.delay;
  2768. }
  2769. if (options && typeof options.max !== 'undefined') {
  2770. this.max = options.max;
  2771. }
  2772. this._flushIfNeeded();
  2773. };
  2774. /**
  2775. * Extend an object with queuing functionality.
  2776. * The object will be extended with a function flush, and the methods provided
  2777. * in options.replace will be replaced with queued ones.
  2778. * @param {Object} object
  2779. * @param {Object} options
  2780. * Available options:
  2781. * - replace: Array.<string>
  2782. * A list with method names of the methods
  2783. * on the object to be replaced with queued ones.
  2784. * - delay: number When provided, the queue will be flushed
  2785. * automatically after an inactivity of this delay
  2786. * in milliseconds.
  2787. * Default value is null.
  2788. * - max: number When the queue exceeds the given maximum number
  2789. * of entries, the queue is flushed automatically.
  2790. * Default value of max is Infinity.
  2791. * @return {Queue} Returns the created queue
  2792. */
  2793. Queue.extend = function (object, options) {
  2794. var queue = new Queue(options);
  2795. if (object.flush !== undefined) {
  2796. throw new Error('Target object already has a property flush');
  2797. }
  2798. object.flush = function () {
  2799. queue.flush();
  2800. };
  2801. var methods = [{
  2802. name: 'flush',
  2803. original: undefined
  2804. }];
  2805. if (options && options.replace) {
  2806. for (var i = 0; i < options.replace.length; i++) {
  2807. var name = options.replace[i];
  2808. methods.push({
  2809. name: name,
  2810. original: object[name]
  2811. });
  2812. queue.replace(object, name);
  2813. }
  2814. }
  2815. queue._extended = {
  2816. object: object,
  2817. methods: methods
  2818. };
  2819. return queue;
  2820. };
  2821. /**
  2822. * Destroy the queue. The queue will first flush all queued actions, and in
  2823. * case it has extended an object, will restore the original object.
  2824. */
  2825. Queue.prototype.destroy = function () {
  2826. this.flush();
  2827. if (this._extended) {
  2828. var object = this._extended.object;
  2829. var methods = this._extended.methods;
  2830. for (var i = 0; i < methods.length; i++) {
  2831. var method = methods[i];
  2832. if (method.original) {
  2833. object[method.name] = method.original;
  2834. }
  2835. else {
  2836. delete object[method.name];
  2837. }
  2838. }
  2839. this._extended = null;
  2840. }
  2841. };
  2842. /**
  2843. * Replace a method on an object with a queued version
  2844. * @param {Object} object Object having the method
  2845. * @param {string} method The method name
  2846. */
  2847. Queue.prototype.replace = function(object, method) {
  2848. var me = this;
  2849. var original = object[method];
  2850. if (!original) {
  2851. throw new Error('Method ' + method + ' undefined');
  2852. }
  2853. object[method] = function () {
  2854. // create an Array with the arguments
  2855. var args = [];
  2856. for (var i = 0; i < arguments.length; i++) {
  2857. args[i] = arguments[i];
  2858. }
  2859. // add this call to the queue
  2860. me.queue({
  2861. args: args,
  2862. fn: original,
  2863. context: this
  2864. });
  2865. };
  2866. };
  2867. /**
  2868. * Queue a call
  2869. * @param {function | {fn: function, args: Array} | {fn: function, args: Array, context: Object}} entry
  2870. */
  2871. Queue.prototype.queue = function(entry) {
  2872. if (typeof entry === 'function') {
  2873. this._queue.push({fn: entry});
  2874. }
  2875. else {
  2876. this._queue.push(entry);
  2877. }
  2878. this._flushIfNeeded();
  2879. };
  2880. /**
  2881. * Check whether the queue needs to be flushed
  2882. * @private
  2883. */
  2884. Queue.prototype._flushIfNeeded = function () {
  2885. // flush when the maximum is exceeded.
  2886. if (this._queue.length > this.max) {
  2887. this.flush();
  2888. }
  2889. // flush after a period of inactivity when a delay is configured
  2890. clearTimeout(this._timeout);
  2891. if (this.queue.length > 0 && typeof this.delay === 'number') {
  2892. var me = this;
  2893. this._timeout = setTimeout(function () {
  2894. me.flush();
  2895. }, this.delay);
  2896. }
  2897. };
  2898. /**
  2899. * Flush all queued calls
  2900. */
  2901. Queue.prototype.flush = function () {
  2902. while (this._queue.length > 0) {
  2903. var entry = this._queue.shift();
  2904. entry.fn.apply(entry.context || entry.fn, entry.args || []);
  2905. }
  2906. };
  2907. module.exports = Queue;
  2908. /***/ },
  2909. /* 6 */
  2910. /***/ function(module, exports, __webpack_require__) {
  2911. var Emitter = __webpack_require__(56);
  2912. var DataSet = __webpack_require__(3);
  2913. var DataView = __webpack_require__(4);
  2914. var util = __webpack_require__(1);
  2915. var Point3d = __webpack_require__(10);
  2916. var Point2d = __webpack_require__(9);
  2917. var Camera = __webpack_require__(7);
  2918. var Filter = __webpack_require__(8);
  2919. var Slider = __webpack_require__(11);
  2920. var StepNumber = __webpack_require__(12);
  2921. /**
  2922. * @constructor Graph3d
  2923. * Graph3d displays data in 3d.
  2924. *
  2925. * Graph3d is developed in javascript as a Google Visualization Chart.
  2926. *
  2927. * @param {Element} container The DOM element in which the Graph3d will
  2928. * be created. Normally a div element.
  2929. * @param {DataSet | DataView | Array} [data]
  2930. * @param {Object} [options]
  2931. */
  2932. function Graph3d(container, data, options) {
  2933. if (!(this instanceof Graph3d)) {
  2934. throw new SyntaxError('Constructor must be called with the new operator');
  2935. }
  2936. // create variables and set default values
  2937. this.containerElement = container;
  2938. this.width = '400px';
  2939. this.height = '400px';
  2940. this.margin = 10; // px
  2941. this.defaultXCenter = '55%';
  2942. this.defaultYCenter = '50%';
  2943. this.xLabel = 'x';
  2944. this.yLabel = 'y';
  2945. this.zLabel = 'z';
  2946. var passValueFn = function(v) { return v; };
  2947. this.xValueLabel = passValueFn;
  2948. this.yValueLabel = passValueFn;
  2949. this.zValueLabel = passValueFn;
  2950. this.filterLabel = 'time';
  2951. this.legendLabel = 'value';
  2952. this.style = Graph3d.STYLE.DOT;
  2953. this.showPerspective = true;
  2954. this.showGrid = true;
  2955. this.keepAspectRatio = true;
  2956. this.showShadow = false;
  2957. this.showGrayBottom = false; // TODO: this does not work correctly
  2958. this.showTooltip = false;
  2959. this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube'
  2960. this.animationInterval = 1000; // milliseconds
  2961. this.animationPreload = false;
  2962. this.camera = new Camera();
  2963. this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window?
  2964. this.dataTable = null; // The original data table
  2965. this.dataPoints = null; // The table with point objects
  2966. // the column indexes
  2967. this.colX = undefined;
  2968. this.colY = undefined;
  2969. this.colZ = undefined;
  2970. this.colValue = undefined;
  2971. this.colFilter = undefined;
  2972. this.xMin = 0;
  2973. this.xStep = undefined; // auto by default
  2974. this.xMax = 1;
  2975. this.yMin = 0;
  2976. this.yStep = undefined; // auto by default
  2977. this.yMax = 1;
  2978. this.zMin = 0;
  2979. this.zStep = undefined; // auto by default
  2980. this.zMax = 1;
  2981. this.valueMin = 0;
  2982. this.valueMax = 1;
  2983. this.xBarWidth = 1;
  2984. this.yBarWidth = 1;
  2985. // TODO: customize axis range
  2986. // constants
  2987. this.colorAxis = '#4D4D4D';
  2988. this.colorGrid = '#D3D3D3';
  2989. this.colorDot = '#7DC1FF';
  2990. this.colorDotBorder = '#3267D2';
  2991. // create a frame and canvas
  2992. this.create();
  2993. // apply options (also when undefined)
  2994. this.setOptions(options);
  2995. // apply data
  2996. if (data) {
  2997. this.setData(data);
  2998. }
  2999. }
  3000. // Extend Graph3d with an Emitter mixin
  3001. Emitter(Graph3d.prototype);
  3002. /**
  3003. * Calculate the scaling values, dependent on the range in x, y, and z direction
  3004. */
  3005. Graph3d.prototype._setScale = function() {
  3006. this.scale = new Point3d(1 / (this.xMax - this.xMin),
  3007. 1 / (this.yMax - this.yMin),
  3008. 1 / (this.zMax - this.zMin));
  3009. // keep aspect ration between x and y scale if desired
  3010. if (this.keepAspectRatio) {
  3011. if (this.scale.x < this.scale.y) {
  3012. //noinspection JSSuspiciousNameCombination
  3013. this.scale.y = this.scale.x;
  3014. }
  3015. else {
  3016. //noinspection JSSuspiciousNameCombination
  3017. this.scale.x = this.scale.y;
  3018. }
  3019. }
  3020. // scale the vertical axis
  3021. this.scale.z *= this.verticalRatio;
  3022. // TODO: can this be automated? verticalRatio?
  3023. // determine scale for (optional) value
  3024. this.scale.value = 1 / (this.valueMax - this.valueMin);
  3025. // position the camera arm
  3026. var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x;
  3027. var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y;
  3028. var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z;
  3029. this.camera.setArmLocation(xCenter, yCenter, zCenter);
  3030. };
  3031. /**
  3032. * Convert a 3D location to a 2D location on screen
  3033. * http://en.wikipedia.org/wiki/3D_projection
  3034. * @param {Point3d} point3d A 3D point with parameters x, y, z
  3035. * @return {Point2d} point2d A 2D point with parameters x, y
  3036. */
  3037. Graph3d.prototype._convert3Dto2D = function(point3d) {
  3038. var translation = this._convertPointToTranslation(point3d);
  3039. return this._convertTranslationToScreen(translation);
  3040. };
  3041. /**
  3042. * Convert a 3D location its translation seen from the camera
  3043. * http://en.wikipedia.org/wiki/3D_projection
  3044. * @param {Point3d} point3d A 3D point with parameters x, y, z
  3045. * @return {Point3d} translation A 3D point with parameters x, y, z This is
  3046. * the translation of the point, seen from the
  3047. * camera
  3048. */
  3049. Graph3d.prototype._convertPointToTranslation = function(point3d) {
  3050. var ax = point3d.x * this.scale.x,
  3051. ay = point3d.y * this.scale.y,
  3052. az = point3d.z * this.scale.z,
  3053. cx = this.camera.getCameraLocation().x,
  3054. cy = this.camera.getCameraLocation().y,
  3055. cz = this.camera.getCameraLocation().z,
  3056. // calculate angles
  3057. sinTx = Math.sin(this.camera.getCameraRotation().x),
  3058. cosTx = Math.cos(this.camera.getCameraRotation().x),
  3059. sinTy = Math.sin(this.camera.getCameraRotation().y),
  3060. cosTy = Math.cos(this.camera.getCameraRotation().y),
  3061. sinTz = Math.sin(this.camera.getCameraRotation().z),
  3062. cosTz = Math.cos(this.camera.getCameraRotation().z),
  3063. // calculate translation
  3064. dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
  3065. dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)),
  3066. dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx));
  3067. return new Point3d(dx, dy, dz);
  3068. };
  3069. /**
  3070. * Convert a translation point to a point on the screen
  3071. * @param {Point3d} translation A 3D point with parameters x, y, z This is
  3072. * the translation of the point, seen from the
  3073. * camera
  3074. * @return {Point2d} point2d A 2D point with parameters x, y
  3075. */
  3076. Graph3d.prototype._convertTranslationToScreen = function(translation) {
  3077. var ex = this.eye.x,
  3078. ey = this.eye.y,
  3079. ez = this.eye.z,
  3080. dx = translation.x,
  3081. dy = translation.y,
  3082. dz = translation.z;
  3083. // calculate position on screen from translation
  3084. var bx;
  3085. var by;
  3086. if (this.showPerspective) {
  3087. bx = (dx - ex) * (ez / dz);
  3088. by = (dy - ey) * (ez / dz);
  3089. }
  3090. else {
  3091. bx = dx * -(ez / this.camera.getArmLength());
  3092. by = dy * -(ez / this.camera.getArmLength());
  3093. }
  3094. // shift and scale the point to the center of the screen
  3095. // use the width of the graph to scale both horizontally and vertically.
  3096. return new Point2d(
  3097. this.xcenter + bx * this.frame.canvas.clientWidth,
  3098. this.ycenter - by * this.frame.canvas.clientWidth);
  3099. };
  3100. /**
  3101. * Set the background styling for the graph
  3102. * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor
  3103. */
  3104. Graph3d.prototype._setBackgroundColor = function(backgroundColor) {
  3105. var fill = 'white';
  3106. var stroke = 'gray';
  3107. var strokeWidth = 1;
  3108. if (typeof(backgroundColor) === 'string') {
  3109. fill = backgroundColor;
  3110. stroke = 'none';
  3111. strokeWidth = 0;
  3112. }
  3113. else if (typeof(backgroundColor) === 'object') {
  3114. if (backgroundColor.fill !== undefined) fill = backgroundColor.fill;
  3115. if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke;
  3116. if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth;
  3117. }
  3118. else if (backgroundColor === undefined) {
  3119. // use use defaults
  3120. }
  3121. else {
  3122. throw 'Unsupported type of backgroundColor';
  3123. }
  3124. this.frame.style.backgroundColor = fill;
  3125. this.frame.style.borderColor = stroke;
  3126. this.frame.style.borderWidth = strokeWidth + 'px';
  3127. this.frame.style.borderStyle = 'solid';
  3128. };
  3129. /// enumerate the available styles
  3130. Graph3d.STYLE = {
  3131. BAR: 0,
  3132. BARCOLOR: 1,
  3133. BARSIZE: 2,
  3134. DOT : 3,
  3135. DOTLINE : 4,
  3136. DOTCOLOR: 5,
  3137. DOTSIZE: 6,
  3138. GRID : 7,
  3139. LINE: 8,
  3140. SURFACE : 9
  3141. };
  3142. /**
  3143. * Retrieve the style index from given styleName
  3144. * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line'
  3145. * @return {Number} styleNumber Enumeration value representing the style, or -1
  3146. * when not found
  3147. */
  3148. Graph3d.prototype._getStyleNumber = function(styleName) {
  3149. switch (styleName) {
  3150. case 'dot': return Graph3d.STYLE.DOT;
  3151. case 'dot-line': return Graph3d.STYLE.DOTLINE;
  3152. case 'dot-color': return Graph3d.STYLE.DOTCOLOR;
  3153. case 'dot-size': return Graph3d.STYLE.DOTSIZE;
  3154. case 'line': return Graph3d.STYLE.LINE;
  3155. case 'grid': return Graph3d.STYLE.GRID;
  3156. case 'surface': return Graph3d.STYLE.SURFACE;
  3157. case 'bar': return Graph3d.STYLE.BAR;
  3158. case 'bar-color': return Graph3d.STYLE.BARCOLOR;
  3159. case 'bar-size': return Graph3d.STYLE.BARSIZE;
  3160. }
  3161. return -1;
  3162. };
  3163. /**
  3164. * Determine the indexes of the data columns, based on the given style and data
  3165. * @param {DataSet} data
  3166. * @param {Number} style
  3167. */
  3168. Graph3d.prototype._determineColumnIndexes = function(data, style) {
  3169. if (this.style === Graph3d.STYLE.DOT ||
  3170. this.style === Graph3d.STYLE.DOTLINE ||
  3171. this.style === Graph3d.STYLE.LINE ||
  3172. this.style === Graph3d.STYLE.GRID ||
  3173. this.style === Graph3d.STYLE.SURFACE ||
  3174. this.style === Graph3d.STYLE.BAR) {
  3175. // 3 columns expected, and optionally a 4th with filter values
  3176. this.colX = 0;
  3177. this.colY = 1;
  3178. this.colZ = 2;
  3179. this.colValue = undefined;
  3180. if (data.getNumberOfColumns() > 3) {
  3181. this.colFilter = 3;
  3182. }
  3183. }
  3184. else if (this.style === Graph3d.STYLE.DOTCOLOR ||
  3185. this.style === Graph3d.STYLE.DOTSIZE ||
  3186. this.style === Graph3d.STYLE.BARCOLOR ||
  3187. this.style === Graph3d.STYLE.BARSIZE) {
  3188. // 4 columns expected, and optionally a 5th with filter values
  3189. this.colX = 0;
  3190. this.colY = 1;
  3191. this.colZ = 2;
  3192. this.colValue = 3;
  3193. if (data.getNumberOfColumns() > 4) {
  3194. this.colFilter = 4;
  3195. }
  3196. }
  3197. else {
  3198. throw 'Unknown style "' + this.style + '"';
  3199. }
  3200. };
  3201. Graph3d.prototype.getNumberOfRows = function(data) {
  3202. return data.length;
  3203. }
  3204. Graph3d.prototype.getNumberOfColumns = function(data) {
  3205. var counter = 0;
  3206. for (var column in data[0]) {
  3207. if (data[0].hasOwnProperty(column)) {
  3208. counter++;
  3209. }
  3210. }
  3211. return counter;
  3212. }
  3213. Graph3d.prototype.getDistinctValues = function(data, column) {
  3214. var distinctValues = [];
  3215. for (var i = 0; i < data.length; i++) {
  3216. if (distinctValues.indexOf(data[i][column]) == -1) {
  3217. distinctValues.push(data[i][column]);
  3218. }
  3219. }
  3220. return distinctValues;
  3221. }
  3222. Graph3d.prototype.getColumnRange = function(data,column) {
  3223. var minMax = {min:data[0][column],max:data[0][column]};
  3224. for (var i = 0; i < data.length; i++) {
  3225. if (minMax.min > data[i][column]) { minMax.min = data[i][column]; }
  3226. if (minMax.max < data[i][column]) { minMax.max = data[i][column]; }
  3227. }
  3228. return minMax;
  3229. };
  3230. /**
  3231. * Initialize the data from the data table. Calculate minimum and maximum values
  3232. * and column index values
  3233. * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph.
  3234. * @param {Number} style Style Number
  3235. */
  3236. Graph3d.prototype._dataInitialize = function (rawData, style) {
  3237. var me = this;
  3238. // unsubscribe from the dataTable
  3239. if (this.dataSet) {
  3240. this.dataSet.off('*', this._onChange);
  3241. }
  3242. if (rawData === undefined)
  3243. return;
  3244. if (Array.isArray(rawData)) {
  3245. rawData = new DataSet(rawData);
  3246. }
  3247. var data;
  3248. if (rawData instanceof DataSet || rawData instanceof DataView) {
  3249. data = rawData.get();
  3250. }
  3251. else {
  3252. throw new Error('Array, DataSet, or DataView expected');
  3253. }
  3254. if (data.length == 0)
  3255. return;
  3256. this.dataSet = rawData;
  3257. this.dataTable = data;
  3258. // subscribe to changes in the dataset
  3259. this._onChange = function () {
  3260. me.setData(me.dataSet);
  3261. };
  3262. this.dataSet.on('*', this._onChange);
  3263. // _determineColumnIndexes
  3264. // getNumberOfRows (points)
  3265. // getNumberOfColumns (x,y,z,v,t,t1,t2...)
  3266. // getDistinctValues (unique values?)
  3267. // getColumnRange
  3268. // determine the location of x,y,z,value,filter columns
  3269. this.colX = 'x';
  3270. this.colY = 'y';
  3271. this.colZ = 'z';
  3272. this.colValue = 'style';
  3273. this.colFilter = 'filter';
  3274. // check if a filter column is provided
  3275. if (data[0].hasOwnProperty('filter')) {
  3276. if (this.dataFilter === undefined) {
  3277. this.dataFilter = new Filter(rawData, this.colFilter, this);
  3278. this.dataFilter.setOnLoadCallback(function() {me.redraw();});
  3279. }
  3280. }
  3281. var withBars = this.style == Graph3d.STYLE.BAR ||
  3282. this.style == Graph3d.STYLE.BARCOLOR ||
  3283. this.style == Graph3d.STYLE.BARSIZE;
  3284. // determine barWidth from data
  3285. if (withBars) {
  3286. if (this.defaultXBarWidth !== undefined) {
  3287. this.xBarWidth = this.defaultXBarWidth;
  3288. }
  3289. else {
  3290. var dataX = this.getDistinctValues(data,this.colX);
  3291. this.xBarWidth = (dataX[1] - dataX[0]) || 1;
  3292. }
  3293. if (this.defaultYBarWidth !== undefined) {
  3294. this.yBarWidth = this.defaultYBarWidth;
  3295. }
  3296. else {
  3297. var dataY = this.getDistinctValues(data,this.colY);
  3298. this.yBarWidth = (dataY[1] - dataY[0]) || 1;
  3299. }
  3300. }
  3301. // calculate minimums and maximums
  3302. var xRange = this.getColumnRange(data,this.colX);
  3303. if (withBars) {
  3304. xRange.min -= this.xBarWidth / 2;
  3305. xRange.max += this.xBarWidth / 2;
  3306. }
  3307. this.xMin = (this.defaultXMin !== undefined) ? this.defaultXMin : xRange.min;
  3308. this.xMax = (this.defaultXMax !== undefined) ? this.defaultXMax : xRange.max;
  3309. if (this.xMax <= this.xMin) this.xMax = this.xMin + 1;
  3310. this.xStep = (this.defaultXStep !== undefined) ? this.defaultXStep : (this.xMax-this.xMin)/5;
  3311. var yRange = this.getColumnRange(data,this.colY);
  3312. if (withBars) {
  3313. yRange.min -= this.yBarWidth / 2;
  3314. yRange.max += this.yBarWidth / 2;
  3315. }
  3316. this.yMin = (this.defaultYMin !== undefined) ? this.defaultYMin : yRange.min;
  3317. this.yMax = (this.defaultYMax !== undefined) ? this.defaultYMax : yRange.max;
  3318. if (this.yMax <= this.yMin) this.yMax = this.yMin + 1;
  3319. this.yStep = (this.defaultYStep !== undefined) ? this.defaultYStep : (this.yMax-this.yMin)/5;
  3320. var zRange = this.getColumnRange(data,this.colZ);
  3321. this.zMin = (this.defaultZMin !== undefined) ? this.defaultZMin : zRange.min;
  3322. this.zMax = (this.defaultZMax !== undefined) ? this.defaultZMax : zRange.max;
  3323. if (this.zMax <= this.zMin) this.zMax = this.zMin + 1;
  3324. this.zStep = (this.defaultZStep !== undefined) ? this.defaultZStep : (this.zMax-this.zMin)/5;
  3325. if (this.colValue !== undefined) {
  3326. var valueRange = this.getColumnRange(data,this.colValue);
  3327. this.valueMin = (this.defaultValueMin !== undefined) ? this.defaultValueMin : valueRange.min;
  3328. this.valueMax = (this.defaultValueMax !== undefined) ? this.defaultValueMax : valueRange.max;
  3329. if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1;
  3330. }
  3331. // set the scale dependent on the ranges.
  3332. this._setScale();
  3333. };
  3334. /**
  3335. * Filter the data based on the current filter
  3336. * @param {Array} data
  3337. * @return {Array} dataPoints Array with point objects which can be drawn on screen
  3338. */
  3339. Graph3d.prototype._getDataPoints = function (data) {
  3340. // TODO: store the created matrix dataPoints in the filters instead of reloading each time
  3341. var x, y, i, z, obj, point;
  3342. var dataPoints = [];
  3343. if (this.style === Graph3d.STYLE.GRID ||
  3344. this.style === Graph3d.STYLE.SURFACE) {
  3345. // copy all values from the google data table to a matrix
  3346. // the provided values are supposed to form a grid of (x,y) positions
  3347. // create two lists with all present x and y values
  3348. var dataX = [];
  3349. var dataY = [];
  3350. for (i = 0; i < this.getNumberOfRows(data); i++) {
  3351. x = data[i][this.colX] || 0;
  3352. y = data[i][this.colY] || 0;
  3353. if (dataX.indexOf(x) === -1) {
  3354. dataX.push(x);
  3355. }
  3356. if (dataY.indexOf(y) === -1) {
  3357. dataY.push(y);
  3358. }
  3359. }
  3360. var sortNumber = function (a, b) {
  3361. return a - b;
  3362. };
  3363. dataX.sort(sortNumber);
  3364. dataY.sort(sortNumber);
  3365. // create a grid, a 2d matrix, with all values.
  3366. var dataMatrix = []; // temporary data matrix
  3367. for (i = 0; i < data.length; i++) {
  3368. x = data[i][this.colX] || 0;
  3369. y = data[i][this.colY] || 0;
  3370. z = data[i][this.colZ] || 0;
  3371. var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer
  3372. var yIndex = dataY.indexOf(y);
  3373. if (dataMatrix[xIndex] === undefined) {
  3374. dataMatrix[xIndex] = [];
  3375. }
  3376. var point3d = new Point3d();
  3377. point3d.x = x;
  3378. point3d.y = y;
  3379. point3d.z = z;
  3380. obj = {};
  3381. obj.point = point3d;
  3382. obj.trans = undefined;
  3383. obj.screen = undefined;
  3384. obj.bottom = new Point3d(x, y, this.zMin);
  3385. dataMatrix[xIndex][yIndex] = obj;
  3386. dataPoints.push(obj);
  3387. }
  3388. // fill in the pointers to the neighbors.
  3389. for (x = 0; x < dataMatrix.length; x++) {
  3390. for (y = 0; y < dataMatrix[x].length; y++) {
  3391. if (dataMatrix[x][y]) {
  3392. dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined;
  3393. dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined;
  3394. dataMatrix[x][y].pointCross =
  3395. (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ?
  3396. dataMatrix[x+1][y+1] :
  3397. undefined;
  3398. }
  3399. }
  3400. }
  3401. }
  3402. else { // 'dot', 'dot-line', etc.
  3403. // copy all values from the google data table to a list with Point3d objects
  3404. for (i = 0; i < data.length; i++) {
  3405. point = new Point3d();
  3406. point.x = data[i][this.colX] || 0;
  3407. point.y = data[i][this.colY] || 0;
  3408. point.z = data[i][this.colZ] || 0;
  3409. if (this.colValue !== undefined) {
  3410. point.value = data[i][this.colValue] || 0;
  3411. }
  3412. obj = {};
  3413. obj.point = point;
  3414. obj.bottom = new Point3d(point.x, point.y, this.zMin);
  3415. obj.trans = undefined;
  3416. obj.screen = undefined;
  3417. dataPoints.push(obj);
  3418. }
  3419. }
  3420. return dataPoints;
  3421. };
  3422. /**
  3423. * Create the main frame for the Graph3d.
  3424. * This function is executed once when a Graph3d object is created. The frame
  3425. * contains a canvas, and this canvas contains all objects like the axis and
  3426. * nodes.
  3427. */
  3428. Graph3d.prototype.create = function () {
  3429. // remove all elements from the container element.
  3430. while (this.containerElement.hasChildNodes()) {
  3431. this.containerElement.removeChild(this.containerElement.firstChild);
  3432. }
  3433. this.frame = document.createElement('div');
  3434. this.frame.style.position = 'relative';
  3435. this.frame.style.overflow = 'hidden';
  3436. // create the graph canvas (HTML canvas element)
  3437. this.frame.canvas = document.createElement( 'canvas' );
  3438. this.frame.canvas.style.position = 'relative';
  3439. this.frame.appendChild(this.frame.canvas);
  3440. //if (!this.frame.canvas.getContext) {
  3441. {
  3442. var noCanvas = document.createElement( 'DIV' );
  3443. noCanvas.style.color = 'red';
  3444. noCanvas.style.fontWeight = 'bold' ;
  3445. noCanvas.style.padding = '10px';
  3446. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  3447. this.frame.canvas.appendChild(noCanvas);
  3448. }
  3449. this.frame.filter = document.createElement( 'div' );
  3450. this.frame.filter.style.position = 'absolute';
  3451. this.frame.filter.style.bottom = '0px';
  3452. this.frame.filter.style.left = '0px';
  3453. this.frame.filter.style.width = '100%';
  3454. this.frame.appendChild(this.frame.filter);
  3455. // add event listeners to handle moving and zooming the contents
  3456. var me = this;
  3457. var onmousedown = function (event) {me._onMouseDown(event);};
  3458. var ontouchstart = function (event) {me._onTouchStart(event);};
  3459. var onmousewheel = function (event) {me._onWheel(event);};
  3460. var ontooltip = function (event) {me._onTooltip(event);};
  3461. // TODO: these events are never cleaned up... can give a 'memory leakage'
  3462. util.addEventListener(this.frame.canvas, 'keydown', onkeydown);
  3463. util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
  3464. util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
  3465. util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
  3466. util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
  3467. // add the new graph to the container element
  3468. this.containerElement.appendChild(this.frame);
  3469. };
  3470. /**
  3471. * Set a new size for the graph
  3472. * @param {string} width Width in pixels or percentage (for example '800px'
  3473. * or '50%')
  3474. * @param {string} height Height in pixels or percentage (for example '400px'
  3475. * or '30%')
  3476. */
  3477. Graph3d.prototype.setSize = function(width, height) {
  3478. this.frame.style.width = width;
  3479. this.frame.style.height = height;
  3480. this._resizeCanvas();
  3481. };
  3482. /**
  3483. * Resize the canvas to the current size of the frame
  3484. */
  3485. Graph3d.prototype._resizeCanvas = function() {
  3486. this.frame.canvas.style.width = '100%';
  3487. this.frame.canvas.style.height = '100%';
  3488. this.frame.canvas.width = this.frame.canvas.clientWidth;
  3489. this.frame.canvas.height = this.frame.canvas.clientHeight;
  3490. // adjust with for margin
  3491. this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px';
  3492. };
  3493. /**
  3494. * Start animation
  3495. */
  3496. Graph3d.prototype.animationStart = function() {
  3497. if (!this.frame.filter || !this.frame.filter.slider)
  3498. throw 'No animation available';
  3499. this.frame.filter.slider.play();
  3500. };
  3501. /**
  3502. * Stop animation
  3503. */
  3504. Graph3d.prototype.animationStop = function() {
  3505. if (!this.frame.filter || !this.frame.filter.slider) return;
  3506. this.frame.filter.slider.stop();
  3507. };
  3508. /**
  3509. * Resize the center position based on the current values in this.defaultXCenter
  3510. * and this.defaultYCenter (which are strings with a percentage or a value
  3511. * in pixels). The center positions are the variables this.xCenter
  3512. * and this.yCenter
  3513. */
  3514. Graph3d.prototype._resizeCenter = function() {
  3515. // calculate the horizontal center position
  3516. if (this.defaultXCenter.charAt(this.defaultXCenter.length-1) === '%') {
  3517. this.xcenter =
  3518. parseFloat(this.defaultXCenter) / 100 *
  3519. this.frame.canvas.clientWidth;
  3520. }
  3521. else {
  3522. this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px
  3523. }
  3524. // calculate the vertical center position
  3525. if (this.defaultYCenter.charAt(this.defaultYCenter.length-1) === '%') {
  3526. this.ycenter =
  3527. parseFloat(this.defaultYCenter) / 100 *
  3528. (this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
  3529. }
  3530. else {
  3531. this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px
  3532. }
  3533. };
  3534. /**
  3535. * Set the rotation and distance of the camera
  3536. * @param {Object} pos An object with the camera position. The object
  3537. * contains three parameters:
  3538. * - horizontal {Number}
  3539. * The horizontal rotation, between 0 and 2*PI.
  3540. * Optional, can be left undefined.
  3541. * - vertical {Number}
  3542. * The vertical rotation, between 0 and 0.5*PI
  3543. * if vertical=0.5*PI, the graph is shown from the
  3544. * top. Optional, can be left undefined.
  3545. * - distance {Number}
  3546. * The (normalized) distance of the camera to the
  3547. * center of the graph, a value between 0.71 and 5.0.
  3548. * Optional, can be left undefined.
  3549. */
  3550. Graph3d.prototype.setCameraPosition = function(pos) {
  3551. if (pos === undefined) {
  3552. return;
  3553. }
  3554. if (pos.horizontal !== undefined && pos.vertical !== undefined) {
  3555. this.camera.setArmRotation(pos.horizontal, pos.vertical);
  3556. }
  3557. if (pos.distance !== undefined) {
  3558. this.camera.setArmLength(pos.distance);
  3559. }
  3560. this.redraw();
  3561. };
  3562. /**
  3563. * Retrieve the current camera rotation
  3564. * @return {object} An object with parameters horizontal, vertical, and
  3565. * distance
  3566. */
  3567. Graph3d.prototype.getCameraPosition = function() {
  3568. var pos = this.camera.getArmRotation();
  3569. pos.distance = this.camera.getArmLength();
  3570. return pos;
  3571. };
  3572. /**
  3573. * Load data into the 3D Graph
  3574. */
  3575. Graph3d.prototype._readData = function(data) {
  3576. // read the data
  3577. this._dataInitialize(data, this.style);
  3578. if (this.dataFilter) {
  3579. // apply filtering
  3580. this.dataPoints = this.dataFilter._getDataPoints();
  3581. }
  3582. else {
  3583. // no filtering. load all data
  3584. this.dataPoints = this._getDataPoints(this.dataTable);
  3585. }
  3586. // draw the filter
  3587. this._redrawFilter();
  3588. };
  3589. /**
  3590. * Replace the dataset of the Graph3d
  3591. * @param {Array | DataSet | DataView} data
  3592. */
  3593. Graph3d.prototype.setData = function (data) {
  3594. this._readData(data);
  3595. this.redraw();
  3596. // start animation when option is true
  3597. if (this.animationAutoStart && this.dataFilter) {
  3598. this.animationStart();
  3599. }
  3600. };
  3601. /**
  3602. * Update the options. Options will be merged with current options
  3603. * @param {Object} options
  3604. */
  3605. Graph3d.prototype.setOptions = function (options) {
  3606. var cameraPosition = undefined;
  3607. this.animationStop();
  3608. if (options !== undefined) {
  3609. // retrieve parameter values
  3610. if (options.width !== undefined) this.width = options.width;
  3611. if (options.height !== undefined) this.height = options.height;
  3612. if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter;
  3613. if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter;
  3614. if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel;
  3615. if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel;
  3616. if (options.xLabel !== undefined) this.xLabel = options.xLabel;
  3617. if (options.yLabel !== undefined) this.yLabel = options.yLabel;
  3618. if (options.zLabel !== undefined) this.zLabel = options.zLabel;
  3619. if (options.xValueLabel !== undefined) this.xValueLabel = options.xValueLabel;
  3620. if (options.yValueLabel !== undefined) this.yValueLabel = options.yValueLabel;
  3621. if (options.zValueLabel !== undefined) this.zValueLabel = options.zValueLabel;
  3622. if (options.style !== undefined) {
  3623. var styleNumber = this._getStyleNumber(options.style);
  3624. if (styleNumber !== -1) {
  3625. this.style = styleNumber;
  3626. }
  3627. }
  3628. if (options.showGrid !== undefined) this.showGrid = options.showGrid;
  3629. if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective;
  3630. if (options.showShadow !== undefined) this.showShadow = options.showShadow;
  3631. if (options.tooltip !== undefined) this.showTooltip = options.tooltip;
  3632. if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls;
  3633. if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio;
  3634. if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio;
  3635. if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval;
  3636. if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload;
  3637. if (options.animationAutoStart !== undefined)this.animationAutoStart = options.animationAutoStart;
  3638. if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth;
  3639. if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth;
  3640. if (options.xMin !== undefined) this.defaultXMin = options.xMin;
  3641. if (options.xStep !== undefined) this.defaultXStep = options.xStep;
  3642. if (options.xMax !== undefined) this.defaultXMax = options.xMax;
  3643. if (options.yMin !== undefined) this.defaultYMin = options.yMin;
  3644. if (options.yStep !== undefined) this.defaultYStep = options.yStep;
  3645. if (options.yMax !== undefined) this.defaultYMax = options.yMax;
  3646. if (options.zMin !== undefined) this.defaultZMin = options.zMin;
  3647. if (options.zStep !== undefined) this.defaultZStep = options.zStep;
  3648. if (options.zMax !== undefined) this.defaultZMax = options.zMax;
  3649. if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin;
  3650. if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax;
  3651. if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition;
  3652. if (cameraPosition !== undefined) {
  3653. this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical);
  3654. this.camera.setArmLength(cameraPosition.distance);
  3655. }
  3656. else {
  3657. this.camera.setArmRotation(1.0, 0.5);
  3658. this.camera.setArmLength(1.7);
  3659. }
  3660. }
  3661. this._setBackgroundColor(options && options.backgroundColor);
  3662. this.setSize(this.width, this.height);
  3663. // re-load the data
  3664. if (this.dataTable) {
  3665. this.setData(this.dataTable);
  3666. }
  3667. // start animation when option is true
  3668. if (this.animationAutoStart && this.dataFilter) {
  3669. this.animationStart();
  3670. }
  3671. };
  3672. /**
  3673. * Redraw the Graph.
  3674. */
  3675. Graph3d.prototype.redraw = function() {
  3676. if (this.dataPoints === undefined) {
  3677. throw 'Error: graph data not initialized';
  3678. }
  3679. this._resizeCanvas();
  3680. this._resizeCenter();
  3681. this._redrawSlider();
  3682. this._redrawClear();
  3683. this._redrawAxis();
  3684. if (this.style === Graph3d.STYLE.GRID ||
  3685. this.style === Graph3d.STYLE.SURFACE) {
  3686. this._redrawDataGrid();
  3687. }
  3688. else if (this.style === Graph3d.STYLE.LINE) {
  3689. this._redrawDataLine();
  3690. }
  3691. else if (this.style === Graph3d.STYLE.BAR ||
  3692. this.style === Graph3d.STYLE.BARCOLOR ||
  3693. this.style === Graph3d.STYLE.BARSIZE) {
  3694. this._redrawDataBar();
  3695. }
  3696. else {
  3697. // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE
  3698. this._redrawDataDot();
  3699. }
  3700. this._redrawInfo();
  3701. this._redrawLegend();
  3702. };
  3703. /**
  3704. * Clear the canvas before redrawing
  3705. */
  3706. Graph3d.prototype._redrawClear = function() {
  3707. var canvas = this.frame.canvas;
  3708. var ctx = canvas.getContext('2d');
  3709. ctx.clearRect(0, 0, canvas.width, canvas.height);
  3710. };
  3711. /**
  3712. * Redraw the legend showing the colors
  3713. */
  3714. Graph3d.prototype._redrawLegend = function() {
  3715. var y;
  3716. if (this.style === Graph3d.STYLE.DOTCOLOR ||
  3717. this.style === Graph3d.STYLE.DOTSIZE) {
  3718. var dotSize = this.frame.clientWidth * 0.02;
  3719. var widthMin, widthMax;
  3720. if (this.style === Graph3d.STYLE.DOTSIZE) {
  3721. widthMin = dotSize / 2; // px
  3722. widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function
  3723. }
  3724. else {
  3725. widthMin = 20; // px
  3726. widthMax = 20; // px
  3727. }
  3728. var height = Math.max(this.frame.clientHeight * 0.25, 100);
  3729. var top = this.margin;
  3730. var right = this.frame.clientWidth - this.margin;
  3731. var left = right - widthMax;
  3732. var bottom = top + height;
  3733. }
  3734. var canvas = this.frame.canvas;
  3735. var ctx = canvas.getContext('2d');
  3736. ctx.lineWidth = 1;
  3737. ctx.font = '14px arial'; // TODO: put in options
  3738. if (this.style === Graph3d.STYLE.DOTCOLOR) {
  3739. // draw the color bar
  3740. var ymin = 0;
  3741. var ymax = height; // Todo: make height customizable
  3742. for (y = ymin; y < ymax; y++) {
  3743. var f = (y - ymin) / (ymax - ymin);
  3744. //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function
  3745. var hue = f * 240;
  3746. var color = this._hsv2rgb(hue, 1, 1);
  3747. ctx.strokeStyle = color;
  3748. ctx.beginPath();
  3749. ctx.moveTo(left, top + y);
  3750. ctx.lineTo(right, top + y);
  3751. ctx.stroke();
  3752. }
  3753. ctx.strokeStyle = this.colorAxis;
  3754. ctx.strokeRect(left, top, widthMax, height);
  3755. }
  3756. if (this.style === Graph3d.STYLE.DOTSIZE) {
  3757. // draw border around color bar
  3758. ctx.strokeStyle = this.colorAxis;
  3759. ctx.fillStyle = this.colorDot;
  3760. ctx.beginPath();
  3761. ctx.moveTo(left, top);
  3762. ctx.lineTo(right, top);
  3763. ctx.lineTo(right - widthMax + widthMin, bottom);
  3764. ctx.lineTo(left, bottom);
  3765. ctx.closePath();
  3766. ctx.fill();
  3767. ctx.stroke();
  3768. }
  3769. if (this.style === Graph3d.STYLE.DOTCOLOR ||
  3770. this.style === Graph3d.STYLE.DOTSIZE) {
  3771. // print values along the color bar
  3772. var gridLineLen = 5; // px
  3773. var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax-this.valueMin)/5, true);
  3774. step.start();
  3775. if (step.getCurrent() < this.valueMin) {
  3776. step.next();
  3777. }
  3778. while (!step.end()) {
  3779. y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height;
  3780. ctx.beginPath();
  3781. ctx.moveTo(left - gridLineLen, y);
  3782. ctx.lineTo(left, y);
  3783. ctx.stroke();
  3784. ctx.textAlign = 'right';
  3785. ctx.textBaseline = 'middle';
  3786. ctx.fillStyle = this.colorAxis;
  3787. ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
  3788. step.next();
  3789. }
  3790. ctx.textAlign = 'right';
  3791. ctx.textBaseline = 'top';
  3792. var label = this.legendLabel;
  3793. ctx.fillText(label, right, bottom + this.margin);
  3794. }
  3795. };
  3796. /**
  3797. * Redraw the filter
  3798. */
  3799. Graph3d.prototype._redrawFilter = function() {
  3800. this.frame.filter.innerHTML = '';
  3801. if (this.dataFilter) {
  3802. var options = {
  3803. 'visible': this.showAnimationControls
  3804. };
  3805. var slider = new Slider(this.frame.filter, options);
  3806. this.frame.filter.slider = slider;
  3807. // TODO: css here is not nice here...
  3808. this.frame.filter.style.padding = '10px';
  3809. //this.frame.filter.style.backgroundColor = '#EFEFEF';
  3810. slider.setValues(this.dataFilter.values);
  3811. slider.setPlayInterval(this.animationInterval);
  3812. // create an event handler
  3813. var me = this;
  3814. var onchange = function () {
  3815. var index = slider.getIndex();
  3816. me.dataFilter.selectValue(index);
  3817. me.dataPoints = me.dataFilter._getDataPoints();
  3818. me.redraw();
  3819. };
  3820. slider.setOnChangeCallback(onchange);
  3821. }
  3822. else {
  3823. this.frame.filter.slider = undefined;
  3824. }
  3825. };
  3826. /**
  3827. * Redraw the slider
  3828. */
  3829. Graph3d.prototype._redrawSlider = function() {
  3830. if ( this.frame.filter.slider !== undefined) {
  3831. this.frame.filter.slider.redraw();
  3832. }
  3833. };
  3834. /**
  3835. * Redraw common information
  3836. */
  3837. Graph3d.prototype._redrawInfo = function() {
  3838. if (this.dataFilter) {
  3839. var canvas = this.frame.canvas;
  3840. var ctx = canvas.getContext('2d');
  3841. ctx.font = '14px arial'; // TODO: put in options
  3842. ctx.lineStyle = 'gray';
  3843. ctx.fillStyle = 'gray';
  3844. ctx.textAlign = 'left';
  3845. ctx.textBaseline = 'top';
  3846. var x = this.margin;
  3847. var y = this.margin;
  3848. ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y);
  3849. }
  3850. };
  3851. /**
  3852. * Redraw the axis
  3853. */
  3854. Graph3d.prototype._redrawAxis = function() {
  3855. var canvas = this.frame.canvas,
  3856. ctx = canvas.getContext('2d'),
  3857. from, to, step, prettyStep,
  3858. text, xText, yText, zText,
  3859. offset, xOffset, yOffset,
  3860. xMin2d, xMax2d;
  3861. // TODO: get the actual rendered style of the containerElement
  3862. //ctx.font = this.containerElement.style.font;
  3863. ctx.font = 24 / this.camera.getArmLength() + 'px arial';
  3864. // calculate the length for the short grid lines
  3865. var gridLenX = 0.025 / this.scale.x;
  3866. var gridLenY = 0.025 / this.scale.y;
  3867. var textMargin = 5 / this.camera.getArmLength(); // px
  3868. var armAngle = this.camera.getArmRotation().horizontal;
  3869. // draw x-grid lines
  3870. ctx.lineWidth = 1;
  3871. prettyStep = (this.defaultXStep === undefined);
  3872. step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep);
  3873. step.start();
  3874. if (step.getCurrent() < this.xMin) {
  3875. step.next();
  3876. }
  3877. while (!step.end()) {
  3878. var x = step.getCurrent();
  3879. if (this.showGrid) {
  3880. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  3881. to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  3882. ctx.strokeStyle = this.colorGrid;
  3883. ctx.beginPath();
  3884. ctx.moveTo(from.x, from.y);
  3885. ctx.lineTo(to.x, to.y);
  3886. ctx.stroke();
  3887. }
  3888. else {
  3889. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  3890. to = this._convert3Dto2D(new Point3d(x, this.yMin+gridLenX, this.zMin));
  3891. ctx.strokeStyle = this.colorAxis;
  3892. ctx.beginPath();
  3893. ctx.moveTo(from.x, from.y);
  3894. ctx.lineTo(to.x, to.y);
  3895. ctx.stroke();
  3896. from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  3897. to = this._convert3Dto2D(new Point3d(x, this.yMax-gridLenX, this.zMin));
  3898. ctx.strokeStyle = this.colorAxis;
  3899. ctx.beginPath();
  3900. ctx.moveTo(from.x, from.y);
  3901. ctx.lineTo(to.x, to.y);
  3902. ctx.stroke();
  3903. }
  3904. yText = (Math.cos(armAngle) > 0) ? this.yMin : this.yMax;
  3905. text = this._convert3Dto2D(new Point3d(x, yText, this.zMin));
  3906. if (Math.cos(armAngle * 2) > 0) {
  3907. ctx.textAlign = 'center';
  3908. ctx.textBaseline = 'top';
  3909. text.y += textMargin;
  3910. }
  3911. else if (Math.sin(armAngle * 2) < 0){
  3912. ctx.textAlign = 'right';
  3913. ctx.textBaseline = 'middle';
  3914. }
  3915. else {
  3916. ctx.textAlign = 'left';
  3917. ctx.textBaseline = 'middle';
  3918. }
  3919. ctx.fillStyle = this.colorAxis;
  3920. ctx.fillText(' ' + this.xValueLabel(step.getCurrent()) + ' ', text.x, text.y);
  3921. step.next();
  3922. }
  3923. // draw y-grid lines
  3924. ctx.lineWidth = 1;
  3925. prettyStep = (this.defaultYStep === undefined);
  3926. step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep);
  3927. step.start();
  3928. if (step.getCurrent() < this.yMin) {
  3929. step.next();
  3930. }
  3931. while (!step.end()) {
  3932. if (this.showGrid) {
  3933. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  3934. to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  3935. ctx.strokeStyle = this.colorGrid;
  3936. ctx.beginPath();
  3937. ctx.moveTo(from.x, from.y);
  3938. ctx.lineTo(to.x, to.y);
  3939. ctx.stroke();
  3940. }
  3941. else {
  3942. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  3943. to = this._convert3Dto2D(new Point3d(this.xMin+gridLenY, step.getCurrent(), this.zMin));
  3944. ctx.strokeStyle = this.colorAxis;
  3945. ctx.beginPath();
  3946. ctx.moveTo(from.x, from.y);
  3947. ctx.lineTo(to.x, to.y);
  3948. ctx.stroke();
  3949. from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  3950. to = this._convert3Dto2D(new Point3d(this.xMax-gridLenY, step.getCurrent(), this.zMin));
  3951. ctx.strokeStyle = this.colorAxis;
  3952. ctx.beginPath();
  3953. ctx.moveTo(from.x, from.y);
  3954. ctx.lineTo(to.x, to.y);
  3955. ctx.stroke();
  3956. }
  3957. xText = (Math.sin(armAngle ) > 0) ? this.xMin : this.xMax;
  3958. text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin));
  3959. if (Math.cos(armAngle * 2) < 0) {
  3960. ctx.textAlign = 'center';
  3961. ctx.textBaseline = 'top';
  3962. text.y += textMargin;
  3963. }
  3964. else if (Math.sin(armAngle * 2) > 0){
  3965. ctx.textAlign = 'right';
  3966. ctx.textBaseline = 'middle';
  3967. }
  3968. else {
  3969. ctx.textAlign = 'left';
  3970. ctx.textBaseline = 'middle';
  3971. }
  3972. ctx.fillStyle = this.colorAxis;
  3973. ctx.fillText(' ' + this.yValueLabel(step.getCurrent()) + ' ', text.x, text.y);
  3974. step.next();
  3975. }
  3976. // draw z-grid lines and axis
  3977. ctx.lineWidth = 1;
  3978. prettyStep = (this.defaultZStep === undefined);
  3979. step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep);
  3980. step.start();
  3981. if (step.getCurrent() < this.zMin) {
  3982. step.next();
  3983. }
  3984. xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
  3985. yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
  3986. while (!step.end()) {
  3987. // TODO: make z-grid lines really 3d?
  3988. from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent()));
  3989. ctx.strokeStyle = this.colorAxis;
  3990. ctx.beginPath();
  3991. ctx.moveTo(from.x, from.y);
  3992. ctx.lineTo(from.x - textMargin, from.y);
  3993. ctx.stroke();
  3994. ctx.textAlign = 'right';
  3995. ctx.textBaseline = 'middle';
  3996. ctx.fillStyle = this.colorAxis;
  3997. ctx.fillText(this.zValueLabel(step.getCurrent()) + ' ', from.x - 5, from.y);
  3998. step.next();
  3999. }
  4000. ctx.lineWidth = 1;
  4001. from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  4002. to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax));
  4003. ctx.strokeStyle = this.colorAxis;
  4004. ctx.beginPath();
  4005. ctx.moveTo(from.x, from.y);
  4006. ctx.lineTo(to.x, to.y);
  4007. ctx.stroke();
  4008. // draw x-axis
  4009. ctx.lineWidth = 1;
  4010. // line at yMin
  4011. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  4012. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  4013. ctx.strokeStyle = this.colorAxis;
  4014. ctx.beginPath();
  4015. ctx.moveTo(xMin2d.x, xMin2d.y);
  4016. ctx.lineTo(xMax2d.x, xMax2d.y);
  4017. ctx.stroke();
  4018. // line at ymax
  4019. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  4020. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  4021. ctx.strokeStyle = this.colorAxis;
  4022. ctx.beginPath();
  4023. ctx.moveTo(xMin2d.x, xMin2d.y);
  4024. ctx.lineTo(xMax2d.x, xMax2d.y);
  4025. ctx.stroke();
  4026. // draw y-axis
  4027. ctx.lineWidth = 1;
  4028. // line at xMin
  4029. from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  4030. to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  4031. ctx.strokeStyle = this.colorAxis;
  4032. ctx.beginPath();
  4033. ctx.moveTo(from.x, from.y);
  4034. ctx.lineTo(to.x, to.y);
  4035. ctx.stroke();
  4036. // line at xMax
  4037. from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  4038. to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  4039. ctx.strokeStyle = this.colorAxis;
  4040. ctx.beginPath();
  4041. ctx.moveTo(from.x, from.y);
  4042. ctx.lineTo(to.x, to.y);
  4043. ctx.stroke();
  4044. // draw x-label
  4045. var xLabel = this.xLabel;
  4046. if (xLabel.length > 0) {
  4047. yOffset = 0.1 / this.scale.y;
  4048. xText = (this.xMin + this.xMax) / 2;
  4049. yText = (Math.cos(armAngle) > 0) ? this.yMin - yOffset: this.yMax + yOffset;
  4050. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  4051. if (Math.cos(armAngle * 2) > 0) {
  4052. ctx.textAlign = 'center';
  4053. ctx.textBaseline = 'top';
  4054. }
  4055. else if (Math.sin(armAngle * 2) < 0){
  4056. ctx.textAlign = 'right';
  4057. ctx.textBaseline = 'middle';
  4058. }
  4059. else {
  4060. ctx.textAlign = 'left';
  4061. ctx.textBaseline = 'middle';
  4062. }
  4063. ctx.fillStyle = this.colorAxis;
  4064. ctx.fillText(xLabel, text.x, text.y);
  4065. }
  4066. // draw y-label
  4067. var yLabel = this.yLabel;
  4068. if (yLabel.length > 0) {
  4069. xOffset = 0.1 / this.scale.x;
  4070. xText = (Math.sin(armAngle ) > 0) ? this.xMin - xOffset : this.xMax + xOffset;
  4071. yText = (this.yMin + this.yMax) / 2;
  4072. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  4073. if (Math.cos(armAngle * 2) < 0) {
  4074. ctx.textAlign = 'center';
  4075. ctx.textBaseline = 'top';
  4076. }
  4077. else if (Math.sin(armAngle * 2) > 0){
  4078. ctx.textAlign = 'right';
  4079. ctx.textBaseline = 'middle';
  4080. }
  4081. else {
  4082. ctx.textAlign = 'left';
  4083. ctx.textBaseline = 'middle';
  4084. }
  4085. ctx.fillStyle = this.colorAxis;
  4086. ctx.fillText(yLabel, text.x, text.y);
  4087. }
  4088. // draw z-label
  4089. var zLabel = this.zLabel;
  4090. if (zLabel.length > 0) {
  4091. offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
  4092. xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
  4093. yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
  4094. zText = (this.zMin + this.zMax) / 2;
  4095. text = this._convert3Dto2D(new Point3d(xText, yText, zText));
  4096. ctx.textAlign = 'right';
  4097. ctx.textBaseline = 'middle';
  4098. ctx.fillStyle = this.colorAxis;
  4099. ctx.fillText(zLabel, text.x - offset, text.y);
  4100. }
  4101. };
  4102. /**
  4103. * Calculate the color based on the given value.
  4104. * @param {Number} H Hue, a value be between 0 and 360
  4105. * @param {Number} S Saturation, a value between 0 and 1
  4106. * @param {Number} V Value, a value between 0 and 1
  4107. */
  4108. Graph3d.prototype._hsv2rgb = function(H, S, V) {
  4109. var R, G, B, C, Hi, X;
  4110. C = V * S;
  4111. Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5
  4112. X = C * (1 - Math.abs(((H/60) % 2) - 1));
  4113. switch (Hi) {
  4114. case 0: R = C; G = X; B = 0; break;
  4115. case 1: R = X; G = C; B = 0; break;
  4116. case 2: R = 0; G = C; B = X; break;
  4117. case 3: R = 0; G = X; B = C; break;
  4118. case 4: R = X; G = 0; B = C; break;
  4119. case 5: R = C; G = 0; B = X; break;
  4120. default: R = 0; G = 0; B = 0; break;
  4121. }
  4122. return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')';
  4123. };
  4124. /**
  4125. * Draw all datapoints as a grid
  4126. * This function can be used when the style is 'grid'
  4127. */
  4128. Graph3d.prototype._redrawDataGrid = function() {
  4129. var canvas = this.frame.canvas,
  4130. ctx = canvas.getContext('2d'),
  4131. point, right, top, cross,
  4132. i,
  4133. topSideVisible, fillStyle, strokeStyle, lineWidth,
  4134. h, s, v, zAvg;
  4135. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  4136. return; // TODO: throw exception?
  4137. // calculate the translations and screen position of all points
  4138. for (i = 0; i < this.dataPoints.length; i++) {
  4139. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  4140. var screen = this._convertTranslationToScreen(trans);
  4141. this.dataPoints[i].trans = trans;
  4142. this.dataPoints[i].screen = screen;
  4143. // calculate the translation of the point at the bottom (needed for sorting)
  4144. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  4145. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  4146. }
  4147. // sort the points on depth of their (x,y) position (not on z)
  4148. var sortDepth = function (a, b) {
  4149. return b.dist - a.dist;
  4150. };
  4151. this.dataPoints.sort(sortDepth);
  4152. if (this.style === Graph3d.STYLE.SURFACE) {
  4153. for (i = 0; i < this.dataPoints.length; i++) {
  4154. point = this.dataPoints[i];
  4155. right = this.dataPoints[i].pointRight;
  4156. top = this.dataPoints[i].pointTop;
  4157. cross = this.dataPoints[i].pointCross;
  4158. if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) {
  4159. if (this.showGrayBottom || this.showShadow) {
  4160. // calculate the cross product of the two vectors from center
  4161. // to left and right, in order to know whether we are looking at the
  4162. // bottom or at the top side. We can also use the cross product
  4163. // for calculating light intensity
  4164. var aDiff = Point3d.subtract(cross.trans, point.trans);
  4165. var bDiff = Point3d.subtract(top.trans, right.trans);
  4166. var crossproduct = Point3d.crossProduct(aDiff, bDiff);
  4167. var len = crossproduct.length();
  4168. // FIXME: there is a bug with determining the surface side (shadow or colored)
  4169. topSideVisible = (crossproduct.z > 0);
  4170. }
  4171. else {
  4172. topSideVisible = true;
  4173. }
  4174. if (topSideVisible) {
  4175. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4176. zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
  4177. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4178. s = 1; // saturation
  4179. if (this.showShadow) {
  4180. v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale
  4181. fillStyle = this._hsv2rgb(h, s, v);
  4182. strokeStyle = fillStyle;
  4183. }
  4184. else {
  4185. v = 1;
  4186. fillStyle = this._hsv2rgb(h, s, v);
  4187. strokeStyle = this.colorAxis;
  4188. }
  4189. }
  4190. else {
  4191. fillStyle = 'gray';
  4192. strokeStyle = this.colorAxis;
  4193. }
  4194. lineWidth = 0.5;
  4195. ctx.lineWidth = lineWidth;
  4196. ctx.fillStyle = fillStyle;
  4197. ctx.strokeStyle = strokeStyle;
  4198. ctx.beginPath();
  4199. ctx.moveTo(point.screen.x, point.screen.y);
  4200. ctx.lineTo(right.screen.x, right.screen.y);
  4201. ctx.lineTo(cross.screen.x, cross.screen.y);
  4202. ctx.lineTo(top.screen.x, top.screen.y);
  4203. ctx.closePath();
  4204. ctx.fill();
  4205. ctx.stroke();
  4206. }
  4207. }
  4208. }
  4209. else { // grid style
  4210. for (i = 0; i < this.dataPoints.length; i++) {
  4211. point = this.dataPoints[i];
  4212. right = this.dataPoints[i].pointRight;
  4213. top = this.dataPoints[i].pointTop;
  4214. if (point !== undefined) {
  4215. if (this.showPerspective) {
  4216. lineWidth = 2 / -point.trans.z;
  4217. }
  4218. else {
  4219. lineWidth = 2 * -(this.eye.z / this.camera.getArmLength());
  4220. }
  4221. }
  4222. if (point !== undefined && right !== undefined) {
  4223. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4224. zAvg = (point.point.z + right.point.z) / 2;
  4225. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4226. ctx.lineWidth = lineWidth;
  4227. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  4228. ctx.beginPath();
  4229. ctx.moveTo(point.screen.x, point.screen.y);
  4230. ctx.lineTo(right.screen.x, right.screen.y);
  4231. ctx.stroke();
  4232. }
  4233. if (point !== undefined && top !== undefined) {
  4234. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4235. zAvg = (point.point.z + top.point.z) / 2;
  4236. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4237. ctx.lineWidth = lineWidth;
  4238. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  4239. ctx.beginPath();
  4240. ctx.moveTo(point.screen.x, point.screen.y);
  4241. ctx.lineTo(top.screen.x, top.screen.y);
  4242. ctx.stroke();
  4243. }
  4244. }
  4245. }
  4246. };
  4247. /**
  4248. * Draw all datapoints as dots.
  4249. * This function can be used when the style is 'dot' or 'dot-line'
  4250. */
  4251. Graph3d.prototype._redrawDataDot = function() {
  4252. var canvas = this.frame.canvas;
  4253. var ctx = canvas.getContext('2d');
  4254. var i;
  4255. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  4256. return; // TODO: throw exception?
  4257. // calculate the translations of all points
  4258. for (i = 0; i < this.dataPoints.length; i++) {
  4259. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  4260. var screen = this._convertTranslationToScreen(trans);
  4261. this.dataPoints[i].trans = trans;
  4262. this.dataPoints[i].screen = screen;
  4263. // calculate the distance from the point at the bottom to the camera
  4264. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  4265. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  4266. }
  4267. // order the translated points by depth
  4268. var sortDepth = function (a, b) {
  4269. return b.dist - a.dist;
  4270. };
  4271. this.dataPoints.sort(sortDepth);
  4272. // draw the datapoints as colored circles
  4273. var dotSize = this.frame.clientWidth * 0.02; // px
  4274. for (i = 0; i < this.dataPoints.length; i++) {
  4275. var point = this.dataPoints[i];
  4276. if (this.style === Graph3d.STYLE.DOTLINE) {
  4277. // draw a vertical line from the bottom to the graph value
  4278. //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin));
  4279. var from = this._convert3Dto2D(point.bottom);
  4280. ctx.lineWidth = 1;
  4281. ctx.strokeStyle = this.colorGrid;
  4282. ctx.beginPath();
  4283. ctx.moveTo(from.x, from.y);
  4284. ctx.lineTo(point.screen.x, point.screen.y);
  4285. ctx.stroke();
  4286. }
  4287. // calculate radius for the circle
  4288. var size;
  4289. if (this.style === Graph3d.STYLE.DOTSIZE) {
  4290. size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin);
  4291. }
  4292. else {
  4293. size = dotSize;
  4294. }
  4295. var radius;
  4296. if (this.showPerspective) {
  4297. radius = size / -point.trans.z;
  4298. }
  4299. else {
  4300. radius = size * -(this.eye.z / this.camera.getArmLength());
  4301. }
  4302. if (radius < 0) {
  4303. radius = 0;
  4304. }
  4305. var hue, color, borderColor;
  4306. if (this.style === Graph3d.STYLE.DOTCOLOR ) {
  4307. // calculate the color based on the value
  4308. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  4309. color = this._hsv2rgb(hue, 1, 1);
  4310. borderColor = this._hsv2rgb(hue, 1, 0.8);
  4311. }
  4312. else if (this.style === Graph3d.STYLE.DOTSIZE) {
  4313. color = this.colorDot;
  4314. borderColor = this.colorDotBorder;
  4315. }
  4316. else {
  4317. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4318. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4319. color = this._hsv2rgb(hue, 1, 1);
  4320. borderColor = this._hsv2rgb(hue, 1, 0.8);
  4321. }
  4322. // draw the circle
  4323. ctx.lineWidth = 1.0;
  4324. ctx.strokeStyle = borderColor;
  4325. ctx.fillStyle = color;
  4326. ctx.beginPath();
  4327. ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true);
  4328. ctx.fill();
  4329. ctx.stroke();
  4330. }
  4331. };
  4332. /**
  4333. * Draw all datapoints as bars.
  4334. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size'
  4335. */
  4336. Graph3d.prototype._redrawDataBar = function() {
  4337. var canvas = this.frame.canvas;
  4338. var ctx = canvas.getContext('2d');
  4339. var i, j, surface, corners;
  4340. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  4341. return; // TODO: throw exception?
  4342. // calculate the translations of all points
  4343. for (i = 0; i < this.dataPoints.length; i++) {
  4344. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  4345. var screen = this._convertTranslationToScreen(trans);
  4346. this.dataPoints[i].trans = trans;
  4347. this.dataPoints[i].screen = screen;
  4348. // calculate the distance from the point at the bottom to the camera
  4349. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  4350. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  4351. }
  4352. // order the translated points by depth
  4353. var sortDepth = function (a, b) {
  4354. return b.dist - a.dist;
  4355. };
  4356. this.dataPoints.sort(sortDepth);
  4357. // draw the datapoints as bars
  4358. var xWidth = this.xBarWidth / 2;
  4359. var yWidth = this.yBarWidth / 2;
  4360. for (i = 0; i < this.dataPoints.length; i++) {
  4361. var point = this.dataPoints[i];
  4362. // determine color
  4363. var hue, color, borderColor;
  4364. if (this.style === Graph3d.STYLE.BARCOLOR ) {
  4365. // calculate the color based on the value
  4366. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  4367. color = this._hsv2rgb(hue, 1, 1);
  4368. borderColor = this._hsv2rgb(hue, 1, 0.8);
  4369. }
  4370. else if (this.style === Graph3d.STYLE.BARSIZE) {
  4371. color = this.colorDot;
  4372. borderColor = this.colorDotBorder;
  4373. }
  4374. else {
  4375. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4376. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4377. color = this._hsv2rgb(hue, 1, 1);
  4378. borderColor = this._hsv2rgb(hue, 1, 0.8);
  4379. }
  4380. // calculate size for the bar
  4381. if (this.style === Graph3d.STYLE.BARSIZE) {
  4382. xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  4383. yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  4384. }
  4385. // calculate all corner points
  4386. var me = this;
  4387. var point3d = point.point;
  4388. var top = [
  4389. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)},
  4390. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)},
  4391. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)},
  4392. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)}
  4393. ];
  4394. var bottom = [
  4395. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin)},
  4396. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin)},
  4397. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)},
  4398. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)}
  4399. ];
  4400. // calculate screen location of the points
  4401. top.forEach(function (obj) {
  4402. obj.screen = me._convert3Dto2D(obj.point);
  4403. });
  4404. bottom.forEach(function (obj) {
  4405. obj.screen = me._convert3Dto2D(obj.point);
  4406. });
  4407. // create five sides, calculate both corner points and center points
  4408. var surfaces = [
  4409. {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)},
  4410. {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)},
  4411. {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)},
  4412. {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)},
  4413. {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)}
  4414. ];
  4415. point.surfaces = surfaces;
  4416. // calculate the distance of each of the surface centers to the camera
  4417. for (j = 0; j < surfaces.length; j++) {
  4418. surface = surfaces[j];
  4419. var transCenter = this._convertPointToTranslation(surface.center);
  4420. surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
  4421. // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
  4422. // but the current solution is fast/simple and works in 99.9% of all cases
  4423. // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
  4424. }
  4425. // order the surfaces by their (translated) depth
  4426. surfaces.sort(function (a, b) {
  4427. var diff = b.dist - a.dist;
  4428. if (diff) return diff;
  4429. // if equal depth, sort the top surface last
  4430. if (a.corners === top) return 1;
  4431. if (b.corners === top) return -1;
  4432. // both are equal
  4433. return 0;
  4434. });
  4435. // draw the ordered surfaces
  4436. ctx.lineWidth = 1;
  4437. ctx.strokeStyle = borderColor;
  4438. ctx.fillStyle = color;
  4439. // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
  4440. for (j = 2; j < surfaces.length; j++) {
  4441. surface = surfaces[j];
  4442. corners = surface.corners;
  4443. ctx.beginPath();
  4444. ctx.moveTo(corners[3].screen.x, corners[3].screen.y);
  4445. ctx.lineTo(corners[0].screen.x, corners[0].screen.y);
  4446. ctx.lineTo(corners[1].screen.x, corners[1].screen.y);
  4447. ctx.lineTo(corners[2].screen.x, corners[2].screen.y);
  4448. ctx.lineTo(corners[3].screen.x, corners[3].screen.y);
  4449. ctx.fill();
  4450. ctx.stroke();
  4451. }
  4452. }
  4453. };
  4454. /**
  4455. * Draw a line through all datapoints.
  4456. * This function can be used when the style is 'line'
  4457. */
  4458. Graph3d.prototype._redrawDataLine = function() {
  4459. var canvas = this.frame.canvas,
  4460. ctx = canvas.getContext('2d'),
  4461. point, i;
  4462. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  4463. return; // TODO: throw exception?
  4464. // calculate the translations of all points
  4465. for (i = 0; i < this.dataPoints.length; i++) {
  4466. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  4467. var screen = this._convertTranslationToScreen(trans);
  4468. this.dataPoints[i].trans = trans;
  4469. this.dataPoints[i].screen = screen;
  4470. }
  4471. // start the line
  4472. if (this.dataPoints.length > 0) {
  4473. point = this.dataPoints[0];
  4474. ctx.lineWidth = 1; // TODO: make customizable
  4475. ctx.strokeStyle = 'blue'; // TODO: make customizable
  4476. ctx.beginPath();
  4477. ctx.moveTo(point.screen.x, point.screen.y);
  4478. }
  4479. // draw the datapoints as colored circles
  4480. for (i = 1; i < this.dataPoints.length; i++) {
  4481. point = this.dataPoints[i];
  4482. ctx.lineTo(point.screen.x, point.screen.y);
  4483. }
  4484. // finish the line
  4485. if (this.dataPoints.length > 0) {
  4486. ctx.stroke();
  4487. }
  4488. };
  4489. /**
  4490. * Start a moving operation inside the provided parent element
  4491. * @param {Event} event The event that occurred (required for
  4492. * retrieving the mouse position)
  4493. */
  4494. Graph3d.prototype._onMouseDown = function(event) {
  4495. event = event || window.event;
  4496. // check if mouse is still down (may be up when focus is lost for example
  4497. // in an iframe)
  4498. if (this.leftButtonDown) {
  4499. this._onMouseUp(event);
  4500. }
  4501. // only react on left mouse button down
  4502. this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  4503. if (!this.leftButtonDown && !this.touchDown) return;
  4504. // get mouse position (different code for IE and all other browsers)
  4505. this.startMouseX = getMouseX(event);
  4506. this.startMouseY = getMouseY(event);
  4507. this.startStart = new Date(this.start);
  4508. this.startEnd = new Date(this.end);
  4509. this.startArmRotation = this.camera.getArmRotation();
  4510. this.frame.style.cursor = 'move';
  4511. // add event listeners to handle moving the contents
  4512. // we store the function onmousemove and onmouseup in the graph, so we can
  4513. // remove the eventlisteners lateron in the function mouseUp()
  4514. var me = this;
  4515. this.onmousemove = function (event) {me._onMouseMove(event);};
  4516. this.onmouseup = function (event) {me._onMouseUp(event);};
  4517. util.addEventListener(document, 'mousemove', me.onmousemove);
  4518. util.addEventListener(document, 'mouseup', me.onmouseup);
  4519. util.preventDefault(event);
  4520. };
  4521. /**
  4522. * Perform moving operating.
  4523. * This function activated from within the funcion Graph.mouseDown().
  4524. * @param {Event} event Well, eehh, the event
  4525. */
  4526. Graph3d.prototype._onMouseMove = function (event) {
  4527. event = event || window.event;
  4528. // calculate change in mouse position
  4529. var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
  4530. var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
  4531. var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
  4532. var verticalNew = this.startArmRotation.vertical + diffY / 200;
  4533. var snapAngle = 4; // degrees
  4534. var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
  4535. // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
  4536. // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
  4537. if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
  4538. horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001;
  4539. }
  4540. if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
  4541. horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001;
  4542. }
  4543. // snap vertically to nice angles
  4544. if (Math.abs(Math.sin(verticalNew)) < snapValue) {
  4545. verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI;
  4546. }
  4547. if (Math.abs(Math.cos(verticalNew)) < snapValue) {
  4548. verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI;
  4549. }
  4550. this.camera.setArmRotation(horizontalNew, verticalNew);
  4551. this.redraw();
  4552. // fire a cameraPositionChange event
  4553. var parameters = this.getCameraPosition();
  4554. this.emit('cameraPositionChange', parameters);
  4555. util.preventDefault(event);
  4556. };
  4557. /**
  4558. * Stop moving operating.
  4559. * This function activated from within the funcion Graph.mouseDown().
  4560. * @param {event} event The event
  4561. */
  4562. Graph3d.prototype._onMouseUp = function (event) {
  4563. this.frame.style.cursor = 'auto';
  4564. this.leftButtonDown = false;
  4565. // remove event listeners here
  4566. util.removeEventListener(document, 'mousemove', this.onmousemove);
  4567. util.removeEventListener(document, 'mouseup', this.onmouseup);
  4568. util.preventDefault(event);
  4569. };
  4570. /**
  4571. * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
  4572. * @param {Event} event A mouse move event
  4573. */
  4574. Graph3d.prototype._onTooltip = function (event) {
  4575. var delay = 300; // ms
  4576. var boundingRect = this.frame.getBoundingClientRect();
  4577. var mouseX = getMouseX(event) - boundingRect.left;
  4578. var mouseY = getMouseY(event) - boundingRect.top;
  4579. if (!this.showTooltip) {
  4580. return;
  4581. }
  4582. if (this.tooltipTimeout) {
  4583. clearTimeout(this.tooltipTimeout);
  4584. }
  4585. // (delayed) display of a tooltip only if no mouse button is down
  4586. if (this.leftButtonDown) {
  4587. this._hideTooltip();
  4588. return;
  4589. }
  4590. if (this.tooltip && this.tooltip.dataPoint) {
  4591. // tooltip is currently visible
  4592. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  4593. if (dataPoint !== this.tooltip.dataPoint) {
  4594. // datapoint changed
  4595. if (dataPoint) {
  4596. this._showTooltip(dataPoint);
  4597. }
  4598. else {
  4599. this._hideTooltip();
  4600. }
  4601. }
  4602. }
  4603. else {
  4604. // tooltip is currently not visible
  4605. var me = this;
  4606. this.tooltipTimeout = setTimeout(function () {
  4607. me.tooltipTimeout = null;
  4608. // show a tooltip if we have a data point
  4609. var dataPoint = me._dataPointFromXY(mouseX, mouseY);
  4610. if (dataPoint) {
  4611. me._showTooltip(dataPoint);
  4612. }
  4613. }, delay);
  4614. }
  4615. };
  4616. /**
  4617. * Event handler for touchstart event on mobile devices
  4618. */
  4619. Graph3d.prototype._onTouchStart = function(event) {
  4620. this.touchDown = true;
  4621. var me = this;
  4622. this.ontouchmove = function (event) {me._onTouchMove(event);};
  4623. this.ontouchend = function (event) {me._onTouchEnd(event);};
  4624. util.addEventListener(document, 'touchmove', me.ontouchmove);
  4625. util.addEventListener(document, 'touchend', me.ontouchend);
  4626. this._onMouseDown(event);
  4627. };
  4628. /**
  4629. * Event handler for touchmove event on mobile devices
  4630. */
  4631. Graph3d.prototype._onTouchMove = function(event) {
  4632. this._onMouseMove(event);
  4633. };
  4634. /**
  4635. * Event handler for touchend event on mobile devices
  4636. */
  4637. Graph3d.prototype._onTouchEnd = function(event) {
  4638. this.touchDown = false;
  4639. util.removeEventListener(document, 'touchmove', this.ontouchmove);
  4640. util.removeEventListener(document, 'touchend', this.ontouchend);
  4641. this._onMouseUp(event);
  4642. };
  4643. /**
  4644. * Event handler for mouse wheel event, used to zoom the graph
  4645. * Code from http://adomas.org/javascript-mouse-wheel/
  4646. * @param {event} event The event
  4647. */
  4648. Graph3d.prototype._onWheel = function(event) {
  4649. if (!event) /* For IE. */
  4650. event = window.event;
  4651. // retrieve delta
  4652. var delta = 0;
  4653. if (event.wheelDelta) { /* IE/Opera. */
  4654. delta = event.wheelDelta/120;
  4655. } else if (event.detail) { /* Mozilla case. */
  4656. // In Mozilla, sign of delta is different than in IE.
  4657. // Also, delta is multiple of 3.
  4658. delta = -event.detail/3;
  4659. }
  4660. // If delta is nonzero, handle it.
  4661. // Basically, delta is now positive if wheel was scrolled up,
  4662. // and negative, if wheel was scrolled down.
  4663. if (delta) {
  4664. var oldLength = this.camera.getArmLength();
  4665. var newLength = oldLength * (1 - delta / 10);
  4666. this.camera.setArmLength(newLength);
  4667. this.redraw();
  4668. this._hideTooltip();
  4669. }
  4670. // fire a cameraPositionChange event
  4671. var parameters = this.getCameraPosition();
  4672. this.emit('cameraPositionChange', parameters);
  4673. // Prevent default actions caused by mouse wheel.
  4674. // That might be ugly, but we handle scrolls somehow
  4675. // anyway, so don't bother here..
  4676. util.preventDefault(event);
  4677. };
  4678. /**
  4679. * Test whether a point lies inside given 2D triangle
  4680. * @param {Point2d} point
  4681. * @param {Point2d[]} triangle
  4682. * @return {boolean} Returns true if given point lies inside or on the edge of the triangle
  4683. * @private
  4684. */
  4685. Graph3d.prototype._insideTriangle = function (point, triangle) {
  4686. var a = triangle[0],
  4687. b = triangle[1],
  4688. c = triangle[2];
  4689. function sign (x) {
  4690. return x > 0 ? 1 : x < 0 ? -1 : 0;
  4691. }
  4692. var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
  4693. var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
  4694. var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
  4695. // each of the three signs must be either equal to each other or zero
  4696. return (as == 0 || bs == 0 || as == bs) &&
  4697. (bs == 0 || cs == 0 || bs == cs) &&
  4698. (as == 0 || cs == 0 || as == cs);
  4699. };
  4700. /**
  4701. * Find a data point close to given screen position (x, y)
  4702. * @param {Number} x
  4703. * @param {Number} y
  4704. * @return {Object | null} The closest data point or null if not close to any data point
  4705. * @private
  4706. */
  4707. Graph3d.prototype._dataPointFromXY = function (x, y) {
  4708. var i,
  4709. distMax = 100, // px
  4710. dataPoint = null,
  4711. closestDataPoint = null,
  4712. closestDist = null,
  4713. center = new Point2d(x, y);
  4714. if (this.style === Graph3d.STYLE.BAR ||
  4715. this.style === Graph3d.STYLE.BARCOLOR ||
  4716. this.style === Graph3d.STYLE.BARSIZE) {
  4717. // the data points are ordered from far away to closest
  4718. for (i = this.dataPoints.length - 1; i >= 0; i--) {
  4719. dataPoint = this.dataPoints[i];
  4720. var surfaces = dataPoint.surfaces;
  4721. if (surfaces) {
  4722. for (var s = surfaces.length - 1; s >= 0; s--) {
  4723. // split each surface in two triangles, and see if the center point is inside one of these
  4724. var surface = surfaces[s];
  4725. var corners = surface.corners;
  4726. var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
  4727. var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
  4728. if (this._insideTriangle(center, triangle1) ||
  4729. this._insideTriangle(center, triangle2)) {
  4730. // return immediately at the first hit
  4731. return dataPoint;
  4732. }
  4733. }
  4734. }
  4735. }
  4736. }
  4737. else {
  4738. // find the closest data point, using distance to the center of the point on 2d screen
  4739. for (i = 0; i < this.dataPoints.length; i++) {
  4740. dataPoint = this.dataPoints[i];
  4741. var point = dataPoint.screen;
  4742. if (point) {
  4743. var distX = Math.abs(x - point.x);
  4744. var distY = Math.abs(y - point.y);
  4745. var dist = Math.sqrt(distX * distX + distY * distY);
  4746. if ((closestDist === null || dist < closestDist) && dist < distMax) {
  4747. closestDist = dist;
  4748. closestDataPoint = dataPoint;
  4749. }
  4750. }
  4751. }
  4752. }
  4753. return closestDataPoint;
  4754. };
  4755. /**
  4756. * Display a tooltip for given data point
  4757. * @param {Object} dataPoint
  4758. * @private
  4759. */
  4760. Graph3d.prototype._showTooltip = function (dataPoint) {
  4761. var content, line, dot;
  4762. if (!this.tooltip) {
  4763. content = document.createElement('div');
  4764. content.style.position = 'absolute';
  4765. content.style.padding = '10px';
  4766. content.style.border = '1px solid #4d4d4d';
  4767. content.style.color = '#1a1a1a';
  4768. content.style.background = 'rgba(255,255,255,0.7)';
  4769. content.style.borderRadius = '2px';
  4770. content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)';
  4771. line = document.createElement('div');
  4772. line.style.position = 'absolute';
  4773. line.style.height = '40px';
  4774. line.style.width = '0';
  4775. line.style.borderLeft = '1px solid #4d4d4d';
  4776. dot = document.createElement('div');
  4777. dot.style.position = 'absolute';
  4778. dot.style.height = '0';
  4779. dot.style.width = '0';
  4780. dot.style.border = '5px solid #4d4d4d';
  4781. dot.style.borderRadius = '5px';
  4782. this.tooltip = {
  4783. dataPoint: null,
  4784. dom: {
  4785. content: content,
  4786. line: line,
  4787. dot: dot
  4788. }
  4789. };
  4790. }
  4791. else {
  4792. content = this.tooltip.dom.content;
  4793. line = this.tooltip.dom.line;
  4794. dot = this.tooltip.dom.dot;
  4795. }
  4796. this._hideTooltip();
  4797. this.tooltip.dataPoint = dataPoint;
  4798. if (typeof this.showTooltip === 'function') {
  4799. content.innerHTML = this.showTooltip(dataPoint.point);
  4800. }
  4801. else {
  4802. content.innerHTML = '<table>' +
  4803. '<tr><td>x:</td><td>' + dataPoint.point.x + '</td></tr>' +
  4804. '<tr><td>y:</td><td>' + dataPoint.point.y + '</td></tr>' +
  4805. '<tr><td>z:</td><td>' + dataPoint.point.z + '</td></tr>' +
  4806. '</table>';
  4807. }
  4808. content.style.left = '0';
  4809. content.style.top = '0';
  4810. this.frame.appendChild(content);
  4811. this.frame.appendChild(line);
  4812. this.frame.appendChild(dot);
  4813. // calculate sizes
  4814. var contentWidth = content.offsetWidth;
  4815. var contentHeight = content.offsetHeight;
  4816. var lineHeight = line.offsetHeight;
  4817. var dotWidth = dot.offsetWidth;
  4818. var dotHeight = dot.offsetHeight;
  4819. var left = dataPoint.screen.x - contentWidth / 2;
  4820. left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
  4821. line.style.left = dataPoint.screen.x + 'px';
  4822. line.style.top = (dataPoint.screen.y - lineHeight) + 'px';
  4823. content.style.left = left + 'px';
  4824. content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px';
  4825. dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px';
  4826. dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px';
  4827. };
  4828. /**
  4829. * Hide the tooltip when displayed
  4830. * @private
  4831. */
  4832. Graph3d.prototype._hideTooltip = function () {
  4833. if (this.tooltip) {
  4834. this.tooltip.dataPoint = null;
  4835. for (var prop in this.tooltip.dom) {
  4836. if (this.tooltip.dom.hasOwnProperty(prop)) {
  4837. var elem = this.tooltip.dom[prop];
  4838. if (elem && elem.parentNode) {
  4839. elem.parentNode.removeChild(elem);
  4840. }
  4841. }
  4842. }
  4843. }
  4844. };
  4845. /**--------------------------------------------------------------------------**/
  4846. /**
  4847. * Get the horizontal mouse position from a mouse event
  4848. * @param {Event} event
  4849. * @return {Number} mouse x
  4850. */
  4851. function getMouseX (event) {
  4852. if ('clientX' in event) return event.clientX;
  4853. return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
  4854. }
  4855. /**
  4856. * Get the vertical mouse position from a mouse event
  4857. * @param {Event} event
  4858. * @return {Number} mouse y
  4859. */
  4860. function getMouseY (event) {
  4861. if ('clientY' in event) return event.clientY;
  4862. return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
  4863. }
  4864. module.exports = Graph3d;
  4865. /***/ },
  4866. /* 7 */
  4867. /***/ function(module, exports, __webpack_require__) {
  4868. var Point3d = __webpack_require__(10);
  4869. /**
  4870. * @class Camera
  4871. * The camera is mounted on a (virtual) camera arm. The camera arm can rotate
  4872. * The camera is always looking in the direction of the origin of the arm.
  4873. * This way, the camera always rotates around one fixed point, the location
  4874. * of the camera arm.
  4875. *
  4876. * Documentation:
  4877. * http://en.wikipedia.org/wiki/3D_projection
  4878. */
  4879. function Camera() {
  4880. this.armLocation = new Point3d();
  4881. this.armRotation = {};
  4882. this.armRotation.horizontal = 0;
  4883. this.armRotation.vertical = 0;
  4884. this.armLength = 1.7;
  4885. this.cameraLocation = new Point3d();
  4886. this.cameraRotation = new Point3d(0.5*Math.PI, 0, 0);
  4887. this.calculateCameraOrientation();
  4888. }
  4889. /**
  4890. * Set the location (origin) of the arm
  4891. * @param {Number} x Normalized value of x
  4892. * @param {Number} y Normalized value of y
  4893. * @param {Number} z Normalized value of z
  4894. */
  4895. Camera.prototype.setArmLocation = function(x, y, z) {
  4896. this.armLocation.x = x;
  4897. this.armLocation.y = y;
  4898. this.armLocation.z = z;
  4899. this.calculateCameraOrientation();
  4900. };
  4901. /**
  4902. * Set the rotation of the camera arm
  4903. * @param {Number} horizontal The horizontal rotation, between 0 and 2*PI.
  4904. * Optional, can be left undefined.
  4905. * @param {Number} vertical The vertical rotation, between 0 and 0.5*PI
  4906. * if vertical=0.5*PI, the graph is shown from the
  4907. * top. Optional, can be left undefined.
  4908. */
  4909. Camera.prototype.setArmRotation = function(horizontal, vertical) {
  4910. if (horizontal !== undefined) {
  4911. this.armRotation.horizontal = horizontal;
  4912. }
  4913. if (vertical !== undefined) {
  4914. this.armRotation.vertical = vertical;
  4915. if (this.armRotation.vertical < 0) this.armRotation.vertical = 0;
  4916. if (this.armRotation.vertical > 0.5*Math.PI) this.armRotation.vertical = 0.5*Math.PI;
  4917. }
  4918. if (horizontal !== undefined || vertical !== undefined) {
  4919. this.calculateCameraOrientation();
  4920. }
  4921. };
  4922. /**
  4923. * Retrieve the current arm rotation
  4924. * @return {object} An object with parameters horizontal and vertical
  4925. */
  4926. Camera.prototype.getArmRotation = function() {
  4927. var rot = {};
  4928. rot.horizontal = this.armRotation.horizontal;
  4929. rot.vertical = this.armRotation.vertical;
  4930. return rot;
  4931. };
  4932. /**
  4933. * Set the (normalized) length of the camera arm.
  4934. * @param {Number} length A length between 0.71 and 5.0
  4935. */
  4936. Camera.prototype.setArmLength = function(length) {
  4937. if (length === undefined)
  4938. return;
  4939. this.armLength = length;
  4940. // Radius must be larger than the corner of the graph,
  4941. // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the
  4942. // graph
  4943. if (this.armLength < 0.71) this.armLength = 0.71;
  4944. if (this.armLength > 5.0) this.armLength = 5.0;
  4945. this.calculateCameraOrientation();
  4946. };
  4947. /**
  4948. * Retrieve the arm length
  4949. * @return {Number} length
  4950. */
  4951. Camera.prototype.getArmLength = function() {
  4952. return this.armLength;
  4953. };
  4954. /**
  4955. * Retrieve the camera location
  4956. * @return {Point3d} cameraLocation
  4957. */
  4958. Camera.prototype.getCameraLocation = function() {
  4959. return this.cameraLocation;
  4960. };
  4961. /**
  4962. * Retrieve the camera rotation
  4963. * @return {Point3d} cameraRotation
  4964. */
  4965. Camera.prototype.getCameraRotation = function() {
  4966. return this.cameraRotation;
  4967. };
  4968. /**
  4969. * Calculate the location and rotation of the camera based on the
  4970. * position and orientation of the camera arm
  4971. */
  4972. Camera.prototype.calculateCameraOrientation = function() {
  4973. // calculate location of the camera
  4974. this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  4975. this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  4976. this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical);
  4977. // calculate rotation of the camera
  4978. this.cameraRotation.x = Math.PI/2 - this.armRotation.vertical;
  4979. this.cameraRotation.y = 0;
  4980. this.cameraRotation.z = -this.armRotation.horizontal;
  4981. };
  4982. module.exports = Camera;
  4983. /***/ },
  4984. /* 8 */
  4985. /***/ function(module, exports, __webpack_require__) {
  4986. var DataView = __webpack_require__(4);
  4987. /**
  4988. * @class Filter
  4989. *
  4990. * @param {DataSet} data The google data table
  4991. * @param {Number} column The index of the column to be filtered
  4992. * @param {Graph} graph The graph
  4993. */
  4994. function Filter (data, column, graph) {
  4995. this.data = data;
  4996. this.column = column;
  4997. this.graph = graph; // the parent graph
  4998. this.index = undefined;
  4999. this.value = undefined;
  5000. // read all distinct values and select the first one
  5001. this.values = graph.getDistinctValues(data.get(), this.column);
  5002. // sort both numeric and string values correctly
  5003. this.values.sort(function (a, b) {
  5004. return a > b ? 1 : a < b ? -1 : 0;
  5005. });
  5006. if (this.values.length > 0) {
  5007. this.selectValue(0);
  5008. }
  5009. // create an array with the filtered datapoints. this will be loaded afterwards
  5010. this.dataPoints = [];
  5011. this.loaded = false;
  5012. this.onLoadCallback = undefined;
  5013. if (graph.animationPreload) {
  5014. this.loaded = false;
  5015. this.loadInBackground();
  5016. }
  5017. else {
  5018. this.loaded = true;
  5019. }
  5020. };
  5021. /**
  5022. * Return the label
  5023. * @return {string} label
  5024. */
  5025. Filter.prototype.isLoaded = function() {
  5026. return this.loaded;
  5027. };
  5028. /**
  5029. * Return the loaded progress
  5030. * @return {Number} percentage between 0 and 100
  5031. */
  5032. Filter.prototype.getLoadedProgress = function() {
  5033. var len = this.values.length;
  5034. var i = 0;
  5035. while (this.dataPoints[i]) {
  5036. i++;
  5037. }
  5038. return Math.round(i / len * 100);
  5039. };
  5040. /**
  5041. * Return the label
  5042. * @return {string} label
  5043. */
  5044. Filter.prototype.getLabel = function() {
  5045. return this.graph.filterLabel;
  5046. };
  5047. /**
  5048. * Return the columnIndex of the filter
  5049. * @return {Number} columnIndex
  5050. */
  5051. Filter.prototype.getColumn = function() {
  5052. return this.column;
  5053. };
  5054. /**
  5055. * Return the currently selected value. Returns undefined if there is no selection
  5056. * @return {*} value
  5057. */
  5058. Filter.prototype.getSelectedValue = function() {
  5059. if (this.index === undefined)
  5060. return undefined;
  5061. return this.values[this.index];
  5062. };
  5063. /**
  5064. * Retrieve all values of the filter
  5065. * @return {Array} values
  5066. */
  5067. Filter.prototype.getValues = function() {
  5068. return this.values;
  5069. };
  5070. /**
  5071. * Retrieve one value of the filter
  5072. * @param {Number} index
  5073. * @return {*} value
  5074. */
  5075. Filter.prototype.getValue = function(index) {
  5076. if (index >= this.values.length)
  5077. throw 'Error: index out of range';
  5078. return this.values[index];
  5079. };
  5080. /**
  5081. * Retrieve the (filtered) dataPoints for the currently selected filter index
  5082. * @param {Number} [index] (optional)
  5083. * @return {Array} dataPoints
  5084. */
  5085. Filter.prototype._getDataPoints = function(index) {
  5086. if (index === undefined)
  5087. index = this.index;
  5088. if (index === undefined)
  5089. return [];
  5090. var dataPoints;
  5091. if (this.dataPoints[index]) {
  5092. dataPoints = this.dataPoints[index];
  5093. }
  5094. else {
  5095. var f = {};
  5096. f.column = this.column;
  5097. f.value = this.values[index];
  5098. var dataView = new DataView(this.data,{filter: function (item) {return (item[f.column] == f.value);}}).get();
  5099. dataPoints = this.graph._getDataPoints(dataView);
  5100. this.dataPoints[index] = dataPoints;
  5101. }
  5102. return dataPoints;
  5103. };
  5104. /**
  5105. * Set a callback function when the filter is fully loaded.
  5106. */
  5107. Filter.prototype.setOnLoadCallback = function(callback) {
  5108. this.onLoadCallback = callback;
  5109. };
  5110. /**
  5111. * Add a value to the list with available values for this filter
  5112. * No double entries will be created.
  5113. * @param {Number} index
  5114. */
  5115. Filter.prototype.selectValue = function(index) {
  5116. if (index >= this.values.length)
  5117. throw 'Error: index out of range';
  5118. this.index = index;
  5119. this.value = this.values[index];
  5120. };
  5121. /**
  5122. * Load all filtered rows in the background one by one
  5123. * Start this method without providing an index!
  5124. */
  5125. Filter.prototype.loadInBackground = function(index) {
  5126. if (index === undefined)
  5127. index = 0;
  5128. var frame = this.graph.frame;
  5129. if (index < this.values.length) {
  5130. var dataPointsTemp = this._getDataPoints(index);
  5131. //this.graph.redrawInfo(); // TODO: not neat
  5132. // create a progress box
  5133. if (frame.progress === undefined) {
  5134. frame.progress = document.createElement('DIV');
  5135. frame.progress.style.position = 'absolute';
  5136. frame.progress.style.color = 'gray';
  5137. frame.appendChild(frame.progress);
  5138. }
  5139. var progress = this.getLoadedProgress();
  5140. frame.progress.innerHTML = 'Loading animation... ' + progress + '%';
  5141. // TODO: this is no nice solution...
  5142. frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider
  5143. frame.progress.style.left = 10 + 'px';
  5144. var me = this;
  5145. setTimeout(function() {me.loadInBackground(index+1);}, 10);
  5146. this.loaded = false;
  5147. }
  5148. else {
  5149. this.loaded = true;
  5150. // remove the progress box
  5151. if (frame.progress !== undefined) {
  5152. frame.removeChild(frame.progress);
  5153. frame.progress = undefined;
  5154. }
  5155. if (this.onLoadCallback)
  5156. this.onLoadCallback();
  5157. }
  5158. };
  5159. module.exports = Filter;
  5160. /***/ },
  5161. /* 9 */
  5162. /***/ function(module, exports, __webpack_require__) {
  5163. /**
  5164. * @prototype Point2d
  5165. * @param {Number} [x]
  5166. * @param {Number} [y]
  5167. */
  5168. function Point2d (x, y) {
  5169. this.x = x !== undefined ? x : 0;
  5170. this.y = y !== undefined ? y : 0;
  5171. }
  5172. module.exports = Point2d;
  5173. /***/ },
  5174. /* 10 */
  5175. /***/ function(module, exports, __webpack_require__) {
  5176. /**
  5177. * @prototype Point3d
  5178. * @param {Number} [x]
  5179. * @param {Number} [y]
  5180. * @param {Number} [z]
  5181. */
  5182. function Point3d(x, y, z) {
  5183. this.x = x !== undefined ? x : 0;
  5184. this.y = y !== undefined ? y : 0;
  5185. this.z = z !== undefined ? z : 0;
  5186. };
  5187. /**
  5188. * Subtract the two provided points, returns a-b
  5189. * @param {Point3d} a
  5190. * @param {Point3d} b
  5191. * @return {Point3d} a-b
  5192. */
  5193. Point3d.subtract = function(a, b) {
  5194. var sub = new Point3d();
  5195. sub.x = a.x - b.x;
  5196. sub.y = a.y - b.y;
  5197. sub.z = a.z - b.z;
  5198. return sub;
  5199. };
  5200. /**
  5201. * Add the two provided points, returns a+b
  5202. * @param {Point3d} a
  5203. * @param {Point3d} b
  5204. * @return {Point3d} a+b
  5205. */
  5206. Point3d.add = function(a, b) {
  5207. var sum = new Point3d();
  5208. sum.x = a.x + b.x;
  5209. sum.y = a.y + b.y;
  5210. sum.z = a.z + b.z;
  5211. return sum;
  5212. };
  5213. /**
  5214. * Calculate the average of two 3d points
  5215. * @param {Point3d} a
  5216. * @param {Point3d} b
  5217. * @return {Point3d} The average, (a+b)/2
  5218. */
  5219. Point3d.avg = function(a, b) {
  5220. return new Point3d(
  5221. (a.x + b.x) / 2,
  5222. (a.y + b.y) / 2,
  5223. (a.z + b.z) / 2
  5224. );
  5225. };
  5226. /**
  5227. * Calculate the cross product of the two provided points, returns axb
  5228. * Documentation: http://en.wikipedia.org/wiki/Cross_product
  5229. * @param {Point3d} a
  5230. * @param {Point3d} b
  5231. * @return {Point3d} cross product axb
  5232. */
  5233. Point3d.crossProduct = function(a, b) {
  5234. var crossproduct = new Point3d();
  5235. crossproduct.x = a.y * b.z - a.z * b.y;
  5236. crossproduct.y = a.z * b.x - a.x * b.z;
  5237. crossproduct.z = a.x * b.y - a.y * b.x;
  5238. return crossproduct;
  5239. };
  5240. /**
  5241. * Rtrieve the length of the vector (or the distance from this point to the origin
  5242. * @return {Number} length
  5243. */
  5244. Point3d.prototype.length = function() {
  5245. return Math.sqrt(
  5246. this.x * this.x +
  5247. this.y * this.y +
  5248. this.z * this.z
  5249. );
  5250. };
  5251. module.exports = Point3d;
  5252. /***/ },
  5253. /* 11 */
  5254. /***/ function(module, exports, __webpack_require__) {
  5255. var util = __webpack_require__(1);
  5256. /**
  5257. * @constructor Slider
  5258. *
  5259. * An html slider control with start/stop/prev/next buttons
  5260. * @param {Element} container The element where the slider will be created
  5261. * @param {Object} options Available options:
  5262. * {boolean} visible If true (default) the
  5263. * slider is visible.
  5264. */
  5265. function Slider(container, options) {
  5266. if (container === undefined) {
  5267. throw 'Error: No container element defined';
  5268. }
  5269. this.container = container;
  5270. this.visible = (options && options.visible != undefined) ? options.visible : true;
  5271. if (this.visible) {
  5272. this.frame = document.createElement('DIV');
  5273. //this.frame.style.backgroundColor = '#E5E5E5';
  5274. this.frame.style.width = '100%';
  5275. this.frame.style.position = 'relative';
  5276. this.container.appendChild(this.frame);
  5277. this.frame.prev = document.createElement('INPUT');
  5278. this.frame.prev.type = 'BUTTON';
  5279. this.frame.prev.value = 'Prev';
  5280. this.frame.appendChild(this.frame.prev);
  5281. this.frame.play = document.createElement('INPUT');
  5282. this.frame.play.type = 'BUTTON';
  5283. this.frame.play.value = 'Play';
  5284. this.frame.appendChild(this.frame.play);
  5285. this.frame.next = document.createElement('INPUT');
  5286. this.frame.next.type = 'BUTTON';
  5287. this.frame.next.value = 'Next';
  5288. this.frame.appendChild(this.frame.next);
  5289. this.frame.bar = document.createElement('INPUT');
  5290. this.frame.bar.type = 'BUTTON';
  5291. this.frame.bar.style.position = 'absolute';
  5292. this.frame.bar.style.border = '1px solid red';
  5293. this.frame.bar.style.width = '100px';
  5294. this.frame.bar.style.height = '6px';
  5295. this.frame.bar.style.borderRadius = '2px';
  5296. this.frame.bar.style.MozBorderRadius = '2px';
  5297. this.frame.bar.style.border = '1px solid #7F7F7F';
  5298. this.frame.bar.style.backgroundColor = '#E5E5E5';
  5299. this.frame.appendChild(this.frame.bar);
  5300. this.frame.slide = document.createElement('INPUT');
  5301. this.frame.slide.type = 'BUTTON';
  5302. this.frame.slide.style.margin = '0px';
  5303. this.frame.slide.value = ' ';
  5304. this.frame.slide.style.position = 'relative';
  5305. this.frame.slide.style.left = '-100px';
  5306. this.frame.appendChild(this.frame.slide);
  5307. // create events
  5308. var me = this;
  5309. this.frame.slide.onmousedown = function (event) {me._onMouseDown(event);};
  5310. this.frame.prev.onclick = function (event) {me.prev(event);};
  5311. this.frame.play.onclick = function (event) {me.togglePlay(event);};
  5312. this.frame.next.onclick = function (event) {me.next(event);};
  5313. }
  5314. this.onChangeCallback = undefined;
  5315. this.values = [];
  5316. this.index = undefined;
  5317. this.playTimeout = undefined;
  5318. this.playInterval = 1000; // milliseconds
  5319. this.playLoop = true;
  5320. }
  5321. /**
  5322. * Select the previous index
  5323. */
  5324. Slider.prototype.prev = function() {
  5325. var index = this.getIndex();
  5326. if (index > 0) {
  5327. index--;
  5328. this.setIndex(index);
  5329. }
  5330. };
  5331. /**
  5332. * Select the next index
  5333. */
  5334. Slider.prototype.next = function() {
  5335. var index = this.getIndex();
  5336. if (index < this.values.length - 1) {
  5337. index++;
  5338. this.setIndex(index);
  5339. }
  5340. };
  5341. /**
  5342. * Select the next index
  5343. */
  5344. Slider.prototype.playNext = function() {
  5345. var start = new Date();
  5346. var index = this.getIndex();
  5347. if (index < this.values.length - 1) {
  5348. index++;
  5349. this.setIndex(index);
  5350. }
  5351. else if (this.playLoop) {
  5352. // jump to the start
  5353. index = 0;
  5354. this.setIndex(index);
  5355. }
  5356. var end = new Date();
  5357. var diff = (end - start);
  5358. // calculate how much time it to to set the index and to execute the callback
  5359. // function.
  5360. var interval = Math.max(this.playInterval - diff, 0);
  5361. // document.title = diff // TODO: cleanup
  5362. var me = this;
  5363. this.playTimeout = setTimeout(function() {me.playNext();}, interval);
  5364. };
  5365. /**
  5366. * Toggle start or stop playing
  5367. */
  5368. Slider.prototype.togglePlay = function() {
  5369. if (this.playTimeout === undefined) {
  5370. this.play();
  5371. } else {
  5372. this.stop();
  5373. }
  5374. };
  5375. /**
  5376. * Start playing
  5377. */
  5378. Slider.prototype.play = function() {
  5379. // Test whether already playing
  5380. if (this.playTimeout) return;
  5381. this.playNext();
  5382. if (this.frame) {
  5383. this.frame.play.value = 'Stop';
  5384. }
  5385. };
  5386. /**
  5387. * Stop playing
  5388. */
  5389. Slider.prototype.stop = function() {
  5390. clearInterval(this.playTimeout);
  5391. this.playTimeout = undefined;
  5392. if (this.frame) {
  5393. this.frame.play.value = 'Play';
  5394. }
  5395. };
  5396. /**
  5397. * Set a callback function which will be triggered when the value of the
  5398. * slider bar has changed.
  5399. */
  5400. Slider.prototype.setOnChangeCallback = function(callback) {
  5401. this.onChangeCallback = callback;
  5402. };
  5403. /**
  5404. * Set the interval for playing the list
  5405. * @param {Number} interval The interval in milliseconds
  5406. */
  5407. Slider.prototype.setPlayInterval = function(interval) {
  5408. this.playInterval = interval;
  5409. };
  5410. /**
  5411. * Retrieve the current play interval
  5412. * @return {Number} interval The interval in milliseconds
  5413. */
  5414. Slider.prototype.getPlayInterval = function(interval) {
  5415. return this.playInterval;
  5416. };
  5417. /**
  5418. * Set looping on or off
  5419. * @pararm {boolean} doLoop If true, the slider will jump to the start when
  5420. * the end is passed, and will jump to the end
  5421. * when the start is passed.
  5422. */
  5423. Slider.prototype.setPlayLoop = function(doLoop) {
  5424. this.playLoop = doLoop;
  5425. };
  5426. /**
  5427. * Execute the onchange callback function
  5428. */
  5429. Slider.prototype.onChange = function() {
  5430. if (this.onChangeCallback !== undefined) {
  5431. this.onChangeCallback();
  5432. }
  5433. };
  5434. /**
  5435. * redraw the slider on the correct place
  5436. */
  5437. Slider.prototype.redraw = function() {
  5438. if (this.frame) {
  5439. // resize the bar
  5440. this.frame.bar.style.top = (this.frame.clientHeight/2 -
  5441. this.frame.bar.offsetHeight/2) + 'px';
  5442. this.frame.bar.style.width = (this.frame.clientWidth -
  5443. this.frame.prev.clientWidth -
  5444. this.frame.play.clientWidth -
  5445. this.frame.next.clientWidth - 30) + 'px';
  5446. // position the slider button
  5447. var left = this.indexToLeft(this.index);
  5448. this.frame.slide.style.left = (left) + 'px';
  5449. }
  5450. };
  5451. /**
  5452. * Set the list with values for the slider
  5453. * @param {Array} values A javascript array with values (any type)
  5454. */
  5455. Slider.prototype.setValues = function(values) {
  5456. this.values = values;
  5457. if (this.values.length > 0)
  5458. this.setIndex(0);
  5459. else
  5460. this.index = undefined;
  5461. };
  5462. /**
  5463. * Select a value by its index
  5464. * @param {Number} index
  5465. */
  5466. Slider.prototype.setIndex = function(index) {
  5467. if (index < this.values.length) {
  5468. this.index = index;
  5469. this.redraw();
  5470. this.onChange();
  5471. }
  5472. else {
  5473. throw 'Error: index out of range';
  5474. }
  5475. };
  5476. /**
  5477. * retrieve the index of the currently selected vaue
  5478. * @return {Number} index
  5479. */
  5480. Slider.prototype.getIndex = function() {
  5481. return this.index;
  5482. };
  5483. /**
  5484. * retrieve the currently selected value
  5485. * @return {*} value
  5486. */
  5487. Slider.prototype.get = function() {
  5488. return this.values[this.index];
  5489. };
  5490. Slider.prototype._onMouseDown = function(event) {
  5491. // only react on left mouse button down
  5492. var leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  5493. if (!leftButtonDown) return;
  5494. this.startClientX = event.clientX;
  5495. this.startSlideX = parseFloat(this.frame.slide.style.left);
  5496. this.frame.style.cursor = 'move';
  5497. // add event listeners to handle moving the contents
  5498. // we store the function onmousemove and onmouseup in the graph, so we can
  5499. // remove the eventlisteners lateron in the function mouseUp()
  5500. var me = this;
  5501. this.onmousemove = function (event) {me._onMouseMove(event);};
  5502. this.onmouseup = function (event) {me._onMouseUp(event);};
  5503. util.addEventListener(document, 'mousemove', this.onmousemove);
  5504. util.addEventListener(document, 'mouseup', this.onmouseup);
  5505. util.preventDefault(event);
  5506. };
  5507. Slider.prototype.leftToIndex = function (left) {
  5508. var width = parseFloat(this.frame.bar.style.width) -
  5509. this.frame.slide.clientWidth - 10;
  5510. var x = left - 3;
  5511. var index = Math.round(x / width * (this.values.length-1));
  5512. if (index < 0) index = 0;
  5513. if (index > this.values.length-1) index = this.values.length-1;
  5514. return index;
  5515. };
  5516. Slider.prototype.indexToLeft = function (index) {
  5517. var width = parseFloat(this.frame.bar.style.width) -
  5518. this.frame.slide.clientWidth - 10;
  5519. var x = index / (this.values.length-1) * width;
  5520. var left = x + 3;
  5521. return left;
  5522. };
  5523. Slider.prototype._onMouseMove = function (event) {
  5524. var diff = event.clientX - this.startClientX;
  5525. var x = this.startSlideX + diff;
  5526. var index = this.leftToIndex(x);
  5527. this.setIndex(index);
  5528. util.preventDefault();
  5529. };
  5530. Slider.prototype._onMouseUp = function (event) {
  5531. this.frame.style.cursor = 'auto';
  5532. // remove event listeners
  5533. util.removeEventListener(document, 'mousemove', this.onmousemove);
  5534. util.removeEventListener(document, 'mouseup', this.onmouseup);
  5535. util.preventDefault();
  5536. };
  5537. module.exports = Slider;
  5538. /***/ },
  5539. /* 12 */
  5540. /***/ function(module, exports, __webpack_require__) {
  5541. /**
  5542. * @prototype StepNumber
  5543. * The class StepNumber is an iterator for Numbers. You provide a start and end
  5544. * value, and a best step size. StepNumber itself rounds to fixed values and
  5545. * a finds the step that best fits the provided step.
  5546. *
  5547. * If prettyStep is true, the step size is chosen as close as possible to the
  5548. * provided step, but being a round value like 1, 2, 5, 10, 20, 50, ....
  5549. *
  5550. * Example usage:
  5551. * var step = new StepNumber(0, 10, 2.5, true);
  5552. * step.start();
  5553. * while (!step.end()) {
  5554. * alert(step.getCurrent());
  5555. * step.next();
  5556. * }
  5557. *
  5558. * Version: 1.0
  5559. *
  5560. * @param {Number} start The start value
  5561. * @param {Number} end The end value
  5562. * @param {Number} step Optional. Step size. Must be a positive value.
  5563. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  5564. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  5565. */
  5566. function StepNumber(start, end, step, prettyStep) {
  5567. // set default values
  5568. this._start = 0;
  5569. this._end = 0;
  5570. this._step = 1;
  5571. this.prettyStep = true;
  5572. this.precision = 5;
  5573. this._current = 0;
  5574. this.setRange(start, end, step, prettyStep);
  5575. };
  5576. /**
  5577. * Set a new range: start, end and step.
  5578. *
  5579. * @param {Number} start The start value
  5580. * @param {Number} end The end value
  5581. * @param {Number} step Optional. Step size. Must be a positive value.
  5582. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  5583. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  5584. */
  5585. StepNumber.prototype.setRange = function(start, end, step, prettyStep) {
  5586. this._start = start ? start : 0;
  5587. this._end = end ? end : 0;
  5588. this.setStep(step, prettyStep);
  5589. };
  5590. /**
  5591. * Set a new step size
  5592. * @param {Number} step New step size. Must be a positive value
  5593. * @param {boolean} prettyStep Optional. If true, the provided step is rounded
  5594. * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  5595. */
  5596. StepNumber.prototype.setStep = function(step, prettyStep) {
  5597. if (step === undefined || step <= 0)
  5598. return;
  5599. if (prettyStep !== undefined)
  5600. this.prettyStep = prettyStep;
  5601. if (this.prettyStep === true)
  5602. this._step = StepNumber.calculatePrettyStep(step);
  5603. else
  5604. this._step = step;
  5605. };
  5606. /**
  5607. * Calculate a nice step size, closest to the desired step size.
  5608. * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an
  5609. * integer Number. For example 1, 2, 5, 10, 20, 50, etc...
  5610. * @param {Number} step Desired step size
  5611. * @return {Number} Nice step size
  5612. */
  5613. StepNumber.calculatePrettyStep = function (step) {
  5614. var log10 = function (x) {return Math.log(x) / Math.LN10;};
  5615. // try three steps (multiple of 1, 2, or 5
  5616. var step1 = Math.pow(10, Math.round(log10(step))),
  5617. step2 = 2 * Math.pow(10, Math.round(log10(step / 2))),
  5618. step5 = 5 * Math.pow(10, Math.round(log10(step / 5)));
  5619. // choose the best step (closest to minimum step)
  5620. var prettyStep = step1;
  5621. if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2;
  5622. if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5;
  5623. // for safety
  5624. if (prettyStep <= 0) {
  5625. prettyStep = 1;
  5626. }
  5627. return prettyStep;
  5628. };
  5629. /**
  5630. * returns the current value of the step
  5631. * @return {Number} current value
  5632. */
  5633. StepNumber.prototype.getCurrent = function () {
  5634. return parseFloat(this._current.toPrecision(this.precision));
  5635. };
  5636. /**
  5637. * returns the current step size
  5638. * @return {Number} current step size
  5639. */
  5640. StepNumber.prototype.getStep = function () {
  5641. return this._step;
  5642. };
  5643. /**
  5644. * Set the current value to the largest value smaller than start, which
  5645. * is a multiple of the step size
  5646. */
  5647. StepNumber.prototype.start = function() {
  5648. this._current = this._start - this._start % this._step;
  5649. };
  5650. /**
  5651. * Do a step, add the step size to the current value
  5652. */
  5653. StepNumber.prototype.next = function () {
  5654. this._current += this._step;
  5655. };
  5656. /**
  5657. * Returns true whether the end is reached
  5658. * @return {boolean} True if the current value has passed the end value.
  5659. */
  5660. StepNumber.prototype.end = function () {
  5661. return (this._current > this._end);
  5662. };
  5663. module.exports = StepNumber;
  5664. /***/ },
  5665. /* 13 */
  5666. /***/ function(module, exports, __webpack_require__) {
  5667. var Emitter = __webpack_require__(56);
  5668. var Hammer = __webpack_require__(45);
  5669. var util = __webpack_require__(1);
  5670. var DataSet = __webpack_require__(3);
  5671. var DataView = __webpack_require__(4);
  5672. var Range = __webpack_require__(17);
  5673. var Core = __webpack_require__(46);
  5674. var TimeAxis = __webpack_require__(35);
  5675. var CurrentTime = __webpack_require__(26);
  5676. var CustomTime = __webpack_require__(27);
  5677. var ItemSet = __webpack_require__(32);
  5678. /**
  5679. * Create a timeline visualization
  5680. * @param {HTMLElement} container
  5681. * @param {vis.DataSet | vis.DataView | Array | google.visualization.DataTable} [items]
  5682. * @param {vis.DataSet | vis.DataView | Array | google.visualization.DataTable} [groups]
  5683. * @param {Object} [options] See Timeline.setOptions for the available options.
  5684. * @constructor
  5685. * @extends Core
  5686. */
  5687. function Timeline (container, items, groups, options) {
  5688. if (!(this instanceof Timeline)) {
  5689. throw new SyntaxError('Constructor must be called with the new operator');
  5690. }
  5691. // if the third element is options, the forth is groups (optionally);
  5692. if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
  5693. var forthArgument = options;
  5694. options = groups;
  5695. groups = forthArgument;
  5696. }
  5697. var me = this;
  5698. this.defaultOptions = {
  5699. start: null,
  5700. end: null,
  5701. autoResize: true,
  5702. orientation: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
  5703. width: null,
  5704. height: null,
  5705. maxHeight: null,
  5706. minHeight: null
  5707. };
  5708. this.options = util.deepExtend({}, this.defaultOptions);
  5709. // Create the DOM, props, and emitter
  5710. this._create(container);
  5711. // all components listed here will be repainted automatically
  5712. this.components = [];
  5713. this.body = {
  5714. dom: this.dom,
  5715. domProps: this.props,
  5716. emitter: {
  5717. on: this.on.bind(this),
  5718. off: this.off.bind(this),
  5719. emit: this.emit.bind(this)
  5720. },
  5721. hiddenDates: [],
  5722. util: {
  5723. getScale: function () {
  5724. return me.timeAxis.step.scale;
  5725. },
  5726. getStep: function () {
  5727. return me.timeAxis.step.step;
  5728. },
  5729. toScreen: me._toScreen.bind(me),
  5730. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  5731. toTime: me._toTime.bind(me),
  5732. toGlobalTime : me._toGlobalTime.bind(me)
  5733. }
  5734. };
  5735. // range
  5736. this.range = new Range(this.body);
  5737. this.components.push(this.range);
  5738. this.body.range = this.range;
  5739. // time axis
  5740. this.timeAxis = new TimeAxis(this.body);
  5741. this.timeAxis2 = null; // used in case of orientation option 'both'
  5742. this.components.push(this.timeAxis);
  5743. // current time bar
  5744. this.currentTime = new CurrentTime(this.body);
  5745. this.components.push(this.currentTime);
  5746. // custom time bar
  5747. // Note: time bar will be attached in this.setOptions when selected
  5748. this.customTime = new CustomTime(this.body);
  5749. this.components.push(this.customTime);
  5750. // item set
  5751. this.itemSet = new ItemSet(this.body);
  5752. this.components.push(this.itemSet);
  5753. this.itemsData = null; // DataSet
  5754. this.groupsData = null; // DataSet
  5755. this.on('tap', function (event) {
  5756. me.emit('click', me.getEventProperties(event))
  5757. });
  5758. this.on('doubletap', function (event) {
  5759. me.emit('doubleClick', me.getEventProperties(event))
  5760. });
  5761. this.dom.root.oncontextmenu = function (event) {
  5762. me.emit('contextmenu', me.getEventProperties(event))
  5763. };
  5764. // apply options
  5765. if (options) {
  5766. this.setOptions(options);
  5767. }
  5768. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  5769. if (groups) {
  5770. this.setGroups(groups);
  5771. }
  5772. // create itemset
  5773. if (items) {
  5774. this.setItems(items);
  5775. }
  5776. else {
  5777. this._redraw();
  5778. }
  5779. }
  5780. // Extend the functionality from Core
  5781. Timeline.prototype = new Core();
  5782. /**
  5783. * Force a redraw. The size of all items will be recalculated.
  5784. * Can be useful to manually redraw when option autoResize=false and the window
  5785. * has been resized, or when the items CSS has been changed.
  5786. */
  5787. Timeline.prototype.redraw = function() {
  5788. this.itemSet && this.itemSet.markDirty({refreshItems: true});
  5789. this._redraw();
  5790. };
  5791. /**
  5792. * Set items
  5793. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  5794. */
  5795. Timeline.prototype.setItems = function(items) {
  5796. var initialLoad = (this.itemsData == null);
  5797. // convert to type DataSet when needed
  5798. var newDataSet;
  5799. if (!items) {
  5800. newDataSet = null;
  5801. }
  5802. else if (items instanceof DataSet || items instanceof DataView) {
  5803. newDataSet = items;
  5804. }
  5805. else {
  5806. // turn an array into a dataset
  5807. newDataSet = new DataSet(items, {
  5808. type: {
  5809. start: 'Date',
  5810. end: 'Date'
  5811. }
  5812. });
  5813. }
  5814. // set items
  5815. this.itemsData = newDataSet;
  5816. this.itemSet && this.itemSet.setItems(newDataSet);
  5817. if (initialLoad) {
  5818. if (this.options.start != undefined || this.options.end != undefined) {
  5819. if (this.options.start == undefined || this.options.end == undefined) {
  5820. var dataRange = this._getDataRange();
  5821. }
  5822. var start = this.options.start != undefined ? this.options.start : dataRange.start;
  5823. var end = this.options.end != undefined ? this.options.end : dataRange.end;
  5824. this.setWindow(start, end, {animate: false});
  5825. }
  5826. else {
  5827. this.fit({animate: false});
  5828. }
  5829. }
  5830. };
  5831. /**
  5832. * Set groups
  5833. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  5834. */
  5835. Timeline.prototype.setGroups = function(groups) {
  5836. // convert to type DataSet when needed
  5837. var newDataSet;
  5838. if (!groups) {
  5839. newDataSet = null;
  5840. }
  5841. else if (groups instanceof DataSet || groups instanceof DataView) {
  5842. newDataSet = groups;
  5843. }
  5844. else {
  5845. // turn an array into a dataset
  5846. newDataSet = new DataSet(groups);
  5847. }
  5848. this.groupsData = newDataSet;
  5849. this.itemSet.setGroups(newDataSet);
  5850. };
  5851. /**
  5852. * Set selected items by their id. Replaces the current selection
  5853. * Unknown id's are silently ignored.
  5854. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  5855. * selected. If ids is an empty array, all items will be
  5856. * unselected.
  5857. * @param {Object} [options] Available options:
  5858. * `focus: boolean`
  5859. * If true, focus will be set to the selected item(s)
  5860. * `animate: boolean | number`
  5861. * If true (default), the range is animated
  5862. * smoothly to the new window.
  5863. * If a number, the number is taken as duration
  5864. * for the animation. Default duration is 500 ms.
  5865. * Only applicable when option focus is true.
  5866. */
  5867. Timeline.prototype.setSelection = function(ids, options) {
  5868. this.itemSet && this.itemSet.setSelection(ids);
  5869. if (options && options.focus) {
  5870. this.focus(ids, options);
  5871. }
  5872. };
  5873. /**
  5874. * Get the selected items by their id
  5875. * @return {Array} ids The ids of the selected items
  5876. */
  5877. Timeline.prototype.getSelection = function() {
  5878. return this.itemSet && this.itemSet.getSelection() || [];
  5879. };
  5880. /**
  5881. * Adjust the visible window such that the selected item (or multiple items)
  5882. * are centered on screen.
  5883. * @param {String | String[]} id An item id or array with item ids
  5884. * @param {Object} [options] Available options:
  5885. * `animate: boolean | number`
  5886. * If true (default), the range is animated
  5887. * smoothly to the new window.
  5888. * If a number, the number is taken as duration
  5889. * for the animation. Default duration is 500 ms.
  5890. * Only applicable when option focus is true
  5891. */
  5892. Timeline.prototype.focus = function(id, options) {
  5893. if (!this.itemsData || id == undefined) return;
  5894. var ids = Array.isArray(id) ? id : [id];
  5895. // get the specified item(s)
  5896. var itemsData = this.itemsData.getDataSet().get(ids, {
  5897. type: {
  5898. start: 'Date',
  5899. end: 'Date'
  5900. }
  5901. });
  5902. // calculate minimum start and maximum end of specified items
  5903. var start = null;
  5904. var end = null;
  5905. itemsData.forEach(function (itemData) {
  5906. var s = itemData.start.valueOf();
  5907. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  5908. if (start === null || s < start) {
  5909. start = s;
  5910. }
  5911. if (end === null || e > end) {
  5912. end = e;
  5913. }
  5914. });
  5915. if (start !== null && end !== null) {
  5916. // calculate the new middle and interval for the window
  5917. var middle = (start + end) / 2;
  5918. var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
  5919. var animate = (options && options.animate !== undefined) ? options.animate : true;
  5920. this.range.setRange(middle - interval / 2, middle + interval / 2, animate);
  5921. }
  5922. };
  5923. /**
  5924. * Get the data range of the item set.
  5925. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  5926. * When no minimum is found, min==null
  5927. * When no maximum is found, max==null
  5928. */
  5929. Timeline.prototype.getItemRange = function() {
  5930. // calculate min from start filed
  5931. var dataset = this.itemsData.getDataSet(),
  5932. min = null,
  5933. max = null;
  5934. if (dataset) {
  5935. // calculate the minimum value of the field 'start'
  5936. var minItem = dataset.min('start');
  5937. min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null;
  5938. // Note: we convert first to Date and then to number because else
  5939. // a conversion from ISODate to Number will fail
  5940. // calculate maximum value of fields 'start' and 'end'
  5941. var maxStartItem = dataset.max('start');
  5942. if (maxStartItem) {
  5943. max = util.convert(maxStartItem.start, 'Date').valueOf();
  5944. }
  5945. var maxEndItem = dataset.max('end');
  5946. if (maxEndItem) {
  5947. if (max == null) {
  5948. max = util.convert(maxEndItem.end, 'Date').valueOf();
  5949. }
  5950. else {
  5951. max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf());
  5952. }
  5953. }
  5954. }
  5955. return {
  5956. min: (min != null) ? new Date(min) : null,
  5957. max: (max != null) ? new Date(max) : null
  5958. };
  5959. };
  5960. /**
  5961. * Generate Timeline related information from an event
  5962. * @param {Event} event
  5963. * @return {Object} An object with related information, like on which area
  5964. * The event happened, whether clicked on an item, etc.
  5965. */
  5966. Timeline.prototype.getEventProperties = function (event) {
  5967. var item = this.itemSet.itemFromTarget(event);
  5968. var group = this.itemSet.groupFromTarget(event);
  5969. var pageX = event.gesture ? event.gesture.center.pageX : event.pageX;
  5970. var pageY = event.gesture ? event.gesture.center.pageY : event.pageY;
  5971. var x = pageX - util.getAbsoluteLeft(this.dom.centerContainer);
  5972. var y = pageY - util.getAbsoluteTop(this.dom.centerContainer);
  5973. var snap = this.itemSet.options.snap || null;
  5974. var scale = this.body.util.getScale();
  5975. var step = this.body.util.getStep();
  5976. var time = this._toTime(x);
  5977. var snappedTime = snap ? snap(time, scale, step) : time;
  5978. var element = util.getTarget(event);
  5979. var what = null;
  5980. if (item != null) {what = 'item';}
  5981. else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  5982. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  5983. else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
  5984. else if (util.hasParent(element, this.customTime.bar)) {what = 'custom-time';} // TODO: fix for multiple custom time bars
  5985. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  5986. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  5987. return {
  5988. event: event,
  5989. item: item ? item.id : null,
  5990. group: group ? group.groupId : null,
  5991. what: what,
  5992. pageX: pageX,
  5993. pageY: pageY,
  5994. x: x,
  5995. y: y,
  5996. time: time,
  5997. snappedTime: snappedTime
  5998. }
  5999. };
  6000. module.exports = Timeline;
  6001. /***/ },
  6002. /* 14 */
  6003. /***/ function(module, exports, __webpack_require__) {
  6004. var Emitter = __webpack_require__(56);
  6005. var Hammer = __webpack_require__(45);
  6006. var util = __webpack_require__(1);
  6007. var DataSet = __webpack_require__(3);
  6008. var DataView = __webpack_require__(4);
  6009. var Range = __webpack_require__(17);
  6010. var Core = __webpack_require__(46);
  6011. var TimeAxis = __webpack_require__(35);
  6012. var CurrentTime = __webpack_require__(26);
  6013. var CustomTime = __webpack_require__(27);
  6014. var LineGraph = __webpack_require__(34);
  6015. /**
  6016. * Create a timeline visualization
  6017. * @param {HTMLElement} container
  6018. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6019. * @param {Object} [options] See Graph2d.setOptions for the available options.
  6020. * @constructor
  6021. * @extends Core
  6022. */
  6023. function Graph2d (container, items, groups, options) {
  6024. // if the third element is options, the forth is groups (optionally);
  6025. if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) {
  6026. var forthArgument = options;
  6027. options = groups;
  6028. groups = forthArgument;
  6029. }
  6030. var me = this;
  6031. this.defaultOptions = {
  6032. start: null,
  6033. end: null,
  6034. autoResize: true,
  6035. orientation: 'bottom',
  6036. width: null,
  6037. height: null,
  6038. maxHeight: null,
  6039. minHeight: null
  6040. };
  6041. this.options = util.deepExtend({}, this.defaultOptions);
  6042. // Create the DOM, props, and emitter
  6043. this._create(container);
  6044. // all components listed here will be repainted automatically
  6045. this.components = [];
  6046. this.body = {
  6047. dom: this.dom,
  6048. domProps: this.props,
  6049. emitter: {
  6050. on: this.on.bind(this),
  6051. off: this.off.bind(this),
  6052. emit: this.emit.bind(this)
  6053. },
  6054. hiddenDates: [],
  6055. util: {
  6056. toScreen: me._toScreen.bind(me),
  6057. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  6058. toTime: me._toTime.bind(me),
  6059. toGlobalTime : me._toGlobalTime.bind(me)
  6060. }
  6061. };
  6062. // range
  6063. this.range = new Range(this.body);
  6064. this.components.push(this.range);
  6065. this.body.range = this.range;
  6066. // time axis
  6067. this.timeAxis = new TimeAxis(this.body);
  6068. this.components.push(this.timeAxis);
  6069. //this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
  6070. // current time bar
  6071. this.currentTime = new CurrentTime(this.body);
  6072. this.components.push(this.currentTime);
  6073. // custom time bar
  6074. // Note: time bar will be attached in this.setOptions when selected
  6075. this.customTime = new CustomTime(this.body);
  6076. this.components.push(this.customTime);
  6077. // item set
  6078. this.linegraph = new LineGraph(this.body);
  6079. this.components.push(this.linegraph);
  6080. this.itemsData = null; // DataSet
  6081. this.groupsData = null; // DataSet
  6082. this.on('tap', function (event) {
  6083. me.emit('click', me.getEventProperties(event))
  6084. });
  6085. this.on('doubletap', function (event) {
  6086. me.emit('doubleClick', me.getEventProperties(event))
  6087. });
  6088. this.dom.root.oncontextmenu = function (event) {
  6089. me.emit('contextmenu', me.getEventProperties(event))
  6090. };
  6091. // apply options
  6092. if (options) {
  6093. this.setOptions(options);
  6094. }
  6095. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  6096. if (groups) {
  6097. this.setGroups(groups);
  6098. }
  6099. // create itemset
  6100. if (items) {
  6101. this.setItems(items);
  6102. }
  6103. else {
  6104. this._redraw();
  6105. }
  6106. }
  6107. // Extend the functionality from Core
  6108. Graph2d.prototype = new Core();
  6109. /**
  6110. * Set items
  6111. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  6112. */
  6113. Graph2d.prototype.setItems = function(items) {
  6114. var initialLoad = (this.itemsData == null);
  6115. // convert to type DataSet when needed
  6116. var newDataSet;
  6117. if (!items) {
  6118. newDataSet = null;
  6119. }
  6120. else if (items instanceof DataSet || items instanceof DataView) {
  6121. newDataSet = items;
  6122. }
  6123. else {
  6124. // turn an array into a dataset
  6125. newDataSet = new DataSet(items, {
  6126. type: {
  6127. start: 'Date',
  6128. end: 'Date'
  6129. }
  6130. });
  6131. }
  6132. // set items
  6133. this.itemsData = newDataSet;
  6134. this.linegraph && this.linegraph.setItems(newDataSet);
  6135. if (initialLoad) {
  6136. if (this.options.start != undefined || this.options.end != undefined) {
  6137. var start = this.options.start != undefined ? this.options.start : null;
  6138. var end = this.options.end != undefined ? this.options.end : null;
  6139. this.setWindow(start, end, {animate: false});
  6140. }
  6141. else {
  6142. this.fit({animate: false});
  6143. }
  6144. }
  6145. };
  6146. /**
  6147. * Set groups
  6148. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  6149. */
  6150. Graph2d.prototype.setGroups = function(groups) {
  6151. // convert to type DataSet when needed
  6152. var newDataSet;
  6153. if (!groups) {
  6154. newDataSet = null;
  6155. }
  6156. else if (groups instanceof DataSet || groups instanceof DataView) {
  6157. newDataSet = groups;
  6158. }
  6159. else {
  6160. // turn an array into a dataset
  6161. newDataSet = new DataSet(groups);
  6162. }
  6163. this.groupsData = newDataSet;
  6164. this.linegraph.setGroups(newDataSet);
  6165. };
  6166. /**
  6167. * Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right).
  6168. * @param groupId
  6169. * @param width
  6170. * @param height
  6171. */
  6172. Graph2d.prototype.getLegend = function(groupId, width, height) {
  6173. if (width === undefined) {width = 15;}
  6174. if (height === undefined) {height = 15;}
  6175. if (this.linegraph.groups[groupId] !== undefined) {
  6176. return this.linegraph.groups[groupId].getLegend(width,height);
  6177. }
  6178. else {
  6179. return "cannot find group:" + groupId;
  6180. }
  6181. };
  6182. /**
  6183. * This checks if the visible option of the supplied group (by ID) is true or false.
  6184. * @param groupId
  6185. * @returns {*}
  6186. */
  6187. Graph2d.prototype.isGroupVisible = function(groupId) {
  6188. if (this.linegraph.groups[groupId] !== undefined) {
  6189. return (this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true));
  6190. }
  6191. else {
  6192. return false;
  6193. }
  6194. };
  6195. /**
  6196. * Get the data range of the item set.
  6197. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6198. * When no minimum is found, min==null
  6199. * When no maximum is found, max==null
  6200. */
  6201. Graph2d.prototype.getItemRange = function() {
  6202. var min = null;
  6203. var max = null;
  6204. // calculate min from start filed
  6205. for (var groupId in this.linegraph.groups) {
  6206. if (this.linegraph.groups.hasOwnProperty(groupId)) {
  6207. if (this.linegraph.groups[groupId].visible == true) {
  6208. for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) {
  6209. var item = this.linegraph.groups[groupId].itemsData[i];
  6210. var value = util.convert(item.x, 'Date').valueOf();
  6211. min = min == null ? value : min > value ? value : min;
  6212. max = max == null ? value : max < value ? value : max;
  6213. }
  6214. }
  6215. }
  6216. }
  6217. return {
  6218. min: (min != null) ? new Date(min) : null,
  6219. max: (max != null) ? new Date(max) : null
  6220. };
  6221. };
  6222. /**
  6223. * Generate Timeline related information from an event
  6224. * @param {Event} event
  6225. * @return {Object} An object with related information, like on which area
  6226. * The event happened, whether clicked on an item, etc.
  6227. */
  6228. Graph2d.prototype.getEventProperties = function (event) {
  6229. var pageX = event.gesture ? event.gesture.center.pageX : event.pageX;
  6230. var pageY = event.gesture ? event.gesture.center.pageY : event.pageY;
  6231. var x = pageX - util.getAbsoluteLeft(this.dom.centerContainer);
  6232. var y = pageY - util.getAbsoluteTop(this.dom.centerContainer);
  6233. var time = this._toTime(x);
  6234. var element = util.getTarget(event);
  6235. var what = null;
  6236. if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
  6237. else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
  6238. else if (util.hasParent(element, this.linegraph.yAxisLeft.dom.frame)) {what = 'data-axis';}
  6239. else if (util.hasParent(element, this.linegraph.yAxisRight.dom.frame)) {what = 'data-axis';}
  6240. else if (util.hasParent(element, this.linegraph.legendLeft.dom.frame)) {what = 'legend';}
  6241. else if (util.hasParent(element, this.linegraph.legendRight.dom.frame)) {what = 'legend';}
  6242. else if (util.hasParent(element, this.customTime.bar)) {what = 'custom-time';} // TODO: fix for multiple custom time bars
  6243. else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
  6244. else if (util.hasParent(element, this.dom.center)) {what = 'background';}
  6245. var value = [];
  6246. var yAxisLeft = this.linegraph.yAxisLeft;
  6247. var yAxisRight = this.linegraph.yAxisRight;
  6248. if (!yAxisLeft.hidden) {
  6249. value.push(yAxisLeft.screenToValue(y));
  6250. }
  6251. if (!yAxisRight.hidden) {
  6252. value.push(yAxisRight.screenToValue(y));
  6253. }
  6254. return {
  6255. event: event,
  6256. what: what,
  6257. pageX: pageX,
  6258. pageY: pageY,
  6259. x: x,
  6260. y: y,
  6261. time: time,
  6262. value: value
  6263. }
  6264. };
  6265. module.exports = Graph2d;
  6266. /***/ },
  6267. /* 15 */
  6268. /***/ function(module, exports, __webpack_require__) {
  6269. /**
  6270. * Created by Alex on 10/3/2014.
  6271. */
  6272. var moment = __webpack_require__(44);
  6273. /**
  6274. * used in Core to convert the options into a volatile variable
  6275. *
  6276. * @param Core
  6277. */
  6278. exports.convertHiddenOptions = function(body, hiddenDates) {
  6279. body.hiddenDates = [];
  6280. if (hiddenDates) {
  6281. if (Array.isArray(hiddenDates) == true) {
  6282. for (var i = 0; i < hiddenDates.length; i++) {
  6283. if (hiddenDates[i].repeat === undefined) {
  6284. var dateItem = {};
  6285. dateItem.start = moment(hiddenDates[i].start).toDate().valueOf();
  6286. dateItem.end = moment(hiddenDates[i].end).toDate().valueOf();
  6287. body.hiddenDates.push(dateItem);
  6288. }
  6289. }
  6290. body.hiddenDates.sort(function (a, b) {
  6291. return a.start - b.start;
  6292. }); // sort by start time
  6293. }
  6294. }
  6295. };
  6296. /**
  6297. * create new entrees for the repeating hidden dates
  6298. * @param body
  6299. * @param hiddenDates
  6300. */
  6301. exports.updateHiddenDates = function (body, hiddenDates) {
  6302. if (hiddenDates && body.domProps.centerContainer.width !== undefined) {
  6303. exports.convertHiddenOptions(body, hiddenDates);
  6304. var start = moment(body.range.start);
  6305. var end = moment(body.range.end);
  6306. var totalRange = (body.range.end - body.range.start);
  6307. var pixelTime = totalRange / body.domProps.centerContainer.width;
  6308. for (var i = 0; i < hiddenDates.length; i++) {
  6309. if (hiddenDates[i].repeat !== undefined) {
  6310. var startDate = moment(hiddenDates[i].start);
  6311. var endDate = moment(hiddenDates[i].end);
  6312. if (startDate._d == "Invalid Date") {
  6313. throw new Error("Supplied start date is not valid: " + hiddenDates[i].start);
  6314. }
  6315. if (endDate._d == "Invalid Date") {
  6316. throw new Error("Supplied end date is not valid: " + hiddenDates[i].end);
  6317. }
  6318. var duration = endDate - startDate;
  6319. if (duration >= 4 * pixelTime) {
  6320. var offset = 0;
  6321. var runUntil = end.clone();
  6322. switch (hiddenDates[i].repeat) {
  6323. case "daily": // case of time
  6324. if (startDate.day() != endDate.day()) {
  6325. offset = 1;
  6326. }
  6327. startDate.dayOfYear(start.dayOfYear());
  6328. startDate.year(start.year());
  6329. startDate.subtract(7,'days');
  6330. endDate.dayOfYear(start.dayOfYear());
  6331. endDate.year(start.year());
  6332. endDate.subtract(7 - offset,'days');
  6333. runUntil.add(1, 'weeks');
  6334. break;
  6335. case "weekly":
  6336. var dayOffset = endDate.diff(startDate,'days')
  6337. var day = startDate.day();
  6338. // set the start date to the range.start
  6339. startDate.date(start.date());
  6340. startDate.month(start.month());
  6341. startDate.year(start.year());
  6342. endDate = startDate.clone();
  6343. // force
  6344. startDate.day(day);
  6345. endDate.day(day);
  6346. endDate.add(dayOffset,'days');
  6347. startDate.subtract(1,'weeks');
  6348. endDate.subtract(1,'weeks');
  6349. runUntil.add(1, 'weeks');
  6350. break
  6351. case "monthly":
  6352. if (startDate.month() != endDate.month()) {
  6353. offset = 1;
  6354. }
  6355. startDate.month(start.month());
  6356. startDate.year(start.year());
  6357. startDate.subtract(1,'months');
  6358. endDate.month(start.month());
  6359. endDate.year(start.year());
  6360. endDate.subtract(1,'months');
  6361. endDate.add(offset,'months');
  6362. runUntil.add(1, 'months');
  6363. break;
  6364. case "yearly":
  6365. if (startDate.year() != endDate.year()) {
  6366. offset = 1;
  6367. }
  6368. startDate.year(start.year());
  6369. startDate.subtract(1,'years');
  6370. endDate.year(start.year());
  6371. endDate.subtract(1,'years');
  6372. endDate.add(offset,'years');
  6373. runUntil.add(1, 'years');
  6374. break;
  6375. default:
  6376. console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
  6377. return;
  6378. }
  6379. while (startDate < runUntil) {
  6380. body.hiddenDates.push({start: startDate.valueOf(), end: endDate.valueOf()});
  6381. switch (hiddenDates[i].repeat) {
  6382. case "daily":
  6383. startDate.add(1, 'days');
  6384. endDate.add(1, 'days');
  6385. break;
  6386. case "weekly":
  6387. startDate.add(1, 'weeks');
  6388. endDate.add(1, 'weeks');
  6389. break
  6390. case "monthly":
  6391. startDate.add(1, 'months');
  6392. endDate.add(1, 'months');
  6393. break;
  6394. case "yearly":
  6395. startDate.add(1, 'y');
  6396. endDate.add(1, 'y');
  6397. break;
  6398. default:
  6399. console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
  6400. return;
  6401. }
  6402. }
  6403. body.hiddenDates.push({start: startDate.valueOf(), end: endDate.valueOf()});
  6404. }
  6405. }
  6406. }
  6407. // remove duplicates, merge where possible
  6408. exports.removeDuplicates(body);
  6409. // ensure the new positions are not on hidden dates
  6410. var startHidden = exports.isHidden(body.range.start, body.hiddenDates);
  6411. var endHidden = exports.isHidden(body.range.end,body.hiddenDates);
  6412. var rangeStart = body.range.start;
  6413. var rangeEnd = body.range.end;
  6414. if (startHidden.hidden == true) {rangeStart = body.range.startToFront == true ? startHidden.startDate - 1 : startHidden.endDate + 1;}
  6415. if (endHidden.hidden == true) {rangeEnd = body.range.endToFront == true ? endHidden.startDate - 1 : endHidden.endDate + 1;}
  6416. if (startHidden.hidden == true || endHidden.hidden == true) {
  6417. body.range._applyRange(rangeStart, rangeEnd);
  6418. }
  6419. }
  6420. }
  6421. /**
  6422. * remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up.
  6423. * Scales with N^2
  6424. * @param body
  6425. */
  6426. exports.removeDuplicates = function(body) {
  6427. var hiddenDates = body.hiddenDates;
  6428. var safeDates = [];
  6429. for (var i = 0; i < hiddenDates.length; i++) {
  6430. for (var j = 0; j < hiddenDates.length; j++) {
  6431. if (i != j && hiddenDates[j].remove != true && hiddenDates[i].remove != true) {
  6432. // j inside i
  6433. if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
  6434. hiddenDates[j].remove = true;
  6435. }
  6436. // j start inside i
  6437. else if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].start <= hiddenDates[i].end) {
  6438. hiddenDates[i].end = hiddenDates[j].end;
  6439. hiddenDates[j].remove = true;
  6440. }
  6441. // j end inside i
  6442. else if (hiddenDates[j].end >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
  6443. hiddenDates[i].start = hiddenDates[j].start;
  6444. hiddenDates[j].remove = true;
  6445. }
  6446. }
  6447. }
  6448. }
  6449. for (var i = 0; i < hiddenDates.length; i++) {
  6450. if (hiddenDates[i].remove !== true) {
  6451. safeDates.push(hiddenDates[i]);
  6452. }
  6453. }
  6454. body.hiddenDates = safeDates;
  6455. body.hiddenDates.sort(function (a, b) {
  6456. return a.start - b.start;
  6457. }); // sort by start time
  6458. }
  6459. exports.printDates = function(dates) {
  6460. for (var i =0; i < dates.length; i++) {
  6461. console.log(i, new Date(dates[i].start),new Date(dates[i].end), dates[i].start, dates[i].end, dates[i].remove);
  6462. }
  6463. }
  6464. /**
  6465. * Used in TimeStep to avoid the hidden times.
  6466. * @param timeStep
  6467. * @param previousTime
  6468. */
  6469. exports.stepOverHiddenDates = function(timeStep, previousTime) {
  6470. var stepInHidden = false;
  6471. var currentValue = timeStep.current.valueOf();
  6472. for (var i = 0; i < timeStep.hiddenDates.length; i++) {
  6473. var startDate = timeStep.hiddenDates[i].start;
  6474. var endDate = timeStep.hiddenDates[i].end;
  6475. if (currentValue >= startDate && currentValue < endDate) {
  6476. stepInHidden = true;
  6477. break;
  6478. }
  6479. }
  6480. if (stepInHidden == true && currentValue < timeStep._end.valueOf() && currentValue != previousTime) {
  6481. var prevValue = moment(previousTime);
  6482. var newValue = moment(endDate);
  6483. //check if the next step should be major
  6484. if (prevValue.year() != newValue.year()) {timeStep.switchedYear = true;}
  6485. else if (prevValue.month() != newValue.month()) {timeStep.switchedMonth = true;}
  6486. else if (prevValue.dayOfYear() != newValue.dayOfYear()) {timeStep.switchedDay = true;}
  6487. timeStep.current = newValue.toDate();
  6488. }
  6489. };
  6490. ///**
  6491. // * Used in TimeStep to avoid the hidden times.
  6492. // * @param timeStep
  6493. // * @param previousTime
  6494. // */
  6495. //exports.checkFirstStep = function(timeStep) {
  6496. // var stepInHidden = false;
  6497. // var currentValue = timeStep.current.valueOf();
  6498. // for (var i = 0; i < timeStep.hiddenDates.length; i++) {
  6499. // var startDate = timeStep.hiddenDates[i].start;
  6500. // var endDate = timeStep.hiddenDates[i].end;
  6501. // if (currentValue >= startDate && currentValue < endDate) {
  6502. // stepInHidden = true;
  6503. // break;
  6504. // }
  6505. // }
  6506. //
  6507. // if (stepInHidden == true && currentValue <= timeStep._end.valueOf()) {
  6508. // var newValue = moment(endDate);
  6509. // timeStep.current = newValue.toDate();
  6510. // }
  6511. //};
  6512. /**
  6513. * replaces the Core toScreen methods
  6514. * @param Core
  6515. * @param time
  6516. * @param width
  6517. * @returns {number}
  6518. */
  6519. exports.toScreen = function(Core, time, width) {
  6520. if (Core.body.hiddenDates.length == 0) {
  6521. var conversion = Core.range.conversion(width);
  6522. return (time.valueOf() - conversion.offset) * conversion.scale;
  6523. }
  6524. else {
  6525. var hidden = exports.isHidden(time, Core.body.hiddenDates)
  6526. if (hidden.hidden == true) {
  6527. time = hidden.startDate;
  6528. }
  6529. var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
  6530. time = exports.correctTimeForHidden(Core.body.hiddenDates, Core.range, time);
  6531. var conversion = Core.range.conversion(width, duration);
  6532. return (time.valueOf() - conversion.offset) * conversion.scale;
  6533. }
  6534. };
  6535. /**
  6536. * Replaces the core toTime methods
  6537. * @param body
  6538. * @param range
  6539. * @param x
  6540. * @param width
  6541. * @returns {Date}
  6542. */
  6543. exports.toTime = function(Core, x, width) {
  6544. if (Core.body.hiddenDates.length == 0) {
  6545. var conversion = Core.range.conversion(width);
  6546. return new Date(x / conversion.scale + conversion.offset);
  6547. }
  6548. else {
  6549. var hiddenDuration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
  6550. var totalDuration = Core.range.end - Core.range.start - hiddenDuration;
  6551. var partialDuration = totalDuration * x / width;
  6552. var accumulatedHiddenDuration = exports.getAccumulatedHiddenDuration(Core.body.hiddenDates, Core.range, partialDuration);
  6553. var newTime = new Date(accumulatedHiddenDuration + partialDuration + Core.range.start);
  6554. return newTime;
  6555. }
  6556. };
  6557. /**
  6558. * Support function
  6559. *
  6560. * @param hiddenDates
  6561. * @param range
  6562. * @returns {number}
  6563. */
  6564. exports.getHiddenDurationBetween = function(hiddenDates, start, end) {
  6565. var duration = 0;
  6566. for (var i = 0; i < hiddenDates.length; i++) {
  6567. var startDate = hiddenDates[i].start;
  6568. var endDate = hiddenDates[i].end;
  6569. // if time after the cutout, and the
  6570. if (startDate >= start && endDate < end) {
  6571. duration += endDate - startDate;
  6572. }
  6573. }
  6574. return duration;
  6575. };
  6576. /**
  6577. * Support function
  6578. * @param hiddenDates
  6579. * @param range
  6580. * @param time
  6581. * @returns {{duration: number, time: *, offset: number}}
  6582. */
  6583. exports.correctTimeForHidden = function(hiddenDates, range, time) {
  6584. time = moment(time).toDate().valueOf();
  6585. time -= exports.getHiddenDurationBefore(hiddenDates,range,time);
  6586. return time;
  6587. };
  6588. exports.getHiddenDurationBefore = function(hiddenDates, range, time) {
  6589. var timeOffset = 0;
  6590. time = moment(time).toDate().valueOf();
  6591. for (var i = 0; i < hiddenDates.length; i++) {
  6592. var startDate = hiddenDates[i].start;
  6593. var endDate = hiddenDates[i].end;
  6594. // if time after the cutout, and the
  6595. if (startDate >= range.start && endDate < range.end) {
  6596. if (time >= endDate) {
  6597. timeOffset += (endDate - startDate);
  6598. }
  6599. }
  6600. }
  6601. return timeOffset;
  6602. }
  6603. /**
  6604. * sum the duration from start to finish, including the hidden duration,
  6605. * until the required amount has been reached, return the accumulated hidden duration
  6606. * @param hiddenDates
  6607. * @param range
  6608. * @param time
  6609. * @returns {{duration: number, time: *, offset: number}}
  6610. */
  6611. exports.getAccumulatedHiddenDuration = function(hiddenDates, range, requiredDuration) {
  6612. var hiddenDuration = 0;
  6613. var duration = 0;
  6614. var previousPoint = range.start;
  6615. //exports.printDates(hiddenDates)
  6616. for (var i = 0; i < hiddenDates.length; i++) {
  6617. var startDate = hiddenDates[i].start;
  6618. var endDate = hiddenDates[i].end;
  6619. // if time after the cutout, and the
  6620. if (startDate >= range.start && endDate < range.end) {
  6621. duration += startDate - previousPoint;
  6622. previousPoint = endDate;
  6623. if (duration >= requiredDuration) {
  6624. break;
  6625. }
  6626. else {
  6627. hiddenDuration += endDate - startDate;
  6628. }
  6629. }
  6630. }
  6631. return hiddenDuration;
  6632. };
  6633. /**
  6634. * used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true
  6635. * @param hiddenDates
  6636. * @param time
  6637. * @param direction
  6638. * @param correctionEnabled
  6639. * @returns {*}
  6640. */
  6641. exports.snapAwayFromHidden = function(hiddenDates, time, direction, correctionEnabled) {
  6642. var isHidden = exports.isHidden(time, hiddenDates);
  6643. if (isHidden.hidden == true) {
  6644. if (direction < 0) {
  6645. if (correctionEnabled == true) {
  6646. return isHidden.startDate - (isHidden.endDate - time) - 1;
  6647. }
  6648. else {
  6649. return isHidden.startDate - 1;
  6650. }
  6651. }
  6652. else {
  6653. if (correctionEnabled == true) {
  6654. return isHidden.endDate + (time - isHidden.startDate) + 1;
  6655. }
  6656. else {
  6657. return isHidden.endDate + 1;
  6658. }
  6659. }
  6660. }
  6661. else {
  6662. return time;
  6663. }
  6664. }
  6665. /**
  6666. * Check if a time is hidden
  6667. *
  6668. * @param time
  6669. * @param hiddenDates
  6670. * @returns {{hidden: boolean, startDate: Window.start, endDate: *}}
  6671. */
  6672. exports.isHidden = function(time, hiddenDates) {
  6673. for (var i = 0; i < hiddenDates.length; i++) {
  6674. var startDate = hiddenDates[i].start;
  6675. var endDate = hiddenDates[i].end;
  6676. if (time >= startDate && time < endDate) { // if the start is entering a hidden zone
  6677. return {hidden: true, startDate: startDate, endDate: endDate};
  6678. break;
  6679. }
  6680. }
  6681. return {hidden: false, startDate: startDate, endDate: endDate};
  6682. }
  6683. /***/ },
  6684. /* 16 */
  6685. /***/ function(module, exports, __webpack_require__) {
  6686. /**
  6687. * @constructor DataStep
  6688. * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an
  6689. * end data point. The class itself determines the best scale (step size) based on the
  6690. * provided start Date, end Date, and minimumStep.
  6691. *
  6692. * If minimumStep is provided, the step size is chosen as close as possible
  6693. * to the minimumStep but larger than minimumStep. If minimumStep is not
  6694. * provided, the scale is set to 1 DAY.
  6695. * The minimumStep should correspond with the onscreen size of about 6 characters
  6696. *
  6697. * Alternatively, you can set a scale by hand.
  6698. * After creation, you can initialize the class by executing first(). Then you
  6699. * can iterate from the start date to the end date via next(). You can check if
  6700. * the end date is reached with the function hasNext(). After each step, you can
  6701. * retrieve the current date via getCurrent().
  6702. * The DataStep has scales ranging from milliseconds, seconds, minutes, hours,
  6703. * days, to years.
  6704. *
  6705. * Version: 1.2
  6706. *
  6707. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  6708. * or new Date(2010, 9, 21, 23, 45, 00)
  6709. * @param {Date} [end] The end date
  6710. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  6711. */
  6712. function DataStep(start, end, minimumStep, containerHeight, customRange, alignZeros) {
  6713. // variables
  6714. this.current = 0;
  6715. this.autoScale = true;
  6716. this.stepIndex = 0;
  6717. this.step = 1;
  6718. this.scale = 1;
  6719. this.marginStart;
  6720. this.marginEnd;
  6721. this.deadSpace = 0;
  6722. this.majorSteps = [1, 2, 5, 10];
  6723. this.minorSteps = [0.25, 0.5, 1, 2];
  6724. this.alignZeros = alignZeros;
  6725. this.setRange(start, end, minimumStep, containerHeight, customRange);
  6726. }
  6727. /**
  6728. * Set a new range
  6729. * If minimumStep is provided, the step size is chosen as close as possible
  6730. * to the minimumStep but larger than minimumStep. If minimumStep is not
  6731. * provided, the scale is set to 1 DAY.
  6732. * The minimumStep should correspond with the onscreen size of about 6 characters
  6733. * @param {Number} [start] The start date and time.
  6734. * @param {Number} [end] The end date and time.
  6735. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  6736. */
  6737. DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight, customRange) {
  6738. this._start = customRange.min === undefined ? start : customRange.min;
  6739. this._end = customRange.max === undefined ? end : customRange.max;
  6740. if (this._start == this._end) {
  6741. this._start -= 0.75;
  6742. this._end += 1;
  6743. }
  6744. if (this.autoScale == true) {
  6745. this.setMinimumStep(minimumStep, containerHeight);
  6746. }
  6747. this.setFirst(customRange);
  6748. };
  6749. /**
  6750. * Automatically determine the scale that bests fits the provided minimum step
  6751. * @param {Number} [minimumStep] The minimum step size in milliseconds
  6752. */
  6753. DataStep.prototype.setMinimumStep = function(minimumStep, containerHeight) {
  6754. // round to floor
  6755. var size = this._end - this._start;
  6756. var safeSize = size * 1.2;
  6757. var minimumStepValue = minimumStep * (safeSize / containerHeight);
  6758. var orderOfMagnitude = Math.round(Math.log(safeSize)/Math.LN10);
  6759. var minorStepIdx = -1;
  6760. var magnitudefactor = Math.pow(10,orderOfMagnitude);
  6761. var start = 0;
  6762. if (orderOfMagnitude < 0) {
  6763. start = orderOfMagnitude;
  6764. }
  6765. var solutionFound = false;
  6766. for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) {
  6767. magnitudefactor = Math.pow(10,i);
  6768. for (var j = 0; j < this.minorSteps.length; j++) {
  6769. var stepSize = magnitudefactor * this.minorSteps[j];
  6770. if (stepSize >= minimumStepValue) {
  6771. solutionFound = true;
  6772. minorStepIdx = j;
  6773. break;
  6774. }
  6775. }
  6776. if (solutionFound == true) {
  6777. break;
  6778. }
  6779. }
  6780. this.stepIndex = minorStepIdx;
  6781. this.scale = magnitudefactor;
  6782. this.step = magnitudefactor * this.minorSteps[minorStepIdx];
  6783. };
  6784. /**
  6785. * Round the current date to the first minor date value
  6786. * This must be executed once when the current date is set to start Date
  6787. */
  6788. DataStep.prototype.setFirst = function(customRange) {
  6789. if (customRange === undefined) {
  6790. customRange = {};
  6791. }
  6792. var niceStart = customRange.min === undefined ? this._start - (this.scale * 2 * this.minorSteps[this.stepIndex]) : customRange.min;
  6793. var niceEnd = customRange.max === undefined ? this._end + (this.scale * this.minorSteps[this.stepIndex]) : customRange.max;
  6794. this.marginEnd = customRange.max === undefined ? this.roundToMinor(niceEnd) : customRange.max;
  6795. this.marginStart = customRange.min === undefined ? this.roundToMinor(niceStart) : customRange.min;
  6796. // if we need to align the zero's we need to make sure that there is a zero to use.
  6797. if (this.alignZeros == true && (this.marginEnd - this.marginStart) % this.step != 0) {
  6798. this.marginEnd += this.marginEnd % this.step;
  6799. }
  6800. this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart;
  6801. this.marginRange = this.marginEnd - this.marginStart;
  6802. this.current = this.marginEnd;
  6803. };
  6804. DataStep.prototype.roundToMinor = function(value) {
  6805. var rounded = value - (value % (this.scale * this.minorSteps[this.stepIndex]));
  6806. if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) {
  6807. return rounded + (this.scale * this.minorSteps[this.stepIndex]);
  6808. }
  6809. else {
  6810. return rounded;
  6811. }
  6812. }
  6813. /**
  6814. * Check if the there is a next step
  6815. * @return {boolean} true if the current date has not passed the end date
  6816. */
  6817. DataStep.prototype.hasNext = function () {
  6818. return (this.current >= this.marginStart);
  6819. };
  6820. /**
  6821. * Do the next step
  6822. */
  6823. DataStep.prototype.next = function() {
  6824. var prev = this.current;
  6825. this.current -= this.step;
  6826. // safety mechanism: if current time is still unchanged, move to the end
  6827. if (this.current == prev) {
  6828. this.current = this._end;
  6829. }
  6830. };
  6831. /**
  6832. * Do the next step
  6833. */
  6834. DataStep.prototype.previous = function() {
  6835. this.current += this.step;
  6836. this.marginEnd += this.step;
  6837. this.marginRange = this.marginEnd - this.marginStart;
  6838. };
  6839. /**
  6840. * Get the current datetime
  6841. * @return {String} current The current date
  6842. */
  6843. DataStep.prototype.getCurrent = function(decimals) {
  6844. // prevent round-off errors when close to zero
  6845. var current = (Math.abs(this.current) < this.step / 2) ? 0 : this.current;
  6846. var toPrecision = '' + Number(current).toPrecision(5);
  6847. // If decimals is specified, then limit or extend the string as required
  6848. if(decimals !== undefined && !isNaN(Number(decimals))) {
  6849. // If string includes exponent, then we need to add it to the end
  6850. var exp = "";
  6851. var index = toPrecision.indexOf("e");
  6852. if(index != -1) {
  6853. // Get the exponent
  6854. exp = toPrecision.slice(index);
  6855. // Remove the exponent in case we need to zero-extend
  6856. toPrecision = toPrecision.slice(0, index);
  6857. }
  6858. index = Math.max(toPrecision.indexOf(","), toPrecision.indexOf("."));
  6859. if(index === -1) {
  6860. // No decimal found - if we want decimals, then we need to add it
  6861. if(decimals !== 0) {
  6862. toPrecision += '.';
  6863. }
  6864. // Calculate how long the string should be
  6865. index = toPrecision.length + decimals;
  6866. }
  6867. else if(decimals !== 0) {
  6868. // Calculate how long the string should be - accounting for the decimal place
  6869. index += decimals + 1;
  6870. }
  6871. if(index > toPrecision.length) {
  6872. // We need to add zeros!
  6873. for(var cnt = index - toPrecision.length; cnt > 0; cnt--) {
  6874. toPrecision += '0';
  6875. }
  6876. }
  6877. else {
  6878. // we need to remove characters
  6879. toPrecision = toPrecision.slice(0, index);
  6880. }
  6881. // Add the exponent if there is one
  6882. toPrecision += exp;
  6883. }
  6884. else {
  6885. if (toPrecision.indexOf(",") != -1 || toPrecision.indexOf(".") != -1) {
  6886. // If no decimal is specified, and there are decimal places, remove trailing zeros
  6887. for (var i = toPrecision.length - 1; i > 0; i--) {
  6888. if (toPrecision[i] == "0") {
  6889. toPrecision = toPrecision.slice(0, i);
  6890. }
  6891. else if (toPrecision[i] == "." || toPrecision[i] == ",") {
  6892. toPrecision = toPrecision.slice(0, i);
  6893. break;
  6894. }
  6895. else {
  6896. break;
  6897. }
  6898. }
  6899. }
  6900. }
  6901. return toPrecision;
  6902. };
  6903. /**
  6904. * Check if the current value is a major value (for example when the step
  6905. * is DAY, a major value is each first day of the MONTH)
  6906. * @return {boolean} true if current date is major, else false.
  6907. */
  6908. DataStep.prototype.isMajor = function() {
  6909. return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0);
  6910. };
  6911. module.exports = DataStep;
  6912. /***/ },
  6913. /* 17 */
  6914. /***/ function(module, exports, __webpack_require__) {
  6915. var util = __webpack_require__(1);
  6916. var hammerUtil = __webpack_require__(47);
  6917. var moment = __webpack_require__(44);
  6918. var Component = __webpack_require__(25);
  6919. var DateUtil = __webpack_require__(15);
  6920. /**
  6921. * @constructor Range
  6922. * A Range controls a numeric range with a start and end value.
  6923. * The Range adjusts the range based on mouse events or programmatic changes,
  6924. * and triggers events when the range is changing or has been changed.
  6925. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body
  6926. * @param {Object} [options] See description at Range.setOptions
  6927. */
  6928. function Range(body, options) {
  6929. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6930. this.start = now.clone().add(-3, 'days').valueOf(); // Number
  6931. this.end = now.clone().add(4, 'days').valueOf(); // Number
  6932. this.body = body;
  6933. this.deltaDifference = 0;
  6934. this.scaleOffset = 0;
  6935. this.startToFront = false;
  6936. this.endToFront = true;
  6937. // default options
  6938. this.defaultOptions = {
  6939. start: null,
  6940. end: null,
  6941. direction: 'horizontal', // 'horizontal' or 'vertical'
  6942. moveable: true,
  6943. zoomable: true,
  6944. min: null,
  6945. max: null,
  6946. zoomMin: 10, // milliseconds
  6947. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds
  6948. };
  6949. this.options = util.extend({}, this.defaultOptions);
  6950. this.props = {
  6951. touch: {}
  6952. };
  6953. this.animateTimer = null;
  6954. // drag listeners for dragging
  6955. this.body.emitter.on('dragstart', this._onDragStart.bind(this));
  6956. this.body.emitter.on('drag', this._onDrag.bind(this));
  6957. this.body.emitter.on('dragend', this._onDragEnd.bind(this));
  6958. // ignore dragging when holding
  6959. this.body.emitter.on('hold', this._onHold.bind(this));
  6960. // mouse wheel for zooming
  6961. this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
  6962. this.body.emitter.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  6963. // pinch to zoom
  6964. this.body.emitter.on('touch', this._onTouch.bind(this));
  6965. this.body.emitter.on('pinch', this._onPinch.bind(this));
  6966. this.setOptions(options);
  6967. }
  6968. Range.prototype = new Component();
  6969. /**
  6970. * Set options for the range controller
  6971. * @param {Object} options Available options:
  6972. * {Number | Date | String} start Start date for the range
  6973. * {Number | Date | String} end End date for the range
  6974. * {Number} min Minimum value for start
  6975. * {Number} max Maximum value for end
  6976. * {Number} zoomMin Set a minimum value for
  6977. * (end - start).
  6978. * {Number} zoomMax Set a maximum value for
  6979. * (end - start).
  6980. * {Boolean} moveable Enable moving of the range
  6981. * by dragging. True by default
  6982. * {Boolean} zoomable Enable zooming of the range
  6983. * by pinching/scrolling. True by default
  6984. */
  6985. Range.prototype.setOptions = function (options) {
  6986. if (options) {
  6987. // copy the options that we know
  6988. var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate', 'hiddenDates'];
  6989. util.selectiveExtend(fields, this.options, options);
  6990. if ('start' in options || 'end' in options) {
  6991. // apply a new range. both start and end are optional
  6992. this.setRange(options.start, options.end);
  6993. }
  6994. }
  6995. };
  6996. /**
  6997. * Test whether direction has a valid value
  6998. * @param {String} direction 'horizontal' or 'vertical'
  6999. */
  7000. function validateDirection (direction) {
  7001. if (direction != 'horizontal' && direction != 'vertical') {
  7002. throw new TypeError('Unknown direction "' + direction + '". ' +
  7003. 'Choose "horizontal" or "vertical".');
  7004. }
  7005. }
  7006. /**
  7007. * Set a new start and end range
  7008. * @param {Date | Number | String} [start]
  7009. * @param {Date | Number | String} [end]
  7010. * @param {boolean | number} [animate=false] If true, the range is animated
  7011. * smoothly to the new window.
  7012. * If animate is a number, the
  7013. * number is taken as duration
  7014. * Default duration is 500 ms.
  7015. * @param {Boolean} [byUser=false]
  7016. *
  7017. */
  7018. Range.prototype.setRange = function(start, end, animate, byUser) {
  7019. if (byUser !== true) {
  7020. byUser = false;
  7021. }
  7022. var _start = start != undefined ? util.convert(start, 'Date').valueOf() : null;
  7023. var _end = end != undefined ? util.convert(end, 'Date').valueOf() : null;
  7024. this._cancelAnimation();
  7025. if (animate) {
  7026. var me = this;
  7027. var initStart = this.start;
  7028. var initEnd = this.end;
  7029. var duration = typeof animate === 'number' ? animate : 500;
  7030. var initTime = new Date().valueOf();
  7031. var anyChanged = false;
  7032. var next = function () {
  7033. if (!me.props.touch.dragging) {
  7034. var now = new Date().valueOf();
  7035. var time = now - initTime;
  7036. var done = time > duration;
  7037. var s = (done || _start === null) ? _start : util.easeInOutQuad(time, initStart, _start, duration);
  7038. var e = (done || _end === null) ? _end : util.easeInOutQuad(time, initEnd, _end, duration);
  7039. changed = me._applyRange(s, e);
  7040. DateUtil.updateHiddenDates(me.body, me.options.hiddenDates);
  7041. anyChanged = anyChanged || changed;
  7042. if (changed) {
  7043. me.body.emitter.emit('rangechange', {start: new Date(me.start), end: new Date(me.end), byUser:byUser});
  7044. }
  7045. if (done) {
  7046. if (anyChanged) {
  7047. me.body.emitter.emit('rangechanged', {start: new Date(me.start), end: new Date(me.end), byUser:byUser});
  7048. }
  7049. }
  7050. else {
  7051. // animate with as high as possible frame rate, leave 20 ms in between
  7052. // each to prevent the browser from blocking
  7053. me.animateTimer = setTimeout(next, 20);
  7054. }
  7055. }
  7056. };
  7057. return next();
  7058. }
  7059. else {
  7060. var changed = this._applyRange(_start, _end);
  7061. DateUtil.updateHiddenDates(this.body, this.options.hiddenDates);
  7062. if (changed) {
  7063. var params = {start: new Date(this.start), end: new Date(this.end), byUser:byUser};
  7064. this.body.emitter.emit('rangechange', params);
  7065. this.body.emitter.emit('rangechanged', params);
  7066. }
  7067. }
  7068. };
  7069. /**
  7070. * Stop an animation
  7071. * @private
  7072. */
  7073. Range.prototype._cancelAnimation = function () {
  7074. if (this.animateTimer) {
  7075. clearTimeout(this.animateTimer);
  7076. this.animateTimer = null;
  7077. }
  7078. };
  7079. /**
  7080. * Set a new start and end range. This method is the same as setRange, but
  7081. * does not trigger a range change and range changed event, and it returns
  7082. * true when the range is changed
  7083. * @param {Number} [start]
  7084. * @param {Number} [end]
  7085. * @return {Boolean} changed
  7086. * @private
  7087. */
  7088. Range.prototype._applyRange = function(start, end) {
  7089. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  7090. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  7091. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  7092. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  7093. diff;
  7094. // check for valid number
  7095. if (isNaN(newStart) || newStart === null) {
  7096. throw new Error('Invalid start "' + start + '"');
  7097. }
  7098. if (isNaN(newEnd) || newEnd === null) {
  7099. throw new Error('Invalid end "' + end + '"');
  7100. }
  7101. // prevent start < end
  7102. if (newEnd < newStart) {
  7103. newEnd = newStart;
  7104. }
  7105. // prevent start < min
  7106. if (min !== null) {
  7107. if (newStart < min) {
  7108. diff = (min - newStart);
  7109. newStart += diff;
  7110. newEnd += diff;
  7111. // prevent end > max
  7112. if (max != null) {
  7113. if (newEnd > max) {
  7114. newEnd = max;
  7115. }
  7116. }
  7117. }
  7118. }
  7119. // prevent end > max
  7120. if (max !== null) {
  7121. if (newEnd > max) {
  7122. diff = (newEnd - max);
  7123. newStart -= diff;
  7124. newEnd -= diff;
  7125. // prevent start < min
  7126. if (min != null) {
  7127. if (newStart < min) {
  7128. newStart = min;
  7129. }
  7130. }
  7131. }
  7132. }
  7133. // prevent (end-start) < zoomMin
  7134. if (this.options.zoomMin !== null) {
  7135. var zoomMin = parseFloat(this.options.zoomMin);
  7136. if (zoomMin < 0) {
  7137. zoomMin = 0;
  7138. }
  7139. if ((newEnd - newStart) < zoomMin) {
  7140. if ((this.end - this.start) === zoomMin && newStart > this.start && newEnd < this.end) {
  7141. // ignore this action, we are already zoomed to the minimum
  7142. newStart = this.start;
  7143. newEnd = this.end;
  7144. }
  7145. else {
  7146. // zoom to the minimum
  7147. diff = (zoomMin - (newEnd - newStart));
  7148. newStart -= diff / 2;
  7149. newEnd += diff / 2;
  7150. }
  7151. }
  7152. }
  7153. // prevent (end-start) > zoomMax
  7154. if (this.options.zoomMax !== null) {
  7155. var zoomMax = parseFloat(this.options.zoomMax);
  7156. if (zoomMax < 0) {
  7157. zoomMax = 0;
  7158. }
  7159. if ((newEnd - newStart) > zoomMax) {
  7160. if ((this.end - this.start) === zoomMax && newStart < this.start && newEnd > this.end) {
  7161. // ignore this action, we are already zoomed to the maximum
  7162. newStart = this.start;
  7163. newEnd = this.end;
  7164. }
  7165. else {
  7166. // zoom to the maximum
  7167. diff = ((newEnd - newStart) - zoomMax);
  7168. newStart += diff / 2;
  7169. newEnd -= diff / 2;
  7170. }
  7171. }
  7172. }
  7173. var changed = (this.start != newStart || this.end != newEnd);
  7174. // if the new range does NOT overlap with the old range, emit checkRangedItems to avoid not showing ranged items (ranged meaning has end time, not necessarily of type Range)
  7175. if (!((newStart >= this.start && newStart <= this.end) || (newEnd >= this.start && newEnd <= this.end)) &&
  7176. !((this.start >= newStart && this.start <= newEnd) || (this.end >= newStart && this.end <= newEnd) )) {
  7177. this.body.emitter.emit('checkRangedItems');
  7178. }
  7179. this.start = newStart;
  7180. this.end = newEnd;
  7181. return changed;
  7182. };
  7183. /**
  7184. * Retrieve the current range.
  7185. * @return {Object} An object with start and end properties
  7186. */
  7187. Range.prototype.getRange = function() {
  7188. return {
  7189. start: this.start,
  7190. end: this.end
  7191. };
  7192. };
  7193. /**
  7194. * Calculate the conversion offset and scale for current range, based on
  7195. * the provided width
  7196. * @param {Number} width
  7197. * @returns {{offset: number, scale: number}} conversion
  7198. */
  7199. Range.prototype.conversion = function (width, totalHidden) {
  7200. return Range.conversion(this.start, this.end, width, totalHidden);
  7201. };
  7202. /**
  7203. * Static method to calculate the conversion offset and scale for a range,
  7204. * based on the provided start, end, and width
  7205. * @param {Number} start
  7206. * @param {Number} end
  7207. * @param {Number} width
  7208. * @returns {{offset: number, scale: number}} conversion
  7209. */
  7210. Range.conversion = function (start, end, width, totalHidden) {
  7211. if (totalHidden === undefined) {
  7212. totalHidden = 0;
  7213. }
  7214. if (width != 0 && (end - start != 0)) {
  7215. return {
  7216. offset: start,
  7217. scale: width / (end - start - totalHidden)
  7218. }
  7219. }
  7220. else {
  7221. return {
  7222. offset: 0,
  7223. scale: 1
  7224. };
  7225. }
  7226. };
  7227. /**
  7228. * Start dragging horizontally or vertically
  7229. * @param {Event} event
  7230. * @private
  7231. */
  7232. Range.prototype._onDragStart = function(event) {
  7233. this.deltaDifference = 0;
  7234. this.previousDelta = 0;
  7235. // only allow dragging when configured as movable
  7236. if (!this.options.moveable) return;
  7237. // refuse to drag when we where pinching to prevent the timeline make a jump
  7238. // when releasing the fingers in opposite order from the touch screen
  7239. if (!this.props.touch.allowDragging) return;
  7240. this.props.touch.start = this.start;
  7241. this.props.touch.end = this.end;
  7242. this.props.touch.dragging = true;
  7243. if (this.body.dom.root) {
  7244. this.body.dom.root.style.cursor = 'move';
  7245. }
  7246. };
  7247. /**
  7248. * Perform dragging operation
  7249. * @param {Event} event
  7250. * @private
  7251. */
  7252. Range.prototype._onDrag = function (event) {
  7253. // only allow dragging when configured as movable
  7254. if (!this.options.moveable) return;
  7255. // refuse to drag when we where pinching to prevent the timeline make a jump
  7256. // when releasing the fingers in opposite order from the touch screen
  7257. if (!this.props.touch.allowDragging) return;
  7258. var direction = this.options.direction;
  7259. validateDirection(direction);
  7260. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY;
  7261. delta -= this.deltaDifference;
  7262. var interval = (this.props.touch.end - this.props.touch.start);
  7263. // normalize dragging speed if cutout is in between.
  7264. var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  7265. interval -= duration;
  7266. var width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height;
  7267. var diffRange = -delta / width * interval;
  7268. var newStart = this.props.touch.start + diffRange;
  7269. var newEnd = this.props.touch.end + diffRange;
  7270. // snapping times away from hidden zones
  7271. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, this.previousDelta-delta, true);
  7272. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, this.previousDelta-delta, true);
  7273. if (safeStart != newStart || safeEnd != newEnd) {
  7274. this.deltaDifference += delta;
  7275. this.props.touch.start = safeStart;
  7276. this.props.touch.end = safeEnd;
  7277. this._onDrag(event);
  7278. return;
  7279. }
  7280. this.previousDelta = delta;
  7281. this._applyRange(newStart, newEnd);
  7282. // fire a rangechange event
  7283. this.body.emitter.emit('rangechange', {
  7284. start: new Date(this.start),
  7285. end: new Date(this.end),
  7286. byUser: true
  7287. });
  7288. };
  7289. /**
  7290. * Stop dragging operation
  7291. * @param {event} event
  7292. * @private
  7293. */
  7294. Range.prototype._onDragEnd = function (event) {
  7295. // only allow dragging when configured as movable
  7296. if (!this.options.moveable) return;
  7297. // refuse to drag when we where pinching to prevent the timeline make a jump
  7298. // when releasing the fingers in opposite order from the touch screen
  7299. if (!this.props.touch.allowDragging) return;
  7300. this.props.touch.dragging = false;
  7301. if (this.body.dom.root) {
  7302. this.body.dom.root.style.cursor = 'auto';
  7303. }
  7304. // fire a rangechanged event
  7305. this.body.emitter.emit('rangechanged', {
  7306. start: new Date(this.start),
  7307. end: new Date(this.end),
  7308. byUser: true
  7309. });
  7310. };
  7311. /**
  7312. * Event handler for mouse wheel event, used to zoom
  7313. * Code from http://adomas.org/javascript-mouse-wheel/
  7314. * @param {Event} event
  7315. * @private
  7316. */
  7317. Range.prototype._onMouseWheel = function(event) {
  7318. // only allow zooming when configured as zoomable and moveable
  7319. if (!(this.options.zoomable && this.options.moveable)) return;
  7320. // retrieve delta
  7321. var delta = 0;
  7322. if (event.wheelDelta) { /* IE/Opera. */
  7323. delta = event.wheelDelta / 120;
  7324. } else if (event.detail) { /* Mozilla case. */
  7325. // In Mozilla, sign of delta is different than in IE.
  7326. // Also, delta is multiple of 3.
  7327. delta = -event.detail / 3;
  7328. }
  7329. // If delta is nonzero, handle it.
  7330. // Basically, delta is now positive if wheel was scrolled up,
  7331. // and negative, if wheel was scrolled down.
  7332. if (delta) {
  7333. // perform the zoom action. Delta is normally 1 or -1
  7334. // adjust a negative delta such that zooming in with delta 0.1
  7335. // equals zooming out with a delta -0.1
  7336. var scale;
  7337. if (delta < 0) {
  7338. scale = 1 - (delta / 5);
  7339. }
  7340. else {
  7341. scale = 1 / (1 + (delta / 5)) ;
  7342. }
  7343. // calculate center, the date to zoom around
  7344. var gesture = hammerUtil.fakeGesture(this, event),
  7345. pointer = getPointer(gesture.center, this.body.dom.center),
  7346. pointerDate = this._pointerToDate(pointer);
  7347. this.zoom(scale, pointerDate, delta);
  7348. }
  7349. // Prevent default actions caused by mouse wheel
  7350. // (else the page and timeline both zoom and scroll)
  7351. event.preventDefault();
  7352. };
  7353. /**
  7354. * Start of a touch gesture
  7355. * @private
  7356. */
  7357. Range.prototype._onTouch = function (event) {
  7358. this.props.touch.start = this.start;
  7359. this.props.touch.end = this.end;
  7360. this.props.touch.allowDragging = true;
  7361. this.props.touch.center = null;
  7362. this.scaleOffset = 0;
  7363. this.deltaDifference = 0;
  7364. };
  7365. /**
  7366. * On start of a hold gesture
  7367. * @private
  7368. */
  7369. Range.prototype._onHold = function () {
  7370. this.props.touch.allowDragging = false;
  7371. };
  7372. /**
  7373. * Handle pinch event
  7374. * @param {Event} event
  7375. * @private
  7376. */
  7377. Range.prototype._onPinch = function (event) {
  7378. // only allow zooming when configured as zoomable and moveable
  7379. if (!(this.options.zoomable && this.options.moveable)) return;
  7380. this.props.touch.allowDragging = false;
  7381. if (event.gesture.touches.length > 1) {
  7382. if (!this.props.touch.center) {
  7383. this.props.touch.center = getPointer(event.gesture.center, this.body.dom.center);
  7384. }
  7385. var scale = 1 / (event.gesture.scale + this.scaleOffset);
  7386. var centerDate = this._pointerToDate(this.props.touch.center);
  7387. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  7388. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, centerDate);
  7389. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  7390. // calculate new start and end
  7391. var newStart = (centerDate - hiddenDurationBefore) + (this.props.touch.start - (centerDate - hiddenDurationBefore)) * scale;
  7392. var newEnd = (centerDate + hiddenDurationAfter) + (this.props.touch.end - (centerDate + hiddenDurationAfter)) * scale;
  7393. // snapping times away from hidden zones
  7394. this.startToFront = 1 - scale > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  7395. this.endToFront = scale - 1 > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  7396. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, 1 - scale, true);
  7397. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, scale - 1, true);
  7398. if (safeStart != newStart || safeEnd != newEnd) {
  7399. this.props.touch.start = safeStart;
  7400. this.props.touch.end = safeEnd;
  7401. this.scaleOffset = 1 - event.gesture.scale;
  7402. newStart = safeStart;
  7403. newEnd = safeEnd;
  7404. }
  7405. this.setRange(newStart, newEnd, false, true);
  7406. this.startToFront = false; // revert to default
  7407. this.endToFront = true; // revert to default
  7408. }
  7409. };
  7410. /**
  7411. * Helper function to calculate the center date for zooming
  7412. * @param {{x: Number, y: Number}} pointer
  7413. * @return {number} date
  7414. * @private
  7415. */
  7416. Range.prototype._pointerToDate = function (pointer) {
  7417. var conversion;
  7418. var direction = this.options.direction;
  7419. validateDirection(direction);
  7420. if (direction == 'horizontal') {
  7421. return this.body.util.toTime(pointer.x).valueOf();
  7422. }
  7423. else {
  7424. var height = this.body.domProps.center.height;
  7425. conversion = this.conversion(height);
  7426. return pointer.y / conversion.scale + conversion.offset;
  7427. }
  7428. };
  7429. /**
  7430. * Get the pointer location relative to the location of the dom element
  7431. * @param {{pageX: Number, pageY: Number}} touch
  7432. * @param {Element} element HTML DOM element
  7433. * @return {{x: Number, y: Number}} pointer
  7434. * @private
  7435. */
  7436. function getPointer (touch, element) {
  7437. return {
  7438. x: touch.pageX - util.getAbsoluteLeft(element),
  7439. y: touch.pageY - util.getAbsoluteTop(element)
  7440. };
  7441. }
  7442. /**
  7443. * Zoom the range the given scale in or out. Start and end date will
  7444. * be adjusted, and the timeline will be redrawn. You can optionally give a
  7445. * date around which to zoom.
  7446. * For example, try scale = 0.9 or 1.1
  7447. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  7448. * values below 1 will zoom in.
  7449. * @param {Number} [center] Value representing a date around which will
  7450. * be zoomed.
  7451. */
  7452. Range.prototype.zoom = function(scale, center, delta) {
  7453. // if centerDate is not provided, take it half between start Date and end Date
  7454. if (center == null) {
  7455. center = (this.start + this.end) / 2;
  7456. }
  7457. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  7458. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, center);
  7459. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  7460. // calculate new start and end
  7461. var newStart = (center-hiddenDurationBefore) + (this.start - (center-hiddenDurationBefore)) * scale;
  7462. var newEnd = (center+hiddenDurationAfter) + (this.end - (center+hiddenDurationAfter)) * scale;
  7463. // snapping times away from hidden zones
  7464. this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  7465. this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  7466. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, delta, true);
  7467. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, -delta, true);
  7468. if (safeStart != newStart || safeEnd != newEnd) {
  7469. newStart = safeStart;
  7470. newEnd = safeEnd;
  7471. }
  7472. this.setRange(newStart, newEnd, false, true);
  7473. this.startToFront = false; // revert to default
  7474. this.endToFront = true; // revert to default
  7475. };
  7476. /**
  7477. * Move the range with a given delta to the left or right. Start and end
  7478. * value will be adjusted. For example, try delta = 0.1 or -0.1
  7479. * @param {Number} delta Moving amount. Positive value will move right,
  7480. * negative value will move left
  7481. */
  7482. Range.prototype.move = function(delta) {
  7483. // zoom start Date and end Date relative to the centerDate
  7484. var diff = (this.end - this.start);
  7485. // apply new values
  7486. var newStart = this.start + diff * delta;
  7487. var newEnd = this.end + diff * delta;
  7488. // TODO: reckon with min and max range
  7489. this.start = newStart;
  7490. this.end = newEnd;
  7491. };
  7492. /**
  7493. * Move the range to a new center point
  7494. * @param {Number} moveTo New center point of the range
  7495. */
  7496. Range.prototype.moveTo = function(moveTo) {
  7497. var center = (this.start + this.end) / 2;
  7498. var diff = center - moveTo;
  7499. // calculate new start and end
  7500. var newStart = this.start - diff;
  7501. var newEnd = this.end - diff;
  7502. this.setRange(newStart, newEnd);
  7503. };
  7504. module.exports = Range;
  7505. /***/ },
  7506. /* 18 */
  7507. /***/ function(module, exports, __webpack_require__) {
  7508. // Utility functions for ordering and stacking of items
  7509. var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors
  7510. /**
  7511. * Order items by their start data
  7512. * @param {Item[]} items
  7513. */
  7514. exports.orderByStart = function(items) {
  7515. items.sort(function (a, b) {
  7516. return a.data.start - b.data.start;
  7517. });
  7518. };
  7519. /**
  7520. * Order items by their end date. If they have no end date, their start date
  7521. * is used.
  7522. * @param {Item[]} items
  7523. */
  7524. exports.orderByEnd = function(items) {
  7525. items.sort(function (a, b) {
  7526. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  7527. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  7528. return aTime - bTime;
  7529. });
  7530. };
  7531. /**
  7532. * Adjust vertical positions of the items such that they don't overlap each
  7533. * other.
  7534. * @param {Item[]} items
  7535. * All visible items
  7536. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  7537. * Margins between items and between items and the axis.
  7538. * @param {boolean} [force=false]
  7539. * If true, all items will be repositioned. If false (default), only
  7540. * items having a top===null will be re-stacked
  7541. */
  7542. exports.stack = function(items, margin, force) {
  7543. var i, iMax;
  7544. if (force) {
  7545. // reset top position of all items
  7546. for (i = 0, iMax = items.length; i < iMax; i++) {
  7547. items[i].top = null;
  7548. }
  7549. }
  7550. // calculate new, non-overlapping positions
  7551. for (i = 0, iMax = items.length; i < iMax; i++) {
  7552. var item = items[i];
  7553. if (item.stack && item.top === null) {
  7554. // initialize top position
  7555. item.top = margin.axis;
  7556. do {
  7557. // TODO: optimize checking for overlap. when there is a gap without items,
  7558. // you only need to check for items from the next item on, not from zero
  7559. var collidingItem = null;
  7560. for (var j = 0, jj = items.length; j < jj; j++) {
  7561. var other = items[j];
  7562. if (other.top !== null && other !== item && other.stack && exports.collision(item, other, margin.item)) {
  7563. collidingItem = other;
  7564. break;
  7565. }
  7566. }
  7567. if (collidingItem != null) {
  7568. // There is a collision. Reposition the items above the colliding element
  7569. item.top = collidingItem.top + collidingItem.height + margin.item.vertical;
  7570. }
  7571. } while (collidingItem);
  7572. }
  7573. }
  7574. };
  7575. /**
  7576. * Adjust vertical positions of the items without stacking them
  7577. * @param {Item[]} items
  7578. * All visible items
  7579. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  7580. * Margins between items and between items and the axis.
  7581. */
  7582. exports.nostack = function(items, margin, subgroups) {
  7583. var i, iMax, newTop;
  7584. // reset top position of all items
  7585. for (i = 0, iMax = items.length; i < iMax; i++) {
  7586. if (items[i].data.subgroup !== undefined) {
  7587. newTop = margin.axis;
  7588. for (var subgroup in subgroups) {
  7589. if (subgroups.hasOwnProperty(subgroup)) {
  7590. if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroups[items[i].data.subgroup].index) {
  7591. newTop += subgroups[subgroup].height + margin.item.vertical;
  7592. }
  7593. }
  7594. }
  7595. items[i].top = newTop;
  7596. }
  7597. else {
  7598. items[i].top = margin.axis;
  7599. }
  7600. }
  7601. };
  7602. /**
  7603. * Test if the two provided items collide
  7604. * The items must have parameters left, width, top, and height.
  7605. * @param {Item} a The first item
  7606. * @param {Item} b The second item
  7607. * @param {{horizontal: number, vertical: number}} margin
  7608. * An object containing a horizontal and vertical
  7609. * minimum required margin.
  7610. * @return {boolean} true if a and b collide, else false
  7611. */
  7612. exports.collision = function(a, b, margin) {
  7613. return ((a.left - margin.horizontal + EPSILON) < (b.left + b.width) &&
  7614. (a.left + a.width + margin.horizontal - EPSILON) > b.left &&
  7615. (a.top - margin.vertical + EPSILON) < (b.top + b.height) &&
  7616. (a.top + a.height + margin.vertical - EPSILON) > b.top);
  7617. };
  7618. /***/ },
  7619. /* 19 */
  7620. /***/ function(module, exports, __webpack_require__) {
  7621. var moment = __webpack_require__(44);
  7622. var DateUtil = __webpack_require__(15);
  7623. var util = __webpack_require__(1);
  7624. /**
  7625. * @constructor TimeStep
  7626. * The class TimeStep is an iterator for dates. You provide a start date and an
  7627. * end date. The class itself determines the best scale (step size) based on the
  7628. * provided start Date, end Date, and minimumStep.
  7629. *
  7630. * If minimumStep is provided, the step size is chosen as close as possible
  7631. * to the minimumStep but larger than minimumStep. If minimumStep is not
  7632. * provided, the scale is set to 1 DAY.
  7633. * The minimumStep should correspond with the onscreen size of about 6 characters
  7634. *
  7635. * Alternatively, you can set a scale by hand.
  7636. * After creation, you can initialize the class by executing first(). Then you
  7637. * can iterate from the start date to the end date via next(). You can check if
  7638. * the end date is reached with the function hasNext(). After each step, you can
  7639. * retrieve the current date via getCurrent().
  7640. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  7641. * days, to years.
  7642. *
  7643. * Version: 1.2
  7644. *
  7645. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  7646. * or new Date(2010, 9, 21, 23, 45, 00)
  7647. * @param {Date} [end] The end date
  7648. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  7649. */
  7650. function TimeStep(start, end, minimumStep, hiddenDates) {
  7651. // variables
  7652. this.current = new Date();
  7653. this._start = new Date();
  7654. this._end = new Date();
  7655. this.autoScale = true;
  7656. this.scale = 'day';
  7657. this.step = 1;
  7658. // initialize the range
  7659. this.setRange(start, end, minimumStep);
  7660. // hidden Dates options
  7661. this.switchedDay = false;
  7662. this.switchedMonth = false;
  7663. this.switchedYear = false;
  7664. this.hiddenDates = hiddenDates;
  7665. if (hiddenDates === undefined) {
  7666. this.hiddenDates = [];
  7667. }
  7668. this.format = TimeStep.FORMAT; // default formatting
  7669. }
  7670. // Time formatting
  7671. TimeStep.FORMAT = {
  7672. minorLabels: {
  7673. millisecond:'SSS',
  7674. second: 's',
  7675. minute: 'HH:mm',
  7676. hour: 'HH:mm',
  7677. weekday: 'ddd D',
  7678. day: 'D',
  7679. month: 'MMM',
  7680. year: 'YYYY'
  7681. },
  7682. majorLabels: {
  7683. millisecond:'HH:mm:ss',
  7684. second: 'D MMMM HH:mm',
  7685. minute: 'ddd D MMMM',
  7686. hour: 'ddd D MMMM',
  7687. weekday: 'MMMM YYYY',
  7688. day: 'MMMM YYYY',
  7689. month: 'YYYY',
  7690. year: ''
  7691. }
  7692. };
  7693. /**
  7694. * Set custom formatting for the minor an major labels of the TimeStep.
  7695. * Both `minorLabels` and `majorLabels` are an Object with properties:
  7696. * 'millisecond, 'second, 'minute', 'hour', 'weekday, 'day, 'month, 'year'.
  7697. * @param {{minorLabels: Object, majorLabels: Object}} format
  7698. */
  7699. TimeStep.prototype.setFormat = function (format) {
  7700. var defaultFormat = util.deepExtend({}, TimeStep.FORMAT);
  7701. this.format = util.deepExtend(defaultFormat, format);
  7702. };
  7703. /**
  7704. * Set a new range
  7705. * If minimumStep is provided, the step size is chosen as close as possible
  7706. * to the minimumStep but larger than minimumStep. If minimumStep is not
  7707. * provided, the scale is set to 1 DAY.
  7708. * The minimumStep should correspond with the onscreen size of about 6 characters
  7709. * @param {Date} [start] The start date and time.
  7710. * @param {Date} [end] The end date and time.
  7711. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  7712. */
  7713. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  7714. if (!(start instanceof Date) || !(end instanceof Date)) {
  7715. throw "No legal start or end date in method setRange";
  7716. }
  7717. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  7718. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  7719. if (this.autoScale) {
  7720. this.setMinimumStep(minimumStep);
  7721. }
  7722. };
  7723. /**
  7724. * Set the range iterator to the start date.
  7725. */
  7726. TimeStep.prototype.first = function() {
  7727. this.current = new Date(this._start.valueOf());
  7728. this.roundToMinor();
  7729. };
  7730. /**
  7731. * Round the current date to the first minor date value
  7732. * This must be executed once when the current date is set to start Date
  7733. */
  7734. TimeStep.prototype.roundToMinor = function() {
  7735. // round to floor
  7736. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  7737. // noinspection FallThroughInSwitchStatementJS
  7738. switch (this.scale) {
  7739. case 'year':
  7740. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  7741. this.current.setMonth(0);
  7742. case 'month': this.current.setDate(1);
  7743. case 'day': // intentional fall through
  7744. case 'weekday': this.current.setHours(0);
  7745. case 'hour': this.current.setMinutes(0);
  7746. case 'minute': this.current.setSeconds(0);
  7747. case 'second': this.current.setMilliseconds(0);
  7748. //case 'millisecond': // nothing to do for milliseconds
  7749. }
  7750. if (this.step != 1) {
  7751. // round down to the first minor value that is a multiple of the current step size
  7752. switch (this.scale) {
  7753. case 'millisecond': this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  7754. case 'second': this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  7755. case 'minute': this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  7756. case 'hour': this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  7757. case 'weekday': // intentional fall through
  7758. case 'day': this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  7759. case 'month': this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  7760. case 'year': this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  7761. default: break;
  7762. }
  7763. }
  7764. };
  7765. /**
  7766. * Check if the there is a next step
  7767. * @return {boolean} true if the current date has not passed the end date
  7768. */
  7769. TimeStep.prototype.hasNext = function () {
  7770. return (this.current.valueOf() <= this._end.valueOf());
  7771. };
  7772. /**
  7773. * Do the next step
  7774. */
  7775. TimeStep.prototype.next = function() {
  7776. var prev = this.current.valueOf();
  7777. // Two cases, needed to prevent issues with switching daylight savings
  7778. // (end of March and end of October)
  7779. if (this.current.getMonth() < 6) {
  7780. switch (this.scale) {
  7781. case 'millisecond':
  7782. this.current = new Date(this.current.valueOf() + this.step); break;
  7783. case 'second': this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  7784. case 'minute': this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  7785. case 'hour':
  7786. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  7787. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  7788. var h = this.current.getHours();
  7789. this.current.setHours(h - (h % this.step));
  7790. break;
  7791. case 'weekday': // intentional fall through
  7792. case 'day': this.current.setDate(this.current.getDate() + this.step); break;
  7793. case 'month': this.current.setMonth(this.current.getMonth() + this.step); break;
  7794. case 'year': this.current.setFullYear(this.current.getFullYear() + this.step); break;
  7795. default: break;
  7796. }
  7797. }
  7798. else {
  7799. switch (this.scale) {
  7800. case 'millisecond': this.current = new Date(this.current.valueOf() + this.step); break;
  7801. case 'second': this.current.setSeconds(this.current.getSeconds() + this.step); break;
  7802. case 'minute': this.current.setMinutes(this.current.getMinutes() + this.step); break;
  7803. case 'hour': this.current.setHours(this.current.getHours() + this.step); break;
  7804. case 'weekday': // intentional fall through
  7805. case 'day': this.current.setDate(this.current.getDate() + this.step); break;
  7806. case 'month': this.current.setMonth(this.current.getMonth() + this.step); break;
  7807. case 'year': this.current.setFullYear(this.current.getFullYear() + this.step); break;
  7808. default: break;
  7809. }
  7810. }
  7811. if (this.step != 1) {
  7812. // round down to the correct major value
  7813. switch (this.scale) {
  7814. case 'millisecond': if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  7815. case 'second': if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  7816. case 'minute': if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  7817. case 'hour': if(this.current.getHours() < this.step) this.current.setHours(0); break;
  7818. case 'weekday': // intentional fall through
  7819. case 'day': if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  7820. case 'month': if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  7821. case 'year': break; // nothing to do for year
  7822. default: break;
  7823. }
  7824. }
  7825. // safety mechanism: if current time is still unchanged, move to the end
  7826. if (this.current.valueOf() == prev) {
  7827. this.current = new Date(this._end.valueOf());
  7828. }
  7829. DateUtil.stepOverHiddenDates(this, prev);
  7830. };
  7831. /**
  7832. * Get the current datetime
  7833. * @return {Date} current The current date
  7834. */
  7835. TimeStep.prototype.getCurrent = function() {
  7836. return this.current;
  7837. };
  7838. /**
  7839. * Set a custom scale. Autoscaling will be disabled.
  7840. * For example setScale('minute', 5) will result
  7841. * in minor steps of 5 minutes, and major steps of an hour.
  7842. *
  7843. * @param {{scale: string, step: number}} params
  7844. * An object containing two properties:
  7845. * - A string 'scale'. Choose from 'millisecond', 'second',
  7846. * 'minute', 'hour', 'weekday, 'day, 'month, 'year'.
  7847. * - A number 'step'. A step size, by default 1.
  7848. * Choose for example 1, 2, 5, or 10.
  7849. */
  7850. TimeStep.prototype.setScale = function(params) {
  7851. if (params && typeof params.scale == 'string') {
  7852. this.scale = params.scale;
  7853. this.step = params.step > 0 ? params.step : 1;
  7854. this.autoScale = false;
  7855. }
  7856. };
  7857. /**
  7858. * Enable or disable autoscaling
  7859. * @param {boolean} enable If true, autoascaling is set true
  7860. */
  7861. TimeStep.prototype.setAutoScale = function (enable) {
  7862. this.autoScale = enable;
  7863. };
  7864. /**
  7865. * Automatically determine the scale that bests fits the provided minimum step
  7866. * @param {Number} [minimumStep] The minimum step size in milliseconds
  7867. */
  7868. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  7869. if (minimumStep == undefined) {
  7870. return;
  7871. }
  7872. //var b = asc + ds;
  7873. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  7874. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  7875. var stepDay = (1000 * 60 * 60 * 24);
  7876. var stepHour = (1000 * 60 * 60);
  7877. var stepMinute = (1000 * 60);
  7878. var stepSecond = (1000);
  7879. var stepMillisecond= (1);
  7880. // find the smallest step that is larger than the provided minimumStep
  7881. if (stepYear*1000 > minimumStep) {this.scale = 'year'; this.step = 1000;}
  7882. if (stepYear*500 > minimumStep) {this.scale = 'year'; this.step = 500;}
  7883. if (stepYear*100 > minimumStep) {this.scale = 'year'; this.step = 100;}
  7884. if (stepYear*50 > minimumStep) {this.scale = 'year'; this.step = 50;}
  7885. if (stepYear*10 > minimumStep) {this.scale = 'year'; this.step = 10;}
  7886. if (stepYear*5 > minimumStep) {this.scale = 'year'; this.step = 5;}
  7887. if (stepYear > minimumStep) {this.scale = 'year'; this.step = 1;}
  7888. if (stepMonth*3 > minimumStep) {this.scale = 'month'; this.step = 3;}
  7889. if (stepMonth > minimumStep) {this.scale = 'month'; this.step = 1;}
  7890. if (stepDay*5 > minimumStep) {this.scale = 'day'; this.step = 5;}
  7891. if (stepDay*2 > minimumStep) {this.scale = 'day'; this.step = 2;}
  7892. if (stepDay > minimumStep) {this.scale = 'day'; this.step = 1;}
  7893. if (stepDay/2 > minimumStep) {this.scale = 'weekday'; this.step = 1;}
  7894. if (stepHour*4 > minimumStep) {this.scale = 'hour'; this.step = 4;}
  7895. if (stepHour > minimumStep) {this.scale = 'hour'; this.step = 1;}
  7896. if (stepMinute*15 > minimumStep) {this.scale = 'minute'; this.step = 15;}
  7897. if (stepMinute*10 > minimumStep) {this.scale = 'minute'; this.step = 10;}
  7898. if (stepMinute*5 > minimumStep) {this.scale = 'minute'; this.step = 5;}
  7899. if (stepMinute > minimumStep) {this.scale = 'minute'; this.step = 1;}
  7900. if (stepSecond*15 > minimumStep) {this.scale = 'second'; this.step = 15;}
  7901. if (stepSecond*10 > minimumStep) {this.scale = 'second'; this.step = 10;}
  7902. if (stepSecond*5 > minimumStep) {this.scale = 'second'; this.step = 5;}
  7903. if (stepSecond > minimumStep) {this.scale = 'second'; this.step = 1;}
  7904. if (stepMillisecond*200 > minimumStep) {this.scale = 'millisecond'; this.step = 200;}
  7905. if (stepMillisecond*100 > minimumStep) {this.scale = 'millisecond'; this.step = 100;}
  7906. if (stepMillisecond*50 > minimumStep) {this.scale = 'millisecond'; this.step = 50;}
  7907. if (stepMillisecond*10 > minimumStep) {this.scale = 'millisecond'; this.step = 10;}
  7908. if (stepMillisecond*5 > minimumStep) {this.scale = 'millisecond'; this.step = 5;}
  7909. if (stepMillisecond > minimumStep) {this.scale = 'millisecond'; this.step = 1;}
  7910. };
  7911. /**
  7912. * Snap a date to a rounded value.
  7913. * The snap intervals are dependent on the current scale and step.
  7914. * Static function
  7915. * @param {Date} date the date to be snapped.
  7916. * @param {string} scale Current scale, can be 'millisecond', 'second',
  7917. * 'minute', 'hour', 'weekday, 'day, 'month, 'year'.
  7918. * @param {number} step Current step (1, 2, 4, 5, ...
  7919. * @return {Date} snappedDate
  7920. */
  7921. TimeStep.snap = function(date, scale, step) {
  7922. var clone = new Date(date.valueOf());
  7923. if (scale == 'year') {
  7924. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  7925. clone.setFullYear(Math.round(year / step) * step);
  7926. clone.setMonth(0);
  7927. clone.setDate(0);
  7928. clone.setHours(0);
  7929. clone.setMinutes(0);
  7930. clone.setSeconds(0);
  7931. clone.setMilliseconds(0);
  7932. }
  7933. else if (scale == 'month') {
  7934. if (clone.getDate() > 15) {
  7935. clone.setDate(1);
  7936. clone.setMonth(clone.getMonth() + 1);
  7937. // important: first set Date to 1, after that change the month.
  7938. }
  7939. else {
  7940. clone.setDate(1);
  7941. }
  7942. clone.setHours(0);
  7943. clone.setMinutes(0);
  7944. clone.setSeconds(0);
  7945. clone.setMilliseconds(0);
  7946. }
  7947. else if (scale == 'day') {
  7948. //noinspection FallthroughInSwitchStatementJS
  7949. switch (step) {
  7950. case 5:
  7951. case 2:
  7952. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  7953. default:
  7954. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  7955. }
  7956. clone.setMinutes(0);
  7957. clone.setSeconds(0);
  7958. clone.setMilliseconds(0);
  7959. }
  7960. else if (scale == 'weekday') {
  7961. //noinspection FallthroughInSwitchStatementJS
  7962. switch (step) {
  7963. case 5:
  7964. case 2:
  7965. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  7966. default:
  7967. clone.setHours(Math.round(clone.getHours() / 6) * 6); break;
  7968. }
  7969. clone.setMinutes(0);
  7970. clone.setSeconds(0);
  7971. clone.setMilliseconds(0);
  7972. }
  7973. else if (scale == 'hour') {
  7974. switch (step) {
  7975. case 4:
  7976. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  7977. default:
  7978. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  7979. }
  7980. clone.setSeconds(0);
  7981. clone.setMilliseconds(0);
  7982. } else if (scale == 'minute') {
  7983. //noinspection FallthroughInSwitchStatementJS
  7984. switch (step) {
  7985. case 15:
  7986. case 10:
  7987. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  7988. clone.setSeconds(0);
  7989. break;
  7990. case 5:
  7991. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  7992. default:
  7993. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  7994. }
  7995. clone.setMilliseconds(0);
  7996. }
  7997. else if (scale == 'second') {
  7998. //noinspection FallthroughInSwitchStatementJS
  7999. switch (step) {
  8000. case 15:
  8001. case 10:
  8002. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  8003. clone.setMilliseconds(0);
  8004. break;
  8005. case 5:
  8006. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  8007. default:
  8008. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  8009. }
  8010. }
  8011. else if (scale == 'millisecond') {
  8012. var _step = step > 5 ? step / 2 : 1;
  8013. clone.setMilliseconds(Math.round(clone.getMilliseconds() / _step) * _step);
  8014. }
  8015. return clone;
  8016. };
  8017. /**
  8018. * Check if the current value is a major value (for example when the step
  8019. * is DAY, a major value is each first day of the MONTH)
  8020. * @return {boolean} true if current date is major, else false.
  8021. */
  8022. TimeStep.prototype.isMajor = function() {
  8023. if (this.switchedYear == true) {
  8024. this.switchedYear = false;
  8025. switch (this.scale) {
  8026. case 'year':
  8027. case 'month':
  8028. case 'weekday':
  8029. case 'day':
  8030. case 'hour':
  8031. case 'minute':
  8032. case 'second':
  8033. case 'millisecond':
  8034. return true;
  8035. default:
  8036. return false;
  8037. }
  8038. }
  8039. else if (this.switchedMonth == true) {
  8040. this.switchedMonth = false;
  8041. switch (this.scale) {
  8042. case 'weekday':
  8043. case 'day':
  8044. case 'hour':
  8045. case 'minute':
  8046. case 'second':
  8047. case 'millisecond':
  8048. return true;
  8049. default:
  8050. return false;
  8051. }
  8052. }
  8053. else if (this.switchedDay == true) {
  8054. this.switchedDay = false;
  8055. switch (this.scale) {
  8056. case 'millisecond':
  8057. case 'second':
  8058. case 'minute':
  8059. case 'hour':
  8060. return true;
  8061. default:
  8062. return false;
  8063. }
  8064. }
  8065. switch (this.scale) {
  8066. case 'millisecond':
  8067. return (this.current.getMilliseconds() == 0);
  8068. case 'second':
  8069. return (this.current.getSeconds() == 0);
  8070. case 'minute':
  8071. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  8072. case 'hour':
  8073. return (this.current.getHours() == 0);
  8074. case 'weekday': // intentional fall through
  8075. case 'day':
  8076. return (this.current.getDate() == 1);
  8077. case 'month':
  8078. return (this.current.getMonth() == 0);
  8079. case 'year':
  8080. return false;
  8081. default:
  8082. return false;
  8083. }
  8084. };
  8085. /**
  8086. * Returns formatted text for the minor axislabel, depending on the current
  8087. * date and the scale. For example when scale is MINUTE, the current time is
  8088. * formatted as "hh:mm".
  8089. * @param {Date} [date] custom date. if not provided, current date is taken
  8090. */
  8091. TimeStep.prototype.getLabelMinor = function(date) {
  8092. if (date == undefined) {
  8093. date = this.current;
  8094. }
  8095. var format = this.format.minorLabels[this.scale];
  8096. return (format && format.length > 0) ? moment(date).format(format) : '';
  8097. };
  8098. /**
  8099. * Returns formatted text for the major axis label, depending on the current
  8100. * date and the scale. For example when scale is MINUTE, the major scale is
  8101. * hours, and the hour will be formatted as "hh".
  8102. * @param {Date} [date] custom date. if not provided, current date is taken
  8103. */
  8104. TimeStep.prototype.getLabelMajor = function(date) {
  8105. if (date == undefined) {
  8106. date = this.current;
  8107. }
  8108. var format = this.format.majorLabels[this.scale];
  8109. return (format && format.length > 0) ? moment(date).format(format) : '';
  8110. };
  8111. TimeStep.prototype.getClassName = function() {
  8112. var m = moment(this.current);
  8113. var date = m.locale ? m.locale('en') : m.lang('en'); // old versions of moment have .lang() function
  8114. var step = this.step;
  8115. function even(value) {
  8116. return (value / step % 2 == 0) ? ' even' : ' odd';
  8117. }
  8118. function today(date) {
  8119. if (date.isSame(new Date(), 'day')) {
  8120. return ' today';
  8121. }
  8122. if (date.isSame(moment().add(1, 'day'), 'day')) {
  8123. return ' tomorrow';
  8124. }
  8125. if (date.isSame(moment().add(-1, 'day'), 'day')) {
  8126. return ' yesterday';
  8127. }
  8128. return '';
  8129. }
  8130. function currentWeek(date) {
  8131. return date.isSame(new Date(), 'week') ? ' current-week' : '';
  8132. }
  8133. function currentMonth(date) {
  8134. return date.isSame(new Date(), 'month') ? ' current-month' : '';
  8135. }
  8136. function currentYear(date) {
  8137. return date.isSame(new Date(), 'year') ? ' current-year' : '';
  8138. }
  8139. switch (this.scale) {
  8140. case 'millisecond':
  8141. return even(date.milliseconds()).trim();
  8142. case 'second':
  8143. return even(date.seconds()).trim();
  8144. case 'minute':
  8145. return even(date.minutes()).trim();
  8146. case 'hour':
  8147. var hours = date.hours();
  8148. if (this.step == 4) {
  8149. hours = hours + '-' + (hours + 4);
  8150. }
  8151. return hours + 'h' + today(date) + even(date.hours());
  8152. case 'weekday':
  8153. return date.format('dddd').toLowerCase() +
  8154. today(date) + currentWeek(date) + even(date.date());
  8155. case 'day':
  8156. var day = date.date();
  8157. var month = date.format('MMMM').toLowerCase();
  8158. return 'day' + day + ' ' + month + currentMonth(date) + even(day - 1);
  8159. case 'month':
  8160. return date.format('MMMM').toLowerCase() +
  8161. currentMonth(date) + even(date.month());
  8162. case 'year':
  8163. var year = date.year();
  8164. return 'year' + year + currentYear(date)+ even(year);
  8165. default:
  8166. return '';
  8167. }
  8168. };
  8169. module.exports = TimeStep;
  8170. /***/ },
  8171. /* 20 */
  8172. /***/ function(module, exports, __webpack_require__) {
  8173. var Hammer = __webpack_require__(45);
  8174. var util = __webpack_require__(1);
  8175. /**
  8176. * @constructor Item
  8177. * @param {Object} data Object containing (optional) parameters type,
  8178. * start, end, content, group, className.
  8179. * @param {{toScreen: function, toTime: function}} conversion
  8180. * Conversion functions from time to screen and vice versa
  8181. * @param {Object} options Configuration options
  8182. * // TODO: describe available options
  8183. */
  8184. function Item (data, conversion, options) {
  8185. this.id = null;
  8186. this.parent = null;
  8187. this.data = data;
  8188. this.dom = null;
  8189. this.conversion = conversion || {};
  8190. this.options = options || {};
  8191. this.selected = false;
  8192. this.displayed = false;
  8193. this.dirty = true;
  8194. this.top = null;
  8195. this.left = null;
  8196. this.width = null;
  8197. this.height = null;
  8198. }
  8199. Item.prototype.stack = true;
  8200. /**
  8201. * Select current item
  8202. */
  8203. Item.prototype.select = function() {
  8204. this.selected = true;
  8205. this.dirty = true;
  8206. if (this.displayed) this.redraw();
  8207. };
  8208. /**
  8209. * Unselect current item
  8210. */
  8211. Item.prototype.unselect = function() {
  8212. this.selected = false;
  8213. this.dirty = true;
  8214. if (this.displayed) this.redraw();
  8215. };
  8216. /**
  8217. * Set data for the item. Existing data will be updated. The id should not
  8218. * be changed. When the item is displayed, it will be redrawn immediately.
  8219. * @param {Object} data
  8220. */
  8221. Item.prototype.setData = function(data) {
  8222. var groupChanged = data.group != undefined && this.data.group != data.group;
  8223. if (groupChanged) {
  8224. this.parent.itemSet._moveToGroup(this, data.group);
  8225. }
  8226. this.data = data;
  8227. this.dirty = true;
  8228. if (this.displayed) this.redraw();
  8229. };
  8230. /**
  8231. * Set a parent for the item
  8232. * @param {ItemSet | Group} parent
  8233. */
  8234. Item.prototype.setParent = function(parent) {
  8235. if (this.displayed) {
  8236. this.hide();
  8237. this.parent = parent;
  8238. if (this.parent) {
  8239. this.show();
  8240. }
  8241. }
  8242. else {
  8243. this.parent = parent;
  8244. }
  8245. };
  8246. /**
  8247. * Check whether this item is visible inside given range
  8248. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  8249. * @returns {boolean} True if visible
  8250. */
  8251. Item.prototype.isVisible = function(range) {
  8252. // Should be implemented by Item implementations
  8253. return false;
  8254. };
  8255. /**
  8256. * Show the Item in the DOM (when not already visible)
  8257. * @return {Boolean} changed
  8258. */
  8259. Item.prototype.show = function() {
  8260. return false;
  8261. };
  8262. /**
  8263. * Hide the Item from the DOM (when visible)
  8264. * @return {Boolean} changed
  8265. */
  8266. Item.prototype.hide = function() {
  8267. return false;
  8268. };
  8269. /**
  8270. * Repaint the item
  8271. */
  8272. Item.prototype.redraw = function() {
  8273. // should be implemented by the item
  8274. };
  8275. /**
  8276. * Reposition the Item horizontally
  8277. */
  8278. Item.prototype.repositionX = function() {
  8279. // should be implemented by the item
  8280. };
  8281. /**
  8282. * Reposition the Item vertically
  8283. */
  8284. Item.prototype.repositionY = function() {
  8285. // should be implemented by the item
  8286. };
  8287. /**
  8288. * Repaint a delete button on the top right of the item when the item is selected
  8289. * @param {HTMLElement} anchor
  8290. * @protected
  8291. */
  8292. Item.prototype._repaintDeleteButton = function (anchor) {
  8293. if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
  8294. // create and show button
  8295. var me = this;
  8296. var deleteButton = document.createElement('div');
  8297. deleteButton.className = 'delete';
  8298. deleteButton.title = 'Delete this item';
  8299. Hammer(deleteButton, {
  8300. preventDefault: true
  8301. }).on('tap', function (event) {
  8302. event.preventDefault();
  8303. event.stopPropagation();
  8304. me.parent.removeFromDataSet(me);
  8305. });
  8306. anchor.appendChild(deleteButton);
  8307. this.dom.deleteButton = deleteButton;
  8308. }
  8309. else if (!this.selected && this.dom.deleteButton) {
  8310. // remove button
  8311. if (this.dom.deleteButton.parentNode) {
  8312. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  8313. }
  8314. this.dom.deleteButton = null;
  8315. }
  8316. };
  8317. /**
  8318. * Set HTML contents for the item
  8319. * @param {Element} element HTML element to fill with the contents
  8320. * @private
  8321. */
  8322. Item.prototype._updateContents = function (element) {
  8323. var content;
  8324. if (this.options.template) {
  8325. var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset
  8326. content = this.options.template(itemData);
  8327. }
  8328. else {
  8329. content = this.data.content;
  8330. }
  8331. if(content !== this.content) {
  8332. // only replace the content when changed
  8333. if (content instanceof Element) {
  8334. element.innerHTML = '';
  8335. element.appendChild(content);
  8336. }
  8337. else if (content != undefined) {
  8338. element.innerHTML = content;
  8339. }
  8340. else {
  8341. if (!(this.data.type == 'background' && this.data.content === undefined)) {
  8342. throw new Error('Property "content" missing in item ' + this.id);
  8343. }
  8344. }
  8345. this.content = content;
  8346. }
  8347. };
  8348. /**
  8349. * Set HTML contents for the item
  8350. * @param {Element} element HTML element to fill with the contents
  8351. * @private
  8352. */
  8353. Item.prototype._updateTitle = function (element) {
  8354. if (this.data.title != null) {
  8355. element.title = this.data.title || '';
  8356. }
  8357. else {
  8358. element.removeAttribute('title');
  8359. }
  8360. };
  8361. /**
  8362. * Process dataAttributes timeline option and set as data- attributes on dom.content
  8363. * @param {Element} element HTML element to which the attributes will be attached
  8364. * @private
  8365. */
  8366. Item.prototype._updateDataAttributes = function(element) {
  8367. if (this.options.dataAttributes && this.options.dataAttributes.length > 0) {
  8368. var attributes = [];
  8369. if (Array.isArray(this.options.dataAttributes)) {
  8370. attributes = this.options.dataAttributes;
  8371. }
  8372. else if (this.options.dataAttributes == 'all') {
  8373. attributes = Object.keys(this.data);
  8374. }
  8375. else {
  8376. return;
  8377. }
  8378. for (var i = 0; i < attributes.length; i++) {
  8379. var name = attributes[i];
  8380. var value = this.data[name];
  8381. if (value != null) {
  8382. element.setAttribute('data-' + name, value);
  8383. }
  8384. else {
  8385. element.removeAttribute('data-' + name);
  8386. }
  8387. }
  8388. }
  8389. };
  8390. /**
  8391. * Update custom styles of the element
  8392. * @param element
  8393. * @private
  8394. */
  8395. Item.prototype._updateStyle = function(element) {
  8396. // remove old styles
  8397. if (this.style) {
  8398. util.removeCssText(element, this.style);
  8399. this.style = null;
  8400. }
  8401. // append new styles
  8402. if (this.data.style) {
  8403. util.addCssText(element, this.data.style);
  8404. this.style = this.data.style;
  8405. }
  8406. };
  8407. module.exports = Item;
  8408. /***/ },
  8409. /* 21 */
  8410. /***/ function(module, exports, __webpack_require__) {
  8411. var Hammer = __webpack_require__(45);
  8412. var Item = __webpack_require__(20);
  8413. var BackgroundGroup = __webpack_require__(31);
  8414. var RangeItem = __webpack_require__(24);
  8415. /**
  8416. * @constructor BackgroundItem
  8417. * @extends Item
  8418. * @param {Object} data Object containing parameters start, end
  8419. * content, className.
  8420. * @param {{toScreen: function, toTime: function}} conversion
  8421. * Conversion functions from time to screen and vice versa
  8422. * @param {Object} [options] Configuration options
  8423. * // TODO: describe options
  8424. */
  8425. // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation
  8426. function BackgroundItem (data, conversion, options) {
  8427. this.props = {
  8428. content: {
  8429. width: 0
  8430. }
  8431. };
  8432. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  8433. // validate data
  8434. if (data) {
  8435. if (data.start == undefined) {
  8436. throw new Error('Property "start" missing in item ' + data.id);
  8437. }
  8438. if (data.end == undefined) {
  8439. throw new Error('Property "end" missing in item ' + data.id);
  8440. }
  8441. }
  8442. Item.call(this, data, conversion, options);
  8443. this.emptyContent = false;
  8444. }
  8445. BackgroundItem.prototype = new Item (null, null, null);
  8446. BackgroundItem.prototype.baseClassName = 'item background';
  8447. BackgroundItem.prototype.stack = false;
  8448. /**
  8449. * Check whether this item is visible inside given range
  8450. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  8451. * @returns {boolean} True if visible
  8452. */
  8453. BackgroundItem.prototype.isVisible = function(range) {
  8454. // determine visibility
  8455. return (this.data.start < range.end) && (this.data.end > range.start);
  8456. };
  8457. /**
  8458. * Repaint the item
  8459. */
  8460. BackgroundItem.prototype.redraw = function() {
  8461. var dom = this.dom;
  8462. if (!dom) {
  8463. // create DOM
  8464. this.dom = {};
  8465. dom = this.dom;
  8466. // background box
  8467. dom.box = document.createElement('div');
  8468. // className is updated in redraw()
  8469. // contents box
  8470. dom.content = document.createElement('div');
  8471. dom.content.className = 'content';
  8472. dom.box.appendChild(dom.content);
  8473. // Note: we do NOT attach this item as attribute to the DOM,
  8474. // such that background items cannot be selected
  8475. //dom.box['timeline-item'] = this;
  8476. this.dirty = true;
  8477. }
  8478. // append DOM to parent DOM
  8479. if (!this.parent) {
  8480. throw new Error('Cannot redraw item: no parent attached');
  8481. }
  8482. if (!dom.box.parentNode) {
  8483. var background = this.parent.dom.background;
  8484. if (!background) {
  8485. throw new Error('Cannot redraw item: parent has no background container element');
  8486. }
  8487. background.appendChild(dom.box);
  8488. }
  8489. this.displayed = true;
  8490. // Update DOM when item is marked dirty. An item is marked dirty when:
  8491. // - the item is not yet rendered
  8492. // - the item's data is changed
  8493. // - the item is selected/deselected
  8494. if (this.dirty) {
  8495. this._updateContents(this.dom.content);
  8496. this._updateTitle(this.dom.content);
  8497. this._updateDataAttributes(this.dom.content);
  8498. this._updateStyle(this.dom.box);
  8499. // update class
  8500. var className = (this.data.className ? (' ' + this.data.className) : '') +
  8501. (this.selected ? ' selected' : '');
  8502. dom.box.className = this.baseClassName + className;
  8503. // determine from css whether this box has overflow
  8504. this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden';
  8505. // recalculate size
  8506. this.props.content.width = this.dom.content.offsetWidth;
  8507. this.height = 0; // set height zero, so this item will be ignored when stacking items
  8508. this.dirty = false;
  8509. }
  8510. };
  8511. /**
  8512. * Show the item in the DOM (when not already visible). The items DOM will
  8513. * be created when needed.
  8514. */
  8515. BackgroundItem.prototype.show = RangeItem.prototype.show;
  8516. /**
  8517. * Hide the item from the DOM (when visible)
  8518. * @return {Boolean} changed
  8519. */
  8520. BackgroundItem.prototype.hide = RangeItem.prototype.hide;
  8521. /**
  8522. * Reposition the item horizontally
  8523. * @Override
  8524. */
  8525. BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX;
  8526. /**
  8527. * Reposition the item vertically
  8528. * @Override
  8529. */
  8530. BackgroundItem.prototype.repositionY = function(margin) {
  8531. var onTop = this.options.orientation === 'top';
  8532. this.dom.content.style.top = onTop ? '' : '0';
  8533. this.dom.content.style.bottom = onTop ? '0' : '';
  8534. var height;
  8535. // special positioning for subgroups
  8536. if (this.data.subgroup !== undefined) {
  8537. // TODO: instead of calculating the top position of the subgroups here for every BackgroundItem, calculate the top of the subgroup once in Itemset
  8538. var itemSubgroup = this.data.subgroup;
  8539. var subgroups = this.parent.subgroups;
  8540. var subgroupIndex = subgroups[itemSubgroup].index;
  8541. // if the orientation is top, we need to take the difference in height into account.
  8542. if (onTop == true) {
  8543. // the first subgroup will have to account for the distance from the top to the first item.
  8544. height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical;
  8545. height += subgroupIndex == 0 ? margin.axis - 0.5*margin.item.vertical : 0;
  8546. var newTop = this.parent.top;
  8547. for (var subgroup in subgroups) {
  8548. if (subgroups.hasOwnProperty(subgroup)) {
  8549. if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroupIndex) {
  8550. newTop += subgroups[subgroup].height + margin.item.vertical;
  8551. }
  8552. }
  8553. }
  8554. // the others will have to be offset downwards with this same distance.
  8555. newTop += subgroupIndex != 0 ? margin.axis - 0.5 * margin.item.vertical : 0;
  8556. this.dom.box.style.top = newTop + 'px';
  8557. this.dom.box.style.bottom = '';
  8558. }
  8559. // and when the orientation is bottom:
  8560. else {
  8561. var newTop = this.parent.top;
  8562. var totalHeight = 0;
  8563. for (var subgroup in subgroups) {
  8564. if (subgroups.hasOwnProperty(subgroup)) {
  8565. if (subgroups[subgroup].visible == true) {
  8566. var newHeight = subgroups[subgroup].height + margin.item.vertical;
  8567. totalHeight += newHeight;
  8568. if (subgroups[subgroup].index > subgroupIndex) {
  8569. newTop += newHeight;
  8570. }
  8571. }
  8572. }
  8573. }
  8574. height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical;
  8575. this.dom.box.style.top = (this.parent.height - totalHeight + newTop) + 'px';
  8576. this.dom.box.style.bottom = '';
  8577. }
  8578. }
  8579. // and in the case of no subgroups:
  8580. else {
  8581. // we want backgrounds with groups to only show in groups.
  8582. if (this.parent instanceof BackgroundGroup) {
  8583. // if the item is not in a group:
  8584. height = Math.max(this.parent.height,
  8585. this.parent.itemSet.body.domProps.center.height,
  8586. this.parent.itemSet.body.domProps.centerContainer.height);
  8587. this.dom.box.style.top = onTop ? '0' : '';
  8588. this.dom.box.style.bottom = onTop ? '' : '0';
  8589. }
  8590. else {
  8591. height = this.parent.height;
  8592. // same alignment for items when orientation is top or bottom
  8593. this.dom.box.style.top = this.parent.top + 'px';
  8594. this.dom.box.style.bottom = '';
  8595. }
  8596. }
  8597. this.dom.box.style.height = height + 'px';
  8598. };
  8599. module.exports = BackgroundItem;
  8600. /***/ },
  8601. /* 22 */
  8602. /***/ function(module, exports, __webpack_require__) {
  8603. var Item = __webpack_require__(20);
  8604. var util = __webpack_require__(1);
  8605. /**
  8606. * @constructor BoxItem
  8607. * @extends Item
  8608. * @param {Object} data Object containing parameters start
  8609. * content, className.
  8610. * @param {{toScreen: function, toTime: function}} conversion
  8611. * Conversion functions from time to screen and vice versa
  8612. * @param {Object} [options] Configuration options
  8613. * // TODO: describe available options
  8614. */
  8615. function BoxItem (data, conversion, options) {
  8616. this.props = {
  8617. dot: {
  8618. width: 0,
  8619. height: 0
  8620. },
  8621. line: {
  8622. width: 0,
  8623. height: 0
  8624. }
  8625. };
  8626. // validate data
  8627. if (data) {
  8628. if (data.start == undefined) {
  8629. throw new Error('Property "start" missing in item ' + data);
  8630. }
  8631. }
  8632. Item.call(this, data, conversion, options);
  8633. }
  8634. BoxItem.prototype = new Item (null, null, null);
  8635. /**
  8636. * Check whether this item is visible inside given range
  8637. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  8638. * @returns {boolean} True if visible
  8639. */
  8640. BoxItem.prototype.isVisible = function(range) {
  8641. // determine visibility
  8642. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  8643. var interval = (range.end - range.start) / 4;
  8644. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  8645. };
  8646. /**
  8647. * Repaint the item
  8648. */
  8649. BoxItem.prototype.redraw = function() {
  8650. var dom = this.dom;
  8651. if (!dom) {
  8652. // create DOM
  8653. this.dom = {};
  8654. dom = this.dom;
  8655. // create main box
  8656. dom.box = document.createElement('DIV');
  8657. // contents box (inside the background box). used for making margins
  8658. dom.content = document.createElement('DIV');
  8659. dom.content.className = 'content';
  8660. dom.box.appendChild(dom.content);
  8661. // line to axis
  8662. dom.line = document.createElement('DIV');
  8663. dom.line.className = 'line';
  8664. // dot on axis
  8665. dom.dot = document.createElement('DIV');
  8666. dom.dot.className = 'dot';
  8667. // attach this item as attribute
  8668. dom.box['timeline-item'] = this;
  8669. this.dirty = true;
  8670. }
  8671. // append DOM to parent DOM
  8672. if (!this.parent) {
  8673. throw new Error('Cannot redraw item: no parent attached');
  8674. }
  8675. if (!dom.box.parentNode) {
  8676. var foreground = this.parent.dom.foreground;
  8677. if (!foreground) throw new Error('Cannot redraw item: parent has no foreground container element');
  8678. foreground.appendChild(dom.box);
  8679. }
  8680. if (!dom.line.parentNode) {
  8681. var background = this.parent.dom.background;
  8682. if (!background) throw new Error('Cannot redraw item: parent has no background container element');
  8683. background.appendChild(dom.line);
  8684. }
  8685. if (!dom.dot.parentNode) {
  8686. var axis = this.parent.dom.axis;
  8687. if (!background) throw new Error('Cannot redraw item: parent has no axis container element');
  8688. axis.appendChild(dom.dot);
  8689. }
  8690. this.displayed = true;
  8691. // Update DOM when item is marked dirty. An item is marked dirty when:
  8692. // - the item is not yet rendered
  8693. // - the item's data is changed
  8694. // - the item is selected/deselected
  8695. if (this.dirty) {
  8696. this._updateContents(this.dom.content);
  8697. this._updateTitle(this.dom.box);
  8698. this._updateDataAttributes(this.dom.box);
  8699. this._updateStyle(this.dom.box);
  8700. // update class
  8701. var className = (this.data.className? ' ' + this.data.className : '') +
  8702. (this.selected ? ' selected' : '');
  8703. dom.box.className = 'item box' + className;
  8704. dom.line.className = 'item line' + className;
  8705. dom.dot.className = 'item dot' + className;
  8706. // recalculate size
  8707. this.props.dot.height = dom.dot.offsetHeight;
  8708. this.props.dot.width = dom.dot.offsetWidth;
  8709. this.props.line.width = dom.line.offsetWidth;
  8710. this.width = dom.box.offsetWidth;
  8711. this.height = dom.box.offsetHeight;
  8712. this.dirty = false;
  8713. }
  8714. this._repaintDeleteButton(dom.box);
  8715. };
  8716. /**
  8717. * Show the item in the DOM (when not already displayed). The items DOM will
  8718. * be created when needed.
  8719. */
  8720. BoxItem.prototype.show = function() {
  8721. if (!this.displayed) {
  8722. this.redraw();
  8723. }
  8724. };
  8725. /**
  8726. * Hide the item from the DOM (when visible)
  8727. */
  8728. BoxItem.prototype.hide = function() {
  8729. if (this.displayed) {
  8730. var dom = this.dom;
  8731. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  8732. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  8733. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  8734. this.displayed = false;
  8735. }
  8736. };
  8737. /**
  8738. * Reposition the item horizontally
  8739. * @Override
  8740. */
  8741. BoxItem.prototype.repositionX = function() {
  8742. var start = this.conversion.toScreen(this.data.start);
  8743. var align = this.options.align;
  8744. var left;
  8745. // calculate left position of the box
  8746. if (align == 'right') {
  8747. this.left = start - this.width;
  8748. }
  8749. else if (align == 'left') {
  8750. this.left = start;
  8751. }
  8752. else {
  8753. // default or 'center'
  8754. this.left = start - this.width / 2;
  8755. }
  8756. // reposition box
  8757. this.dom.box.style.left = this.left + 'px';
  8758. // reposition line
  8759. this.dom.line.style.left = (start - this.props.line.width / 2) + 'px';
  8760. // reposition dot
  8761. this.dom.dot.style.left = (start - this.props.dot.width / 2) + 'px';
  8762. };
  8763. /**
  8764. * Reposition the item vertically
  8765. * @Override
  8766. */
  8767. BoxItem.prototype.repositionY = function() {
  8768. var orientation = this.options.orientation;
  8769. var box = this.dom.box;
  8770. var line = this.dom.line;
  8771. var dot = this.dom.dot;
  8772. if (orientation == 'top') {
  8773. box.style.top = (this.top || 0) + 'px';
  8774. line.style.top = '0';
  8775. line.style.height = (this.parent.top + this.top + 1) + 'px';
  8776. line.style.bottom = '';
  8777. }
  8778. else { // orientation 'bottom'
  8779. var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty
  8780. var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top;
  8781. box.style.top = (this.parent.height - this.top - this.height || 0) + 'px';
  8782. line.style.top = (itemSetHeight - lineHeight) + 'px';
  8783. line.style.bottom = '0';
  8784. }
  8785. dot.style.top = (-this.props.dot.height / 2) + 'px';
  8786. };
  8787. module.exports = BoxItem;
  8788. /***/ },
  8789. /* 23 */
  8790. /***/ function(module, exports, __webpack_require__) {
  8791. var Item = __webpack_require__(20);
  8792. /**
  8793. * @constructor PointItem
  8794. * @extends Item
  8795. * @param {Object} data Object containing parameters start
  8796. * content, className.
  8797. * @param {{toScreen: function, toTime: function}} conversion
  8798. * Conversion functions from time to screen and vice versa
  8799. * @param {Object} [options] Configuration options
  8800. * // TODO: describe available options
  8801. */
  8802. function PointItem (data, conversion, options) {
  8803. this.props = {
  8804. dot: {
  8805. top: 0,
  8806. width: 0,
  8807. height: 0
  8808. },
  8809. content: {
  8810. height: 0,
  8811. marginLeft: 0
  8812. }
  8813. };
  8814. // validate data
  8815. if (data) {
  8816. if (data.start == undefined) {
  8817. throw new Error('Property "start" missing in item ' + data);
  8818. }
  8819. }
  8820. Item.call(this, data, conversion, options);
  8821. }
  8822. PointItem.prototype = new Item (null, null, null);
  8823. /**
  8824. * Check whether this item is visible inside given range
  8825. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  8826. * @returns {boolean} True if visible
  8827. */
  8828. PointItem.prototype.isVisible = function(range) {
  8829. // determine visibility
  8830. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  8831. var interval = (range.end - range.start) / 4;
  8832. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  8833. };
  8834. /**
  8835. * Repaint the item
  8836. */
  8837. PointItem.prototype.redraw = function() {
  8838. var dom = this.dom;
  8839. if (!dom) {
  8840. // create DOM
  8841. this.dom = {};
  8842. dom = this.dom;
  8843. // background box
  8844. dom.point = document.createElement('div');
  8845. // className is updated in redraw()
  8846. // contents box, right from the dot
  8847. dom.content = document.createElement('div');
  8848. dom.content.className = 'content';
  8849. dom.point.appendChild(dom.content);
  8850. // dot at start
  8851. dom.dot = document.createElement('div');
  8852. dom.point.appendChild(dom.dot);
  8853. // attach this item as attribute
  8854. dom.point['timeline-item'] = this;
  8855. this.dirty = true;
  8856. }
  8857. // append DOM to parent DOM
  8858. if (!this.parent) {
  8859. throw new Error('Cannot redraw item: no parent attached');
  8860. }
  8861. if (!dom.point.parentNode) {
  8862. var foreground = this.parent.dom.foreground;
  8863. if (!foreground) {
  8864. throw new Error('Cannot redraw item: parent has no foreground container element');
  8865. }
  8866. foreground.appendChild(dom.point);
  8867. }
  8868. this.displayed = true;
  8869. // Update DOM when item is marked dirty. An item is marked dirty when:
  8870. // - the item is not yet rendered
  8871. // - the item's data is changed
  8872. // - the item is selected/deselected
  8873. if (this.dirty) {
  8874. this._updateContents(this.dom.content);
  8875. this._updateTitle(this.dom.point);
  8876. this._updateDataAttributes(this.dom.point);
  8877. this._updateStyle(this.dom.point);
  8878. // update class
  8879. var className = (this.data.className? ' ' + this.data.className : '') +
  8880. (this.selected ? ' selected' : '');
  8881. dom.point.className = 'item point' + className;
  8882. dom.dot.className = 'item dot' + className;
  8883. // recalculate size
  8884. this.width = dom.point.offsetWidth;
  8885. this.height = dom.point.offsetHeight;
  8886. this.props.dot.width = dom.dot.offsetWidth;
  8887. this.props.dot.height = dom.dot.offsetHeight;
  8888. this.props.content.height = dom.content.offsetHeight;
  8889. // resize contents
  8890. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  8891. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  8892. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  8893. dom.dot.style.left = (this.props.dot.width / 2) + 'px';
  8894. this.dirty = false;
  8895. }
  8896. this._repaintDeleteButton(dom.point);
  8897. };
  8898. /**
  8899. * Show the item in the DOM (when not already visible). The items DOM will
  8900. * be created when needed.
  8901. */
  8902. PointItem.prototype.show = function() {
  8903. if (!this.displayed) {
  8904. this.redraw();
  8905. }
  8906. };
  8907. /**
  8908. * Hide the item from the DOM (when visible)
  8909. */
  8910. PointItem.prototype.hide = function() {
  8911. if (this.displayed) {
  8912. if (this.dom.point.parentNode) {
  8913. this.dom.point.parentNode.removeChild(this.dom.point);
  8914. }
  8915. this.displayed = false;
  8916. }
  8917. };
  8918. /**
  8919. * Reposition the item horizontally
  8920. * @Override
  8921. */
  8922. PointItem.prototype.repositionX = function() {
  8923. var start = this.conversion.toScreen(this.data.start);
  8924. this.left = start - this.props.dot.width;
  8925. // reposition point
  8926. this.dom.point.style.left = this.left + 'px';
  8927. };
  8928. /**
  8929. * Reposition the item vertically
  8930. * @Override
  8931. */
  8932. PointItem.prototype.repositionY = function() {
  8933. var orientation = this.options.orientation,
  8934. point = this.dom.point;
  8935. if (orientation == 'top') {
  8936. point.style.top = this.top + 'px';
  8937. }
  8938. else {
  8939. point.style.top = (this.parent.height - this.top - this.height) + 'px';
  8940. }
  8941. };
  8942. module.exports = PointItem;
  8943. /***/ },
  8944. /* 24 */
  8945. /***/ function(module, exports, __webpack_require__) {
  8946. var Hammer = __webpack_require__(45);
  8947. var Item = __webpack_require__(20);
  8948. /**
  8949. * @constructor RangeItem
  8950. * @extends Item
  8951. * @param {Object} data Object containing parameters start, end
  8952. * content, className.
  8953. * @param {{toScreen: function, toTime: function}} conversion
  8954. * Conversion functions from time to screen and vice versa
  8955. * @param {Object} [options] Configuration options
  8956. * // TODO: describe options
  8957. */
  8958. function RangeItem (data, conversion, options) {
  8959. this.props = {
  8960. content: {
  8961. width: 0
  8962. }
  8963. };
  8964. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  8965. // validate data
  8966. if (data) {
  8967. if (data.start == undefined) {
  8968. throw new Error('Property "start" missing in item ' + data.id);
  8969. }
  8970. if (data.end == undefined) {
  8971. throw new Error('Property "end" missing in item ' + data.id);
  8972. }
  8973. }
  8974. Item.call(this, data, conversion, options);
  8975. }
  8976. RangeItem.prototype = new Item (null, null, null);
  8977. RangeItem.prototype.baseClassName = 'item range';
  8978. /**
  8979. * Check whether this item is visible inside given range
  8980. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  8981. * @returns {boolean} True if visible
  8982. */
  8983. RangeItem.prototype.isVisible = function(range) {
  8984. // determine visibility
  8985. return (this.data.start < range.end) && (this.data.end > range.start);
  8986. };
  8987. /**
  8988. * Repaint the item
  8989. */
  8990. RangeItem.prototype.redraw = function() {
  8991. var dom = this.dom;
  8992. if (!dom) {
  8993. // create DOM
  8994. this.dom = {};
  8995. dom = this.dom;
  8996. // background box
  8997. dom.box = document.createElement('div');
  8998. // className is updated in redraw()
  8999. // contents box
  9000. dom.content = document.createElement('div');
  9001. dom.content.className = 'content';
  9002. dom.box.appendChild(dom.content);
  9003. // attach this item as attribute
  9004. dom.box['timeline-item'] = this;
  9005. this.dirty = true;
  9006. }
  9007. // append DOM to parent DOM
  9008. if (!this.parent) {
  9009. throw new Error('Cannot redraw item: no parent attached');
  9010. }
  9011. if (!dom.box.parentNode) {
  9012. var foreground = this.parent.dom.foreground;
  9013. if (!foreground) {
  9014. throw new Error('Cannot redraw item: parent has no foreground container element');
  9015. }
  9016. foreground.appendChild(dom.box);
  9017. }
  9018. this.displayed = true;
  9019. // Update DOM when item is marked dirty. An item is marked dirty when:
  9020. // - the item is not yet rendered
  9021. // - the item's data is changed
  9022. // - the item is selected/deselected
  9023. if (this.dirty) {
  9024. this._updateContents(this.dom.content);
  9025. this._updateTitle(this.dom.box);
  9026. this._updateDataAttributes(this.dom.box);
  9027. this._updateStyle(this.dom.box);
  9028. // update class
  9029. var className = (this.data.className ? (' ' + this.data.className) : '') +
  9030. (this.selected ? ' selected' : '');
  9031. dom.box.className = this.baseClassName + className;
  9032. // determine from css whether this box has overflow
  9033. this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden';
  9034. // recalculate size
  9035. // turn off max-width to be able to calculate the real width
  9036. // this causes an extra browser repaint/reflow, but so be it
  9037. this.dom.content.style.maxWidth = 'none';
  9038. this.props.content.width = this.dom.content.offsetWidth;
  9039. this.height = this.dom.box.offsetHeight;
  9040. this.dom.content.style.maxWidth = '';
  9041. this.dirty = false;
  9042. }
  9043. this._repaintDeleteButton(dom.box);
  9044. this._repaintDragLeft();
  9045. this._repaintDragRight();
  9046. };
  9047. /**
  9048. * Show the item in the DOM (when not already visible). The items DOM will
  9049. * be created when needed.
  9050. */
  9051. RangeItem.prototype.show = function() {
  9052. if (!this.displayed) {
  9053. this.redraw();
  9054. }
  9055. };
  9056. /**
  9057. * Hide the item from the DOM (when visible)
  9058. * @return {Boolean} changed
  9059. */
  9060. RangeItem.prototype.hide = function() {
  9061. if (this.displayed) {
  9062. var box = this.dom.box;
  9063. if (box.parentNode) {
  9064. box.parentNode.removeChild(box);
  9065. }
  9066. this.displayed = false;
  9067. }
  9068. };
  9069. /**
  9070. * Reposition the item horizontally
  9071. * @param {boolean} [limitSize=true] If true (default), the width of the range
  9072. * item will be limited, as the browser cannot
  9073. * display very wide divs. This means though
  9074. * that the applied left and width may
  9075. * not correspond to the ranges start and end
  9076. * @Override
  9077. */
  9078. RangeItem.prototype.repositionX = function(limitSize) {
  9079. var parentWidth = this.parent.width;
  9080. var start = this.conversion.toScreen(this.data.start);
  9081. var end = this.conversion.toScreen(this.data.end);
  9082. var contentLeft;
  9083. var contentWidth;
  9084. // limit the width of the range, as browsers cannot draw very wide divs
  9085. if (limitSize === undefined || limitSize === true) {
  9086. if (start < -parentWidth) {
  9087. start = -parentWidth;
  9088. }
  9089. if (end > 2 * parentWidth) {
  9090. end = 2 * parentWidth;
  9091. }
  9092. }
  9093. var boxWidth = Math.max(end - start, 1);
  9094. if (this.overflow) {
  9095. this.left = start;
  9096. this.width = boxWidth + this.props.content.width;
  9097. contentWidth = this.props.content.width;
  9098. // Note: The calculation of width is an optimistic calculation, giving
  9099. // a width which will not change when moving the Timeline
  9100. // So no re-stacking needed, which is nicer for the eye;
  9101. }
  9102. else {
  9103. this.left = start;
  9104. this.width = boxWidth;
  9105. contentWidth = Math.min(end - start - 2 * this.options.padding, this.props.content.width);
  9106. }
  9107. this.dom.box.style.left = this.left + 'px';
  9108. this.dom.box.style.width = boxWidth + 'px';
  9109. switch (this.options.align) {
  9110. case 'left':
  9111. this.dom.content.style.left = '0';
  9112. break;
  9113. case 'right':
  9114. this.dom.content.style.left = Math.max((boxWidth - contentWidth - 2 * this.options.padding), 0) + 'px';
  9115. break;
  9116. case 'center':
  9117. this.dom.content.style.left = Math.max((boxWidth - contentWidth - 2 * this.options.padding) / 2, 0) + 'px';
  9118. break;
  9119. default: // 'auto'
  9120. // when range exceeds left of the window, position the contents at the left of the visible area
  9121. if (this.overflow) {
  9122. if (end > 0) {
  9123. contentLeft = Math.max(-start, 0);
  9124. }
  9125. else {
  9126. contentLeft = -contentWidth; // ensure it's not visible anymore
  9127. }
  9128. }
  9129. else {
  9130. if (start < 0) {
  9131. contentLeft = Math.min(-start,
  9132. (end - start - contentWidth - 2 * this.options.padding));
  9133. // TODO: remove the need for options.padding. it's terrible.
  9134. }
  9135. else {
  9136. contentLeft = 0;
  9137. }
  9138. }
  9139. this.dom.content.style.left = contentLeft + 'px';
  9140. }
  9141. };
  9142. /**
  9143. * Reposition the item vertically
  9144. * @Override
  9145. */
  9146. RangeItem.prototype.repositionY = function() {
  9147. var orientation = this.options.orientation,
  9148. box = this.dom.box;
  9149. if (orientation == 'top') {
  9150. box.style.top = this.top + 'px';
  9151. }
  9152. else {
  9153. box.style.top = (this.parent.height - this.top - this.height) + 'px';
  9154. }
  9155. };
  9156. /**
  9157. * Repaint a drag area on the left side of the range when the range is selected
  9158. * @protected
  9159. */
  9160. RangeItem.prototype._repaintDragLeft = function () {
  9161. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  9162. // create and show drag area
  9163. var dragLeft = document.createElement('div');
  9164. dragLeft.className = 'drag-left';
  9165. dragLeft.dragLeftItem = this;
  9166. // TODO: this should be redundant?
  9167. Hammer(dragLeft, {
  9168. preventDefault: true
  9169. }).on('drag', function () {
  9170. //console.log('drag left')
  9171. });
  9172. this.dom.box.appendChild(dragLeft);
  9173. this.dom.dragLeft = dragLeft;
  9174. }
  9175. else if (!this.selected && this.dom.dragLeft) {
  9176. // delete drag area
  9177. if (this.dom.dragLeft.parentNode) {
  9178. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  9179. }
  9180. this.dom.dragLeft = null;
  9181. }
  9182. };
  9183. /**
  9184. * Repaint a drag area on the right side of the range when the range is selected
  9185. * @protected
  9186. */
  9187. RangeItem.prototype._repaintDragRight = function () {
  9188. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  9189. // create and show drag area
  9190. var dragRight = document.createElement('div');
  9191. dragRight.className = 'drag-right';
  9192. dragRight.dragRightItem = this;
  9193. // TODO: this should be redundant?
  9194. Hammer(dragRight, {
  9195. preventDefault: true
  9196. }).on('drag', function () {
  9197. //console.log('drag right')
  9198. });
  9199. this.dom.box.appendChild(dragRight);
  9200. this.dom.dragRight = dragRight;
  9201. }
  9202. else if (!this.selected && this.dom.dragRight) {
  9203. // delete drag area
  9204. if (this.dom.dragRight.parentNode) {
  9205. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  9206. }
  9207. this.dom.dragRight = null;
  9208. }
  9209. };
  9210. module.exports = RangeItem;
  9211. /***/ },
  9212. /* 25 */
  9213. /***/ function(module, exports, __webpack_require__) {
  9214. /**
  9215. * Prototype for visual components
  9216. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body]
  9217. * @param {Object} [options]
  9218. */
  9219. function Component (body, options) {
  9220. this.options = null;
  9221. this.props = null;
  9222. }
  9223. /**
  9224. * Set options for the component. The new options will be merged into the
  9225. * current options.
  9226. * @param {Object} options
  9227. */
  9228. Component.prototype.setOptions = function(options) {
  9229. if (options) {
  9230. util.extend(this.options, options);
  9231. }
  9232. };
  9233. /**
  9234. * Repaint the component
  9235. * @return {boolean} Returns true if the component is resized
  9236. */
  9237. Component.prototype.redraw = function() {
  9238. // should be implemented by the component
  9239. return false;
  9240. };
  9241. /**
  9242. * Destroy the component. Cleanup DOM and event listeners
  9243. */
  9244. Component.prototype.destroy = function() {
  9245. // should be implemented by the component
  9246. };
  9247. /**
  9248. * Test whether the component is resized since the last time _isResized() was
  9249. * called.
  9250. * @return {Boolean} Returns true if the component is resized
  9251. * @protected
  9252. */
  9253. Component.prototype._isResized = function() {
  9254. var resized = (this.props._previousWidth !== this.props.width ||
  9255. this.props._previousHeight !== this.props.height);
  9256. this.props._previousWidth = this.props.width;
  9257. this.props._previousHeight = this.props.height;
  9258. return resized;
  9259. };
  9260. module.exports = Component;
  9261. /***/ },
  9262. /* 26 */
  9263. /***/ function(module, exports, __webpack_require__) {
  9264. var util = __webpack_require__(1);
  9265. var Component = __webpack_require__(25);
  9266. var moment = __webpack_require__(44);
  9267. var locales = __webpack_require__(48);
  9268. /**
  9269. * A current time bar
  9270. * @param {{range: Range, dom: Object, domProps: Object}} body
  9271. * @param {Object} [options] Available parameters:
  9272. * {Boolean} [showCurrentTime]
  9273. * @constructor CurrentTime
  9274. * @extends Component
  9275. */
  9276. function CurrentTime (body, options) {
  9277. this.body = body;
  9278. // default options
  9279. this.defaultOptions = {
  9280. showCurrentTime: true,
  9281. locales: locales,
  9282. locale: 'en'
  9283. };
  9284. this.options = util.extend({}, this.defaultOptions);
  9285. this.offset = 0;
  9286. this._create();
  9287. this.setOptions(options);
  9288. }
  9289. CurrentTime.prototype = new Component();
  9290. /**
  9291. * Create the HTML DOM for the current time bar
  9292. * @private
  9293. */
  9294. CurrentTime.prototype._create = function() {
  9295. var bar = document.createElement('div');
  9296. bar.className = 'currenttime';
  9297. bar.style.position = 'absolute';
  9298. bar.style.top = '0px';
  9299. bar.style.height = '100%';
  9300. this.bar = bar;
  9301. };
  9302. /**
  9303. * Destroy the CurrentTime bar
  9304. */
  9305. CurrentTime.prototype.destroy = function () {
  9306. this.options.showCurrentTime = false;
  9307. this.redraw(); // will remove the bar from the DOM and stop refreshing
  9308. this.body = null;
  9309. };
  9310. /**
  9311. * Set options for the component. Options will be merged in current options.
  9312. * @param {Object} options Available parameters:
  9313. * {boolean} [showCurrentTime]
  9314. */
  9315. CurrentTime.prototype.setOptions = function(options) {
  9316. if (options) {
  9317. // copy all options that we know
  9318. util.selectiveExtend(['showCurrentTime', 'locale', 'locales'], this.options, options);
  9319. }
  9320. };
  9321. /**
  9322. * Repaint the component
  9323. * @return {boolean} Returns true if the component is resized
  9324. */
  9325. CurrentTime.prototype.redraw = function() {
  9326. if (this.options.showCurrentTime) {
  9327. var parent = this.body.dom.backgroundVertical;
  9328. if (this.bar.parentNode != parent) {
  9329. // attach to the dom
  9330. if (this.bar.parentNode) {
  9331. this.bar.parentNode.removeChild(this.bar);
  9332. }
  9333. parent.appendChild(this.bar);
  9334. this.start();
  9335. }
  9336. var now = new Date(new Date().valueOf() + this.offset);
  9337. var x = this.body.util.toScreen(now);
  9338. var locale = this.options.locales[this.options.locale];
  9339. var title = locale.current + ' ' + locale.time + ': ' + moment(now).format('dddd, MMMM Do YYYY, H:mm:ss');
  9340. title = title.charAt(0).toUpperCase() + title.substring(1);
  9341. this.bar.style.left = x + 'px';
  9342. this.bar.title = title;
  9343. }
  9344. else {
  9345. // remove the line from the DOM
  9346. if (this.bar.parentNode) {
  9347. this.bar.parentNode.removeChild(this.bar);
  9348. }
  9349. this.stop();
  9350. }
  9351. return false;
  9352. };
  9353. /**
  9354. * Start auto refreshing the current time bar
  9355. */
  9356. CurrentTime.prototype.start = function() {
  9357. var me = this;
  9358. function update () {
  9359. me.stop();
  9360. // determine interval to refresh
  9361. var scale = me.body.range.conversion(me.body.domProps.center.width).scale;
  9362. var interval = 1 / scale / 10;
  9363. if (interval < 30) interval = 30;
  9364. if (interval > 1000) interval = 1000;
  9365. me.redraw();
  9366. // start a timer to adjust for the new time
  9367. me.currentTimeTimer = setTimeout(update, interval);
  9368. }
  9369. update();
  9370. };
  9371. /**
  9372. * Stop auto refreshing the current time bar
  9373. */
  9374. CurrentTime.prototype.stop = function() {
  9375. if (this.currentTimeTimer !== undefined) {
  9376. clearTimeout(this.currentTimeTimer);
  9377. delete this.currentTimeTimer;
  9378. }
  9379. };
  9380. /**
  9381. * Set a current time. This can be used for example to ensure that a client's
  9382. * time is synchronized with a shared server time.
  9383. * @param {Date | String | Number} time A Date, unix timestamp, or
  9384. * ISO date string.
  9385. */
  9386. CurrentTime.prototype.setCurrentTime = function(time) {
  9387. var t = util.convert(time, 'Date').valueOf();
  9388. var now = new Date().valueOf();
  9389. this.offset = t - now;
  9390. this.redraw();
  9391. };
  9392. /**
  9393. * Get the current time.
  9394. * @return {Date} Returns the current time.
  9395. */
  9396. CurrentTime.prototype.getCurrentTime = function() {
  9397. return new Date(new Date().valueOf() + this.offset);
  9398. };
  9399. module.exports = CurrentTime;
  9400. /***/ },
  9401. /* 27 */
  9402. /***/ function(module, exports, __webpack_require__) {
  9403. var Hammer = __webpack_require__(45);
  9404. var util = __webpack_require__(1);
  9405. var Component = __webpack_require__(25);
  9406. var moment = __webpack_require__(44);
  9407. var locales = __webpack_require__(48);
  9408. /**
  9409. * A custom time bar
  9410. * @param {{range: Range, dom: Object}} body
  9411. * @param {Object} [options] Available parameters:
  9412. * {Boolean} [showCustomTime]
  9413. * @constructor CustomTime
  9414. * @extends Component
  9415. */
  9416. function CustomTime (body, options) {
  9417. this.body = body;
  9418. // default options
  9419. this.defaultOptions = {
  9420. showCustomTime: false,
  9421. locales: locales,
  9422. locale: 'en',
  9423. id: 0
  9424. };
  9425. this.options = util.extend({}, this.defaultOptions);
  9426. if (options && options.time) {
  9427. this.customTime = options.time;
  9428. } else {
  9429. this.customTime = new Date();
  9430. }
  9431. this.eventParams = {}; // stores state parameters while dragging the bar
  9432. // create the DOM
  9433. this._create();
  9434. this.setOptions(options);
  9435. }
  9436. CustomTime.prototype = new Component();
  9437. /**
  9438. * Set options for the component. Options will be merged in current options.
  9439. * @param {Object} options Available parameters:
  9440. * {boolean} [showCustomTime]
  9441. */
  9442. CustomTime.prototype.setOptions = function(options) {
  9443. if (options) {
  9444. // copy all options that we know
  9445. util.selectiveExtend(['showCustomTime', 'locale', 'locales', 'id'], this.options, options);
  9446. // Triggered by addCustomTimeBar, redraw to add new bar
  9447. if (this.options.id) {
  9448. this.redraw();
  9449. }
  9450. }
  9451. };
  9452. /**
  9453. * Create the DOM for the custom time
  9454. * @private
  9455. */
  9456. CustomTime.prototype._create = function() {
  9457. var bar = document.createElement('div');
  9458. bar.className = 'customtime';
  9459. bar.style.position = 'absolute';
  9460. bar.style.top = '0px';
  9461. bar.style.height = '100%';
  9462. this.bar = bar;
  9463. var drag = document.createElement('div');
  9464. drag.style.position = 'relative';
  9465. drag.style.top = '0px';
  9466. drag.style.left = '-10px';
  9467. drag.style.height = '100%';
  9468. drag.style.width = '20px';
  9469. bar.appendChild(drag);
  9470. // attach event listeners
  9471. this.hammer = Hammer(bar, {
  9472. prevent_default: true
  9473. });
  9474. this.hammer.on('dragstart', this._onDragStart.bind(this));
  9475. this.hammer.on('drag', this._onDrag.bind(this));
  9476. this.hammer.on('dragend', this._onDragEnd.bind(this));
  9477. };
  9478. /**
  9479. * Destroy the CustomTime bar
  9480. */
  9481. CustomTime.prototype.destroy = function () {
  9482. this.options.showCustomTime = false;
  9483. this.redraw(); // will remove the bar from the DOM
  9484. this.hammer.enable(false);
  9485. this.hammer = null;
  9486. this.body = null;
  9487. };
  9488. /**
  9489. * Repaint the component
  9490. * @return {boolean} Returns true if the component is resized
  9491. */
  9492. CustomTime.prototype.redraw = function () {
  9493. if (this.options.showCustomTime) {
  9494. var parent = this.body.dom.backgroundVertical;
  9495. if (this.bar.parentNode != parent) {
  9496. // attach to the dom
  9497. if (this.bar.parentNode) {
  9498. this.bar.parentNode.removeChild(this.bar);
  9499. }
  9500. parent.appendChild(this.bar);
  9501. }
  9502. var x = this.body.util.toScreen(this.customTime);
  9503. var locale = this.options.locales[this.options.locale];
  9504. var title = locale.time + ': ' + moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss');
  9505. title = title.charAt(0).toUpperCase() + title.substring(1);
  9506. this.bar.style.left = x + 'px';
  9507. this.bar.title = title;
  9508. }
  9509. else {
  9510. // remove the line from the DOM
  9511. if (this.bar.parentNode) {
  9512. this.bar.parentNode.removeChild(this.bar);
  9513. }
  9514. }
  9515. return false;
  9516. };
  9517. /**
  9518. * Set custom time.
  9519. * @param {Date | number | string} time
  9520. */
  9521. CustomTime.prototype.setCustomTime = function(time) {
  9522. this.customTime = util.convert(time, 'Date');
  9523. this.redraw();
  9524. };
  9525. /**
  9526. * Retrieve the current custom time.
  9527. * @return {Date} customTime
  9528. */
  9529. CustomTime.prototype.getCustomTime = function() {
  9530. return new Date(this.customTime.valueOf());
  9531. };
  9532. /**
  9533. * Start moving horizontally
  9534. * @param {Event} event
  9535. * @private
  9536. */
  9537. CustomTime.prototype._onDragStart = function(event) {
  9538. this.eventParams.dragging = true;
  9539. this.eventParams.customTime = this.customTime;
  9540. event.stopPropagation();
  9541. event.preventDefault();
  9542. };
  9543. /**
  9544. * Perform moving operating.
  9545. * @param {Event} event
  9546. * @private
  9547. */
  9548. CustomTime.prototype._onDrag = function (event) {
  9549. if (!this.eventParams.dragging) return;
  9550. var deltaX = event.gesture.deltaX,
  9551. x = this.body.util.toScreen(this.eventParams.customTime) + deltaX,
  9552. time = this.body.util.toTime(x);
  9553. this.setCustomTime(time);
  9554. // fire a timechange event
  9555. this.body.emitter.emit('timechange', {
  9556. id: this.options.id,
  9557. time: new Date(this.customTime.valueOf())
  9558. });
  9559. event.stopPropagation();
  9560. event.preventDefault();
  9561. };
  9562. /**
  9563. * Stop moving operating.
  9564. * @param {event} event
  9565. * @private
  9566. */
  9567. CustomTime.prototype._onDragEnd = function (event) {
  9568. if (!this.eventParams.dragging) return;
  9569. // fire a timechanged event
  9570. this.body.emitter.emit('timechanged', {
  9571. id: this.options.id,
  9572. time: new Date(this.customTime.valueOf())
  9573. });
  9574. event.stopPropagation();
  9575. event.preventDefault();
  9576. };
  9577. module.exports = CustomTime;
  9578. /***/ },
  9579. /* 28 */
  9580. /***/ function(module, exports, __webpack_require__) {
  9581. var util = __webpack_require__(1);
  9582. var DOMutil = __webpack_require__(2);
  9583. var Component = __webpack_require__(25);
  9584. var DataStep = __webpack_require__(16);
  9585. /**
  9586. * A horizontal time axis
  9587. * @param {Object} [options] See DataAxis.setOptions for the available
  9588. * options.
  9589. * @constructor DataAxis
  9590. * @extends Component
  9591. * @param body
  9592. */
  9593. function DataAxis (body, options, svg, linegraphOptions) {
  9594. this.id = util.randomUUID();
  9595. this.body = body;
  9596. this.defaultOptions = {
  9597. orientation: 'left', // supported: 'left', 'right'
  9598. showMinorLabels: true,
  9599. showMajorLabels: true,
  9600. icons: true,
  9601. majorLinesOffset: 7,
  9602. minorLinesOffset: 4,
  9603. labelOffsetX: 10,
  9604. labelOffsetY: 2,
  9605. iconWidth: 20,
  9606. width: '40px',
  9607. visible: true,
  9608. alignZeros: true,
  9609. customRange: {
  9610. left: {min:undefined, max:undefined},
  9611. right: {min:undefined, max:undefined}
  9612. },
  9613. title: {
  9614. left: {text:undefined},
  9615. right: {text:undefined}
  9616. },
  9617. format: {
  9618. left: {decimals: undefined},
  9619. right: {decimals: undefined}
  9620. }
  9621. };
  9622. this.linegraphOptions = linegraphOptions;
  9623. this.linegraphSVG = svg;
  9624. this.props = {};
  9625. this.DOMelements = { // dynamic elements
  9626. lines: {},
  9627. labels: {},
  9628. title: {}
  9629. };
  9630. this.dom = {};
  9631. this.range = {start:0, end:0};
  9632. this.options = util.extend({}, this.defaultOptions);
  9633. this.conversionFactor = 1;
  9634. this.setOptions(options);
  9635. this.width = Number(('' + this.options.width).replace("px",""));
  9636. this.minWidth = this.width;
  9637. this.height = this.linegraphSVG.offsetHeight;
  9638. this.hidden = false;
  9639. this.stepPixels = 25;
  9640. this.stepPixelsForced = 25;
  9641. this.zeroCrossing = -1;
  9642. this.lineOffset = 0;
  9643. this.master = true;
  9644. this.svgElements = {};
  9645. this.iconsRemoved = false;
  9646. this.groups = {};
  9647. this.amountOfGroups = 0;
  9648. // create the HTML DOM
  9649. this._create();
  9650. var me = this;
  9651. this.body.emitter.on("verticalDrag", function() {
  9652. me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px';
  9653. });
  9654. }
  9655. DataAxis.prototype = new Component();
  9656. DataAxis.prototype.addGroup = function(label, graphOptions) {
  9657. if (!this.groups.hasOwnProperty(label)) {
  9658. this.groups[label] = graphOptions;
  9659. }
  9660. this.amountOfGroups += 1;
  9661. };
  9662. DataAxis.prototype.updateGroup = function(label, graphOptions) {
  9663. this.groups[label] = graphOptions;
  9664. };
  9665. DataAxis.prototype.removeGroup = function(label) {
  9666. if (this.groups.hasOwnProperty(label)) {
  9667. delete this.groups[label];
  9668. this.amountOfGroups -= 1;
  9669. }
  9670. };
  9671. DataAxis.prototype.setOptions = function (options) {
  9672. if (options) {
  9673. var redraw = false;
  9674. if (this.options.orientation != options.orientation && options.orientation !== undefined) {
  9675. redraw = true;
  9676. }
  9677. var fields = [
  9678. 'orientation',
  9679. 'showMinorLabels',
  9680. 'showMajorLabels',
  9681. 'icons',
  9682. 'majorLinesOffset',
  9683. 'minorLinesOffset',
  9684. 'labelOffsetX',
  9685. 'labelOffsetY',
  9686. 'iconWidth',
  9687. 'width',
  9688. 'visible',
  9689. 'customRange',
  9690. 'title',
  9691. 'format',
  9692. 'alignZeros'
  9693. ];
  9694. util.selectiveExtend(fields, this.options, options);
  9695. this.minWidth = Number(('' + this.options.width).replace("px",""));
  9696. if (redraw == true && this.dom.frame) {
  9697. this.hide();
  9698. this.show();
  9699. }
  9700. }
  9701. };
  9702. /**
  9703. * Create the HTML DOM for the DataAxis
  9704. */
  9705. DataAxis.prototype._create = function() {
  9706. this.dom.frame = document.createElement('div');
  9707. this.dom.frame.style.width = this.options.width;
  9708. this.dom.frame.style.height = this.height;
  9709. this.dom.lineContainer = document.createElement('div');
  9710. this.dom.lineContainer.style.width = '100%';
  9711. this.dom.lineContainer.style.height = this.height;
  9712. this.dom.lineContainer.style.position = 'relative';
  9713. // create svg element for graph drawing.
  9714. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  9715. this.svg.style.position = "absolute";
  9716. this.svg.style.top = '0px';
  9717. this.svg.style.height = '100%';
  9718. this.svg.style.width = '100%';
  9719. this.svg.style.display = "block";
  9720. this.dom.frame.appendChild(this.svg);
  9721. };
  9722. DataAxis.prototype._redrawGroupIcons = function () {
  9723. DOMutil.prepareElements(this.svgElements);
  9724. var x;
  9725. var iconWidth = this.options.iconWidth;
  9726. var iconHeight = 15;
  9727. var iconOffset = 4;
  9728. var y = iconOffset + 0.5 * iconHeight;
  9729. if (this.options.orientation == 'left') {
  9730. x = iconOffset;
  9731. }
  9732. else {
  9733. x = this.width - iconWidth - iconOffset;
  9734. }
  9735. for (var groupId in this.groups) {
  9736. if (this.groups.hasOwnProperty(groupId)) {
  9737. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  9738. this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight);
  9739. y += iconHeight + iconOffset;
  9740. }
  9741. }
  9742. }
  9743. DOMutil.cleanupElements(this.svgElements);
  9744. this.iconsRemoved = false;
  9745. };
  9746. DataAxis.prototype._cleanupIcons = function() {
  9747. if (this.iconsRemoved == false) {
  9748. DOMutil.prepareElements(this.svgElements);
  9749. DOMutil.cleanupElements(this.svgElements);
  9750. this.iconsRemoved = true;
  9751. }
  9752. }
  9753. /**
  9754. * Create the HTML DOM for the DataAxis
  9755. */
  9756. DataAxis.prototype.show = function() {
  9757. this.hidden = false;
  9758. if (!this.dom.frame.parentNode) {
  9759. if (this.options.orientation == 'left') {
  9760. this.body.dom.left.appendChild(this.dom.frame);
  9761. }
  9762. else {
  9763. this.body.dom.right.appendChild(this.dom.frame);
  9764. }
  9765. }
  9766. if (!this.dom.lineContainer.parentNode) {
  9767. this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer);
  9768. }
  9769. };
  9770. /**
  9771. * Create the HTML DOM for the DataAxis
  9772. */
  9773. DataAxis.prototype.hide = function() {
  9774. this.hidden = true;
  9775. if (this.dom.frame.parentNode) {
  9776. this.dom.frame.parentNode.removeChild(this.dom.frame);
  9777. }
  9778. if (this.dom.lineContainer.parentNode) {
  9779. this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer);
  9780. }
  9781. };
  9782. /**
  9783. * Set a range (start and end)
  9784. * @param end
  9785. * @param start
  9786. * @param end
  9787. */
  9788. DataAxis.prototype.setRange = function (start, end) {
  9789. if (this.master == false && this.options.alignZeros == true && this.zeroCrossing != -1) {
  9790. if (start > 0) {
  9791. start = 0;
  9792. }
  9793. }
  9794. this.range.start = start;
  9795. this.range.end = end;
  9796. };
  9797. /**
  9798. * Repaint the component
  9799. * @return {boolean} Returns true if the component is resized
  9800. */
  9801. DataAxis.prototype.redraw = function () {
  9802. var resized = false;
  9803. var activeGroups = 0;
  9804. // Make sure the line container adheres to the vertical scrolling.
  9805. this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px';
  9806. for (var groupId in this.groups) {
  9807. if (this.groups.hasOwnProperty(groupId)) {
  9808. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  9809. activeGroups++;
  9810. }
  9811. }
  9812. }
  9813. if (this.amountOfGroups == 0 || activeGroups == 0) {
  9814. this.hide();
  9815. }
  9816. else {
  9817. this.show();
  9818. this.height = Number(this.linegraphSVG.style.height.replace("px",""));
  9819. // svg offsetheight did not work in firefox and explorer...
  9820. this.dom.lineContainer.style.height = this.height + 'px';
  9821. this.width = this.options.visible == true ? Number(('' + this.options.width).replace("px","")) : 0;
  9822. var props = this.props;
  9823. var frame = this.dom.frame;
  9824. // update classname
  9825. frame.className = 'dataaxis';
  9826. // calculate character width and height
  9827. this._calculateCharSize();
  9828. var orientation = this.options.orientation;
  9829. var showMinorLabels = this.options.showMinorLabels;
  9830. var showMajorLabels = this.options.showMajorLabels;
  9831. // determine the width and height of the elements for the axis
  9832. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  9833. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  9834. props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset;
  9835. props.minorLineHeight = 1;
  9836. props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset;
  9837. props.majorLineHeight = 1;
  9838. // take frame offline while updating (is almost twice as fast)
  9839. if (orientation == 'left') {
  9840. frame.style.top = '0';
  9841. frame.style.left = '0';
  9842. frame.style.bottom = '';
  9843. frame.style.width = this.width + 'px';
  9844. frame.style.height = this.height + "px";
  9845. this.props.width = this.body.domProps.left.width;
  9846. this.props.height = this.body.domProps.left.height;
  9847. }
  9848. else { // right
  9849. frame.style.top = '';
  9850. frame.style.bottom = '0';
  9851. frame.style.left = '0';
  9852. frame.style.width = this.width + 'px';
  9853. frame.style.height = this.height + "px";
  9854. this.props.width = this.body.domProps.right.width;
  9855. this.props.height = this.body.domProps.right.height;
  9856. }
  9857. resized = this._redrawLabels();
  9858. resized = this._isResized() || resized;
  9859. if (this.options.icons == true) {
  9860. this._redrawGroupIcons();
  9861. }
  9862. else {
  9863. this._cleanupIcons();
  9864. }
  9865. this._redrawTitle(orientation);
  9866. }
  9867. return resized;
  9868. };
  9869. /**
  9870. * Repaint major and minor text labels and vertical grid lines
  9871. * @private
  9872. */
  9873. DataAxis.prototype._redrawLabels = function () {
  9874. var resized = false;
  9875. DOMutil.prepareElements(this.DOMelements.lines);
  9876. DOMutil.prepareElements(this.DOMelements.labels);
  9877. var orientation = this.options['orientation'];
  9878. // calculate range and step (step such that we have space for 7 characters per label)
  9879. var minimumStep = this.master ? this.props.majorCharHeight || 10 : this.stepPixelsForced;
  9880. var step = new DataStep(
  9881. this.range.start,
  9882. this.range.end,
  9883. minimumStep,
  9884. this.dom.frame.offsetHeight,
  9885. this.options.customRange[this.options.orientation],
  9886. this.master == false && this.options.alignZeros // doess the step have to align zeros? only if not master and the options is on
  9887. );
  9888. this.step = step;
  9889. // get the distance in pixels for a step
  9890. // dead space is space that is "left over" after a step
  9891. var stepPixels = (this.dom.frame.offsetHeight - (step.deadSpace * (this.dom.frame.offsetHeight / step.marginRange))) / (((step.marginRange - step.deadSpace) / step.step));
  9892. this.stepPixels = stepPixels;
  9893. var amountOfSteps = this.height / stepPixels;
  9894. var stepDifference = 0;
  9895. // the slave axis needs to use the same horizontal lines as the master axis.
  9896. if (this.master == false) {
  9897. stepPixels = this.stepPixelsForced;
  9898. stepDifference = Math.round((this.dom.frame.offsetHeight / stepPixels) - amountOfSteps);
  9899. for (var i = 0; i < 0.5 * stepDifference; i++) {
  9900. step.previous();
  9901. }
  9902. amountOfSteps = this.height / stepPixels;
  9903. if (this.zeroCrossing != -1 && this.options.alignZeros == true) {
  9904. var zeroStepDifference = (step.marginEnd / step.step) - this.zeroCrossing;
  9905. if (zeroStepDifference > 0) {
  9906. for (var i = 0; i < zeroStepDifference; i++) {step.next();}
  9907. }
  9908. else if (zeroStepDifference < 0) {
  9909. for (var i = 0; i < -zeroStepDifference; i++) {step.previous();}
  9910. }
  9911. }
  9912. }
  9913. else {
  9914. amountOfSteps += 0.25;
  9915. }
  9916. this.valueAtZero = step.marginEnd;
  9917. var marginStartPos = 0;
  9918. // do not draw the first label
  9919. var max = 1;
  9920. // Get the number of decimal places
  9921. var decimals;
  9922. if(this.options.format[orientation] !== undefined) {
  9923. decimals = this.options.format[orientation].decimals;
  9924. }
  9925. this.maxLabelSize = 0;
  9926. var y = 0;
  9927. while (max < Math.round(amountOfSteps)) {
  9928. step.next();
  9929. y = Math.round(max * stepPixels);
  9930. marginStartPos = max * stepPixels;
  9931. var isMajor = step.isMajor();
  9932. if (this.options['showMinorLabels'] && isMajor == false || this.master == false && this.options['showMinorLabels'] == true) {
  9933. this._redrawLabel(y - 2, step.getCurrent(decimals), orientation, 'yAxis minor', this.props.minorCharHeight);
  9934. }
  9935. if (isMajor && this.options['showMajorLabels'] && this.master == true ||
  9936. this.options['showMinorLabels'] == false && this.master == false && isMajor == true) {
  9937. if (y >= 0) {
  9938. this._redrawLabel(y - 2, step.getCurrent(decimals), orientation, 'yAxis major', this.props.majorCharHeight);
  9939. }
  9940. this._redrawLine(y, orientation, 'grid horizontal major', this.options.majorLinesOffset, this.props.majorLineWidth);
  9941. }
  9942. else {
  9943. this._redrawLine(y, orientation, 'grid horizontal minor', this.options.minorLinesOffset, this.props.minorLineWidth);
  9944. }
  9945. if (this.master == true && step.current == 0) {
  9946. this.zeroCrossing = max;
  9947. }
  9948. max++;
  9949. }
  9950. if (this.master == false) {
  9951. this.conversionFactor = y / (this.valueAtZero - step.current);
  9952. }
  9953. else {
  9954. this.conversionFactor = this.dom.frame.offsetHeight / step.marginRange;
  9955. }
  9956. // Note that title is rotated, so we're using the height, not width!
  9957. var titleWidth = 0;
  9958. if (this.options.title[orientation] !== undefined && this.options.title[orientation].text !== undefined) {
  9959. titleWidth = this.props.titleCharHeight;
  9960. }
  9961. var offset = this.options.icons == true ? Math.max(this.options.iconWidth, titleWidth) + this.options.labelOffsetX + 15 : titleWidth + this.options.labelOffsetX + 15;
  9962. // this will resize the yAxis to accommodate the labels.
  9963. if (this.maxLabelSize > (this.width - offset) && this.options.visible == true) {
  9964. this.width = this.maxLabelSize + offset;
  9965. this.options.width = this.width + "px";
  9966. DOMutil.cleanupElements(this.DOMelements.lines);
  9967. DOMutil.cleanupElements(this.DOMelements.labels);
  9968. this.redraw();
  9969. resized = true;
  9970. }
  9971. // this will resize the yAxis if it is too big for the labels.
  9972. else if (this.maxLabelSize < (this.width - offset) && this.options.visible == true && this.width > this.minWidth) {
  9973. this.width = Math.max(this.minWidth,this.maxLabelSize + offset);
  9974. this.options.width = this.width + "px";
  9975. DOMutil.cleanupElements(this.DOMelements.lines);
  9976. DOMutil.cleanupElements(this.DOMelements.labels);
  9977. this.redraw();
  9978. resized = true;
  9979. }
  9980. else {
  9981. DOMutil.cleanupElements(this.DOMelements.lines);
  9982. DOMutil.cleanupElements(this.DOMelements.labels);
  9983. resized = false;
  9984. }
  9985. return resized;
  9986. };
  9987. DataAxis.prototype.convertValue = function (value) {
  9988. var invertedValue = this.valueAtZero - value;
  9989. var convertedValue = invertedValue * this.conversionFactor;
  9990. return convertedValue;
  9991. };
  9992. DataAxis.prototype.screenToValue = function (x) {
  9993. return this.valueAtZero - (x / this.conversionFactor);
  9994. };
  9995. /**
  9996. * Create a label for the axis at position x
  9997. * @private
  9998. * @param y
  9999. * @param text
  10000. * @param orientation
  10001. * @param className
  10002. * @param characterHeight
  10003. */
  10004. DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) {
  10005. // reuse redundant label
  10006. var label = DOMutil.getDOMElement('div',this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift();
  10007. label.className = className;
  10008. label.innerHTML = text;
  10009. if (orientation == 'left') {
  10010. label.style.left = '-' + this.options.labelOffsetX + 'px';
  10011. label.style.textAlign = "right";
  10012. }
  10013. else {
  10014. label.style.right = '-' + this.options.labelOffsetX + 'px';
  10015. label.style.textAlign = "left";
  10016. }
  10017. label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px';
  10018. text += '';
  10019. var largestWidth = Math.max(this.props.majorCharWidth,this.props.minorCharWidth);
  10020. if (this.maxLabelSize < text.length * largestWidth) {
  10021. this.maxLabelSize = text.length * largestWidth;
  10022. }
  10023. };
  10024. /**
  10025. * Create a minor line for the axis at position y
  10026. * @param y
  10027. * @param orientation
  10028. * @param className
  10029. * @param offset
  10030. * @param width
  10031. */
  10032. DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) {
  10033. if (this.master == true) {
  10034. var line = DOMutil.getDOMElement('div',this.DOMelements.lines, this.dom.lineContainer);//this.dom.redundant.lines.shift();
  10035. line.className = className;
  10036. line.innerHTML = '';
  10037. if (orientation == 'left') {
  10038. line.style.left = (this.width - offset) + 'px';
  10039. }
  10040. else {
  10041. line.style.right = (this.width - offset) + 'px';
  10042. }
  10043. line.style.width = width + 'px';
  10044. line.style.top = y + 'px';
  10045. }
  10046. };
  10047. /**
  10048. * Create a title for the axis
  10049. * @private
  10050. * @param orientation
  10051. */
  10052. DataAxis.prototype._redrawTitle = function (orientation) {
  10053. DOMutil.prepareElements(this.DOMelements.title);
  10054. // Check if the title is defined for this axes
  10055. if (this.options.title[orientation] !== undefined && this.options.title[orientation].text !== undefined) {
  10056. var title = DOMutil.getDOMElement('div', this.DOMelements.title, this.dom.frame);
  10057. title.className = 'yAxis title ' + orientation;
  10058. title.innerHTML = this.options.title[orientation].text;
  10059. // Add style - if provided
  10060. if (this.options.title[orientation].style !== undefined) {
  10061. util.addCssText(title, this.options.title[orientation].style);
  10062. }
  10063. if (orientation == 'left') {
  10064. title.style.left = this.props.titleCharHeight + 'px';
  10065. }
  10066. else {
  10067. title.style.right = this.props.titleCharHeight + 'px';
  10068. }
  10069. title.style.width = this.height + 'px';
  10070. }
  10071. // we need to clean up in case we did not use all elements.
  10072. DOMutil.cleanupElements(this.DOMelements.title);
  10073. };
  10074. /**
  10075. * Determine the size of text on the axis (both major and minor axis).
  10076. * The size is calculated only once and then cached in this.props.
  10077. * @private
  10078. */
  10079. DataAxis.prototype._calculateCharSize = function () {
  10080. // determine the char width and height on the minor axis
  10081. if (!('minorCharHeight' in this.props)) {
  10082. var textMinor = document.createTextNode('0');
  10083. var measureCharMinor = document.createElement('div');
  10084. measureCharMinor.className = 'yAxis minor measure';
  10085. measureCharMinor.appendChild(textMinor);
  10086. this.dom.frame.appendChild(measureCharMinor);
  10087. this.props.minorCharHeight = measureCharMinor.clientHeight;
  10088. this.props.minorCharWidth = measureCharMinor.clientWidth;
  10089. this.dom.frame.removeChild(measureCharMinor);
  10090. }
  10091. if (!('majorCharHeight' in this.props)) {
  10092. var textMajor = document.createTextNode('0');
  10093. var measureCharMajor = document.createElement('div');
  10094. measureCharMajor.className = 'yAxis major measure';
  10095. measureCharMajor.appendChild(textMajor);
  10096. this.dom.frame.appendChild(measureCharMajor);
  10097. this.props.majorCharHeight = measureCharMajor.clientHeight;
  10098. this.props.majorCharWidth = measureCharMajor.clientWidth;
  10099. this.dom.frame.removeChild(measureCharMajor);
  10100. }
  10101. if (!('titleCharHeight' in this.props)) {
  10102. var textTitle = document.createTextNode('0');
  10103. var measureCharTitle = document.createElement('div');
  10104. measureCharTitle.className = 'yAxis title measure';
  10105. measureCharTitle.appendChild(textTitle);
  10106. this.dom.frame.appendChild(measureCharTitle);
  10107. this.props.titleCharHeight = measureCharTitle.clientHeight;
  10108. this.props.titleCharWidth = measureCharTitle.clientWidth;
  10109. this.dom.frame.removeChild(measureCharTitle);
  10110. }
  10111. };
  10112. module.exports = DataAxis;
  10113. /***/ },
  10114. /* 29 */
  10115. /***/ function(module, exports, __webpack_require__) {
  10116. var util = __webpack_require__(1);
  10117. var DOMutil = __webpack_require__(2);
  10118. var Line = __webpack_require__(49);
  10119. var Bar = __webpack_require__(50);
  10120. var Points = __webpack_require__(51);
  10121. /**
  10122. * /**
  10123. * @param {object} group | the object of the group from the dataset
  10124. * @param {string} groupId | ID of the group
  10125. * @param {object} options | the default options
  10126. * @param {array} groupsUsingDefaultStyles | this array has one entree.
  10127. * It is passed as an array so it is passed by reference.
  10128. * It enumerates through the default styles
  10129. * @constructor
  10130. */
  10131. function GraphGroup (group, groupId, options, groupsUsingDefaultStyles) {
  10132. this.id = groupId;
  10133. var fields = ['sampling','style','sort','yAxisOrientation','barChart','drawPoints','shaded','catmullRom']
  10134. this.options = util.selectiveBridgeObject(fields,options);
  10135. this.usingDefaultStyle = group.className === undefined;
  10136. this.groupsUsingDefaultStyles = groupsUsingDefaultStyles;
  10137. this.zeroPosition = 0;
  10138. this.update(group);
  10139. if (this.usingDefaultStyle == true) {
  10140. this.groupsUsingDefaultStyles[0] += 1;
  10141. }
  10142. this.itemsData = [];
  10143. this.visible = group.visible === undefined ? true : group.visible;
  10144. }
  10145. /**
  10146. * this loads a reference to all items in this group into this group.
  10147. * @param {array} items
  10148. */
  10149. GraphGroup.prototype.setItems = function(items) {
  10150. if (items != null) {
  10151. this.itemsData = items;
  10152. if (this.options.sort == true) {
  10153. this.itemsData.sort(function (a,b) {return a.x - b.x;})
  10154. }
  10155. }
  10156. else {
  10157. this.itemsData = [];
  10158. }
  10159. };
  10160. /**
  10161. * this is used for plotting barcharts, this way, we only have to calculate it once.
  10162. * @param pos
  10163. */
  10164. GraphGroup.prototype.setZeroPosition = function(pos) {
  10165. this.zeroPosition = pos;
  10166. };
  10167. /**
  10168. * set the options of the graph group over the default options.
  10169. * @param options
  10170. */
  10171. GraphGroup.prototype.setOptions = function(options) {
  10172. if (options !== undefined) {
  10173. var fields = ['sampling','style','sort','yAxisOrientation','barChart'];
  10174. util.selectiveDeepExtend(fields, this.options, options);
  10175. util.mergeOptions(this.options, options,'catmullRom');
  10176. util.mergeOptions(this.options, options,'drawPoints');
  10177. util.mergeOptions(this.options, options,'shaded');
  10178. if (options.catmullRom) {
  10179. if (typeof options.catmullRom == 'object') {
  10180. if (options.catmullRom.parametrization) {
  10181. if (options.catmullRom.parametrization == 'uniform') {
  10182. this.options.catmullRom.alpha = 0;
  10183. }
  10184. else if (options.catmullRom.parametrization == 'chordal') {
  10185. this.options.catmullRom.alpha = 1.0;
  10186. }
  10187. else {
  10188. this.options.catmullRom.parametrization = 'centripetal';
  10189. this.options.catmullRom.alpha = 0.5;
  10190. }
  10191. }
  10192. }
  10193. }
  10194. }
  10195. if (this.options.style == 'line') {
  10196. this.type = new Line(this.id, this.options);
  10197. }
  10198. else if (this.options.style == 'bar') {
  10199. this.type = new Bar(this.id, this.options);
  10200. }
  10201. else if (this.options.style == 'points') {
  10202. this.type = new Points(this.id, this.options);
  10203. }
  10204. };
  10205. /**
  10206. * this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph
  10207. * @param group
  10208. */
  10209. GraphGroup.prototype.update = function(group) {
  10210. this.group = group;
  10211. this.content = group.content || 'graph';
  10212. this.className = group.className || this.className || "graphGroup" + this.groupsUsingDefaultStyles[0] % 10;
  10213. this.visible = group.visible === undefined ? true : group.visible;
  10214. this.style = group.style;
  10215. this.setOptions(group.options);
  10216. };
  10217. /**
  10218. * draw the icon for the legend.
  10219. *
  10220. * @param x
  10221. * @param y
  10222. * @param JSONcontainer
  10223. * @param SVGcontainer
  10224. * @param iconWidth
  10225. * @param iconHeight
  10226. */
  10227. GraphGroup.prototype.drawIcon = function(x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) {
  10228. var fillHeight = iconHeight * 0.5;
  10229. var path, fillPath;
  10230. var outline = DOMutil.getSVGElement("rect", JSONcontainer, SVGcontainer);
  10231. outline.setAttributeNS(null, "x", x);
  10232. outline.setAttributeNS(null, "y", y - fillHeight);
  10233. outline.setAttributeNS(null, "width", iconWidth);
  10234. outline.setAttributeNS(null, "height", 2*fillHeight);
  10235. outline.setAttributeNS(null, "class", "outline");
  10236. if (this.options.style == 'line') {
  10237. path = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
  10238. path.setAttributeNS(null, "class", this.className);
  10239. if(this.style !== undefined) {
  10240. path.setAttributeNS(null, "style", this.style);
  10241. }
  10242. path.setAttributeNS(null, "d", "M" + x + ","+y+" L" + (x + iconWidth) + ","+y+"");
  10243. if (this.options.shaded.enabled == true) {
  10244. fillPath = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
  10245. if (this.options.shaded.orientation == 'top') {
  10246. fillPath.setAttributeNS(null, "d", "M"+x+", " + (y - fillHeight) +
  10247. "L"+x+","+y+" L"+ (x + iconWidth) + ","+y+" L"+ (x + iconWidth) + "," + (y - fillHeight));
  10248. }
  10249. else {
  10250. fillPath.setAttributeNS(null, "d", "M"+x+","+y+" " +
  10251. "L"+x+"," + (y + fillHeight) + " " +
  10252. "L"+ (x + iconWidth) + "," + (y + fillHeight) +
  10253. "L"+ (x + iconWidth) + ","+y);
  10254. }
  10255. fillPath.setAttributeNS(null, "class", this.className + " iconFill");
  10256. }
  10257. if (this.options.drawPoints.enabled == true) {
  10258. DOMutil.drawPoint(x + 0.5 * iconWidth,y, this, JSONcontainer, SVGcontainer);
  10259. }
  10260. }
  10261. else {
  10262. var barWidth = Math.round(0.3 * iconWidth);
  10263. var bar1Height = Math.round(0.4 * iconHeight);
  10264. var bar2Height = Math.round(0.75 * iconHeight);
  10265. var offset = Math.round((iconWidth - (2 * barWidth))/3);
  10266. DOMutil.drawBar(x + 0.5*barWidth + offset , y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' bar', JSONcontainer, SVGcontainer);
  10267. DOMutil.drawBar(x + 1.5*barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' bar', JSONcontainer, SVGcontainer);
  10268. }
  10269. };
  10270. /**
  10271. * return the legend entree for this group.
  10272. *
  10273. * @param iconWidth
  10274. * @param iconHeight
  10275. * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}}
  10276. */
  10277. GraphGroup.prototype.getLegend = function(iconWidth, iconHeight) {
  10278. var svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  10279. this.drawIcon(0,0.5*iconHeight,[],svg,iconWidth,iconHeight);
  10280. return {icon: svg, label: this.content, orientation:this.options.yAxisOrientation};
  10281. }
  10282. GraphGroup.prototype.getYRange = function(groupData) {
  10283. return this.type.getYRange(groupData);
  10284. }
  10285. GraphGroup.prototype.draw = function(dataset, group, framework) {
  10286. this.type.draw(dataset, group, framework);
  10287. }
  10288. module.exports = GraphGroup;
  10289. /***/ },
  10290. /* 30 */
  10291. /***/ function(module, exports, __webpack_require__) {
  10292. var util = __webpack_require__(1);
  10293. var stack = __webpack_require__(18);
  10294. var RangeItem = __webpack_require__(24);
  10295. /**
  10296. * @constructor Group
  10297. * @param {Number | String} groupId
  10298. * @param {Object} data
  10299. * @param {ItemSet} itemSet
  10300. */
  10301. function Group (groupId, data, itemSet) {
  10302. this.groupId = groupId;
  10303. this.subgroups = {};
  10304. this.subgroupIndex = 0;
  10305. this.subgroupOrderer = data && data.subgroupOrder;
  10306. this.itemSet = itemSet;
  10307. this.dom = {};
  10308. this.props = {
  10309. label: {
  10310. width: 0,
  10311. height: 0
  10312. }
  10313. };
  10314. this.className = null;
  10315. this.items = {}; // items filtered by groupId of this group
  10316. this.visibleItems = []; // items currently visible in window
  10317. this.orderedItems = {
  10318. byStart: [],
  10319. byEnd: []
  10320. };
  10321. this.checkRangedItems = false; // needed to refresh the ranged items if the window is programatically changed with NO overlap.
  10322. var me = this;
  10323. this.itemSet.body.emitter.on("checkRangedItems", function () {
  10324. me.checkRangedItems = true;
  10325. })
  10326. this._create();
  10327. this.setData(data);
  10328. }
  10329. /**
  10330. * Create DOM elements for the group
  10331. * @private
  10332. */
  10333. Group.prototype._create = function() {
  10334. var label = document.createElement('div');
  10335. label.className = 'vlabel';
  10336. this.dom.label = label;
  10337. var inner = document.createElement('div');
  10338. inner.className = 'inner';
  10339. label.appendChild(inner);
  10340. this.dom.inner = inner;
  10341. var foreground = document.createElement('div');
  10342. foreground.className = 'group';
  10343. foreground['timeline-group'] = this;
  10344. this.dom.foreground = foreground;
  10345. this.dom.background = document.createElement('div');
  10346. this.dom.background.className = 'group';
  10347. this.dom.axis = document.createElement('div');
  10348. this.dom.axis.className = 'group';
  10349. // create a hidden marker to detect when the Timelines container is attached
  10350. // to the DOM, or the style of a parent of the Timeline is changed from
  10351. // display:none is changed to visible.
  10352. this.dom.marker = document.createElement('div');
  10353. this.dom.marker.style.visibility = 'hidden'; // TODO: ask jos why this is not none?
  10354. this.dom.marker.innerHTML = '?';
  10355. this.dom.background.appendChild(this.dom.marker);
  10356. };
  10357. /**
  10358. * Set the group data for this group
  10359. * @param {Object} data Group data, can contain properties content and className
  10360. */
  10361. Group.prototype.setData = function(data) {
  10362. // update contents
  10363. var content = data && data.content;
  10364. if (content instanceof Element) {
  10365. this.dom.inner.appendChild(content);
  10366. }
  10367. else if (content !== undefined && content !== null) {
  10368. this.dom.inner.innerHTML = content;
  10369. }
  10370. else {
  10371. this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null
  10372. }
  10373. // update title
  10374. this.dom.label.title = data && data.title || '';
  10375. if (!this.dom.inner.firstChild) {
  10376. util.addClassName(this.dom.inner, 'hidden');
  10377. }
  10378. else {
  10379. util.removeClassName(this.dom.inner, 'hidden');
  10380. }
  10381. // update className
  10382. var className = data && data.className || null;
  10383. if (className != this.className) {
  10384. if (this.className) {
  10385. util.removeClassName(this.dom.label, this.className);
  10386. util.removeClassName(this.dom.foreground, this.className);
  10387. util.removeClassName(this.dom.background, this.className);
  10388. util.removeClassName(this.dom.axis, this.className);
  10389. }
  10390. util.addClassName(this.dom.label, className);
  10391. util.addClassName(this.dom.foreground, className);
  10392. util.addClassName(this.dom.background, className);
  10393. util.addClassName(this.dom.axis, className);
  10394. this.className = className;
  10395. }
  10396. // update style
  10397. if (this.style) {
  10398. util.removeCssText(this.dom.label, this.style);
  10399. this.style = null;
  10400. }
  10401. if (data && data.style) {
  10402. util.addCssText(this.dom.label, data.style);
  10403. this.style = data.style;
  10404. }
  10405. };
  10406. /**
  10407. * Get the width of the group label
  10408. * @return {number} width
  10409. */
  10410. Group.prototype.getLabelWidth = function() {
  10411. return this.props.label.width;
  10412. };
  10413. /**
  10414. * Repaint this group
  10415. * @param {{start: number, end: number}} range
  10416. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  10417. * @param {boolean} [restack=false] Force restacking of all items
  10418. * @return {boolean} Returns true if the group is resized
  10419. */
  10420. Group.prototype.redraw = function(range, margin, restack) {
  10421. var resized = false;
  10422. // force recalculation of the height of the items when the marker height changed
  10423. // (due to the Timeline being attached to the DOM or changed from display:none to visible)
  10424. var markerHeight = this.dom.marker.clientHeight;
  10425. if (markerHeight != this.lastMarkerHeight) {
  10426. this.lastMarkerHeight = markerHeight;
  10427. util.forEach(this.items, function (item) {
  10428. item.dirty = true;
  10429. if (item.displayed) item.redraw();
  10430. });
  10431. restack = true;
  10432. }
  10433. // reposition visible items vertically
  10434. if (typeof this.itemSet.options.order === 'function') {
  10435. // a custom order function
  10436. if (restack) {
  10437. // brute force restack of all items
  10438. // show all items
  10439. var me = this;
  10440. var limitSize = false;
  10441. util.forEach(this.items, function (item) {
  10442. if (!item.displayed) {
  10443. item.redraw();
  10444. me.visibleItems.push(item);
  10445. }
  10446. item.repositionX(limitSize);
  10447. });
  10448. // order all items and force a restacking
  10449. var customOrderedItems = this.orderedItems.byStart.slice().sort(function (a, b) {
  10450. return me.itemSet.options.order(a.data, b.data);
  10451. });
  10452. stack.stack(customOrderedItems, margin, true /* restack=true */);
  10453. }
  10454. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  10455. }
  10456. else {
  10457. // no custom order function, lazy stacking
  10458. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  10459. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  10460. stack.stack(this.visibleItems, margin, restack);
  10461. }
  10462. else { // no stacking
  10463. stack.nostack(this.visibleItems, margin, this.subgroups);
  10464. }
  10465. }
  10466. // recalculate the height of the group
  10467. var height = this._calculateHeight(margin);
  10468. // calculate actual size and position
  10469. var foreground = this.dom.foreground;
  10470. this.top = foreground.offsetTop;
  10471. this.left = foreground.offsetLeft;
  10472. this.width = foreground.offsetWidth;
  10473. resized = util.updateProperty(this, 'height', height) || resized;
  10474. // recalculate size of label
  10475. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  10476. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  10477. // apply new height
  10478. this.dom.background.style.height = height + 'px';
  10479. this.dom.foreground.style.height = height + 'px';
  10480. this.dom.label.style.height = height + 'px';
  10481. // update vertical position of items after they are re-stacked and the height of the group is calculated
  10482. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  10483. var item = this.visibleItems[i];
  10484. item.repositionY(margin);
  10485. }
  10486. return resized;
  10487. };
  10488. /**
  10489. * recalculate the height of the group
  10490. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  10491. * @returns {number} Returns the height
  10492. * @private
  10493. */
  10494. Group.prototype._calculateHeight = function (margin) {
  10495. // recalculate the height of the group
  10496. var height;
  10497. var visibleItems = this.visibleItems;
  10498. //var visibleSubgroups = [];
  10499. //this.visibleSubgroups = 0;
  10500. this.resetSubgroups();
  10501. var me = this;
  10502. if (visibleItems.length) {
  10503. var min = visibleItems[0].top;
  10504. var max = visibleItems[0].top + visibleItems[0].height;
  10505. util.forEach(visibleItems, function (item) {
  10506. min = Math.min(min, item.top);
  10507. max = Math.max(max, (item.top + item.height));
  10508. if (item.data.subgroup !== undefined) {
  10509. me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height,item.height);
  10510. me.subgroups[item.data.subgroup].visible = true;
  10511. //if (visibleSubgroups.indexOf(item.data.subgroup) == -1){
  10512. // visibleSubgroups.push(item.data.subgroup);
  10513. // me.visibleSubgroups += 1;
  10514. //}
  10515. }
  10516. });
  10517. if (min > margin.axis) {
  10518. // there is an empty gap between the lowest item and the axis
  10519. var offset = min - margin.axis;
  10520. max -= offset;
  10521. util.forEach(visibleItems, function (item) {
  10522. item.top -= offset;
  10523. });
  10524. }
  10525. height = max + margin.item.vertical / 2;
  10526. }
  10527. else {
  10528. height = 0;
  10529. }
  10530. height = Math.max(height, this.props.label.height);
  10531. return height;
  10532. };
  10533. /**
  10534. * Show this group: attach to the DOM
  10535. */
  10536. Group.prototype.show = function() {
  10537. if (!this.dom.label.parentNode) {
  10538. this.itemSet.dom.labelSet.appendChild(this.dom.label);
  10539. }
  10540. if (!this.dom.foreground.parentNode) {
  10541. this.itemSet.dom.foreground.appendChild(this.dom.foreground);
  10542. }
  10543. if (!this.dom.background.parentNode) {
  10544. this.itemSet.dom.background.appendChild(this.dom.background);
  10545. }
  10546. if (!this.dom.axis.parentNode) {
  10547. this.itemSet.dom.axis.appendChild(this.dom.axis);
  10548. }
  10549. };
  10550. /**
  10551. * Hide this group: remove from the DOM
  10552. */
  10553. Group.prototype.hide = function() {
  10554. var label = this.dom.label;
  10555. if (label.parentNode) {
  10556. label.parentNode.removeChild(label);
  10557. }
  10558. var foreground = this.dom.foreground;
  10559. if (foreground.parentNode) {
  10560. foreground.parentNode.removeChild(foreground);
  10561. }
  10562. var background = this.dom.background;
  10563. if (background.parentNode) {
  10564. background.parentNode.removeChild(background);
  10565. }
  10566. var axis = this.dom.axis;
  10567. if (axis.parentNode) {
  10568. axis.parentNode.removeChild(axis);
  10569. }
  10570. };
  10571. /**
  10572. * Add an item to the group
  10573. * @param {Item} item
  10574. */
  10575. Group.prototype.add = function(item) {
  10576. this.items[item.id] = item;
  10577. item.setParent(this);
  10578. // add to
  10579. if (item.data.subgroup !== undefined) {
  10580. if (this.subgroups[item.data.subgroup] === undefined) {
  10581. this.subgroups[item.data.subgroup] = {height:0, visible: false, index:this.subgroupIndex, items: []};
  10582. this.subgroupIndex++;
  10583. }
  10584. this.subgroups[item.data.subgroup].items.push(item);
  10585. }
  10586. this.orderSubgroups();
  10587. if (this.visibleItems.indexOf(item) == -1) {
  10588. var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
  10589. this._checkIfVisible(item, this.visibleItems, range);
  10590. }
  10591. };
  10592. Group.prototype.orderSubgroups = function() {
  10593. if (this.subgroupOrderer !== undefined) {
  10594. var sortArray = [];
  10595. if (typeof this.subgroupOrderer == 'string') {
  10596. for (var subgroup in this.subgroups) {
  10597. sortArray.push({subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer]})
  10598. }
  10599. sortArray.sort(function (a, b) {
  10600. return a.sortField - b.sortField;
  10601. })
  10602. }
  10603. else if (typeof this.subgroupOrderer == 'function') {
  10604. for (var subgroup in this.subgroups) {
  10605. sortArray.push(this.subgroups[subgroup].items[0].data);
  10606. }
  10607. sortArray.sort(this.subgroupOrderer);
  10608. }
  10609. if (sortArray.length > 0) {
  10610. for (var i = 0; i < sortArray.length; i++) {
  10611. this.subgroups[sortArray[i].subgroup].index = i;
  10612. }
  10613. }
  10614. }
  10615. };
  10616. Group.prototype.resetSubgroups = function() {
  10617. for (var subgroup in this.subgroups) {
  10618. if (this.subgroups.hasOwnProperty(subgroup)) {
  10619. this.subgroups[subgroup].visible = false;
  10620. }
  10621. }
  10622. };
  10623. /**
  10624. * Remove an item from the group
  10625. * @param {Item} item
  10626. */
  10627. Group.prototype.remove = function(item) {
  10628. delete this.items[item.id];
  10629. item.setParent(null);
  10630. // remove from visible items
  10631. var index = this.visibleItems.indexOf(item);
  10632. if (index != -1) this.visibleItems.splice(index, 1);
  10633. // TODO: also remove from ordered items?
  10634. };
  10635. /**
  10636. * Remove an item from the corresponding DataSet
  10637. * @param {Item} item
  10638. */
  10639. Group.prototype.removeFromDataSet = function(item) {
  10640. this.itemSet.removeItem(item.id);
  10641. };
  10642. /**
  10643. * Reorder the items
  10644. */
  10645. Group.prototype.order = function() {
  10646. var array = util.toArray(this.items);
  10647. var startArray = [];
  10648. var endArray = [];
  10649. for (var i = 0; i < array.length; i++) {
  10650. if (array[i].data.end !== undefined) {
  10651. endArray.push(array[i]);
  10652. }
  10653. startArray.push(array[i]);
  10654. }
  10655. this.orderedItems = {
  10656. byStart: startArray,
  10657. byEnd: endArray
  10658. };
  10659. stack.orderByStart(this.orderedItems.byStart);
  10660. stack.orderByEnd(this.orderedItems.byEnd);
  10661. };
  10662. /**
  10663. * Update the visible items
  10664. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  10665. * @param {Item[]} visibleItems The previously visible items.
  10666. * @param {{start: number, end: number}} range Visible range
  10667. * @return {Item[]} visibleItems The new visible items.
  10668. * @private
  10669. */
  10670. Group.prototype._updateVisibleItems = function(orderedItems, oldVisibleItems, range) {
  10671. var visibleItems = [];
  10672. var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
  10673. var interval = (range.end - range.start) / 4;
  10674. var lowerBound = range.start - interval;
  10675. var upperBound = range.end + interval;
  10676. var item, i;
  10677. // this function is used to do the binary search.
  10678. var searchFunction = function (value) {
  10679. if (value < lowerBound) {return -1;}
  10680. else if (value <= upperBound) {return 0;}
  10681. else {return 1;}
  10682. }
  10683. // first check if the items that were in view previously are still in view.
  10684. // IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
  10685. // also cleans up invisible items.
  10686. if (oldVisibleItems.length > 0) {
  10687. for (i = 0; i < oldVisibleItems.length; i++) {
  10688. this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
  10689. }
  10690. }
  10691. // we do a binary search for the items that have only start values.
  10692. var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data','start');
  10693. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
  10694. this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
  10695. return (item.data.start < lowerBound || item.data.start > upperBound);
  10696. });
  10697. // if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
  10698. // We therefore have to brute force check all items in the byEnd list
  10699. if (this.checkRangedItems == true) {
  10700. this.checkRangedItems = false;
  10701. for (i = 0; i < orderedItems.byEnd.length; i++) {
  10702. this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
  10703. }
  10704. }
  10705. else {
  10706. // we do a binary search for the items that have defined end times.
  10707. var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data','end');
  10708. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
  10709. this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
  10710. return (item.data.end < lowerBound || item.data.end > upperBound);
  10711. });
  10712. }
  10713. // finally, we reposition all the visible items.
  10714. for (i = 0; i < visibleItems.length; i++) {
  10715. item = visibleItems[i];
  10716. if (!item.displayed) item.show();
  10717. // reposition item horizontally
  10718. item.repositionX();
  10719. }
  10720. // debug
  10721. //console.log("new line")
  10722. //if (this.groupId == null) {
  10723. // for (i = 0; i < orderedItems.byStart.length; i++) {
  10724. // item = orderedItems.byStart[i].data;
  10725. // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "")
  10726. // }
  10727. // for (i = 0; i < orderedItems.byEnd.length; i++) {
  10728. // item = orderedItems.byEnd[i].data;
  10729. // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "")
  10730. // }
  10731. //}
  10732. return visibleItems;
  10733. };
  10734. Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
  10735. var item;
  10736. var i;
  10737. if (initialPos != -1) {
  10738. for (i = initialPos; i >= 0; i--) {
  10739. item = items[i];
  10740. if (breakCondition(item)) {
  10741. break;
  10742. }
  10743. else {
  10744. if (visibleItemsLookup[item.id] === undefined) {
  10745. visibleItemsLookup[item.id] = true;
  10746. visibleItems.push(item);
  10747. }
  10748. }
  10749. }
  10750. for (i = initialPos + 1; i < items.length; i++) {
  10751. item = items[i];
  10752. if (breakCondition(item)) {
  10753. break;
  10754. }
  10755. else {
  10756. if (visibleItemsLookup[item.id] === undefined) {
  10757. visibleItemsLookup[item.id] = true;
  10758. visibleItems.push(item);
  10759. }
  10760. }
  10761. }
  10762. }
  10763. }
  10764. /**
  10765. * this function is very similar to the _checkIfInvisible() but it does not
  10766. * return booleans, hides the item if it should not be seen and always adds to
  10767. * the visibleItems.
  10768. * this one is for brute forcing and hiding.
  10769. *
  10770. * @param {Item} item
  10771. * @param {Array} visibleItems
  10772. * @param {{start:number, end:number}} range
  10773. * @private
  10774. */
  10775. Group.prototype._checkIfVisible = function(item, visibleItems, range) {
  10776. if (item.isVisible(range)) {
  10777. if (!item.displayed) item.show();
  10778. // reposition item horizontally
  10779. item.repositionX();
  10780. visibleItems.push(item);
  10781. }
  10782. else {
  10783. if (item.displayed) item.hide();
  10784. }
  10785. };
  10786. /**
  10787. * this function is very similar to the _checkIfInvisible() but it does not
  10788. * return booleans, hides the item if it should not be seen and always adds to
  10789. * the visibleItems.
  10790. * this one is for brute forcing and hiding.
  10791. *
  10792. * @param {Item} item
  10793. * @param {Array} visibleItems
  10794. * @param {{start:number, end:number}} range
  10795. * @private
  10796. */
  10797. Group.prototype._checkIfVisibleWithReference = function(item, visibleItems, visibleItemsLookup, range) {
  10798. if (item.isVisible(range)) {
  10799. if (visibleItemsLookup[item.id] === undefined) {
  10800. visibleItemsLookup[item.id] = true;
  10801. visibleItems.push(item);
  10802. }
  10803. }
  10804. else {
  10805. if (item.displayed) item.hide();
  10806. }
  10807. };
  10808. module.exports = Group;
  10809. /***/ },
  10810. /* 31 */
  10811. /***/ function(module, exports, __webpack_require__) {
  10812. var util = __webpack_require__(1);
  10813. var Group = __webpack_require__(30);
  10814. /**
  10815. * @constructor BackgroundGroup
  10816. * @param {Number | String} groupId
  10817. * @param {Object} data
  10818. * @param {ItemSet} itemSet
  10819. */
  10820. function BackgroundGroup (groupId, data, itemSet) {
  10821. Group.call(this, groupId, data, itemSet);
  10822. this.width = 0;
  10823. this.height = 0;
  10824. this.top = 0;
  10825. this.left = 0;
  10826. }
  10827. BackgroundGroup.prototype = Object.create(Group.prototype);
  10828. /**
  10829. * Repaint this group
  10830. * @param {{start: number, end: number}} range
  10831. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  10832. * @param {boolean} [restack=false] Force restacking of all items
  10833. * @return {boolean} Returns true if the group is resized
  10834. */
  10835. BackgroundGroup.prototype.redraw = function(range, margin, restack) {
  10836. var resized = false;
  10837. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  10838. // calculate actual size
  10839. this.width = this.dom.background.offsetWidth;
  10840. // apply new height (just always zero for BackgroundGroup
  10841. this.dom.background.style.height = '0';
  10842. // update vertical position of items after they are re-stacked and the height of the group is calculated
  10843. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  10844. var item = this.visibleItems[i];
  10845. item.repositionY(margin);
  10846. }
  10847. return resized;
  10848. };
  10849. /**
  10850. * Show this group: attach to the DOM
  10851. */
  10852. BackgroundGroup.prototype.show = function() {
  10853. if (!this.dom.background.parentNode) {
  10854. this.itemSet.dom.background.appendChild(this.dom.background);
  10855. }
  10856. };
  10857. module.exports = BackgroundGroup;
  10858. /***/ },
  10859. /* 32 */
  10860. /***/ function(module, exports, __webpack_require__) {
  10861. var Hammer = __webpack_require__(45);
  10862. var util = __webpack_require__(1);
  10863. var DataSet = __webpack_require__(3);
  10864. var DataView = __webpack_require__(4);
  10865. var TimeStep = __webpack_require__(19);
  10866. var Component = __webpack_require__(25);
  10867. var Group = __webpack_require__(30);
  10868. var BackgroundGroup = __webpack_require__(31);
  10869. var BoxItem = __webpack_require__(22);
  10870. var PointItem = __webpack_require__(23);
  10871. var RangeItem = __webpack_require__(24);
  10872. var BackgroundItem = __webpack_require__(21);
  10873. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  10874. var BACKGROUND = '__background__'; // reserved group id for background items without group
  10875. /**
  10876. * An ItemSet holds a set of items and ranges which can be displayed in a
  10877. * range. The width is determined by the parent of the ItemSet, and the height
  10878. * is determined by the size of the items.
  10879. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  10880. * @param {Object} [options] See ItemSet.setOptions for the available options.
  10881. * @constructor ItemSet
  10882. * @extends Component
  10883. */
  10884. function ItemSet(body, options) {
  10885. this.body = body;
  10886. this.defaultOptions = {
  10887. type: null, // 'box', 'point', 'range', 'background'
  10888. orientation: 'bottom', // item orientation: 'top' or 'bottom'
  10889. align: 'auto', // alignment of box items
  10890. stack: true,
  10891. groupOrder: null,
  10892. selectable: true,
  10893. editable: {
  10894. updateTime: false,
  10895. updateGroup: false,
  10896. add: false,
  10897. remove: false
  10898. },
  10899. snap: TimeStep.snap,
  10900. onAdd: function (item, callback) {
  10901. callback(item);
  10902. },
  10903. onUpdate: function (item, callback) {
  10904. callback(item);
  10905. },
  10906. onMove: function (item, callback) {
  10907. callback(item);
  10908. },
  10909. onRemove: function (item, callback) {
  10910. callback(item);
  10911. },
  10912. onMoving: function (item, callback) {
  10913. callback(item);
  10914. },
  10915. margin: {
  10916. item: {
  10917. horizontal: 10,
  10918. vertical: 10
  10919. },
  10920. axis: 20
  10921. },
  10922. padding: 5
  10923. };
  10924. // options is shared by this ItemSet and all its items
  10925. this.options = util.extend({}, this.defaultOptions);
  10926. // options for getting items from the DataSet with the correct type
  10927. this.itemOptions = {
  10928. type: {start: 'Date', end: 'Date'}
  10929. };
  10930. this.conversion = {
  10931. toScreen: body.util.toScreen,
  10932. toTime: body.util.toTime
  10933. };
  10934. this.dom = {};
  10935. this.props = {};
  10936. this.hammer = null;
  10937. var me = this;
  10938. this.itemsData = null; // DataSet
  10939. this.groupsData = null; // DataSet
  10940. // listeners for the DataSet of the items
  10941. this.itemListeners = {
  10942. 'add': function (event, params, senderId) {
  10943. me._onAdd(params.items);
  10944. },
  10945. 'update': function (event, params, senderId) {
  10946. me._onUpdate(params.items);
  10947. },
  10948. 'remove': function (event, params, senderId) {
  10949. me._onRemove(params.items);
  10950. }
  10951. };
  10952. // listeners for the DataSet of the groups
  10953. this.groupListeners = {
  10954. 'add': function (event, params, senderId) {
  10955. me._onAddGroups(params.items);
  10956. },
  10957. 'update': function (event, params, senderId) {
  10958. me._onUpdateGroups(params.items);
  10959. },
  10960. 'remove': function (event, params, senderId) {
  10961. me._onRemoveGroups(params.items);
  10962. }
  10963. };
  10964. this.items = {}; // object with an Item for every data item
  10965. this.groups = {}; // Group object for every group
  10966. this.groupIds = [];
  10967. this.selection = []; // list with the ids of all selected nodes
  10968. this.stackDirty = true; // if true, all items will be restacked on next redraw
  10969. this.touchParams = {}; // stores properties while dragging
  10970. // create the HTML DOM
  10971. this._create();
  10972. this.setOptions(options);
  10973. }
  10974. ItemSet.prototype = new Component();
  10975. // available item types will be registered here
  10976. ItemSet.types = {
  10977. background: BackgroundItem,
  10978. box: BoxItem,
  10979. range: RangeItem,
  10980. point: PointItem
  10981. };
  10982. /**
  10983. * Create the HTML DOM for the ItemSet
  10984. */
  10985. ItemSet.prototype._create = function(){
  10986. var frame = document.createElement('div');
  10987. frame.className = 'itemset';
  10988. frame['timeline-itemset'] = this;
  10989. this.dom.frame = frame;
  10990. // create background panel
  10991. var background = document.createElement('div');
  10992. background.className = 'background';
  10993. frame.appendChild(background);
  10994. this.dom.background = background;
  10995. // create foreground panel
  10996. var foreground = document.createElement('div');
  10997. foreground.className = 'foreground';
  10998. frame.appendChild(foreground);
  10999. this.dom.foreground = foreground;
  11000. // create axis panel
  11001. var axis = document.createElement('div');
  11002. axis.className = 'axis';
  11003. this.dom.axis = axis;
  11004. // create labelset
  11005. var labelSet = document.createElement('div');
  11006. labelSet.className = 'labelset';
  11007. this.dom.labelSet = labelSet;
  11008. // create ungrouped Group
  11009. this._updateUngrouped();
  11010. // create background Group
  11011. var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
  11012. backgroundGroup.show();
  11013. this.groups[BACKGROUND] = backgroundGroup;
  11014. // attach event listeners
  11015. // Note: we bind to the centerContainer for the case where the height
  11016. // of the center container is larger than of the ItemSet, so we
  11017. // can click in the empty area to create a new item or deselect an item.
  11018. this.hammer = Hammer(this.body.dom.centerContainer, {
  11019. preventDefault: true
  11020. });
  11021. // drag items when selected
  11022. this.hammer.on('touch', this._onTouch.bind(this));
  11023. this.hammer.on('dragstart', this._onDragStart.bind(this));
  11024. this.hammer.on('drag', this._onDrag.bind(this));
  11025. this.hammer.on('dragend', this._onDragEnd.bind(this));
  11026. // single select (or unselect) when tapping an item
  11027. this.hammer.on('tap', this._onSelectItem.bind(this));
  11028. // multi select when holding mouse/touch, or on ctrl+click
  11029. this.hammer.on('hold', this._onMultiSelectItem.bind(this));
  11030. // add item on doubletap
  11031. this.hammer.on('doubletap', this._onAddItem.bind(this));
  11032. // attach to the DOM
  11033. this.show();
  11034. };
  11035. /**
  11036. * Set options for the ItemSet. Existing options will be extended/overwritten.
  11037. * @param {Object} [options] The following options are available:
  11038. * {String} type
  11039. * Default type for the items. Choose from 'box'
  11040. * (default), 'point', 'range', or 'background'.
  11041. * The default style can be overwritten by
  11042. * individual items.
  11043. * {String} align
  11044. * Alignment for the items, only applicable for
  11045. * BoxItem. Choose 'center' (default), 'left', or
  11046. * 'right'.
  11047. * {String} orientation
  11048. * Orientation of the item set. Choose 'top' or
  11049. * 'bottom' (default).
  11050. * {Function} groupOrder
  11051. * A sorting function for ordering groups
  11052. * {Boolean} stack
  11053. * If true (deafult), items will be stacked on
  11054. * top of each other.
  11055. * {Number} margin.axis
  11056. * Margin between the axis and the items in pixels.
  11057. * Default is 20.
  11058. * {Number} margin.item.horizontal
  11059. * Horizontal margin between items in pixels.
  11060. * Default is 10.
  11061. * {Number} margin.item.vertical
  11062. * Vertical Margin between items in pixels.
  11063. * Default is 10.
  11064. * {Number} margin.item
  11065. * Margin between items in pixels in both horizontal
  11066. * and vertical direction. Default is 10.
  11067. * {Number} margin
  11068. * Set margin for both axis and items in pixels.
  11069. * {Number} padding
  11070. * Padding of the contents of an item in pixels.
  11071. * Must correspond with the items css. Default is 5.
  11072. * {Boolean} selectable
  11073. * If true (default), items can be selected.
  11074. * {Boolean} editable
  11075. * Set all editable options to true or false
  11076. * {Boolean} editable.updateTime
  11077. * Allow dragging an item to an other moment in time
  11078. * {Boolean} editable.updateGroup
  11079. * Allow dragging an item to an other group
  11080. * {Boolean} editable.add
  11081. * Allow creating new items on double tap
  11082. * {Boolean} editable.remove
  11083. * Allow removing items by clicking the delete button
  11084. * top right of a selected item.
  11085. * {Function(item: Item, callback: Function)} onAdd
  11086. * Callback function triggered when an item is about to be added:
  11087. * when the user double taps an empty space in the Timeline.
  11088. * {Function(item: Item, callback: Function)} onUpdate
  11089. * Callback function fired when an item is about to be updated.
  11090. * This function typically has to show a dialog where the user
  11091. * change the item. If not implemented, nothing happens.
  11092. * {Function(item: Item, callback: Function)} onMove
  11093. * Fired when an item has been moved. If not implemented,
  11094. * the move action will be accepted.
  11095. * {Function(item: Item, callback: Function)} onRemove
  11096. * Fired when an item is about to be deleted.
  11097. * If not implemented, the item will be always removed.
  11098. */
  11099. ItemSet.prototype.setOptions = function(options) {
  11100. if (options) {
  11101. // copy all options that we know
  11102. var fields = ['type', 'align', 'order', 'padding', 'stack', 'selectable', 'groupOrder', 'dataAttributes', 'template','hide', 'snap'];
  11103. util.selectiveExtend(fields, this.options, options);
  11104. if ('orientation' in options) {
  11105. if (typeof options.orientation === 'string') {
  11106. this.options.orientation = options.orientation;
  11107. }
  11108. else if (typeof options.orientation === 'object' && 'item' in options.orientation) {
  11109. this.options.orientation = options.orientation.item;
  11110. }
  11111. }
  11112. if ('margin' in options) {
  11113. if (typeof options.margin === 'number') {
  11114. this.options.margin.axis = options.margin;
  11115. this.options.margin.item.horizontal = options.margin;
  11116. this.options.margin.item.vertical = options.margin;
  11117. }
  11118. else if (typeof options.margin === 'object') {
  11119. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  11120. if ('item' in options.margin) {
  11121. if (typeof options.margin.item === 'number') {
  11122. this.options.margin.item.horizontal = options.margin.item;
  11123. this.options.margin.item.vertical = options.margin.item;
  11124. }
  11125. else if (typeof options.margin.item === 'object') {
  11126. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  11127. }
  11128. }
  11129. }
  11130. }
  11131. if ('editable' in options) {
  11132. if (typeof options.editable === 'boolean') {
  11133. this.options.editable.updateTime = options.editable;
  11134. this.options.editable.updateGroup = options.editable;
  11135. this.options.editable.add = options.editable;
  11136. this.options.editable.remove = options.editable;
  11137. }
  11138. else if (typeof options.editable === 'object') {
  11139. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable);
  11140. }
  11141. }
  11142. // callback functions
  11143. var addCallback = (function (name) {
  11144. var fn = options[name];
  11145. if (fn) {
  11146. if (!(fn instanceof Function)) {
  11147. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  11148. }
  11149. this.options[name] = fn;
  11150. }
  11151. }).bind(this);
  11152. ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving'].forEach(addCallback);
  11153. // force the itemSet to refresh: options like orientation and margins may be changed
  11154. this.markDirty();
  11155. }
  11156. };
  11157. /**
  11158. * Mark the ItemSet dirty so it will refresh everything with next redraw.
  11159. * Optionally, all items can be marked as dirty and be refreshed.
  11160. * @param {{refreshItems: boolean}} [options]
  11161. */
  11162. ItemSet.prototype.markDirty = function(options) {
  11163. this.groupIds = [];
  11164. this.stackDirty = true;
  11165. if (options && options.refreshItems) {
  11166. util.forEach(this.items, function (item) {
  11167. item.dirty = true;
  11168. if (item.displayed) item.redraw();
  11169. });
  11170. }
  11171. };
  11172. /**
  11173. * Destroy the ItemSet
  11174. */
  11175. ItemSet.prototype.destroy = function() {
  11176. this.hide();
  11177. this.setItems(null);
  11178. this.setGroups(null);
  11179. this.hammer = null;
  11180. this.body = null;
  11181. this.conversion = null;
  11182. };
  11183. /**
  11184. * Hide the component from the DOM
  11185. */
  11186. ItemSet.prototype.hide = function() {
  11187. // remove the frame containing the items
  11188. if (this.dom.frame.parentNode) {
  11189. this.dom.frame.parentNode.removeChild(this.dom.frame);
  11190. }
  11191. // remove the axis with dots
  11192. if (this.dom.axis.parentNode) {
  11193. this.dom.axis.parentNode.removeChild(this.dom.axis);
  11194. }
  11195. // remove the labelset containing all group labels
  11196. if (this.dom.labelSet.parentNode) {
  11197. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  11198. }
  11199. };
  11200. /**
  11201. * Show the component in the DOM (when not already visible).
  11202. * @return {Boolean} changed
  11203. */
  11204. ItemSet.prototype.show = function() {
  11205. // show frame containing the items
  11206. if (!this.dom.frame.parentNode) {
  11207. this.body.dom.center.appendChild(this.dom.frame);
  11208. }
  11209. // show axis with dots
  11210. if (!this.dom.axis.parentNode) {
  11211. this.body.dom.backgroundVertical.appendChild(this.dom.axis);
  11212. }
  11213. // show labelset containing labels
  11214. if (!this.dom.labelSet.parentNode) {
  11215. this.body.dom.left.appendChild(this.dom.labelSet);
  11216. }
  11217. };
  11218. /**
  11219. * Set selected items by their id. Replaces the current selection
  11220. * Unknown id's are silently ignored.
  11221. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  11222. * selected, or a single item id. If ids is undefined
  11223. * or an empty array, all items will be unselected.
  11224. */
  11225. ItemSet.prototype.setSelection = function(ids) {
  11226. var i, ii, id, item;
  11227. if (ids == undefined) ids = [];
  11228. if (!Array.isArray(ids)) ids = [ids];
  11229. // unselect currently selected items
  11230. for (i = 0, ii = this.selection.length; i < ii; i++) {
  11231. id = this.selection[i];
  11232. item = this.items[id];
  11233. if (item) item.unselect();
  11234. }
  11235. // select items
  11236. this.selection = [];
  11237. for (i = 0, ii = ids.length; i < ii; i++) {
  11238. id = ids[i];
  11239. item = this.items[id];
  11240. if (item) {
  11241. this.selection.push(id);
  11242. item.select();
  11243. }
  11244. }
  11245. };
  11246. /**
  11247. * Get the selected items by their id
  11248. * @return {Array} ids The ids of the selected items
  11249. */
  11250. ItemSet.prototype.getSelection = function() {
  11251. return this.selection.concat([]);
  11252. };
  11253. /**
  11254. * Get the id's of the currently visible items.
  11255. * @returns {Array} The ids of the visible items
  11256. */
  11257. ItemSet.prototype.getVisibleItems = function() {
  11258. var range = this.body.range.getRange();
  11259. var left = this.body.util.toScreen(range.start);
  11260. var right = this.body.util.toScreen(range.end);
  11261. var ids = [];
  11262. for (var groupId in this.groups) {
  11263. if (this.groups.hasOwnProperty(groupId)) {
  11264. var group = this.groups[groupId];
  11265. var rawVisibleItems = group.visibleItems;
  11266. // filter the "raw" set with visibleItems into a set which is really
  11267. // visible by pixels
  11268. for (var i = 0; i < rawVisibleItems.length; i++) {
  11269. var item = rawVisibleItems[i];
  11270. // TODO: also check whether visible vertically
  11271. if ((item.left < right) && (item.left + item.width > left)) {
  11272. ids.push(item.id);
  11273. }
  11274. }
  11275. }
  11276. }
  11277. return ids;
  11278. };
  11279. /**
  11280. * Deselect a selected item
  11281. * @param {String | Number} id
  11282. * @private
  11283. */
  11284. ItemSet.prototype._deselect = function(id) {
  11285. var selection = this.selection;
  11286. for (var i = 0, ii = selection.length; i < ii; i++) {
  11287. if (selection[i] == id) { // non-strict comparison!
  11288. selection.splice(i, 1);
  11289. break;
  11290. }
  11291. }
  11292. };
  11293. /**
  11294. * Repaint the component
  11295. * @return {boolean} Returns true if the component is resized
  11296. */
  11297. ItemSet.prototype.redraw = function() {
  11298. var margin = this.options.margin,
  11299. range = this.body.range,
  11300. asSize = util.option.asSize,
  11301. options = this.options,
  11302. orientation = options.orientation,
  11303. resized = false,
  11304. frame = this.dom.frame,
  11305. editable = options.editable.updateTime || options.editable.updateGroup;
  11306. // recalculate absolute position (before redrawing groups)
  11307. this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
  11308. this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
  11309. // update class name
  11310. frame.className = 'itemset' + (editable ? ' editable' : '');
  11311. // reorder the groups (if needed)
  11312. resized = this._orderGroups() || resized;
  11313. // check whether zoomed (in that case we need to re-stack everything)
  11314. // TODO: would be nicer to get this as a trigger from Range
  11315. var visibleInterval = range.end - range.start;
  11316. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth);
  11317. if (zoomed) this.stackDirty = true;
  11318. this.lastVisibleInterval = visibleInterval;
  11319. this.props.lastWidth = this.props.width;
  11320. var restack = this.stackDirty;
  11321. var firstGroup = this._firstGroup();
  11322. var firstMargin = {
  11323. item: margin.item,
  11324. axis: margin.axis
  11325. };
  11326. var nonFirstMargin = {
  11327. item: margin.item,
  11328. axis: margin.item.vertical / 2
  11329. };
  11330. var height = 0;
  11331. var minHeight = margin.axis + margin.item.vertical;
  11332. // redraw the background group
  11333. this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack);
  11334. // redraw all regular groups
  11335. util.forEach(this.groups, function (group) {
  11336. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  11337. var groupResized = group.redraw(range, groupMargin, restack);
  11338. resized = groupResized || resized;
  11339. height += group.height;
  11340. });
  11341. height = Math.max(height, minHeight);
  11342. this.stackDirty = false;
  11343. // update frame height
  11344. frame.style.height = asSize(height);
  11345. // calculate actual size
  11346. this.props.width = frame.offsetWidth;
  11347. this.props.height = height;
  11348. // reposition axis
  11349. this.dom.axis.style.top = asSize((orientation == 'top') ?
  11350. (this.body.domProps.top.height + this.body.domProps.border.top) :
  11351. (this.body.domProps.top.height + this.body.domProps.centerContainer.height));
  11352. this.dom.axis.style.left = '0';
  11353. // check if this component is resized
  11354. resized = this._isResized() || resized;
  11355. return resized;
  11356. };
  11357. /**
  11358. * Get the first group, aligned with the axis
  11359. * @return {Group | null} firstGroup
  11360. * @private
  11361. */
  11362. ItemSet.prototype._firstGroup = function() {
  11363. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  11364. var firstGroupId = this.groupIds[firstGroupIndex];
  11365. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  11366. return firstGroup || null;
  11367. };
  11368. /**
  11369. * Create or delete the group holding all ungrouped items. This group is used when
  11370. * there are no groups specified.
  11371. * @protected
  11372. */
  11373. ItemSet.prototype._updateUngrouped = function() {
  11374. var ungrouped = this.groups[UNGROUPED];
  11375. var background = this.groups[BACKGROUND];
  11376. var item, itemId;
  11377. if (this.groupsData) {
  11378. // remove the group holding all ungrouped items
  11379. if (ungrouped) {
  11380. ungrouped.hide();
  11381. delete this.groups[UNGROUPED];
  11382. for (itemId in this.items) {
  11383. if (this.items.hasOwnProperty(itemId)) {
  11384. item = this.items[itemId];
  11385. item.parent && item.parent.remove(item);
  11386. var groupId = this._getGroupId(item.data);
  11387. var group = this.groups[groupId];
  11388. group && group.add(item) || item.hide();
  11389. }
  11390. }
  11391. }
  11392. }
  11393. else {
  11394. // create a group holding all (unfiltered) items
  11395. if (!ungrouped) {
  11396. var id = null;
  11397. var data = null;
  11398. ungrouped = new Group(id, data, this);
  11399. this.groups[UNGROUPED] = ungrouped;
  11400. for (itemId in this.items) {
  11401. if (this.items.hasOwnProperty(itemId)) {
  11402. item = this.items[itemId];
  11403. ungrouped.add(item);
  11404. }
  11405. }
  11406. ungrouped.show();
  11407. }
  11408. }
  11409. };
  11410. /**
  11411. * Get the element for the labelset
  11412. * @return {HTMLElement} labelSet
  11413. */
  11414. ItemSet.prototype.getLabelSet = function() {
  11415. return this.dom.labelSet;
  11416. };
  11417. /**
  11418. * Set items
  11419. * @param {vis.DataSet | null} items
  11420. */
  11421. ItemSet.prototype.setItems = function(items) {
  11422. var me = this,
  11423. ids,
  11424. oldItemsData = this.itemsData;
  11425. // replace the dataset
  11426. if (!items) {
  11427. this.itemsData = null;
  11428. }
  11429. else if (items instanceof DataSet || items instanceof DataView) {
  11430. this.itemsData = items;
  11431. }
  11432. else {
  11433. throw new TypeError('Data must be an instance of DataSet or DataView');
  11434. }
  11435. if (oldItemsData) {
  11436. // unsubscribe from old dataset
  11437. util.forEach(this.itemListeners, function (callback, event) {
  11438. oldItemsData.off(event, callback);
  11439. });
  11440. // remove all drawn items
  11441. ids = oldItemsData.getIds();
  11442. this._onRemove(ids);
  11443. }
  11444. if (this.itemsData) {
  11445. // subscribe to new dataset
  11446. var id = this.id;
  11447. util.forEach(this.itemListeners, function (callback, event) {
  11448. me.itemsData.on(event, callback, id);
  11449. });
  11450. // add all new items
  11451. ids = this.itemsData.getIds();
  11452. this._onAdd(ids);
  11453. // update the group holding all ungrouped items
  11454. this._updateUngrouped();
  11455. }
  11456. };
  11457. /**
  11458. * Get the current items
  11459. * @returns {vis.DataSet | null}
  11460. */
  11461. ItemSet.prototype.getItems = function() {
  11462. return this.itemsData;
  11463. };
  11464. /**
  11465. * Set groups
  11466. * @param {vis.DataSet} groups
  11467. */
  11468. ItemSet.prototype.setGroups = function(groups) {
  11469. var me = this,
  11470. ids;
  11471. // unsubscribe from current dataset
  11472. if (this.groupsData) {
  11473. util.forEach(this.groupListeners, function (callback, event) {
  11474. me.groupsData.unsubscribe(event, callback);
  11475. });
  11476. // remove all drawn groups
  11477. ids = this.groupsData.getIds();
  11478. this.groupsData = null;
  11479. this._onRemoveGroups(ids); // note: this will cause a redraw
  11480. }
  11481. // replace the dataset
  11482. if (!groups) {
  11483. this.groupsData = null;
  11484. }
  11485. else if (groups instanceof DataSet || groups instanceof DataView) {
  11486. this.groupsData = groups;
  11487. }
  11488. else {
  11489. throw new TypeError('Data must be an instance of DataSet or DataView');
  11490. }
  11491. if (this.groupsData) {
  11492. // subscribe to new dataset
  11493. var id = this.id;
  11494. util.forEach(this.groupListeners, function (callback, event) {
  11495. me.groupsData.on(event, callback, id);
  11496. });
  11497. // draw all ms
  11498. ids = this.groupsData.getIds();
  11499. this._onAddGroups(ids);
  11500. }
  11501. // update the group holding all ungrouped items
  11502. this._updateUngrouped();
  11503. // update the order of all items in each group
  11504. this._order();
  11505. this.body.emitter.emit('change', {queue: true});
  11506. };
  11507. /**
  11508. * Get the current groups
  11509. * @returns {vis.DataSet | null} groups
  11510. */
  11511. ItemSet.prototype.getGroups = function() {
  11512. return this.groupsData;
  11513. };
  11514. /**
  11515. * Remove an item by its id
  11516. * @param {String | Number} id
  11517. */
  11518. ItemSet.prototype.removeItem = function(id) {
  11519. var item = this.itemsData.get(id),
  11520. dataset = this.itemsData.getDataSet();
  11521. if (item) {
  11522. // confirm deletion
  11523. this.options.onRemove(item, function (item) {
  11524. if (item) {
  11525. // remove by id here, it is possible that an item has no id defined
  11526. // itself, so better not delete by the item itself
  11527. dataset.remove(id);
  11528. }
  11529. });
  11530. }
  11531. };
  11532. /**
  11533. * Get the time of an item based on it's data and options.type
  11534. * @param {Object} itemData
  11535. * @returns {string} Returns the type
  11536. * @private
  11537. */
  11538. ItemSet.prototype._getType = function (itemData) {
  11539. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  11540. };
  11541. /**
  11542. * Get the group id for an item
  11543. * @param {Object} itemData
  11544. * @returns {string} Returns the groupId
  11545. * @private
  11546. */
  11547. ItemSet.prototype._getGroupId = function (itemData) {
  11548. var type = this._getType(itemData);
  11549. if (type == 'background' && itemData.group == undefined) {
  11550. return BACKGROUND;
  11551. }
  11552. else {
  11553. return this.groupsData ? itemData.group : UNGROUPED;
  11554. }
  11555. };
  11556. /**
  11557. * Handle updated items
  11558. * @param {Number[]} ids
  11559. * @protected
  11560. */
  11561. ItemSet.prototype._onUpdate = function(ids) {
  11562. var me = this;
  11563. ids.forEach(function (id) {
  11564. var itemData = me.itemsData.get(id, me.itemOptions);
  11565. var item = me.items[id];
  11566. var type = me._getType(itemData);
  11567. var constructor = ItemSet.types[type];
  11568. if (item) {
  11569. // update item
  11570. if (!constructor || !(item instanceof constructor)) {
  11571. // item type has changed, delete the item and recreate it
  11572. me._removeItem(item);
  11573. item = null;
  11574. }
  11575. else {
  11576. me._updateItem(item, itemData);
  11577. }
  11578. }
  11579. if (!item) {
  11580. // create item
  11581. if (constructor) {
  11582. item = new constructor(itemData, me.conversion, me.options);
  11583. item.id = id; // TODO: not so nice setting id afterwards
  11584. me._addItem(item);
  11585. }
  11586. else if (type == 'rangeoverflow') {
  11587. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  11588. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  11589. '.vis.timeline .item.range .content {overflow: visible;}');
  11590. }
  11591. else {
  11592. throw new TypeError('Unknown item type "' + type + '"');
  11593. }
  11594. }
  11595. });
  11596. this._order();
  11597. this.stackDirty = true; // force re-stacking of all items next redraw
  11598. this.body.emitter.emit('change', {queue: true});
  11599. };
  11600. /**
  11601. * Handle added items
  11602. * @param {Number[]} ids
  11603. * @protected
  11604. */
  11605. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  11606. /**
  11607. * Handle removed items
  11608. * @param {Number[]} ids
  11609. * @protected
  11610. */
  11611. ItemSet.prototype._onRemove = function(ids) {
  11612. var count = 0;
  11613. var me = this;
  11614. ids.forEach(function (id) {
  11615. var item = me.items[id];
  11616. if (item) {
  11617. count++;
  11618. me._removeItem(item);
  11619. }
  11620. });
  11621. if (count) {
  11622. // update order
  11623. this._order();
  11624. this.stackDirty = true; // force re-stacking of all items next redraw
  11625. this.body.emitter.emit('change', {queue: true});
  11626. }
  11627. };
  11628. /**
  11629. * Update the order of item in all groups
  11630. * @private
  11631. */
  11632. ItemSet.prototype._order = function() {
  11633. // reorder the items in all groups
  11634. // TODO: optimization: only reorder groups affected by the changed items
  11635. util.forEach(this.groups, function (group) {
  11636. group.order();
  11637. });
  11638. };
  11639. /**
  11640. * Handle updated groups
  11641. * @param {Number[]} ids
  11642. * @private
  11643. */
  11644. ItemSet.prototype._onUpdateGroups = function(ids) {
  11645. this._onAddGroups(ids);
  11646. };
  11647. /**
  11648. * Handle changed groups (added or updated)
  11649. * @param {Number[]} ids
  11650. * @private
  11651. */
  11652. ItemSet.prototype._onAddGroups = function(ids) {
  11653. var me = this;
  11654. ids.forEach(function (id) {
  11655. var groupData = me.groupsData.get(id);
  11656. var group = me.groups[id];
  11657. if (!group) {
  11658. // check for reserved ids
  11659. if (id == UNGROUPED || id == BACKGROUND) {
  11660. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  11661. }
  11662. var groupOptions = Object.create(me.options);
  11663. util.extend(groupOptions, {
  11664. height: null
  11665. });
  11666. group = new Group(id, groupData, me);
  11667. me.groups[id] = group;
  11668. // add items with this groupId to the new group
  11669. for (var itemId in me.items) {
  11670. if (me.items.hasOwnProperty(itemId)) {
  11671. var item = me.items[itemId];
  11672. if (item.data.group == id) {
  11673. group.add(item);
  11674. }
  11675. }
  11676. }
  11677. group.order();
  11678. group.show();
  11679. }
  11680. else {
  11681. // update group
  11682. group.setData(groupData);
  11683. }
  11684. });
  11685. this.body.emitter.emit('change', {queue: true});
  11686. };
  11687. /**
  11688. * Handle removed groups
  11689. * @param {Number[]} ids
  11690. * @private
  11691. */
  11692. ItemSet.prototype._onRemoveGroups = function(ids) {
  11693. var groups = this.groups;
  11694. ids.forEach(function (id) {
  11695. var group = groups[id];
  11696. if (group) {
  11697. group.hide();
  11698. delete groups[id];
  11699. }
  11700. });
  11701. this.markDirty();
  11702. this.body.emitter.emit('change', {queue: true});
  11703. };
  11704. /**
  11705. * Reorder the groups if needed
  11706. * @return {boolean} changed
  11707. * @private
  11708. */
  11709. ItemSet.prototype._orderGroups = function () {
  11710. if (this.groupsData) {
  11711. // reorder the groups
  11712. var groupIds = this.groupsData.getIds({
  11713. order: this.options.groupOrder
  11714. });
  11715. var changed = !util.equalArray(groupIds, this.groupIds);
  11716. if (changed) {
  11717. // hide all groups, removes them from the DOM
  11718. var groups = this.groups;
  11719. groupIds.forEach(function (groupId) {
  11720. groups[groupId].hide();
  11721. });
  11722. // show the groups again, attach them to the DOM in correct order
  11723. groupIds.forEach(function (groupId) {
  11724. groups[groupId].show();
  11725. });
  11726. this.groupIds = groupIds;
  11727. }
  11728. return changed;
  11729. }
  11730. else {
  11731. return false;
  11732. }
  11733. };
  11734. /**
  11735. * Add a new item
  11736. * @param {Item} item
  11737. * @private
  11738. */
  11739. ItemSet.prototype._addItem = function(item) {
  11740. this.items[item.id] = item;
  11741. // add to group
  11742. var groupId = this._getGroupId(item.data);
  11743. var group = this.groups[groupId];
  11744. if (group) group.add(item);
  11745. };
  11746. /**
  11747. * Update an existing item
  11748. * @param {Item} item
  11749. * @param {Object} itemData
  11750. * @private
  11751. */
  11752. ItemSet.prototype._updateItem = function(item, itemData) {
  11753. var oldGroupId = item.data.group;
  11754. // update the items data (will redraw the item when displayed)
  11755. item.setData(itemData);
  11756. // update group
  11757. if (oldGroupId != item.data.group) {
  11758. var oldGroup = this.groups[oldGroupId];
  11759. if (oldGroup) oldGroup.remove(item);
  11760. var groupId = this._getGroupId(item.data);
  11761. var group = this.groups[groupId];
  11762. if (group) group.add(item);
  11763. }
  11764. };
  11765. /**
  11766. * Delete an item from the ItemSet: remove it from the DOM, from the map
  11767. * with items, and from the map with visible items, and from the selection
  11768. * @param {Item} item
  11769. * @private
  11770. */
  11771. ItemSet.prototype._removeItem = function(item) {
  11772. // remove from DOM
  11773. item.hide();
  11774. // remove from items
  11775. delete this.items[item.id];
  11776. // remove from selection
  11777. var index = this.selection.indexOf(item.id);
  11778. if (index != -1) this.selection.splice(index, 1);
  11779. // remove from group
  11780. item.parent && item.parent.remove(item);
  11781. };
  11782. /**
  11783. * Create an array containing all items being a range (having an end date)
  11784. * @param array
  11785. * @returns {Array}
  11786. * @private
  11787. */
  11788. ItemSet.prototype._constructByEndArray = function(array) {
  11789. var endArray = [];
  11790. for (var i = 0; i < array.length; i++) {
  11791. if (array[i] instanceof RangeItem) {
  11792. endArray.push(array[i]);
  11793. }
  11794. }
  11795. return endArray;
  11796. };
  11797. /**
  11798. * Register the clicked item on touch, before dragStart is initiated.
  11799. *
  11800. * dragStart is initiated from a mousemove event, which can have left the item
  11801. * already resulting in an item == null
  11802. *
  11803. * @param {Event} event
  11804. * @private
  11805. */
  11806. ItemSet.prototype._onTouch = function (event) {
  11807. // store the touched item, used in _onDragStart
  11808. this.touchParams.item = this.itemFromTarget(event);
  11809. };
  11810. /**
  11811. * Start dragging the selected events
  11812. * @param {Event} event
  11813. * @private
  11814. */
  11815. ItemSet.prototype._onDragStart = function (event) {
  11816. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  11817. return;
  11818. }
  11819. var item = this.touchParams.item || null;
  11820. var me = this;
  11821. var props;
  11822. if (item && item.selected) {
  11823. var dragLeftItem = event.target.dragLeftItem;
  11824. var dragRightItem = event.target.dragRightItem;
  11825. if (dragLeftItem) {
  11826. props = {
  11827. item: dragLeftItem,
  11828. initialX: event.gesture.center.pageX,
  11829. dragLeft: true,
  11830. data: util.extend({}, item.data) // clone the items data
  11831. };
  11832. this.touchParams.itemProps = [props];
  11833. }
  11834. else if (dragRightItem) {
  11835. props = {
  11836. item: dragRightItem,
  11837. initialX: event.gesture.center.pageX,
  11838. dragRight: true,
  11839. data: util.extend({}, item.data) // clone the items data
  11840. };
  11841. this.touchParams.itemProps = [props];
  11842. }
  11843. else {
  11844. this.touchParams.itemProps = this.getSelection().map(function (id) {
  11845. var item = me.items[id];
  11846. var props = {
  11847. item: item,
  11848. initialX: event.gesture.center.pageX,
  11849. data: util.extend({}, item.data) // clone the items data
  11850. };
  11851. return props;
  11852. });
  11853. }
  11854. event.stopPropagation();
  11855. }
  11856. else if (this.options.editable.add && event.gesture.srcEvent.ctrlKey) {
  11857. // create a new range item when dragging with ctrl key down
  11858. this._onDragStartAddItem(event);
  11859. }
  11860. };
  11861. /**
  11862. * Start creating a new range item by dragging.
  11863. * @param {Event} event
  11864. * @private
  11865. */
  11866. ItemSet.prototype._onDragStartAddItem = function (event) {
  11867. var snap = this.options.snap || null;
  11868. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  11869. var x = event.gesture.center.pageX - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  11870. var time = this.body.util.toTime(x);
  11871. var scale = this.body.util.getScale();
  11872. var step = this.body.util.getStep();
  11873. var start = snap ? snap(time, scale, step) : start;
  11874. var end = start;
  11875. var itemData = {
  11876. type: 'range',
  11877. start: start,
  11878. end: end,
  11879. content: 'new item'
  11880. };
  11881. var id = util.randomUUID();
  11882. itemData[this.itemsData._fieldId] = id;
  11883. var group = this.groupFromTarget(event);
  11884. if (group) {
  11885. itemData.group = group.groupId;
  11886. }
  11887. var newItem = new RangeItem(itemData, this.conversion, this.options);
  11888. newItem.id = id; // TODO: not so nice setting id afterwards
  11889. newItem.data = itemData;
  11890. this._addItem(newItem);
  11891. var props = {
  11892. item: newItem,
  11893. dragRight: true,
  11894. initialX: event.gesture.center.pageX,
  11895. data: util.extend({}, itemData)
  11896. };
  11897. this.touchParams.itemProps = [props];
  11898. event.stopPropagation();
  11899. };
  11900. /**
  11901. * Drag selected items
  11902. * @param {Event} event
  11903. * @private
  11904. */
  11905. ItemSet.prototype._onDrag = function (event) {
  11906. event.preventDefault();
  11907. if (this.touchParams.itemProps) {
  11908. event.stopPropagation();
  11909. var me = this;
  11910. var snap = this.options.snap || null;
  11911. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  11912. var scale = this.body.util.getScale();
  11913. var step = this.body.util.getStep();
  11914. // move
  11915. this.touchParams.itemProps.forEach(function (props) {
  11916. var current = me.body.util.toTime(event.gesture.center.pageX - xOffset);
  11917. var initial = me.body.util.toTime(props.initialX - xOffset);
  11918. var offset = current - initial;
  11919. var itemData = util.extend({}, props.item.data); // clone the data
  11920. if (me.options.editable.updateTime) {
  11921. if (props.dragLeft) {
  11922. // drag left side of a range item
  11923. if (itemData.start != undefined) {
  11924. var initialStart = util.convert(props.data.start, 'Date');
  11925. var start = new Date(initialStart.valueOf() + offset);
  11926. itemData.start = snap ? snap(start, scale, step) : start;
  11927. }
  11928. }
  11929. else if (props.dragRight) {
  11930. // drag right side of a range item
  11931. if (itemData.end != undefined) {
  11932. var initialEnd = util.convert(props.data.end, 'Date');
  11933. var end = new Date(initialEnd.valueOf() + offset);
  11934. itemData.end = snap ? snap(end, scale, step) : end;
  11935. }
  11936. }
  11937. else {
  11938. // drag both start and end
  11939. if (itemData.start != undefined) {
  11940. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  11941. var start = new Date(initialStart + offset);
  11942. if (itemData.end != undefined) {
  11943. var initialEnd = util.convert(props.data.end, 'Date');
  11944. var duration = initialEnd.valueOf() - initialStart.valueOf();
  11945. itemData.start = snap ? snap(start, scale, step) : start;
  11946. itemData.end = new Date(itemData.start.valueOf() + duration);
  11947. }
  11948. else {
  11949. itemData.start = snap ? snap(start, scale, step) : start;
  11950. }
  11951. }
  11952. }
  11953. }
  11954. if (me.options.editable.updateGroup && (!props.dragLeft && !props.dragRight)) {
  11955. if (itemData.group != undefined) {
  11956. // drag from one group to another
  11957. var group = me.groupFromTarget(event);
  11958. if (group) {
  11959. itemData.group = group.groupId;
  11960. }
  11961. }
  11962. }
  11963. // confirm moving the item
  11964. me.options.onMoving(itemData, function (itemData) {
  11965. if (itemData) {
  11966. props.item.setData(itemData);
  11967. }
  11968. });
  11969. });
  11970. this.stackDirty = true; // force re-stacking of all items next redraw
  11971. this.body.emitter.emit('change');
  11972. }
  11973. };
  11974. /**
  11975. * Move an item to another group
  11976. * @param {Item} item
  11977. * @param {String | Number} groupId
  11978. * @private
  11979. */
  11980. ItemSet.prototype._moveToGroup = function(item, groupId) {
  11981. var group = this.groups[groupId];
  11982. if (group && group.groupId != item.data.group) {
  11983. var oldGroup = item.parent;
  11984. oldGroup.remove(item);
  11985. oldGroup.order();
  11986. group.add(item);
  11987. group.order();
  11988. item.data.group = group.groupId;
  11989. }
  11990. };
  11991. /**
  11992. * End of dragging selected items
  11993. * @param {Event} event
  11994. * @private
  11995. */
  11996. ItemSet.prototype._onDragEnd = function (event) {
  11997. event.preventDefault();
  11998. if (this.touchParams.itemProps) {
  11999. event.stopPropagation();
  12000. // prepare a change set for the changed items
  12001. var changes = [];
  12002. var me = this;
  12003. var dataset = this.itemsData.getDataSet();
  12004. var itemProps = this.touchParams.itemProps ;
  12005. this.touchParams.itemProps = null;
  12006. itemProps.forEach(function (props) {
  12007. var id = props.item.id;
  12008. var exists = me.itemsData.get(id, me.itemOptions) != null;
  12009. if (!exists) {
  12010. // add a new item
  12011. me.options.onAdd(props.item.data, function (itemData) {
  12012. me._removeItem(props.item); // remove temporary item
  12013. if (itemData) {
  12014. me.itemsData.getDataSet().add(itemData);
  12015. }
  12016. // force re-stacking of all items next redraw
  12017. me.stackDirty = true;
  12018. me.body.emitter.emit('change');
  12019. });
  12020. }
  12021. else {
  12022. // update existing item
  12023. var itemData = util.extend({}, props.item.data); // clone the data
  12024. me.options.onMove(itemData, function (itemData) {
  12025. if (itemData) {
  12026. // apply changes
  12027. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  12028. changes.push(itemData);
  12029. }
  12030. else {
  12031. // restore original values
  12032. props.item.setData(props.data);
  12033. me.stackDirty = true; // force re-stacking of all items next redraw
  12034. me.body.emitter.emit('change');
  12035. }
  12036. });
  12037. }
  12038. });
  12039. // apply the changes to the data (if there are changes)
  12040. if (changes.length) {
  12041. dataset.update(changes);
  12042. }
  12043. }
  12044. };
  12045. /**
  12046. * Handle selecting/deselecting an item when tapping it
  12047. * @param {Event} event
  12048. * @private
  12049. */
  12050. ItemSet.prototype._onSelectItem = function (event) {
  12051. if (!this.options.selectable) return;
  12052. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  12053. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  12054. if (ctrlKey || shiftKey) {
  12055. this._onMultiSelectItem(event);
  12056. return;
  12057. }
  12058. var oldSelection = this.getSelection();
  12059. var item = this.itemFromTarget(event);
  12060. var selection = item ? [item.id] : [];
  12061. this.setSelection(selection);
  12062. var newSelection = this.getSelection();
  12063. // emit a select event,
  12064. // except when old selection is empty and new selection is still empty
  12065. if (newSelection.length > 0 || oldSelection.length > 0) {
  12066. this.body.emitter.emit('select', {
  12067. items: newSelection
  12068. });
  12069. }
  12070. };
  12071. /**
  12072. * Handle creation and updates of an item on double tap
  12073. * @param event
  12074. * @private
  12075. */
  12076. ItemSet.prototype._onAddItem = function (event) {
  12077. if (!this.options.selectable) return;
  12078. if (!this.options.editable.add) return;
  12079. var me = this,
  12080. snap = this.options.snap || null,
  12081. item = this.itemFromTarget(event);
  12082. if (item) {
  12083. // update item
  12084. // execute async handler to update the item (or cancel it)
  12085. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  12086. this.options.onUpdate(itemData, function (itemData) {
  12087. if (itemData) {
  12088. me.itemsData.getDataSet().update(itemData);
  12089. }
  12090. });
  12091. }
  12092. else {
  12093. // add item
  12094. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  12095. var x = event.gesture.center.pageX - xAbs;
  12096. var start = this.body.util.toTime(x);
  12097. var scale = this.body.util.getScale();
  12098. var step = this.body.util.getStep();
  12099. var newItem = {
  12100. start: snap ? snap(start, scale, step) : start,
  12101. content: 'new item'
  12102. };
  12103. // when default type is a range, add a default end date to the new item
  12104. if (this.options.type === 'range') {
  12105. var end = this.body.util.toTime(x + this.props.width / 5);
  12106. newItem.end = snap ? snap(end, scale, step) : end;
  12107. }
  12108. newItem[this.itemsData._fieldId] = util.randomUUID();
  12109. var group = this.groupFromTarget(event);
  12110. if (group) {
  12111. newItem.group = group.groupId;
  12112. }
  12113. // execute async handler to customize (or cancel) adding an item
  12114. this.options.onAdd(newItem, function (item) {
  12115. if (item) {
  12116. me.itemsData.getDataSet().add(item);
  12117. // TODO: need to trigger a redraw?
  12118. }
  12119. });
  12120. }
  12121. };
  12122. /**
  12123. * Handle selecting/deselecting multiple items when holding an item
  12124. * @param {Event} event
  12125. * @private
  12126. */
  12127. ItemSet.prototype._onMultiSelectItem = function (event) {
  12128. if (!this.options.selectable) return;
  12129. var selection,
  12130. item = this.itemFromTarget(event);
  12131. if (item) {
  12132. // multi select items
  12133. selection = this.getSelection(); // current selection
  12134. var shiftKey = event.gesture.touches[0] && event.gesture.touches[0].shiftKey || false;
  12135. if (shiftKey) {
  12136. // select all items between the old selection and the tapped item
  12137. // determine the selection range
  12138. selection.push(item.id);
  12139. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  12140. // select all items within the selection range
  12141. selection = [];
  12142. for (var id in this.items) {
  12143. if (this.items.hasOwnProperty(id)) {
  12144. var _item = this.items[id];
  12145. var start = _item.data.start;
  12146. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  12147. if (start >= range.min &&
  12148. end <= range.max &&
  12149. !(_item instanceof BackgroundItem)) {
  12150. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  12151. }
  12152. }
  12153. }
  12154. }
  12155. else {
  12156. // add/remove this item from the current selection
  12157. var index = selection.indexOf(item.id);
  12158. if (index == -1) {
  12159. // item is not yet selected -> select it
  12160. selection.push(item.id);
  12161. }
  12162. else {
  12163. // item is already selected -> deselect it
  12164. selection.splice(index, 1);
  12165. }
  12166. }
  12167. this.setSelection(selection);
  12168. this.body.emitter.emit('select', {
  12169. items: this.getSelection()
  12170. });
  12171. }
  12172. };
  12173. /**
  12174. * Calculate the time range of a list of items
  12175. * @param {Array.<Object>} itemsData
  12176. * @return {{min: Date, max: Date}} Returns the range of the provided items
  12177. * @private
  12178. */
  12179. ItemSet._getItemRange = function(itemsData) {
  12180. var max = null;
  12181. var min = null;
  12182. itemsData.forEach(function (data) {
  12183. if (min == null || data.start < min) {
  12184. min = data.start;
  12185. }
  12186. if (data.end != undefined) {
  12187. if (max == null || data.end > max) {
  12188. max = data.end;
  12189. }
  12190. }
  12191. else {
  12192. if (max == null || data.start > max) {
  12193. max = data.start;
  12194. }
  12195. }
  12196. });
  12197. return {
  12198. min: min,
  12199. max: max
  12200. }
  12201. };
  12202. /**
  12203. * Find an item from an event target:
  12204. * searches for the attribute 'timeline-item' in the event target's element tree
  12205. * @param {Event} event
  12206. * @return {Item | null} item
  12207. */
  12208. ItemSet.prototype.itemFromTarget = function(event) {
  12209. var target = event.target;
  12210. while (target) {
  12211. if (target.hasOwnProperty('timeline-item')) {
  12212. return target['timeline-item'];
  12213. }
  12214. target = target.parentNode;
  12215. }
  12216. return null;
  12217. };
  12218. /**
  12219. * Find the Group from an event target:
  12220. * searches for the attribute 'timeline-group' in the event target's element tree
  12221. * @param {Event} event
  12222. * @return {Group | null} group
  12223. */
  12224. ItemSet.prototype.groupFromTarget = function(event) {
  12225. var pageY = event.gesture ? event.gesture.center.pageY : event.pageY;
  12226. for (var i = 0; i < this.groupIds.length; i++) {
  12227. var groupId = this.groupIds[i];
  12228. var group = this.groups[groupId];
  12229. var foreground = group.dom.foreground;
  12230. var top = util.getAbsoluteTop(foreground);
  12231. if (pageY > top && pageY < top + foreground.offsetHeight) {
  12232. return group;
  12233. }
  12234. if (this.options.orientation === 'top') {
  12235. if (i === this.groupIds.length - 1 && pageY > top) {
  12236. return group;
  12237. }
  12238. }
  12239. else {
  12240. if (i === 0 && pageY < top + foreground.offset) {
  12241. return group;
  12242. }
  12243. }
  12244. }
  12245. return null;
  12246. };
  12247. /**
  12248. * Find the ItemSet from an event target:
  12249. * searches for the attribute 'timeline-itemset' in the event target's element tree
  12250. * @param {Event} event
  12251. * @return {ItemSet | null} item
  12252. */
  12253. ItemSet.itemSetFromTarget = function(event) {
  12254. var target = event.target;
  12255. while (target) {
  12256. if (target.hasOwnProperty('timeline-itemset')) {
  12257. return target['timeline-itemset'];
  12258. }
  12259. target = target.parentNode;
  12260. }
  12261. return null;
  12262. };
  12263. module.exports = ItemSet;
  12264. /***/ },
  12265. /* 33 */
  12266. /***/ function(module, exports, __webpack_require__) {
  12267. var util = __webpack_require__(1);
  12268. var DOMutil = __webpack_require__(2);
  12269. var Component = __webpack_require__(25);
  12270. /**
  12271. * Legend for Graph2d
  12272. */
  12273. function Legend(body, options, side, linegraphOptions) {
  12274. this.body = body;
  12275. this.defaultOptions = {
  12276. enabled: true,
  12277. icons: true,
  12278. iconSize: 20,
  12279. iconSpacing: 6,
  12280. left: {
  12281. visible: true,
  12282. position: 'top-left' // top/bottom - left,center,right
  12283. },
  12284. right: {
  12285. visible: true,
  12286. position: 'top-left' // top/bottom - left,center,right
  12287. }
  12288. }
  12289. this.side = side;
  12290. this.options = util.extend({},this.defaultOptions);
  12291. this.linegraphOptions = linegraphOptions;
  12292. this.svgElements = {};
  12293. this.dom = {};
  12294. this.groups = {};
  12295. this.amountOfGroups = 0;
  12296. this._create();
  12297. this.setOptions(options);
  12298. }
  12299. Legend.prototype = new Component();
  12300. Legend.prototype.clear = function() {
  12301. this.groups = {};
  12302. this.amountOfGroups = 0;
  12303. }
  12304. Legend.prototype.addGroup = function(label, graphOptions) {
  12305. if (!this.groups.hasOwnProperty(label)) {
  12306. this.groups[label] = graphOptions;
  12307. }
  12308. this.amountOfGroups += 1;
  12309. };
  12310. Legend.prototype.updateGroup = function(label, graphOptions) {
  12311. this.groups[label] = graphOptions;
  12312. };
  12313. Legend.prototype.removeGroup = function(label) {
  12314. if (this.groups.hasOwnProperty(label)) {
  12315. delete this.groups[label];
  12316. this.amountOfGroups -= 1;
  12317. }
  12318. };
  12319. Legend.prototype._create = function() {
  12320. this.dom.frame = document.createElement('div');
  12321. this.dom.frame.className = 'legend';
  12322. this.dom.frame.style.position = "absolute";
  12323. this.dom.frame.style.top = "10px";
  12324. this.dom.frame.style.display = "block";
  12325. this.dom.textArea = document.createElement('div');
  12326. this.dom.textArea.className = 'legendText';
  12327. this.dom.textArea.style.position = "relative";
  12328. this.dom.textArea.style.top = "0px";
  12329. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  12330. this.svg.style.position = 'absolute';
  12331. this.svg.style.top = 0 +'px';
  12332. this.svg.style.width = this.options.iconSize + 5 + 'px';
  12333. this.svg.style.height = '100%';
  12334. this.dom.frame.appendChild(this.svg);
  12335. this.dom.frame.appendChild(this.dom.textArea);
  12336. };
  12337. /**
  12338. * Hide the component from the DOM
  12339. */
  12340. Legend.prototype.hide = function() {
  12341. // remove the frame containing the items
  12342. if (this.dom.frame.parentNode) {
  12343. this.dom.frame.parentNode.removeChild(this.dom.frame);
  12344. }
  12345. };
  12346. /**
  12347. * Show the component in the DOM (when not already visible).
  12348. * @return {Boolean} changed
  12349. */
  12350. Legend.prototype.show = function() {
  12351. // show frame containing the items
  12352. if (!this.dom.frame.parentNode) {
  12353. this.body.dom.center.appendChild(this.dom.frame);
  12354. }
  12355. };
  12356. Legend.prototype.setOptions = function(options) {
  12357. var fields = ['enabled','orientation','icons','left','right'];
  12358. util.selectiveDeepExtend(fields, this.options, options);
  12359. };
  12360. Legend.prototype.redraw = function() {
  12361. var activeGroups = 0;
  12362. for (var groupId in this.groups) {
  12363. if (this.groups.hasOwnProperty(groupId)) {
  12364. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  12365. activeGroups++;
  12366. }
  12367. }
  12368. }
  12369. if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) {
  12370. this.hide();
  12371. }
  12372. else {
  12373. this.show();
  12374. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') {
  12375. this.dom.frame.style.left = '4px';
  12376. this.dom.frame.style.textAlign = "left";
  12377. this.dom.textArea.style.textAlign = "left";
  12378. this.dom.textArea.style.left = (this.options.iconSize + 15) + 'px';
  12379. this.dom.textArea.style.right = '';
  12380. this.svg.style.left = 0 +'px';
  12381. this.svg.style.right = '';
  12382. }
  12383. else {
  12384. this.dom.frame.style.right = '4px';
  12385. this.dom.frame.style.textAlign = "right";
  12386. this.dom.textArea.style.textAlign = "right";
  12387. this.dom.textArea.style.right = (this.options.iconSize + 15) + 'px';
  12388. this.dom.textArea.style.left = '';
  12389. this.svg.style.right = 0 +'px';
  12390. this.svg.style.left = '';
  12391. }
  12392. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') {
  12393. this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px';
  12394. this.dom.frame.style.bottom = '';
  12395. }
  12396. else {
  12397. var scrollableHeight = this.body.domProps.center.height - this.body.domProps.centerContainer.height;
  12398. this.dom.frame.style.bottom = 4 + scrollableHeight + Number(this.body.dom.center.style.top.replace("px","")) + 'px';
  12399. this.dom.frame.style.top = '';
  12400. }
  12401. if (this.options.icons == false) {
  12402. this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px';
  12403. this.dom.textArea.style.right = '';
  12404. this.dom.textArea.style.left = '';
  12405. this.svg.style.width = '0px';
  12406. }
  12407. else {
  12408. this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px'
  12409. this.drawLegendIcons();
  12410. }
  12411. var content = '';
  12412. for (var groupId in this.groups) {
  12413. if (this.groups.hasOwnProperty(groupId)) {
  12414. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  12415. content += this.groups[groupId].content + '<br />';
  12416. }
  12417. }
  12418. }
  12419. this.dom.textArea.innerHTML = content;
  12420. this.dom.textArea.style.lineHeight = ((0.75 * this.options.iconSize) + this.options.iconSpacing) + 'px';
  12421. }
  12422. };
  12423. Legend.prototype.drawLegendIcons = function() {
  12424. if (this.dom.frame.parentNode) {
  12425. DOMutil.prepareElements(this.svgElements);
  12426. var padding = window.getComputedStyle(this.dom.frame).paddingTop;
  12427. var iconOffset = Number(padding.replace('px',''));
  12428. var x = iconOffset;
  12429. var iconWidth = this.options.iconSize;
  12430. var iconHeight = 0.75 * this.options.iconSize;
  12431. var y = iconOffset + 0.5 * iconHeight + 3;
  12432. this.svg.style.width = iconWidth + 5 + iconOffset + 'px';
  12433. for (var groupId in this.groups) {
  12434. if (this.groups.hasOwnProperty(groupId)) {
  12435. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  12436. this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight);
  12437. y += iconHeight + this.options.iconSpacing;
  12438. }
  12439. }
  12440. }
  12441. DOMutil.cleanupElements(this.svgElements);
  12442. }
  12443. };
  12444. module.exports = Legend;
  12445. /***/ },
  12446. /* 34 */
  12447. /***/ function(module, exports, __webpack_require__) {
  12448. var util = __webpack_require__(1);
  12449. var DOMutil = __webpack_require__(2);
  12450. var DataSet = __webpack_require__(3);
  12451. var DataView = __webpack_require__(4);
  12452. var Component = __webpack_require__(25);
  12453. var DataAxis = __webpack_require__(28);
  12454. var GraphGroup = __webpack_require__(29);
  12455. var Legend = __webpack_require__(33);
  12456. var BarGraphFunctions = __webpack_require__(50);
  12457. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  12458. /**
  12459. * This is the constructor of the LineGraph. It requires a Timeline body and options.
  12460. *
  12461. * @param body
  12462. * @param options
  12463. * @constructor
  12464. */
  12465. function LineGraph(body, options) {
  12466. this.id = util.randomUUID();
  12467. this.body = body;
  12468. this.defaultOptions = {
  12469. yAxisOrientation: 'left',
  12470. defaultGroup: 'default',
  12471. sort: true,
  12472. sampling: true,
  12473. graphHeight: '400px',
  12474. shaded: {
  12475. enabled: false,
  12476. orientation: 'bottom' // top, bottom
  12477. },
  12478. style: 'line', // line, bar
  12479. barChart: {
  12480. width: 50,
  12481. handleOverlap: 'overlap',
  12482. align: 'center' // left, center, right
  12483. },
  12484. catmullRom: {
  12485. enabled: true,
  12486. parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  12487. alpha: 0.5
  12488. },
  12489. drawPoints: {
  12490. enabled: true,
  12491. size: 6,
  12492. style: 'square' // square, circle
  12493. },
  12494. dataAxis: {
  12495. showMinorLabels: true,
  12496. showMajorLabels: true,
  12497. icons: false,
  12498. width: '40px',
  12499. visible: true,
  12500. alignZeros: true,
  12501. customRange: {
  12502. left: {min:undefined, max:undefined},
  12503. right: {min:undefined, max:undefined}
  12504. }
  12505. //, these options are not set by default, but this shows the format they will be in
  12506. //format: {
  12507. // left: {decimals: 2},
  12508. // right: {decimals: 2}
  12509. //},
  12510. //title: {
  12511. // left: {
  12512. // text: 'left',
  12513. // style: 'color:black;'
  12514. // },
  12515. // right: {
  12516. // text: 'right',
  12517. // style: 'color:black;'
  12518. // }
  12519. //}
  12520. },
  12521. legend: {
  12522. enabled: false,
  12523. icons: true,
  12524. left: {
  12525. visible: true,
  12526. position: 'top-left' // top/bottom - left,right
  12527. },
  12528. right: {
  12529. visible: true,
  12530. position: 'top-right' // top/bottom - left,right
  12531. }
  12532. },
  12533. groups: {
  12534. visibility: {}
  12535. }
  12536. };
  12537. // options is shared by this ItemSet and all its items
  12538. this.options = util.extend({}, this.defaultOptions);
  12539. this.dom = {};
  12540. this.props = {};
  12541. this.hammer = null;
  12542. this.groups = {};
  12543. this.abortedGraphUpdate = false;
  12544. this.updateSVGheight = false;
  12545. this.updateSVGheightOnResize = false;
  12546. var me = this;
  12547. this.itemsData = null; // DataSet
  12548. this.groupsData = null; // DataSet
  12549. // listeners for the DataSet of the items
  12550. this.itemListeners = {
  12551. 'add': function (event, params, senderId) {
  12552. me._onAdd(params.items);
  12553. },
  12554. 'update': function (event, params, senderId) {
  12555. me._onUpdate(params.items);
  12556. },
  12557. 'remove': function (event, params, senderId) {
  12558. me._onRemove(params.items);
  12559. }
  12560. };
  12561. // listeners for the DataSet of the groups
  12562. this.groupListeners = {
  12563. 'add': function (event, params, senderId) {
  12564. me._onAddGroups(params.items);
  12565. },
  12566. 'update': function (event, params, senderId) {
  12567. me._onUpdateGroups(params.items);
  12568. },
  12569. 'remove': function (event, params, senderId) {
  12570. me._onRemoveGroups(params.items);
  12571. }
  12572. };
  12573. this.items = {}; // object with an Item for every data item
  12574. this.selection = []; // list with the ids of all selected nodes
  12575. this.lastStart = this.body.range.start;
  12576. this.touchParams = {}; // stores properties while dragging
  12577. this.svgElements = {};
  12578. this.setOptions(options);
  12579. this.groupsUsingDefaultStyles = [0];
  12580. this.COUNTER = 0;
  12581. this.body.emitter.on('rangechanged', function() {
  12582. me.lastStart = me.body.range.start;
  12583. me.svg.style.left = util.option.asSize(-me.props.width);
  12584. me.redraw.call(me,true);
  12585. });
  12586. // create the HTML DOM
  12587. this._create();
  12588. this.framework = {svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups};
  12589. this.body.emitter.emit('change');
  12590. }
  12591. LineGraph.prototype = new Component();
  12592. /**
  12593. * Create the HTML DOM for the ItemSet
  12594. */
  12595. LineGraph.prototype._create = function(){
  12596. var frame = document.createElement('div');
  12597. frame.className = 'LineGraph';
  12598. this.dom.frame = frame;
  12599. // create svg element for graph drawing.
  12600. this.svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
  12601. this.svg.style.position = 'relative';
  12602. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  12603. this.svg.style.display = 'block';
  12604. frame.appendChild(this.svg);
  12605. // data axis
  12606. this.options.dataAxis.orientation = 'left';
  12607. this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  12608. this.options.dataAxis.orientation = 'right';
  12609. this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  12610. delete this.options.dataAxis.orientation;
  12611. // legends
  12612. this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups);
  12613. this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups);
  12614. this.show();
  12615. };
  12616. /**
  12617. * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
  12618. * @param {object} options
  12619. */
  12620. LineGraph.prototype.setOptions = function(options) {
  12621. if (options) {
  12622. var fields = ['sampling','defaultGroup','height','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort','groups'];
  12623. if (options.graphHeight === undefined && options.height !== undefined && this.body.domProps.centerContainer.height !== undefined) {
  12624. this.updateSVGheight = true;
  12625. this.updateSVGheightOnResize = true;
  12626. }
  12627. else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) {
  12628. if (parseInt((options.graphHeight + '').replace("px",'')) < this.body.domProps.centerContainer.height) {
  12629. this.updateSVGheight = true;
  12630. }
  12631. }
  12632. util.selectiveDeepExtend(fields, this.options, options);
  12633. util.mergeOptions(this.options, options,'catmullRom');
  12634. util.mergeOptions(this.options, options,'drawPoints');
  12635. util.mergeOptions(this.options, options,'shaded');
  12636. util.mergeOptions(this.options, options,'legend');
  12637. if (options.catmullRom) {
  12638. if (typeof options.catmullRom == 'object') {
  12639. if (options.catmullRom.parametrization) {
  12640. if (options.catmullRom.parametrization == 'uniform') {
  12641. this.options.catmullRom.alpha = 0;
  12642. }
  12643. else if (options.catmullRom.parametrization == 'chordal') {
  12644. this.options.catmullRom.alpha = 1.0;
  12645. }
  12646. else {
  12647. this.options.catmullRom.parametrization = 'centripetal';
  12648. this.options.catmullRom.alpha = 0.5;
  12649. }
  12650. }
  12651. }
  12652. }
  12653. if (this.yAxisLeft) {
  12654. if (options.dataAxis !== undefined) {
  12655. this.yAxisLeft.setOptions(this.options.dataAxis);
  12656. this.yAxisRight.setOptions(this.options.dataAxis);
  12657. }
  12658. }
  12659. if (this.legendLeft) {
  12660. if (options.legend !== undefined) {
  12661. this.legendLeft.setOptions(this.options.legend);
  12662. this.legendRight.setOptions(this.options.legend);
  12663. }
  12664. }
  12665. if (this.groups.hasOwnProperty(UNGROUPED)) {
  12666. this.groups[UNGROUPED].setOptions(options);
  12667. }
  12668. }
  12669. // this is used to redraw the graph if the visibility of the groups is changed.
  12670. if (this.dom.frame) {
  12671. this.redraw(true);
  12672. }
  12673. };
  12674. /**
  12675. * Hide the component from the DOM
  12676. */
  12677. LineGraph.prototype.hide = function() {
  12678. // remove the frame containing the items
  12679. if (this.dom.frame.parentNode) {
  12680. this.dom.frame.parentNode.removeChild(this.dom.frame);
  12681. }
  12682. };
  12683. /**
  12684. * Show the component in the DOM (when not already visible).
  12685. * @return {Boolean} changed
  12686. */
  12687. LineGraph.prototype.show = function() {
  12688. // show frame containing the items
  12689. if (!this.dom.frame.parentNode) {
  12690. this.body.dom.center.appendChild(this.dom.frame);
  12691. }
  12692. };
  12693. /**
  12694. * Set items
  12695. * @param {vis.DataSet | null} items
  12696. */
  12697. LineGraph.prototype.setItems = function(items) {
  12698. var me = this,
  12699. ids,
  12700. oldItemsData = this.itemsData;
  12701. // replace the dataset
  12702. if (!items) {
  12703. this.itemsData = null;
  12704. }
  12705. else if (items instanceof DataSet || items instanceof DataView) {
  12706. this.itemsData = items;
  12707. }
  12708. else {
  12709. throw new TypeError('Data must be an instance of DataSet or DataView');
  12710. }
  12711. if (oldItemsData) {
  12712. // unsubscribe from old dataset
  12713. util.forEach(this.itemListeners, function (callback, event) {
  12714. oldItemsData.off(event, callback);
  12715. });
  12716. // remove all drawn items
  12717. ids = oldItemsData.getIds();
  12718. this._onRemove(ids);
  12719. }
  12720. if (this.itemsData) {
  12721. // subscribe to new dataset
  12722. var id = this.id;
  12723. util.forEach(this.itemListeners, function (callback, event) {
  12724. me.itemsData.on(event, callback, id);
  12725. });
  12726. // add all new items
  12727. ids = this.itemsData.getIds();
  12728. this._onAdd(ids);
  12729. }
  12730. this._updateUngrouped();
  12731. //this._updateGraph();
  12732. this.redraw(true);
  12733. };
  12734. /**
  12735. * Set groups
  12736. * @param {vis.DataSet} groups
  12737. */
  12738. LineGraph.prototype.setGroups = function(groups) {
  12739. var me = this;
  12740. var ids;
  12741. // unsubscribe from current dataset
  12742. if (this.groupsData) {
  12743. util.forEach(this.groupListeners, function (callback, event) {
  12744. me.groupsData.unsubscribe(event, callback);
  12745. });
  12746. // remove all drawn groups
  12747. ids = this.groupsData.getIds();
  12748. this.groupsData = null;
  12749. this._onRemoveGroups(ids); // note: this will cause a redraw
  12750. }
  12751. // replace the dataset
  12752. if (!groups) {
  12753. this.groupsData = null;
  12754. }
  12755. else if (groups instanceof DataSet || groups instanceof DataView) {
  12756. this.groupsData = groups;
  12757. }
  12758. else {
  12759. throw new TypeError('Data must be an instance of DataSet or DataView');
  12760. }
  12761. if (this.groupsData) {
  12762. // subscribe to new dataset
  12763. var id = this.id;
  12764. util.forEach(this.groupListeners, function (callback, event) {
  12765. me.groupsData.on(event, callback, id);
  12766. });
  12767. // draw all ms
  12768. ids = this.groupsData.getIds();
  12769. this._onAddGroups(ids);
  12770. }
  12771. this._onUpdate();
  12772. };
  12773. /**
  12774. * Update the data
  12775. * @param [ids]
  12776. * @private
  12777. */
  12778. LineGraph.prototype._onUpdate = function(ids) {
  12779. this._updateUngrouped();
  12780. this._updateAllGroupData();
  12781. //this._updateGraph();
  12782. this.redraw(true);
  12783. };
  12784. LineGraph.prototype._onAdd = function (ids) {this._onUpdate(ids);};
  12785. LineGraph.prototype._onRemove = function (ids) {this._onUpdate(ids);};
  12786. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  12787. for (var i = 0; i < groupIds.length; i++) {
  12788. var group = this.groupsData.get(groupIds[i]);
  12789. this._updateGroup(group, groupIds[i]);
  12790. }
  12791. //this._updateGraph();
  12792. this.redraw(true);
  12793. };
  12794. LineGraph.prototype._onAddGroups = function (groupIds) {this._onUpdateGroups(groupIds);};
  12795. /**
  12796. * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph
  12797. * @param {Array} groupIds
  12798. * @private
  12799. */
  12800. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  12801. for (var i = 0; i < groupIds.length; i++) {
  12802. if (this.groups.hasOwnProperty(groupIds[i])) {
  12803. if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') {
  12804. this.yAxisRight.removeGroup(groupIds[i]);
  12805. this.legendRight.removeGroup(groupIds[i]);
  12806. this.legendRight.redraw();
  12807. }
  12808. else {
  12809. this.yAxisLeft.removeGroup(groupIds[i]);
  12810. this.legendLeft.removeGroup(groupIds[i]);
  12811. this.legendLeft.redraw();
  12812. }
  12813. delete this.groups[groupIds[i]];
  12814. }
  12815. }
  12816. this._updateUngrouped();
  12817. //this._updateGraph();
  12818. this.redraw(true);
  12819. };
  12820. /**
  12821. * update a group object with the group dataset entree
  12822. *
  12823. * @param group
  12824. * @param groupId
  12825. * @private
  12826. */
  12827. LineGraph.prototype._updateGroup = function (group, groupId) {
  12828. if (!this.groups.hasOwnProperty(groupId)) {
  12829. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  12830. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  12831. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  12832. this.legendRight.addGroup(groupId, this.groups[groupId]);
  12833. }
  12834. else {
  12835. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  12836. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  12837. }
  12838. }
  12839. else {
  12840. this.groups[groupId].update(group);
  12841. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  12842. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  12843. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  12844. }
  12845. else {
  12846. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  12847. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  12848. }
  12849. }
  12850. this.legendLeft.redraw();
  12851. this.legendRight.redraw();
  12852. };
  12853. /**
  12854. * this updates all groups, it is used when there is an update the the itemset.
  12855. *
  12856. * @private
  12857. */
  12858. LineGraph.prototype._updateAllGroupData = function () {
  12859. if (this.itemsData != null) {
  12860. var groupsContent = {};
  12861. var groupId;
  12862. for (groupId in this.groups) {
  12863. if (this.groups.hasOwnProperty(groupId)) {
  12864. groupsContent[groupId] = [];
  12865. }
  12866. }
  12867. for (var itemId in this.itemsData._data) {
  12868. if (this.itemsData._data.hasOwnProperty(itemId)) {
  12869. var item = this.itemsData._data[itemId];
  12870. if (groupsContent[item.group] === undefined) {
  12871. throw new Error('Cannot find referenced group. Possible reason: items added before groups? Groups need to be added before items, as items refer to groups.')
  12872. }
  12873. item.x = util.convert(item.x,'Date');
  12874. groupsContent[item.group].push(item);
  12875. }
  12876. }
  12877. for (groupId in this.groups) {
  12878. if (this.groups.hasOwnProperty(groupId)) {
  12879. this.groups[groupId].setItems(groupsContent[groupId]);
  12880. }
  12881. }
  12882. }
  12883. };
  12884. /**
  12885. * Create or delete the group holding all ungrouped items. This group is used when
  12886. * there are no groups specified. This anonymous group is called 'graph'.
  12887. * @protected
  12888. */
  12889. LineGraph.prototype._updateUngrouped = function() {
  12890. if (this.itemsData && this.itemsData != null) {
  12891. var ungroupedCounter = 0;
  12892. for (var itemId in this.itemsData._data) {
  12893. if (this.itemsData._data.hasOwnProperty(itemId)) {
  12894. var item = this.itemsData._data[itemId];
  12895. if (item != undefined) {
  12896. if (item.hasOwnProperty('group')) {
  12897. if (item.group === undefined) {
  12898. item.group = UNGROUPED;
  12899. }
  12900. }
  12901. else {
  12902. item.group = UNGROUPED;
  12903. }
  12904. ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter;
  12905. }
  12906. }
  12907. }
  12908. if (ungroupedCounter == 0) {
  12909. delete this.groups[UNGROUPED];
  12910. this.legendLeft.removeGroup(UNGROUPED);
  12911. this.legendRight.removeGroup(UNGROUPED);
  12912. this.yAxisLeft.removeGroup(UNGROUPED);
  12913. this.yAxisRight.removeGroup(UNGROUPED);
  12914. }
  12915. else {
  12916. var group = {id: UNGROUPED, content: this.options.defaultGroup};
  12917. this._updateGroup(group, UNGROUPED);
  12918. }
  12919. }
  12920. else {
  12921. delete this.groups[UNGROUPED];
  12922. this.legendLeft.removeGroup(UNGROUPED);
  12923. this.legendRight.removeGroup(UNGROUPED);
  12924. this.yAxisLeft.removeGroup(UNGROUPED);
  12925. this.yAxisRight.removeGroup(UNGROUPED);
  12926. }
  12927. this.legendLeft.redraw();
  12928. this.legendRight.redraw();
  12929. };
  12930. /**
  12931. * Redraw the component, mandatory function
  12932. * @return {boolean} Returns true if the component is resized
  12933. */
  12934. LineGraph.prototype.redraw = function(forceGraphUpdate) {
  12935. var resized = false;
  12936. // calculate actual size and position
  12937. this.props.width = this.dom.frame.offsetWidth;
  12938. this.props.height = this.body.domProps.centerContainer.height;
  12939. // update the graph if there is no lastWidth or with, used for the initial draw
  12940. if (this.lastWidth === undefined && this.props.width) {
  12941. forceGraphUpdate = true;
  12942. }
  12943. // check if this component is resized
  12944. resized = this._isResized() || resized;
  12945. // check whether zoomed (in that case we need to re-stack everything)
  12946. var visibleInterval = this.body.range.end - this.body.range.start;
  12947. var zoomed = (visibleInterval != this.lastVisibleInterval);
  12948. this.lastVisibleInterval = visibleInterval;
  12949. // the svg element is three times as big as the width, this allows for fully dragging left and right
  12950. // without reloading the graph. the controls for this are bound to events in the constructor
  12951. if (resized == true) {
  12952. this.svg.style.width = util.option.asSize(3*this.props.width);
  12953. this.svg.style.left = util.option.asSize(-this.props.width);
  12954. // if the height of the graph is set as proportional, change the height of the svg
  12955. if ((this.options.height + '').indexOf("%") != -1 || this.updateSVGheightOnResize == true) {
  12956. this.updateSVGheight = true;
  12957. }
  12958. }
  12959. // update the height of the graph on each redraw of the graph.
  12960. if (this.updateSVGheight == true) {
  12961. if (this.options.graphHeight != this.body.domProps.centerContainer.height + 'px') {
  12962. this.options.graphHeight = this.body.domProps.centerContainer.height + 'px';
  12963. this.svg.style.height = this.body.domProps.centerContainer.height + 'px';
  12964. }
  12965. this.updateSVGheight = false;
  12966. }
  12967. else {
  12968. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  12969. }
  12970. // zoomed is here to ensure that animations are shown correctly.
  12971. if (resized == true || zoomed == true || this.abortedGraphUpdate == true || forceGraphUpdate == true) {
  12972. resized = this._updateGraph() || resized;
  12973. }
  12974. else {
  12975. // move the whole svg while dragging
  12976. if (this.lastStart != 0) {
  12977. var offset = this.body.range.start - this.lastStart;
  12978. var range = this.body.range.end - this.body.range.start;
  12979. if (this.props.width != 0) {
  12980. var rangePerPixelInv = this.props.width/range;
  12981. var xOffset = offset * rangePerPixelInv;
  12982. this.svg.style.left = (-this.props.width - xOffset) + 'px';
  12983. }
  12984. }
  12985. }
  12986. this.legendLeft.redraw();
  12987. this.legendRight.redraw();
  12988. return resized;
  12989. };
  12990. /**
  12991. * Update and redraw the graph.
  12992. *
  12993. */
  12994. LineGraph.prototype._updateGraph = function () {
  12995. // reset the svg elements
  12996. DOMutil.prepareElements(this.svgElements);
  12997. if (this.props.width != 0 && this.itemsData != null) {
  12998. var group, i;
  12999. var preprocessedGroupData = {};
  13000. var processedGroupData = {};
  13001. var groupRanges = {};
  13002. var changeCalled = false;
  13003. // getting group Ids
  13004. var groupIds = [];
  13005. for (var groupId in this.groups) {
  13006. if (this.groups.hasOwnProperty(groupId)) {
  13007. group = this.groups[groupId];
  13008. if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) {
  13009. groupIds.push(groupId);
  13010. }
  13011. }
  13012. }
  13013. if (groupIds.length > 0) {
  13014. // this is the range of the SVG canvas
  13015. var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width);
  13016. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  13017. var groupsData = {};
  13018. // fill groups data, this only loads the data we require based on the timewindow
  13019. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  13020. // apply sampling, if disabled, it will pass through this function.
  13021. this._applySampling(groupIds, groupsData);
  13022. // we transform the X coordinates to detect collisions
  13023. for (i = 0; i < groupIds.length; i++) {
  13024. preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]);
  13025. }
  13026. // now all needed data has been collected we start the processing.
  13027. this._getYRanges(groupIds, preprocessedGroupData, groupRanges);
  13028. // update the Y axis first, we use this data to draw at the correct Y points
  13029. // changeCalled is required to clean the SVG on a change emit.
  13030. changeCalled = this._updateYAxis(groupIds, groupRanges);
  13031. var MAX_CYCLES = 5;
  13032. if (changeCalled == true && this.COUNTER < MAX_CYCLES) {
  13033. DOMutil.cleanupElements(this.svgElements);
  13034. this.abortedGraphUpdate = true;
  13035. this.COUNTER++;
  13036. this.body.emitter.emit('change');
  13037. return true;
  13038. }
  13039. else {
  13040. if (this.COUNTER > MAX_CYCLES) {
  13041. console.log("WARNING: there may be an infinite loop in the _updateGraph emitter cycle.")
  13042. }
  13043. this.COUNTER = 0;
  13044. this.abortedGraphUpdate = false;
  13045. // With the yAxis scaled correctly, use this to get the Y values of the points.
  13046. for (i = 0; i < groupIds.length; i++) {
  13047. group = this.groups[groupIds[i]];
  13048. processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group);
  13049. }
  13050. // draw the groups
  13051. for (i = 0; i < groupIds.length; i++) {
  13052. group = this.groups[groupIds[i]];
  13053. if (group.options.style != 'bar') { // bar needs to be drawn enmasse
  13054. group.draw(processedGroupData[groupIds[i]], group, this.framework);
  13055. }
  13056. }
  13057. BarGraphFunctions.draw(groupIds, processedGroupData, this.framework);
  13058. }
  13059. }
  13060. }
  13061. // cleanup unused svg elements
  13062. DOMutil.cleanupElements(this.svgElements);
  13063. return false;
  13064. };
  13065. /**
  13066. * first select and preprocess the data from the datasets.
  13067. * the groups have their preselection of data, we now loop over this data to see
  13068. * what data we need to draw. Sorted data is much faster.
  13069. * more optimization is possible by doing the sampling before and using the binary search
  13070. * to find the end date to determine the increment.
  13071. *
  13072. * @param {array} groupIds
  13073. * @param {object} groupsData
  13074. * @param {date} minDate
  13075. * @param {date} maxDate
  13076. * @private
  13077. */
  13078. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  13079. var group, i, j, item;
  13080. if (groupIds.length > 0) {
  13081. for (i = 0; i < groupIds.length; i++) {
  13082. group = this.groups[groupIds[i]];
  13083. groupsData[groupIds[i]] = [];
  13084. var dataContainer = groupsData[groupIds[i]];
  13085. // optimization for sorted data
  13086. if (group.options.sort == true) {
  13087. var guess = Math.max(0, util.binarySearchValue(group.itemsData, minDate, 'x', 'before'));
  13088. for (j = guess; j < group.itemsData.length; j++) {
  13089. item = group.itemsData[j];
  13090. if (item !== undefined) {
  13091. if (item.x > maxDate) {
  13092. dataContainer.push(item);
  13093. break;
  13094. }
  13095. else {
  13096. dataContainer.push(item);
  13097. }
  13098. }
  13099. }
  13100. }
  13101. else {
  13102. for (j = 0; j < group.itemsData.length; j++) {
  13103. item = group.itemsData[j];
  13104. if (item !== undefined) {
  13105. if (item.x > minDate && item.x < maxDate) {
  13106. dataContainer.push(item);
  13107. }
  13108. }
  13109. }
  13110. }
  13111. }
  13112. }
  13113. };
  13114. /**
  13115. *
  13116. * @param groupIds
  13117. * @param groupsData
  13118. * @private
  13119. */
  13120. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  13121. var group;
  13122. if (groupIds.length > 0) {
  13123. for (var i = 0; i < groupIds.length; i++) {
  13124. group = this.groups[groupIds[i]];
  13125. if (group.options.sampling == true) {
  13126. var dataContainer = groupsData[groupIds[i]];
  13127. if (dataContainer.length > 0) {
  13128. var increment = 1;
  13129. var amountOfPoints = dataContainer.length;
  13130. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  13131. // of width changing of the yAxis.
  13132. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  13133. var pointsPerPixel = amountOfPoints / xDistance;
  13134. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  13135. var sampledData = [];
  13136. for (var j = 0; j < amountOfPoints; j += increment) {
  13137. sampledData.push(dataContainer[j]);
  13138. }
  13139. groupsData[groupIds[i]] = sampledData;
  13140. }
  13141. }
  13142. }
  13143. }
  13144. };
  13145. /**
  13146. *
  13147. *
  13148. * @param {array} groupIds
  13149. * @param {object} groupsData
  13150. * @param {object} groupRanges | this is being filled here
  13151. * @private
  13152. */
  13153. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  13154. var groupData, group, i;
  13155. var barCombinedDataLeft = [];
  13156. var barCombinedDataRight = [];
  13157. var options;
  13158. if (groupIds.length > 0) {
  13159. for (i = 0; i < groupIds.length; i++) {
  13160. groupData = groupsData[groupIds[i]];
  13161. options = this.groups[groupIds[i]].options;
  13162. if (groupData.length > 0) {
  13163. group = this.groups[groupIds[i]];
  13164. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  13165. if (options.barChart.handleOverlap == 'stack' && options.style == 'bar') {
  13166. if (options.yAxisOrientation == 'left') {barCombinedDataLeft = barCombinedDataLeft.concat(group.getYRange(groupData)) ;}
  13167. else {barCombinedDataRight = barCombinedDataRight.concat(group.getYRange(groupData));}
  13168. }
  13169. else {
  13170. groupRanges[groupIds[i]] = group.getYRange(groupData,groupIds[i]);
  13171. }
  13172. }
  13173. }
  13174. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  13175. BarGraphFunctions.getStackedBarYRange(barCombinedDataLeft , groupRanges, groupIds, '__barchartLeft' , 'left' );
  13176. BarGraphFunctions.getStackedBarYRange(barCombinedDataRight, groupRanges, groupIds, '__barchartRight', 'right');
  13177. }
  13178. };
  13179. /**
  13180. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  13181. * @param {Array} groupIds
  13182. * @param {Object} groupRanges
  13183. * @private
  13184. */
  13185. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  13186. var resized = false;
  13187. var yAxisLeftUsed = false;
  13188. var yAxisRightUsed = false;
  13189. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  13190. // if groups are present
  13191. if (groupIds.length > 0) {
  13192. // this is here to make sure that if there are no items in the axis but there are groups, that there is no infinite draw/redraw loop.
  13193. for (var i = 0; i < groupIds.length; i++) {
  13194. var group = this.groups[groupIds[i]];
  13195. if (group && group.options.yAxisOrientation != 'right') {
  13196. yAxisLeftUsed = true;
  13197. minLeft = 0;
  13198. maxLeft = 0;
  13199. }
  13200. else if (group && group.options.yAxisOrientation) {
  13201. yAxisRightUsed = true;
  13202. minRight = 0;
  13203. maxRight = 0;
  13204. }
  13205. }
  13206. // if there are items:
  13207. for (var i = 0; i < groupIds.length; i++) {
  13208. if (groupRanges.hasOwnProperty(groupIds[i])) {
  13209. if (groupRanges[groupIds[i]].ignore !== true) {
  13210. minVal = groupRanges[groupIds[i]].min;
  13211. maxVal = groupRanges[groupIds[i]].max;
  13212. if (groupRanges[groupIds[i]].yAxisOrientation != 'right') {
  13213. yAxisLeftUsed = true;
  13214. minLeft = minLeft > minVal ? minVal : minLeft;
  13215. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  13216. }
  13217. else {
  13218. yAxisRightUsed = true;
  13219. minRight = minRight > minVal ? minVal : minRight;
  13220. maxRight = maxRight < maxVal ? maxVal : maxRight;
  13221. }
  13222. }
  13223. }
  13224. }
  13225. if (yAxisLeftUsed == true) {
  13226. this.yAxisLeft.setRange(minLeft, maxLeft);
  13227. }
  13228. if (yAxisRightUsed == true) {
  13229. this.yAxisRight.setRange(minRight, maxRight);
  13230. }
  13231. }
  13232. resized = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || resized;
  13233. resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized;
  13234. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  13235. this.yAxisLeft.drawIcons = true;
  13236. this.yAxisRight.drawIcons = true;
  13237. }
  13238. else {
  13239. this.yAxisLeft.drawIcons = false;
  13240. this.yAxisRight.drawIcons = false;
  13241. }
  13242. this.yAxisRight.master = !yAxisLeftUsed;
  13243. if (this.yAxisRight.master == false) {
  13244. if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;}
  13245. else {this.yAxisLeft.lineOffset = 0;}
  13246. resized = this.yAxisLeft.redraw() || resized;
  13247. this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels;
  13248. this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing;
  13249. resized = this.yAxisRight.redraw() || resized;
  13250. }
  13251. else {
  13252. resized = this.yAxisRight.redraw() || resized;
  13253. }
  13254. // clean the accumulated lists
  13255. if (groupIds.indexOf('__barchartLeft') != -1) {
  13256. groupIds.splice(groupIds.indexOf('__barchartLeft'),1);
  13257. }
  13258. if (groupIds.indexOf('__barchartRight') != -1) {
  13259. groupIds.splice(groupIds.indexOf('__barchartRight'),1);
  13260. }
  13261. return resized;
  13262. };
  13263. /**
  13264. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  13265. *
  13266. * @param {boolean} axisUsed
  13267. * @returns {boolean}
  13268. * @private
  13269. * @param axis
  13270. */
  13271. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  13272. var changed = false;
  13273. if (axisUsed == false) {
  13274. if (axis.dom.frame.parentNode && axis.hidden == false) {
  13275. axis.hide()
  13276. changed = true;
  13277. }
  13278. }
  13279. else {
  13280. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  13281. axis.show();
  13282. changed = true;
  13283. }
  13284. }
  13285. return changed;
  13286. };
  13287. /**
  13288. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  13289. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  13290. * the yAxis.
  13291. *
  13292. * @param datapoints
  13293. * @returns {Array}
  13294. * @private
  13295. */
  13296. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  13297. var extractedData = [];
  13298. var xValue, yValue;
  13299. var toScreen = this.body.util.toScreen;
  13300. for (var i = 0; i < datapoints.length; i++) {
  13301. xValue = toScreen(datapoints[i].x) + this.props.width;
  13302. yValue = datapoints[i].y;
  13303. extractedData.push({x: xValue, y: yValue});
  13304. }
  13305. return extractedData;
  13306. };
  13307. /**
  13308. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  13309. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  13310. * the yAxis.
  13311. *
  13312. * @param datapoints
  13313. * @param group
  13314. * @returns {Array}
  13315. * @private
  13316. */
  13317. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  13318. var extractedData = [];
  13319. var xValue, yValue;
  13320. var toScreen = this.body.util.toScreen;
  13321. var axis = this.yAxisLeft;
  13322. var svgHeight = Number(this.svg.style.height.replace('px',''));
  13323. if (group.options.yAxisOrientation == 'right') {
  13324. axis = this.yAxisRight;
  13325. }
  13326. for (var i = 0; i < datapoints.length; i++) {
  13327. var labelValue;
  13328. //if (datapoints[i].label) {
  13329. // labelValue = datapoints[i].label;
  13330. //}
  13331. //else {
  13332. // labelValue = null;
  13333. //}
  13334. labelValue = datapoints[i].label ? datapoints[i].label : null;
  13335. xValue = toScreen(datapoints[i].x) + this.props.width;
  13336. yValue = Math.round(axis.convertValue(datapoints[i].y));
  13337. extractedData.push({x: xValue, y: yValue, label:labelValue});
  13338. }
  13339. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  13340. return extractedData;
  13341. };
  13342. module.exports = LineGraph;
  13343. /***/ },
  13344. /* 35 */
  13345. /***/ function(module, exports, __webpack_require__) {
  13346. var util = __webpack_require__(1);
  13347. var Component = __webpack_require__(25);
  13348. var TimeStep = __webpack_require__(19);
  13349. var DateUtil = __webpack_require__(15);
  13350. var moment = __webpack_require__(44);
  13351. /**
  13352. * A horizontal time axis
  13353. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  13354. * @param {Object} [options] See TimeAxis.setOptions for the available
  13355. * options.
  13356. * @constructor TimeAxis
  13357. * @extends Component
  13358. */
  13359. function TimeAxis (body, options) {
  13360. this.dom = {
  13361. foreground: null,
  13362. lines: [],
  13363. majorTexts: [],
  13364. minorTexts: [],
  13365. redundant: {
  13366. lines: [],
  13367. majorTexts: [],
  13368. minorTexts: []
  13369. }
  13370. };
  13371. this.props = {
  13372. range: {
  13373. start: 0,
  13374. end: 0,
  13375. minimumStep: 0
  13376. },
  13377. lineTop: 0
  13378. };
  13379. this.defaultOptions = {
  13380. orientation: 'bottom', // axis orientation: 'top' or 'bottom'
  13381. showMinorLabels: true,
  13382. showMajorLabels: true,
  13383. format: null,
  13384. timeAxis: null
  13385. };
  13386. this.options = util.extend({}, this.defaultOptions);
  13387. this.body = body;
  13388. // create the HTML DOM
  13389. this._create();
  13390. this.setOptions(options);
  13391. }
  13392. TimeAxis.prototype = new Component();
  13393. /**
  13394. * Set options for the TimeAxis.
  13395. * Parameters will be merged in current options.
  13396. * @param {Object} options Available options:
  13397. * {string} [orientation]
  13398. * {boolean} [showMinorLabels]
  13399. * {boolean} [showMajorLabels]
  13400. */
  13401. TimeAxis.prototype.setOptions = function(options) {
  13402. if (options) {
  13403. // copy all options that we know
  13404. util.selectiveExtend([
  13405. 'showMinorLabels',
  13406. 'showMajorLabels',
  13407. 'hiddenDates',
  13408. 'format',
  13409. 'timeAxis'
  13410. ], this.options, options);
  13411. if ('orientation' in options) {
  13412. if (typeof options.orientation === 'string') {
  13413. this.options.orientation = options.orientation;
  13414. }
  13415. else if (typeof options.orientation === 'object' && 'axis' in options.orientation) {
  13416. this.options.orientation = options.orientation.axis;
  13417. }
  13418. }
  13419. // apply locale to moment.js
  13420. // TODO: not so nice, this is applied globally to moment.js
  13421. if ('locale' in options) {
  13422. if (typeof moment.locale === 'function') {
  13423. // moment.js 2.8.1+
  13424. moment.locale(options.locale);
  13425. }
  13426. else {
  13427. moment.lang(options.locale);
  13428. }
  13429. }
  13430. }
  13431. };
  13432. /**
  13433. * Create the HTML DOM for the TimeAxis
  13434. */
  13435. TimeAxis.prototype._create = function() {
  13436. this.dom.foreground = document.createElement('div');
  13437. this.dom.background = document.createElement('div');
  13438. this.dom.foreground.className = 'timeaxis foreground';
  13439. this.dom.background.className = 'timeaxis background';
  13440. };
  13441. /**
  13442. * Destroy the TimeAxis
  13443. */
  13444. TimeAxis.prototype.destroy = function() {
  13445. // remove from DOM
  13446. if (this.dom.foreground.parentNode) {
  13447. this.dom.foreground.parentNode.removeChild(this.dom.foreground);
  13448. }
  13449. if (this.dom.background.parentNode) {
  13450. this.dom.background.parentNode.removeChild(this.dom.background);
  13451. }
  13452. this.body = null;
  13453. };
  13454. /**
  13455. * Repaint the component
  13456. * @return {boolean} Returns true if the component is resized
  13457. */
  13458. TimeAxis.prototype.redraw = function () {
  13459. var options = this.options;
  13460. var props = this.props;
  13461. var foreground = this.dom.foreground;
  13462. var background = this.dom.background;
  13463. // determine the correct parent DOM element (depending on option orientation)
  13464. var parent = (options.orientation == 'top') ? this.body.dom.top : this.body.dom.bottom;
  13465. var parentChanged = (foreground.parentNode !== parent);
  13466. // calculate character width and height
  13467. this._calculateCharSize();
  13468. // TODO: recalculate sizes only needed when parent is resized or options is changed
  13469. var showMinorLabels = this.options.showMinorLabels;
  13470. var showMajorLabels = this.options.showMajorLabels;
  13471. // determine the width and height of the elemens for the axis
  13472. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  13473. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  13474. props.height = props.minorLabelHeight + props.majorLabelHeight;
  13475. props.width = foreground.offsetWidth;
  13476. props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight -
  13477. (options.orientation == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height);
  13478. props.minorLineWidth = 1; // TODO: really calculate width
  13479. props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight;
  13480. props.majorLineWidth = 1; // TODO: really calculate width
  13481. // take foreground and background offline while updating (is almost twice as fast)
  13482. var foregroundNextSibling = foreground.nextSibling;
  13483. var backgroundNextSibling = background.nextSibling;
  13484. foreground.parentNode && foreground.parentNode.removeChild(foreground);
  13485. background.parentNode && background.parentNode.removeChild(background);
  13486. foreground.style.height = this.props.height + 'px';
  13487. this._repaintLabels();
  13488. // put DOM online again (at the same place)
  13489. if (foregroundNextSibling) {
  13490. parent.insertBefore(foreground, foregroundNextSibling);
  13491. }
  13492. else {
  13493. parent.appendChild(foreground)
  13494. }
  13495. if (backgroundNextSibling) {
  13496. this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling);
  13497. }
  13498. else {
  13499. this.body.dom.backgroundVertical.appendChild(background)
  13500. }
  13501. return this._isResized() || parentChanged;
  13502. };
  13503. /**
  13504. * Repaint major and minor text labels and vertical grid lines
  13505. * @private
  13506. */
  13507. TimeAxis.prototype._repaintLabels = function () {
  13508. var orientation = this.options.orientation;
  13509. // calculate range and step (step such that we have space for 7 characters per label)
  13510. var start = util.convert(this.body.range.start, 'Number');
  13511. var end = util.convert(this.body.range.end, 'Number');
  13512. var timeLabelsize = this.body.util.toTime((this.props.minorCharWidth || 10) * 7).valueOf();
  13513. var minimumStep = timeLabelsize - DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this.body.range, timeLabelsize);
  13514. minimumStep -= this.body.util.toTime(0).valueOf();
  13515. var step = new TimeStep(new Date(start), new Date(end), minimumStep, this.body.hiddenDates);
  13516. if (this.options.format) {
  13517. step.setFormat(this.options.format);
  13518. }
  13519. if (this.options.timeAxis) {
  13520. step.setScale(this.options.timeAxis);
  13521. }
  13522. this.step = step;
  13523. // Move all DOM elements to a "redundant" list, where they
  13524. // can be picked for re-use, and clear the lists with lines and texts.
  13525. // At the end of the function _repaintLabels, left over elements will be cleaned up
  13526. var dom = this.dom;
  13527. dom.redundant.lines = dom.lines;
  13528. dom.redundant.majorTexts = dom.majorTexts;
  13529. dom.redundant.minorTexts = dom.minorTexts;
  13530. dom.lines = [];
  13531. dom.majorTexts = [];
  13532. dom.minorTexts = [];
  13533. var cur;
  13534. var x = 0;
  13535. var isMajor;
  13536. var xPrev = 0;
  13537. var width = 0;
  13538. var prevLine;
  13539. var xFirstMajorLabel = undefined;
  13540. var max = 0;
  13541. var className;
  13542. step.first();
  13543. while (step.hasNext() && max < 1000) {
  13544. max++;
  13545. cur = step.getCurrent();
  13546. isMajor = step.isMajor();
  13547. className = step.getClassName();
  13548. xPrev = x;
  13549. x = this.body.util.toScreen(cur);
  13550. width = x - xPrev;
  13551. if (prevLine) {
  13552. prevLine.style.width = width + 'px';
  13553. }
  13554. if (this.options.showMinorLabels) {
  13555. this._repaintMinorText(x, step.getLabelMinor(), orientation, className);
  13556. }
  13557. if (isMajor && this.options.showMajorLabels) {
  13558. if (x > 0) {
  13559. if (xFirstMajorLabel == undefined) {
  13560. xFirstMajorLabel = x;
  13561. }
  13562. this._repaintMajorText(x, step.getLabelMajor(), orientation, className);
  13563. }
  13564. prevLine = this._repaintMajorLine(x, orientation, className);
  13565. }
  13566. else {
  13567. prevLine = this._repaintMinorLine(x, orientation, className);
  13568. }
  13569. step.next();
  13570. }
  13571. // create a major label on the left when needed
  13572. if (this.options.showMajorLabels) {
  13573. var leftTime = this.body.util.toTime(0),
  13574. leftText = step.getLabelMajor(leftTime),
  13575. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  13576. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  13577. this._repaintMajorText(0, leftText, orientation, className);
  13578. }
  13579. }
  13580. // Cleanup leftover DOM elements from the redundant list
  13581. util.forEach(this.dom.redundant, function (arr) {
  13582. while (arr.length) {
  13583. var elem = arr.pop();
  13584. if (elem && elem.parentNode) {
  13585. elem.parentNode.removeChild(elem);
  13586. }
  13587. }
  13588. });
  13589. };
  13590. /**
  13591. * Create a minor label for the axis at position x
  13592. * @param {Number} x
  13593. * @param {String} text
  13594. * @param {String} orientation "top" or "bottom" (default)
  13595. * @param {String} className
  13596. * @private
  13597. */
  13598. TimeAxis.prototype._repaintMinorText = function (x, text, orientation, className) {
  13599. // reuse redundant label
  13600. var label = this.dom.redundant.minorTexts.shift();
  13601. if (!label) {
  13602. // create new label
  13603. var content = document.createTextNode('');
  13604. label = document.createElement('div');
  13605. label.appendChild(content);
  13606. this.dom.foreground.appendChild(label);
  13607. }
  13608. this.dom.minorTexts.push(label);
  13609. label.childNodes[0].nodeValue = text;
  13610. label.style.top = (orientation == 'top') ? (this.props.majorLabelHeight + 'px') : '0';
  13611. label.style.left = x + 'px';
  13612. label.className = 'text minor ' + className;
  13613. //label.title = title; // TODO: this is a heavy operation
  13614. };
  13615. /**
  13616. * Create a Major label for the axis at position x
  13617. * @param {Number} x
  13618. * @param {String} text
  13619. * @param {String} orientation "top" or "bottom" (default)
  13620. * @param {String} className
  13621. * @private
  13622. */
  13623. TimeAxis.prototype._repaintMajorText = function (x, text, orientation, className) {
  13624. // reuse redundant label
  13625. var label = this.dom.redundant.majorTexts.shift();
  13626. if (!label) {
  13627. // create label
  13628. var content = document.createTextNode(text);
  13629. label = document.createElement('div');
  13630. label.appendChild(content);
  13631. this.dom.foreground.appendChild(label);
  13632. }
  13633. this.dom.majorTexts.push(label);
  13634. label.childNodes[0].nodeValue = text;
  13635. label.className = 'text major ' + className;
  13636. //label.title = title; // TODO: this is a heavy operation
  13637. label.style.top = (orientation == 'top') ? '0' : (this.props.minorLabelHeight + 'px');
  13638. label.style.left = x + 'px';
  13639. };
  13640. /**
  13641. * Create a minor line for the axis at position x
  13642. * @param {Number} x
  13643. * @param {String} orientation "top" or "bottom" (default)
  13644. * @param {String} className
  13645. * @return {Element} Returns the created line
  13646. * @private
  13647. */
  13648. TimeAxis.prototype._repaintMinorLine = function (x, orientation, className) {
  13649. // reuse redundant line
  13650. var line = this.dom.redundant.lines.shift();
  13651. if (!line) {
  13652. // create vertical line
  13653. line = document.createElement('div');
  13654. this.dom.background.appendChild(line);
  13655. }
  13656. this.dom.lines.push(line);
  13657. var props = this.props;
  13658. if (orientation == 'top') {
  13659. line.style.top = props.majorLabelHeight + 'px';
  13660. }
  13661. else {
  13662. line.style.top = this.body.domProps.top.height + 'px';
  13663. }
  13664. line.style.height = props.minorLineHeight + 'px';
  13665. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  13666. line.className = 'grid vertical minor ' + className;
  13667. return line;
  13668. };
  13669. /**
  13670. * Create a Major line for the axis at position x
  13671. * @param {Number} x
  13672. * @param {String} orientation "top" or "bottom" (default)
  13673. * @param {String} className
  13674. * @return {Element} Returns the created line
  13675. * @private
  13676. */
  13677. TimeAxis.prototype._repaintMajorLine = function (x, orientation, className) {
  13678. // reuse redundant line
  13679. var line = this.dom.redundant.lines.shift();
  13680. if (!line) {
  13681. // create vertical line
  13682. line = document.createElement('div');
  13683. this.dom.background.appendChild(line);
  13684. }
  13685. this.dom.lines.push(line);
  13686. var props = this.props;
  13687. if (orientation == 'top') {
  13688. line.style.top = '0';
  13689. }
  13690. else {
  13691. line.style.top = this.body.domProps.top.height + 'px';
  13692. }
  13693. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  13694. line.style.height = props.majorLineHeight + 'px';
  13695. line.className = 'grid vertical major ' + className;
  13696. return line;
  13697. };
  13698. /**
  13699. * Determine the size of text on the axis (both major and minor axis).
  13700. * The size is calculated only once and then cached in this.props.
  13701. * @private
  13702. */
  13703. TimeAxis.prototype._calculateCharSize = function () {
  13704. // Note: We calculate char size with every redraw. Size may change, for
  13705. // example when any of the timelines parents had display:none for example.
  13706. // determine the char width and height on the minor axis
  13707. if (!this.dom.measureCharMinor) {
  13708. this.dom.measureCharMinor = document.createElement('DIV');
  13709. this.dom.measureCharMinor.className = 'text minor measure';
  13710. this.dom.measureCharMinor.style.position = 'absolute';
  13711. this.dom.measureCharMinor.appendChild(document.createTextNode('0'));
  13712. this.dom.foreground.appendChild(this.dom.measureCharMinor);
  13713. }
  13714. this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight;
  13715. this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth;
  13716. // determine the char width and height on the major axis
  13717. if (!this.dom.measureCharMajor) {
  13718. this.dom.measureCharMajor = document.createElement('DIV');
  13719. this.dom.measureCharMajor.className = 'text major measure';
  13720. this.dom.measureCharMajor.style.position = 'absolute';
  13721. this.dom.measureCharMajor.appendChild(document.createTextNode('0'));
  13722. this.dom.foreground.appendChild(this.dom.measureCharMajor);
  13723. }
  13724. this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight;
  13725. this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth;
  13726. };
  13727. module.exports = TimeAxis;
  13728. /***/ },
  13729. /* 36 */
  13730. /***/ function(module, exports, __webpack_require__) {
  13731. var Emitter = __webpack_require__(56);
  13732. var Hammer = __webpack_require__(45);
  13733. var keycharm = __webpack_require__(57);
  13734. var util = __webpack_require__(1);
  13735. var hammerUtil = __webpack_require__(47);
  13736. var DataSet = __webpack_require__(3);
  13737. var DataView = __webpack_require__(4);
  13738. var dotparser = __webpack_require__(42);
  13739. var gephiParser = __webpack_require__(43);
  13740. var Groups = __webpack_require__(38);
  13741. var Images = __webpack_require__(39);
  13742. var Node = __webpack_require__(40);
  13743. var Edge = __webpack_require__(37);
  13744. var Popup = __webpack_require__(41);
  13745. var MixinLoader = __webpack_require__(52);
  13746. var Activator = __webpack_require__(53);
  13747. var locales = __webpack_require__(54);
  13748. // Load custom shapes into CanvasRenderingContext2D
  13749. __webpack_require__(55);
  13750. /**
  13751. * @constructor Network
  13752. * Create a network visualization, displaying nodes and edges.
  13753. *
  13754. * @param {Element} container The DOM element in which the Network will
  13755. * be created. Normally a div element.
  13756. * @param {Object} data An object containing parameters
  13757. * {Array} nodes
  13758. * {Array} edges
  13759. * @param {Object} options Options
  13760. */
  13761. function Network (container, data, options) {
  13762. if (!(this instanceof Network)) {
  13763. throw new SyntaxError('Constructor must be called with the new operator');
  13764. }
  13765. this._determineBrowserMethod();
  13766. this._initializeMixinLoaders();
  13767. // create variables and set default values
  13768. this.containerElement = container;
  13769. // render and calculation settings
  13770. this.renderRefreshRate = 60; // hz (fps)
  13771. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13772. this.renderTime = 0; // measured time it takes to render a frame
  13773. this.physicsTime = 0; // measured time it takes to render a frame
  13774. this.runDoubleSpeed = false;
  13775. this.physicsDiscreteStepsize = 0.50; // discrete stepsize of the simulation
  13776. this.initializing = true;
  13777. this.triggerFunctions = {add:null,edit:null,editEdge:null,connect:null,del:null};
  13778. var customScalingFunction = function (min,max,total,value) {
  13779. if (max == min) {
  13780. return 0.5;
  13781. }
  13782. else {
  13783. var scale = 1 / (max - min);
  13784. return Math.max(0,(value - min)*scale);
  13785. }
  13786. };
  13787. // set constant values
  13788. this.defaultOptions = {
  13789. nodes: {
  13790. customScalingFunction: customScalingFunction,
  13791. mass: 1,
  13792. radiusMin: 10,
  13793. radiusMax: 30,
  13794. radius: 10,
  13795. shape: 'ellipse',
  13796. image: undefined,
  13797. widthMin: 16, // px
  13798. widthMax: 64, // px
  13799. fontColor: 'black',
  13800. fontSize: 14, // px
  13801. fontFace: 'verdana',
  13802. fontFill: undefined,
  13803. fontStrokeWidth: 0, // px
  13804. fontStrokeColor: '#ffffff',
  13805. fontDrawThreshold: 3,
  13806. scaleFontWithValue: false,
  13807. fontSizeMin: 14,
  13808. fontSizeMax: 30,
  13809. fontSizeMaxVisible: 30,
  13810. level: -1,
  13811. color: {
  13812. border: '#2B7CE9',
  13813. background: '#97C2FC',
  13814. highlight: {
  13815. border: '#2B7CE9',
  13816. background: '#D2E5FF'
  13817. },
  13818. hover: {
  13819. border: '#2B7CE9',
  13820. background: '#D2E5FF'
  13821. }
  13822. },
  13823. group: undefined,
  13824. borderWidth: 1,
  13825. borderWidthSelected: undefined
  13826. },
  13827. edges: {
  13828. customScalingFunction: customScalingFunction,
  13829. widthMin: 1, //
  13830. widthMax: 15,//
  13831. width: 1,
  13832. widthSelectionMultiplier: 2,
  13833. hoverWidth: 1.5,
  13834. style: 'line',
  13835. color: {
  13836. color:'#848484',
  13837. highlight:'#848484',
  13838. hover: '#848484'
  13839. },
  13840. opacity:1.0,
  13841. fontColor: '#343434',
  13842. fontSize: 14, // px
  13843. fontFace: 'arial',
  13844. fontFill: 'white',
  13845. fontStrokeWidth: 0, // px
  13846. fontStrokeColor: 'white',
  13847. labelAlignment:'horizontal',
  13848. arrowScaleFactor: 1,
  13849. dash: {
  13850. length: 10,
  13851. gap: 5,
  13852. altLength: undefined
  13853. },
  13854. inheritColor: "from", // to, from, false, true (== from)
  13855. useGradients: false // release in 4.0
  13856. },
  13857. configurePhysics:false,
  13858. physics: {
  13859. barnesHut: {
  13860. enabled: true,
  13861. thetaInverted: 1 / 0.5, // inverted to save time during calculation
  13862. gravitationalConstant: -2000,
  13863. centralGravity: 0.3,
  13864. springLength: 95,
  13865. springConstant: 0.04,
  13866. damping: 0.09
  13867. },
  13868. repulsion: {
  13869. centralGravity: 0.0,
  13870. springLength: 200,
  13871. springConstant: 0.05,
  13872. nodeDistance: 100,
  13873. damping: 0.09
  13874. },
  13875. hierarchicalRepulsion: {
  13876. enabled: false,
  13877. centralGravity: 0.0,
  13878. springLength: 100,
  13879. springConstant: 0.01,
  13880. nodeDistance: 150,
  13881. damping: 0.09
  13882. },
  13883. damping: null,
  13884. centralGravity: null,
  13885. springLength: null,
  13886. springConstant: null
  13887. },
  13888. clustering: { // Per Node in Cluster = PNiC
  13889. enabled: false, // (Boolean) | global on/off switch for clustering.
  13890. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13891. clusterThreshold:500, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than this. If it is, cluster until reduced to reduceToNodes
  13892. reduceToNodes:300, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than clusterThreshold. If it is, cluster until reduced to this
  13893. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13894. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13895. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13896. screenSizeThreshold: 0.2, // (% of canvas) | relative size threshold. If the width or height of a clusternode takes up this much of the screen, decluster node.
  13897. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13898. maxFontSize: 1000,
  13899. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13900. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13901. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13902. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13903. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13904. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13905. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13906. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13907. clusterLevelDifference: 2, // used for normalization of the cluster levels
  13908. clusterByZoom: true // enable clustering through zooming in and out
  13909. },
  13910. navigation: {
  13911. enabled: false
  13912. },
  13913. keyboard: {
  13914. enabled: false,
  13915. speed: {x: 10, y: 10, zoom: 0.02},
  13916. bindToWindow: true
  13917. },
  13918. dataManipulation: {
  13919. enabled: false,
  13920. initiallyVisible: false
  13921. },
  13922. hierarchicalLayout: {
  13923. enabled:false,
  13924. levelSeparation: 150,
  13925. nodeSpacing: 100,
  13926. direction: "UD", // UD, DU, LR, RL
  13927. layout: "hubsize" // hubsize, directed
  13928. },
  13929. freezeForStabilization: false,
  13930. smoothCurves: {
  13931. enabled: true,
  13932. dynamic: true,
  13933. type: "continuous",
  13934. roundness: 0.5
  13935. },
  13936. maxVelocity: 50,
  13937. minVelocity: 0.1, // px/s
  13938. stabilize: true, // stabilize before displaying the network
  13939. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  13940. zoomExtentOnStabilize: true,
  13941. locale: 'en',
  13942. locales: locales,
  13943. tooltip: {
  13944. delay: 300,
  13945. fontColor: 'black',
  13946. fontSize: 14, // px
  13947. fontFace: 'verdana',
  13948. color: {
  13949. border: '#666',
  13950. background: '#FFFFC6'
  13951. }
  13952. },
  13953. dragNetwork: true,
  13954. dragNodes: true,
  13955. zoomable: true,
  13956. hover: false,
  13957. hideEdgesOnDrag: false,
  13958. hideNodesOnDrag: false,
  13959. width : '100%',
  13960. height : '100%',
  13961. selectable: true,
  13962. useDefaultGroups: true
  13963. };
  13964. this.constants = util.extend({}, this.defaultOptions);
  13965. this.pixelRatio = 1;
  13966. this.hoverObj = {nodes:{},edges:{}};
  13967. this.controlNodesActive = false;
  13968. this.navigationHammers = [];
  13969. this.manipulationHammers = [];
  13970. // animation properties
  13971. this.animationSpeed = 1/this.renderRefreshRate;
  13972. this.animationEasingFunction = "easeInOutQuint";
  13973. this.animating = false;
  13974. this.easingTime = 0;
  13975. this.sourceScale = 0;
  13976. this.targetScale = 0;
  13977. this.sourceTranslation = 0;
  13978. this.targetTranslation = 0;
  13979. this.lockedOnNodeId = null;
  13980. this.lockedOnNodeOffset = null;
  13981. this.touchTime = 0;
  13982. this.redrawRequested = false;
  13983. // Node variables
  13984. var network = this;
  13985. this.groups = new Groups(); // object with groups
  13986. this.images = new Images(); // object with images
  13987. this.images.setOnloadCallback(function (status) {
  13988. network._requestRedraw();
  13989. });
  13990. // keyboard navigation variables
  13991. this.xIncrement = 0;
  13992. this.yIncrement = 0;
  13993. this.zoomIncrement = 0;
  13994. // loading all the mixins:
  13995. // load the force calculation functions, grouped under the physics system.
  13996. this._loadPhysicsSystem();
  13997. // create a frame and canvas
  13998. this._create();
  13999. // load the sector system. (mandatory, fully integrated with Network)
  14000. this._loadSectorSystem();
  14001. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  14002. this._loadClusterSystem();
  14003. // load the selection system. (mandatory, required by Network)
  14004. this._loadSelectionSystem();
  14005. // load the selection system. (mandatory, required by Network)
  14006. this._loadHierarchySystem();
  14007. // apply options
  14008. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14009. this._setScale(1);
  14010. this.setOptions(options);
  14011. // other vars
  14012. this.freezeSimulationEnabled = false;// freeze the simulation
  14013. this.cachedFunctions = {};
  14014. this.startedStabilization = false;
  14015. this.stabilized = false;
  14016. this.stabilizationIterations = null;
  14017. this.draggingNodes = false;
  14018. // containers for nodes and edges
  14019. this.calculationNodes = {};
  14020. this.calculationNodeIndices = [];
  14021. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  14022. this.nodes = {}; // object with Node objects
  14023. this.edges = {}; // object with Edge objects
  14024. // position and scale variables and objects
  14025. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  14026. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14027. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14028. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  14029. this.scale = 1; // defining the global scale variable in the constructor
  14030. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  14031. // datasets or dataviews
  14032. this.nodesData = null; // A DataSet or DataView
  14033. this.edgesData = null; // A DataSet or DataView
  14034. // create event listeners used to subscribe on the DataSets of the nodes and edges
  14035. this.nodesListeners = {
  14036. 'add': function (event, params) {
  14037. network._addNodes(params.items);
  14038. network.start();
  14039. },
  14040. 'update': function (event, params) {
  14041. network._updateNodes(params.items);
  14042. network.start();
  14043. },
  14044. 'remove': function (event, params) {
  14045. network._removeNodes(params.items);
  14046. network.start();
  14047. }
  14048. };
  14049. this.edgesListeners = {
  14050. 'add': function (event, params) {
  14051. network._addEdges(params.items);
  14052. network.start();
  14053. },
  14054. 'update': function (event, params) {
  14055. network._updateEdges(params.items);
  14056. network.start();
  14057. },
  14058. 'remove': function (event, params) {
  14059. network._removeEdges(params.items);
  14060. network.start();
  14061. }
  14062. };
  14063. // properties for the animation
  14064. this.moving = true;
  14065. this.timer = undefined; // Scheduling function. Is definded in this.start();
  14066. // load data (the disable start variable will be the same as the enabled clustering)
  14067. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  14068. // hierarchical layout
  14069. this.initializing = false;
  14070. if (this.constants.hierarchicalLayout.enabled == true) {
  14071. this._setupHierarchicalLayout();
  14072. }
  14073. else {
  14074. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  14075. if (this.constants.stabilize == false) {
  14076. this.zoomExtent({duration:0}, true, this.constants.clustering.enabled);
  14077. }
  14078. }
  14079. // if clustering is disabled, the simulation will have started in the setData function
  14080. if (this.constants.clustering.enabled) {
  14081. this.startWithClustering();
  14082. }
  14083. }
  14084. // Extend Network with an Emitter mixin
  14085. Emitter(Network.prototype);
  14086. /**
  14087. * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because
  14088. * some implementations (safari and IE9) did not support requestAnimationFrame
  14089. * @private
  14090. */
  14091. Network.prototype._determineBrowserMethod = function() {
  14092. var browserType = navigator.userAgent.toLowerCase();
  14093. this.requiresTimeout = false;
  14094. if (browserType.indexOf('msie 9.0') != -1) { // IE 9
  14095. this.requiresTimeout = true;
  14096. }
  14097. else if (browserType.indexOf('safari') != -1) { // safari
  14098. if (browserType.indexOf('chrome') <= -1) {
  14099. this.requiresTimeout = true;
  14100. }
  14101. }
  14102. }
  14103. /**
  14104. * Get the script path where the vis.js library is located
  14105. *
  14106. * @returns {string | null} path Path or null when not found. Path does not
  14107. * end with a slash.
  14108. * @private
  14109. */
  14110. Network.prototype._getScriptPath = function() {
  14111. var scripts = document.getElementsByTagName( 'script' );
  14112. // find script named vis.js or vis.min.js
  14113. for (var i = 0; i < scripts.length; i++) {
  14114. var src = scripts[i].src;
  14115. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  14116. if (match) {
  14117. // return path without the script name
  14118. return src.substring(0, src.length - match[0].length);
  14119. }
  14120. }
  14121. return null;
  14122. };
  14123. /**
  14124. * Find the center position of the network
  14125. * @private
  14126. */
  14127. Network.prototype._getRange = function(specificNodes) {
  14128. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  14129. if (specificNodes.length > 0) {
  14130. for (var i = 0; i < specificNodes.length; i++) {
  14131. node = this.nodes[specificNodes[i]];
  14132. if (minX > (node.boundingBox.left)) {
  14133. minX = node.boundingBox.left;
  14134. }
  14135. if (maxX < (node.boundingBox.right)) {
  14136. maxX = node.boundingBox.right;
  14137. }
  14138. if (minY > (node.boundingBox.bottom)) {
  14139. minY = node.boundingBox.top;
  14140. } // top is negative, bottom is positive
  14141. if (maxY < (node.boundingBox.top)) {
  14142. maxY = node.boundingBox.bottom;
  14143. } // top is negative, bottom is positive
  14144. }
  14145. }
  14146. else {
  14147. for (var nodeId in this.nodes) {
  14148. if (this.nodes.hasOwnProperty(nodeId)) {
  14149. node = this.nodes[nodeId];
  14150. if (minX > (node.boundingBox.left)) {
  14151. minX = node.boundingBox.left;
  14152. }
  14153. if (maxX < (node.boundingBox.right)) {
  14154. maxX = node.boundingBox.right;
  14155. }
  14156. if (minY > (node.boundingBox.bottom)) {
  14157. minY = node.boundingBox.top;
  14158. } // top is negative, bottom is positive
  14159. if (maxY < (node.boundingBox.top)) {
  14160. maxY = node.boundingBox.bottom;
  14161. } // top is negative, bottom is positive
  14162. }
  14163. }
  14164. }
  14165. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  14166. minY = 0, maxY = 0, minX = 0, maxX = 0;
  14167. }
  14168. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14169. };
  14170. /**
  14171. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14172. * @returns {{x: number, y: number}}
  14173. * @private
  14174. */
  14175. Network.prototype._findCenter = function(range) {
  14176. return {x: (0.5 * (range.maxX + range.minX)),
  14177. y: (0.5 * (range.maxY + range.minY))};
  14178. };
  14179. /**
  14180. * This function zooms out to fit all data on screen based on amount of nodes
  14181. *
  14182. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14183. * @param {Boolean} [disableStart] | If true, start is not called.
  14184. */
  14185. Network.prototype.zoomExtent = function(options, initialZoom, disableStart) {
  14186. this._redraw(true);
  14187. if (initialZoom === undefined) {initialZoom = false;}
  14188. if (disableStart === undefined) {disableStart = false;}
  14189. if (options === undefined) {options = {nodes:[]};}
  14190. if (options.nodes === undefined) {
  14191. options.nodes = [];
  14192. }
  14193. var range;
  14194. var zoomLevel;
  14195. if (initialZoom == true) {
  14196. // check if more than half of the nodes have a predefined position. If so, we use the range, not the approximation.
  14197. var positionDefined = 0;
  14198. for (var nodeId in this.nodes) {
  14199. if (this.nodes.hasOwnProperty(nodeId)) {
  14200. var node = this.nodes[nodeId];
  14201. if (node.predefinedPosition == true) {
  14202. positionDefined += 1;
  14203. }
  14204. }
  14205. }
  14206. if (positionDefined > 0.5 * this.nodeIndices.length) {
  14207. this.zoomExtent(options,false,disableStart);
  14208. return;
  14209. }
  14210. range = this._getRange(options.nodes);
  14211. var numberOfNodes = this.nodeIndices.length;
  14212. if (this.constants.smoothCurves == true) {
  14213. if (this.constants.clustering.enabled == true &&
  14214. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14215. zoomLevel = 49.07548 / (numberOfNodes + 142.05338) + 9.1444e-04; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14216. }
  14217. else {
  14218. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14219. }
  14220. }
  14221. else {
  14222. if (this.constants.clustering.enabled == true &&
  14223. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14224. zoomLevel = 77.5271985 / (numberOfNodes + 187.266146) + 4.76710517e-05; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14225. }
  14226. else {
  14227. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14228. }
  14229. }
  14230. // correct for larger canvasses.
  14231. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14232. zoomLevel *= factor;
  14233. }
  14234. else {
  14235. range = this._getRange(options.nodes);
  14236. var xDistance = Math.abs(range.maxX - range.minX) * 1.1;
  14237. var yDistance = Math.abs(range.maxY - range.minY) * 1.1;
  14238. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14239. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14240. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14241. }
  14242. if (zoomLevel > 1.0) {
  14243. zoomLevel = 1.0;
  14244. }
  14245. var center = this._findCenter(range);
  14246. if (disableStart == false) {
  14247. var options = {position: center, scale: zoomLevel, animation: options};
  14248. this.moveTo(options);
  14249. this.moving = true;
  14250. this.start();
  14251. }
  14252. else {
  14253. center.x *= zoomLevel;
  14254. center.y *= zoomLevel;
  14255. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14256. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14257. this._setScale(zoomLevel);
  14258. this._setTranslation(-center.x,-center.y);
  14259. }
  14260. };
  14261. /**
  14262. * Update the this.nodeIndices with the most recent node index list
  14263. * @private
  14264. */
  14265. Network.prototype._updateNodeIndexList = function() {
  14266. this._clearNodeIndexList();
  14267. for (var idx in this.nodes) {
  14268. if (this.nodes.hasOwnProperty(idx)) {
  14269. this.nodeIndices.push(idx);
  14270. }
  14271. }
  14272. };
  14273. /**
  14274. * Set nodes and edges, and optionally options as well.
  14275. *
  14276. * @param {Object} data Object containing parameters:
  14277. * {Array | DataSet | DataView} [nodes] Array with nodes
  14278. * {Array | DataSet | DataView} [edges] Array with edges
  14279. * {String} [dot] String containing data in DOT format
  14280. * {String} [gephi] String containing data in gephi JSON format
  14281. * {Options} [options] Object with options
  14282. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14283. */
  14284. Network.prototype.setData = function(data, disableStart) {
  14285. if (disableStart === undefined) {
  14286. disableStart = false;
  14287. }
  14288. // unselect all to ensure no selections from old data are carried over.
  14289. this._unselectAll(true);
  14290. // we set initializing to true to ensure that the hierarchical layout is not performed until both nodes and edges are added.
  14291. this.initializing = true;
  14292. if (data && data.dot && (data.nodes || data.edges)) {
  14293. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14294. ' parameter pair "nodes" and "edges", but not both.');
  14295. }
  14296. // clean up in case there is anyone in an active mode of the manipulation. This is the same option as bound to the escape button.
  14297. if (this.constants.dataManipulation.enabled == true) {
  14298. this._createManipulatorBar();
  14299. }
  14300. // set options
  14301. this.setOptions(data && data.options);
  14302. // set all data
  14303. if (data && data.dot) {
  14304. // parse DOT file
  14305. if(data && data.dot) {
  14306. var dotData = dotparser.DOTToGraph(data.dot);
  14307. this.setData(dotData);
  14308. return;
  14309. }
  14310. }
  14311. else if (data && data.gephi) {
  14312. // parse DOT file
  14313. if(data && data.gephi) {
  14314. var gephiData = gephiParser.parseGephi(data.gephi);
  14315. this.setData(gephiData);
  14316. return;
  14317. }
  14318. }
  14319. else {
  14320. this._setNodes(data && data.nodes);
  14321. this._setEdges(data && data.edges);
  14322. }
  14323. this._putDataInSector();
  14324. if (disableStart == false) {
  14325. if (this.constants.hierarchicalLayout.enabled == true) {
  14326. this._resetLevels();
  14327. this._setupHierarchicalLayout();
  14328. }
  14329. else {
  14330. // find a stable position or start animating to a stable position
  14331. if (this.constants.stabilize == true) {
  14332. this._stabilize();
  14333. }
  14334. }
  14335. this.start();
  14336. }
  14337. this.initializing = false;
  14338. };
  14339. /**
  14340. * Set options
  14341. * @param {Object} options
  14342. */
  14343. Network.prototype.setOptions = function (options) {
  14344. if (options) {
  14345. var prop;
  14346. var fields = ['nodes','edges','smoothCurves','hierarchicalLayout','clustering','navigation',
  14347. 'keyboard','dataManipulation','onAdd','onEdit','onEditEdge','onConnect','onDelete','clickToUse'
  14348. ];
  14349. // extend all but the values in fields
  14350. util.selectiveNotDeepExtend(fields,this.constants, options);
  14351. util.selectiveNotDeepExtend(['color'],this.constants.nodes, options.nodes);
  14352. util.selectiveNotDeepExtend(['color','length'],this.constants.edges, options.edges);
  14353. this.groups.useDefaultGroups = this.constants.useDefaultGroups;
  14354. if (options.physics) {
  14355. util.mergeOptions(this.constants.physics, options.physics,'barnesHut');
  14356. util.mergeOptions(this.constants.physics, options.physics,'repulsion');
  14357. if (options.physics.hierarchicalRepulsion) {
  14358. this.constants.hierarchicalLayout.enabled = true;
  14359. this.constants.physics.hierarchicalRepulsion.enabled = true;
  14360. this.constants.physics.barnesHut.enabled = false;
  14361. for (prop in options.physics.hierarchicalRepulsion) {
  14362. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  14363. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  14364. }
  14365. }
  14366. }
  14367. }
  14368. if (options.onAdd) {this.triggerFunctions.add = options.onAdd;}
  14369. if (options.onEdit) {this.triggerFunctions.edit = options.onEdit;}
  14370. if (options.onEditEdge) {this.triggerFunctions.editEdge = options.onEditEdge;}
  14371. if (options.onConnect) {this.triggerFunctions.connect = options.onConnect;}
  14372. if (options.onDelete) {this.triggerFunctions.del = options.onDelete;}
  14373. util.mergeOptions(this.constants, options,'smoothCurves');
  14374. util.mergeOptions(this.constants, options,'hierarchicalLayout');
  14375. util.mergeOptions(this.constants, options,'clustering');
  14376. util.mergeOptions(this.constants, options,'navigation');
  14377. util.mergeOptions(this.constants, options,'keyboard');
  14378. util.mergeOptions(this.constants, options,'dataManipulation');
  14379. if (options.dataManipulation) {
  14380. this.editMode = this.constants.dataManipulation.initiallyVisible;
  14381. }
  14382. // TODO: work out these options and document them
  14383. if (options.edges) {
  14384. if (options.edges.color !== undefined) {
  14385. if (util.isString(options.edges.color)) {
  14386. this.constants.edges.color = {};
  14387. this.constants.edges.color.color = options.edges.color;
  14388. this.constants.edges.color.highlight = options.edges.color;
  14389. this.constants.edges.color.hover = options.edges.color;
  14390. }
  14391. else {
  14392. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14393. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14394. if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;}
  14395. }
  14396. this.constants.edges.inheritColor = false;
  14397. }
  14398. if (!options.edges.fontColor) {
  14399. if (options.edges.color !== undefined) {
  14400. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14401. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14402. }
  14403. }
  14404. }
  14405. if (options.nodes) {
  14406. if (options.nodes.color) {
  14407. var newColorObj = util.parseColor(options.nodes.color);
  14408. this.constants.nodes.color.background = newColorObj.background;
  14409. this.constants.nodes.color.border = newColorObj.border;
  14410. this.constants.nodes.color.highlight.background = newColorObj.highlight.background;
  14411. this.constants.nodes.color.highlight.border = newColorObj.highlight.border;
  14412. this.constants.nodes.color.hover.background = newColorObj.hover.background;
  14413. this.constants.nodes.color.hover.border = newColorObj.hover.border;
  14414. }
  14415. }
  14416. if (options.groups) {
  14417. for (var groupname in options.groups) {
  14418. if (options.groups.hasOwnProperty(groupname)) {
  14419. var group = options.groups[groupname];
  14420. this.groups.add(groupname, group);
  14421. }
  14422. }
  14423. }
  14424. if (options.tooltip) {
  14425. for (prop in options.tooltip) {
  14426. if (options.tooltip.hasOwnProperty(prop)) {
  14427. this.constants.tooltip[prop] = options.tooltip[prop];
  14428. }
  14429. }
  14430. if (options.tooltip.color) {
  14431. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  14432. }
  14433. }
  14434. if ('clickToUse' in options) {
  14435. if (options.clickToUse) {
  14436. if (!this.activator) {
  14437. this.activator = new Activator(this.frame);
  14438. this.activator.on('change', this._createKeyBinds.bind(this));
  14439. }
  14440. }
  14441. else {
  14442. if (this.activator) {
  14443. this.activator.destroy();
  14444. delete this.activator;
  14445. }
  14446. }
  14447. }
  14448. if (options.labels) {
  14449. throw new Error('Option "labels" is deprecated. Use options "locale" and "locales" instead.');
  14450. }
  14451. // (Re)loading the mixins that can be enabled or disabled in the options.
  14452. // load the force calculation functions, grouped under the physics system.
  14453. this._loadPhysicsSystem();
  14454. // load the navigation system.
  14455. this._loadNavigationControls();
  14456. // load the data manipulation system
  14457. this._loadManipulationSystem();
  14458. // configure the smooth curves
  14459. this._configureSmoothCurves();
  14460. // bind hammer
  14461. this._bindHammer();
  14462. // bind keys. If disabled, this will not do anything;
  14463. this._createKeyBinds();
  14464. this._markAllEdgesAsDirty();
  14465. this.setSize(this.constants.width, this.constants.height);
  14466. this.moving = true;
  14467. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14468. this._resetLevels();
  14469. this._setupHierarchicalLayout();
  14470. }
  14471. this.start();
  14472. }
  14473. };
  14474. /**
  14475. * Create the main frame for the Network.
  14476. * This function is executed once when a Network object is created. The frame
  14477. * contains a canvas, and this canvas contains all objects like the axis and
  14478. * nodes.
  14479. * @private
  14480. */
  14481. Network.prototype._create = function () {
  14482. // remove all elements from the container element.
  14483. while (this.containerElement.hasChildNodes()) {
  14484. this.containerElement.removeChild(this.containerElement.firstChild);
  14485. }
  14486. this.frame = document.createElement('div');
  14487. this.frame.className = 'vis network-frame';
  14488. this.frame.style.position = 'relative';
  14489. this.frame.style.overflow = 'hidden';
  14490. this.frame.tabIndex = 900;
  14491. //////////////////////////////////////////////////////////////////
  14492. this.frame.canvas = document.createElement("canvas");
  14493. this.frame.canvas.style.position = 'relative';
  14494. this.frame.appendChild(this.frame.canvas);
  14495. if (!this.frame.canvas.getContext) {
  14496. var noCanvas = document.createElement( 'DIV' );
  14497. noCanvas.style.color = 'red';
  14498. noCanvas.style.fontWeight = 'bold' ;
  14499. noCanvas.style.padding = '10px';
  14500. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14501. this.frame.canvas.appendChild(noCanvas);
  14502. }
  14503. else {
  14504. var ctx = this.frame.canvas.getContext("2d");
  14505. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  14506. ctx.mozBackingStorePixelRatio ||
  14507. ctx.msBackingStorePixelRatio ||
  14508. ctx.oBackingStorePixelRatio ||
  14509. ctx.backingStorePixelRatio || 1);
  14510. //this.pixelRatio = Math.max(1,this.pixelRatio); // this is to account for browser zooming out. The pixel ratio is ment to switch between 1 and 2 for HD screens.
  14511. this.frame.canvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  14512. }
  14513. this._bindHammer();
  14514. };
  14515. /**
  14516. * This function binds hammer, it can be repeated over and over due to the uniqueness check.
  14517. * @private
  14518. */
  14519. Network.prototype._bindHammer = function() {
  14520. var me = this;
  14521. if (this.hammer !== undefined) {
  14522. this.hammer.dispose();
  14523. }
  14524. this.drag = {};
  14525. this.pinch = {};
  14526. this.hammer = Hammer(this.frame.canvas, {
  14527. prevent_default: true
  14528. });
  14529. this.hammer.on('tap', me._onTap.bind(me) );
  14530. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14531. this.hammer.on('hold', me._onHold.bind(me) );
  14532. this.hammer.on('touch', me._onTouch.bind(me) );
  14533. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14534. this.hammer.on('drag', me._onDrag.bind(me) );
  14535. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14536. if (this.constants.zoomable == true) {
  14537. this.hammer.on('mousewheel', me._onMouseWheel.bind(me));
  14538. this.hammer.on('DOMMouseScroll', me._onMouseWheel.bind(me)); // for FF
  14539. this.hammer.on('pinch', me._onPinch.bind(me) );
  14540. }
  14541. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14542. this.hammerFrame = Hammer(this.frame, {
  14543. prevent_default: true
  14544. });
  14545. this.hammerFrame.on('release', me._onRelease.bind(me) );
  14546. // add the frame to the container element
  14547. this.containerElement.appendChild(this.frame);
  14548. }
  14549. /**
  14550. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14551. * @private
  14552. */
  14553. Network.prototype._createKeyBinds = function() {
  14554. var me = this;
  14555. if (this.keycharm !== undefined) {
  14556. this.keycharm.destroy();
  14557. }
  14558. if (this.constants.keyboard.bindToWindow == true) {
  14559. this.keycharm = keycharm({container: window, preventDefault: false});
  14560. }
  14561. else {
  14562. this.keycharm = keycharm({container: this.frame, preventDefault: false});
  14563. }
  14564. this.keycharm.reset();
  14565. if (this.constants.keyboard.enabled && this.isActive()) {
  14566. this.keycharm.bind("up", this._moveUp.bind(me) , "keydown");
  14567. this.keycharm.bind("up", this._yStopMoving.bind(me), "keyup");
  14568. this.keycharm.bind("down", this._moveDown.bind(me) , "keydown");
  14569. this.keycharm.bind("down", this._yStopMoving.bind(me), "keyup");
  14570. this.keycharm.bind("left", this._moveLeft.bind(me) , "keydown");
  14571. this.keycharm.bind("left", this._xStopMoving.bind(me), "keyup");
  14572. this.keycharm.bind("right",this._moveRight.bind(me), "keydown");
  14573. this.keycharm.bind("right",this._xStopMoving.bind(me), "keyup");
  14574. this.keycharm.bind("=", this._zoomIn.bind(me), "keydown");
  14575. this.keycharm.bind("=", this._stopZoom.bind(me), "keyup");
  14576. this.keycharm.bind("num+", this._zoomIn.bind(me), "keydown");
  14577. this.keycharm.bind("num+", this._stopZoom.bind(me), "keyup");
  14578. this.keycharm.bind("num-", this._zoomOut.bind(me), "keydown");
  14579. this.keycharm.bind("num-", this._stopZoom.bind(me), "keyup");
  14580. this.keycharm.bind("-", this._zoomOut.bind(me), "keydown");
  14581. this.keycharm.bind("-", this._stopZoom.bind(me), "keyup");
  14582. this.keycharm.bind("[", this._zoomIn.bind(me), "keydown");
  14583. this.keycharm.bind("[", this._stopZoom.bind(me), "keyup");
  14584. this.keycharm.bind("]", this._zoomOut.bind(me), "keydown");
  14585. this.keycharm.bind("]", this._stopZoom.bind(me), "keyup");
  14586. this.keycharm.bind("pageup",this._zoomIn.bind(me), "keydown");
  14587. this.keycharm.bind("pageup",this._stopZoom.bind(me), "keyup");
  14588. this.keycharm.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14589. this.keycharm.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14590. }
  14591. if (this.constants.dataManipulation.enabled == true) {
  14592. this.keycharm.bind("esc",this._createManipulatorBar.bind(me));
  14593. this.keycharm.bind("delete",this._deleteSelected.bind(me));
  14594. }
  14595. };
  14596. /**
  14597. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  14598. * var network = new vis.Network(..);
  14599. * network.destroy();
  14600. * network = null;
  14601. */
  14602. Network.prototype.destroy = function() {
  14603. this.start = function () {};
  14604. this.redraw = function () {};
  14605. this.timer = false;
  14606. // cleanup physicsConfiguration if it exists
  14607. this._cleanupPhysicsConfiguration();
  14608. // remove keybindings
  14609. this.keycharm.reset();
  14610. // clear hammer bindings
  14611. this.hammer.dispose();
  14612. // clear events
  14613. this.off();
  14614. this._recursiveDOMDelete(this.containerElement);
  14615. }
  14616. Network.prototype._recursiveDOMDelete = function(DOMobject) {
  14617. while (DOMobject.hasChildNodes() == true) {
  14618. this._recursiveDOMDelete(DOMobject.firstChild);
  14619. DOMobject.removeChild(DOMobject.firstChild);
  14620. }
  14621. }
  14622. /**
  14623. * Get the pointer location from a touch location
  14624. * @param {{pageX: Number, pageY: Number}} touch
  14625. * @return {{x: Number, y: Number}} pointer
  14626. * @private
  14627. */
  14628. Network.prototype._getPointer = function (touch) {
  14629. return {
  14630. x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas),
  14631. y: touch.pageY - util.getAbsoluteTop(this.frame.canvas)
  14632. };
  14633. };
  14634. /**
  14635. * On start of a touch gesture, store the pointer
  14636. * @param event
  14637. * @private
  14638. */
  14639. Network.prototype._onTouch = function (event) {
  14640. if (new Date().valueOf() - this.touchTime > 100) {
  14641. this.drag.pointer = this._getPointer(event.gesture.center);
  14642. this.drag.pinched = false;
  14643. this.pinch.scale = this._getScale();
  14644. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  14645. this.touchTime = new Date().valueOf();
  14646. this._handleTouch(this.drag.pointer);
  14647. }
  14648. };
  14649. /**
  14650. * handle drag start event
  14651. * @private
  14652. */
  14653. Network.prototype._onDragStart = function (event) {
  14654. this._handleDragStart(event);
  14655. };
  14656. /**
  14657. * This function is called by _onDragStart.
  14658. * It is separated out because we can then overload it for the datamanipulation system.
  14659. *
  14660. * @private
  14661. */
  14662. Network.prototype._handleDragStart = function(event) {
  14663. // in case the touch event was triggered on an external div, do the initial touch now.
  14664. if (this.drag.pointer === undefined) {
  14665. this._onTouch(event);
  14666. }
  14667. var node = this._getNodeAt(this.drag.pointer);
  14668. // note: drag.pointer is set in _onTouch to get the initial touch location
  14669. this.drag.dragging = true;
  14670. this.drag.selection = [];
  14671. this.drag.translation = this._getTranslation();
  14672. this.drag.nodeId = null;
  14673. this.draggingNodes = false;
  14674. if (node != null && this.constants.dragNodes == true) {
  14675. this.draggingNodes = true;
  14676. this.drag.nodeId = node.id;
  14677. // select the clicked node if not yet selected
  14678. if (!node.isSelected()) {
  14679. this._selectObject(node,false);
  14680. }
  14681. this.emit("dragStart",{nodeIds:this.getSelection().nodes});
  14682. // create an array with the selected nodes and their original location and status
  14683. for (var objectId in this.selectionObj.nodes) {
  14684. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14685. var object = this.selectionObj.nodes[objectId];
  14686. var s = {
  14687. id: object.id,
  14688. node: object,
  14689. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14690. x: object.x,
  14691. y: object.y,
  14692. xFixed: object.xFixed,
  14693. yFixed: object.yFixed
  14694. };
  14695. object.xFixed = true;
  14696. object.yFixed = true;
  14697. this.drag.selection.push(s);
  14698. }
  14699. }
  14700. }
  14701. };
  14702. /**
  14703. * handle drag event
  14704. * @private
  14705. */
  14706. Network.prototype._onDrag = function (event) {
  14707. this._handleOnDrag(event)
  14708. };
  14709. /**
  14710. * This function is called by _onDrag.
  14711. * It is separated out because we can then overload it for the datamanipulation system.
  14712. *
  14713. * @private
  14714. */
  14715. Network.prototype._handleOnDrag = function(event) {
  14716. if (this.drag.pinched) {
  14717. return;
  14718. }
  14719. // remove the focus on node if it is focussed on by the focusOnNode
  14720. this.releaseNode();
  14721. var pointer = this._getPointer(event.gesture.center);
  14722. var me = this;
  14723. var drag = this.drag;
  14724. var selection = drag.selection;
  14725. if (selection && selection.length && this.constants.dragNodes == true) {
  14726. // calculate delta's and new location
  14727. var deltaX = pointer.x - drag.pointer.x;
  14728. var deltaY = pointer.y - drag.pointer.y;
  14729. // update position of all selected nodes
  14730. selection.forEach(function (s) {
  14731. var node = s.node;
  14732. if (!s.xFixed) {
  14733. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  14734. }
  14735. if (!s.yFixed) {
  14736. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  14737. }
  14738. });
  14739. // start _animationStep if not yet running
  14740. if (!this.moving) {
  14741. this.moving = true;
  14742. this.start();
  14743. }
  14744. }
  14745. else {
  14746. // move the network
  14747. if (this.constants.dragNetwork == true) {
  14748. // if the drag was not started properly because the click started outside the network div, start it now.
  14749. if (this.drag.pointer === undefined) {
  14750. this._handleDragStart(event);
  14751. return;
  14752. }
  14753. var diffX = pointer.x - this.drag.pointer.x;
  14754. var diffY = pointer.y - this.drag.pointer.y;
  14755. this._setTranslation(
  14756. this.drag.translation.x + diffX,
  14757. this.drag.translation.y + diffY
  14758. );
  14759. this._redraw();
  14760. }
  14761. }
  14762. };
  14763. /**
  14764. * handle drag start event
  14765. * @private
  14766. */
  14767. Network.prototype._onDragEnd = function (event) {
  14768. this._handleDragEnd(event);
  14769. };
  14770. Network.prototype._handleDragEnd = function(event) {
  14771. this.drag.dragging = false;
  14772. var selection = this.drag.selection;
  14773. if (selection && selection.length) {
  14774. selection.forEach(function (s) {
  14775. // restore original xFixed and yFixed
  14776. s.node.xFixed = s.xFixed;
  14777. s.node.yFixed = s.yFixed;
  14778. });
  14779. this.moving = true;
  14780. this.start();
  14781. }
  14782. else {
  14783. this._redraw();
  14784. }
  14785. if (this.draggingNodes == false) {
  14786. this.emit("dragEnd",{nodeIds:[]});
  14787. }
  14788. else {
  14789. this.emit("dragEnd",{nodeIds:this.getSelection().nodes});
  14790. }
  14791. }
  14792. /**
  14793. * handle tap/click event: select/unselect a node
  14794. * @private
  14795. */
  14796. Network.prototype._onTap = function (event) {
  14797. var pointer = this._getPointer(event.gesture.center);
  14798. this.pointerPosition = pointer;
  14799. this._handleTap(pointer);
  14800. };
  14801. /**
  14802. * handle doubletap event
  14803. * @private
  14804. */
  14805. Network.prototype._onDoubleTap = function (event) {
  14806. var pointer = this._getPointer(event.gesture.center);
  14807. this._handleDoubleTap(pointer);
  14808. };
  14809. /**
  14810. * handle long tap event: multi select nodes
  14811. * @private
  14812. */
  14813. Network.prototype._onHold = function (event) {
  14814. var pointer = this._getPointer(event.gesture.center);
  14815. this.pointerPosition = pointer;
  14816. this._handleOnHold(pointer);
  14817. };
  14818. /**
  14819. * handle the release of the screen
  14820. *
  14821. * @private
  14822. */
  14823. Network.prototype._onRelease = function (event) {
  14824. var pointer = this._getPointer(event.gesture.center);
  14825. this._handleOnRelease(pointer);
  14826. };
  14827. /**
  14828. * Handle pinch event
  14829. * @param event
  14830. * @private
  14831. */
  14832. Network.prototype._onPinch = function (event) {
  14833. var pointer = this._getPointer(event.gesture.center);
  14834. this.drag.pinched = true;
  14835. if (!('scale' in this.pinch)) {
  14836. this.pinch.scale = 1;
  14837. }
  14838. // TODO: enabled moving while pinching?
  14839. var scale = this.pinch.scale * event.gesture.scale;
  14840. this._zoom(scale, pointer)
  14841. };
  14842. /**
  14843. * Zoom the network in or out
  14844. * @param {Number} scale a number around 1, and between 0.01 and 10
  14845. * @param {{x: Number, y: Number}} pointer Position on screen
  14846. * @return {Number} appliedScale scale is limited within the boundaries
  14847. * @private
  14848. */
  14849. Network.prototype._zoom = function(scale, pointer) {
  14850. if (this.constants.zoomable == true) {
  14851. var scaleOld = this._getScale();
  14852. if (scale < 0.00001) {
  14853. scale = 0.00001;
  14854. }
  14855. if (scale > 10) {
  14856. scale = 10;
  14857. }
  14858. var preScaleDragPointer = null;
  14859. if (this.drag !== undefined) {
  14860. if (this.drag.dragging == true) {
  14861. preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
  14862. }
  14863. }
  14864. // + this.frame.canvas.clientHeight / 2
  14865. var translation = this._getTranslation();
  14866. var scaleFrac = scale / scaleOld;
  14867. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14868. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14869. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  14870. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  14871. this._setScale(scale);
  14872. this._setTranslation(tx, ty);
  14873. this.updateClustersDefault();
  14874. if (preScaleDragPointer != null) {
  14875. var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
  14876. this.drag.pointer.x = postScaleDragPointer.x;
  14877. this.drag.pointer.y = postScaleDragPointer.y;
  14878. }
  14879. this._redraw();
  14880. if (scaleOld < scale) {
  14881. this.emit("zoom", {direction:"+"});
  14882. }
  14883. else {
  14884. this.emit("zoom", {direction:"-"});
  14885. }
  14886. return scale;
  14887. }
  14888. };
  14889. /**
  14890. * Event handler for mouse wheel event, used to zoom the timeline
  14891. * See http://adomas.org/javascript-mouse-wheel/
  14892. * https://github.com/EightMedia/hammer.js/issues/256
  14893. * @param {MouseEvent} event
  14894. * @private
  14895. */
  14896. Network.prototype._onMouseWheel = function(event) {
  14897. // retrieve delta
  14898. var delta = 0;
  14899. if (event.wheelDelta) { /* IE/Opera. */
  14900. delta = event.wheelDelta/120;
  14901. } else if (event.detail) { /* Mozilla case. */
  14902. // In Mozilla, sign of delta is different than in IE.
  14903. // Also, delta is multiple of 3.
  14904. delta = -event.detail/3;
  14905. }
  14906. // If delta is nonzero, handle it.
  14907. // Basically, delta is now positive if wheel was scrolled up,
  14908. // and negative, if wheel was scrolled down.
  14909. if (delta) {
  14910. // calculate the new scale
  14911. var scale = this._getScale();
  14912. var zoom = delta / 10;
  14913. if (delta < 0) {
  14914. zoom = zoom / (1 - zoom);
  14915. }
  14916. scale *= (1 + zoom);
  14917. // calculate the pointer location
  14918. var gesture = hammerUtil.fakeGesture(this, event);
  14919. var pointer = this._getPointer(gesture.center);
  14920. // apply the new scale
  14921. this._zoom(scale, pointer);
  14922. }
  14923. // Prevent default actions caused by mouse wheel.
  14924. event.preventDefault();
  14925. };
  14926. /**
  14927. * Mouse move handler for checking whether the title moves over a node with a title.
  14928. * @param {Event} event
  14929. * @private
  14930. */
  14931. Network.prototype._onMouseMoveTitle = function (event) {
  14932. var gesture = hammerUtil.fakeGesture(this, event);
  14933. var pointer = this._getPointer(gesture.center);
  14934. var popupVisible = false;
  14935. // check if the previously selected node is still selected
  14936. if (this.popup !== undefined) {
  14937. if (this.popup.hidden === false) {
  14938. this._checkHidePopup(pointer);
  14939. }
  14940. // if the popup was not hidden above
  14941. if (this.popup.hidden === false) {
  14942. popupVisible = true;
  14943. this.popup.setPosition(pointer.x + 3,pointer.y - 5)
  14944. this.popup.show();
  14945. }
  14946. }
  14947. // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over
  14948. if (this.constants.keyboard.bindToWindow == false && this.constants.keyboard.enabled == true) {
  14949. this.frame.focus();
  14950. }
  14951. // start a timeout that will check if the mouse is positioned above an element
  14952. if (popupVisible === false) {
  14953. var me = this;
  14954. var checkShow = function () {
  14955. me._checkShowPopup(pointer);
  14956. };
  14957. if (this.popupTimer) {
  14958. clearInterval(this.popupTimer); // stop any running calculationTimer
  14959. }
  14960. if (!this.drag.dragging) {
  14961. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  14962. }
  14963. }
  14964. /**
  14965. * Adding hover highlights
  14966. */
  14967. if (this.constants.hover == true) {
  14968. // removing all hover highlights
  14969. for (var edgeId in this.hoverObj.edges) {
  14970. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  14971. this.hoverObj.edges[edgeId].hover = false;
  14972. delete this.hoverObj.edges[edgeId];
  14973. }
  14974. }
  14975. // adding hover highlights
  14976. var obj = this._getNodeAt(pointer);
  14977. if (obj == null) {
  14978. obj = this._getEdgeAt(pointer);
  14979. }
  14980. if (obj != null) {
  14981. this._hoverObject(obj);
  14982. }
  14983. // removing all node hover highlights except for the selected one.
  14984. for (var nodeId in this.hoverObj.nodes) {
  14985. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  14986. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  14987. this._blurObject(this.hoverObj.nodes[nodeId]);
  14988. delete this.hoverObj.nodes[nodeId];
  14989. }
  14990. }
  14991. }
  14992. this.redraw();
  14993. }
  14994. };
  14995. /**
  14996. * Check if there is an element on the given position in the network
  14997. * (a node or edge). If so, and if this element has a title,
  14998. * show a popup window with its title.
  14999. *
  15000. * @param {{x:Number, y:Number}} pointer
  15001. * @private
  15002. */
  15003. Network.prototype._checkShowPopup = function (pointer) {
  15004. var obj = {
  15005. left: this._XconvertDOMtoCanvas(pointer.x),
  15006. top: this._YconvertDOMtoCanvas(pointer.y),
  15007. right: this._XconvertDOMtoCanvas(pointer.x),
  15008. bottom: this._YconvertDOMtoCanvas(pointer.y)
  15009. };
  15010. var id;
  15011. var previousPopupObjId = this.popupObj === undefined ? "" : this.popupObj.id;
  15012. var nodeUnderCursor = false;
  15013. var popupType = "node";
  15014. if (this.popupObj == undefined) {
  15015. // search the nodes for overlap, select the top one in case of multiple nodes
  15016. var nodes = this.nodes;
  15017. var overlappingNodes = [];
  15018. for (id in nodes) {
  15019. if (nodes.hasOwnProperty(id)) {
  15020. var node = nodes[id];
  15021. if (node.isOverlappingWith(obj)) {
  15022. if (node.getTitle() !== undefined) {
  15023. overlappingNodes.push(id);
  15024. }
  15025. }
  15026. }
  15027. }
  15028. if (overlappingNodes.length > 0) {
  15029. // if there are overlapping nodes, select the last one, this is the
  15030. // one which is drawn on top of the others
  15031. this.popupObj = this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  15032. // if you hover over a node, the title of the edge is not supposed to be shown.
  15033. nodeUnderCursor = true;
  15034. }
  15035. }
  15036. if (this.popupObj === undefined && nodeUnderCursor == false) {
  15037. // search the edges for overlap
  15038. var edges = this.edges;
  15039. var overlappingEdges = [];
  15040. for (id in edges) {
  15041. if (edges.hasOwnProperty(id)) {
  15042. var edge = edges[id];
  15043. if (edge.connected && (edge.getTitle() !== undefined) &&
  15044. edge.isOverlappingWith(obj)) {
  15045. overlappingEdges.push(id);
  15046. }
  15047. }
  15048. }
  15049. if (overlappingEdges.length > 0) {
  15050. this.popupObj = this.edges[overlappingEdges[overlappingEdges.length - 1]];
  15051. popupType = "edge";
  15052. }
  15053. }
  15054. if (this.popupObj) {
  15055. // show popup message window
  15056. if (this.popupObj.id != previousPopupObjId) {
  15057. if (this.popup === undefined) {
  15058. this.popup = new Popup(this.frame, this.constants.tooltip);
  15059. }
  15060. this.popup.popupTargetType = popupType;
  15061. this.popup.popupTargetId = this.popupObj.id;
  15062. // adjust a small offset such that the mouse cursor is located in the
  15063. // bottom left location of the popup, and you can easily move over the
  15064. // popup area
  15065. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  15066. this.popup.setText(this.popupObj.getTitle());
  15067. this.popup.show();
  15068. }
  15069. }
  15070. else {
  15071. if (this.popup) {
  15072. this.popup.hide();
  15073. }
  15074. }
  15075. };
  15076. /**
  15077. * Check if the popup must be hidden, which is the case when the mouse is no
  15078. * longer hovering on the object
  15079. * @param {{x:Number, y:Number}} pointer
  15080. * @private
  15081. */
  15082. Network.prototype._checkHidePopup = function (pointer) {
  15083. var pointerObj = {
  15084. left: this._XconvertDOMtoCanvas(pointer.x),
  15085. top: this._YconvertDOMtoCanvas(pointer.y),
  15086. right: this._XconvertDOMtoCanvas(pointer.x),
  15087. bottom: this._YconvertDOMtoCanvas(pointer.y)
  15088. };
  15089. var stillOnObj = false;
  15090. if (this.popup.popupTargetType == 'node') {
  15091. stillOnObj = this.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  15092. if (stillOnObj === true) {
  15093. var overNode = this._getNodeAt(pointer);
  15094. stillOnObj = overNode.id == this.popup.popupTargetId;
  15095. }
  15096. }
  15097. else {
  15098. if (this._getNodeAt(pointer) === null) {
  15099. stillOnObj = this.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  15100. }
  15101. }
  15102. if (stillOnObj === false) {
  15103. this.popupObj = undefined;
  15104. this.popup.hide();
  15105. }
  15106. };
  15107. /**
  15108. * Set a new size for the network
  15109. * @param {string} width Width in pixels or percentage (for example '800px'
  15110. * or '50%')
  15111. * @param {string} height Height in pixels or percentage (for example '400px'
  15112. * or '30%')
  15113. */
  15114. Network.prototype.setSize = function(width, height) {
  15115. var emitEvent = false;
  15116. var oldWidth = this.frame.canvas.width;
  15117. var oldHeight = this.frame.canvas.height;
  15118. if (width != this.constants.width || height != this.constants.height || this.frame.style.width != width || this.frame.style.height != height) {
  15119. this.frame.style.width = width;
  15120. this.frame.style.height = height;
  15121. this.frame.canvas.style.width = '100%';
  15122. this.frame.canvas.style.height = '100%';
  15123. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  15124. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  15125. this.constants.width = width;
  15126. this.constants.height = height;
  15127. emitEvent = true;
  15128. }
  15129. else {
  15130. // this would adapt the width of the canvas to the width from 100% if and only if
  15131. // there is a change.
  15132. if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) {
  15133. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  15134. emitEvent = true;
  15135. }
  15136. if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) {
  15137. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  15138. emitEvent = true;
  15139. }
  15140. }
  15141. if (emitEvent == true) {
  15142. this.emit('resize', {width:this.frame.canvas.width * this.pixelRatio,height:this.frame.canvas.height * this.pixelRatio, oldWidth: oldWidth * this.pixelRatio, oldHeight: oldHeight * this.pixelRatio});
  15143. }
  15144. };
  15145. /**
  15146. * Set a data set with nodes for the network
  15147. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  15148. * @private
  15149. */
  15150. Network.prototype._setNodes = function(nodes) {
  15151. var oldNodesData = this.nodesData;
  15152. if (nodes instanceof DataSet || nodes instanceof DataView) {
  15153. this.nodesData = nodes;
  15154. }
  15155. else if (Array.isArray(nodes)) {
  15156. this.nodesData = new DataSet();
  15157. this.nodesData.add(nodes);
  15158. }
  15159. else if (!nodes) {
  15160. this.nodesData = new DataSet();
  15161. }
  15162. else {
  15163. throw new TypeError('Array or DataSet expected');
  15164. }
  15165. if (oldNodesData) {
  15166. // unsubscribe from old dataset
  15167. util.forEach(this.nodesListeners, function (callback, event) {
  15168. oldNodesData.off(event, callback);
  15169. });
  15170. }
  15171. // remove drawn nodes
  15172. this.nodes = {};
  15173. if (this.nodesData) {
  15174. // subscribe to new dataset
  15175. var me = this;
  15176. util.forEach(this.nodesListeners, function (callback, event) {
  15177. me.nodesData.on(event, callback);
  15178. });
  15179. // draw all new nodes
  15180. var ids = this.nodesData.getIds();
  15181. this._addNodes(ids);
  15182. }
  15183. this._updateSelection();
  15184. };
  15185. /**
  15186. * Add nodes
  15187. * @param {Number[] | String[]} ids
  15188. * @private
  15189. */
  15190. Network.prototype._addNodes = function(ids) {
  15191. var id;
  15192. var fieldId = this.nodesData._fieldId || null;
  15193. for (var i = 0, len = ids.length; i < len; i++) {
  15194. id = ids[i];
  15195. var data = this.nodesData.get(id);
  15196. if (fieldId) {
  15197. data.id = data[fieldId];
  15198. }
  15199. var node = new Node(data, this.images, this.groups, this.constants);
  15200. this.nodes[id] = node; // note: this may replace an existing node
  15201. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  15202. var radius = 10 * 0.1*ids.length + 10;
  15203. var angle = 2 * Math.PI * Math.random();
  15204. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  15205. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  15206. }
  15207. this.moving = true;
  15208. }
  15209. this._updateNodeIndexList();
  15210. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15211. this._resetLevels();
  15212. this._setupHierarchicalLayout();
  15213. }
  15214. this._updateCalculationNodes();
  15215. this._reconnectEdges();
  15216. this._updateValueRange(this.nodes);
  15217. this.updateLabels();
  15218. };
  15219. /**
  15220. * Update existing nodes, or create them when not yet existing
  15221. * @param {Number[] | String[]} ids
  15222. * @private
  15223. */
  15224. Network.prototype._updateNodes = function(ids) {
  15225. var nodesData = this.nodesData.get(ids);
  15226. var nodes = this.nodes;
  15227. for (var i = 0, len = ids.length; i < len; i++) {
  15228. var id = ids[i];
  15229. var node = nodes[id];
  15230. var data = nodesData[i];
  15231. if (node) {
  15232. // update node
  15233. node.setProperties(data, this.constants);
  15234. }
  15235. else {
  15236. // create node
  15237. node = new Node(properties, this.images, this.groups, this.constants);
  15238. nodes[id] = node;
  15239. }
  15240. }
  15241. this.moving = true;
  15242. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15243. this._resetLevels();
  15244. this._setupHierarchicalLayout();
  15245. }
  15246. this._updateNodeIndexList();
  15247. this._updateValueRange(nodes);
  15248. this._markAllEdgesAsDirty();
  15249. };
  15250. Network.prototype._markAllEdgesAsDirty = function() {
  15251. for (var edgeId in this.edges) {
  15252. this.edges[edgeId].colorDirty = true;
  15253. }
  15254. }
  15255. /**
  15256. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  15257. * @param {Number[] | String[]} ids
  15258. * @private
  15259. */
  15260. Network.prototype._removeNodes = function(ids) {
  15261. var nodes = this.nodes;
  15262. // remove from selection
  15263. for (var i = 0, len = ids.length; i < len; i++) {
  15264. if (this.selectionObj.nodes[ids[i]] !== undefined) {
  15265. this.nodes[ids[i]].unselect();
  15266. this._removeFromSelection(this.nodes[ids[i]]);
  15267. }
  15268. }
  15269. for (var i = 0, len = ids.length; i < len; i++) {
  15270. var id = ids[i];
  15271. delete nodes[id];
  15272. }
  15273. this._updateNodeIndexList();
  15274. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15275. this._resetLevels();
  15276. this._setupHierarchicalLayout();
  15277. }
  15278. this._updateCalculationNodes();
  15279. this._reconnectEdges();
  15280. this._updateSelection();
  15281. this._updateValueRange(nodes);
  15282. };
  15283. /**
  15284. * Load edges by reading the data table
  15285. * @param {Array | DataSet | DataView} edges The data containing the edges.
  15286. * @private
  15287. * @private
  15288. */
  15289. Network.prototype._setEdges = function(edges) {
  15290. var oldEdgesData = this.edgesData;
  15291. if (edges instanceof DataSet || edges instanceof DataView) {
  15292. this.edgesData = edges;
  15293. }
  15294. else if (Array.isArray(edges)) {
  15295. this.edgesData = new DataSet();
  15296. this.edgesData.add(edges);
  15297. }
  15298. else if (!edges) {
  15299. this.edgesData = new DataSet();
  15300. }
  15301. else {
  15302. throw new TypeError('Array or DataSet expected');
  15303. }
  15304. if (oldEdgesData) {
  15305. // unsubscribe from old dataset
  15306. util.forEach(this.edgesListeners, function (callback, event) {
  15307. oldEdgesData.off(event, callback);
  15308. });
  15309. }
  15310. // remove drawn edges
  15311. this.edges = {};
  15312. if (this.edgesData) {
  15313. // subscribe to new dataset
  15314. var me = this;
  15315. util.forEach(this.edgesListeners, function (callback, event) {
  15316. me.edgesData.on(event, callback);
  15317. });
  15318. // draw all new nodes
  15319. var ids = this.edgesData.getIds();
  15320. this._addEdges(ids);
  15321. }
  15322. this._reconnectEdges();
  15323. };
  15324. /**
  15325. * Add edges
  15326. * @param {Number[] | String[]} ids
  15327. * @private
  15328. */
  15329. Network.prototype._addEdges = function (ids) {
  15330. var edges = this.edges;
  15331. var edgesData = this.edgesData;
  15332. var fieldId = this.edgesData._fieldId;
  15333. for (var i = 0, len = ids.length; i < len; i++) {
  15334. var id = ids[i];
  15335. var oldEdge = edges[id];
  15336. if (oldEdge) {
  15337. oldEdge.disconnect();
  15338. }
  15339. var data = edgesData.get(id, {"showInternalIds" : true});
  15340. if (fieldId) {
  15341. data.id = data[fieldId];
  15342. }
  15343. edges[id] = new Edge(data, this, this.constants);
  15344. }
  15345. this.moving = true;
  15346. this._updateValueRange(edges);
  15347. this._createBezierNodes();
  15348. this._updateCalculationNodes();
  15349. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15350. this._resetLevels();
  15351. this._setupHierarchicalLayout();
  15352. }
  15353. };
  15354. /**
  15355. * Update existing edges, or create them when not yet existing
  15356. * @param {Number[] | String[]} ids
  15357. * @private
  15358. */
  15359. Network.prototype._updateEdges = function (ids) {
  15360. var edges = this.edges,
  15361. edgesData = this.edgesData;
  15362. for (var i = 0, len = ids.length; i < len; i++) {
  15363. var id = ids[i];
  15364. var data = edgesData.get(id);
  15365. var edge = edges[id];
  15366. if (edge) {
  15367. // update edge
  15368. edge.disconnect();
  15369. edge.setProperties(data, this.constants);
  15370. edge.connect();
  15371. }
  15372. else {
  15373. // create edge
  15374. edge = new Edge(data, this, this.constants);
  15375. this.edges[id] = edge;
  15376. }
  15377. }
  15378. this._createBezierNodes();
  15379. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15380. this._resetLevels();
  15381. this._setupHierarchicalLayout();
  15382. }
  15383. this.moving = true;
  15384. this._updateValueRange(edges);
  15385. };
  15386. /**
  15387. * Remove existing edges. Non existing ids will be ignored
  15388. * @param {Number[] | String[]} ids
  15389. * @private
  15390. */
  15391. Network.prototype._removeEdges = function (ids) {
  15392. var edges = this.edges;
  15393. // remove from selection
  15394. for (var i = 0, len = ids.length; i < len; i++) {
  15395. if (this.selectionObj.edges[ids[i]] !== undefined) {
  15396. edges[ids[i]].unselect();
  15397. this._removeFromSelection(edges[ids[i]]);
  15398. }
  15399. }
  15400. for (var i = 0, len = ids.length; i < len; i++) {
  15401. var id = ids[i];
  15402. var edge = edges[id];
  15403. if (edge) {
  15404. if (edge.via != null) {
  15405. delete this.sectors['support']['nodes'][edge.via.id];
  15406. }
  15407. edge.disconnect();
  15408. delete edges[id];
  15409. }
  15410. }
  15411. this.moving = true;
  15412. this._updateValueRange(edges);
  15413. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15414. this._resetLevels();
  15415. this._setupHierarchicalLayout();
  15416. }
  15417. this._updateCalculationNodes();
  15418. };
  15419. /**
  15420. * Reconnect all edges
  15421. * @private
  15422. */
  15423. Network.prototype._reconnectEdges = function() {
  15424. var id,
  15425. nodes = this.nodes,
  15426. edges = this.edges;
  15427. for (id in nodes) {
  15428. if (nodes.hasOwnProperty(id)) {
  15429. nodes[id].edges = [];
  15430. nodes[id].dynamicEdges = [];
  15431. }
  15432. }
  15433. for (id in edges) {
  15434. if (edges.hasOwnProperty(id)) {
  15435. var edge = edges[id];
  15436. edge.from = null;
  15437. edge.to = null;
  15438. edge.connect();
  15439. }
  15440. }
  15441. };
  15442. /**
  15443. * Update the values of all object in the given array according to the current
  15444. * value range of the objects in the array.
  15445. * @param {Object} obj An object containing a set of Edges or Nodes
  15446. * The objects must have a method getValue() and
  15447. * setValueRange(min, max).
  15448. * @private
  15449. */
  15450. Network.prototype._updateValueRange = function(obj) {
  15451. var id;
  15452. // determine the range of the objects
  15453. var valueMin = undefined;
  15454. var valueMax = undefined;
  15455. var valueTotal = 0;
  15456. for (id in obj) {
  15457. if (obj.hasOwnProperty(id)) {
  15458. var value = obj[id].getValue();
  15459. if (value !== undefined) {
  15460. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15461. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15462. valueTotal += value;
  15463. }
  15464. }
  15465. }
  15466. // adjust the range of all objects
  15467. if (valueMin !== undefined && valueMax !== undefined) {
  15468. for (id in obj) {
  15469. if (obj.hasOwnProperty(id)) {
  15470. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  15471. }
  15472. }
  15473. }
  15474. };
  15475. /**
  15476. * Redraw the network with the current data
  15477. * chart will be resized too.
  15478. */
  15479. Network.prototype.redraw = function() {
  15480. this.setSize(this.constants.width, this.constants.height);
  15481. this._redraw();
  15482. };
  15483. /**
  15484. * Redraw the network with the current data
  15485. * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over.
  15486. * @private
  15487. */
  15488. Network.prototype._requestRedraw = function(hidden) {
  15489. if (this.redrawRequested !== true) {
  15490. this.redrawRequested = true;
  15491. if (this.requiresTimeout === true) {
  15492. window.setTimeout(this._redraw.bind(this, hidden),0);
  15493. }
  15494. else {
  15495. window.requestAnimationFrame(this._redraw.bind(this, hidden, true));
  15496. }
  15497. }
  15498. };
  15499. Network.prototype._redraw = function(hidden, requested) {
  15500. if (hidden === undefined) {
  15501. hidden = false;
  15502. }
  15503. this.redrawRequested = false;
  15504. var ctx = this.frame.canvas.getContext('2d');
  15505. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  15506. // clear the canvas
  15507. var w = this.frame.canvas.clientWidth;
  15508. var h = this.frame.canvas.clientHeight;
  15509. ctx.clearRect(0, 0, w, h);
  15510. // set scaling and translation
  15511. ctx.save();
  15512. ctx.translate(this.translation.x, this.translation.y);
  15513. ctx.scale(this.scale, this.scale);
  15514. this.canvasTopLeft = {
  15515. "x": this._XconvertDOMtoCanvas(0),
  15516. "y": this._YconvertDOMtoCanvas(0)
  15517. };
  15518. this.canvasBottomRight = {
  15519. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth),
  15520. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight)
  15521. };
  15522. if (hidden === false) {
  15523. this._doInAllSectors("_drawAllSectorNodes", ctx);
  15524. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
  15525. this._doInAllSectors("_drawEdges", ctx);
  15526. }
  15527. }
  15528. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
  15529. this._doInAllSectors("_drawNodes",ctx,false);
  15530. }
  15531. if (hidden === false) {
  15532. if (this.controlNodesActive == true) {
  15533. this._doInAllSectors("_drawControlNodes", ctx);
  15534. }
  15535. }
  15536. // this._doInSupportSector("_drawNodes",ctx,true);
  15537. // this._drawTree(ctx,"#F00F0F");
  15538. // restore original scaling and translation
  15539. ctx.restore();
  15540. if (hidden === true) {
  15541. ctx.clearRect(0, 0, w, h);
  15542. }
  15543. }
  15544. /**
  15545. * Set the translation of the network
  15546. * @param {Number} offsetX Horizontal offset
  15547. * @param {Number} offsetY Vertical offset
  15548. * @private
  15549. */
  15550. Network.prototype._setTranslation = function(offsetX, offsetY) {
  15551. if (this.translation === undefined) {
  15552. this.translation = {
  15553. x: 0,
  15554. y: 0
  15555. };
  15556. }
  15557. if (offsetX !== undefined) {
  15558. this.translation.x = offsetX;
  15559. }
  15560. if (offsetY !== undefined) {
  15561. this.translation.y = offsetY;
  15562. }
  15563. this.emit('viewChanged');
  15564. };
  15565. /**
  15566. * Get the translation of the network
  15567. * @return {Object} translation An object with parameters x and y, both a number
  15568. * @private
  15569. */
  15570. Network.prototype._getTranslation = function() {
  15571. return {
  15572. x: this.translation.x,
  15573. y: this.translation.y
  15574. };
  15575. };
  15576. /**
  15577. * Scale the network
  15578. * @param {Number} scale Scaling factor 1.0 is unscaled
  15579. * @private
  15580. */
  15581. Network.prototype._setScale = function(scale) {
  15582. this.scale = scale;
  15583. };
  15584. /**
  15585. * Get the current scale of the network
  15586. * @return {Number} scale Scaling factor 1.0 is unscaled
  15587. * @private
  15588. */
  15589. Network.prototype._getScale = function() {
  15590. return this.scale;
  15591. };
  15592. /**
  15593. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  15594. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  15595. * @param {number} x
  15596. * @returns {number}
  15597. * @private
  15598. */
  15599. Network.prototype._XconvertDOMtoCanvas = function(x) {
  15600. return (x - this.translation.x) / this.scale;
  15601. };
  15602. /**
  15603. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  15604. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  15605. * @param {number} x
  15606. * @returns {number}
  15607. * @private
  15608. */
  15609. Network.prototype._XconvertCanvasToDOM = function(x) {
  15610. return x * this.scale + this.translation.x;
  15611. };
  15612. /**
  15613. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  15614. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  15615. * @param {number} y
  15616. * @returns {number}
  15617. * @private
  15618. */
  15619. Network.prototype._YconvertDOMtoCanvas = function(y) {
  15620. return (y - this.translation.y) / this.scale;
  15621. };
  15622. /**
  15623. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  15624. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  15625. * @param {number} y
  15626. * @returns {number}
  15627. * @private
  15628. */
  15629. Network.prototype._YconvertCanvasToDOM = function(y) {
  15630. return y * this.scale + this.translation.y ;
  15631. };
  15632. /**
  15633. *
  15634. * @param {object} pos = {x: number, y: number}
  15635. * @returns {{x: number, y: number}}
  15636. * @constructor
  15637. */
  15638. Network.prototype.canvasToDOM = function (pos) {
  15639. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  15640. };
  15641. /**
  15642. *
  15643. * @param {object} pos = {x: number, y: number}
  15644. * @returns {{x: number, y: number}}
  15645. * @constructor
  15646. */
  15647. Network.prototype.DOMtoCanvas = function (pos) {
  15648. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  15649. };
  15650. /**
  15651. * Redraw all nodes
  15652. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15653. * @param {CanvasRenderingContext2D} ctx
  15654. * @param {Boolean} [alwaysShow]
  15655. * @private
  15656. */
  15657. Network.prototype._drawNodes = function(ctx,alwaysShow) {
  15658. if (alwaysShow === undefined) {
  15659. alwaysShow = false;
  15660. }
  15661. // first draw the unselected nodes
  15662. var nodes = this.nodes;
  15663. var selected = [];
  15664. for (var id in nodes) {
  15665. if (nodes.hasOwnProperty(id)) {
  15666. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15667. if (nodes[id].isSelected()) {
  15668. selected.push(id);
  15669. }
  15670. else {
  15671. if (nodes[id].inArea() || alwaysShow) {
  15672. nodes[id].draw(ctx);
  15673. }
  15674. }
  15675. }
  15676. }
  15677. // draw the selected nodes on top
  15678. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15679. if (nodes[selected[s]].inArea() || alwaysShow) {
  15680. nodes[selected[s]].draw(ctx);
  15681. }
  15682. }
  15683. };
  15684. /**
  15685. * Redraw all edges
  15686. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15687. * @param {CanvasRenderingContext2D} ctx
  15688. * @private
  15689. */
  15690. Network.prototype._drawEdges = function(ctx) {
  15691. var edges = this.edges;
  15692. for (var id in edges) {
  15693. if (edges.hasOwnProperty(id)) {
  15694. var edge = edges[id];
  15695. edge.setScale(this.scale);
  15696. if (edge.connected) {
  15697. edges[id].draw(ctx);
  15698. }
  15699. }
  15700. }
  15701. };
  15702. /**
  15703. * Redraw all edges
  15704. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15705. * @param {CanvasRenderingContext2D} ctx
  15706. * @private
  15707. */
  15708. Network.prototype._drawControlNodes = function(ctx) {
  15709. var edges = this.edges;
  15710. for (var id in edges) {
  15711. if (edges.hasOwnProperty(id)) {
  15712. edges[id]._drawControlNodes(ctx);
  15713. }
  15714. }
  15715. };
  15716. /**
  15717. * Find a stable position for all nodes
  15718. * @private
  15719. */
  15720. Network.prototype._stabilize = function() {
  15721. if (this.constants.freezeForStabilization == true) {
  15722. this._freezeDefinedNodes();
  15723. }
  15724. // find stable position
  15725. var count = 0;
  15726. while (this.moving && count < this.constants.stabilizationIterations) {
  15727. this._physicsTick();
  15728. count++;
  15729. }
  15730. if (this.constants.zoomExtentOnStabilize == true) {
  15731. this.zoomExtent({duration:0}, false, true);
  15732. }
  15733. if (this.constants.freezeForStabilization == true) {
  15734. this._restoreFrozenNodes();
  15735. }
  15736. this.emit("stabilizationIterationsDone");
  15737. };
  15738. /**
  15739. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  15740. * because only the supportnodes for the smoothCurves have to settle.
  15741. *
  15742. * @private
  15743. */
  15744. Network.prototype._freezeDefinedNodes = function() {
  15745. var nodes = this.nodes;
  15746. for (var id in nodes) {
  15747. if (nodes.hasOwnProperty(id)) {
  15748. if (nodes[id].x != null && nodes[id].y != null) {
  15749. nodes[id].fixedData.x = nodes[id].xFixed;
  15750. nodes[id].fixedData.y = nodes[id].yFixed;
  15751. nodes[id].xFixed = true;
  15752. nodes[id].yFixed = true;
  15753. }
  15754. }
  15755. }
  15756. };
  15757. /**
  15758. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  15759. *
  15760. * @private
  15761. */
  15762. Network.prototype._restoreFrozenNodes = function() {
  15763. var nodes = this.nodes;
  15764. for (var id in nodes) {
  15765. if (nodes.hasOwnProperty(id)) {
  15766. if (nodes[id].fixedData.x != null) {
  15767. nodes[id].xFixed = nodes[id].fixedData.x;
  15768. nodes[id].yFixed = nodes[id].fixedData.y;
  15769. }
  15770. }
  15771. }
  15772. };
  15773. /**
  15774. * Check if any of the nodes is still moving
  15775. * @param {number} vmin the minimum velocity considered as 'moving'
  15776. * @return {boolean} true if moving, false if non of the nodes is moving
  15777. * @private
  15778. */
  15779. Network.prototype._isMoving = function(vmin) {
  15780. var nodes = this.nodes;
  15781. for (var id in nodes) {
  15782. if (nodes[id] !== undefined) {
  15783. if (nodes[id].isMoving(vmin) == true) {
  15784. return true;
  15785. }
  15786. }
  15787. }
  15788. return false;
  15789. };
  15790. /**
  15791. * /**
  15792. * Perform one discrete step for all nodes
  15793. *
  15794. * @private
  15795. */
  15796. Network.prototype._discreteStepNodes = function() {
  15797. var interval = this.physicsDiscreteStepsize;
  15798. var nodes = this.nodes;
  15799. var nodeId;
  15800. var nodesPresent = false;
  15801. if (this.constants.maxVelocity > 0) {
  15802. for (nodeId in nodes) {
  15803. if (nodes.hasOwnProperty(nodeId)) {
  15804. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15805. nodesPresent = true;
  15806. }
  15807. }
  15808. }
  15809. else {
  15810. for (nodeId in nodes) {
  15811. if (nodes.hasOwnProperty(nodeId)) {
  15812. nodes[nodeId].discreteStep(interval);
  15813. nodesPresent = true;
  15814. }
  15815. }
  15816. }
  15817. if (nodesPresent == true) {
  15818. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15819. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15820. return true;
  15821. }
  15822. else {
  15823. return this._isMoving(vminCorrected);
  15824. }
  15825. }
  15826. return false;
  15827. };
  15828. Network.prototype._revertPhysicsState = function() {
  15829. var nodes = this.nodes;
  15830. for (var nodeId in nodes) {
  15831. if (nodes.hasOwnProperty(nodeId)) {
  15832. nodes[nodeId].revertPosition();
  15833. }
  15834. }
  15835. }
  15836. Network.prototype._revertPhysicsTick = function() {
  15837. this._doInAllActiveSectors("_revertPhysicsState");
  15838. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  15839. this._doInSupportSector("_revertPhysicsState");
  15840. }
  15841. }
  15842. /**
  15843. * A single simulation step (or "tick") in the physics simulation
  15844. *
  15845. * @private
  15846. */
  15847. Network.prototype._physicsTick = function() {
  15848. if (!this.freezeSimulationEnabled) {
  15849. if (this.moving == true) {
  15850. var mainMovingStatus = false;
  15851. var supportMovingStatus = false;
  15852. this._doInAllActiveSectors("_initializeForceCalculation");
  15853. var mainMoving = this._doInAllActiveSectors("_discreteStepNodes");
  15854. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  15855. supportMovingStatus = this._doInSupportSector("_discreteStepNodes");
  15856. }
  15857. // gather movement data from all sectors, if one moves, we are NOT stabilzied
  15858. for (var i = 0; i < mainMoving.length; i++) {
  15859. mainMovingStatus = mainMoving[i] || mainMovingStatus;
  15860. }
  15861. // determine if the network has stabilzied
  15862. this.moving = mainMovingStatus || supportMovingStatus;
  15863. if (this.moving == false) {
  15864. this._revertPhysicsTick();
  15865. }
  15866. else {
  15867. // this is here to ensure that there is no start event when the network is already stable.
  15868. if (this.startedStabilization == false) {
  15869. this.emit("startStabilization");
  15870. this.startedStabilization = true;
  15871. }
  15872. }
  15873. this.stabilizationIterations++;
  15874. }
  15875. }
  15876. };
  15877. /**
  15878. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15879. * It reschedules itself at the beginning of the function
  15880. *
  15881. * @private
  15882. */
  15883. Network.prototype._animationStep = function() {
  15884. // reset the timer so a new scheduled animation step can be set
  15885. this.timer = undefined;
  15886. if (this.requiresTimeout == true) {
  15887. // this schedules a new animation step
  15888. this.start();
  15889. }
  15890. // handle the keyboad movement
  15891. this._handleNavigation();
  15892. // check if the physics have settled
  15893. if (this.moving == true) {
  15894. var startTime = Date.now();
  15895. this._physicsTick();
  15896. var physicsTime = Date.now() - startTime;
  15897. // run double speed if it is a little graph
  15898. if ((this.renderTimestep - this.renderTime > 2 * physicsTime || this.runDoubleSpeed == true) && this.moving == true) {
  15899. this._physicsTick();
  15900. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  15901. if (this.renderTime != 0) {
  15902. this.runDoubleSpeed = true
  15903. }
  15904. }
  15905. }
  15906. var renderStartTime = Date.now();
  15907. this._redraw();
  15908. this.renderTime = Date.now() - renderStartTime;
  15909. if (this.requiresTimeout == false) {
  15910. // this schedules a new animation step
  15911. this.start();
  15912. }
  15913. };
  15914. if (typeof window !== 'undefined') {
  15915. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15916. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15917. }
  15918. /**
  15919. * Schedule a animation step with the refreshrate interval.
  15920. */
  15921. Network.prototype.start = function() {
  15922. if (this.freezeSimulationEnabled == true) {
  15923. this.moving = false;
  15924. }
  15925. if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0 || this.animating == true) {
  15926. if (!this.timer) {
  15927. if (this.requiresTimeout == true) {
  15928. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15929. }
  15930. else {
  15931. this.timer = window.requestAnimationFrame(this._animationStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function
  15932. }
  15933. }
  15934. }
  15935. else {
  15936. this._requestRedraw();
  15937. // this check is to ensure that the network does not emit these events if it was already stabilized and setOptions is called (setting moving to true and calling start())
  15938. if (this.stabilizationIterations > 1) {
  15939. // trigger the "stabilized" event.
  15940. // The event is triggered on the next tick, to prevent the case that
  15941. // it is fired while initializing the Network, in which case you would not
  15942. // be able to catch it
  15943. var me = this;
  15944. var params = {
  15945. iterations: me.stabilizationIterations
  15946. };
  15947. this.stabilizationIterations = 0;
  15948. this.startedStabilization = false;
  15949. setTimeout(function () {
  15950. me.emit("stabilized", params);
  15951. }, 0);
  15952. }
  15953. else {
  15954. this.stabilizationIterations = 0;
  15955. }
  15956. }
  15957. };
  15958. /**
  15959. * Move the network according to the keyboard presses.
  15960. *
  15961. * @private
  15962. */
  15963. Network.prototype._handleNavigation = function() {
  15964. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15965. var translation = this._getTranslation();
  15966. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15967. }
  15968. if (this.zoomIncrement != 0) {
  15969. var center = {
  15970. x: this.frame.canvas.clientWidth / 2,
  15971. y: this.frame.canvas.clientHeight / 2
  15972. };
  15973. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15974. }
  15975. };
  15976. /**
  15977. * Freeze the _animationStep
  15978. */
  15979. Network.prototype.freezeSimulation = function(freeze) {
  15980. if (freeze == true) {
  15981. this.freezeSimulationEnabled = true;
  15982. this.moving = false;
  15983. }
  15984. else {
  15985. this.freezeSimulationEnabled = false;
  15986. this.moving = true;
  15987. this.start();
  15988. }
  15989. };
  15990. /**
  15991. * This function cleans the support nodes if they are not needed and adds them when they are.
  15992. *
  15993. * @param {boolean} [disableStart]
  15994. * @private
  15995. */
  15996. Network.prototype._configureSmoothCurves = function(disableStart) {
  15997. if (disableStart === undefined) {
  15998. disableStart = true;
  15999. }
  16000. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  16001. this._createBezierNodes();
  16002. // cleanup unused support nodes
  16003. for (var nodeId in this.sectors['support']['nodes']) {
  16004. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  16005. if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) {
  16006. delete this.sectors['support']['nodes'][nodeId];
  16007. }
  16008. }
  16009. }
  16010. }
  16011. else {
  16012. // delete the support nodes
  16013. this.sectors['support']['nodes'] = {};
  16014. for (var edgeId in this.edges) {
  16015. if (this.edges.hasOwnProperty(edgeId)) {
  16016. this.edges[edgeId].via = null;
  16017. }
  16018. }
  16019. }
  16020. this._updateCalculationNodes();
  16021. if (!disableStart) {
  16022. this.moving = true;
  16023. this.start();
  16024. }
  16025. };
  16026. /**
  16027. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  16028. * are used for the force calculation.
  16029. *
  16030. * @private
  16031. */
  16032. Network.prototype._createBezierNodes = function() {
  16033. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  16034. for (var edgeId in this.edges) {
  16035. if (this.edges.hasOwnProperty(edgeId)) {
  16036. var edge = this.edges[edgeId];
  16037. if (edge.via == null) {
  16038. var nodeId = "edgeId:".concat(edge.id);
  16039. this.sectors['support']['nodes'][nodeId] = new Node(
  16040. {id:nodeId,
  16041. mass:1,
  16042. shape:'circle',
  16043. image:"",
  16044. internalMultiplier:1
  16045. },{},{},this.constants);
  16046. edge.via = this.sectors['support']['nodes'][nodeId];
  16047. edge.via.parentEdgeId = edge.id;
  16048. edge.positionBezierNode();
  16049. }
  16050. }
  16051. }
  16052. }
  16053. };
  16054. /**
  16055. * load the functions that load the mixins into the prototype.
  16056. *
  16057. * @private
  16058. */
  16059. Network.prototype._initializeMixinLoaders = function () {
  16060. for (var mixin in MixinLoader) {
  16061. if (MixinLoader.hasOwnProperty(mixin)) {
  16062. Network.prototype[mixin] = MixinLoader[mixin];
  16063. }
  16064. }
  16065. };
  16066. /**
  16067. * Load the XY positions of the nodes into the dataset.
  16068. */
  16069. Network.prototype.storePosition = function() {
  16070. console.log("storePosition is depricated: use .storePositions() from now on.")
  16071. this.storePositions();
  16072. };
  16073. /**
  16074. * Load the XY positions of the nodes into the dataset.
  16075. */
  16076. Network.prototype.storePositions = function() {
  16077. var dataArray = [];
  16078. for (var nodeId in this.nodes) {
  16079. if (this.nodes.hasOwnProperty(nodeId)) {
  16080. var node = this.nodes[nodeId];
  16081. var allowedToMoveX = !this.nodes.xFixed;
  16082. var allowedToMoveY = !this.nodes.yFixed;
  16083. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  16084. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  16085. }
  16086. }
  16087. }
  16088. this.nodesData.update(dataArray);
  16089. };
  16090. /**
  16091. * Return the positions of the nodes.
  16092. */
  16093. Network.prototype.getPositions = function(ids) {
  16094. var dataArray = {};
  16095. if (ids !== undefined) {
  16096. if (Array.isArray(ids) == true) {
  16097. for (var i = 0; i < ids.length; i++) {
  16098. if (this.nodes[ids[i]] !== undefined) {
  16099. var node = this.nodes[ids[i]];
  16100. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  16101. }
  16102. }
  16103. }
  16104. else {
  16105. if (this.nodes[ids] !== undefined) {
  16106. var node = this.nodes[ids];
  16107. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  16108. }
  16109. }
  16110. }
  16111. else {
  16112. for (var nodeId in this.nodes) {
  16113. if (this.nodes.hasOwnProperty(nodeId)) {
  16114. var node = this.nodes[nodeId];
  16115. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  16116. }
  16117. }
  16118. }
  16119. return dataArray;
  16120. };
  16121. /**
  16122. * Center a node in view.
  16123. *
  16124. * @param {Number} nodeId
  16125. * @param {Number} [options]
  16126. */
  16127. Network.prototype.focusOnNode = function (nodeId, options) {
  16128. if (this.nodes.hasOwnProperty(nodeId)) {
  16129. if (options === undefined) {
  16130. options = {};
  16131. }
  16132. var nodePosition = {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  16133. options.position = nodePosition;
  16134. options.lockedOnNode = nodeId;
  16135. this.moveTo(options)
  16136. }
  16137. else {
  16138. console.log("This nodeId cannot be found.");
  16139. }
  16140. };
  16141. /**
  16142. *
  16143. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  16144. * | options.scale = Number // scale to move to
  16145. * | options.position = {x:Number, y:Number} // position to move to
  16146. * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to
  16147. */
  16148. Network.prototype.moveTo = function (options) {
  16149. if (options === undefined) {
  16150. options = {};
  16151. return;
  16152. }
  16153. if (options.offset === undefined) {options.offset = {x: 0, y: 0}; }
  16154. if (options.offset.x === undefined) {options.offset.x = 0; }
  16155. if (options.offset.y === undefined) {options.offset.y = 0; }
  16156. if (options.scale === undefined) {options.scale = this._getScale(); }
  16157. if (options.position === undefined) {options.position = this._getTranslation();}
  16158. if (options.animation === undefined) {options.animation = {duration:0}; }
  16159. if (options.animation === false ) {options.animation = {duration:0}; }
  16160. if (options.animation === true ) {options.animation = {}; }
  16161. if (options.animation.duration === undefined) {options.animation.duration = 1000; } // default duration
  16162. if (options.animation.easingFunction === undefined) {options.animation.easingFunction = "easeInOutQuad"; } // default easing function
  16163. this.animateView(options);
  16164. };
  16165. /**
  16166. *
  16167. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  16168. * | options.time = Number // animation time in milliseconds
  16169. * | options.scale = Number // scale to animate to
  16170. * | options.position = {x:Number, y:Number} // position to animate to
  16171. * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
  16172. * // easeInCubic, easeOutCubic, easeInOutCubic,
  16173. * // easeInQuart, easeOutQuart, easeInOutQuart,
  16174. * // easeInQuint, easeOutQuint, easeInOutQuint
  16175. */
  16176. Network.prototype.animateView = function (options) {
  16177. if (options === undefined) {
  16178. options = {};
  16179. return;
  16180. }
  16181. // release if something focussed on the node
  16182. this.releaseNode();
  16183. if (options.locked == true) {
  16184. this.lockedOnNodeId = options.lockedOnNode;
  16185. this.lockedOnNodeOffset = options.offset;
  16186. }
  16187. // forcefully complete the old animation if it was still running
  16188. if (this.easingTime != 0) {
  16189. this._transitionRedraw(1); // by setting easingtime to 1, we finish the animation.
  16190. }
  16191. this.sourceScale = this._getScale();
  16192. this.sourceTranslation = this._getTranslation();
  16193. this.targetScale = options.scale;
  16194. // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
  16195. // but at least then we'll have the target transition
  16196. this._setScale(this.targetScale);
  16197. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  16198. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  16199. x: viewCenter.x - options.position.x,
  16200. y: viewCenter.y - options.position.y
  16201. };
  16202. this.targetTranslation = {
  16203. x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x,
  16204. y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y
  16205. };
  16206. // if the time is set to 0, don't do an animation
  16207. if (options.animation.duration == 0) {
  16208. if (this.lockedOnNodeId != null) {
  16209. this._classicRedraw = this._redraw;
  16210. this._redraw = this._lockedRedraw;
  16211. }
  16212. else {
  16213. this._setScale(this.targetScale);
  16214. this._setTranslation(this.targetTranslation.x, this.targetTranslation.y);
  16215. this._redraw();
  16216. }
  16217. }
  16218. else {
  16219. this.animating = true;
  16220. this.animationSpeed = 1 / (this.renderRefreshRate * options.animation.duration * 0.001) || 1 / this.renderRefreshRate;
  16221. this.animationEasingFunction = options.animation.easingFunction;
  16222. this._classicRedraw = this._redraw;
  16223. this._redraw = this._transitionRedraw;
  16224. this._redraw();
  16225. this.start();
  16226. }
  16227. };
  16228. /**
  16229. * used to animate smoothly by hijacking the redraw function.
  16230. * @private
  16231. */
  16232. Network.prototype._lockedRedraw = function () {
  16233. var nodePosition = {x: this.nodes[this.lockedOnNodeId].x, y: this.nodes[this.lockedOnNodeId].y};
  16234. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  16235. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  16236. x: viewCenter.x - nodePosition.x,
  16237. y: viewCenter.y - nodePosition.y
  16238. };
  16239. var sourceTranslation = this._getTranslation();
  16240. var targetTranslation = {
  16241. x: sourceTranslation.x + distanceFromCenter.x * this.scale + this.lockedOnNodeOffset.x,
  16242. y: sourceTranslation.y + distanceFromCenter.y * this.scale + this.lockedOnNodeOffset.y
  16243. };
  16244. this._setTranslation(targetTranslation.x,targetTranslation.y);
  16245. this._classicRedraw();
  16246. }
  16247. Network.prototype.releaseNode = function () {
  16248. if (this.lockedOnNodeId != null) {
  16249. this._redraw = this._classicRedraw;
  16250. this.lockedOnNodeId = null;
  16251. this.lockedOnNodeOffset = null;
  16252. }
  16253. }
  16254. /**
  16255. *
  16256. * @param easingTime
  16257. * @private
  16258. */
  16259. Network.prototype._transitionRedraw = function (easingTime) {
  16260. this.easingTime = easingTime || this.easingTime + this.animationSpeed;
  16261. this.easingTime += this.animationSpeed;
  16262. var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime);
  16263. this._setScale(this.sourceScale + (this.targetScale - this.sourceScale) * progress);
  16264. this._setTranslation(
  16265. this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress,
  16266. this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress
  16267. );
  16268. this._classicRedraw();
  16269. // cleanup
  16270. if (this.easingTime >= 1.0) {
  16271. this.animating = false;
  16272. this.easingTime = 0;
  16273. if (this.lockedOnNodeId != null) {
  16274. this._redraw = this._lockedRedraw;
  16275. }
  16276. else {
  16277. this._redraw = this._classicRedraw;
  16278. }
  16279. this.emit("animationFinished");
  16280. }
  16281. };
  16282. Network.prototype._classicRedraw = function () {
  16283. // placeholder function to be overloaded by animations;
  16284. };
  16285. /**
  16286. * Returns true when the Network is active.
  16287. * @returns {boolean}
  16288. */
  16289. Network.prototype.isActive = function () {
  16290. return !this.activator || this.activator.active;
  16291. };
  16292. /**
  16293. * Sets the scale
  16294. * @returns {Number}
  16295. */
  16296. Network.prototype.setScale = function () {
  16297. return this._setScale();
  16298. };
  16299. /**
  16300. * Returns the scale
  16301. * @returns {Number}
  16302. */
  16303. Network.prototype.getScale = function () {
  16304. return this._getScale();
  16305. };
  16306. /**
  16307. * Returns the scale
  16308. * @returns {Number}
  16309. */
  16310. Network.prototype.getCenterCoordinates = function () {
  16311. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  16312. };
  16313. Network.prototype.getBoundingBox = function(nodeId) {
  16314. if (this.nodes[nodeId] !== undefined) {
  16315. return this.nodes[nodeId].boundingBox;
  16316. }
  16317. }
  16318. Network.prototype.getConnectedNodes = function(nodeId) {
  16319. var nodeList = [];
  16320. if (this.nodes[nodeId] !== undefined) {
  16321. var node = this.nodes[nodeId];
  16322. var nodeObj = {nodeId : true}; // used to quickly check if node already exists
  16323. for (var i = 0; i < node.edges.length; i++) {
  16324. var edge = node.edges[i];
  16325. if (edge.toId == nodeId) {
  16326. if (nodeObj[edge.fromId] === undefined) {
  16327. nodeList.push(edge.fromId);
  16328. nodeObj[edge.fromId] = true;
  16329. }
  16330. }
  16331. else if (edge.fromId == nodeId) {
  16332. if (nodeObj[edge.toId] === undefined) {
  16333. nodeList.push(edge.toId)
  16334. nodeObj[edge.toId] = true;
  16335. }
  16336. }
  16337. }
  16338. }
  16339. return nodeList;
  16340. }
  16341. Network.prototype.getEdgesFromNode = function(nodeId) {
  16342. var edgesList = [];
  16343. if (this.nodes[nodeId] !== undefined) {
  16344. var node = this.nodes[nodeId];
  16345. for (var i = 0; i < node.edges.length; i++) {
  16346. edgesList.push(node.edges[i].id);
  16347. }
  16348. }
  16349. return edgesList;
  16350. }
  16351. Network.prototype.generateColorObject = function(color) {
  16352. return util.parseColor(color);
  16353. }
  16354. module.exports = Network;
  16355. /***/ },
  16356. /* 37 */
  16357. /***/ function(module, exports, __webpack_require__) {
  16358. var util = __webpack_require__(1);
  16359. var Node = __webpack_require__(40);
  16360. /**
  16361. * @class Edge
  16362. *
  16363. * A edge connects two nodes
  16364. * @param {Object} properties Object with properties. Must contain
  16365. * At least properties from and to.
  16366. * Available properties: from (number),
  16367. * to (number), label (string, color (string),
  16368. * width (number), style (string),
  16369. * length (number), title (string)
  16370. * @param {Network} network A Network object, used to find and edge to
  16371. * nodes.
  16372. * @param {Object} constants An object with default values for
  16373. * example for the color
  16374. */
  16375. function Edge (properties, network, networkConstants) {
  16376. if (!network) {
  16377. throw "No network provided";
  16378. }
  16379. var fields = ['edges','physics'];
  16380. var constants = util.selectiveBridgeObject(fields,networkConstants);
  16381. this.options = constants.edges;
  16382. this.physics = constants.physics;
  16383. this.options['smoothCurves'] = networkConstants['smoothCurves'];
  16384. this.network = network;
  16385. // initialize variables
  16386. this.id = undefined;
  16387. this.fromId = undefined;
  16388. this.toId = undefined;
  16389. this.title = undefined;
  16390. this.widthSelected = this.options.width * this.options.widthSelectionMultiplier;
  16391. this.value = undefined;
  16392. this.selected = false;
  16393. this.hover = false;
  16394. this.labelDimensions = {top:0,left:0,width:0,height:0,yLine:0}; // could be cached
  16395. this.dirtyLabel = true;
  16396. this.colorDirty = true;
  16397. this.from = null; // a node
  16398. this.to = null; // a node
  16399. this.via = null; // a temp node
  16400. this.fromBackup = null; // used to clean up after reconnect
  16401. this.toBackup = null;; // used to clean up after reconnect
  16402. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  16403. // by storing the original information we can revert to the original connection when the cluser is opened.
  16404. this.originalFromId = [];
  16405. this.originalToId = [];
  16406. this.connected = false;
  16407. this.widthFixed = false;
  16408. this.lengthFixed = false;
  16409. this.setProperties(properties);
  16410. this.controlNodesEnabled = false;
  16411. this.controlNodes = {from:null, to:null, positions:{}};
  16412. this.connectedNode = null;
  16413. }
  16414. /**
  16415. * Set or overwrite properties for the edge
  16416. * @param {Object} properties an object with properties
  16417. * @param {Object} constants and object with default, global properties
  16418. */
  16419. Edge.prototype.setProperties = function(properties) {
  16420. this.colorDirty = true;
  16421. if (!properties) {
  16422. return;
  16423. }
  16424. var fields = ['style','fontSize','fontFace','fontColor','fontFill','fontStrokeWidth','fontStrokeColor','width',
  16425. 'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash','inheritColor','labelAlignment', 'opacity',
  16426. 'customScalingFunction','useGradients'
  16427. ];
  16428. util.selectiveDeepExtend(fields, this.options, properties);
  16429. if (properties.from !== undefined) {this.fromId = properties.from;}
  16430. if (properties.to !== undefined) {this.toId = properties.to;}
  16431. if (properties.id !== undefined) {this.id = properties.id;}
  16432. if (properties.label !== undefined) {this.label = properties.label; this.dirtyLabel = true;}
  16433. if (properties.title !== undefined) {this.title = properties.title;}
  16434. if (properties.value !== undefined) {this.value = properties.value;}
  16435. if (properties.length !== undefined) {this.physics.springLength = properties.length;}
  16436. if (properties.color !== undefined) {
  16437. this.options.inheritColor = false;
  16438. if (util.isString(properties.color)) {
  16439. this.options.color.color = properties.color;
  16440. this.options.color.highlight = properties.color;
  16441. }
  16442. else {
  16443. if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;}
  16444. if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;}
  16445. if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;}
  16446. }
  16447. }
  16448. // A node is connected when it has a from and to node.
  16449. this.connect();
  16450. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  16451. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  16452. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  16453. // set draw method based on style
  16454. switch (this.options.style) {
  16455. case 'line': this.draw = this._drawLine; break;
  16456. case 'arrow': this.draw = this._drawArrow; break;
  16457. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  16458. case 'dash-line': this.draw = this._drawDashLine; break;
  16459. default: this.draw = this._drawLine; break;
  16460. }
  16461. };
  16462. /**
  16463. * Connect an edge to its nodes
  16464. */
  16465. Edge.prototype.connect = function () {
  16466. this.disconnect();
  16467. this.from = this.network.nodes[this.fromId] || null;
  16468. this.to = this.network.nodes[this.toId] || null;
  16469. this.connected = (this.from && this.to);
  16470. if (this.connected) {
  16471. this.from.attachEdge(this);
  16472. this.to.attachEdge(this);
  16473. }
  16474. else {
  16475. if (this.from) {
  16476. this.from.detachEdge(this);
  16477. }
  16478. if (this.to) {
  16479. this.to.detachEdge(this);
  16480. }
  16481. }
  16482. };
  16483. /**
  16484. * Disconnect an edge from its nodes
  16485. */
  16486. Edge.prototype.disconnect = function () {
  16487. if (this.from) {
  16488. this.from.detachEdge(this);
  16489. this.from = null;
  16490. }
  16491. if (this.to) {
  16492. this.to.detachEdge(this);
  16493. this.to = null;
  16494. }
  16495. this.connected = false;
  16496. };
  16497. /**
  16498. * get the title of this edge.
  16499. * @return {string} title The title of the edge, or undefined when no title
  16500. * has been set.
  16501. */
  16502. Edge.prototype.getTitle = function() {
  16503. return typeof this.title === "function" ? this.title() : this.title;
  16504. };
  16505. /**
  16506. * Retrieve the value of the edge. Can be undefined
  16507. * @return {Number} value
  16508. */
  16509. Edge.prototype.getValue = function() {
  16510. return this.value;
  16511. };
  16512. /**
  16513. * Adjust the value range of the edge. The edge will adjust it's width
  16514. * based on its value.
  16515. * @param {Number} min
  16516. * @param {Number} max
  16517. */
  16518. Edge.prototype.setValueRange = function(min, max, total) {
  16519. if (!this.widthFixed && this.value !== undefined) {
  16520. var scale = this.options.customScalingFunction(min, max, total, this.value);
  16521. var widthDiff = this.options.widthMax - this.options.widthMin;
  16522. this.options.width = this.options.widthMin + scale * widthDiff;
  16523. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  16524. }
  16525. };
  16526. /**
  16527. * Redraw a edge
  16528. * Draw this edge in the given canvas
  16529. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  16530. * @param {CanvasRenderingContext2D} ctx
  16531. */
  16532. Edge.prototype.draw = function(ctx) {
  16533. throw "Method draw not initialized in edge";
  16534. };
  16535. /**
  16536. * Check if this object is overlapping with the provided object
  16537. * @param {Object} obj an object with parameters left, top
  16538. * @return {boolean} True if location is located on the edge
  16539. */
  16540. Edge.prototype.isOverlappingWith = function(obj) {
  16541. if (this.connected) {
  16542. var distMax = 10;
  16543. var xFrom = this.from.x;
  16544. var yFrom = this.from.y;
  16545. var xTo = this.to.x;
  16546. var yTo = this.to.y;
  16547. var xObj = obj.left;
  16548. var yObj = obj.top;
  16549. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  16550. return (dist < distMax);
  16551. }
  16552. else {
  16553. return false
  16554. }
  16555. };
  16556. Edge.prototype._getColor = function(ctx) {
  16557. var colorObj = this.options.color;
  16558. if (this.options.useGradients == true) {
  16559. var grd = ctx.createLinearGradient(this.from.x, this.from.y, this.to.x, this.to.y);
  16560. var fromColor, toColor;
  16561. fromColor = this.from.options.color.highlight.border;
  16562. toColor = this.to.options.color.highlight.border;
  16563. if (this.from.selected == false && this.to.selected == false) {
  16564. fromColor = util.overrideOpacity(this.from.options.color.border, this.options.opacity);
  16565. toColor = util.overrideOpacity(this.to.options.color.border, this.options.opacity);
  16566. }
  16567. else if (this.from.selected == true && this.to.selected == false) {
  16568. toColor = this.to.options.color.border;
  16569. }
  16570. else if (this.from.selected == false && this.to.selected == true) {
  16571. fromColor = this.from.options.color.border;
  16572. }
  16573. grd.addColorStop(0, fromColor);
  16574. grd.addColorStop(1, toColor);
  16575. return grd;
  16576. }
  16577. if (this.colorDirty === true) {
  16578. if (this.options.inheritColor == "to") {
  16579. colorObj = {
  16580. highlight: this.to.options.color.highlight.border,
  16581. hover: this.to.options.color.hover.border,
  16582. color: util.overrideOpacity(this.from.options.color.border, this.options.opacity)
  16583. };
  16584. }
  16585. else if (this.options.inheritColor == "from" || this.options.inheritColor == true) {
  16586. colorObj = {
  16587. highlight: this.from.options.color.highlight.border,
  16588. hover: this.from.options.color.hover.border,
  16589. color: util.overrideOpacity(this.from.options.color.border, this.options.opacity)
  16590. };
  16591. }
  16592. this.options.color = colorObj;
  16593. this.colorDirty = false;
  16594. }
  16595. if (this.selected == true) {return colorObj.highlight;}
  16596. else if (this.hover == true) {return colorObj.hover;}
  16597. else {return colorObj.color;}
  16598. };
  16599. /**
  16600. * Redraw a edge as a line
  16601. * Draw this edge in the given canvas
  16602. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  16603. * @param {CanvasRenderingContext2D} ctx
  16604. * @private
  16605. */
  16606. Edge.prototype._drawLine = function(ctx) {
  16607. // set style
  16608. ctx.strokeStyle = this._getColor(ctx);
  16609. ctx.lineWidth = this._getLineWidth();
  16610. if (this.from != this.to) {
  16611. // draw line
  16612. var via = this._line(ctx);
  16613. // draw label
  16614. var point;
  16615. if (this.label) {
  16616. if (this.options.smoothCurves.enabled == true && via != null) {
  16617. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  16618. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  16619. point = {x:midpointX, y:midpointY};
  16620. }
  16621. else {
  16622. point = this._pointOnLine(0.5);
  16623. }
  16624. this._label(ctx, this.label, point.x, point.y);
  16625. }
  16626. }
  16627. else {
  16628. var x, y;
  16629. var radius = this.physics.springLength / 4;
  16630. var node = this.from;
  16631. if (!node.width) {
  16632. node.resize(ctx);
  16633. }
  16634. if (node.width > node.height) {
  16635. x = node.x + node.width / 2;
  16636. y = node.y - radius;
  16637. }
  16638. else {
  16639. x = node.x + radius;
  16640. y = node.y - node.height / 2;
  16641. }
  16642. this._circle(ctx, x, y, radius);
  16643. point = this._pointOnCircle(x, y, radius, 0.5);
  16644. this._label(ctx, this.label, point.x, point.y);
  16645. }
  16646. };
  16647. /**
  16648. * Get the line width of the edge. Depends on width and whether one of the
  16649. * connected nodes is selected.
  16650. * @return {Number} width
  16651. * @private
  16652. */
  16653. Edge.prototype._getLineWidth = function() {
  16654. if (this.selected == true) {
  16655. return Math.max(Math.min(this.widthSelected, this.options.widthMax), 0.3*this.networkScaleInv);
  16656. }
  16657. else {
  16658. if (this.hover == true) {
  16659. return Math.max(Math.min(this.options.hoverWidth, this.options.widthMax), 0.3*this.networkScaleInv);
  16660. }
  16661. else {
  16662. return Math.max(this.options.width, 0.3*this.networkScaleInv);
  16663. }
  16664. }
  16665. };
  16666. Edge.prototype._getViaCoordinates = function () {
  16667. if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) {
  16668. return this.via;
  16669. }
  16670. else if (this.options.smoothCurves.enabled == false) {
  16671. return {x:0,y:0};
  16672. }
  16673. else {
  16674. var xVia = null;
  16675. var yVia = null;
  16676. var factor = this.options.smoothCurves.roundness;
  16677. var type = this.options.smoothCurves.type;
  16678. var dx = Math.abs(this.from.x - this.to.x);
  16679. var dy = Math.abs(this.from.y - this.to.y);
  16680. if (type == 'discrete' || type == 'diagonalCross') {
  16681. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  16682. if (this.from.y > this.to.y) {
  16683. if (this.from.x < this.to.x) {
  16684. xVia = this.from.x + factor * dy;
  16685. yVia = this.from.y - factor * dy;
  16686. }
  16687. else if (this.from.x > this.to.x) {
  16688. xVia = this.from.x - factor * dy;
  16689. yVia = this.from.y - factor * dy;
  16690. }
  16691. }
  16692. else if (this.from.y < this.to.y) {
  16693. if (this.from.x < this.to.x) {
  16694. xVia = this.from.x + factor * dy;
  16695. yVia = this.from.y + factor * dy;
  16696. }
  16697. else if (this.from.x > this.to.x) {
  16698. xVia = this.from.x - factor * dy;
  16699. yVia = this.from.y + factor * dy;
  16700. }
  16701. }
  16702. if (type == "discrete") {
  16703. xVia = dx < factor * dy ? this.from.x : xVia;
  16704. }
  16705. }
  16706. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  16707. if (this.from.y > this.to.y) {
  16708. if (this.from.x < this.to.x) {
  16709. xVia = this.from.x + factor * dx;
  16710. yVia = this.from.y - factor * dx;
  16711. }
  16712. else if (this.from.x > this.to.x) {
  16713. xVia = this.from.x - factor * dx;
  16714. yVia = this.from.y - factor * dx;
  16715. }
  16716. }
  16717. else if (this.from.y < this.to.y) {
  16718. if (this.from.x < this.to.x) {
  16719. xVia = this.from.x + factor * dx;
  16720. yVia = this.from.y + factor * dx;
  16721. }
  16722. else if (this.from.x > this.to.x) {
  16723. xVia = this.from.x - factor * dx;
  16724. yVia = this.from.y + factor * dx;
  16725. }
  16726. }
  16727. if (type == "discrete") {
  16728. yVia = dy < factor * dx ? this.from.y : yVia;
  16729. }
  16730. }
  16731. }
  16732. else if (type == "straightCross") {
  16733. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down
  16734. xVia = this.from.x;
  16735. if (this.from.y < this.to.y) {
  16736. yVia = this.to.y - (1 - factor) * dy;
  16737. }
  16738. else {
  16739. yVia = this.to.y + (1 - factor) * dy;
  16740. }
  16741. }
  16742. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right
  16743. if (this.from.x < this.to.x) {
  16744. xVia = this.to.x - (1 - factor) * dx;
  16745. }
  16746. else {
  16747. xVia = this.to.x + (1 - factor) * dx;
  16748. }
  16749. yVia = this.from.y;
  16750. }
  16751. }
  16752. else if (type == 'horizontal') {
  16753. if (this.from.x < this.to.x) {
  16754. xVia = this.to.x - (1 - factor) * dx;
  16755. }
  16756. else {
  16757. xVia = this.to.x + (1 - factor) * dx;
  16758. }
  16759. yVia = this.from.y;
  16760. }
  16761. else if (type == 'vertical') {
  16762. xVia = this.from.x;
  16763. if (this.from.y < this.to.y) {
  16764. yVia = this.to.y - (1 - factor) * dy;
  16765. }
  16766. else {
  16767. yVia = this.to.y + (1 - factor) * dy;
  16768. }
  16769. }
  16770. else if (type == 'curvedCW') {
  16771. var dx = this.to.x - this.from.x;
  16772. var dy = this.from.y - this.to.y;
  16773. var radius = Math.sqrt(dx*dx + dy*dy);
  16774. var pi = Math.PI;
  16775. var originalAngle = Math.atan2(dy,dx);
  16776. var myAngle = (originalAngle + ((factor * 0.5) + 0.5) * pi) % (2 * pi);
  16777. xVia = this.from.x + (factor*0.5 + 0.5)*radius*Math.sin(myAngle);
  16778. yVia = this.from.y + (factor*0.5 + 0.5)*radius*Math.cos(myAngle);
  16779. }
  16780. else if (type == 'curvedCCW') {
  16781. var dx = this.to.x - this.from.x;
  16782. var dy = this.from.y - this.to.y;
  16783. var radius = Math.sqrt(dx*dx + dy*dy);
  16784. var pi = Math.PI;
  16785. var originalAngle = Math.atan2(dy,dx);
  16786. var myAngle = (originalAngle + ((-factor * 0.5) + 0.5) * pi) % (2 * pi);
  16787. xVia = this.from.x + (factor*0.5 + 0.5)*radius*Math.sin(myAngle);
  16788. yVia = this.from.y + (factor*0.5 + 0.5)*radius*Math.cos(myAngle);
  16789. }
  16790. else { // continuous
  16791. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  16792. if (this.from.y > this.to.y) {
  16793. if (this.from.x < this.to.x) {
  16794. xVia = this.from.x + factor * dy;
  16795. yVia = this.from.y - factor * dy;
  16796. xVia = this.to.x < xVia ? this.to.x : xVia;
  16797. }
  16798. else if (this.from.x > this.to.x) {
  16799. xVia = this.from.x - factor * dy;
  16800. yVia = this.from.y - factor * dy;
  16801. xVia = this.to.x > xVia ? this.to.x : xVia;
  16802. }
  16803. }
  16804. else if (this.from.y < this.to.y) {
  16805. if (this.from.x < this.to.x) {
  16806. xVia = this.from.x + factor * dy;
  16807. yVia = this.from.y + factor * dy;
  16808. xVia = this.to.x < xVia ? this.to.x : xVia;
  16809. }
  16810. else if (this.from.x > this.to.x) {
  16811. xVia = this.from.x - factor * dy;
  16812. yVia = this.from.y + factor * dy;
  16813. xVia = this.to.x > xVia ? this.to.x : xVia;
  16814. }
  16815. }
  16816. }
  16817. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  16818. if (this.from.y > this.to.y) {
  16819. if (this.from.x < this.to.x) {
  16820. xVia = this.from.x + factor * dx;
  16821. yVia = this.from.y - factor * dx;
  16822. yVia = this.to.y > yVia ? this.to.y : yVia;
  16823. }
  16824. else if (this.from.x > this.to.x) {
  16825. xVia = this.from.x - factor * dx;
  16826. yVia = this.from.y - factor * dx;
  16827. yVia = this.to.y > yVia ? this.to.y : yVia;
  16828. }
  16829. }
  16830. else if (this.from.y < this.to.y) {
  16831. if (this.from.x < this.to.x) {
  16832. xVia = this.from.x + factor * dx;
  16833. yVia = this.from.y + factor * dx;
  16834. yVia = this.to.y < yVia ? this.to.y : yVia;
  16835. }
  16836. else if (this.from.x > this.to.x) {
  16837. xVia = this.from.x - factor * dx;
  16838. yVia = this.from.y + factor * dx;
  16839. yVia = this.to.y < yVia ? this.to.y : yVia;
  16840. }
  16841. }
  16842. }
  16843. }
  16844. return {x: xVia, y: yVia};
  16845. }
  16846. };
  16847. /**
  16848. * Draw a line between two nodes
  16849. * @param {CanvasRenderingContext2D} ctx
  16850. * @private
  16851. */
  16852. Edge.prototype._line = function (ctx) {
  16853. // draw a straight line
  16854. ctx.beginPath();
  16855. ctx.moveTo(this.from.x, this.from.y);
  16856. if (this.options.smoothCurves.enabled == true) {
  16857. if (this.options.smoothCurves.dynamic == false) {
  16858. var via = this._getViaCoordinates();
  16859. if (via.x == null) {
  16860. ctx.lineTo(this.to.x, this.to.y);
  16861. ctx.stroke();
  16862. return null;
  16863. }
  16864. else {
  16865. // this.via.x = via.x;
  16866. // this.via.y = via.y;
  16867. ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y);
  16868. ctx.stroke();
  16869. //ctx.circle(via.x,via.y,2)
  16870. //ctx.stroke();
  16871. return via;
  16872. }
  16873. }
  16874. else {
  16875. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  16876. ctx.stroke();
  16877. return this.via;
  16878. }
  16879. }
  16880. else {
  16881. ctx.lineTo(this.to.x, this.to.y);
  16882. ctx.stroke();
  16883. return null;
  16884. }
  16885. };
  16886. /**
  16887. * Draw a line from a node to itself, a circle
  16888. * @param {CanvasRenderingContext2D} ctx
  16889. * @param {Number} x
  16890. * @param {Number} y
  16891. * @param {Number} radius
  16892. * @private
  16893. */
  16894. Edge.prototype._circle = function (ctx, x, y, radius) {
  16895. // draw a circle
  16896. ctx.beginPath();
  16897. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  16898. ctx.stroke();
  16899. };
  16900. /**
  16901. * Draw label with white background and with the middle at (x, y)
  16902. * @param {CanvasRenderingContext2D} ctx
  16903. * @param {String} text
  16904. * @param {Number} x
  16905. * @param {Number} y
  16906. * @private
  16907. */
  16908. Edge.prototype._label = function (ctx, text, x, y) {
  16909. if (text) {
  16910. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  16911. this.options.fontSize + "px " + this.options.fontFace;
  16912. var yLine;
  16913. if (this.dirtyLabel == true) {
  16914. var lines = String(text).split('\n');
  16915. var lineCount = lines.length;
  16916. var fontSize = Number(this.options.fontSize);
  16917. yLine = y + (1 - lineCount) / 2 * fontSize;
  16918. var width = ctx.measureText(lines[0]).width;
  16919. for (var i = 1; i < lineCount; i++) {
  16920. var lineWidth = ctx.measureText(lines[i]).width;
  16921. width = lineWidth > width ? lineWidth : width;
  16922. }
  16923. var height = this.options.fontSize * lineCount;
  16924. var left = x - width / 2;
  16925. var top = y - height / 2;
  16926. // cache
  16927. this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
  16928. }
  16929. var yLine = this.labelDimensions.yLine;
  16930. ctx.save();
  16931. if (this.options.labelAlignment != "horizontal"){
  16932. ctx.translate(x, yLine);
  16933. this._rotateForLabelAlignment(ctx);
  16934. x = 0;
  16935. yLine = 0;
  16936. }
  16937. this._drawLabelRect(ctx);
  16938. this._drawLabelText(ctx,x,yLine, lines, lineCount, fontSize);
  16939. ctx.restore();
  16940. }
  16941. };
  16942. /**
  16943. * Rotates the canvas so the text is most readable
  16944. * @param {CanvasRenderingContext2D} ctx
  16945. * @private
  16946. */
  16947. Edge.prototype._rotateForLabelAlignment = function(ctx) {
  16948. var dy = this.from.y - this.to.y;
  16949. var dx = this.from.x - this.to.x;
  16950. var angleInDegrees = Math.atan2(dy, dx);
  16951. // rotate so label it is readable
  16952. if((angleInDegrees < -1 && dx < 0) || (angleInDegrees > 0 && dx < 0)){
  16953. angleInDegrees = angleInDegrees + Math.PI;
  16954. }
  16955. ctx.rotate(angleInDegrees);
  16956. };
  16957. /**
  16958. * Draws the label rectangle
  16959. * @param {CanvasRenderingContext2D} ctx
  16960. * @param {String} labelAlignment
  16961. * @private
  16962. */
  16963. Edge.prototype._drawLabelRect = function(ctx) {
  16964. if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
  16965. ctx.fillStyle = this.options.fontFill;
  16966. var lineMargin = 2;
  16967. if (this.options.labelAlignment == 'line-center') {
  16968. ctx.fillRect(-this.labelDimensions.width * 0.5, -this.labelDimensions.height * 0.5, this.labelDimensions.width, this.labelDimensions.height);
  16969. }
  16970. else if (this.options.labelAlignment == 'line-above') {
  16971. ctx.fillRect(-this.labelDimensions.width * 0.5, -(this.labelDimensions.height + lineMargin), this.labelDimensions.width, this.labelDimensions.height);
  16972. }
  16973. else if (this.options.labelAlignment == 'line-below') {
  16974. ctx.fillRect(-this.labelDimensions.width * 0.5, lineMargin, this.labelDimensions.width, this.labelDimensions.height);
  16975. }
  16976. else {
  16977. ctx.fillRect(this.labelDimensions.left, this.labelDimensions.top, this.labelDimensions.width, this.labelDimensions.height);
  16978. }
  16979. }
  16980. };
  16981. /**
  16982. * Draws the label text
  16983. * @param {CanvasRenderingContext2D} ctx
  16984. * @param {Number} x
  16985. * @param {Number} yLine
  16986. * @param {Array} lines
  16987. * @param {Number} lineCount
  16988. * @param {Number} fontSize
  16989. * @private
  16990. */
  16991. Edge.prototype._drawLabelText = function(ctx, x, yLine, lines, lineCount, fontSize) {
  16992. // draw text
  16993. ctx.fillStyle = this.options.fontColor || "black";
  16994. ctx.textAlign = "center";
  16995. // check for label alignment
  16996. if (this.options.labelAlignment != 'horizontal') {
  16997. var lineMargin = 2;
  16998. if (this.options.labelAlignment == 'line-above') {
  16999. ctx.textBaseline = "alphabetic";
  17000. yLine -= 2 * lineMargin; // distance from edge, required because we use alphabetic. Alphabetic has less difference between browsers
  17001. }
  17002. else if (this.options.labelAlignment == 'line-below') {
  17003. ctx.textBaseline = "hanging";
  17004. yLine += 2 * lineMargin;// distance from edge, required because we use hanging. Hanging has less difference between browsers
  17005. }
  17006. else {
  17007. ctx.textBaseline = "middle";
  17008. }
  17009. }
  17010. else {
  17011. ctx.textBaseline = "middle";
  17012. }
  17013. // check for strokeWidth
  17014. if (this.options.fontStrokeWidth > 0){
  17015. ctx.lineWidth = this.options.fontStrokeWidth;
  17016. ctx.strokeStyle = this.options.fontStrokeColor;
  17017. ctx.lineJoin = 'round';
  17018. }
  17019. for (var i = 0; i < lineCount; i++) {
  17020. if(this.options.fontStrokeWidth > 0){
  17021. ctx.strokeText(lines[i], x, yLine);
  17022. }
  17023. ctx.fillText(lines[i], x, yLine);
  17024. yLine += fontSize;
  17025. }
  17026. };
  17027. /**
  17028. * Redraw a edge as a dashed line
  17029. * Draw this edge in the given canvas
  17030. * @author David Jordan
  17031. * @date 2012-08-08
  17032. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  17033. * @param {CanvasRenderingContext2D} ctx
  17034. * @private
  17035. */
  17036. Edge.prototype._drawDashLine = function(ctx) {
  17037. // set style
  17038. ctx.strokeStyle = this._getColor(ctx);
  17039. ctx.lineWidth = this._getLineWidth();
  17040. var via = null;
  17041. // only firefox and chrome support this method, else we use the legacy one.
  17042. if (ctx.setLineDash !== undefined) {
  17043. ctx.save();
  17044. // configure the dash pattern
  17045. var pattern = [0];
  17046. if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) {
  17047. pattern = [this.options.dash.length,this.options.dash.gap];
  17048. }
  17049. else {
  17050. pattern = [5,5];
  17051. }
  17052. // set dash settings for chrome or firefox
  17053. ctx.setLineDash(pattern);
  17054. ctx.lineDashOffset = 0;
  17055. // draw the line
  17056. via = this._line(ctx);
  17057. // restore the dash settings.
  17058. ctx.setLineDash([0]);
  17059. ctx.lineDashOffset = 0;
  17060. ctx.restore();
  17061. }
  17062. else { // unsupporting smooth lines
  17063. // draw dashed line
  17064. ctx.beginPath();
  17065. ctx.lineCap = 'round';
  17066. if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  17067. {
  17068. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  17069. [this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]);
  17070. }
  17071. else if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value
  17072. {
  17073. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  17074. [this.options.dash.length,this.options.dash.gap]);
  17075. }
  17076. else //If all else fails draw a line
  17077. {
  17078. ctx.moveTo(this.from.x, this.from.y);
  17079. ctx.lineTo(this.to.x, this.to.y);
  17080. }
  17081. ctx.stroke();
  17082. }
  17083. // draw label
  17084. if (this.label) {
  17085. var point;
  17086. if (this.options.smoothCurves.enabled == true && via != null) {
  17087. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  17088. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  17089. point = {x:midpointX, y:midpointY};
  17090. }
  17091. else {
  17092. point = this._pointOnLine(0.5);
  17093. }
  17094. this._label(ctx, this.label, point.x, point.y);
  17095. }
  17096. };
  17097. /**
  17098. * Get a point on a line
  17099. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  17100. * @return {Object} point
  17101. * @private
  17102. */
  17103. Edge.prototype._pointOnLine = function (percentage) {
  17104. return {
  17105. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  17106. y: (1 - percentage) * this.from.y + percentage * this.to.y
  17107. }
  17108. };
  17109. /**
  17110. * Get a point on a circle
  17111. * @param {Number} x
  17112. * @param {Number} y
  17113. * @param {Number} radius
  17114. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  17115. * @return {Object} point
  17116. * @private
  17117. */
  17118. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  17119. var angle = (percentage - 3/8) * 2 * Math.PI;
  17120. return {
  17121. x: x + radius * Math.cos(angle),
  17122. y: y - radius * Math.sin(angle)
  17123. }
  17124. };
  17125. /**
  17126. * Redraw a edge as a line with an arrow halfway the line
  17127. * Draw this edge in the given canvas
  17128. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  17129. * @param {CanvasRenderingContext2D} ctx
  17130. * @private
  17131. */
  17132. Edge.prototype._drawArrowCenter = function(ctx) {
  17133. var point;
  17134. // set style
  17135. ctx.strokeStyle = this._getColor(ctx);
  17136. ctx.fillStyle = ctx.strokeStyle;
  17137. ctx.lineWidth = this._getLineWidth();
  17138. if (this.from != this.to) {
  17139. // draw line
  17140. var via = this._line(ctx);
  17141. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  17142. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  17143. // draw an arrow halfway the line
  17144. if (this.options.smoothCurves.enabled == true && via != null) {
  17145. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  17146. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  17147. point = {x:midpointX, y:midpointY};
  17148. }
  17149. else {
  17150. point = this._pointOnLine(0.5);
  17151. }
  17152. ctx.arrow(point.x, point.y, angle, length);
  17153. ctx.fill();
  17154. ctx.stroke();
  17155. // draw label
  17156. if (this.label) {
  17157. this._label(ctx, this.label, point.x, point.y);
  17158. }
  17159. }
  17160. else {
  17161. // draw circle
  17162. var x, y;
  17163. var radius = 0.25 * Math.max(100,this.physics.springLength);
  17164. var node = this.from;
  17165. if (!node.width) {
  17166. node.resize(ctx);
  17167. }
  17168. if (node.width > node.height) {
  17169. x = node.x + node.width * 0.5;
  17170. y = node.y - radius;
  17171. }
  17172. else {
  17173. x = node.x + radius;
  17174. y = node.y - node.height * 0.5;
  17175. }
  17176. this._circle(ctx, x, y, radius);
  17177. // draw all arrows
  17178. var angle = 0.2 * Math.PI;
  17179. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  17180. point = this._pointOnCircle(x, y, radius, 0.5);
  17181. ctx.arrow(point.x, point.y, angle, length);
  17182. ctx.fill();
  17183. ctx.stroke();
  17184. // draw label
  17185. if (this.label) {
  17186. point = this._pointOnCircle(x, y, radius, 0.5);
  17187. this._label(ctx, this.label, point.x, point.y);
  17188. }
  17189. }
  17190. };
  17191. Edge.prototype._pointOnBezier = function(t) {
  17192. var via = this._getViaCoordinates();
  17193. var x = Math.pow(1-t,2)*this.from.x + (2*t*(1 - t))*via.x + Math.pow(t,2)*this.to.x;
  17194. var y = Math.pow(1-t,2)*this.from.y + (2*t*(1 - t))*via.y + Math.pow(t,2)*this.to.y;
  17195. return {x:x,y:y};
  17196. }
  17197. /**
  17198. * This function uses binary search to look for the point where the bezier curve crosses the border of the node.
  17199. *
  17200. * @param from
  17201. * @param ctx
  17202. * @returns {*}
  17203. * @private
  17204. */
  17205. Edge.prototype._findBorderPosition = function(from,ctx) {
  17206. var maxIterations = 10;
  17207. var iteration = 0;
  17208. var low = 0;
  17209. var high = 1;
  17210. var pos,angle,distanceToBorder, distanceToNodes, difference;
  17211. var threshold = 0.2;
  17212. var node = this.to;
  17213. if (from == true) {
  17214. node = this.from;
  17215. }
  17216. while (low <= high && iteration < maxIterations) {
  17217. var middle = (low + high) * 0.5;
  17218. pos = this._pointOnBezier(middle);
  17219. angle = Math.atan2((node.y - pos.y), (node.x - pos.x));
  17220. distanceToBorder = node.distanceToBorder(ctx,angle);
  17221. distanceToNodes = Math.sqrt(Math.pow(pos.x-node.x,2) + Math.pow(pos.y-node.y,2));
  17222. difference = distanceToBorder - distanceToNodes;
  17223. if (Math.abs(difference) < threshold) {
  17224. break; // found
  17225. }
  17226. else if (difference < 0) { // distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
  17227. if (from == false) {
  17228. low = middle;
  17229. }
  17230. else {
  17231. high = middle;
  17232. }
  17233. }
  17234. else {
  17235. if (from == false) {
  17236. high = middle;
  17237. }
  17238. else {
  17239. low = middle;
  17240. }
  17241. }
  17242. iteration++;
  17243. }
  17244. pos.t = middle;
  17245. return pos;
  17246. };
  17247. /**
  17248. * Redraw a edge as a line with an arrow
  17249. * Draw this edge in the given canvas
  17250. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  17251. * @param {CanvasRenderingContext2D} ctx
  17252. * @private
  17253. */
  17254. Edge.prototype._drawArrow = function(ctx) {
  17255. // set style
  17256. ctx.strokeStyle = this._getColor(ctx);
  17257. ctx.fillStyle = ctx.strokeStyle;
  17258. ctx.lineWidth = this._getLineWidth();
  17259. // set vars
  17260. var angle, length, arrowPos;
  17261. // if not connected to itself
  17262. if (this.from != this.to) {
  17263. // draw line
  17264. this._line(ctx);
  17265. // draw arrow head
  17266. if (this.options.smoothCurves.enabled == true) {
  17267. var via = this._getViaCoordinates();
  17268. arrowPos = this._findBorderPosition(false, ctx);
  17269. var guidePos = this._pointOnBezier(Math.max(0.0, arrowPos.t - 0.1))
  17270. angle = Math.atan2((arrowPos.y - guidePos.y), (arrowPos.x - guidePos.x));
  17271. }
  17272. else {
  17273. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  17274. var dx = (this.to.x - this.from.x);
  17275. var dy = (this.to.y - this.from.y);
  17276. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  17277. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  17278. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  17279. arrowPos = {};
  17280. arrowPos.x = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  17281. arrowPos.y = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  17282. }
  17283. // draw arrow at the end of the line
  17284. length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  17285. ctx.arrow(arrowPos.x,arrowPos.y, angle, length);
  17286. ctx.fill();
  17287. ctx.stroke();
  17288. // draw label
  17289. if (this.label) {
  17290. var point;
  17291. if (this.options.smoothCurves.enabled == true && via != null) {
  17292. point = this._pointOnBezier(0.5);
  17293. }
  17294. else {
  17295. point = this._pointOnLine(0.5);
  17296. }
  17297. this._label(ctx, this.label, point.x, point.y);
  17298. }
  17299. }
  17300. else {
  17301. // draw circle
  17302. var node = this.from;
  17303. var x, y, arrow;
  17304. var radius = 0.25 * Math.max(100,this.physics.springLength);
  17305. if (!node.width) {
  17306. node.resize(ctx);
  17307. }
  17308. if (node.width > node.height) {
  17309. x = node.x + node.width * 0.5;
  17310. y = node.y - radius;
  17311. arrow = {
  17312. x: x,
  17313. y: node.y,
  17314. angle: 0.9 * Math.PI
  17315. };
  17316. }
  17317. else {
  17318. x = node.x + radius;
  17319. y = node.y - node.height * 0.5;
  17320. arrow = {
  17321. x: node.x,
  17322. y: y,
  17323. angle: 0.6 * Math.PI
  17324. };
  17325. }
  17326. ctx.beginPath();
  17327. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  17328. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  17329. ctx.stroke();
  17330. // draw all arrows
  17331. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  17332. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  17333. ctx.fill();
  17334. ctx.stroke();
  17335. // draw label
  17336. if (this.label) {
  17337. point = this._pointOnCircle(x, y, radius, 0.5);
  17338. this._label(ctx, this.label, point.x, point.y);
  17339. }
  17340. }
  17341. };
  17342. /**
  17343. * Calculate the distance between a point (x3,y3) and a line segment from
  17344. * (x1,y1) to (x2,y2).
  17345. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  17346. * @param {number} x1
  17347. * @param {number} y1
  17348. * @param {number} x2
  17349. * @param {number} y2
  17350. * @param {number} x3
  17351. * @param {number} y3
  17352. * @private
  17353. */
  17354. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  17355. var returnValue = 0;
  17356. if (this.from != this.to) {
  17357. if (this.options.smoothCurves.enabled == true) {
  17358. var xVia, yVia;
  17359. if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) {
  17360. xVia = this.via.x;
  17361. yVia = this.via.y;
  17362. }
  17363. else {
  17364. var via = this._getViaCoordinates();
  17365. xVia = via.x;
  17366. yVia = via.y;
  17367. }
  17368. var minDistance = 1e9;
  17369. var distance;
  17370. var i,t,x,y, lastX, lastY;
  17371. for (i = 0; i < 10; i++) {
  17372. t = 0.1*i;
  17373. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2;
  17374. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2;
  17375. if (i > 0) {
  17376. distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3);
  17377. minDistance = distance < minDistance ? distance : minDistance;
  17378. }
  17379. lastX = x; lastY = y;
  17380. }
  17381. returnValue = minDistance;
  17382. }
  17383. else {
  17384. returnValue = this._getDistanceToLine(x1,y1,x2,y2,x3,y3);
  17385. }
  17386. }
  17387. else {
  17388. var x, y, dx, dy;
  17389. var radius = 0.25 * this.physics.springLength;
  17390. var node = this.from;
  17391. if (node.width > node.height) {
  17392. x = node.x + 0.5 * node.width;
  17393. y = node.y - radius;
  17394. }
  17395. else {
  17396. x = node.x + radius;
  17397. y = node.y - 0.5 * node.height;
  17398. }
  17399. dx = x - x3;
  17400. dy = y - y3;
  17401. returnValue = Math.abs(Math.sqrt(dx*dx + dy*dy) - radius);
  17402. }
  17403. if (this.labelDimensions.left < x3 &&
  17404. this.labelDimensions.left + this.labelDimensions.width > x3 &&
  17405. this.labelDimensions.top < y3 &&
  17406. this.labelDimensions.top + this.labelDimensions.height > y3) {
  17407. return 0;
  17408. }
  17409. else {
  17410. return returnValue;
  17411. }
  17412. };
  17413. Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) {
  17414. var px = x2-x1,
  17415. py = y2-y1,
  17416. something = px*px + py*py,
  17417. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  17418. if (u > 1) {
  17419. u = 1;
  17420. }
  17421. else if (u < 0) {
  17422. u = 0;
  17423. }
  17424. var x = x1 + u * px,
  17425. y = y1 + u * py,
  17426. dx = x - x3,
  17427. dy = y - y3;
  17428. //# Note: If the actual distance does not matter,
  17429. //# if you only want to compare what this function
  17430. //# returns to other results of this function, you
  17431. //# can just return the squared distance instead
  17432. //# (i.e. remove the sqrt) to gain a little performance
  17433. return Math.sqrt(dx*dx + dy*dy);
  17434. };
  17435. /**
  17436. * This allows the zoom level of the network to influence the rendering
  17437. *
  17438. * @param scale
  17439. */
  17440. Edge.prototype.setScale = function(scale) {
  17441. this.networkScaleInv = 1.0/scale;
  17442. };
  17443. Edge.prototype.select = function() {
  17444. this.selected = true;
  17445. };
  17446. Edge.prototype.unselect = function() {
  17447. this.selected = false;
  17448. };
  17449. Edge.prototype.positionBezierNode = function() {
  17450. if (this.via !== null && this.from !== null && this.to !== null) {
  17451. this.via.x = 0.5 * (this.from.x + this.to.x);
  17452. this.via.y = 0.5 * (this.from.y + this.to.y);
  17453. }
  17454. else if (this.via !== null) {
  17455. this.via.x = 0;
  17456. this.via.y = 0;
  17457. }
  17458. };
  17459. /**
  17460. * This function draws the control nodes for the manipulator.
  17461. * In order to enable this, only set the this.controlNodesEnabled to true.
  17462. * @param ctx
  17463. */
  17464. Edge.prototype._drawControlNodes = function(ctx) {
  17465. if (this.controlNodesEnabled == true) {
  17466. if (this.controlNodes.from === null && this.controlNodes.to === null) {
  17467. var nodeIdFrom = "edgeIdFrom:".concat(this.id);
  17468. var nodeIdTo = "edgeIdTo:".concat(this.id);
  17469. var constants = {
  17470. nodes:{group:'', radius:7, borderWidth:2, borderWidthSelected: 2},
  17471. physics:{damping:0},
  17472. clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}}
  17473. };
  17474. this.controlNodes.from = new Node(
  17475. {id:nodeIdFrom,
  17476. shape:'dot',
  17477. color:{background:'#ff0000', border:'#3c3c3c', highlight: {background:'#07f968'}}
  17478. },{},{},constants);
  17479. this.controlNodes.to = new Node(
  17480. {id:nodeIdTo,
  17481. shape:'dot',
  17482. color:{background:'#ff0000', border:'#3c3c3c', highlight: {background:'#07f968'}}
  17483. },{},{},constants);
  17484. }
  17485. this.controlNodes.positions = {};
  17486. if (this.controlNodes.from.selected == false) {
  17487. this.controlNodes.positions.from = this.getControlNodeFromPosition(ctx);
  17488. this.controlNodes.from.x = this.controlNodes.positions.from.x;
  17489. this.controlNodes.from.y = this.controlNodes.positions.from.y;
  17490. }
  17491. if (this.controlNodes.to.selected == false) {
  17492. this.controlNodes.positions.to = this.getControlNodeToPosition(ctx);
  17493. this.controlNodes.to.x = this.controlNodes.positions.to.x;
  17494. this.controlNodes.to.y = this.controlNodes.positions.to.y;
  17495. }
  17496. this.controlNodes.from.draw(ctx);
  17497. this.controlNodes.to.draw(ctx);
  17498. }
  17499. else {
  17500. this.controlNodes = {from:null, to:null, positions:{}};
  17501. }
  17502. };
  17503. /**
  17504. * Enable control nodes.
  17505. * @private
  17506. */
  17507. Edge.prototype._enableControlNodes = function() {
  17508. this.fromBackup = this.from;
  17509. this.toBackup = this.to;
  17510. this.controlNodesEnabled = true;
  17511. };
  17512. /**
  17513. * disable control nodes and remove from dynamicEdges from old node
  17514. * @private
  17515. */
  17516. Edge.prototype._disableControlNodes = function() {
  17517. this.fromId = this.from.id;
  17518. this.toId = this.to.id;
  17519. if (this.fromId != this.fromBackup.id) { // from was changed, remove edge from old 'from' node dynamic edges
  17520. this.fromBackup.detachEdge(this);
  17521. }
  17522. else if (this.toId != this.toBackup.id) { // to was changed, remove edge from old 'to' node dynamic edges
  17523. this.toBackup.detachEdge(this);
  17524. }
  17525. this.fromBackup = null;
  17526. this.toBackup = null;
  17527. this.controlNodesEnabled = false;
  17528. };
  17529. /**
  17530. * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null.
  17531. * @param x
  17532. * @param y
  17533. * @returns {null}
  17534. * @private
  17535. */
  17536. Edge.prototype._getSelectedControlNode = function(x,y) {
  17537. var positions = this.controlNodes.positions;
  17538. var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2));
  17539. var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2));
  17540. if (fromDistance < 15) {
  17541. this.connectedNode = this.from;
  17542. this.from = this.controlNodes.from;
  17543. return this.controlNodes.from;
  17544. }
  17545. else if (toDistance < 15) {
  17546. this.connectedNode = this.to;
  17547. this.to = this.controlNodes.to;
  17548. return this.controlNodes.to;
  17549. }
  17550. else {
  17551. return null;
  17552. }
  17553. };
  17554. /**
  17555. * this resets the control nodes to their original position.
  17556. * @private
  17557. */
  17558. Edge.prototype._restoreControlNodes = function() {
  17559. if (this.controlNodes.from.selected == true) {
  17560. this.from = this.connectedNode;
  17561. this.connectedNode = null;
  17562. this.controlNodes.from.unselect();
  17563. }
  17564. else if (this.controlNodes.to.selected == true) {
  17565. this.to = this.connectedNode;
  17566. this.connectedNode = null;
  17567. this.controlNodes.to.unselect();
  17568. }
  17569. };
  17570. /**
  17571. * this calculates the position of the control nodes on the edges of the parent nodes.
  17572. *
  17573. * @param ctx
  17574. * @returns {x: *, y: *}
  17575. */
  17576. Edge.prototype.getControlNodeFromPosition = function(ctx) {
  17577. // draw arrow head
  17578. var controlnodeFromPos;
  17579. if (this.options.smoothCurves.enabled == true) {
  17580. controlnodeFromPos = this._findBorderPosition(true, ctx);
  17581. }
  17582. else {
  17583. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  17584. var dx = (this.to.x - this.from.x);
  17585. var dy = (this.to.y - this.from.y);
  17586. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  17587. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  17588. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  17589. controlnodeFromPos = {};
  17590. controlnodeFromPos.x = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  17591. controlnodeFromPos.y = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  17592. }
  17593. return controlnodeFromPos;
  17594. };
  17595. /**
  17596. * this calculates the position of the control nodes on the edges of the parent nodes.
  17597. *
  17598. * @param ctx
  17599. * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}}
  17600. */
  17601. Edge.prototype.getControlNodeToPosition = function(ctx) {
  17602. // draw arrow head
  17603. var controlnodeFromPos,controlnodeToPos;
  17604. if (this.options.smoothCurves.enabled == true) {
  17605. controlnodeToPos = this._findBorderPosition(false, ctx);
  17606. }
  17607. else {
  17608. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  17609. var dx = (this.to.x - this.from.x);
  17610. var dy = (this.to.y - this.from.y);
  17611. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  17612. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  17613. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  17614. controlnodeToPos = {};
  17615. controlnodeToPos.x = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  17616. controlnodeToPos.y = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  17617. }
  17618. return controlnodeToPos;
  17619. };
  17620. module.exports = Edge;
  17621. /***/ },
  17622. /* 38 */
  17623. /***/ function(module, exports, __webpack_require__) {
  17624. var util = __webpack_require__(1);
  17625. /**
  17626. * @class Groups
  17627. * This class can store groups and properties specific for groups.
  17628. */
  17629. function Groups() {
  17630. this.clear();
  17631. this.defaultIndex = 0;
  17632. this.groupsArray = [];
  17633. this.groupIndex = 0;
  17634. this.useDefaultGroups = true;
  17635. }
  17636. /**
  17637. * default constants for group colors
  17638. */
  17639. Groups.DEFAULT = [
  17640. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}, hover: {border: "#2B7CE9", background: "#D2E5FF"}}, // 0: blue
  17641. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}, hover: {border: "#FFA500", background: "#FFFFA3"}}, // 1: yellow
  17642. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}, hover: {border: "#FA0A10", background: "#FFAFB1"}}, // 2: red
  17643. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}, hover: {border: "#41A906", background: "#A1EC76"}}, // 3: green
  17644. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}, hover: {border: "#E129F0", background: "#F0B3F5"}}, // 4: magenta
  17645. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}, hover: {border: "#7C29F0", background: "#D3BDF0"}}, // 5: purple
  17646. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}, hover: {border: "#C37F00", background: "#FFCA66"}}, // 6: orange
  17647. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}, hover: {border: "#4220FB", background: "#9B9BFD"}}, // 7: darkblue
  17648. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}, hover: {border: "#FD5A77", background: "#FFD1D9"}}, // 8: pink
  17649. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}, hover: {border: "#4AD63A", background: "#E6FFE3"}}, // 9: mint
  17650. {border: "#990000", background: "#EE0000", highlight: {border: "#BB0000", background: "#FF3333"}, hover: {border: "#BB0000", background: "#FF3333"}}, // 10:bright red
  17651. {border: "#FF6000", background: "#FF6000", highlight: {border: "#FF6000", background: "#FF6000"}, hover: {border: "#FF6000", background: "#FF6000"}}, // 12: real orange
  17652. {border: "#97C2FC", background: "#2B7CE9", highlight: {border: "#D2E5FF", background: "#2B7CE9"}, hover: {border: "#D2E5FF", background: "#2B7CE9"}}, // 13: blue
  17653. {border: "#399605", background: "#255C03", highlight: {border: "#399605", background: "#255C03"}, hover: {border: "#399605", background: "#255C03"}}, // 14: green
  17654. {border: "#B70054", background: "#FF007E", highlight: {border: "#B70054", background: "#FF007E"}, hover: {border: "#B70054", background: "#FF007E"}}, // 15: magenta
  17655. {border: "#AD85E4", background: "#7C29F0", highlight: {border: "#D3BDF0", background: "#7C29F0"}, hover: {border: "#D3BDF0", background: "#7C29F0"}}, // 16: purple
  17656. {border: "#4557FA", background: "#000EA1", highlight: {border: "#6E6EFD", background: "#000EA1"}, hover: {border: "#6E6EFD", background: "#000EA1"}}, // 17: darkblue
  17657. {border: "#FFC0CB", background: "#FD5A77", highlight: {border: "#FFD1D9", background: "#FD5A77"}, hover: {border: "#FFD1D9", background: "#FD5A77"}}, // 18: pink
  17658. {border: "#C2FABC", background: "#74D66A", highlight: {border: "#E6FFE3", background: "#74D66A"}, hover: {border: "#E6FFE3", background: "#74D66A"}}, // 19: mint
  17659. {border: "#EE0000", background: "#990000", highlight: {border: "#FF3333", background: "#BB0000"}, hover: {border: "#FF3333", background: "#BB0000"}}, // 20:bright red
  17660. ];
  17661. /**
  17662. * Clear all groups
  17663. */
  17664. Groups.prototype.clear = function () {
  17665. this.groups = {};
  17666. this.groups.length = function()
  17667. {
  17668. var i = 0;
  17669. for ( var p in this ) {
  17670. if (this.hasOwnProperty(p)) {
  17671. i++;
  17672. }
  17673. }
  17674. return i;
  17675. }
  17676. };
  17677. /**
  17678. * get group properties of a groupname. If groupname is not found, a new group
  17679. * is added.
  17680. * @param {*} groupname Can be a number, string, Date, etc.
  17681. * @return {Object} group The created group, containing all group properties
  17682. */
  17683. Groups.prototype.get = function (groupname) {
  17684. var group = this.groups[groupname];
  17685. if (group == undefined) {
  17686. if (this.useDefaultGroups === false && this.groupsArray.length > 0) {
  17687. // create new group
  17688. var index = this.groupIndex % this.groupsArray.length;
  17689. this.groupIndex++;
  17690. group = {};
  17691. group.color = this.groups[this.groupsArray[index]];
  17692. this.groups[groupname] = group;
  17693. }
  17694. else {
  17695. // create new group
  17696. var index = this.defaultIndex % Groups.DEFAULT.length;
  17697. this.defaultIndex++;
  17698. group = {};
  17699. group.color = Groups.DEFAULT[index];
  17700. this.groups[groupname] = group;
  17701. }
  17702. }
  17703. return group;
  17704. };
  17705. /**
  17706. * Add a custom group style
  17707. * @param {String} groupName
  17708. * @param {Object} style An object containing borderColor,
  17709. * backgroundColor, etc.
  17710. * @return {Object} group The created group object
  17711. */
  17712. Groups.prototype.add = function (groupName, style) {
  17713. this.groups[groupName] = style;
  17714. this.groupsArray.push(groupName);
  17715. return style;
  17716. };
  17717. module.exports = Groups;
  17718. /***/ },
  17719. /* 39 */
  17720. /***/ function(module, exports, __webpack_require__) {
  17721. /**
  17722. * @class Images
  17723. * This class loads images and keeps them stored.
  17724. */
  17725. function Images() {
  17726. this.images = {};
  17727. this.imageBroken = {};
  17728. this.callback = undefined;
  17729. }
  17730. /**
  17731. * Set an onload callback function. This will be called each time an image
  17732. * is loaded
  17733. * @param {function} callback
  17734. */
  17735. Images.prototype.setOnloadCallback = function(callback) {
  17736. this.callback = callback;
  17737. };
  17738. /**
  17739. *
  17740. * @param {string} url Url of the image
  17741. * @param {string} url Url of an image to use if the url image is not found
  17742. * @return {Image} img The image object
  17743. */
  17744. Images.prototype.load = function(url, brokenUrl) {
  17745. var img = this.images[url]; // make a pointer
  17746. if (img === undefined) {
  17747. // create the image
  17748. var me = this;
  17749. img = new Image();
  17750. img.onload = function () {
  17751. // IE11 fix -- thanks dponch!
  17752. if (this.width == 0) {
  17753. document.body.appendChild(this);
  17754. this.width = this.offsetWidth;
  17755. this.height = this.offsetHeight;
  17756. document.body.removeChild(this);
  17757. }
  17758. if (me.callback) {
  17759. me.images[url] = img;
  17760. me.callback(this);
  17761. }
  17762. };
  17763. img.onerror = function () {
  17764. if (brokenUrl === undefined) {
  17765. console.error("Could not load image:", url);
  17766. delete this.src;
  17767. if (me.callback) {
  17768. me.callback(this);
  17769. }
  17770. }
  17771. else {
  17772. if (me.imageBroken[url] === true) {
  17773. if (this.src == brokenUrl) {
  17774. console.error("Could not load brokenImage:", brokenUrl);
  17775. delete this.src;
  17776. if (me.callback) {
  17777. me.callback(this);
  17778. }
  17779. }
  17780. else {
  17781. console.error("Could not load image:", url);
  17782. this.src = brokenUrl;
  17783. }
  17784. }
  17785. else {
  17786. console.error("Could not load image:", url);
  17787. this.src = brokenUrl;
  17788. me.imageBroken[url] = true;
  17789. }
  17790. }
  17791. };
  17792. img.src = url;
  17793. }
  17794. return img;
  17795. };
  17796. module.exports = Images;
  17797. /***/ },
  17798. /* 40 */
  17799. /***/ function(module, exports, __webpack_require__) {
  17800. var util = __webpack_require__(1);
  17801. /**
  17802. * @class Node
  17803. * A node. A node can be connected to other nodes via one or multiple edges.
  17804. * @param {object} properties An object containing properties for the node. All
  17805. * properties are optional, except for the id.
  17806. * {number} id Id of the node. Required
  17807. * {string} label Text label for the node
  17808. * {number} x Horizontal position of the node
  17809. * {number} y Vertical position of the node
  17810. * {string} shape Node shape, available:
  17811. * "database", "circle", "ellipse",
  17812. * "box", "image", "text", "dot",
  17813. * "star", "triangle", "triangleDown",
  17814. * "square", "icon"
  17815. * {string} image An image url
  17816. * {string} title An title text, can be HTML
  17817. * {anytype} group A group name or number
  17818. * @param {Network.Images} imagelist A list with images. Only needed
  17819. * when the node has an image
  17820. * @param {Network.Groups} grouplist A list with groups. Needed for
  17821. * retrieving group properties
  17822. * @param {Object} constants An object with default values for
  17823. * example for the color
  17824. *
  17825. */
  17826. function Node(properties, imagelist, grouplist, networkConstants) {
  17827. var constants = util.selectiveBridgeObject(['nodes'],networkConstants);
  17828. this.options = constants.nodes;
  17829. this.selected = false;
  17830. this.hover = false;
  17831. this.edges = []; // all edges connected to this node
  17832. this.dynamicEdges = [];
  17833. this.reroutedEdges = {};
  17834. // set defaults for the properties
  17835. this.id = undefined;
  17836. this.allowedToMoveX = false;
  17837. this.allowedToMoveY = false;
  17838. this.xFixed = false;
  17839. this.yFixed = false;
  17840. this.horizontalAlignLeft = true; // these are for the navigation controls
  17841. this.verticalAlignTop = true; // these are for the navigation controls
  17842. this.baseRadiusValue = networkConstants.nodes.radius;
  17843. this.radiusFixed = false;
  17844. this.level = -1;
  17845. this.preassignedLevel = false;
  17846. this.hierarchyEnumerated = false;
  17847. this.labelDimensions = {top:0, left:0, width:0, height:0, yLine:0}; // could be cached
  17848. this.boundingBox = {top:0, left:0, right:0, bottom:0};
  17849. this.imagelist = imagelist;
  17850. this.grouplist = grouplist;
  17851. // physics properties
  17852. this.fx = 0.0; // external force x
  17853. this.fy = 0.0; // external force y
  17854. this.vx = 0.0; // velocity x
  17855. this.vy = 0.0; // velocity y
  17856. this.x = null;
  17857. this.y = null;
  17858. this.predefinedPosition = false; // used to check if initial zoomExtent should just take the range or approximate
  17859. // used for reverting to previous position on stabilization
  17860. this.previousState = {vx:0,vy:0,x:0,y:0};
  17861. this.damping = networkConstants.physics.damping; // written every time gravity is calculated
  17862. this.fixedData = {x:null,y:null};
  17863. this.setProperties(properties, constants);
  17864. // creating the variables for clustering
  17865. this.resetCluster();
  17866. this.clusterSession = 0;
  17867. this.clusterSizeWidthFactor = networkConstants.clustering.nodeScaling.width;
  17868. this.clusterSizeHeightFactor = networkConstants.clustering.nodeScaling.height;
  17869. this.clusterSizeRadiusFactor = networkConstants.clustering.nodeScaling.radius;
  17870. this.maxNodeSizeIncrements = networkConstants.clustering.maxNodeSizeIncrements;
  17871. this.growthIndicator = 0;
  17872. // variables to tell the node about the network.
  17873. this.networkScaleInv = 1;
  17874. this.networkScale = 1;
  17875. this.canvasTopLeft = {"x": -300, "y": -300};
  17876. this.canvasBottomRight = {"x": 300, "y": 300};
  17877. this.parentEdgeId = null;
  17878. }
  17879. /**
  17880. * Revert the position and velocity of the previous step.
  17881. */
  17882. Node.prototype.revertPosition = function() {
  17883. this.x = this.previousState.x;
  17884. this.y = this.previousState.y;
  17885. this.vx = this.previousState.vx;
  17886. this.vy = this.previousState.vy;
  17887. }
  17888. /**
  17889. * (re)setting the clustering variables and objects
  17890. */
  17891. Node.prototype.resetCluster = function() {
  17892. // clustering variables
  17893. this.formationScale = undefined; // this is used to determine when to open the cluster
  17894. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  17895. this.containedNodes = {};
  17896. this.containedEdges = {};
  17897. this.clusterSessions = [];
  17898. };
  17899. /**
  17900. * Attach a edge to the node
  17901. * @param {Edge} edge
  17902. */
  17903. Node.prototype.attachEdge = function(edge) {
  17904. if (this.edges.indexOf(edge) == -1) {
  17905. this.edges.push(edge);
  17906. }
  17907. if (this.dynamicEdges.indexOf(edge) == -1) {
  17908. this.dynamicEdges.push(edge);
  17909. }
  17910. };
  17911. /**
  17912. * Detach a edge from the node
  17913. * @param {Edge} edge
  17914. */
  17915. Node.prototype.detachEdge = function(edge) {
  17916. var index = this.edges.indexOf(edge);
  17917. if (index != -1) {
  17918. this.edges.splice(index, 1);
  17919. }
  17920. index = this.dynamicEdges.indexOf(edge);
  17921. if (index != -1) {
  17922. this.dynamicEdges.splice(index, 1);
  17923. }
  17924. };
  17925. /**
  17926. * Set or overwrite properties for the node
  17927. * @param {Object} properties an object with properties
  17928. * @param {Object} constants and object with default, global properties
  17929. */
  17930. Node.prototype.setProperties = function(properties, constants) {
  17931. if (!properties) {
  17932. return;
  17933. }
  17934. var fields = ['borderWidth','borderWidthSelected','shape','image','brokenImage','radius','fontColor',
  17935. 'fontSize','fontFace','fontFill','fontStrokeWidth','fontStrokeColor','group','mass','fontDrawThreshold',
  17936. 'scaleFontWithValue','fontSizeMaxVisible','customScalingFunction','iconFontFace', 'icon', 'iconColor', 'iconSize'
  17937. ];
  17938. util.selectiveDeepExtend(fields, this.options, properties);
  17939. // basic properties
  17940. if (properties.id !== undefined) {this.id = properties.id;}
  17941. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  17942. if (properties.title !== undefined) {this.title = properties.title;}
  17943. if (properties.x !== undefined) {this.x = properties.x; this.predefinedPosition = true;}
  17944. if (properties.y !== undefined) {this.y = properties.y; this.predefinedPosition = true;}
  17945. if (properties.value !== undefined) {this.value = properties.value;}
  17946. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  17947. // navigation controls properties
  17948. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  17949. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  17950. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  17951. if (this.id === undefined) {
  17952. throw "Node must have an id";
  17953. }
  17954. // copy group properties
  17955. if (typeof properties.group === 'number' || (typeof properties.group === 'string' && properties.group != '')) {
  17956. var groupObj = this.grouplist.get(properties.group);
  17957. util.deepExtend(this.options, groupObj);
  17958. // the color object needs to be completely defined. Since groups can partially overwrite the colors, we parse it again, just in case.
  17959. this.options.color = util.parseColor(this.options.color);
  17960. }
  17961. // individual shape properties
  17962. if (properties.radius !== undefined) {this.baseRadiusValue = this.options.radius;}
  17963. if (properties.color !== undefined) {this.options.color = util.parseColor(properties.color);}
  17964. if (this.options.image !== undefined && this.options.image!= "") {
  17965. if (this.imagelist) {
  17966. this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage);
  17967. }
  17968. else {
  17969. throw "No imagelist provided";
  17970. }
  17971. }
  17972. if (properties.allowedToMoveX !== undefined) {
  17973. this.xFixed = !properties.allowedToMoveX;
  17974. this.allowedToMoveX = properties.allowedToMoveX;
  17975. }
  17976. else if (properties.x !== undefined && this.allowedToMoveX == false) {
  17977. this.xFixed = true;
  17978. }
  17979. if (properties.allowedToMoveY !== undefined) {
  17980. this.yFixed = !properties.allowedToMoveY;
  17981. this.allowedToMoveY = properties.allowedToMoveY;
  17982. }
  17983. else if (properties.y !== undefined && this.allowedToMoveY == false) {
  17984. this.yFixed = true;
  17985. }
  17986. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  17987. if (this.options.shape === 'image' || this.options.shape === 'circularImage') {
  17988. this.options.radiusMin = constants.nodes.widthMin;
  17989. this.options.radiusMax = constants.nodes.widthMax;
  17990. }
  17991. // choose draw method depending on the shape
  17992. switch (this.options.shape) {
  17993. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  17994. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  17995. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  17996. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  17997. // TODO: add diamond shape
  17998. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  17999. case 'circularImage': this.draw = this._drawCircularImage; this.resize = this._resizeCircularImage; break;
  18000. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  18001. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  18002. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  18003. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  18004. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  18005. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  18006. case 'icon': this.draw = this._drawIcon; this.resize = this._resizeIcon; break;
  18007. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  18008. }
  18009. // reset the size of the node, this can be changed
  18010. this._reset();
  18011. };
  18012. /**
  18013. * select this node
  18014. */
  18015. Node.prototype.select = function() {
  18016. this.selected = true;
  18017. this._reset();
  18018. };
  18019. /**
  18020. * unselect this node
  18021. */
  18022. Node.prototype.unselect = function() {
  18023. this.selected = false;
  18024. this._reset();
  18025. };
  18026. /**
  18027. * Reset the calculated size of the node, forces it to recalculate its size
  18028. */
  18029. Node.prototype.clearSizeCache = function() {
  18030. this._reset();
  18031. };
  18032. /**
  18033. * Reset the calculated size of the node, forces it to recalculate its size
  18034. * @private
  18035. */
  18036. Node.prototype._reset = function() {
  18037. this.width = undefined;
  18038. this.height = undefined;
  18039. };
  18040. /**
  18041. * get the title of this node.
  18042. * @return {string} title The title of the node, or undefined when no title
  18043. * has been set.
  18044. */
  18045. Node.prototype.getTitle = function() {
  18046. return typeof this.title === "function" ? this.title() : this.title;
  18047. };
  18048. /**
  18049. * Calculate the distance to the border of the Node
  18050. * @param {CanvasRenderingContext2D} ctx
  18051. * @param {Number} angle Angle in radians
  18052. * @returns {number} distance Distance to the border in pixels
  18053. */
  18054. Node.prototype.distanceToBorder = function (ctx, angle) {
  18055. var borderWidth = 1;
  18056. if (!this.width) {
  18057. this.resize(ctx);
  18058. }
  18059. switch (this.options.shape) {
  18060. case 'circle':
  18061. case 'dot':
  18062. return this.options.radius+ borderWidth;
  18063. case 'ellipse':
  18064. var a = this.width / 2;
  18065. var b = this.height / 2;
  18066. var w = (Math.sin(angle) * a);
  18067. var h = (Math.cos(angle) * b);
  18068. return a * b / Math.sqrt(w * w + h * h);
  18069. // TODO: implement distanceToBorder for database
  18070. // TODO: implement distanceToBorder for triangle
  18071. // TODO: implement distanceToBorder for triangleDown
  18072. case 'box':
  18073. case 'image':
  18074. case 'text':
  18075. default:
  18076. if (this.width) {
  18077. return Math.min(
  18078. Math.abs(this.width / 2 / Math.cos(angle)),
  18079. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  18080. // TODO: reckon with border radius too in case of box
  18081. }
  18082. else {
  18083. return 0;
  18084. }
  18085. }
  18086. // TODO: implement calculation of distance to border for all shapes
  18087. };
  18088. /**
  18089. * Set forces acting on the node
  18090. * @param {number} fx Force in horizontal direction
  18091. * @param {number} fy Force in vertical direction
  18092. */
  18093. Node.prototype._setForce = function(fx, fy) {
  18094. this.fx = fx;
  18095. this.fy = fy;
  18096. };
  18097. /**
  18098. * Add forces acting on the node
  18099. * @param {number} fx Force in horizontal direction
  18100. * @param {number} fy Force in vertical direction
  18101. * @private
  18102. */
  18103. Node.prototype._addForce = function(fx, fy) {
  18104. this.fx += fx;
  18105. this.fy += fy;
  18106. };
  18107. /**
  18108. * Store the state before the next step
  18109. */
  18110. Node.prototype.storeState = function() {
  18111. this.previousState.x = this.x;
  18112. this.previousState.y = this.y;
  18113. this.previousState.vx = this.vx;
  18114. this.previousState.vy = this.vy;
  18115. }
  18116. /**
  18117. * Perform one discrete step for the node
  18118. * @param {number} interval Time interval in seconds
  18119. */
  18120. Node.prototype.discreteStep = function(interval) {
  18121. this.storeState();
  18122. if (!this.xFixed) {
  18123. var dx = this.damping * this.vx; // damping force
  18124. var ax = (this.fx - dx) / this.options.mass; // acceleration
  18125. this.vx += ax * interval; // velocity
  18126. this.x += this.vx * interval; // position
  18127. }
  18128. else {
  18129. this.fx = 0;
  18130. this.vx = 0;
  18131. }
  18132. if (!this.yFixed) {
  18133. var dy = this.damping * this.vy; // damping force
  18134. var ay = (this.fy - dy) / this.options.mass; // acceleration
  18135. this.vy += ay * interval; // velocity
  18136. this.y += this.vy * interval; // position
  18137. }
  18138. else {
  18139. this.fy = 0;
  18140. this.vy = 0;
  18141. }
  18142. };
  18143. /**
  18144. * Perform one discrete step for the node
  18145. * @param {number} interval Time interval in seconds
  18146. * @param {number} maxVelocity The speed limit imposed on the velocity
  18147. */
  18148. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  18149. this.storeState();
  18150. if (!this.xFixed) {
  18151. var dx = this.damping * this.vx; // damping force
  18152. var ax = (this.fx - dx) / this.options.mass; // acceleration
  18153. this.vx += ax * interval; // velocity
  18154. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  18155. this.x += this.vx * interval; // position
  18156. }
  18157. else {
  18158. this.fx = 0;
  18159. this.vx = 0;
  18160. }
  18161. if (!this.yFixed) {
  18162. var dy = this.damping * this.vy; // damping force
  18163. var ay = (this.fy - dy) / this.options.mass; // acceleration
  18164. this.vy += ay * interval; // velocity
  18165. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  18166. this.y += this.vy * interval; // position
  18167. }
  18168. else {
  18169. this.fy = 0;
  18170. this.vy = 0;
  18171. }
  18172. };
  18173. /**
  18174. * Check if this node has a fixed x and y position
  18175. * @return {boolean} true if fixed, false if not
  18176. */
  18177. Node.prototype.isFixed = function() {
  18178. return (this.xFixed && this.yFixed);
  18179. };
  18180. /**
  18181. * Check if this node is moving
  18182. * @param {number} vmin the minimum velocity considered as "moving"
  18183. * @return {boolean} true if moving, false if it has no velocity
  18184. */
  18185. Node.prototype.isMoving = function(vmin) {
  18186. var velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2));
  18187. // this.velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2))
  18188. return (velocity > vmin);
  18189. };
  18190. /**
  18191. * check if this node is selecte
  18192. * @return {boolean} selected True if node is selected, else false
  18193. */
  18194. Node.prototype.isSelected = function() {
  18195. return this.selected;
  18196. };
  18197. /**
  18198. * Retrieve the value of the node. Can be undefined
  18199. * @return {Number} value
  18200. */
  18201. Node.prototype.getValue = function() {
  18202. return this.value;
  18203. };
  18204. /**
  18205. * Calculate the distance from the nodes location to the given location (x,y)
  18206. * @param {Number} x
  18207. * @param {Number} y
  18208. * @return {Number} value
  18209. */
  18210. Node.prototype.getDistance = function(x, y) {
  18211. var dx = this.x - x,
  18212. dy = this.y - y;
  18213. return Math.sqrt(dx * dx + dy * dy);
  18214. };
  18215. /**
  18216. * Adjust the value range of the node. The node will adjust it's radius
  18217. * based on its value.
  18218. * @param {Number} min
  18219. * @param {Number} max
  18220. */
  18221. Node.prototype.setValueRange = function(min, max, total) {
  18222. if (!this.radiusFixed && this.value !== undefined) {
  18223. var scale = this.options.customScalingFunction(min, max, total, this.value);
  18224. var radiusDiff = this.options.radiusMax - this.options.radiusMin;
  18225. if (this.options.scaleFontWithValue == true) {
  18226. var fontDiff = this.options.fontSizeMax - this.options.fontSizeMin;
  18227. this.options.fontSize = this.options.fontSizeMin + scale * fontDiff;
  18228. }
  18229. this.options.radius = this.options.radiusMin + scale * radiusDiff;
  18230. }
  18231. this.baseRadiusValue = this.options.radius;
  18232. };
  18233. /**
  18234. * Draw this node in the given canvas
  18235. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  18236. * @param {CanvasRenderingContext2D} ctx
  18237. */
  18238. Node.prototype.draw = function(ctx) {
  18239. throw "Draw method not initialized for node";
  18240. };
  18241. /**
  18242. * Recalculate the size of this node in the given canvas
  18243. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  18244. * @param {CanvasRenderingContext2D} ctx
  18245. */
  18246. Node.prototype.resize = function(ctx) {
  18247. throw "Resize method not initialized for node";
  18248. };
  18249. /**
  18250. * Check if this object is overlapping with the provided object
  18251. * @param {Object} obj an object with parameters left, top, right, bottom
  18252. * @return {boolean} True if location is located on node
  18253. */
  18254. Node.prototype.isOverlappingWith = function(obj) {
  18255. return (this.left < obj.right &&
  18256. this.left + this.width > obj.left &&
  18257. this.top < obj.bottom &&
  18258. this.top + this.height > obj.top);
  18259. };
  18260. Node.prototype._resizeImage = function (ctx) {
  18261. // TODO: pre calculate the image size
  18262. if (!this.width || !this.height) { // undefined or 0
  18263. var width, height;
  18264. if (this.value) {
  18265. this.options.radius= this.baseRadiusValue;
  18266. var scale = this.imageObj.height / this.imageObj.width;
  18267. if (scale !== undefined) {
  18268. width = this.options.radius|| this.imageObj.width;
  18269. height = this.options.radius* scale || this.imageObj.height;
  18270. }
  18271. else {
  18272. width = 0;
  18273. height = 0;
  18274. }
  18275. }
  18276. else {
  18277. width = this.imageObj.width;
  18278. height = this.imageObj.height;
  18279. }
  18280. this.width = width;
  18281. this.height = height;
  18282. this.growthIndicator = 0;
  18283. if (this.width > 0 && this.height > 0) {
  18284. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  18285. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  18286. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  18287. this.growthIndicator = this.width - width;
  18288. }
  18289. }
  18290. };
  18291. Node.prototype._drawImageAtPosition = function (ctx) {
  18292. if (this.imageObj.width != 0 ) {
  18293. // draw the shade
  18294. if (this.clusterSize > 1) {
  18295. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  18296. lineWidth *= this.networkScaleInv;
  18297. lineWidth = Math.min(0.2 * this.width,lineWidth);
  18298. ctx.globalAlpha = 0.5;
  18299. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  18300. }
  18301. // draw the image
  18302. ctx.globalAlpha = 1.0;
  18303. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  18304. }
  18305. };
  18306. Node.prototype._drawImageLabel = function (ctx) {
  18307. var yLabel;
  18308. var offset = 0;
  18309. if (this.height){
  18310. offset = this.height / 2;
  18311. var labelDimensions = this.getTextSize(ctx);
  18312. if (labelDimensions.lineCount >= 1){
  18313. offset += labelDimensions.height / 2;
  18314. offset += 3;
  18315. }
  18316. }
  18317. yLabel = this.y + offset;
  18318. this._label(ctx, this.label, this.x, yLabel, undefined);
  18319. };
  18320. Node.prototype._drawImage = function (ctx) {
  18321. this._resizeImage(ctx);
  18322. this.left = this.x - this.width / 2;
  18323. this.top = this.y - this.height / 2;
  18324. this._drawImageAtPosition(ctx);
  18325. this.boundingBox.top = this.top;
  18326. this.boundingBox.left = this.left;
  18327. this.boundingBox.right = this.left + this.width;
  18328. this.boundingBox.bottom = this.top + this.height;
  18329. this._drawImageLabel(ctx);
  18330. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelDimensions.left);
  18331. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelDimensions.left + this.labelDimensions.width);
  18332. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelDimensions.height);
  18333. };
  18334. Node.prototype._resizeCircularImage = function (ctx) {
  18335. if(!this.imageObj.src || !this.imageObj.width || !this.imageObj.height){
  18336. if (!this.width) {
  18337. var diameter = this.options.radius * 2;
  18338. this.width = diameter;
  18339. this.height = diameter;
  18340. // scaling used for clustering
  18341. //this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  18342. //this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  18343. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  18344. this.growthIndicator = this.options.radius- 0.5*diameter;
  18345. this._swapToImageResizeWhenImageLoaded = true;
  18346. }
  18347. }
  18348. else {
  18349. if (this._swapToImageResizeWhenImageLoaded) {
  18350. this.width = 0;
  18351. this.height = 0;
  18352. delete this._swapToImageResizeWhenImageLoaded;
  18353. }
  18354. this._resizeImage(ctx);
  18355. }
  18356. };
  18357. Node.prototype._drawCircularImage = function (ctx) {
  18358. this._resizeCircularImage(ctx);
  18359. this.left = this.x - this.width / 2;
  18360. this.top = this.y - this.height / 2;
  18361. var centerX = this.left + (this.width / 2);
  18362. var centerY = this.top + (this.height / 2);
  18363. var radius = Math.abs(this.height / 2);
  18364. this._drawRawCircle(ctx, centerX, centerY, radius);
  18365. ctx.save();
  18366. ctx.circle(this.x, this.y, radius);
  18367. ctx.stroke();
  18368. ctx.clip();
  18369. this._drawImageAtPosition(ctx);
  18370. ctx.restore();
  18371. this.boundingBox.top = this.y - this.options.radius;
  18372. this.boundingBox.left = this.x - this.options.radius;
  18373. this.boundingBox.right = this.x + this.options.radius;
  18374. this.boundingBox.bottom = this.y + this.options.radius;
  18375. this._drawImageLabel(ctx);
  18376. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelDimensions.left);
  18377. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelDimensions.left + this.labelDimensions.width);
  18378. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelDimensions.height);
  18379. };
  18380. Node.prototype._resizeBox = function (ctx) {
  18381. if (!this.width) {
  18382. var margin = 5;
  18383. var textSize = this.getTextSize(ctx);
  18384. this.width = textSize.width + 2 * margin;
  18385. this.height = textSize.height + 2 * margin;
  18386. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  18387. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  18388. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  18389. // this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  18390. }
  18391. };
  18392. Node.prototype._drawBox = function (ctx) {
  18393. this._resizeBox(ctx);
  18394. this.left = this.x - this.width / 2;
  18395. this.top = this.y - this.height / 2;
  18396. var clusterLineWidth = 2.5;
  18397. var borderWidth = this.options.borderWidth;
  18398. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  18399. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  18400. // draw the outer border
  18401. if (this.clusterSize > 1) {
  18402. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  18403. ctx.lineWidth *= this.networkScaleInv;
  18404. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  18405. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.options.radius);
  18406. ctx.stroke();
  18407. }
  18408. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  18409. ctx.lineWidth *= this.networkScaleInv;
  18410. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  18411. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  18412. ctx.roundRect(this.left, this.top, this.width, this.height, this.options.radius);
  18413. ctx.fill();
  18414. ctx.stroke();
  18415. this.boundingBox.top = this.top;
  18416. this.boundingBox.left = this.left;
  18417. this.boundingBox.right = this.left + this.width;
  18418. this.boundingBox.bottom = this.top + this.height;
  18419. this._label(ctx, this.label, this.x, this.y);
  18420. };
  18421. Node.prototype._resizeDatabase = function (ctx) {
  18422. if (!this.width) {
  18423. var margin = 5;
  18424. var textSize = this.getTextSize(ctx);
  18425. var size = textSize.width + 2 * margin;
  18426. this.width = size;
  18427. this.height = size;
  18428. // scaling used for clustering
  18429. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  18430. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  18431. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  18432. this.growthIndicator = this.width - size;
  18433. }
  18434. };
  18435. Node.prototype._drawDatabase = function (ctx) {
  18436. this._resizeDatabase(ctx);
  18437. this.left = this.x - this.width / 2;
  18438. this.top = this.y - this.height / 2;
  18439. var clusterLineWidth = 2.5;
  18440. var borderWidth = this.options.borderWidth;
  18441. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  18442. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  18443. // draw the outer border
  18444. if (this.clusterSize > 1) {
  18445. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  18446. ctx.lineWidth *= this.networkScaleInv;
  18447. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  18448. ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth);
  18449. ctx.stroke();
  18450. }
  18451. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  18452. ctx.lineWidth *= this.networkScaleInv;
  18453. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  18454. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  18455. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  18456. ctx.fill();
  18457. ctx.stroke();
  18458. this.boundingBox.top = this.top;
  18459. this.boundingBox.left = this.left;
  18460. this.boundingBox.right = this.left + this.width;
  18461. this.boundingBox.bottom = this.top + this.height;
  18462. this._label(ctx, this.label, this.x, this.y);
  18463. };
  18464. Node.prototype._resizeCircle = function (ctx) {
  18465. if (!this.width) {
  18466. var margin = 5;
  18467. var textSize = this.getTextSize(ctx);
  18468. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  18469. this.options.radius = diameter / 2;
  18470. this.width = diameter;
  18471. this.height = diameter;
  18472. // scaling used for clustering
  18473. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  18474. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  18475. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  18476. this.growthIndicator = this.options.radius- 0.5*diameter;
  18477. }
  18478. };
  18479. Node.prototype._drawRawCircle = function (ctx, x, y, radius) {
  18480. var clusterLineWidth = 2.5;
  18481. var borderWidth = this.options.borderWidth;
  18482. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  18483. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  18484. // draw the outer border
  18485. if (this.clusterSize > 1) {
  18486. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  18487. ctx.lineWidth *= this.networkScaleInv;
  18488. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  18489. ctx.circle(x, y, radius+2*ctx.lineWidth);
  18490. ctx.stroke();
  18491. }
  18492. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  18493. ctx.lineWidth *= this.networkScaleInv;
  18494. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  18495. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  18496. ctx.circle(this.x, this.y, radius);
  18497. ctx.fill();
  18498. ctx.stroke();
  18499. };
  18500. Node.prototype._drawCircle = function (ctx) {
  18501. this._resizeCircle(ctx);
  18502. this.left = this.x - this.width / 2;
  18503. this.top = this.y - this.height / 2;
  18504. this._drawRawCircle(ctx, this.x, this.y, this.options.radius);
  18505. this.boundingBox.top = this.y - this.options.radius;
  18506. this.boundingBox.left = this.x - this.options.radius;
  18507. this.boundingBox.right = this.x + this.options.radius;
  18508. this.boundingBox.bottom = this.y + this.options.radius;
  18509. this._label(ctx, this.label, this.x, this.y);
  18510. };
  18511. Node.prototype._resizeEllipse = function (ctx) {
  18512. if (!this.width) {
  18513. var textSize = this.getTextSize(ctx);
  18514. this.width = textSize.width * 1.5;
  18515. this.height = textSize.height * 2;
  18516. if (this.width < this.height) {
  18517. this.width = this.height;
  18518. }
  18519. var defaultSize = this.width;
  18520. // scaling used for clustering
  18521. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  18522. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  18523. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  18524. this.growthIndicator = this.width - defaultSize;
  18525. }
  18526. };
  18527. Node.prototype._drawEllipse = function (ctx) {
  18528. this._resizeEllipse(ctx);
  18529. this.left = this.x - this.width / 2;
  18530. this.top = this.y - this.height / 2;
  18531. var clusterLineWidth = 2.5;
  18532. var borderWidth = this.options.borderWidth;
  18533. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  18534. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  18535. // draw the outer border
  18536. if (this.clusterSize > 1) {
  18537. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  18538. ctx.lineWidth *= this.networkScaleInv;
  18539. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  18540. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  18541. ctx.stroke();
  18542. }
  18543. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  18544. ctx.lineWidth *= this.networkScaleInv;
  18545. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  18546. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  18547. ctx.ellipse(this.left, this.top, this.width, this.height);
  18548. ctx.fill();
  18549. ctx.stroke();
  18550. this.boundingBox.top = this.top;
  18551. this.boundingBox.left = this.left;
  18552. this.boundingBox.right = this.left + this.width;
  18553. this.boundingBox.bottom = this.top + this.height;
  18554. this._label(ctx, this.label, this.x, this.y);
  18555. };
  18556. Node.prototype._drawDot = function (ctx) {
  18557. this._drawShape(ctx, 'circle');
  18558. };
  18559. Node.prototype._drawTriangle = function (ctx) {
  18560. this._drawShape(ctx, 'triangle');
  18561. };
  18562. Node.prototype._drawTriangleDown = function (ctx) {
  18563. this._drawShape(ctx, 'triangleDown');
  18564. };
  18565. Node.prototype._drawSquare = function (ctx) {
  18566. this._drawShape(ctx, 'square');
  18567. };
  18568. Node.prototype._drawStar = function (ctx) {
  18569. this._drawShape(ctx, 'star');
  18570. };
  18571. Node.prototype._resizeShape = function (ctx) {
  18572. if (!this.width) {
  18573. this.options.radius= this.baseRadiusValue;
  18574. var size = 2 * this.options.radius;
  18575. this.width = size;
  18576. this.height = size;
  18577. // scaling used for clustering
  18578. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  18579. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  18580. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  18581. this.growthIndicator = this.width - size;
  18582. }
  18583. };
  18584. Node.prototype._drawShape = function (ctx, shape) {
  18585. this._resizeShape(ctx);
  18586. this.left = this.x - this.width / 2;
  18587. this.top = this.y - this.height / 2;
  18588. var clusterLineWidth = 2.5;
  18589. var borderWidth = this.options.borderWidth;
  18590. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  18591. var radiusMultiplier = 2;
  18592. // choose draw method depending on the shape
  18593. switch (shape) {
  18594. case 'dot': radiusMultiplier = 2; break;
  18595. case 'square': radiusMultiplier = 2; break;
  18596. case 'triangle': radiusMultiplier = 3; break;
  18597. case 'triangleDown': radiusMultiplier = 3; break;
  18598. case 'star': radiusMultiplier = 4; break;
  18599. }
  18600. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  18601. // draw the outer border
  18602. if (this.clusterSize > 1) {
  18603. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  18604. ctx.lineWidth *= this.networkScaleInv;
  18605. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  18606. ctx[shape](this.x, this.y, this.options.radius+ radiusMultiplier * ctx.lineWidth);
  18607. ctx.stroke();
  18608. }
  18609. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  18610. ctx.lineWidth *= this.networkScaleInv;
  18611. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  18612. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  18613. ctx[shape](this.x, this.y, this.options.radius);
  18614. ctx.fill();
  18615. ctx.stroke();
  18616. this.boundingBox.top = this.y - this.options.radius;
  18617. this.boundingBox.left = this.x - this.options.radius;
  18618. this.boundingBox.right = this.x + this.options.radius;
  18619. this.boundingBox.bottom = this.y + this.options.radius;
  18620. if (this.label) {
  18621. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'hanging',true);
  18622. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelDimensions.left);
  18623. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelDimensions.left + this.labelDimensions.width);
  18624. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelDimensions.height);
  18625. }
  18626. };
  18627. Node.prototype._resizeText = function (ctx) {
  18628. if (!this.width) {
  18629. var margin = 5;
  18630. var textSize = this.getTextSize(ctx);
  18631. this.width = textSize.width + 2 * margin;
  18632. this.height = textSize.height + 2 * margin;
  18633. // scaling used for clustering
  18634. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  18635. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  18636. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  18637. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  18638. }
  18639. };
  18640. Node.prototype._drawText = function (ctx) {
  18641. this._resizeText(ctx);
  18642. this.left = this.x - this.width / 2;
  18643. this.top = this.y - this.height / 2;
  18644. this._label(ctx, this.label, this.x, this.y);
  18645. this.boundingBox.top = this.top;
  18646. this.boundingBox.left = this.left;
  18647. this.boundingBox.right = this.left + this.width;
  18648. this.boundingBox.bottom = this.top + this.height;
  18649. };
  18650. Node.prototype._resizeIcon = function (ctx) {
  18651. if (!this.width) {
  18652. var margin = 5;
  18653. var iconSize =
  18654. {
  18655. width: Number(this.options.iconSize),
  18656. height: Number(this.options.iconSize)
  18657. };
  18658. this.width = iconSize.width + 2 * margin;
  18659. this.height = iconSize.height + 2 * margin;
  18660. // scaling used for clustering
  18661. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  18662. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  18663. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  18664. this.growthIndicator = this.width - (iconSize.width + 2 * margin);
  18665. }
  18666. };
  18667. Node.prototype._drawIcon = function (ctx) {
  18668. this._resizeIcon(ctx);
  18669. this.options.iconSize = this.options.iconSize || 50;
  18670. this.left = this.x - this.width / 2;
  18671. this.top = this.y - this.height / 2;
  18672. this._icon(ctx);
  18673. this.boundingBox.top = this.y - this.options.iconSize/2;
  18674. this.boundingBox.left = this.x - this.options.iconSize/2;
  18675. this.boundingBox.right = this.x + this.options.iconSize/2;
  18676. this.boundingBox.bottom = this.y + this.options.iconSize/2;
  18677. if (this.label) {
  18678. var iconTextSpacing = 5;
  18679. this._label(ctx, this.label, this.x, this.y + this.height / 2 + iconTextSpacing, 'top', true);
  18680. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelDimensions.left);
  18681. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelDimensions.left + this.labelDimensions.width);
  18682. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelDimensions.height);
  18683. }
  18684. };
  18685. Node.prototype._icon = function (ctx) {
  18686. var relativeIconSize = Number(this.options.iconSize) * this.networkScale;
  18687. if (this.options.icon && relativeIconSize > this.options.fontDrawThreshold - 1) {
  18688. var iconSize = Number(this.options.iconSize);
  18689. ctx.font = (this.selected ? "bold " : "") + iconSize + "px " + this.options.iconFontFace;
  18690. // draw icon
  18691. ctx.fillStyle = this.options.iconColor || "black";
  18692. ctx.textAlign = "center";
  18693. ctx.textBaseline = "middle";
  18694. ctx.fillText(this.options.icon, this.x, this.y);
  18695. }
  18696. };
  18697. Node.prototype._label = function (ctx, text, x, y, align, baseline, labelUnderNode) {
  18698. var relativeFontSize = Number(this.options.fontSize) * this.networkScale;
  18699. if (text && relativeFontSize >= this.options.fontDrawThreshold - 1) {
  18700. var fontSize = Number(this.options.fontSize);
  18701. // this ensures that there will not be HUGE letters on screen by setting an upper limit on the visible text size (regardless of zoomLevel)
  18702. if (relativeFontSize >= this.options.fontSizeMaxVisible) {
  18703. fontSize = Number(this.options.fontSizeMaxVisible) * this.networkScaleInv;
  18704. }
  18705. // fade in when relative scale is between threshold and threshold - 1
  18706. var fontColor = this.options.fontColor || "#000000";
  18707. var strokecolor = this.options.fontStrokeColor;
  18708. if (relativeFontSize <= this.options.fontDrawThreshold) {
  18709. var opacity = Math.max(0,Math.min(1,1 - (this.options.fontDrawThreshold - relativeFontSize)));
  18710. fontColor = util.overrideOpacity(fontColor, opacity);
  18711. strokecolor = util.overrideOpacity(strokecolor, opacity);
  18712. }
  18713. ctx.font = (this.selected ? "bold " : "") + fontSize + "px " + this.options.fontFace;
  18714. var lines = text.split('\n');
  18715. var lineCount = lines.length;
  18716. var yLine = y + (1 - lineCount) / 2 * fontSize;
  18717. if (labelUnderNode == true) {
  18718. yLine = y + (1 - lineCount) / (2 * fontSize);
  18719. }
  18720. // font fill from edges now for nodes!
  18721. var width = ctx.measureText(lines[0]).width;
  18722. for (var i = 1; i < lineCount; i++) {
  18723. var lineWidth = ctx.measureText(lines[i]).width;
  18724. width = lineWidth > width ? lineWidth : width;
  18725. }
  18726. var height = fontSize * lineCount;
  18727. var left = x - width / 2;
  18728. var top = y - height / 2;
  18729. if (baseline == "hanging") {
  18730. top += 0.5 * fontSize;
  18731. top += 4; // distance from node, required because we use hanging. Hanging has less difference between browsers
  18732. yLine += 4; // distance from node
  18733. }
  18734. this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
  18735. // create the fontfill background
  18736. if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
  18737. ctx.fillStyle = this.options.fontFill;
  18738. ctx.fillRect(left, top, width, height);
  18739. }
  18740. // draw text
  18741. ctx.fillStyle = fontColor;
  18742. ctx.textAlign = align || "center";
  18743. ctx.textBaseline = baseline || "middle";
  18744. if (this.options.fontStrokeWidth > 0){
  18745. ctx.lineWidth = this.options.fontStrokeWidth;
  18746. ctx.strokeStyle = strokecolor;
  18747. ctx.lineJoin = 'round';
  18748. }
  18749. for (var i = 0; i < lineCount; i++) {
  18750. if(this.options.fontStrokeWidth){
  18751. ctx.strokeText(lines[i], x, yLine);
  18752. }
  18753. ctx.fillText(lines[i], x, yLine);
  18754. yLine += fontSize;
  18755. }
  18756. }
  18757. };
  18758. Node.prototype.getTextSize = function(ctx) {
  18759. if (this.label !== undefined) {
  18760. var fontSize = Number(this.options.fontSize);
  18761. if (fontSize * this.networkScale > this.options.fontSizeMaxVisible) {
  18762. fontSize = Number(this.options.fontSizeMaxVisible) * this.networkScaleInv;
  18763. }
  18764. ctx.font = (this.selected ? "bold " : "") + fontSize + "px " + this.options.fontFace;
  18765. var lines = this.label.split('\n'),
  18766. height = (fontSize + 4) * lines.length,
  18767. width = 0;
  18768. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  18769. width = Math.max(width, ctx.measureText(lines[i]).width);
  18770. }
  18771. return {"width": width, "height": height, lineCount: lines.length};
  18772. }
  18773. else {
  18774. return {"width": 0, "height": 0, lineCount: 0};
  18775. }
  18776. };
  18777. /**
  18778. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  18779. * there is a safety margin of 0.3 * width;
  18780. *
  18781. * @returns {boolean}
  18782. */
  18783. Node.prototype.inArea = function() {
  18784. if (this.width !== undefined) {
  18785. return (this.x + this.width *this.networkScaleInv >= this.canvasTopLeft.x &&
  18786. this.x - this.width *this.networkScaleInv < this.canvasBottomRight.x &&
  18787. this.y + this.height*this.networkScaleInv >= this.canvasTopLeft.y &&
  18788. this.y - this.height*this.networkScaleInv < this.canvasBottomRight.y);
  18789. }
  18790. else {
  18791. return true;
  18792. }
  18793. };
  18794. /**
  18795. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  18796. * @returns {boolean}
  18797. */
  18798. Node.prototype.inView = function() {
  18799. return (this.x >= this.canvasTopLeft.x &&
  18800. this.x < this.canvasBottomRight.x &&
  18801. this.y >= this.canvasTopLeft.y &&
  18802. this.y < this.canvasBottomRight.y);
  18803. };
  18804. /**
  18805. * This allows the zoom level of the network to influence the rendering
  18806. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  18807. *
  18808. * @param scale
  18809. * @param canvasTopLeft
  18810. * @param canvasBottomRight
  18811. */
  18812. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  18813. this.networkScaleInv = 1.0/scale;
  18814. this.networkScale = scale;
  18815. this.canvasTopLeft = canvasTopLeft;
  18816. this.canvasBottomRight = canvasBottomRight;
  18817. };
  18818. /**
  18819. * This allows the zoom level of the network to influence the rendering
  18820. *
  18821. * @param scale
  18822. */
  18823. Node.prototype.setScale = function(scale) {
  18824. this.networkScaleInv = 1.0/scale;
  18825. this.networkScale = scale;
  18826. };
  18827. /**
  18828. * set the velocity at 0. Is called when this node is contained in another during clustering
  18829. */
  18830. Node.prototype.clearVelocity = function() {
  18831. this.vx = 0;
  18832. this.vy = 0;
  18833. };
  18834. /**
  18835. * Basic preservation of (kinectic) energy
  18836. *
  18837. * @param massBeforeClustering
  18838. */
  18839. Node.prototype.updateVelocity = function(massBeforeClustering) {
  18840. var energyBefore = this.vx * this.vx * massBeforeClustering;
  18841. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  18842. this.vx = Math.sqrt(energyBefore/this.options.mass);
  18843. energyBefore = this.vy * this.vy * massBeforeClustering;
  18844. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  18845. this.vy = Math.sqrt(energyBefore/this.options.mass);
  18846. };
  18847. module.exports = Node;
  18848. /***/ },
  18849. /* 41 */
  18850. /***/ function(module, exports, __webpack_require__) {
  18851. /**
  18852. * Popup is a class to create a popup window with some text
  18853. * @param {Element} container The container object.
  18854. * @param {Number} [x]
  18855. * @param {Number} [y]
  18856. * @param {String} [text]
  18857. * @param {Object} [style] An object containing borderColor,
  18858. * backgroundColor, etc.
  18859. */
  18860. function Popup(container, x, y, text, style) {
  18861. if (container) {
  18862. this.container = container;
  18863. }
  18864. else {
  18865. this.container = document.body;
  18866. }
  18867. // x, y and text are optional, see if a style object was passed in their place
  18868. if (style === undefined) {
  18869. if (typeof x === "object") {
  18870. style = x;
  18871. x = undefined;
  18872. } else if (typeof text === "object") {
  18873. style = text;
  18874. text = undefined;
  18875. } else {
  18876. // for backwards compatibility, in case clients other than Network are creating Popup directly
  18877. style = {
  18878. fontColor: 'black',
  18879. fontSize: 14, // px
  18880. fontFace: 'verdana',
  18881. color: {
  18882. border: '#666',
  18883. background: '#FFFFC6'
  18884. }
  18885. }
  18886. }
  18887. }
  18888. this.x = 0;
  18889. this.y = 0;
  18890. this.padding = 5;
  18891. this.hidden = false;
  18892. if (x !== undefined && y !== undefined) {
  18893. this.setPosition(x, y);
  18894. }
  18895. if (text !== undefined) {
  18896. this.setText(text);
  18897. }
  18898. // create the frame
  18899. this.frame = document.createElement('div');
  18900. this.frame.className = 'network-tooltip';
  18901. this.frame.style.color = style.fontColor;
  18902. this.frame.style.backgroundColor = style.color.background;
  18903. this.frame.style.borderColor = style.color.border;
  18904. this.frame.style.fontSize = style.fontSize + 'px';
  18905. this.frame.style.fontFamily = style.fontFace;
  18906. this.container.appendChild(this.frame);
  18907. }
  18908. /**
  18909. * @param {number} x Horizontal position of the popup window
  18910. * @param {number} y Vertical position of the popup window
  18911. */
  18912. Popup.prototype.setPosition = function(x, y) {
  18913. this.x = parseInt(x);
  18914. this.y = parseInt(y);
  18915. };
  18916. /**
  18917. * Set the content for the popup window. This can be HTML code or text.
  18918. * @param {string | Element} content
  18919. */
  18920. Popup.prototype.setText = function(content) {
  18921. if (content instanceof Element) {
  18922. this.frame.innerHTML = '';
  18923. this.frame.appendChild(content);
  18924. }
  18925. else {
  18926. this.frame.innerHTML = content; // string containing text or HTML
  18927. }
  18928. };
  18929. /**
  18930. * Show the popup window
  18931. * @param {boolean} show Optional. Show or hide the window
  18932. */
  18933. Popup.prototype.show = function (show) {
  18934. if (show === undefined) {
  18935. show = true;
  18936. }
  18937. if (show) {
  18938. var height = this.frame.clientHeight;
  18939. var width = this.frame.clientWidth;
  18940. var maxHeight = this.frame.parentNode.clientHeight;
  18941. var maxWidth = this.frame.parentNode.clientWidth;
  18942. var top = (this.y - height);
  18943. if (top + height + this.padding > maxHeight) {
  18944. top = maxHeight - height - this.padding;
  18945. }
  18946. if (top < this.padding) {
  18947. top = this.padding;
  18948. }
  18949. var left = this.x;
  18950. if (left + width + this.padding > maxWidth) {
  18951. left = maxWidth - width - this.padding;
  18952. }
  18953. if (left < this.padding) {
  18954. left = this.padding;
  18955. }
  18956. this.frame.style.left = left + "px";
  18957. this.frame.style.top = top + "px";
  18958. this.frame.style.visibility = "visible";
  18959. this.hidden = false;
  18960. }
  18961. else {
  18962. this.hide();
  18963. }
  18964. };
  18965. /**
  18966. * Hide the popup window
  18967. */
  18968. Popup.prototype.hide = function () {
  18969. this.hidden = true;
  18970. this.frame.style.visibility = "hidden";
  18971. };
  18972. module.exports = Popup;
  18973. /***/ },
  18974. /* 42 */
  18975. /***/ function(module, exports, __webpack_require__) {
  18976. /**
  18977. * Parse a text source containing data in DOT language into a JSON object.
  18978. * The object contains two lists: one with nodes and one with edges.
  18979. *
  18980. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  18981. *
  18982. * @param {String} data Text containing a graph in DOT-notation
  18983. * @return {Object} graph An object containing two parameters:
  18984. * {Object[]} nodes
  18985. * {Object[]} edges
  18986. */
  18987. function parseDOT (data) {
  18988. dot = data;
  18989. return parseGraph();
  18990. }
  18991. // token types enumeration
  18992. var TOKENTYPE = {
  18993. NULL : 0,
  18994. DELIMITER : 1,
  18995. IDENTIFIER: 2,
  18996. UNKNOWN : 3
  18997. };
  18998. // map with all delimiters
  18999. var DELIMITERS = {
  19000. '{': true,
  19001. '}': true,
  19002. '[': true,
  19003. ']': true,
  19004. ';': true,
  19005. '=': true,
  19006. ',': true,
  19007. '->': true,
  19008. '--': true
  19009. };
  19010. var dot = ''; // current dot file
  19011. var index = 0; // current index in dot file
  19012. var c = ''; // current token character in expr
  19013. var token = ''; // current token
  19014. var tokenType = TOKENTYPE.NULL; // type of the token
  19015. /**
  19016. * Get the first character from the dot file.
  19017. * The character is stored into the char c. If the end of the dot file is
  19018. * reached, the function puts an empty string in c.
  19019. */
  19020. function first() {
  19021. index = 0;
  19022. c = dot.charAt(0);
  19023. }
  19024. /**
  19025. * Get the next character from the dot file.
  19026. * The character is stored into the char c. If the end of the dot file is
  19027. * reached, the function puts an empty string in c.
  19028. */
  19029. function next() {
  19030. index++;
  19031. c = dot.charAt(index);
  19032. }
  19033. /**
  19034. * Preview the next character from the dot file.
  19035. * @return {String} cNext
  19036. */
  19037. function nextPreview() {
  19038. return dot.charAt(index + 1);
  19039. }
  19040. /**
  19041. * Test whether given character is alphabetic or numeric
  19042. * @param {String} c
  19043. * @return {Boolean} isAlphaNumeric
  19044. */
  19045. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  19046. function isAlphaNumeric(c) {
  19047. return regexAlphaNumeric.test(c);
  19048. }
  19049. /**
  19050. * Merge all properties of object b into object b
  19051. * @param {Object} a
  19052. * @param {Object} b
  19053. * @return {Object} a
  19054. */
  19055. function merge (a, b) {
  19056. if (!a) {
  19057. a = {};
  19058. }
  19059. if (b) {
  19060. for (var name in b) {
  19061. if (b.hasOwnProperty(name)) {
  19062. a[name] = b[name];
  19063. }
  19064. }
  19065. }
  19066. return a;
  19067. }
  19068. /**
  19069. * Set a value in an object, where the provided parameter name can be a
  19070. * path with nested parameters. For example:
  19071. *
  19072. * var obj = {a: 2};
  19073. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  19074. *
  19075. * @param {Object} obj
  19076. * @param {String} path A parameter name or dot-separated parameter path,
  19077. * like "color.highlight.border".
  19078. * @param {*} value
  19079. */
  19080. function setValue(obj, path, value) {
  19081. var keys = path.split('.');
  19082. var o = obj;
  19083. while (keys.length) {
  19084. var key = keys.shift();
  19085. if (keys.length) {
  19086. // this isn't the end point
  19087. if (!o[key]) {
  19088. o[key] = {};
  19089. }
  19090. o = o[key];
  19091. }
  19092. else {
  19093. // this is the end point
  19094. o[key] = value;
  19095. }
  19096. }
  19097. }
  19098. /**
  19099. * Add a node to a graph object. If there is already a node with
  19100. * the same id, their attributes will be merged.
  19101. * @param {Object} graph
  19102. * @param {Object} node
  19103. */
  19104. function addNode(graph, node) {
  19105. var i, len;
  19106. var current = null;
  19107. // find root graph (in case of subgraph)
  19108. var graphs = [graph]; // list with all graphs from current graph to root graph
  19109. var root = graph;
  19110. while (root.parent) {
  19111. graphs.push(root.parent);
  19112. root = root.parent;
  19113. }
  19114. // find existing node (at root level) by its id
  19115. if (root.nodes) {
  19116. for (i = 0, len = root.nodes.length; i < len; i++) {
  19117. if (node.id === root.nodes[i].id) {
  19118. current = root.nodes[i];
  19119. break;
  19120. }
  19121. }
  19122. }
  19123. if (!current) {
  19124. // this is a new node
  19125. current = {
  19126. id: node.id
  19127. };
  19128. if (graph.node) {
  19129. // clone default attributes
  19130. current.attr = merge(current.attr, graph.node);
  19131. }
  19132. }
  19133. // add node to this (sub)graph and all its parent graphs
  19134. for (i = graphs.length - 1; i >= 0; i--) {
  19135. var g = graphs[i];
  19136. if (!g.nodes) {
  19137. g.nodes = [];
  19138. }
  19139. if (g.nodes.indexOf(current) == -1) {
  19140. g.nodes.push(current);
  19141. }
  19142. }
  19143. // merge attributes
  19144. if (node.attr) {
  19145. current.attr = merge(current.attr, node.attr);
  19146. }
  19147. }
  19148. /**
  19149. * Add an edge to a graph object
  19150. * @param {Object} graph
  19151. * @param {Object} edge
  19152. */
  19153. function addEdge(graph, edge) {
  19154. if (!graph.edges) {
  19155. graph.edges = [];
  19156. }
  19157. graph.edges.push(edge);
  19158. if (graph.edge) {
  19159. var attr = merge({}, graph.edge); // clone default attributes
  19160. edge.attr = merge(attr, edge.attr); // merge attributes
  19161. }
  19162. }
  19163. /**
  19164. * Create an edge to a graph object
  19165. * @param {Object} graph
  19166. * @param {String | Number | Object} from
  19167. * @param {String | Number | Object} to
  19168. * @param {String} type
  19169. * @param {Object | null} attr
  19170. * @return {Object} edge
  19171. */
  19172. function createEdge(graph, from, to, type, attr) {
  19173. var edge = {
  19174. from: from,
  19175. to: to,
  19176. type: type
  19177. };
  19178. if (graph.edge) {
  19179. edge.attr = merge({}, graph.edge); // clone default attributes
  19180. }
  19181. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  19182. return edge;
  19183. }
  19184. /**
  19185. * Get next token in the current dot file.
  19186. * The token and token type are available as token and tokenType
  19187. */
  19188. function getToken() {
  19189. tokenType = TOKENTYPE.NULL;
  19190. token = '';
  19191. // skip over whitespaces
  19192. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  19193. next();
  19194. }
  19195. do {
  19196. var isComment = false;
  19197. // skip comment
  19198. if (c == '#') {
  19199. // find the previous non-space character
  19200. var i = index - 1;
  19201. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  19202. i--;
  19203. }
  19204. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  19205. // the # is at the start of a line, this is indeed a line comment
  19206. while (c != '' && c != '\n') {
  19207. next();
  19208. }
  19209. isComment = true;
  19210. }
  19211. }
  19212. if (c == '/' && nextPreview() == '/') {
  19213. // skip line comment
  19214. while (c != '' && c != '\n') {
  19215. next();
  19216. }
  19217. isComment = true;
  19218. }
  19219. if (c == '/' && nextPreview() == '*') {
  19220. // skip block comment
  19221. while (c != '') {
  19222. if (c == '*' && nextPreview() == '/') {
  19223. // end of block comment found. skip these last two characters
  19224. next();
  19225. next();
  19226. break;
  19227. }
  19228. else {
  19229. next();
  19230. }
  19231. }
  19232. isComment = true;
  19233. }
  19234. // skip over whitespaces
  19235. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  19236. next();
  19237. }
  19238. }
  19239. while (isComment);
  19240. // check for end of dot file
  19241. if (c == '') {
  19242. // token is still empty
  19243. tokenType = TOKENTYPE.DELIMITER;
  19244. return;
  19245. }
  19246. // check for delimiters consisting of 2 characters
  19247. var c2 = c + nextPreview();
  19248. if (DELIMITERS[c2]) {
  19249. tokenType = TOKENTYPE.DELIMITER;
  19250. token = c2;
  19251. next();
  19252. next();
  19253. return;
  19254. }
  19255. // check for delimiters consisting of 1 character
  19256. if (DELIMITERS[c]) {
  19257. tokenType = TOKENTYPE.DELIMITER;
  19258. token = c;
  19259. next();
  19260. return;
  19261. }
  19262. // check for an identifier (number or string)
  19263. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  19264. if (isAlphaNumeric(c) || c == '-') {
  19265. token += c;
  19266. next();
  19267. while (isAlphaNumeric(c)) {
  19268. token += c;
  19269. next();
  19270. }
  19271. if (token == 'false') {
  19272. token = false; // convert to boolean
  19273. }
  19274. else if (token == 'true') {
  19275. token = true; // convert to boolean
  19276. }
  19277. else if (!isNaN(Number(token))) {
  19278. token = Number(token); // convert to number
  19279. }
  19280. tokenType = TOKENTYPE.IDENTIFIER;
  19281. return;
  19282. }
  19283. // check for a string enclosed by double quotes
  19284. if (c == '"') {
  19285. next();
  19286. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  19287. token += c;
  19288. if (c == '"') { // skip the escape character
  19289. next();
  19290. }
  19291. next();
  19292. }
  19293. if (c != '"') {
  19294. throw newSyntaxError('End of string " expected');
  19295. }
  19296. next();
  19297. tokenType = TOKENTYPE.IDENTIFIER;
  19298. return;
  19299. }
  19300. // something unknown is found, wrong characters, a syntax error
  19301. tokenType = TOKENTYPE.UNKNOWN;
  19302. while (c != '') {
  19303. token += c;
  19304. next();
  19305. }
  19306. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  19307. }
  19308. /**
  19309. * Parse a graph.
  19310. * @returns {Object} graph
  19311. */
  19312. function parseGraph() {
  19313. var graph = {};
  19314. first();
  19315. getToken();
  19316. // optional strict keyword
  19317. if (token == 'strict') {
  19318. graph.strict = true;
  19319. getToken();
  19320. }
  19321. // graph or digraph keyword
  19322. if (token == 'graph' || token == 'digraph') {
  19323. graph.type = token;
  19324. getToken();
  19325. }
  19326. // optional graph id
  19327. if (tokenType == TOKENTYPE.IDENTIFIER) {
  19328. graph.id = token;
  19329. getToken();
  19330. }
  19331. // open angle bracket
  19332. if (token != '{') {
  19333. throw newSyntaxError('Angle bracket { expected');
  19334. }
  19335. getToken();
  19336. // statements
  19337. parseStatements(graph);
  19338. // close angle bracket
  19339. if (token != '}') {
  19340. throw newSyntaxError('Angle bracket } expected');
  19341. }
  19342. getToken();
  19343. // end of file
  19344. if (token !== '') {
  19345. throw newSyntaxError('End of file expected');
  19346. }
  19347. getToken();
  19348. // remove temporary default properties
  19349. delete graph.node;
  19350. delete graph.edge;
  19351. delete graph.graph;
  19352. return graph;
  19353. }
  19354. /**
  19355. * Parse a list with statements.
  19356. * @param {Object} graph
  19357. */
  19358. function parseStatements (graph) {
  19359. while (token !== '' && token != '}') {
  19360. parseStatement(graph);
  19361. if (token == ';') {
  19362. getToken();
  19363. }
  19364. }
  19365. }
  19366. /**
  19367. * Parse a single statement. Can be a an attribute statement, node
  19368. * statement, a series of node statements and edge statements, or a
  19369. * parameter.
  19370. * @param {Object} graph
  19371. */
  19372. function parseStatement(graph) {
  19373. // parse subgraph
  19374. var subgraph = parseSubgraph(graph);
  19375. if (subgraph) {
  19376. // edge statements
  19377. parseEdge(graph, subgraph);
  19378. return;
  19379. }
  19380. // parse an attribute statement
  19381. var attr = parseAttributeStatement(graph);
  19382. if (attr) {
  19383. return;
  19384. }
  19385. // parse node
  19386. if (tokenType != TOKENTYPE.IDENTIFIER) {
  19387. throw newSyntaxError('Identifier expected');
  19388. }
  19389. var id = token; // id can be a string or a number
  19390. getToken();
  19391. if (token == '=') {
  19392. // id statement
  19393. getToken();
  19394. if (tokenType != TOKENTYPE.IDENTIFIER) {
  19395. throw newSyntaxError('Identifier expected');
  19396. }
  19397. graph[id] = token;
  19398. getToken();
  19399. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  19400. }
  19401. else {
  19402. parseNodeStatement(graph, id);
  19403. }
  19404. }
  19405. /**
  19406. * Parse a subgraph
  19407. * @param {Object} graph parent graph object
  19408. * @return {Object | null} subgraph
  19409. */
  19410. function parseSubgraph (graph) {
  19411. var subgraph = null;
  19412. // optional subgraph keyword
  19413. if (token == 'subgraph') {
  19414. subgraph = {};
  19415. subgraph.type = 'subgraph';
  19416. getToken();
  19417. // optional graph id
  19418. if (tokenType == TOKENTYPE.IDENTIFIER) {
  19419. subgraph.id = token;
  19420. getToken();
  19421. }
  19422. }
  19423. // open angle bracket
  19424. if (token == '{') {
  19425. getToken();
  19426. if (!subgraph) {
  19427. subgraph = {};
  19428. }
  19429. subgraph.parent = graph;
  19430. subgraph.node = graph.node;
  19431. subgraph.edge = graph.edge;
  19432. subgraph.graph = graph.graph;
  19433. // statements
  19434. parseStatements(subgraph);
  19435. // close angle bracket
  19436. if (token != '}') {
  19437. throw newSyntaxError('Angle bracket } expected');
  19438. }
  19439. getToken();
  19440. // remove temporary default properties
  19441. delete subgraph.node;
  19442. delete subgraph.edge;
  19443. delete subgraph.graph;
  19444. delete subgraph.parent;
  19445. // register at the parent graph
  19446. if (!graph.subgraphs) {
  19447. graph.subgraphs = [];
  19448. }
  19449. graph.subgraphs.push(subgraph);
  19450. }
  19451. return subgraph;
  19452. }
  19453. /**
  19454. * parse an attribute statement like "node [shape=circle fontSize=16]".
  19455. * Available keywords are 'node', 'edge', 'graph'.
  19456. * The previous list with default attributes will be replaced
  19457. * @param {Object} graph
  19458. * @returns {String | null} keyword Returns the name of the parsed attribute
  19459. * (node, edge, graph), or null if nothing
  19460. * is parsed.
  19461. */
  19462. function parseAttributeStatement (graph) {
  19463. // attribute statements
  19464. if (token == 'node') {
  19465. getToken();
  19466. // node attributes
  19467. graph.node = parseAttributeList();
  19468. return 'node';
  19469. }
  19470. else if (token == 'edge') {
  19471. getToken();
  19472. // edge attributes
  19473. graph.edge = parseAttributeList();
  19474. return 'edge';
  19475. }
  19476. else if (token == 'graph') {
  19477. getToken();
  19478. // graph attributes
  19479. graph.graph = parseAttributeList();
  19480. return 'graph';
  19481. }
  19482. return null;
  19483. }
  19484. /**
  19485. * parse a node statement
  19486. * @param {Object} graph
  19487. * @param {String | Number} id
  19488. */
  19489. function parseNodeStatement(graph, id) {
  19490. // node statement
  19491. var node = {
  19492. id: id
  19493. };
  19494. var attr = parseAttributeList();
  19495. if (attr) {
  19496. node.attr = attr;
  19497. }
  19498. addNode(graph, node);
  19499. // edge statements
  19500. parseEdge(graph, id);
  19501. }
  19502. /**
  19503. * Parse an edge or a series of edges
  19504. * @param {Object} graph
  19505. * @param {String | Number} from Id of the from node
  19506. */
  19507. function parseEdge(graph, from) {
  19508. while (token == '->' || token == '--') {
  19509. var to;
  19510. var type = token;
  19511. getToken();
  19512. var subgraph = parseSubgraph(graph);
  19513. if (subgraph) {
  19514. to = subgraph;
  19515. }
  19516. else {
  19517. if (tokenType != TOKENTYPE.IDENTIFIER) {
  19518. throw newSyntaxError('Identifier or subgraph expected');
  19519. }
  19520. to = token;
  19521. addNode(graph, {
  19522. id: to
  19523. });
  19524. getToken();
  19525. }
  19526. // parse edge attributes
  19527. var attr = parseAttributeList();
  19528. // create edge
  19529. var edge = createEdge(graph, from, to, type, attr);
  19530. addEdge(graph, edge);
  19531. from = to;
  19532. }
  19533. }
  19534. /**
  19535. * Parse a set with attributes,
  19536. * for example [label="1.000", shape=solid]
  19537. * @return {Object | null} attr
  19538. */
  19539. function parseAttributeList() {
  19540. var attr = null;
  19541. while (token == '[') {
  19542. getToken();
  19543. attr = {};
  19544. while (token !== '' && token != ']') {
  19545. if (tokenType != TOKENTYPE.IDENTIFIER) {
  19546. throw newSyntaxError('Attribute name expected');
  19547. }
  19548. var name = token;
  19549. getToken();
  19550. if (token != '=') {
  19551. throw newSyntaxError('Equal sign = expected');
  19552. }
  19553. getToken();
  19554. if (tokenType != TOKENTYPE.IDENTIFIER) {
  19555. throw newSyntaxError('Attribute value expected');
  19556. }
  19557. var value = token;
  19558. setValue(attr, name, value); // name can be a path
  19559. getToken();
  19560. if (token ==',') {
  19561. getToken();
  19562. }
  19563. }
  19564. if (token != ']') {
  19565. throw newSyntaxError('Bracket ] expected');
  19566. }
  19567. getToken();
  19568. }
  19569. return attr;
  19570. }
  19571. /**
  19572. * Create a syntax error with extra information on current token and index.
  19573. * @param {String} message
  19574. * @returns {SyntaxError} err
  19575. */
  19576. function newSyntaxError(message) {
  19577. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  19578. }
  19579. /**
  19580. * Chop off text after a maximum length
  19581. * @param {String} text
  19582. * @param {Number} maxLength
  19583. * @returns {String}
  19584. */
  19585. function chop (text, maxLength) {
  19586. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  19587. }
  19588. /**
  19589. * Execute a function fn for each pair of elements in two arrays
  19590. * @param {Array | *} array1
  19591. * @param {Array | *} array2
  19592. * @param {function} fn
  19593. */
  19594. function forEach2(array1, array2, fn) {
  19595. if (Array.isArray(array1)) {
  19596. array1.forEach(function (elem1) {
  19597. if (Array.isArray(array2)) {
  19598. array2.forEach(function (elem2) {
  19599. fn(elem1, elem2);
  19600. });
  19601. }
  19602. else {
  19603. fn(elem1, array2);
  19604. }
  19605. });
  19606. }
  19607. else {
  19608. if (Array.isArray(array2)) {
  19609. array2.forEach(function (elem2) {
  19610. fn(array1, elem2);
  19611. });
  19612. }
  19613. else {
  19614. fn(array1, array2);
  19615. }
  19616. }
  19617. }
  19618. /**
  19619. * Convert a string containing a graph in DOT language into a map containing
  19620. * with nodes and edges in the format of graph.
  19621. * @param {String} data Text containing a graph in DOT-notation
  19622. * @return {Object} graphData
  19623. */
  19624. function DOTToGraph (data) {
  19625. // parse the DOT file
  19626. var dotData = parseDOT(data);
  19627. var graphData = {
  19628. nodes: [],
  19629. edges: [],
  19630. options: {}
  19631. };
  19632. // copy the nodes
  19633. if (dotData.nodes) {
  19634. dotData.nodes.forEach(function (dotNode) {
  19635. var graphNode = {
  19636. id: dotNode.id,
  19637. label: String(dotNode.label || dotNode.id)
  19638. };
  19639. merge(graphNode, dotNode.attr);
  19640. if (graphNode.image) {
  19641. graphNode.shape = 'image';
  19642. }
  19643. graphData.nodes.push(graphNode);
  19644. });
  19645. }
  19646. // copy the edges
  19647. if (dotData.edges) {
  19648. /**
  19649. * Convert an edge in DOT format to an edge with VisGraph format
  19650. * @param {Object} dotEdge
  19651. * @returns {Object} graphEdge
  19652. */
  19653. var convertEdge = function (dotEdge) {
  19654. var graphEdge = {
  19655. from: dotEdge.from,
  19656. to: dotEdge.to
  19657. };
  19658. merge(graphEdge, dotEdge.attr);
  19659. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  19660. return graphEdge;
  19661. }
  19662. dotData.edges.forEach(function (dotEdge) {
  19663. var from, to;
  19664. if (dotEdge.from instanceof Object) {
  19665. from = dotEdge.from.nodes;
  19666. }
  19667. else {
  19668. from = {
  19669. id: dotEdge.from
  19670. }
  19671. }
  19672. if (dotEdge.to instanceof Object) {
  19673. to = dotEdge.to.nodes;
  19674. }
  19675. else {
  19676. to = {
  19677. id: dotEdge.to
  19678. }
  19679. }
  19680. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  19681. dotEdge.from.edges.forEach(function (subEdge) {
  19682. var graphEdge = convertEdge(subEdge);
  19683. graphData.edges.push(graphEdge);
  19684. });
  19685. }
  19686. forEach2(from, to, function (from, to) {
  19687. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  19688. var graphEdge = convertEdge(subEdge);
  19689. graphData.edges.push(graphEdge);
  19690. });
  19691. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  19692. dotEdge.to.edges.forEach(function (subEdge) {
  19693. var graphEdge = convertEdge(subEdge);
  19694. graphData.edges.push(graphEdge);
  19695. });
  19696. }
  19697. });
  19698. }
  19699. // copy the options
  19700. if (dotData.attr) {
  19701. graphData.options = dotData.attr;
  19702. }
  19703. return graphData;
  19704. }
  19705. // exports
  19706. exports.parseDOT = parseDOT;
  19707. exports.DOTToGraph = DOTToGraph;
  19708. /***/ },
  19709. /* 43 */
  19710. /***/ function(module, exports, __webpack_require__) {
  19711. function parseGephi(gephiJSON, options) {
  19712. var edges = [];
  19713. var nodes = [];
  19714. this.options = {
  19715. edges: {
  19716. inheritColor: true
  19717. },
  19718. nodes: {
  19719. allowedToMove: false,
  19720. parseColor: false
  19721. }
  19722. };
  19723. if (options !== undefined) {
  19724. this.options.nodes['allowedToMove'] = options.allowedToMove | false;
  19725. this.options.nodes['parseColor'] = options.parseColor | false;
  19726. this.options.edges['inheritColor'] = options.inheritColor | true;
  19727. }
  19728. var gEdges = gephiJSON.edges;
  19729. var gNodes = gephiJSON.nodes;
  19730. for (var i = 0; i < gEdges.length; i++) {
  19731. var edge = {};
  19732. var gEdge = gEdges[i];
  19733. edge['id'] = gEdge.id;
  19734. edge['from'] = gEdge.source;
  19735. edge['to'] = gEdge.target;
  19736. edge['attributes'] = gEdge.attributes;
  19737. // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined;
  19738. // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size;
  19739. edge['color'] = gEdge.color;
  19740. edge['inheritColor'] = edge['color'] !== undefined ? false : this.options.inheritColor;
  19741. edges.push(edge);
  19742. }
  19743. for (var i = 0; i < gNodes.length; i++) {
  19744. var node = {};
  19745. var gNode = gNodes[i];
  19746. node['id'] = gNode.id;
  19747. node['attributes'] = gNode.attributes;
  19748. node['x'] = gNode.x;
  19749. node['y'] = gNode.y;
  19750. node['label'] = gNode.label;
  19751. if (this.options.nodes.parseColor == true) {
  19752. node['color'] = gNode.color;
  19753. }
  19754. else {
  19755. node['color'] = gNode.color !== undefined ? {background:gNode.color, border:gNode.color} : undefined;
  19756. }
  19757. node['radius'] = gNode.size;
  19758. node['allowedToMoveX'] = this.options.nodes.allowedToMove;
  19759. node['allowedToMoveY'] = this.options.nodes.allowedToMove;
  19760. nodes.push(node);
  19761. }
  19762. return {nodes:nodes, edges:edges};
  19763. }
  19764. exports.parseGephi = parseGephi;
  19765. /***/ },
  19766. /* 44 */
  19767. /***/ function(module, exports, __webpack_require__) {
  19768. // first check if moment.js is already loaded in the browser window, if so,
  19769. // use this instance. Else, load via commonjs.
  19770. module.exports = (typeof window !== 'undefined') && window['moment'] || __webpack_require__(58);
  19771. /***/ },
  19772. /* 45 */
  19773. /***/ function(module, exports, __webpack_require__) {
  19774. // Only load hammer.js when in a browser environment
  19775. // (loading hammer.js in a node.js environment gives errors)
  19776. if (typeof window !== 'undefined') {
  19777. module.exports = window['Hammer'] || __webpack_require__(59);
  19778. }
  19779. else {
  19780. module.exports = function () {
  19781. throw Error('hammer.js is only available in a browser, not in node.js.');
  19782. }
  19783. }
  19784. /***/ },
  19785. /* 46 */
  19786. /***/ function(module, exports, __webpack_require__) {
  19787. var Emitter = __webpack_require__(56);
  19788. var Hammer = __webpack_require__(45);
  19789. var util = __webpack_require__(1);
  19790. var DataSet = __webpack_require__(3);
  19791. var DataView = __webpack_require__(4);
  19792. var Range = __webpack_require__(17);
  19793. var ItemSet = __webpack_require__(32);
  19794. var TimeAxis = __webpack_require__(35);
  19795. var Activator = __webpack_require__(53);
  19796. var DateUtil = __webpack_require__(15);
  19797. var CustomTime = __webpack_require__(27);
  19798. /**
  19799. * Create a timeline visualization
  19800. * @param {HTMLElement} container
  19801. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  19802. * @param {Object} [options] See Core.setOptions for the available options.
  19803. * @constructor
  19804. */
  19805. function Core () {}
  19806. // turn Core into an event emitter
  19807. Emitter(Core.prototype);
  19808. /**
  19809. * Create the main DOM for the Core: a root panel containing left, right,
  19810. * top, bottom, content, and background panel.
  19811. * @param {Element} container The container element where the Core will
  19812. * be attached.
  19813. * @protected
  19814. */
  19815. Core.prototype._create = function (container) {
  19816. this.dom = {};
  19817. this.dom.root = document.createElement('div');
  19818. this.dom.background = document.createElement('div');
  19819. this.dom.backgroundVertical = document.createElement('div');
  19820. this.dom.backgroundHorizontal = document.createElement('div');
  19821. this.dom.centerContainer = document.createElement('div');
  19822. this.dom.leftContainer = document.createElement('div');
  19823. this.dom.rightContainer = document.createElement('div');
  19824. this.dom.center = document.createElement('div');
  19825. this.dom.left = document.createElement('div');
  19826. this.dom.right = document.createElement('div');
  19827. this.dom.top = document.createElement('div');
  19828. this.dom.bottom = document.createElement('div');
  19829. this.dom.shadowTop = document.createElement('div');
  19830. this.dom.shadowBottom = document.createElement('div');
  19831. this.dom.shadowTopLeft = document.createElement('div');
  19832. this.dom.shadowBottomLeft = document.createElement('div');
  19833. this.dom.shadowTopRight = document.createElement('div');
  19834. this.dom.shadowBottomRight = document.createElement('div');
  19835. this.dom.root.className = 'vis timeline root';
  19836. this.dom.background.className = 'vispanel background';
  19837. this.dom.backgroundVertical.className = 'vispanel background vertical';
  19838. this.dom.backgroundHorizontal.className = 'vispanel background horizontal';
  19839. this.dom.centerContainer.className = 'vispanel center';
  19840. this.dom.leftContainer.className = 'vispanel left';
  19841. this.dom.rightContainer.className = 'vispanel right';
  19842. this.dom.top.className = 'vispanel top';
  19843. this.dom.bottom.className = 'vispanel bottom';
  19844. this.dom.left.className = 'content';
  19845. this.dom.center.className = 'content';
  19846. this.dom.right.className = 'content';
  19847. this.dom.shadowTop.className = 'shadow top';
  19848. this.dom.shadowBottom.className = 'shadow bottom';
  19849. this.dom.shadowTopLeft.className = 'shadow top';
  19850. this.dom.shadowBottomLeft.className = 'shadow bottom';
  19851. this.dom.shadowTopRight.className = 'shadow top';
  19852. this.dom.shadowBottomRight.className = 'shadow bottom';
  19853. this.dom.root.appendChild(this.dom.background);
  19854. this.dom.root.appendChild(this.dom.backgroundVertical);
  19855. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  19856. this.dom.root.appendChild(this.dom.centerContainer);
  19857. this.dom.root.appendChild(this.dom.leftContainer);
  19858. this.dom.root.appendChild(this.dom.rightContainer);
  19859. this.dom.root.appendChild(this.dom.top);
  19860. this.dom.root.appendChild(this.dom.bottom);
  19861. this.dom.centerContainer.appendChild(this.dom.center);
  19862. this.dom.leftContainer.appendChild(this.dom.left);
  19863. this.dom.rightContainer.appendChild(this.dom.right);
  19864. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  19865. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  19866. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  19867. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  19868. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  19869. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  19870. this.on('rangechange', this._redraw.bind(this));
  19871. this.on('touch', this._onTouch.bind(this));
  19872. this.on('pinch', this._onPinch.bind(this));
  19873. this.on('dragstart', this._onDragStart.bind(this));
  19874. this.on('drag', this._onDrag.bind(this));
  19875. var me = this;
  19876. this.on('change', function (properties) {
  19877. if (properties && properties.queue == true) {
  19878. // redraw once on next tick
  19879. if (!me._redrawTimer) {
  19880. me._redrawTimer = setTimeout(function () {
  19881. me._redrawTimer = null;
  19882. me._redraw();
  19883. }, 0)
  19884. }
  19885. }
  19886. else {
  19887. // redraw immediately
  19888. me._redraw();
  19889. }
  19890. });
  19891. // create event listeners for all interesting events, these events will be
  19892. // emitted via emitter
  19893. this.hammer = Hammer(this.dom.root, {
  19894. preventDefault: true
  19895. });
  19896. this.listeners = {};
  19897. var events = [
  19898. 'touch', 'pinch',
  19899. 'tap', 'doubletap', 'hold',
  19900. 'dragstart', 'drag', 'dragend',
  19901. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  19902. ];
  19903. events.forEach(function (event) {
  19904. var listener = function () {
  19905. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  19906. if (me.isActive()) {
  19907. me.emit.apply(me, args);
  19908. }
  19909. };
  19910. me.hammer.on(event, listener);
  19911. me.listeners[event] = listener;
  19912. });
  19913. // size properties of each of the panels
  19914. this.props = {
  19915. root: {},
  19916. background: {},
  19917. centerContainer: {},
  19918. leftContainer: {},
  19919. rightContainer: {},
  19920. center: {},
  19921. left: {},
  19922. right: {},
  19923. top: {},
  19924. bottom: {},
  19925. border: {},
  19926. scrollTop: 0,
  19927. scrollTopMin: 0
  19928. };
  19929. this.touch = {}; // store state information needed for touch events
  19930. this.redrawCount = 0;
  19931. // attach the root panel to the provided container
  19932. if (!container) throw new Error('No container provided');
  19933. container.appendChild(this.dom.root);
  19934. };
  19935. /**
  19936. * Set options. Options will be passed to all components loaded in the Timeline.
  19937. * @param {Object} [options]
  19938. * {String} orientation
  19939. * Vertical orientation for the Timeline,
  19940. * can be 'bottom' (default) or 'top'.
  19941. * {String | Number} width
  19942. * Width for the timeline, a number in pixels or
  19943. * a css string like '1000px' or '75%'. '100%' by default.
  19944. * {String | Number} height
  19945. * Fixed height for the Timeline, a number in pixels or
  19946. * a css string like '400px' or '75%'. If undefined,
  19947. * The Timeline will automatically size such that
  19948. * its contents fit.
  19949. * {String | Number} minHeight
  19950. * Minimum height for the Timeline, a number in pixels or
  19951. * a css string like '400px' or '75%'.
  19952. * {String | Number} maxHeight
  19953. * Maximum height for the Timeline, a number in pixels or
  19954. * a css string like '400px' or '75%'.
  19955. * {Number | Date | String} start
  19956. * Start date for the visible window
  19957. * {Number | Date | String} end
  19958. * End date for the visible window
  19959. */
  19960. Core.prototype.setOptions = function (options) {
  19961. if (options) {
  19962. // copy the known options
  19963. var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'clickToUse', 'dataAttributes', 'hiddenDates'];
  19964. util.selectiveExtend(fields, this.options, options);
  19965. if ('orientation' in options) {
  19966. if (typeof options.orientation === 'string') {
  19967. this.options.orientation = options.orientation;
  19968. }
  19969. else if (typeof options.orientation === 'object' && 'axis' in options.orientation) {
  19970. this.options.orientation = options.orientation.axis;
  19971. }
  19972. }
  19973. if (this.options.orientation === 'both') {
  19974. if (!this.timeAxis2) {
  19975. var timeAxis2 = this.timeAxis2 = new TimeAxis(this.body);
  19976. timeAxis2.setOptions = function (options) {
  19977. var _options = options ? util.extend({}, options) : {};
  19978. _options.orientation = 'top'; // override the orientation option, always top
  19979. TimeAxis.prototype.setOptions.call(timeAxis2, _options);
  19980. };
  19981. this.components.push(timeAxis2);
  19982. }
  19983. }
  19984. else {
  19985. if (this.timeAxis2) {
  19986. var index = this.components.indexOf(this.timeAxis2);
  19987. if (index !== -1) {
  19988. this.components.splice(index, 1);
  19989. }
  19990. this.timeAxis2.destroy();
  19991. this.timeAxis2 = null;
  19992. }
  19993. }
  19994. if ('hiddenDates' in this.options) {
  19995. DateUtil.convertHiddenOptions(this.body, this.options.hiddenDates);
  19996. }
  19997. if ('clickToUse' in options) {
  19998. if (options.clickToUse) {
  19999. if (!this.activator) {
  20000. this.activator = new Activator(this.dom.root);
  20001. }
  20002. }
  20003. else {
  20004. if (this.activator) {
  20005. this.activator.destroy();
  20006. delete this.activator;
  20007. }
  20008. }
  20009. }
  20010. // enable/disable autoResize
  20011. this._initAutoResize();
  20012. }
  20013. // propagate options to all components
  20014. this.components.forEach(function (component) {
  20015. component.setOptions(options);
  20016. });
  20017. // redraw everything
  20018. this._redraw();
  20019. };
  20020. /**
  20021. * Returns true when the Timeline is active.
  20022. * @returns {boolean}
  20023. */
  20024. Core.prototype.isActive = function () {
  20025. return !this.activator || this.activator.active;
  20026. };
  20027. /**
  20028. * Destroy the Core, clean up all DOM elements and event listeners.
  20029. */
  20030. Core.prototype.destroy = function () {
  20031. // unbind datasets
  20032. this.clear();
  20033. // remove all event listeners
  20034. this.off();
  20035. // stop checking for changed size
  20036. this._stopAutoResize();
  20037. // remove from DOM
  20038. if (this.dom.root.parentNode) {
  20039. this.dom.root.parentNode.removeChild(this.dom.root);
  20040. }
  20041. this.dom = null;
  20042. // remove Activator
  20043. if (this.activator) {
  20044. this.activator.destroy();
  20045. delete this.activator;
  20046. }
  20047. // cleanup hammer touch events
  20048. for (var event in this.listeners) {
  20049. if (this.listeners.hasOwnProperty(event)) {
  20050. delete this.listeners[event];
  20051. }
  20052. }
  20053. this.listeners = null;
  20054. this.hammer = null;
  20055. // give all components the opportunity to cleanup
  20056. this.components.forEach(function (component) {
  20057. component.destroy();
  20058. });
  20059. this.body = null;
  20060. };
  20061. /**
  20062. * Set a custom time bar
  20063. * @param {Date} time
  20064. * @param {int} id
  20065. */
  20066. Core.prototype.setCustomTime = function (time, id) {
  20067. if (!this.customTime) {
  20068. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  20069. }
  20070. var barId = id || 0;
  20071. this.components.forEach(function (element, index, components) {
  20072. if (element instanceof CustomTime && element.options.id === barId) {
  20073. element.setCustomTime(time);
  20074. }
  20075. });
  20076. };
  20077. /**
  20078. * Retrieve the current custom time.
  20079. * @return {Date} customTime
  20080. * @param {int} id
  20081. */
  20082. Core.prototype.getCustomTime = function(id) {
  20083. if (!this.customTime) {
  20084. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  20085. }
  20086. var barId = id || 0,
  20087. customTime = this.customTime.getCustomTime();
  20088. this.components.forEach(function (element, index, components) {
  20089. if (element instanceof CustomTime && element.options.id === barId) {
  20090. customTime = element.getCustomTime();
  20091. }
  20092. });
  20093. return customTime;
  20094. };
  20095. /**
  20096. * Add custom vertical bar
  20097. * @param {Date | String | Number} time A Date, unix timestamp, or
  20098. * ISO date string. Time point where the new bar should be placed
  20099. * @param {Number | String} ID of the new bar
  20100. * @return {Number | String} ID of the new bar
  20101. */
  20102. Core.prototype.addCustomTime = function (time, id) {
  20103. if (!this.currentTime) {
  20104. throw new Error('Option showCurrentTime must be true');
  20105. }
  20106. if (time === undefined) {
  20107. throw new Error('Time parameter for the custom bar must be provided');
  20108. }
  20109. var ts = util.convert(time, 'Date').valueOf(),
  20110. numIds, customTime, customBarId;
  20111. // All bar IDs are kept in 1 array, mixed types
  20112. // Bar with ID 0 is the default bar.
  20113. if (!this.customBarIds || this.customBarIds.constructor !== Array) {
  20114. this.customBarIds = [0];
  20115. }
  20116. // If the ID is not provided, generate one, otherwise just use it
  20117. if (id === undefined) {
  20118. numIds = this.customBarIds.filter(function (element) {
  20119. return util.isNumber(element);
  20120. });
  20121. customBarId = numIds.length > 0 ? Math.max.apply(null, numIds) + 1 : 1;
  20122. } else {
  20123. // Check for duplicates
  20124. this.customBarIds.forEach(function (element) {
  20125. if (element === id) {
  20126. throw new Error('Custom time ID already exists');
  20127. }
  20128. });
  20129. customBarId = id;
  20130. }
  20131. this.customBarIds.push(customBarId);
  20132. customTime = new CustomTime(this.body, {
  20133. showCustomTime : true,
  20134. time : ts,
  20135. id : customBarId
  20136. });
  20137. this.components.push(customTime);
  20138. this.redraw();
  20139. return customBarId;
  20140. };
  20141. /**
  20142. * Remove previously added custom bar
  20143. * @param {int} id ID of the custom bar to be removed
  20144. * @return {boolean} True if the bar exists and is removed, false otherwise
  20145. */
  20146. Core.prototype.removeCustomTime = function (id) {
  20147. var me = this;
  20148. this.components.forEach(function (bar, index, components) {
  20149. if (bar instanceof CustomTime && bar.options.id === id) {
  20150. // Only the lines added by the user will be removed
  20151. if (bar.options.id !== 0) {
  20152. me.customBarIds.splice(me.customBarIds.indexOf(id), 1);
  20153. components.splice(index, 1);
  20154. bar.destroy();
  20155. }
  20156. }
  20157. });
  20158. };
  20159. /**
  20160. * Get the id's of the currently visible items.
  20161. * @returns {Array} The ids of the visible items
  20162. */
  20163. Core.prototype.getVisibleItems = function() {
  20164. return this.itemSet && this.itemSet.getVisibleItems() || [];
  20165. };
  20166. /**
  20167. * Clear the Core. By Default, items, groups and options are cleared.
  20168. * Example usage:
  20169. *
  20170. * timeline.clear(); // clear items, groups, and options
  20171. * timeline.clear({options: true}); // clear options only
  20172. *
  20173. * @param {Object} [what] Optionally specify what to clear. By default:
  20174. * {items: true, groups: true, options: true}
  20175. */
  20176. Core.prototype.clear = function(what) {
  20177. // clear items
  20178. if (!what || what.items) {
  20179. this.setItems(null);
  20180. }
  20181. // clear groups
  20182. if (!what || what.groups) {
  20183. this.setGroups(null);
  20184. }
  20185. // clear options of timeline and of each of the components
  20186. if (!what || what.options) {
  20187. this.components.forEach(function (component) {
  20188. component.setOptions(component.defaultOptions);
  20189. });
  20190. this.setOptions(this.defaultOptions); // this will also do a redraw
  20191. }
  20192. };
  20193. /**
  20194. * Set Core window such that it fits all items
  20195. * @param {Object} [options] Available options:
  20196. * `animate: boolean | number`
  20197. * If true (default), the range is animated
  20198. * smoothly to the new window.
  20199. * If a number, the number is taken as duration
  20200. * for the animation. Default duration is 500 ms.
  20201. */
  20202. Core.prototype.fit = function(options) {
  20203. var range = this._getDataRange();
  20204. // skip range set if there is no start and end date
  20205. if (range.start === null && range.end === null) {
  20206. return;
  20207. }
  20208. var animate = (options && options.animate !== undefined) ? options.animate : true;
  20209. this.range.setRange(range.start, range.end, animate);
  20210. };
  20211. /**
  20212. * Calculate the data range of the items and applies a 5% window around it.
  20213. * @returns {{start: Date | null, end: Date | null}}
  20214. * @protected
  20215. */
  20216. Core.prototype._getDataRange = function() {
  20217. // apply the data range as range
  20218. var dataRange = this.getItemRange();
  20219. // add 5% space on both sides
  20220. var start = dataRange.min;
  20221. var end = dataRange.max;
  20222. if (start != null && end != null) {
  20223. var interval = (end.valueOf() - start.valueOf());
  20224. if (interval <= 0) {
  20225. // prevent an empty interval
  20226. interval = 24 * 60 * 60 * 1000; // 1 day
  20227. }
  20228. start = new Date(start.valueOf() - interval * 0.05);
  20229. end = new Date(end.valueOf() + interval * 0.05);
  20230. }
  20231. return {
  20232. start: start,
  20233. end: end
  20234. }
  20235. };
  20236. /**
  20237. * Set the visible window. Both parameters are optional, you can change only
  20238. * start or only end. Syntax:
  20239. *
  20240. * TimeLine.setWindow(start, end)
  20241. * TimeLine.setWindow(start, end, options)
  20242. * TimeLine.setWindow(range)
  20243. *
  20244. * Where start and end can be a Date, number, or string, and range is an
  20245. * object with properties start and end.
  20246. *
  20247. * @param {Date | Number | String | Object} [start] Start date of visible window
  20248. * @param {Date | Number | String} [end] End date of visible window
  20249. * @param {Object} [options] Available options:
  20250. * `animate: boolean | number`
  20251. * If true (default), the range is animated
  20252. * smoothly to the new window.
  20253. * If a number, the number is taken as duration
  20254. * for the animation. Default duration is 500 ms.
  20255. */
  20256. Core.prototype.setWindow = function(start, end, options) {
  20257. var animate;
  20258. if (arguments.length == 1) {
  20259. var range = arguments[0];
  20260. animate = (range.animate !== undefined) ? range.animate : true;
  20261. this.range.setRange(range.start, range.end, animate);
  20262. }
  20263. else {
  20264. animate = (options && options.animate !== undefined) ? options.animate : true;
  20265. this.range.setRange(start, end, animate);
  20266. }
  20267. };
  20268. /**
  20269. * Move the window such that given time is centered on screen.
  20270. * @param {Date | Number | String} time
  20271. * @param {Object} [options] Available options:
  20272. * `animate: boolean | number`
  20273. * If true (default), the range is animated
  20274. * smoothly to the new window.
  20275. * If a number, the number is taken as duration
  20276. * for the animation. Default duration is 500 ms.
  20277. */
  20278. Core.prototype.moveTo = function(time, options) {
  20279. var interval = this.range.end - this.range.start;
  20280. var t = util.convert(time, 'Date').valueOf();
  20281. var start = t - interval / 2;
  20282. var end = t + interval / 2;
  20283. var animate = (options && options.animate !== undefined) ? options.animate : true;
  20284. this.range.setRange(start, end, animate);
  20285. };
  20286. /**
  20287. * Get the visible window
  20288. * @return {{start: Date, end: Date}} Visible range
  20289. */
  20290. Core.prototype.getWindow = function() {
  20291. var range = this.range.getRange();
  20292. return {
  20293. start: new Date(range.start),
  20294. end: new Date(range.end)
  20295. };
  20296. };
  20297. /**
  20298. * Force a redraw. Can be overridden by implementations of Core
  20299. */
  20300. Core.prototype.redraw = function() {
  20301. this._redraw();
  20302. };
  20303. /**
  20304. * Redraw for internal use. Redraws all components. See also the public
  20305. * method redraw.
  20306. * @protected
  20307. */
  20308. Core.prototype._redraw = function() {
  20309. var resized = false;
  20310. var options = this.options;
  20311. var props = this.props;
  20312. var dom = this.dom;
  20313. if (!dom) return; // when destroyed
  20314. DateUtil.updateHiddenDates(this.body, this.options.hiddenDates);
  20315. // update class names
  20316. if (options.orientation == 'top') {
  20317. util.addClassName(dom.root, 'top');
  20318. util.removeClassName(dom.root, 'bottom');
  20319. }
  20320. else {
  20321. util.removeClassName(dom.root, 'top');
  20322. util.addClassName(dom.root, 'bottom');
  20323. }
  20324. // update root width and height options
  20325. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  20326. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  20327. dom.root.style.width = util.option.asSize(options.width, '');
  20328. // calculate border widths
  20329. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  20330. props.border.right = props.border.left;
  20331. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  20332. props.border.bottom = props.border.top;
  20333. var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  20334. var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  20335. // workaround for a bug in IE: the clientWidth of an element with
  20336. // a height:0px and overflow:hidden is not calculated and always has value 0
  20337. if (dom.centerContainer.clientHeight === 0) {
  20338. props.border.left = props.border.top;
  20339. props.border.right = props.border.left;
  20340. }
  20341. if (dom.root.clientHeight === 0) {
  20342. borderRootWidth = borderRootHeight;
  20343. }
  20344. // calculate the heights. If any of the side panels is empty, we set the height to
  20345. // minus the border width, such that the border will be invisible
  20346. props.center.height = dom.center.offsetHeight;
  20347. props.left.height = dom.left.offsetHeight;
  20348. props.right.height = dom.right.offsetHeight;
  20349. props.top.height = dom.top.clientHeight || -props.border.top;
  20350. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  20351. // TODO: compensate borders when any of the panels is empty.
  20352. // apply auto height
  20353. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  20354. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  20355. var autoHeight = props.top.height + contentHeight + props.bottom.height +
  20356. borderRootHeight + props.border.top + props.border.bottom;
  20357. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  20358. // calculate heights of the content panels
  20359. props.root.height = dom.root.offsetHeight;
  20360. props.background.height = props.root.height - borderRootHeight;
  20361. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  20362. borderRootHeight;
  20363. props.centerContainer.height = containerHeight;
  20364. props.leftContainer.height = containerHeight;
  20365. props.rightContainer.height = props.leftContainer.height;
  20366. // calculate the widths of the panels
  20367. props.root.width = dom.root.offsetWidth;
  20368. props.background.width = props.root.width - borderRootWidth;
  20369. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  20370. props.leftContainer.width = props.left.width;
  20371. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  20372. props.rightContainer.width = props.right.width;
  20373. var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth;
  20374. props.center.width = centerWidth;
  20375. props.centerContainer.width = centerWidth;
  20376. props.top.width = centerWidth;
  20377. props.bottom.width = centerWidth;
  20378. // resize the panels
  20379. dom.background.style.height = props.background.height + 'px';
  20380. dom.backgroundVertical.style.height = props.background.height + 'px';
  20381. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  20382. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  20383. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  20384. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  20385. dom.background.style.width = props.background.width + 'px';
  20386. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  20387. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  20388. dom.centerContainer.style.width = props.center.width + 'px';
  20389. dom.top.style.width = props.top.width + 'px';
  20390. dom.bottom.style.width = props.bottom.width + 'px';
  20391. // reposition the panels
  20392. dom.background.style.left = '0';
  20393. dom.background.style.top = '0';
  20394. dom.backgroundVertical.style.left = (props.left.width + props.border.left) + 'px';
  20395. dom.backgroundVertical.style.top = '0';
  20396. dom.backgroundHorizontal.style.left = '0';
  20397. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  20398. dom.centerContainer.style.left = props.left.width + 'px';
  20399. dom.centerContainer.style.top = props.top.height + 'px';
  20400. dom.leftContainer.style.left = '0';
  20401. dom.leftContainer.style.top = props.top.height + 'px';
  20402. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  20403. dom.rightContainer.style.top = props.top.height + 'px';
  20404. dom.top.style.left = props.left.width + 'px';
  20405. dom.top.style.top = '0';
  20406. dom.bottom.style.left = props.left.width + 'px';
  20407. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  20408. // update the scrollTop, feasible range for the offset can be changed
  20409. // when the height of the Core or of the contents of the center changed
  20410. this._updateScrollTop();
  20411. // reposition the scrollable contents
  20412. var offset = this.props.scrollTop;
  20413. if (options.orientation == 'bottom') {
  20414. offset += Math.max(this.props.centerContainer.height - this.props.center.height -
  20415. this.props.border.top - this.props.border.bottom, 0);
  20416. }
  20417. dom.center.style.left = '0';
  20418. dom.center.style.top = offset + 'px';
  20419. dom.left.style.left = '0';
  20420. dom.left.style.top = offset + 'px';
  20421. dom.right.style.left = '0';
  20422. dom.right.style.top = offset + 'px';
  20423. // show shadows when vertical scrolling is available
  20424. var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : '';
  20425. var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : '';
  20426. dom.shadowTop.style.visibility = visibilityTop;
  20427. dom.shadowBottom.style.visibility = visibilityBottom;
  20428. dom.shadowTopLeft.style.visibility = visibilityTop;
  20429. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  20430. dom.shadowTopRight.style.visibility = visibilityTop;
  20431. dom.shadowBottomRight.style.visibility = visibilityBottom;
  20432. // redraw all components
  20433. this.components.forEach(function (component) {
  20434. resized = component.redraw() || resized;
  20435. });
  20436. if (resized) {
  20437. // keep repainting until all sizes are settled
  20438. var MAX_REDRAWS = 3; // maximum number of consecutive redraws
  20439. if (this.redrawCount < MAX_REDRAWS) {
  20440. this.redrawCount++;
  20441. this._redraw();
  20442. }
  20443. else {
  20444. console.log('WARNING: infinite loop in redraw?');
  20445. }
  20446. this.redrawCount = 0;
  20447. }
  20448. this.emit("finishedRedraw");
  20449. };
  20450. // TODO: deprecated since version 1.1.0, remove some day
  20451. Core.prototype.repaint = function () {
  20452. throw new Error('Function repaint is deprecated. Use redraw instead.');
  20453. };
  20454. /**
  20455. * Set a current time. This can be used for example to ensure that a client's
  20456. * time is synchronized with a shared server time.
  20457. * Only applicable when option `showCurrentTime` is true.
  20458. * @param {Date | String | Number} time A Date, unix timestamp, or
  20459. * ISO date string.
  20460. */
  20461. Core.prototype.setCurrentTime = function(time) {
  20462. if (!this.currentTime) {
  20463. throw new Error('Option showCurrentTime must be true');
  20464. }
  20465. this.currentTime.setCurrentTime(time);
  20466. };
  20467. /**
  20468. * Get the current time.
  20469. * Only applicable when option `showCurrentTime` is true.
  20470. * @return {Date} Returns the current time.
  20471. */
  20472. Core.prototype.getCurrentTime = function() {
  20473. if (!this.currentTime) {
  20474. throw new Error('Option showCurrentTime must be true');
  20475. }
  20476. return this.currentTime.getCurrentTime();
  20477. };
  20478. /**
  20479. * Convert a position on screen (pixels) to a datetime
  20480. * @param {int} x Position on the screen in pixels
  20481. * @return {Date} time The datetime the corresponds with given position x
  20482. * @protected
  20483. */
  20484. // TODO: move this function to Range
  20485. Core.prototype._toTime = function(x) {
  20486. return DateUtil.toTime(this, x, this.props.center.width);
  20487. };
  20488. /**
  20489. * Convert a position on the global screen (pixels) to a datetime
  20490. * @param {int} x Position on the screen in pixels
  20491. * @return {Date} time The datetime the corresponds with given position x
  20492. * @protected
  20493. */
  20494. // TODO: move this function to Range
  20495. Core.prototype._toGlobalTime = function(x) {
  20496. return DateUtil.toTime(this, x, this.props.root.width);
  20497. //var conversion = this.range.conversion(this.props.root.width);
  20498. //return new Date(x / conversion.scale + conversion.offset);
  20499. };
  20500. /**
  20501. * Convert a datetime (Date object) into a position on the screen
  20502. * @param {Date} time A date
  20503. * @return {int} x The position on the screen in pixels which corresponds
  20504. * with the given date.
  20505. * @protected
  20506. */
  20507. // TODO: move this function to Range
  20508. Core.prototype._toScreen = function(time) {
  20509. return DateUtil.toScreen(this, time, this.props.center.width);
  20510. };
  20511. /**
  20512. * Convert a datetime (Date object) into a position on the root
  20513. * This is used to get the pixel density estimate for the screen, not the center panel
  20514. * @param {Date} time A date
  20515. * @return {int} x The position on root in pixels which corresponds
  20516. * with the given date.
  20517. * @protected
  20518. */
  20519. // TODO: move this function to Range
  20520. Core.prototype._toGlobalScreen = function(time) {
  20521. return DateUtil.toScreen(this, time, this.props.root.width);
  20522. //var conversion = this.range.conversion(this.props.root.width);
  20523. //return (time.valueOf() - conversion.offset) * conversion.scale;
  20524. };
  20525. /**
  20526. * Initialize watching when option autoResize is true
  20527. * @private
  20528. */
  20529. Core.prototype._initAutoResize = function () {
  20530. if (this.options.autoResize == true) {
  20531. this._startAutoResize();
  20532. }
  20533. else {
  20534. this._stopAutoResize();
  20535. }
  20536. };
  20537. /**
  20538. * Watch for changes in the size of the container. On resize, the Panel will
  20539. * automatically redraw itself.
  20540. * @private
  20541. */
  20542. Core.prototype._startAutoResize = function () {
  20543. var me = this;
  20544. this._stopAutoResize();
  20545. this._onResize = function() {
  20546. if (me.options.autoResize != true) {
  20547. // stop watching when the option autoResize is changed to false
  20548. me._stopAutoResize();
  20549. return;
  20550. }
  20551. if (me.dom.root) {
  20552. // check whether the frame is resized
  20553. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  20554. // IE does not restore the clientWidth from 0 to the actual width after
  20555. // changing the timeline's container display style from none to visible
  20556. if ((me.dom.root.offsetWidth != me.props.lastWidth) ||
  20557. (me.dom.root.offsetHeight != me.props.lastHeight)) {
  20558. me.props.lastWidth = me.dom.root.offsetWidth;
  20559. me.props.lastHeight = me.dom.root.offsetHeight;
  20560. me.emit('change');
  20561. }
  20562. }
  20563. };
  20564. // add event listener to window resize
  20565. util.addEventListener(window, 'resize', this._onResize);
  20566. this.watchTimer = setInterval(this._onResize, 1000);
  20567. };
  20568. /**
  20569. * Stop watching for a resize of the frame.
  20570. * @private
  20571. */
  20572. Core.prototype._stopAutoResize = function () {
  20573. if (this.watchTimer) {
  20574. clearInterval(this.watchTimer);
  20575. this.watchTimer = undefined;
  20576. }
  20577. // remove event listener on window.resize
  20578. util.removeEventListener(window, 'resize', this._onResize);
  20579. this._onResize = null;
  20580. };
  20581. /**
  20582. * Start moving the timeline vertically
  20583. * @param {Event} event
  20584. * @private
  20585. */
  20586. Core.prototype._onTouch = function (event) {
  20587. this.touch.allowDragging = true;
  20588. };
  20589. /**
  20590. * Start moving the timeline vertically
  20591. * @param {Event} event
  20592. * @private
  20593. */
  20594. Core.prototype._onPinch = function (event) {
  20595. this.touch.allowDragging = false;
  20596. };
  20597. /**
  20598. * Start moving the timeline vertically
  20599. * @param {Event} event
  20600. * @private
  20601. */
  20602. Core.prototype._onDragStart = function (event) {
  20603. this.touch.initialScrollTop = this.props.scrollTop;
  20604. };
  20605. /**
  20606. * Move the timeline vertically
  20607. * @param {Event} event
  20608. * @private
  20609. */
  20610. Core.prototype._onDrag = function (event) {
  20611. // refuse to drag when we where pinching to prevent the timeline make a jump
  20612. // when releasing the fingers in opposite order from the touch screen
  20613. if (!this.touch.allowDragging) return;
  20614. var delta = event.gesture.deltaY;
  20615. var oldScrollTop = this._getScrollTop();
  20616. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  20617. if (newScrollTop != oldScrollTop) {
  20618. this._redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already
  20619. this.emit("verticalDrag");
  20620. }
  20621. };
  20622. /**
  20623. * Apply a scrollTop
  20624. * @param {Number} scrollTop
  20625. * @returns {Number} scrollTop Returns the applied scrollTop
  20626. * @private
  20627. */
  20628. Core.prototype._setScrollTop = function (scrollTop) {
  20629. this.props.scrollTop = scrollTop;
  20630. this._updateScrollTop();
  20631. return this.props.scrollTop;
  20632. };
  20633. /**
  20634. * Update the current scrollTop when the height of the containers has been changed
  20635. * @returns {Number} scrollTop Returns the applied scrollTop
  20636. * @private
  20637. */
  20638. Core.prototype._updateScrollTop = function () {
  20639. // recalculate the scrollTopMin
  20640. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  20641. if (scrollTopMin != this.props.scrollTopMin) {
  20642. // in case of bottom orientation, change the scrollTop such that the contents
  20643. // do not move relative to the time axis at the bottom
  20644. if (this.options.orientation == 'bottom') {
  20645. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  20646. }
  20647. this.props.scrollTopMin = scrollTopMin;
  20648. }
  20649. // limit the scrollTop to the feasible scroll range
  20650. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  20651. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  20652. return this.props.scrollTop;
  20653. };
  20654. /**
  20655. * Get the current scrollTop
  20656. * @returns {number} scrollTop
  20657. * @private
  20658. */
  20659. Core.prototype._getScrollTop = function () {
  20660. return this.props.scrollTop;
  20661. };
  20662. module.exports = Core;
  20663. /***/ },
  20664. /* 47 */
  20665. /***/ function(module, exports, __webpack_require__) {
  20666. var Hammer = __webpack_require__(45);
  20667. /**
  20668. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  20669. * @param {Element} element
  20670. * @param {Event} event
  20671. */
  20672. exports.fakeGesture = function(element, event) {
  20673. var eventType = null;
  20674. // for hammer.js 1.0.5
  20675. // var gesture = Hammer.event.collectEventData(this, eventType, event);
  20676. // for hammer.js 1.0.6+
  20677. var touches = Hammer.event.getTouchList(event, eventType);
  20678. var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  20679. // on IE in standards mode, no touches are recognized by hammer.js,
  20680. // resulting in NaN values for center.pageX and center.pageY
  20681. if (isNaN(gesture.center.pageX)) {
  20682. gesture.center.pageX = event.pageX;
  20683. }
  20684. if (isNaN(gesture.center.pageY)) {
  20685. gesture.center.pageY = event.pageY;
  20686. }
  20687. return gesture;
  20688. };
  20689. /***/ },
  20690. /* 48 */
  20691. /***/ function(module, exports, __webpack_require__) {
  20692. // English
  20693. exports['en'] = {
  20694. current: 'current',
  20695. time: 'time'
  20696. };
  20697. exports['en_EN'] = exports['en'];
  20698. exports['en_US'] = exports['en'];
  20699. // Dutch
  20700. exports['nl'] = {
  20701. current: 'aangepaste',
  20702. time: 'tijd'
  20703. };
  20704. exports['nl_NL'] = exports['nl'];
  20705. exports['nl_BE'] = exports['nl'];
  20706. /***/ },
  20707. /* 49 */
  20708. /***/ function(module, exports, __webpack_require__) {
  20709. /**
  20710. * Created by Alex on 11/11/2014.
  20711. */
  20712. var DOMutil = __webpack_require__(2);
  20713. var Points = __webpack_require__(51);
  20714. function Line(groupId, options) {
  20715. this.groupId = groupId;
  20716. this.options = options;
  20717. }
  20718. Line.prototype.getYRange = function(groupData) {
  20719. var yMin = groupData[0].y;
  20720. var yMax = groupData[0].y;
  20721. for (var j = 0; j < groupData.length; j++) {
  20722. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  20723. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  20724. }
  20725. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  20726. };
  20727. /**
  20728. * draw a line graph
  20729. *
  20730. * @param dataset
  20731. * @param group
  20732. */
  20733. Line.prototype.draw = function (dataset, group, framework) {
  20734. if (dataset != null) {
  20735. if (dataset.length > 0) {
  20736. var path, d;
  20737. var svgHeight = Number(framework.svg.style.height.replace('px',''));
  20738. path = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  20739. path.setAttributeNS(null, "class", group.className);
  20740. if(group.style !== undefined) {
  20741. path.setAttributeNS(null, "style", group.style);
  20742. }
  20743. // construct path from dataset
  20744. if (group.options.catmullRom.enabled == true) {
  20745. d = Line._catmullRom(dataset, group);
  20746. }
  20747. else {
  20748. d = Line._linear(dataset);
  20749. }
  20750. // append with points for fill and finalize the path
  20751. if (group.options.shaded.enabled == true) {
  20752. var fillPath = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  20753. var dFill;
  20754. if (group.options.shaded.orientation == 'top') {
  20755. dFill = 'M' + dataset[0].x + ',' + 0 + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + 0;
  20756. }
  20757. else {
  20758. dFill = 'M' + dataset[0].x + ',' + svgHeight + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + svgHeight;
  20759. }
  20760. fillPath.setAttributeNS(null, "class", group.className + " fill");
  20761. if(group.options.shaded.style !== undefined) {
  20762. fillPath.setAttributeNS(null, "style", group.options.shaded.style);
  20763. }
  20764. fillPath.setAttributeNS(null, "d", dFill);
  20765. }
  20766. // copy properties to path for drawing.
  20767. path.setAttributeNS(null, 'd', 'M' + d);
  20768. // draw points
  20769. if (group.options.drawPoints.enabled == true) {
  20770. Points.draw(dataset, group, framework);
  20771. }
  20772. }
  20773. }
  20774. };
  20775. /**
  20776. * This uses an uniform parametrization of the CatmullRom algorithm:
  20777. * 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al.
  20778. * @param data
  20779. * @returns {string}
  20780. * @private
  20781. */
  20782. Line._catmullRomUniform = function(data) {
  20783. // catmull rom
  20784. var p0, p1, p2, p3, bp1, bp2;
  20785. var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' ';
  20786. var normalization = 1/6;
  20787. var length = data.length;
  20788. for (var i = 0; i < length - 1; i++) {
  20789. p0 = (i == 0) ? data[0] : data[i-1];
  20790. p1 = data[i];
  20791. p2 = data[i+1];
  20792. p3 = (i + 2 < length) ? data[i+2] : p2;
  20793. // Catmull-Rom to Cubic Bezier conversion matrix
  20794. // 0 1 0 0
  20795. // -1/6 1 1/6 0
  20796. // 0 1/6 1 -1/6
  20797. // 0 0 1 0
  20798. // bp0 = { x: p1.x, y: p1.y };
  20799. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)};
  20800. bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)};
  20801. // bp0 = { x: p2.x, y: p2.y };
  20802. d += 'C' +
  20803. bp1.x + ',' +
  20804. bp1.y + ' ' +
  20805. bp2.x + ',' +
  20806. bp2.y + ' ' +
  20807. p2.x + ',' +
  20808. p2.y + ' ';
  20809. }
  20810. return d;
  20811. };
  20812. /**
  20813. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  20814. * By default, the centripetal parameterization is used because this gives the nicest results.
  20815. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  20816. *
  20817. * One optimization can be used to reuse distances since this is a sliding window approach.
  20818. * @param data
  20819. * @param group
  20820. * @returns {string}
  20821. * @private
  20822. */
  20823. Line._catmullRom = function(data, group) {
  20824. var alpha = group.options.catmullRom.alpha;
  20825. if (alpha == 0 || alpha === undefined) {
  20826. return this._catmullRomUniform(data);
  20827. }
  20828. else {
  20829. var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M;
  20830. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  20831. var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' ';
  20832. var length = data.length;
  20833. for (var i = 0; i < length - 1; i++) {
  20834. p0 = (i == 0) ? data[0] : data[i-1];
  20835. p1 = data[i];
  20836. p2 = data[i+1];
  20837. p3 = (i + 2 < length) ? data[i+2] : p2;
  20838. d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2));
  20839. d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2));
  20840. d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2));
  20841. // Catmull-Rom to Cubic Bezier conversion matrix
  20842. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  20843. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  20844. // [ 0 1 0 0 ]
  20845. // [ -d2^2a /N A/N d1^2a /N 0 ]
  20846. // [ 0 d3^2a /M B/M -d2^2a /M ]
  20847. // [ 0 0 1 0 ]
  20848. d3powA = Math.pow(d3, alpha);
  20849. d3pow2A = Math.pow(d3,2*alpha);
  20850. d2powA = Math.pow(d2, alpha);
  20851. d2pow2A = Math.pow(d2,2*alpha);
  20852. d1powA = Math.pow(d1, alpha);
  20853. d1pow2A = Math.pow(d1,2*alpha);
  20854. A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A;
  20855. B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A;
  20856. N = 3*d1powA * (d1powA + d2powA);
  20857. if (N > 0) {N = 1 / N;}
  20858. M = 3*d3powA * (d3powA + d2powA);
  20859. if (M > 0) {M = 1 / M;}
  20860. bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N),
  20861. y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)};
  20862. bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M),
  20863. y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)};
  20864. if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;}
  20865. if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;}
  20866. d += 'C' +
  20867. bp1.x + ',' +
  20868. bp1.y + ' ' +
  20869. bp2.x + ',' +
  20870. bp2.y + ' ' +
  20871. p2.x + ',' +
  20872. p2.y + ' ';
  20873. }
  20874. return d;
  20875. }
  20876. };
  20877. /**
  20878. * this generates the SVG path for a linear drawing between datapoints.
  20879. * @param data
  20880. * @returns {string}
  20881. * @private
  20882. */
  20883. Line._linear = function(data) {
  20884. // linear
  20885. var d = '';
  20886. for (var i = 0; i < data.length; i++) {
  20887. if (i == 0) {
  20888. d += data[i].x + ',' + data[i].y;
  20889. }
  20890. else {
  20891. d += ' ' + data[i].x + ',' + data[i].y;
  20892. }
  20893. }
  20894. return d;
  20895. };
  20896. module.exports = Line;
  20897. /***/ },
  20898. /* 50 */
  20899. /***/ function(module, exports, __webpack_require__) {
  20900. /**
  20901. * Created by Alex on 11/11/2014.
  20902. */
  20903. var DOMutil = __webpack_require__(2);
  20904. var Points = __webpack_require__(51);
  20905. function Bargraph(groupId, options) {
  20906. this.groupId = groupId;
  20907. this.options = options;
  20908. }
  20909. Bargraph.prototype.getYRange = function(groupData) {
  20910. if (this.options.barChart.handleOverlap != 'stack') {
  20911. var yMin = groupData[0].y;
  20912. var yMax = groupData[0].y;
  20913. for (var j = 0; j < groupData.length; j++) {
  20914. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  20915. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  20916. }
  20917. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  20918. }
  20919. else {
  20920. var barCombinedData = [];
  20921. for (var j = 0; j < groupData.length; j++) {
  20922. barCombinedData.push({
  20923. x: groupData[j].x,
  20924. y: groupData[j].y,
  20925. groupId: this.groupId
  20926. });
  20927. }
  20928. return barCombinedData;
  20929. }
  20930. };
  20931. /**
  20932. * draw a bar graph
  20933. *
  20934. * @param groupIds
  20935. * @param processedGroupData
  20936. */
  20937. Bargraph.draw = function (groupIds, processedGroupData, framework) {
  20938. var combinedData = [];
  20939. var intersections = {};
  20940. var coreDistance;
  20941. var key, drawData;
  20942. var group;
  20943. var i,j;
  20944. var barPoints = 0;
  20945. // combine all barchart data
  20946. for (i = 0; i < groupIds.length; i++) {
  20947. group = framework.groups[groupIds[i]];
  20948. if (group.options.style == 'bar') {
  20949. if (group.visible == true && (framework.options.groups.visibility[groupIds[i]] === undefined || framework.options.groups.visibility[groupIds[i]] == true)) {
  20950. for (j = 0; j < processedGroupData[groupIds[i]].length; j++) {
  20951. combinedData.push({
  20952. x: processedGroupData[groupIds[i]][j].x,
  20953. y: processedGroupData[groupIds[i]][j].y,
  20954. groupId: groupIds[i],
  20955. label: processedGroupData[groupIds[i]][j].label,
  20956. });
  20957. barPoints += 1;
  20958. }
  20959. }
  20960. }
  20961. }
  20962. if (barPoints == 0) {return;}
  20963. // sort by time and by group
  20964. combinedData.sort(function (a, b) {
  20965. if (a.x == b.x) {
  20966. return a.groupId - b.groupId;
  20967. } else {
  20968. return a.x - b.x;
  20969. }
  20970. });
  20971. // get intersections
  20972. Bargraph._getDataIntersections(intersections, combinedData);
  20973. // plot barchart
  20974. for (i = 0; i < combinedData.length; i++) {
  20975. group = framework.groups[combinedData[i].groupId];
  20976. var minWidth = 0.1 * group.options.barChart.width;
  20977. key = combinedData[i].x;
  20978. var heightOffset = 0;
  20979. if (intersections[key] === undefined) {
  20980. if (i+1 < combinedData.length) {coreDistance = Math.abs(combinedData[i+1].x - key);}
  20981. if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[i-1].x - key));}
  20982. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  20983. }
  20984. else {
  20985. var nextKey = i + (intersections[key].amount - intersections[key].resolved);
  20986. var prevKey = i - (intersections[key].resolved + 1);
  20987. if (nextKey < combinedData.length) {coreDistance = Math.abs(combinedData[nextKey].x - key);}
  20988. if (prevKey > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[prevKey].x - key));}
  20989. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  20990. intersections[key].resolved += 1;
  20991. if (group.options.barChart.handleOverlap == 'stack') {
  20992. heightOffset = intersections[key].accumulated;
  20993. intersections[key].accumulated += group.zeroPosition - combinedData[i].y;
  20994. }
  20995. else if (group.options.barChart.handleOverlap == 'sideBySide') {
  20996. drawData.width = drawData.width / intersections[key].amount;
  20997. drawData.offset += (intersections[key].resolved) * drawData.width - (0.5*drawData.width * (intersections[key].amount+1));
  20998. if (group.options.barChart.align == 'left') {drawData.offset -= 0.5*drawData.width;}
  20999. else if (group.options.barChart.align == 'right') {drawData.offset += 0.5*drawData.width;}
  21000. }
  21001. }
  21002. DOMutil.drawBar(combinedData[i].x + drawData.offset, combinedData[i].y - heightOffset, drawData.width, group.zeroPosition - combinedData[i].y, group.className + ' bar', framework.svgElements, framework.svg);
  21003. // draw points
  21004. if (group.options.drawPoints.enabled == true) {
  21005. DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg, combinedData[i].label);
  21006. }
  21007. }
  21008. };
  21009. /**
  21010. * Fill the intersections object with counters of how many datapoints share the same x coordinates
  21011. * @param intersections
  21012. * @param combinedData
  21013. * @private
  21014. */
  21015. Bargraph._getDataIntersections = function (intersections, combinedData) {
  21016. // get intersections
  21017. var coreDistance;
  21018. for (var i = 0; i < combinedData.length; i++) {
  21019. if (i + 1 < combinedData.length) {
  21020. coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x);
  21021. }
  21022. if (i > 0) {
  21023. coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x));
  21024. }
  21025. if (coreDistance == 0) {
  21026. if (intersections[combinedData[i].x] === undefined) {
  21027. intersections[combinedData[i].x] = {amount: 0, resolved: 0, accumulated: 0};
  21028. }
  21029. intersections[combinedData[i].x].amount += 1;
  21030. }
  21031. }
  21032. };
  21033. /**
  21034. * Get the width and offset for bargraphs based on the coredistance between datapoints
  21035. *
  21036. * @param coreDistance
  21037. * @param group
  21038. * @param minWidth
  21039. * @returns {{width: Number, offset: Number}}
  21040. * @private
  21041. */
  21042. Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) {
  21043. var width, offset;
  21044. if (coreDistance < group.options.barChart.width && coreDistance > 0) {
  21045. width = coreDistance < minWidth ? minWidth : coreDistance;
  21046. offset = 0; // recalculate offset with the new width;
  21047. if (group.options.barChart.align == 'left') {
  21048. offset -= 0.5 * coreDistance;
  21049. }
  21050. else if (group.options.barChart.align == 'right') {
  21051. offset += 0.5 * coreDistance;
  21052. }
  21053. }
  21054. else {
  21055. // default settings
  21056. width = group.options.barChart.width;
  21057. offset = 0;
  21058. if (group.options.barChart.align == 'left') {
  21059. offset -= 0.5 * group.options.barChart.width;
  21060. }
  21061. else if (group.options.barChart.align == 'right') {
  21062. offset += 0.5 * group.options.barChart.width;
  21063. }
  21064. }
  21065. return {width: width, offset: offset};
  21066. };
  21067. Bargraph.getStackedBarYRange = function(barCombinedData, groupRanges, groupIds, groupLabel, orientation) {
  21068. if (barCombinedData.length > 0) {
  21069. // sort by time and by group
  21070. barCombinedData.sort(function (a, b) {
  21071. if (a.x == b.x) {
  21072. return a.groupId - b.groupId;
  21073. } else {
  21074. return a.x - b.x;
  21075. }
  21076. });
  21077. var intersections = {};
  21078. Bargraph._getDataIntersections(intersections, barCombinedData);
  21079. groupRanges[groupLabel] = Bargraph._getStackedBarYRange(intersections, barCombinedData);
  21080. groupRanges[groupLabel].yAxisOrientation = orientation;
  21081. groupIds.push(groupLabel);
  21082. }
  21083. }
  21084. Bargraph._getStackedBarYRange = function (intersections, combinedData) {
  21085. var key;
  21086. var yMin = combinedData[0].y;
  21087. var yMax = combinedData[0].y;
  21088. for (var i = 0; i < combinedData.length; i++) {
  21089. key = combinedData[i].x;
  21090. if (intersections[key] === undefined) {
  21091. yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin;
  21092. yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax;
  21093. }
  21094. else {
  21095. intersections[key].accumulated += combinedData[i].y;
  21096. }
  21097. }
  21098. for (var xpos in intersections) {
  21099. if (intersections.hasOwnProperty(xpos)) {
  21100. yMin = yMin > intersections[xpos].accumulated ? intersections[xpos].accumulated : yMin;
  21101. yMax = yMax < intersections[xpos].accumulated ? intersections[xpos].accumulated : yMax;
  21102. }
  21103. }
  21104. return {min: yMin, max: yMax};
  21105. };
  21106. module.exports = Bargraph;
  21107. /***/ },
  21108. /* 51 */
  21109. /***/ function(module, exports, __webpack_require__) {
  21110. /**
  21111. * Created by Alex on 11/11/2014.
  21112. */
  21113. var DOMutil = __webpack_require__(2);
  21114. function Points(groupId, options) {
  21115. this.groupId = groupId;
  21116. this.options = options;
  21117. }
  21118. Points.prototype.getYRange = function(groupData) {
  21119. var yMin = groupData[0].y;
  21120. var yMax = groupData[0].y;
  21121. for (var j = 0; j < groupData.length; j++) {
  21122. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  21123. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  21124. }
  21125. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  21126. };
  21127. Points.prototype.draw = function(dataset, group, framework, offset) {
  21128. Points.draw(dataset, group, framework, offset);
  21129. }
  21130. /**
  21131. * draw the data points
  21132. *
  21133. * @param {Array} dataset
  21134. * @param {Object} JSONcontainer
  21135. * @param {Object} svg | SVG DOM element
  21136. * @param {GraphGroup} group
  21137. * @param {Number} [offset]
  21138. */
  21139. Points.draw = function (dataset, group, framework, offset) {
  21140. if (offset === undefined) {offset = 0;}
  21141. for (var i = 0; i < dataset.length; i++) {
  21142. DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, framework.svgElements, framework.svg, dataset[i].label);
  21143. }
  21144. };
  21145. module.exports = Points;
  21146. /***/ },
  21147. /* 52 */
  21148. /***/ function(module, exports, __webpack_require__) {
  21149. var PhysicsMixin = __webpack_require__(60);
  21150. var ClusterMixin = __webpack_require__(61);
  21151. var SectorsMixin = __webpack_require__(62);
  21152. var SelectionMixin = __webpack_require__(63);
  21153. var ManipulationMixin = __webpack_require__(64);
  21154. var NavigationMixin = __webpack_require__(65);
  21155. var HierarchicalLayoutMixin = __webpack_require__(66);
  21156. /**
  21157. * Load a mixin into the network object
  21158. *
  21159. * @param {Object} sourceVariable | this object has to contain functions.
  21160. * @private
  21161. */
  21162. exports._loadMixin = function (sourceVariable) {
  21163. for (var mixinFunction in sourceVariable) {
  21164. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  21165. this[mixinFunction] = sourceVariable[mixinFunction];
  21166. }
  21167. }
  21168. };
  21169. /**
  21170. * removes a mixin from the network object.
  21171. *
  21172. * @param {Object} sourceVariable | this object has to contain functions.
  21173. * @private
  21174. */
  21175. exports._clearMixin = function (sourceVariable) {
  21176. for (var mixinFunction in sourceVariable) {
  21177. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  21178. this[mixinFunction] = undefined;
  21179. }
  21180. }
  21181. };
  21182. /**
  21183. * Mixin the physics system and initialize the parameters required.
  21184. *
  21185. * @private
  21186. */
  21187. exports._loadPhysicsSystem = function () {
  21188. this._loadMixin(PhysicsMixin);
  21189. this._loadSelectedForceSolver();
  21190. if (this.constants.configurePhysics == true) {
  21191. this._loadPhysicsConfiguration();
  21192. }
  21193. else {
  21194. this._cleanupPhysicsConfiguration();
  21195. }
  21196. };
  21197. /**
  21198. * Mixin the cluster system and initialize the parameters required.
  21199. *
  21200. * @private
  21201. */
  21202. exports._loadClusterSystem = function () {
  21203. this.clusterSession = 0;
  21204. this.hubThreshold = 5;
  21205. this._loadMixin(ClusterMixin);
  21206. };
  21207. /**
  21208. * Mixin the sector system and initialize the parameters required
  21209. *
  21210. * @private
  21211. */
  21212. exports._loadSectorSystem = function () {
  21213. this.sectors = {};
  21214. this.activeSector = ["default"];
  21215. this.sectors["active"] = {};
  21216. this.sectors["active"]["default"] = {"nodes": {},
  21217. "edges": {},
  21218. "nodeIndices": [],
  21219. "formationScale": 1.0,
  21220. "drawingNode": undefined };
  21221. this.sectors["frozen"] = {};
  21222. this.sectors["support"] = {"nodes": {},
  21223. "edges": {},
  21224. "nodeIndices": [],
  21225. "formationScale": 1.0,
  21226. "drawingNode": undefined };
  21227. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  21228. this._loadMixin(SectorsMixin);
  21229. };
  21230. /**
  21231. * Mixin the selection system and initialize the parameters required
  21232. *
  21233. * @private
  21234. */
  21235. exports._loadSelectionSystem = function () {
  21236. this.selectionObj = {nodes: {}, edges: {}};
  21237. this._loadMixin(SelectionMixin);
  21238. };
  21239. /**
  21240. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  21241. *
  21242. * @private
  21243. */
  21244. exports._loadManipulationSystem = function () {
  21245. // reset global variables -- these are used by the selection of nodes and edges.
  21246. this.blockConnectingEdgeSelection = false;
  21247. this.forceAppendSelection = false;
  21248. if (this.constants.dataManipulation.enabled == true) {
  21249. // load the manipulator HTML elements. All styling done in css.
  21250. if (this.manipulationDiv === undefined) {
  21251. this.manipulationDiv = document.createElement('div');
  21252. this.manipulationDiv.className = 'network-manipulationDiv';
  21253. if (this.editMode == true) {
  21254. this.manipulationDiv.style.display = "block";
  21255. }
  21256. else {
  21257. this.manipulationDiv.style.display = "none";
  21258. }
  21259. this.frame.appendChild(this.manipulationDiv);
  21260. }
  21261. if (this.editModeDiv === undefined) {
  21262. this.editModeDiv = document.createElement('div');
  21263. this.editModeDiv.className = 'network-manipulation-editMode';
  21264. if (this.editMode == true) {
  21265. this.editModeDiv.style.display = "none";
  21266. }
  21267. else {
  21268. this.editModeDiv.style.display = "block";
  21269. }
  21270. this.frame.appendChild(this.editModeDiv);
  21271. }
  21272. if (this.closeDiv === undefined) {
  21273. this.closeDiv = document.createElement('div');
  21274. this.closeDiv.className = 'network-manipulation-closeDiv';
  21275. this.closeDiv.style.display = this.manipulationDiv.style.display;
  21276. this.frame.appendChild(this.closeDiv);
  21277. }
  21278. // load the manipulation functions
  21279. this._loadMixin(ManipulationMixin);
  21280. // create the manipulator toolbar
  21281. this._createManipulatorBar();
  21282. }
  21283. else {
  21284. if (this.manipulationDiv !== undefined) {
  21285. // removes all the bindings and overloads
  21286. this._createManipulatorBar();
  21287. // remove the manipulation divs
  21288. this.frame.removeChild(this.manipulationDiv);
  21289. this.frame.removeChild(this.editModeDiv);
  21290. this.frame.removeChild(this.closeDiv);
  21291. this.manipulationDiv = undefined;
  21292. this.editModeDiv = undefined;
  21293. this.closeDiv = undefined;
  21294. // remove the mixin functions
  21295. this._clearMixin(ManipulationMixin);
  21296. }
  21297. }
  21298. };
  21299. /**
  21300. * Mixin the navigation (User Interface) system and initialize the parameters required
  21301. *
  21302. * @private
  21303. */
  21304. exports._loadNavigationControls = function () {
  21305. this._loadMixin(NavigationMixin);
  21306. // the clean function removes the button divs, this is done to remove the bindings.
  21307. this._cleanNavigation();
  21308. if (this.constants.navigation.enabled == true) {
  21309. this._loadNavigationElements();
  21310. }
  21311. };
  21312. /**
  21313. * Mixin the hierarchical layout system.
  21314. *
  21315. * @private
  21316. */
  21317. exports._loadHierarchySystem = function () {
  21318. this._loadMixin(HierarchicalLayoutMixin);
  21319. };
  21320. /***/ },
  21321. /* 53 */
  21322. /***/ function(module, exports, __webpack_require__) {
  21323. var keycharm = __webpack_require__(57);
  21324. var Emitter = __webpack_require__(56);
  21325. var Hammer = __webpack_require__(45);
  21326. var util = __webpack_require__(1);
  21327. /**
  21328. * Turn an element into an clickToUse element.
  21329. * When not active, the element has a transparent overlay. When the overlay is
  21330. * clicked, the mode is changed to active.
  21331. * When active, the element is displayed with a blue border around it, and
  21332. * the interactive contents of the element can be used. When clicked outside
  21333. * the element, the elements mode is changed to inactive.
  21334. * @param {Element} container
  21335. * @constructor
  21336. */
  21337. function Activator(container) {
  21338. this.active = false;
  21339. this.dom = {
  21340. container: container
  21341. };
  21342. this.dom.overlay = document.createElement('div');
  21343. this.dom.overlay.className = 'overlay';
  21344. this.dom.container.appendChild(this.dom.overlay);
  21345. this.hammer = Hammer(this.dom.overlay, {prevent_default: false});
  21346. this.hammer.on('tap', this._onTapOverlay.bind(this));
  21347. // block all touch events (except tap)
  21348. var me = this;
  21349. var events = [
  21350. 'touch', 'pinch',
  21351. 'doubletap', 'hold',
  21352. 'dragstart', 'drag', 'dragend',
  21353. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  21354. ];
  21355. events.forEach(function (event) {
  21356. me.hammer.on(event, function (event) {
  21357. event.stopPropagation();
  21358. });
  21359. });
  21360. // attach a tap event to the window, in order to deactivate when clicking outside the timeline
  21361. this.windowHammer = Hammer(window, {prevent_default: false});
  21362. this.windowHammer.on('tap', function (event) {
  21363. // deactivate when clicked outside the container
  21364. if (!_hasParent(event.target, container)) {
  21365. me.deactivate();
  21366. }
  21367. });
  21368. if (this.keycharm !== undefined) {
  21369. this.keycharm.destroy();
  21370. }
  21371. this.keycharm = keycharm();
  21372. // keycharm listener only bounded when active)
  21373. this.escListener = this.deactivate.bind(this);
  21374. }
  21375. // turn into an event emitter
  21376. Emitter(Activator.prototype);
  21377. // The currently active activator
  21378. Activator.current = null;
  21379. /**
  21380. * Destroy the activator. Cleans up all created DOM and event listeners
  21381. */
  21382. Activator.prototype.destroy = function () {
  21383. this.deactivate();
  21384. // remove dom
  21385. this.dom.overlay.parentNode.removeChild(this.dom.overlay);
  21386. // cleanup hammer instances
  21387. this.hammer = null;
  21388. this.windowHammer = null;
  21389. // FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory)
  21390. };
  21391. /**
  21392. * Activate the element
  21393. * Overlay is hidden, element is decorated with a blue shadow border
  21394. */
  21395. Activator.prototype.activate = function () {
  21396. // we allow only one active activator at a time
  21397. if (Activator.current) {
  21398. Activator.current.deactivate();
  21399. }
  21400. Activator.current = this;
  21401. this.active = true;
  21402. this.dom.overlay.style.display = 'none';
  21403. util.addClassName(this.dom.container, 'vis-active');
  21404. this.emit('change');
  21405. this.emit('activate');
  21406. // ugly hack: bind ESC after emitting the events, as the Network rebinds all
  21407. // keyboard events on a 'change' event
  21408. this.keycharm.bind('esc', this.escListener);
  21409. };
  21410. /**
  21411. * Deactivate the element
  21412. * Overlay is displayed on top of the element
  21413. */
  21414. Activator.prototype.deactivate = function () {
  21415. this.active = false;
  21416. this.dom.overlay.style.display = '';
  21417. util.removeClassName(this.dom.container, 'vis-active');
  21418. this.keycharm.unbind('esc', this.escListener);
  21419. this.emit('change');
  21420. this.emit('deactivate');
  21421. };
  21422. /**
  21423. * Handle a tap event: activate the container
  21424. * @param event
  21425. * @private
  21426. */
  21427. Activator.prototype._onTapOverlay = function (event) {
  21428. // activate the container
  21429. this.activate();
  21430. event.stopPropagation();
  21431. };
  21432. /**
  21433. * Test whether the element has the requested parent element somewhere in
  21434. * its chain of parent nodes.
  21435. * @param {HTMLElement} element
  21436. * @param {HTMLElement} parent
  21437. * @returns {boolean} Returns true when the parent is found somewhere in the
  21438. * chain of parent nodes.
  21439. * @private
  21440. */
  21441. function _hasParent(element, parent) {
  21442. while (element) {
  21443. if (element === parent) {
  21444. return true
  21445. }
  21446. element = element.parentNode;
  21447. }
  21448. return false;
  21449. }
  21450. module.exports = Activator;
  21451. /***/ },
  21452. /* 54 */
  21453. /***/ function(module, exports, __webpack_require__) {
  21454. // English
  21455. exports['en'] = {
  21456. edit: 'Edit',
  21457. del: 'Delete selected',
  21458. back: 'Back',
  21459. addNode: 'Add Node',
  21460. addEdge: 'Add Edge',
  21461. editNode: 'Edit Node',
  21462. editEdge: 'Edit Edge',
  21463. addDescription: 'Click in an empty space to place a new node.',
  21464. edgeDescription: 'Click on a node and drag the edge to another node to connect them.',
  21465. editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.',
  21466. createEdgeError: 'Cannot link edges to a cluster.',
  21467. deleteClusterError: 'Clusters cannot be deleted.'
  21468. };
  21469. exports['en_EN'] = exports['en'];
  21470. exports['en_US'] = exports['en'];
  21471. // Dutch
  21472. exports['nl'] = {
  21473. edit: 'Wijzigen',
  21474. del: 'Selectie verwijderen',
  21475. back: 'Terug',
  21476. addNode: 'Node toevoegen',
  21477. addEdge: 'Link toevoegen',
  21478. editNode: 'Node wijzigen',
  21479. editEdge: 'Link wijzigen',
  21480. addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.',
  21481. edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.',
  21482. editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.',
  21483. createEdgeError: 'Kan geen link maken naar een cluster.',
  21484. deleteClusterError: 'Clusters kunnen niet worden verwijderd.'
  21485. };
  21486. exports['nl_NL'] = exports['nl'];
  21487. exports['nl_BE'] = exports['nl'];
  21488. /***/ },
  21489. /* 55 */
  21490. /***/ function(module, exports, __webpack_require__) {
  21491. /**
  21492. * Canvas shapes used by Network
  21493. */
  21494. if (typeof CanvasRenderingContext2D !== 'undefined') {
  21495. /**
  21496. * Draw a circle shape
  21497. */
  21498. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  21499. this.beginPath();
  21500. this.arc(x, y, r, 0, 2*Math.PI, false);
  21501. };
  21502. /**
  21503. * Draw a square shape
  21504. * @param {Number} x horizontal center
  21505. * @param {Number} y vertical center
  21506. * @param {Number} r size, width and height of the square
  21507. */
  21508. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  21509. this.beginPath();
  21510. this.rect(x - r, y - r, r * 2, r * 2);
  21511. };
  21512. /**
  21513. * Draw a triangle shape
  21514. * @param {Number} x horizontal center
  21515. * @param {Number} y vertical center
  21516. * @param {Number} r radius, half the length of the sides of the triangle
  21517. */
  21518. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  21519. // http://en.wikipedia.org/wiki/Equilateral_triangle
  21520. this.beginPath();
  21521. var s = r * 2;
  21522. var s2 = s / 2;
  21523. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  21524. var h = Math.sqrt(s * s - s2 * s2); // height
  21525. this.moveTo(x, y - (h - ir));
  21526. this.lineTo(x + s2, y + ir);
  21527. this.lineTo(x - s2, y + ir);
  21528. this.lineTo(x, y - (h - ir));
  21529. this.closePath();
  21530. };
  21531. /**
  21532. * Draw a triangle shape in downward orientation
  21533. * @param {Number} x horizontal center
  21534. * @param {Number} y vertical center
  21535. * @param {Number} r radius
  21536. */
  21537. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  21538. // http://en.wikipedia.org/wiki/Equilateral_triangle
  21539. this.beginPath();
  21540. var s = r * 2;
  21541. var s2 = s / 2;
  21542. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  21543. var h = Math.sqrt(s * s - s2 * s2); // height
  21544. this.moveTo(x, y + (h - ir));
  21545. this.lineTo(x + s2, y - ir);
  21546. this.lineTo(x - s2, y - ir);
  21547. this.lineTo(x, y + (h - ir));
  21548. this.closePath();
  21549. };
  21550. /**
  21551. * Draw a star shape, a star with 5 points
  21552. * @param {Number} x horizontal center
  21553. * @param {Number} y vertical center
  21554. * @param {Number} r radius, half the length of the sides of the triangle
  21555. */
  21556. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  21557. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  21558. this.beginPath();
  21559. for (var n = 0; n < 10; n++) {
  21560. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  21561. this.lineTo(
  21562. x + radius * Math.sin(n * 2 * Math.PI / 10),
  21563. y - radius * Math.cos(n * 2 * Math.PI / 10)
  21564. );
  21565. }
  21566. this.closePath();
  21567. };
  21568. /**
  21569. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  21570. */
  21571. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  21572. var r2d = Math.PI/180;
  21573. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  21574. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  21575. this.beginPath();
  21576. this.moveTo(x+r,y);
  21577. this.lineTo(x+w-r,y);
  21578. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  21579. this.lineTo(x+w,y+h-r);
  21580. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  21581. this.lineTo(x+r,y+h);
  21582. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  21583. this.lineTo(x,y+r);
  21584. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  21585. };
  21586. /**
  21587. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  21588. */
  21589. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  21590. var kappa = .5522848,
  21591. ox = (w / 2) * kappa, // control point offset horizontal
  21592. oy = (h / 2) * kappa, // control point offset vertical
  21593. xe = x + w, // x-end
  21594. ye = y + h, // y-end
  21595. xm = x + w / 2, // x-middle
  21596. ym = y + h / 2; // y-middle
  21597. this.beginPath();
  21598. this.moveTo(x, ym);
  21599. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  21600. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  21601. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  21602. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  21603. };
  21604. /**
  21605. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  21606. */
  21607. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  21608. var f = 1/3;
  21609. var wEllipse = w;
  21610. var hEllipse = h * f;
  21611. var kappa = .5522848,
  21612. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  21613. oy = (hEllipse / 2) * kappa, // control point offset vertical
  21614. xe = x + wEllipse, // x-end
  21615. ye = y + hEllipse, // y-end
  21616. xm = x + wEllipse / 2, // x-middle
  21617. ym = y + hEllipse / 2, // y-middle
  21618. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  21619. yeb = y + h; // y-end, bottom ellipse
  21620. this.beginPath();
  21621. this.moveTo(xe, ym);
  21622. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  21623. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  21624. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  21625. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  21626. this.lineTo(xe, ymb);
  21627. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  21628. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  21629. this.lineTo(x, ym);
  21630. };
  21631. /**
  21632. * Draw an arrow point (no line)
  21633. */
  21634. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  21635. // tail
  21636. var xt = x - length * Math.cos(angle);
  21637. var yt = y - length * Math.sin(angle);
  21638. // inner tail
  21639. // TODO: allow to customize different shapes
  21640. var xi = x - length * 0.9 * Math.cos(angle);
  21641. var yi = y - length * 0.9 * Math.sin(angle);
  21642. // left
  21643. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  21644. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  21645. // right
  21646. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  21647. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  21648. this.beginPath();
  21649. this.moveTo(x, y);
  21650. this.lineTo(xl, yl);
  21651. this.lineTo(xi, yi);
  21652. this.lineTo(xr, yr);
  21653. this.closePath();
  21654. };
  21655. /**
  21656. * Sets up the dashedLine functionality for drawing
  21657. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  21658. * @author David Jordan
  21659. * @date 2012-08-08
  21660. */
  21661. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  21662. if (!dashArray) dashArray=[10,5];
  21663. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  21664. var dashCount = dashArray.length;
  21665. this.moveTo(x, y);
  21666. var dx = (x2-x), dy = (y2-y);
  21667. var slope = dy/dx;
  21668. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  21669. var dashIndex=0, draw=true;
  21670. while (distRemaining>=0.1){
  21671. var dashLength = dashArray[dashIndex++%dashCount];
  21672. if (dashLength > distRemaining) dashLength = distRemaining;
  21673. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  21674. if (dx<0) xStep = -xStep;
  21675. x += xStep;
  21676. y += slope*xStep;
  21677. this[draw ? 'lineTo' : 'moveTo'](x,y);
  21678. distRemaining -= dashLength;
  21679. draw = !draw;
  21680. }
  21681. };
  21682. // TODO: add diamond shape
  21683. }
  21684. /***/ },
  21685. /* 56 */
  21686. /***/ function(module, exports, __webpack_require__) {
  21687. /**
  21688. * Expose `Emitter`.
  21689. */
  21690. module.exports = Emitter;
  21691. /**
  21692. * Initialize a new `Emitter`.
  21693. *
  21694. * @api public
  21695. */
  21696. function Emitter(obj) {
  21697. if (obj) return mixin(obj);
  21698. };
  21699. /**
  21700. * Mixin the emitter properties.
  21701. *
  21702. * @param {Object} obj
  21703. * @return {Object}
  21704. * @api private
  21705. */
  21706. function mixin(obj) {
  21707. for (var key in Emitter.prototype) {
  21708. obj[key] = Emitter.prototype[key];
  21709. }
  21710. return obj;
  21711. }
  21712. /**
  21713. * Listen on the given `event` with `fn`.
  21714. *
  21715. * @param {String} event
  21716. * @param {Function} fn
  21717. * @return {Emitter}
  21718. * @api public
  21719. */
  21720. Emitter.prototype.on =
  21721. Emitter.prototype.addEventListener = function(event, fn){
  21722. this._callbacks = this._callbacks || {};
  21723. (this._callbacks[event] = this._callbacks[event] || [])
  21724. .push(fn);
  21725. return this;
  21726. };
  21727. /**
  21728. * Adds an `event` listener that will be invoked a single
  21729. * time then automatically removed.
  21730. *
  21731. * @param {String} event
  21732. * @param {Function} fn
  21733. * @return {Emitter}
  21734. * @api public
  21735. */
  21736. Emitter.prototype.once = function(event, fn){
  21737. var self = this;
  21738. this._callbacks = this._callbacks || {};
  21739. function on() {
  21740. self.off(event, on);
  21741. fn.apply(this, arguments);
  21742. }
  21743. on.fn = fn;
  21744. this.on(event, on);
  21745. return this;
  21746. };
  21747. /**
  21748. * Remove the given callback for `event` or all
  21749. * registered callbacks.
  21750. *
  21751. * @param {String} event
  21752. * @param {Function} fn
  21753. * @return {Emitter}
  21754. * @api public
  21755. */
  21756. Emitter.prototype.off =
  21757. Emitter.prototype.removeListener =
  21758. Emitter.prototype.removeAllListeners =
  21759. Emitter.prototype.removeEventListener = function(event, fn){
  21760. this._callbacks = this._callbacks || {};
  21761. // all
  21762. if (0 == arguments.length) {
  21763. this._callbacks = {};
  21764. return this;
  21765. }
  21766. // specific event
  21767. var callbacks = this._callbacks[event];
  21768. if (!callbacks) return this;
  21769. // remove all handlers
  21770. if (1 == arguments.length) {
  21771. delete this._callbacks[event];
  21772. return this;
  21773. }
  21774. // remove specific handler
  21775. var cb;
  21776. for (var i = 0; i < callbacks.length; i++) {
  21777. cb = callbacks[i];
  21778. if (cb === fn || cb.fn === fn) {
  21779. callbacks.splice(i, 1);
  21780. break;
  21781. }
  21782. }
  21783. return this;
  21784. };
  21785. /**
  21786. * Emit `event` with the given args.
  21787. *
  21788. * @param {String} event
  21789. * @param {Mixed} ...
  21790. * @return {Emitter}
  21791. */
  21792. Emitter.prototype.emit = function(event){
  21793. this._callbacks = this._callbacks || {};
  21794. var args = [].slice.call(arguments, 1)
  21795. , callbacks = this._callbacks[event];
  21796. if (callbacks) {
  21797. callbacks = callbacks.slice(0);
  21798. for (var i = 0, len = callbacks.length; i < len; ++i) {
  21799. callbacks[i].apply(this, args);
  21800. }
  21801. }
  21802. return this;
  21803. };
  21804. /**
  21805. * Return array of callbacks for `event`.
  21806. *
  21807. * @param {String} event
  21808. * @return {Array}
  21809. * @api public
  21810. */
  21811. Emitter.prototype.listeners = function(event){
  21812. this._callbacks = this._callbacks || {};
  21813. return this._callbacks[event] || [];
  21814. };
  21815. /**
  21816. * Check if this emitter has `event` handlers.
  21817. *
  21818. * @param {String} event
  21819. * @return {Boolean}
  21820. * @api public
  21821. */
  21822. Emitter.prototype.hasListeners = function(event){
  21823. return !! this.listeners(event).length;
  21824. };
  21825. /***/ },
  21826. /* 57 */
  21827. /***/ function(module, exports, __webpack_require__) {
  21828. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
  21829. /**
  21830. * Created by Alex on 11/6/2014.
  21831. */
  21832. // https://github.com/umdjs/umd/blob/master/returnExports.js#L40-L60
  21833. // if the module has no dependencies, the above pattern can be simplified to
  21834. (function (root, factory) {
  21835. if (true) {
  21836. // AMD. Register as an anonymous module.
  21837. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  21838. } else if (typeof exports === 'object') {
  21839. // Node. Does not work with strict CommonJS, but
  21840. // only CommonJS-like environments that support module.exports,
  21841. // like Node.
  21842. module.exports = factory();
  21843. } else {
  21844. // Browser globals (root is window)
  21845. root.keycharm = factory();
  21846. }
  21847. }(this, function () {
  21848. function keycharm(options) {
  21849. var preventDefault = options && options.preventDefault || false;
  21850. var container = options && options.container || window;
  21851. var _exportFunctions = {};
  21852. var _bound = {keydown:{}, keyup:{}};
  21853. var _keys = {};
  21854. var i;
  21855. // a - z
  21856. for (i = 97; i <= 122; i++) {_keys[String.fromCharCode(i)] = {code:65 + (i - 97), shift: false};}
  21857. // A - Z
  21858. for (i = 65; i <= 90; i++) {_keys[String.fromCharCode(i)] = {code:i, shift: true};}
  21859. // 0 - 9
  21860. for (i = 0; i <= 9; i++) {_keys['' + i] = {code:48 + i, shift: false};}
  21861. // F1 - F12
  21862. for (i = 1; i <= 12; i++) {_keys['F' + i] = {code:111 + i, shift: false};}
  21863. // num0 - num9
  21864. for (i = 0; i <= 9; i++) {_keys['num' + i] = {code:96 + i, shift: false};}
  21865. // numpad misc
  21866. _keys['num*'] = {code:106, shift: false};
  21867. _keys['num+'] = {code:107, shift: false};
  21868. _keys['num-'] = {code:109, shift: false};
  21869. _keys['num/'] = {code:111, shift: false};
  21870. _keys['num.'] = {code:110, shift: false};
  21871. // arrows
  21872. _keys['left'] = {code:37, shift: false};
  21873. _keys['up'] = {code:38, shift: false};
  21874. _keys['right'] = {code:39, shift: false};
  21875. _keys['down'] = {code:40, shift: false};
  21876. // extra keys
  21877. _keys['space'] = {code:32, shift: false};
  21878. _keys['enter'] = {code:13, shift: false};
  21879. _keys['shift'] = {code:16, shift: undefined};
  21880. _keys['esc'] = {code:27, shift: false};
  21881. _keys['backspace'] = {code:8, shift: false};
  21882. _keys['tab'] = {code:9, shift: false};
  21883. _keys['ctrl'] = {code:17, shift: false};
  21884. _keys['alt'] = {code:18, shift: false};
  21885. _keys['delete'] = {code:46, shift: false};
  21886. _keys['pageup'] = {code:33, shift: false};
  21887. _keys['pagedown'] = {code:34, shift: false};
  21888. // symbols
  21889. _keys['='] = {code:187, shift: false};
  21890. _keys['-'] = {code:189, shift: false};
  21891. _keys[']'] = {code:221, shift: false};
  21892. _keys['['] = {code:219, shift: false};
  21893. var down = function(event) {handleEvent(event,'keydown');};
  21894. var up = function(event) {handleEvent(event,'keyup');};
  21895. // handle the actualy bound key with the event
  21896. var handleEvent = function(event,type) {
  21897. if (_bound[type][event.keyCode] !== undefined) {
  21898. var bound = _bound[type][event.keyCode];
  21899. for (var i = 0; i < bound.length; i++) {
  21900. if (bound[i].shift === undefined) {
  21901. bound[i].fn(event);
  21902. }
  21903. else if (bound[i].shift == true && event.shiftKey == true) {
  21904. bound[i].fn(event);
  21905. }
  21906. else if (bound[i].shift == false && event.shiftKey == false) {
  21907. bound[i].fn(event);
  21908. }
  21909. }
  21910. if (preventDefault == true) {
  21911. event.preventDefault();
  21912. }
  21913. }
  21914. };
  21915. // bind a key to a callback
  21916. _exportFunctions.bind = function(key, callback, type) {
  21917. if (type === undefined) {
  21918. type = 'keydown';
  21919. }
  21920. if (_keys[key] === undefined) {
  21921. throw new Error("unsupported key: " + key);
  21922. }
  21923. if (_bound[type][_keys[key].code] === undefined) {
  21924. _bound[type][_keys[key].code] = [];
  21925. }
  21926. _bound[type][_keys[key].code].push({fn:callback, shift:_keys[key].shift});
  21927. };
  21928. // bind all keys to a call back (demo purposes)
  21929. _exportFunctions.bindAll = function(callback, type) {
  21930. if (type === undefined) {
  21931. type = 'keydown';
  21932. }
  21933. for (var key in _keys) {
  21934. if (_keys.hasOwnProperty(key)) {
  21935. _exportFunctions.bind(key,callback,type);
  21936. }
  21937. }
  21938. };
  21939. // get the key label from an event
  21940. _exportFunctions.getKey = function(event) {
  21941. for (var key in _keys) {
  21942. if (_keys.hasOwnProperty(key)) {
  21943. if (event.shiftKey == true && _keys[key].shift == true && event.keyCode == _keys[key].code) {
  21944. return key;
  21945. }
  21946. else if (event.shiftKey == false && _keys[key].shift == false && event.keyCode == _keys[key].code) {
  21947. return key;
  21948. }
  21949. else if (event.keyCode == _keys[key].code && key == 'shift') {
  21950. return key;
  21951. }
  21952. }
  21953. }
  21954. return "unknown key, currently not supported";
  21955. };
  21956. // unbind either a specific callback from a key or all of them (by leaving callback undefined)
  21957. _exportFunctions.unbind = function(key, callback, type) {
  21958. if (type === undefined) {
  21959. type = 'keydown';
  21960. }
  21961. if (_keys[key] === undefined) {
  21962. throw new Error("unsupported key: " + key);
  21963. }
  21964. if (callback !== undefined) {
  21965. var newBindings = [];
  21966. var bound = _bound[type][_keys[key].code];
  21967. if (bound !== undefined) {
  21968. for (var i = 0; i < bound.length; i++) {
  21969. if (!(bound[i].fn == callback && bound[i].shift == _keys[key].shift)) {
  21970. newBindings.push(_bound[type][_keys[key].code][i]);
  21971. }
  21972. }
  21973. }
  21974. _bound[type][_keys[key].code] = newBindings;
  21975. }
  21976. else {
  21977. _bound[type][_keys[key].code] = [];
  21978. }
  21979. };
  21980. // reset all bound variables.
  21981. _exportFunctions.reset = function() {
  21982. _bound = {keydown:{}, keyup:{}};
  21983. };
  21984. // unbind all listeners and reset all variables.
  21985. _exportFunctions.destroy = function() {
  21986. _bound = {keydown:{}, keyup:{}};
  21987. container.removeEventListener('keydown', down, true);
  21988. container.removeEventListener('keyup', up, true);
  21989. };
  21990. // create listeners.
  21991. container.addEventListener('keydown',down,true);
  21992. container.addEventListener('keyup',up,true);
  21993. // return the public functions.
  21994. return _exportFunctions;
  21995. }
  21996. return keycharm;
  21997. }));
  21998. /***/ },
  21999. /* 58 */
  22000. /***/ function(module, exports, __webpack_require__) {
  22001. /* WEBPACK VAR INJECTION */(function(module) {//! moment.js
  22002. //! version : 2.10.0
  22003. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  22004. //! license : MIT
  22005. //! momentjs.com
  22006. (function (global, factory) {
  22007. true ? module.exports = factory() :
  22008. typeof define === 'function' && define.amd ? define(factory) :
  22009. global.moment = factory()
  22010. }(this, function () { 'use strict';
  22011. var hookCallback;
  22012. function hooks__hooks () {
  22013. return hookCallback.apply(null, arguments);
  22014. }
  22015. // This is done to register the method called with moment()
  22016. // without creating circular dependencies.
  22017. function setHookCallback (callback) {
  22018. hookCallback = callback;
  22019. }
  22020. function defaultParsingFlags() {
  22021. // We need to deep clone this object.
  22022. return {
  22023. empty : false,
  22024. unusedTokens : [],
  22025. unusedInput : [],
  22026. overflow : -2,
  22027. charsLeftOver : 0,
  22028. nullInput : false,
  22029. invalidMonth : null,
  22030. invalidFormat : false,
  22031. userInvalidated : false,
  22032. iso : false
  22033. };
  22034. }
  22035. function isArray(input) {
  22036. return Object.prototype.toString.call(input) === '[object Array]';
  22037. }
  22038. function isDate(input) {
  22039. return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
  22040. }
  22041. function map(arr, fn) {
  22042. var res = [], i;
  22043. for (i = 0; i < arr.length; ++i) {
  22044. res.push(fn(arr[i], i));
  22045. }
  22046. return res;
  22047. }
  22048. function hasOwnProp(a, b) {
  22049. return Object.prototype.hasOwnProperty.call(a, b);
  22050. }
  22051. function extend(a, b) {
  22052. for (var i in b) {
  22053. if (hasOwnProp(b, i)) {
  22054. a[i] = b[i];
  22055. }
  22056. }
  22057. if (hasOwnProp(b, 'toString')) {
  22058. a.toString = b.toString;
  22059. }
  22060. if (hasOwnProp(b, 'valueOf')) {
  22061. a.valueOf = b.valueOf;
  22062. }
  22063. return a;
  22064. }
  22065. function utc__createUTC (input, format, locale, strict) {
  22066. return createLocalOrUTC(input, format, locale, strict, true).utc();
  22067. }
  22068. function valid__isValid(m) {
  22069. if (m._isValid == null) {
  22070. m._isValid = !isNaN(m._d.getTime()) &&
  22071. m._pf.overflow < 0 &&
  22072. !m._pf.empty &&
  22073. !m._pf.invalidMonth &&
  22074. !m._pf.nullInput &&
  22075. !m._pf.invalidFormat &&
  22076. !m._pf.userInvalidated;
  22077. if (m._strict) {
  22078. m._isValid = m._isValid &&
  22079. m._pf.charsLeftOver === 0 &&
  22080. m._pf.unusedTokens.length === 0 &&
  22081. m._pf.bigHour === undefined;
  22082. }
  22083. }
  22084. return m._isValid;
  22085. }
  22086. function valid__createInvalid (flags) {
  22087. var m = utc__createUTC(NaN);
  22088. if (flags != null) {
  22089. extend(m._pf, flags);
  22090. }
  22091. else {
  22092. m._pf.userInvalidated = true;
  22093. }
  22094. return m;
  22095. }
  22096. var momentProperties = hooks__hooks.momentProperties = [];
  22097. function copyConfig(to, from) {
  22098. var i, prop, val;
  22099. if (typeof from._isAMomentObject !== 'undefined') {
  22100. to._isAMomentObject = from._isAMomentObject;
  22101. }
  22102. if (typeof from._i !== 'undefined') {
  22103. to._i = from._i;
  22104. }
  22105. if (typeof from._f !== 'undefined') {
  22106. to._f = from._f;
  22107. }
  22108. if (typeof from._l !== 'undefined') {
  22109. to._l = from._l;
  22110. }
  22111. if (typeof from._strict !== 'undefined') {
  22112. to._strict = from._strict;
  22113. }
  22114. if (typeof from._tzm !== 'undefined') {
  22115. to._tzm = from._tzm;
  22116. }
  22117. if (typeof from._isUTC !== 'undefined') {
  22118. to._isUTC = from._isUTC;
  22119. }
  22120. if (typeof from._offset !== 'undefined') {
  22121. to._offset = from._offset;
  22122. }
  22123. if (typeof from._pf !== 'undefined') {
  22124. to._pf = from._pf;
  22125. }
  22126. if (typeof from._locale !== 'undefined') {
  22127. to._locale = from._locale;
  22128. }
  22129. if (momentProperties.length > 0) {
  22130. for (i in momentProperties) {
  22131. prop = momentProperties[i];
  22132. val = from[prop];
  22133. if (typeof val !== 'undefined') {
  22134. to[prop] = val;
  22135. }
  22136. }
  22137. }
  22138. return to;
  22139. }
  22140. var updateInProgress = false;
  22141. // Moment prototype object
  22142. function Moment(config) {
  22143. copyConfig(this, config);
  22144. this._d = new Date(+config._d);
  22145. // Prevent infinite loop in case updateOffset creates new moment
  22146. // objects.
  22147. if (updateInProgress === false) {
  22148. updateInProgress = true;
  22149. hooks__hooks.updateOffset(this);
  22150. updateInProgress = false;
  22151. }
  22152. }
  22153. function isMoment (obj) {
  22154. return obj instanceof Moment || (obj != null && hasOwnProp(obj, '_isAMomentObject'));
  22155. }
  22156. function toInt(argumentForCoercion) {
  22157. var coercedNumber = +argumentForCoercion,
  22158. value = 0;
  22159. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  22160. if (coercedNumber >= 0) {
  22161. value = Math.floor(coercedNumber);
  22162. } else {
  22163. value = Math.ceil(coercedNumber);
  22164. }
  22165. }
  22166. return value;
  22167. }
  22168. function compareArrays(array1, array2, dontConvert) {
  22169. var len = Math.min(array1.length, array2.length),
  22170. lengthDiff = Math.abs(array1.length - array2.length),
  22171. diffs = 0,
  22172. i;
  22173. for (i = 0; i < len; i++) {
  22174. if ((dontConvert && array1[i] !== array2[i]) ||
  22175. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  22176. diffs++;
  22177. }
  22178. }
  22179. return diffs + lengthDiff;
  22180. }
  22181. function Locale() {
  22182. }
  22183. var locales = {};
  22184. var globalLocale;
  22185. function normalizeLocale(key) {
  22186. return key ? key.toLowerCase().replace('_', '-') : key;
  22187. }
  22188. // pick the locale from the array
  22189. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  22190. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  22191. function chooseLocale(names) {
  22192. var i = 0, j, next, locale, split;
  22193. while (i < names.length) {
  22194. split = normalizeLocale(names[i]).split('-');
  22195. j = split.length;
  22196. next = normalizeLocale(names[i + 1]);
  22197. next = next ? next.split('-') : null;
  22198. while (j > 0) {
  22199. locale = loadLocale(split.slice(0, j).join('-'));
  22200. if (locale) {
  22201. return locale;
  22202. }
  22203. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  22204. //the next array item is better than a shallower substring of this one
  22205. break;
  22206. }
  22207. j--;
  22208. }
  22209. i++;
  22210. }
  22211. return null;
  22212. }
  22213. function loadLocale(name) {
  22214. var oldLocale = null;
  22215. // TODO: Find a better way to register and load all the locales in Node
  22216. if (!locales[name] && typeof module !== 'undefined' &&
  22217. module && module.exports) {
  22218. try {
  22219. oldLocale = globalLocale._abbr;
  22220. !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }());
  22221. // because defineLocale currently also sets the global locale, we
  22222. // want to undo that for lazy loaded locales
  22223. locales__getSetGlobalLocale(oldLocale);
  22224. } catch (e) { }
  22225. }
  22226. return locales[name];
  22227. }
  22228. // This function will load locale and then set the global locale. If
  22229. // no arguments are passed in, it will simply return the current global
  22230. // locale key.
  22231. function locales__getSetGlobalLocale (key, values) {
  22232. var data;
  22233. if (key) {
  22234. if (typeof values === 'undefined') {
  22235. data = locales__getLocale(key);
  22236. }
  22237. else {
  22238. data = defineLocale(key, values);
  22239. }
  22240. if (data) {
  22241. // moment.duration._locale = moment._locale = data;
  22242. globalLocale = data;
  22243. }
  22244. }
  22245. return globalLocale._abbr;
  22246. }
  22247. function defineLocale (name, values) {
  22248. if (values !== null) {
  22249. values.abbr = name;
  22250. if (!locales[name]) {
  22251. locales[name] = new Locale();
  22252. }
  22253. locales[name].set(values);
  22254. // backwards compat for now: also set the locale
  22255. locales__getSetGlobalLocale(name);
  22256. return locales[name];
  22257. } else {
  22258. // useful for testing
  22259. delete locales[name];
  22260. return null;
  22261. }
  22262. }
  22263. // returns locale data
  22264. function locales__getLocale (key) {
  22265. var locale;
  22266. if (key && key._locale && key._locale._abbr) {
  22267. key = key._locale._abbr;
  22268. }
  22269. if (!key) {
  22270. return globalLocale;
  22271. }
  22272. if (!isArray(key)) {
  22273. //short-circuit everything else
  22274. locale = loadLocale(key);
  22275. if (locale) {
  22276. return locale;
  22277. }
  22278. key = [key];
  22279. }
  22280. return chooseLocale(key);
  22281. }
  22282. var aliases = {};
  22283. function addUnitAlias (unit, shorthand) {
  22284. var lowerCase = unit.toLowerCase();
  22285. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  22286. }
  22287. function normalizeUnits(units) {
  22288. return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
  22289. }
  22290. function normalizeObjectUnits(inputObject) {
  22291. var normalizedInput = {},
  22292. normalizedProp,
  22293. prop;
  22294. for (prop in inputObject) {
  22295. if (hasOwnProp(inputObject, prop)) {
  22296. normalizedProp = normalizeUnits(prop);
  22297. if (normalizedProp) {
  22298. normalizedInput[normalizedProp] = inputObject[prop];
  22299. }
  22300. }
  22301. }
  22302. return normalizedInput;
  22303. }
  22304. function makeGetSet (unit, keepTime) {
  22305. return function (value) {
  22306. if (value != null) {
  22307. get_set__set(this, unit, value);
  22308. hooks__hooks.updateOffset(this, keepTime);
  22309. return this;
  22310. } else {
  22311. return get_set__get(this, unit);
  22312. }
  22313. };
  22314. }
  22315. function get_set__get (mom, unit) {
  22316. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  22317. }
  22318. function get_set__set (mom, unit, value) {
  22319. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  22320. }
  22321. // MOMENTS
  22322. function getSet (units, value) {
  22323. var unit;
  22324. if (typeof units === 'object') {
  22325. for (unit in units) {
  22326. this.set(unit, units[unit]);
  22327. }
  22328. } else {
  22329. units = normalizeUnits(units);
  22330. if (typeof this[units] === 'function') {
  22331. return this[units](value);
  22332. }
  22333. }
  22334. return this;
  22335. }
  22336. function zeroFill(number, targetLength, forceSign) {
  22337. var output = '' + Math.abs(number),
  22338. sign = number >= 0;
  22339. while (output.length < targetLength) {
  22340. output = '0' + output;
  22341. }
  22342. return (sign ? (forceSign ? '+' : '') : '-') + output;
  22343. }
  22344. var formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g;
  22345. var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
  22346. var formatFunctions = {};
  22347. var formatTokenFunctions = {};
  22348. // token: 'M'
  22349. // padded: ['MM', 2]
  22350. // ordinal: 'Mo'
  22351. // callback: function () { this.month() + 1 }
  22352. function addFormatToken (token, padded, ordinal, callback) {
  22353. var func = callback;
  22354. if (typeof callback === 'string') {
  22355. func = function () {
  22356. return this[callback]();
  22357. };
  22358. }
  22359. if (token) {
  22360. formatTokenFunctions[token] = func;
  22361. }
  22362. if (padded) {
  22363. formatTokenFunctions[padded[0]] = function () {
  22364. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  22365. };
  22366. }
  22367. if (ordinal) {
  22368. formatTokenFunctions[ordinal] = function () {
  22369. return this.localeData().ordinal(func.apply(this, arguments), token);
  22370. };
  22371. }
  22372. }
  22373. function removeFormattingTokens(input) {
  22374. if (input.match(/\[[\s\S]/)) {
  22375. return input.replace(/^\[|\]$/g, '');
  22376. }
  22377. return input.replace(/\\/g, '');
  22378. }
  22379. function makeFormatFunction(format) {
  22380. var array = format.match(formattingTokens), i, length;
  22381. for (i = 0, length = array.length; i < length; i++) {
  22382. if (formatTokenFunctions[array[i]]) {
  22383. array[i] = formatTokenFunctions[array[i]];
  22384. } else {
  22385. array[i] = removeFormattingTokens(array[i]);
  22386. }
  22387. }
  22388. return function (mom) {
  22389. var output = '';
  22390. for (i = 0; i < length; i++) {
  22391. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  22392. }
  22393. return output;
  22394. };
  22395. }
  22396. // format date using native date object
  22397. function formatMoment(m, format) {
  22398. if (!m.isValid()) {
  22399. return m.localeData().invalidDate();
  22400. }
  22401. format = expandFormat(format, m.localeData());
  22402. if (!formatFunctions[format]) {
  22403. formatFunctions[format] = makeFormatFunction(format);
  22404. }
  22405. return formatFunctions[format](m);
  22406. }
  22407. function expandFormat(format, locale) {
  22408. var i = 5;
  22409. function replaceLongDateFormatTokens(input) {
  22410. return locale.longDateFormat(input) || input;
  22411. }
  22412. localFormattingTokens.lastIndex = 0;
  22413. while (i >= 0 && localFormattingTokens.test(format)) {
  22414. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  22415. localFormattingTokens.lastIndex = 0;
  22416. i -= 1;
  22417. }
  22418. return format;
  22419. }
  22420. var match1 = /\d/; // 0 - 9
  22421. var match2 = /\d\d/; // 00 - 99
  22422. var match3 = /\d{3}/; // 000 - 999
  22423. var match4 = /\d{4}/; // 0000 - 9999
  22424. var match6 = /[+-]?\d{6}/; // -999999 - 999999
  22425. var match1to2 = /\d\d?/; // 0 - 99
  22426. var match1to3 = /\d{1,3}/; // 0 - 999
  22427. var match1to4 = /\d{1,4}/; // 0 - 9999
  22428. var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
  22429. var matchUnsigned = /\d+/; // 0 - inf
  22430. var matchSigned = /[+-]?\d+/; // -inf - inf
  22431. var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
  22432. var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
  22433. // any word (or two) characters or numbers including two/three word month in arabic.
  22434. var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
  22435. var regexes = {};
  22436. function addRegexToken (token, regex, strictRegex) {
  22437. regexes[token] = typeof regex === 'function' ? regex : function (isStrict) {
  22438. return (isStrict && strictRegex) ? strictRegex : regex;
  22439. };
  22440. }
  22441. function getParseRegexForToken (token, config) {
  22442. if (!hasOwnProp(regexes, token)) {
  22443. return new RegExp(unescapeFormat(token));
  22444. }
  22445. return regexes[token](config._strict, config._locale);
  22446. }
  22447. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  22448. function unescapeFormat(s) {
  22449. return s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  22450. return p1 || p2 || p3 || p4;
  22451. }).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  22452. }
  22453. var tokens = {};
  22454. function addParseToken (token, callback) {
  22455. var i, func = callback;
  22456. if (typeof token === 'string') {
  22457. token = [token];
  22458. }
  22459. if (typeof callback === 'number') {
  22460. func = function (input, array) {
  22461. array[callback] = toInt(input);
  22462. };
  22463. }
  22464. for (i = 0; i < token.length; i++) {
  22465. tokens[token[i]] = func;
  22466. }
  22467. }
  22468. function addWeekParseToken (token, callback) {
  22469. addParseToken(token, function (input, array, config, token) {
  22470. config._w = config._w || {};
  22471. callback(input, config._w, config, token);
  22472. });
  22473. }
  22474. function addTimeToArrayFromToken(token, input, config) {
  22475. if (input != null && hasOwnProp(tokens, token)) {
  22476. tokens[token](input, config._a, config, token);
  22477. }
  22478. }
  22479. var YEAR = 0;
  22480. var MONTH = 1;
  22481. var DATE = 2;
  22482. var HOUR = 3;
  22483. var MINUTE = 4;
  22484. var SECOND = 5;
  22485. var MILLISECOND = 6;
  22486. function daysInMonth(year, month) {
  22487. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  22488. }
  22489. // FORMATTING
  22490. addFormatToken('M', ['MM', 2], 'Mo', function () {
  22491. return this.month() + 1;
  22492. });
  22493. addFormatToken('MMM', 0, 0, function (format) {
  22494. return this.localeData().monthsShort(this, format);
  22495. });
  22496. addFormatToken('MMMM', 0, 0, function (format) {
  22497. return this.localeData().months(this, format);
  22498. });
  22499. // ALIASES
  22500. addUnitAlias('month', 'M');
  22501. // PARSING
  22502. addRegexToken('M', match1to2);
  22503. addRegexToken('MM', match1to2, match2);
  22504. addRegexToken('MMM', matchWord);
  22505. addRegexToken('MMMM', matchWord);
  22506. addParseToken(['M', 'MM'], function (input, array) {
  22507. array[MONTH] = toInt(input) - 1;
  22508. });
  22509. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  22510. var month = config._locale.monthsParse(input, token, config._strict);
  22511. // if we didn't find a month name, mark the date as invalid.
  22512. if (month != null) {
  22513. array[MONTH] = month;
  22514. } else {
  22515. config._pf.invalidMonth = input;
  22516. }
  22517. });
  22518. // LOCALES
  22519. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
  22520. function localeMonths (m) {
  22521. return this._months[m.month()];
  22522. }
  22523. var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
  22524. function localeMonthsShort (m) {
  22525. return this._monthsShort[m.month()];
  22526. }
  22527. function localeMonthsParse (monthName, format, strict) {
  22528. var i, mom, regex;
  22529. if (!this._monthsParse) {
  22530. this._monthsParse = [];
  22531. this._longMonthsParse = [];
  22532. this._shortMonthsParse = [];
  22533. }
  22534. for (i = 0; i < 12; i++) {
  22535. // make the regex if we don't have it already
  22536. mom = utc__createUTC([2000, i]);
  22537. if (strict && !this._longMonthsParse[i]) {
  22538. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  22539. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  22540. }
  22541. if (!strict && !this._monthsParse[i]) {
  22542. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  22543. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  22544. }
  22545. // test the regex
  22546. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  22547. return i;
  22548. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  22549. return i;
  22550. } else if (!strict && this._monthsParse[i].test(monthName)) {
  22551. return i;
  22552. }
  22553. }
  22554. }
  22555. // MOMENTS
  22556. function setMonth (mom, value) {
  22557. var dayOfMonth;
  22558. // TODO: Move this out of here!
  22559. if (typeof value === 'string') {
  22560. value = mom.localeData().monthsParse(value);
  22561. // TODO: Another silent failure?
  22562. if (typeof value !== 'number') {
  22563. return mom;
  22564. }
  22565. }
  22566. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  22567. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  22568. return mom;
  22569. }
  22570. function getSetMonth (value) {
  22571. if (value != null) {
  22572. setMonth(this, value);
  22573. hooks__hooks.updateOffset(this, true);
  22574. return this;
  22575. } else {
  22576. return get_set__get(this, 'Month');
  22577. }
  22578. }
  22579. function getDaysInMonth () {
  22580. return daysInMonth(this.year(), this.month());
  22581. }
  22582. function checkOverflow (m) {
  22583. var overflow;
  22584. var a = m._a;
  22585. if (a && m._pf.overflow === -2) {
  22586. overflow =
  22587. a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
  22588. a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
  22589. a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
  22590. a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
  22591. a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
  22592. a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
  22593. -1;
  22594. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  22595. overflow = DATE;
  22596. }
  22597. m._pf.overflow = overflow;
  22598. }
  22599. return m;
  22600. }
  22601. function warn(msg) {
  22602. if (hooks__hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) {
  22603. console.warn('Deprecation warning: ' + msg);
  22604. }
  22605. }
  22606. function deprecate(msg, fn) {
  22607. var firstTime = true;
  22608. return extend(function () {
  22609. if (firstTime) {
  22610. warn(msg);
  22611. firstTime = false;
  22612. }
  22613. return fn.apply(this, arguments);
  22614. }, fn);
  22615. }
  22616. var deprecations = {};
  22617. function deprecateSimple(name, msg) {
  22618. if (!deprecations[name]) {
  22619. warn(msg);
  22620. deprecations[name] = true;
  22621. }
  22622. }
  22623. hooks__hooks.suppressDeprecationWarnings = false;
  22624. var from_string__isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
  22625. var isoDates = [
  22626. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  22627. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  22628. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  22629. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  22630. ['YYYY-DDD', /\d{4}-\d{3}/]
  22631. ];
  22632. // iso time formats and regexes
  22633. var isoTimes = [
  22634. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  22635. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  22636. ['HH:mm', /(T| )\d\d:\d\d/],
  22637. ['HH', /(T| )\d\d/]
  22638. ];
  22639. var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
  22640. // date from iso format
  22641. function configFromISO(config) {
  22642. var i, l,
  22643. string = config._i,
  22644. match = from_string__isoRegex.exec(string);
  22645. if (match) {
  22646. config._pf.iso = true;
  22647. for (i = 0, l = isoDates.length; i < l; i++) {
  22648. if (isoDates[i][1].exec(string)) {
  22649. // match[5] should be 'T' or undefined
  22650. config._f = isoDates[i][0] + (match[6] || ' ');
  22651. break;
  22652. }
  22653. }
  22654. for (i = 0, l = isoTimes.length; i < l; i++) {
  22655. if (isoTimes[i][1].exec(string)) {
  22656. config._f += isoTimes[i][0];
  22657. break;
  22658. }
  22659. }
  22660. if (string.match(matchOffset)) {
  22661. config._f += 'Z';
  22662. }
  22663. configFromStringAndFormat(config);
  22664. } else {
  22665. config._isValid = false;
  22666. }
  22667. }
  22668. // date from iso format or fallback
  22669. function configFromString(config) {
  22670. var matched = aspNetJsonRegex.exec(config._i);
  22671. if (matched !== null) {
  22672. config._d = new Date(+matched[1]);
  22673. return;
  22674. }
  22675. configFromISO(config);
  22676. if (config._isValid === false) {
  22677. delete config._isValid;
  22678. hooks__hooks.createFromInputFallback(config);
  22679. }
  22680. }
  22681. hooks__hooks.createFromInputFallback = deprecate(
  22682. 'moment construction falls back to js Date. This is ' +
  22683. 'discouraged and will be removed in upcoming major ' +
  22684. 'release. Please refer to ' +
  22685. 'https://github.com/moment/moment/issues/1407 for more info.',
  22686. function (config) {
  22687. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  22688. }
  22689. );
  22690. function createDate (y, m, d, h, M, s, ms) {
  22691. //can't just apply() to create a date:
  22692. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  22693. var date = new Date(y, m, d, h, M, s, ms);
  22694. //the date constructor doesn't accept years < 1970
  22695. if (y < 1970) {
  22696. date.setFullYear(y);
  22697. }
  22698. return date;
  22699. }
  22700. function createUTCDate (y) {
  22701. var date = new Date(Date.UTC.apply(null, arguments));
  22702. if (y < 1970) {
  22703. date.setUTCFullYear(y);
  22704. }
  22705. return date;
  22706. }
  22707. addFormatToken(0, ['YY', 2], 0, function () {
  22708. return this.year() % 100;
  22709. });
  22710. addFormatToken(0, ['YYYY', 4], 0, 'year');
  22711. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  22712. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  22713. // ALIASES
  22714. addUnitAlias('year', 'y');
  22715. // PARSING
  22716. addRegexToken('Y', matchSigned);
  22717. addRegexToken('YY', match1to2, match2);
  22718. addRegexToken('YYYY', match1to4, match4);
  22719. addRegexToken('YYYYY', match1to6, match6);
  22720. addRegexToken('YYYYYY', match1to6, match6);
  22721. addParseToken(['YYYY', 'YYYYY', 'YYYYYY'], YEAR);
  22722. addParseToken('YY', function (input, array) {
  22723. array[YEAR] = hooks__hooks.parseTwoDigitYear(input);
  22724. });
  22725. // HELPERS
  22726. function daysInYear(year) {
  22727. return isLeapYear(year) ? 366 : 365;
  22728. }
  22729. function isLeapYear(year) {
  22730. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  22731. }
  22732. // HOOKS
  22733. hooks__hooks.parseTwoDigitYear = function (input) {
  22734. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  22735. };
  22736. // MOMENTS
  22737. var getSetYear = makeGetSet('FullYear', false);
  22738. function getIsLeapYear () {
  22739. return isLeapYear(this.year());
  22740. }
  22741. addFormatToken('w', ['ww', 2], 'wo', 'week');
  22742. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  22743. // ALIASES
  22744. addUnitAlias('week', 'w');
  22745. addUnitAlias('isoWeek', 'W');
  22746. // PARSING
  22747. addRegexToken('w', match1to2);
  22748. addRegexToken('ww', match1to2, match2);
  22749. addRegexToken('W', match1to2);
  22750. addRegexToken('WW', match1to2, match2);
  22751. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
  22752. week[token.substr(0, 1)] = toInt(input);
  22753. });
  22754. // HELPERS
  22755. // firstDayOfWeek 0 = sun, 6 = sat
  22756. // the day of the week that starts the week
  22757. // (usually sunday or monday)
  22758. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  22759. // the first week is the week that contains the first
  22760. // of this day of the week
  22761. // (eg. ISO weeks use thursday (4))
  22762. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  22763. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  22764. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  22765. adjustedMoment;
  22766. if (daysToDayOfWeek > end) {
  22767. daysToDayOfWeek -= 7;
  22768. }
  22769. if (daysToDayOfWeek < end - 7) {
  22770. daysToDayOfWeek += 7;
  22771. }
  22772. adjustedMoment = local__createLocal(mom).add(daysToDayOfWeek, 'd');
  22773. return {
  22774. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  22775. year: adjustedMoment.year()
  22776. };
  22777. }
  22778. // LOCALES
  22779. function localeWeek (mom) {
  22780. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  22781. }
  22782. var defaultLocaleWeek = {
  22783. dow : 0, // Sunday is the first day of the week.
  22784. doy : 6 // The week that contains Jan 1st is the first week of the year.
  22785. };
  22786. function localeFirstDayOfWeek () {
  22787. return this._week.dow;
  22788. }
  22789. function localeFirstDayOfYear () {
  22790. return this._week.doy;
  22791. }
  22792. // MOMENTS
  22793. function getSetWeek (input) {
  22794. var week = this.localeData().week(this);
  22795. return input == null ? week : this.add((input - week) * 7, 'd');
  22796. }
  22797. function getSetISOWeek (input) {
  22798. var week = weekOfYear(this, 1, 4).week;
  22799. return input == null ? week : this.add((input - week) * 7, 'd');
  22800. }
  22801. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  22802. // ALIASES
  22803. addUnitAlias('dayOfYear', 'DDD');
  22804. // PARSING
  22805. addRegexToken('DDD', match1to3);
  22806. addRegexToken('DDDD', match3);
  22807. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  22808. config._dayOfYear = toInt(input);
  22809. });
  22810. // HELPERS
  22811. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  22812. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  22813. var d = createUTCDate(year, 0, 1).getUTCDay();
  22814. var daysToAdd;
  22815. var dayOfYear;
  22816. d = d === 0 ? 7 : d;
  22817. weekday = weekday != null ? weekday : firstDayOfWeek;
  22818. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  22819. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  22820. return {
  22821. year : dayOfYear > 0 ? year : year - 1,
  22822. dayOfYear : dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  22823. };
  22824. }
  22825. // MOMENTS
  22826. function getSetDayOfYear (input) {
  22827. var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
  22828. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  22829. }
  22830. // Pick the first defined of two or three arguments.
  22831. function defaults(a, b, c) {
  22832. if (a != null) {
  22833. return a;
  22834. }
  22835. if (b != null) {
  22836. return b;
  22837. }
  22838. return c;
  22839. }
  22840. function currentDateArray(config) {
  22841. var now = new Date();
  22842. if (config._useUTC) {
  22843. return [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()];
  22844. }
  22845. return [now.getFullYear(), now.getMonth(), now.getDate()];
  22846. }
  22847. // convert an array to a date.
  22848. // the array should mirror the parameters below
  22849. // note: all values past the year are optional and will default to the lowest possible value.
  22850. // [year, month, day , hour, minute, second, millisecond]
  22851. function configFromArray (config) {
  22852. var i, date, input = [], currentDate, yearToUse;
  22853. if (config._d) {
  22854. return;
  22855. }
  22856. currentDate = currentDateArray(config);
  22857. //compute day of the year from weeks and weekdays
  22858. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  22859. dayOfYearFromWeekInfo(config);
  22860. }
  22861. //if the day of the year is set, figure out what it is
  22862. if (config._dayOfYear) {
  22863. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  22864. if (config._dayOfYear > daysInYear(yearToUse)) {
  22865. config._pf._overflowDayOfYear = true;
  22866. }
  22867. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  22868. config._a[MONTH] = date.getUTCMonth();
  22869. config._a[DATE] = date.getUTCDate();
  22870. }
  22871. // Default to current date.
  22872. // * if no year, month, day of month are given, default to today
  22873. // * if day of month is given, default month and year
  22874. // * if month is given, default only year
  22875. // * if year is given, don't default anything
  22876. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  22877. config._a[i] = input[i] = currentDate[i];
  22878. }
  22879. // Zero out whatever was not defaulted, including time
  22880. for (; i < 7; i++) {
  22881. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  22882. }
  22883. // Check for 24:00:00.000
  22884. if (config._a[HOUR] === 24 &&
  22885. config._a[MINUTE] === 0 &&
  22886. config._a[SECOND] === 0 &&
  22887. config._a[MILLISECOND] === 0) {
  22888. config._nextDay = true;
  22889. config._a[HOUR] = 0;
  22890. }
  22891. config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
  22892. // Apply timezone offset from input. The actual utcOffset can be changed
  22893. // with parseZone.
  22894. if (config._tzm != null) {
  22895. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  22896. }
  22897. if (config._nextDay) {
  22898. config._a[HOUR] = 24;
  22899. }
  22900. }
  22901. function dayOfYearFromWeekInfo(config) {
  22902. var w, weekYear, week, weekday, dow, doy, temp;
  22903. w = config._w;
  22904. if (w.GG != null || w.W != null || w.E != null) {
  22905. dow = 1;
  22906. doy = 4;
  22907. // TODO: We need to take the current isoWeekYear, but that depends on
  22908. // how we interpret now (local, utc, fixed offset). So create
  22909. // a now version of current config (take local/utc/offset flags, and
  22910. // create now).
  22911. weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year);
  22912. week = defaults(w.W, 1);
  22913. weekday = defaults(w.E, 1);
  22914. } else {
  22915. dow = config._locale._week.dow;
  22916. doy = config._locale._week.doy;
  22917. weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year);
  22918. week = defaults(w.w, 1);
  22919. if (w.d != null) {
  22920. // weekday -- low day numbers are considered next week
  22921. weekday = w.d;
  22922. if (weekday < dow) {
  22923. ++week;
  22924. }
  22925. } else if (w.e != null) {
  22926. // local weekday -- counting starts from begining of week
  22927. weekday = w.e + dow;
  22928. } else {
  22929. // default to begining of week
  22930. weekday = dow;
  22931. }
  22932. }
  22933. temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow);
  22934. config._a[YEAR] = temp.year;
  22935. config._dayOfYear = temp.dayOfYear;
  22936. }
  22937. hooks__hooks.ISO_8601 = function () {};
  22938. // date from string and format string
  22939. function configFromStringAndFormat(config) {
  22940. // TODO: Move this to another part of the creation flow to prevent circular deps
  22941. if (config._f === hooks__hooks.ISO_8601) {
  22942. configFromISO(config);
  22943. return;
  22944. }
  22945. config._a = [];
  22946. config._pf.empty = true;
  22947. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  22948. var string = '' + config._i,
  22949. i, parsedInput, tokens, token, skipped,
  22950. stringLength = string.length,
  22951. totalParsedInputLength = 0;
  22952. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  22953. for (i = 0; i < tokens.length; i++) {
  22954. token = tokens[i];
  22955. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  22956. if (parsedInput) {
  22957. skipped = string.substr(0, string.indexOf(parsedInput));
  22958. if (skipped.length > 0) {
  22959. config._pf.unusedInput.push(skipped);
  22960. }
  22961. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  22962. totalParsedInputLength += parsedInput.length;
  22963. }
  22964. // don't parse if it's not a known token
  22965. if (formatTokenFunctions[token]) {
  22966. if (parsedInput) {
  22967. config._pf.empty = false;
  22968. }
  22969. else {
  22970. config._pf.unusedTokens.push(token);
  22971. }
  22972. addTimeToArrayFromToken(token, parsedInput, config);
  22973. }
  22974. else if (config._strict && !parsedInput) {
  22975. config._pf.unusedTokens.push(token);
  22976. }
  22977. }
  22978. // add remaining unparsed input length to the string
  22979. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  22980. if (string.length > 0) {
  22981. config._pf.unusedInput.push(string);
  22982. }
  22983. // clear _12h flag if hour is <= 12
  22984. if (config._pf.bigHour === true && config._a[HOUR] <= 12) {
  22985. config._pf.bigHour = undefined;
  22986. }
  22987. // handle meridiem
  22988. config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
  22989. configFromArray(config);
  22990. checkOverflow(config);
  22991. }
  22992. function meridiemFixWrap (locale, hour, meridiem) {
  22993. var isPm;
  22994. if (meridiem == null) {
  22995. // nothing to do
  22996. return hour;
  22997. }
  22998. if (locale.meridiemHour != null) {
  22999. return locale.meridiemHour(hour, meridiem);
  23000. } else if (locale.isPM != null) {
  23001. // Fallback
  23002. isPm = locale.isPM(meridiem);
  23003. if (isPm && hour < 12) {
  23004. hour += 12;
  23005. }
  23006. if (!isPm && hour === 12) {
  23007. hour = 0;
  23008. }
  23009. return hour;
  23010. } else {
  23011. // this is not supposed to happen
  23012. return hour;
  23013. }
  23014. }
  23015. function configFromStringAndArray(config) {
  23016. var tempConfig,
  23017. bestMoment,
  23018. scoreToBeat,
  23019. i,
  23020. currentScore;
  23021. if (config._f.length === 0) {
  23022. config._pf.invalidFormat = true;
  23023. config._d = new Date(NaN);
  23024. return;
  23025. }
  23026. for (i = 0; i < config._f.length; i++) {
  23027. currentScore = 0;
  23028. tempConfig = copyConfig({}, config);
  23029. if (config._useUTC != null) {
  23030. tempConfig._useUTC = config._useUTC;
  23031. }
  23032. tempConfig._pf = defaultParsingFlags();
  23033. tempConfig._f = config._f[i];
  23034. configFromStringAndFormat(tempConfig);
  23035. if (!valid__isValid(tempConfig)) {
  23036. continue;
  23037. }
  23038. // if there is any input that was not parsed add a penalty for that format
  23039. currentScore += tempConfig._pf.charsLeftOver;
  23040. //or tokens
  23041. currentScore += tempConfig._pf.unusedTokens.length * 10;
  23042. tempConfig._pf.score = currentScore;
  23043. if (scoreToBeat == null || currentScore < scoreToBeat) {
  23044. scoreToBeat = currentScore;
  23045. bestMoment = tempConfig;
  23046. }
  23047. }
  23048. extend(config, bestMoment || tempConfig);
  23049. }
  23050. function configFromObject(config) {
  23051. if (config._d) {
  23052. return;
  23053. }
  23054. var i = normalizeObjectUnits(config._i);
  23055. config._a = [i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond];
  23056. configFromArray(config);
  23057. }
  23058. function createFromConfig (config) {
  23059. var input = config._i,
  23060. format = config._f,
  23061. res;
  23062. config._locale = config._locale || locales__getLocale(config._l);
  23063. if (input === null || (format === undefined && input === '')) {
  23064. return valid__createInvalid({nullInput: true});
  23065. }
  23066. if (typeof input === 'string') {
  23067. config._i = input = config._locale.preparse(input);
  23068. }
  23069. if (isMoment(input)) {
  23070. return new Moment(checkOverflow(input));
  23071. } else if (isArray(format)) {
  23072. configFromStringAndArray(config);
  23073. } else if (format) {
  23074. configFromStringAndFormat(config);
  23075. } else {
  23076. configFromInput(config);
  23077. }
  23078. res = new Moment(checkOverflow(config));
  23079. if (res._nextDay) {
  23080. // Adding is smart enough around DST
  23081. res.add(1, 'd');
  23082. res._nextDay = undefined;
  23083. }
  23084. return res;
  23085. }
  23086. function configFromInput(config) {
  23087. var input = config._i;
  23088. if (input === undefined) {
  23089. config._d = new Date();
  23090. } else if (isDate(input)) {
  23091. config._d = new Date(+input);
  23092. } else if (typeof input === 'string') {
  23093. configFromString(config);
  23094. } else if (isArray(input)) {
  23095. config._a = map(input.slice(0), function (obj) {
  23096. return parseInt(obj, 10);
  23097. });
  23098. configFromArray(config);
  23099. } else if (typeof(input) === 'object') {
  23100. configFromObject(config);
  23101. } else if (typeof(input) === 'number') {
  23102. // from milliseconds
  23103. config._d = new Date(input);
  23104. } else {
  23105. hooks__hooks.createFromInputFallback(config);
  23106. }
  23107. }
  23108. function createLocalOrUTC (input, format, locale, strict, isUTC) {
  23109. var c = {};
  23110. if (typeof(locale) === 'boolean') {
  23111. strict = locale;
  23112. locale = undefined;
  23113. }
  23114. // object construction must be done this way.
  23115. // https://github.com/moment/moment/issues/1423
  23116. c._isAMomentObject = true;
  23117. c._useUTC = c._isUTC = isUTC;
  23118. c._l = locale;
  23119. c._i = input;
  23120. c._f = format;
  23121. c._strict = strict;
  23122. c._pf = defaultParsingFlags();
  23123. return createFromConfig(c);
  23124. }
  23125. function local__createLocal (input, format, locale, strict) {
  23126. return createLocalOrUTC(input, format, locale, strict, false);
  23127. }
  23128. var prototypeMin = deprecate(
  23129. 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
  23130. function () {
  23131. var other = local__createLocal.apply(null, arguments);
  23132. return other < this ? this : other;
  23133. }
  23134. );
  23135. var prototypeMax = deprecate(
  23136. 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
  23137. function () {
  23138. var other = local__createLocal.apply(null, arguments);
  23139. return other > this ? this : other;
  23140. }
  23141. );
  23142. // Pick a moment m from moments so that m[fn](other) is true for all
  23143. // other. This relies on the function fn to be transitive.
  23144. //
  23145. // moments should either be an array of moment objects or an array, whose
  23146. // first element is an array of moment objects.
  23147. function pickBy(fn, moments) {
  23148. var res, i;
  23149. if (moments.length === 1 && isArray(moments[0])) {
  23150. moments = moments[0];
  23151. }
  23152. if (!moments.length) {
  23153. return local__createLocal();
  23154. }
  23155. res = moments[0];
  23156. for (i = 1; i < moments.length; ++i) {
  23157. if (moments[i][fn](res)) {
  23158. res = moments[i];
  23159. }
  23160. }
  23161. return res;
  23162. }
  23163. // TODO: Use [].sort instead?
  23164. function min () {
  23165. var args = [].slice.call(arguments, 0);
  23166. return pickBy('isBefore', args);
  23167. }
  23168. function max () {
  23169. var args = [].slice.call(arguments, 0);
  23170. return pickBy('isAfter', args);
  23171. }
  23172. function Duration (duration) {
  23173. var normalizedInput = normalizeObjectUnits(duration),
  23174. years = normalizedInput.year || 0,
  23175. quarters = normalizedInput.quarter || 0,
  23176. months = normalizedInput.month || 0,
  23177. weeks = normalizedInput.week || 0,
  23178. days = normalizedInput.day || 0,
  23179. hours = normalizedInput.hour || 0,
  23180. minutes = normalizedInput.minute || 0,
  23181. seconds = normalizedInput.second || 0,
  23182. milliseconds = normalizedInput.millisecond || 0;
  23183. // representation for dateAddRemove
  23184. this._milliseconds = +milliseconds +
  23185. seconds * 1e3 + // 1000
  23186. minutes * 6e4 + // 1000 * 60
  23187. hours * 36e5; // 1000 * 60 * 60
  23188. // Because of dateAddRemove treats 24 hours as different from a
  23189. // day when working around DST, we need to store them separately
  23190. this._days = +days +
  23191. weeks * 7;
  23192. // It is impossible translate months into days without knowing
  23193. // which months you are are talking about, so we have to store
  23194. // it separately.
  23195. this._months = +months +
  23196. quarters * 3 +
  23197. years * 12;
  23198. this._data = {};
  23199. this._locale = locales__getLocale();
  23200. this._bubble();
  23201. }
  23202. function isDuration (obj) {
  23203. return obj instanceof Duration;
  23204. }
  23205. function offset (token, separator) {
  23206. addFormatToken(token, 0, 0, function () {
  23207. var offset = this.utcOffset();
  23208. var sign = '+';
  23209. if (offset < 0) {
  23210. offset = -offset;
  23211. sign = '-';
  23212. }
  23213. return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
  23214. });
  23215. }
  23216. offset('Z', ':');
  23217. offset('ZZ', '');
  23218. // PARSING
  23219. addRegexToken('Z', matchOffset);
  23220. addRegexToken('ZZ', matchOffset);
  23221. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  23222. config._useUTC = true;
  23223. config._tzm = offsetFromString(input);
  23224. });
  23225. // HELPERS
  23226. // timezone chunker
  23227. // '+10:00' > ['10', '00']
  23228. // '-1530' > ['-15', '30']
  23229. var chunkOffset = /([\+\-]|\d\d)/gi;
  23230. function offsetFromString(string) {
  23231. var matches = ((string || '').match(matchOffset) || []);
  23232. var chunk = matches[matches.length - 1] || [];
  23233. var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  23234. var minutes = +(parts[1] * 60) + toInt(parts[2]);
  23235. return parts[0] === '+' ? minutes : -minutes;
  23236. }
  23237. // Return a moment from input, that is local/utc/zone equivalent to model.
  23238. function cloneWithOffset(input, model) {
  23239. var res, diff;
  23240. if (model._isUTC) {
  23241. res = model.clone();
  23242. diff = (isMoment(input) || isDate(input) ? +input : +local__createLocal(input)) - (+res);
  23243. // Use low-level api, because this fn is low-level api.
  23244. res._d.setTime(+res._d + diff);
  23245. hooks__hooks.updateOffset(res, false);
  23246. return res;
  23247. } else {
  23248. return local__createLocal(input).local();
  23249. }
  23250. return model._isUTC ? local__createLocal(input).zone(model._offset || 0) : local__createLocal(input).local();
  23251. }
  23252. function getDateOffset (m) {
  23253. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  23254. // https://github.com/moment/moment/pull/1871
  23255. return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
  23256. }
  23257. // HOOKS
  23258. // This function will be called whenever a moment is mutated.
  23259. // It is intended to keep the offset in sync with the timezone.
  23260. hooks__hooks.updateOffset = function () {};
  23261. // MOMENTS
  23262. // keepLocalTime = true means only change the timezone, without
  23263. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  23264. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  23265. // +0200, so we adjust the time as needed, to be valid.
  23266. //
  23267. // Keeping the time actually adds/subtracts (one hour)
  23268. // from the actual represented time. That is why we call updateOffset
  23269. // a second time. In case it wants us to change the offset again
  23270. // _changeInProgress == true case, then we have to adjust, because
  23271. // there is no such time in the given timezone.
  23272. function getSetOffset (input, keepLocalTime) {
  23273. var offset = this._offset || 0,
  23274. localAdjust;
  23275. if (input != null) {
  23276. if (typeof input === 'string') {
  23277. input = offsetFromString(input);
  23278. }
  23279. if (Math.abs(input) < 16) {
  23280. input = input * 60;
  23281. }
  23282. if (!this._isUTC && keepLocalTime) {
  23283. localAdjust = getDateOffset(this);
  23284. }
  23285. this._offset = input;
  23286. this._isUTC = true;
  23287. if (localAdjust != null) {
  23288. this.add(localAdjust, 'm');
  23289. }
  23290. if (offset !== input) {
  23291. if (!keepLocalTime || this._changeInProgress) {
  23292. add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false);
  23293. } else if (!this._changeInProgress) {
  23294. this._changeInProgress = true;
  23295. hooks__hooks.updateOffset(this, true);
  23296. this._changeInProgress = null;
  23297. }
  23298. }
  23299. return this;
  23300. } else {
  23301. return this._isUTC ? offset : getDateOffset(this);
  23302. }
  23303. }
  23304. function getSetZone (input, keepLocalTime) {
  23305. if (input != null) {
  23306. if (typeof input !== 'string') {
  23307. input = -input;
  23308. }
  23309. this.utcOffset(input, keepLocalTime);
  23310. return this;
  23311. } else {
  23312. return -this.utcOffset();
  23313. }
  23314. }
  23315. function setOffsetToUTC (keepLocalTime) {
  23316. return this.utcOffset(0, keepLocalTime);
  23317. }
  23318. function setOffsetToLocal (keepLocalTime) {
  23319. if (this._isUTC) {
  23320. this.utcOffset(0, keepLocalTime);
  23321. this._isUTC = false;
  23322. if (keepLocalTime) {
  23323. this.subtract(getDateOffset(this), 'm');
  23324. }
  23325. }
  23326. return this;
  23327. }
  23328. function setOffsetToParsedOffset () {
  23329. if (this._tzm) {
  23330. this.utcOffset(this._tzm);
  23331. } else if (typeof this._i === 'string') {
  23332. this.utcOffset(offsetFromString(this._i));
  23333. }
  23334. return this;
  23335. }
  23336. function hasAlignedHourOffset (input) {
  23337. if (!input) {
  23338. input = 0;
  23339. }
  23340. else {
  23341. input = local__createLocal(input).utcOffset();
  23342. }
  23343. return (this.utcOffset() - input) % 60 === 0;
  23344. }
  23345. function isDaylightSavingTime () {
  23346. return (
  23347. this.utcOffset() > this.clone().month(0).utcOffset() ||
  23348. this.utcOffset() > this.clone().month(5).utcOffset()
  23349. );
  23350. }
  23351. function isDaylightSavingTimeShifted () {
  23352. if (this._a) {
  23353. var other = this._isUTC ? utc__createUTC(this._a) : local__createLocal(this._a);
  23354. return this.isValid() && compareArrays(this._a, other.toArray()) > 0;
  23355. }
  23356. return false;
  23357. }
  23358. function isLocal () {
  23359. return !this._isUTC;
  23360. }
  23361. function isUtcOffset () {
  23362. return this._isUTC;
  23363. }
  23364. function isUtc () {
  23365. return this._isUTC && this._offset === 0;
  23366. }
  23367. var aspNetRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/;
  23368. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  23369. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  23370. var create__isoRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;
  23371. function create__createDuration (input, key) {
  23372. var duration = input,
  23373. // matching against regexp is expensive, do it on demand
  23374. match = null,
  23375. sign,
  23376. ret,
  23377. diffRes;
  23378. if (isDuration(input)) {
  23379. duration = {
  23380. ms : input._milliseconds,
  23381. d : input._days,
  23382. M : input._months
  23383. };
  23384. } else if (typeof input === 'number') {
  23385. duration = {};
  23386. if (key) {
  23387. duration[key] = input;
  23388. } else {
  23389. duration.milliseconds = input;
  23390. }
  23391. } else if (!!(match = aspNetRegex.exec(input))) {
  23392. sign = (match[1] === '-') ? -1 : 1;
  23393. duration = {
  23394. y : 0,
  23395. d : toInt(match[DATE]) * sign,
  23396. h : toInt(match[HOUR]) * sign,
  23397. m : toInt(match[MINUTE]) * sign,
  23398. s : toInt(match[SECOND]) * sign,
  23399. ms : toInt(match[MILLISECOND]) * sign
  23400. };
  23401. } else if (!!(match = create__isoRegex.exec(input))) {
  23402. sign = (match[1] === '-') ? -1 : 1;
  23403. duration = {
  23404. y : parseIso(match[2], sign),
  23405. M : parseIso(match[3], sign),
  23406. d : parseIso(match[4], sign),
  23407. h : parseIso(match[5], sign),
  23408. m : parseIso(match[6], sign),
  23409. s : parseIso(match[7], sign),
  23410. w : parseIso(match[8], sign)
  23411. };
  23412. } else if (duration == null) {// checks for null or undefined
  23413. duration = {};
  23414. } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
  23415. diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to));
  23416. duration = {};
  23417. duration.ms = diffRes.milliseconds;
  23418. duration.M = diffRes.months;
  23419. }
  23420. ret = new Duration(duration);
  23421. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  23422. ret._locale = input._locale;
  23423. }
  23424. return ret;
  23425. }
  23426. function parseIso (inp, sign) {
  23427. // We'd normally use ~~inp for this, but unfortunately it also
  23428. // converts floats to ints.
  23429. // inp may be undefined, so careful calling replace on it.
  23430. var res = inp && parseFloat(inp.replace(',', '.'));
  23431. // apply sign while we're at it
  23432. return (isNaN(res) ? 0 : res) * sign;
  23433. }
  23434. function positiveMomentsDifference(base, other) {
  23435. var res = {milliseconds: 0, months: 0};
  23436. res.months = other.month() - base.month() +
  23437. (other.year() - base.year()) * 12;
  23438. if (base.clone().add(res.months, 'M').isAfter(other)) {
  23439. --res.months;
  23440. }
  23441. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  23442. return res;
  23443. }
  23444. function momentsDifference(base, other) {
  23445. var res;
  23446. other = cloneWithOffset(other, base);
  23447. if (base.isBefore(other)) {
  23448. res = positiveMomentsDifference(base, other);
  23449. } else {
  23450. res = positiveMomentsDifference(other, base);
  23451. res.milliseconds = -res.milliseconds;
  23452. res.months = -res.months;
  23453. }
  23454. return res;
  23455. }
  23456. function createAdder(direction, name) {
  23457. return function (val, period) {
  23458. var dur, tmp;
  23459. //invert the arguments, but complain about it
  23460. if (period !== null && !isNaN(+period)) {
  23461. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
  23462. tmp = val; val = period; period = tmp;
  23463. }
  23464. val = typeof val === 'string' ? +val : val;
  23465. dur = create__createDuration(val, period);
  23466. add_subtract__addSubtract(this, dur, direction);
  23467. return this;
  23468. };
  23469. }
  23470. function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) {
  23471. var milliseconds = duration._milliseconds,
  23472. days = duration._days,
  23473. months = duration._months;
  23474. updateOffset = updateOffset == null ? true : updateOffset;
  23475. if (milliseconds) {
  23476. mom._d.setTime(+mom._d + milliseconds * isAdding);
  23477. }
  23478. if (days) {
  23479. get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding);
  23480. }
  23481. if (months) {
  23482. setMonth(mom, get_set__get(mom, 'Month') + months * isAdding);
  23483. }
  23484. if (updateOffset) {
  23485. hooks__hooks.updateOffset(mom, days || months);
  23486. }
  23487. }
  23488. var add_subtract__add = createAdder(1, 'add');
  23489. var add_subtract__subtract = createAdder(-1, 'subtract');
  23490. function calendar__calendar (time) {
  23491. // We want to compare the start of today, vs this.
  23492. // Getting start-of-today depends on whether we're local/utc/offset or not.
  23493. var now = time || local__createLocal(),
  23494. sod = cloneWithOffset(now, this).startOf('day'),
  23495. diff = this.diff(sod, 'days', true),
  23496. format = diff < -6 ? 'sameElse' :
  23497. diff < -1 ? 'lastWeek' :
  23498. diff < 0 ? 'lastDay' :
  23499. diff < 1 ? 'sameDay' :
  23500. diff < 2 ? 'nextDay' :
  23501. diff < 7 ? 'nextWeek' : 'sameElse';
  23502. return this.format(this.localeData().calendar(format, this, local__createLocal(now)));
  23503. }
  23504. function clone () {
  23505. return new Moment(this);
  23506. }
  23507. function isAfter (input, units) {
  23508. var inputMs;
  23509. units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
  23510. if (units === 'millisecond') {
  23511. input = isMoment(input) ? input : local__createLocal(input);
  23512. return +this > +input;
  23513. } else {
  23514. inputMs = isMoment(input) ? +input : +local__createLocal(input);
  23515. return inputMs < +this.clone().startOf(units);
  23516. }
  23517. }
  23518. function isBefore (input, units) {
  23519. var inputMs;
  23520. units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
  23521. if (units === 'millisecond') {
  23522. input = isMoment(input) ? input : local__createLocal(input);
  23523. return +this < +input;
  23524. } else {
  23525. inputMs = isMoment(input) ? +input : +local__createLocal(input);
  23526. return +this.clone().endOf(units) < inputMs;
  23527. }
  23528. }
  23529. function isBetween (from, to, units) {
  23530. return this.isAfter(from, units) && this.isBefore(to, units);
  23531. }
  23532. function isSame (input, units) {
  23533. var inputMs;
  23534. units = normalizeUnits(units || 'millisecond');
  23535. if (units === 'millisecond') {
  23536. input = isMoment(input) ? input : local__createLocal(input);
  23537. return +this === +input;
  23538. } else {
  23539. inputMs = +local__createLocal(input);
  23540. return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units));
  23541. }
  23542. }
  23543. function absFloor (number) {
  23544. if (number < 0) {
  23545. return Math.ceil(number);
  23546. } else {
  23547. return Math.floor(number);
  23548. }
  23549. }
  23550. function diff (input, units, asFloat) {
  23551. var that = cloneWithOffset(input, this),
  23552. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4,
  23553. delta, output;
  23554. units = normalizeUnits(units);
  23555. if (units === 'year' || units === 'month' || units === 'quarter') {
  23556. output = monthDiff(this, that);
  23557. if (units === 'quarter') {
  23558. output = output / 3;
  23559. } else if (units === 'year') {
  23560. output = output / 12;
  23561. }
  23562. } else {
  23563. delta = this - that;
  23564. output = units === 'second' ? delta / 1e3 : // 1000
  23565. units === 'minute' ? delta / 6e4 : // 1000 * 60
  23566. units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
  23567. units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  23568. units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  23569. delta;
  23570. }
  23571. return asFloat ? output : absFloor(output);
  23572. }
  23573. function monthDiff (a, b) {
  23574. // difference in months
  23575. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  23576. // b is in (anchor - 1 month, anchor + 1 month)
  23577. anchor = a.clone().add(wholeMonthDiff, 'months'),
  23578. anchor2, adjust;
  23579. if (b - anchor < 0) {
  23580. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  23581. // linear across the month
  23582. adjust = (b - anchor) / (anchor - anchor2);
  23583. } else {
  23584. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  23585. // linear across the month
  23586. adjust = (b - anchor) / (anchor2 - anchor);
  23587. }
  23588. return -(wholeMonthDiff + adjust);
  23589. }
  23590. hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  23591. function toString () {
  23592. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  23593. }
  23594. function moment_format__toISOString () {
  23595. var m = this.clone().utc();
  23596. if (0 < m.year() && m.year() <= 9999) {
  23597. if ('function' === typeof Date.prototype.toISOString) {
  23598. // native implementation is ~50x faster, use it when we can
  23599. return this.toDate().toISOString();
  23600. } else {
  23601. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  23602. }
  23603. } else {
  23604. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  23605. }
  23606. }
  23607. function format (inputString) {
  23608. var output = formatMoment(this, inputString || hooks__hooks.defaultFormat);
  23609. return this.localeData().postformat(output);
  23610. }
  23611. function from (time, withoutSuffix) {
  23612. return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  23613. }
  23614. function fromNow (withoutSuffix) {
  23615. return this.from(local__createLocal(), withoutSuffix);
  23616. }
  23617. function locale (key) {
  23618. var newLocaleData;
  23619. if (key === undefined) {
  23620. return this._locale._abbr;
  23621. } else {
  23622. newLocaleData = locales__getLocale(key);
  23623. if (newLocaleData != null) {
  23624. this._locale = newLocaleData;
  23625. }
  23626. return this;
  23627. }
  23628. }
  23629. var lang = deprecate(
  23630. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  23631. function (key) {
  23632. if (key === undefined) {
  23633. return this.localeData();
  23634. } else {
  23635. return this.locale(key);
  23636. }
  23637. }
  23638. );
  23639. function localeData () {
  23640. return this._locale;
  23641. }
  23642. function startOf (units) {
  23643. units = normalizeUnits(units);
  23644. // the following switch intentionally omits break keywords
  23645. // to utilize falling through the cases.
  23646. switch (units) {
  23647. case 'year':
  23648. this.month(0);
  23649. /* falls through */
  23650. case 'quarter':
  23651. case 'month':
  23652. this.date(1);
  23653. /* falls through */
  23654. case 'week':
  23655. case 'isoWeek':
  23656. case 'day':
  23657. this.hours(0);
  23658. /* falls through */
  23659. case 'hour':
  23660. this.minutes(0);
  23661. /* falls through */
  23662. case 'minute':
  23663. this.seconds(0);
  23664. /* falls through */
  23665. case 'second':
  23666. this.milliseconds(0);
  23667. /* falls through */
  23668. }
  23669. // weeks are a special case
  23670. if (units === 'week') {
  23671. this.weekday(0);
  23672. }
  23673. if (units === 'isoWeek') {
  23674. this.isoWeekday(1);
  23675. }
  23676. // quarters are also special
  23677. if (units === 'quarter') {
  23678. this.month(Math.floor(this.month() / 3) * 3);
  23679. }
  23680. return this;
  23681. }
  23682. function endOf (units) {
  23683. units = normalizeUnits(units);
  23684. if (units === undefined || units === 'millisecond') {
  23685. return this;
  23686. }
  23687. return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
  23688. }
  23689. function to_type__valueOf () {
  23690. return +this._d - ((this._offset || 0) * 60000);
  23691. }
  23692. function unix () {
  23693. return Math.floor(+this / 1000);
  23694. }
  23695. function toDate () {
  23696. return this._offset ? new Date(+this) : this._d;
  23697. }
  23698. function toArray () {
  23699. var m = this;
  23700. return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
  23701. }
  23702. function moment_valid__isValid () {
  23703. return valid__isValid(this);
  23704. }
  23705. function parsingFlags () {
  23706. return extend({}, this._pf);
  23707. }
  23708. function invalidAt () {
  23709. return this._pf.overflow;
  23710. }
  23711. addFormatToken(0, ['gg', 2], 0, function () {
  23712. return this.weekYear() % 100;
  23713. });
  23714. addFormatToken(0, ['GG', 2], 0, function () {
  23715. return this.isoWeekYear() % 100;
  23716. });
  23717. function addWeekYearFormatToken (token, getter) {
  23718. addFormatToken(0, [token, token.length], 0, getter);
  23719. }
  23720. addWeekYearFormatToken('gggg', 'weekYear');
  23721. addWeekYearFormatToken('ggggg', 'weekYear');
  23722. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  23723. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  23724. // ALIASES
  23725. addUnitAlias('weekYear', 'gg');
  23726. addUnitAlias('isoWeekYear', 'GG');
  23727. // PARSING
  23728. addRegexToken('G', matchSigned);
  23729. addRegexToken('g', matchSigned);
  23730. addRegexToken('GG', match1to2, match2);
  23731. addRegexToken('gg', match1to2, match2);
  23732. addRegexToken('GGGG', match1to4, match4);
  23733. addRegexToken('gggg', match1to4, match4);
  23734. addRegexToken('GGGGG', match1to6, match6);
  23735. addRegexToken('ggggg', match1to6, match6);
  23736. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
  23737. week[token.substr(0, 2)] = toInt(input);
  23738. });
  23739. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  23740. week[token] = hooks__hooks.parseTwoDigitYear(input);
  23741. });
  23742. // HELPERS
  23743. function weeksInYear(year, dow, doy) {
  23744. return weekOfYear(local__createLocal([year, 11, 31 + dow - doy]), dow, doy).week;
  23745. }
  23746. // MOMENTS
  23747. function getSetWeekYear (input) {
  23748. var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year;
  23749. return input == null ? year : this.add((input - year), 'y');
  23750. }
  23751. function getSetISOWeekYear (input) {
  23752. var year = weekOfYear(this, 1, 4).year;
  23753. return input == null ? year : this.add((input - year), 'y');
  23754. }
  23755. function getISOWeeksInYear () {
  23756. return weeksInYear(this.year(), 1, 4);
  23757. }
  23758. function getWeeksInYear () {
  23759. var weekInfo = this.localeData()._week;
  23760. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  23761. }
  23762. addFormatToken('Q', 0, 0, 'quarter');
  23763. // ALIASES
  23764. addUnitAlias('quarter', 'Q');
  23765. // PARSING
  23766. addRegexToken('Q', match1);
  23767. addParseToken('Q', function (input, array) {
  23768. array[MONTH] = (toInt(input) - 1) * 3;
  23769. });
  23770. // MOMENTS
  23771. function getSetQuarter (input) {
  23772. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  23773. }
  23774. addFormatToken('D', ['DD', 2], 'Do', 'date');
  23775. // ALIASES
  23776. addUnitAlias('date', 'D');
  23777. // PARSING
  23778. addRegexToken('D', match1to2);
  23779. addRegexToken('DD', match1to2, match2);
  23780. addRegexToken('Do', function (isStrict, locale) {
  23781. return isStrict ? locale._ordinalParse : locale._ordinalParseLenient;
  23782. });
  23783. addParseToken(['D', 'DD'], DATE);
  23784. addParseToken('Do', function (input, array) {
  23785. array[DATE] = toInt(input.match(match1to2)[0], 10);
  23786. });
  23787. // MOMENTS
  23788. var getSetDayOfMonth = makeGetSet('Date', true);
  23789. addFormatToken('d', 0, 'do', 'day');
  23790. addFormatToken('dd', 0, 0, function (format) {
  23791. return this.localeData().weekdaysMin(this, format);
  23792. });
  23793. addFormatToken('ddd', 0, 0, function (format) {
  23794. return this.localeData().weekdaysShort(this, format);
  23795. });
  23796. addFormatToken('dddd', 0, 0, function (format) {
  23797. return this.localeData().weekdays(this, format);
  23798. });
  23799. addFormatToken('e', 0, 0, 'weekday');
  23800. addFormatToken('E', 0, 0, 'isoWeekday');
  23801. // ALIASES
  23802. addUnitAlias('day', 'd');
  23803. addUnitAlias('weekday', 'e');
  23804. addUnitAlias('isoWeekday', 'E');
  23805. // PARSING
  23806. addRegexToken('d', match1to2);
  23807. addRegexToken('e', match1to2);
  23808. addRegexToken('E', match1to2);
  23809. addRegexToken('dd', matchWord);
  23810. addRegexToken('ddd', matchWord);
  23811. addRegexToken('dddd', matchWord);
  23812. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config) {
  23813. var weekday = config._locale.weekdaysParse(input);
  23814. // if we didn't get a weekday name, mark the date as invalid
  23815. if (weekday != null) {
  23816. week.d = weekday;
  23817. } else {
  23818. config._pf.invalidWeekday = input;
  23819. }
  23820. });
  23821. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  23822. week[token] = toInt(input);
  23823. });
  23824. // HELPERS
  23825. function parseWeekday(input, locale) {
  23826. if (typeof input === 'string') {
  23827. if (!isNaN(input)) {
  23828. input = parseInt(input, 10);
  23829. }
  23830. else {
  23831. input = locale.weekdaysParse(input);
  23832. if (typeof input !== 'number') {
  23833. return null;
  23834. }
  23835. }
  23836. }
  23837. return input;
  23838. }
  23839. // LOCALES
  23840. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
  23841. function localeWeekdays (m) {
  23842. return this._weekdays[m.day()];
  23843. }
  23844. var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
  23845. function localeWeekdaysShort (m) {
  23846. return this._weekdaysShort[m.day()];
  23847. }
  23848. var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
  23849. function localeWeekdaysMin (m) {
  23850. return this._weekdaysMin[m.day()];
  23851. }
  23852. function localeWeekdaysParse (weekdayName) {
  23853. var i, mom, regex;
  23854. if (!this._weekdaysParse) {
  23855. this._weekdaysParse = [];
  23856. }
  23857. for (i = 0; i < 7; i++) {
  23858. // make the regex if we don't have it already
  23859. if (!this._weekdaysParse[i]) {
  23860. mom = local__createLocal([2000, 1]).day(i);
  23861. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  23862. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  23863. }
  23864. // test the regex
  23865. if (this._weekdaysParse[i].test(weekdayName)) {
  23866. return i;
  23867. }
  23868. }
  23869. }
  23870. // MOMENTS
  23871. function getSetDayOfWeek (input) {
  23872. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  23873. if (input != null) {
  23874. input = parseWeekday(input, this.localeData());
  23875. return this.add(input - day, 'd');
  23876. } else {
  23877. return day;
  23878. }
  23879. }
  23880. function getSetLocaleDayOfWeek (input) {
  23881. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  23882. return input == null ? weekday : this.add(input - weekday, 'd');
  23883. }
  23884. function getSetISODayOfWeek (input) {
  23885. // behaves the same as moment#day except
  23886. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  23887. // as a setter, sunday should belong to the previous week.
  23888. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  23889. }
  23890. addFormatToken('H', ['HH', 2], 0, 'hour');
  23891. addFormatToken('h', ['hh', 2], 0, function () {
  23892. return this.hours() % 12 || 12;
  23893. });
  23894. function meridiem (token, lowercase) {
  23895. addFormatToken(token, 0, 0, function () {
  23896. return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
  23897. });
  23898. }
  23899. meridiem('a', true);
  23900. meridiem('A', false);
  23901. // ALIASES
  23902. addUnitAlias('hour', 'h');
  23903. // PARSING
  23904. function matchMeridiem (isStrict, locale) {
  23905. return locale._meridiemParse;
  23906. }
  23907. addRegexToken('a', matchMeridiem);
  23908. addRegexToken('A', matchMeridiem);
  23909. addRegexToken('H', match1to2);
  23910. addRegexToken('h', match1to2);
  23911. addRegexToken('HH', match1to2, match2);
  23912. addRegexToken('hh', match1to2, match2);
  23913. addParseToken(['H', 'HH'], HOUR);
  23914. addParseToken(['a', 'A'], function (input, array, config) {
  23915. config._isPm = config._locale.isPM(input);
  23916. config._meridiem = input;
  23917. });
  23918. addParseToken(['h', 'hh'], function (input, array, config) {
  23919. array[HOUR] = toInt(input);
  23920. config._pf.bigHour = true;
  23921. });
  23922. // LOCALES
  23923. function localeIsPM (input) {
  23924. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  23925. // Using charAt should be more compatible.
  23926. return ((input + '').toLowerCase().charAt(0) === 'p');
  23927. }
  23928. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
  23929. function localeMeridiem (hours, minutes, isLower) {
  23930. if (hours > 11) {
  23931. return isLower ? 'pm' : 'PM';
  23932. } else {
  23933. return isLower ? 'am' : 'AM';
  23934. }
  23935. }
  23936. // MOMENTS
  23937. // Setting the hour should keep the time, because the user explicitly
  23938. // specified which hour he wants. So trying to maintain the same hour (in
  23939. // a new timezone) makes sense. Adding/subtracting hours does not follow
  23940. // this rule.
  23941. var getSetHour = makeGetSet('Hours', true);
  23942. addFormatToken('m', ['mm', 2], 0, 'minute');
  23943. // ALIASES
  23944. addUnitAlias('minute', 'm');
  23945. // PARSING
  23946. addRegexToken('m', match1to2);
  23947. addRegexToken('mm', match1to2, match2);
  23948. addParseToken(['m', 'mm'], MINUTE);
  23949. // MOMENTS
  23950. var getSetMinute = makeGetSet('Minutes', false);
  23951. addFormatToken('s', ['ss', 2], 0, 'second');
  23952. // ALIASES
  23953. addUnitAlias('second', 's');
  23954. // PARSING
  23955. addRegexToken('s', match1to2);
  23956. addRegexToken('ss', match1to2, match2);
  23957. addParseToken(['s', 'ss'], SECOND);
  23958. // MOMENTS
  23959. var getSetSecond = makeGetSet('Seconds', false);
  23960. addFormatToken('S', 0, 0, function () {
  23961. return ~~(this.millisecond() / 100);
  23962. });
  23963. addFormatToken(0, ['SS', 2], 0, function () {
  23964. return ~~(this.millisecond() / 10);
  23965. });
  23966. function millisecond__milliseconds (token) {
  23967. addFormatToken(0, [token, 3], 0, 'millisecond');
  23968. }
  23969. millisecond__milliseconds('SSS');
  23970. millisecond__milliseconds('SSSS');
  23971. // ALIASES
  23972. addUnitAlias('millisecond', 'ms');
  23973. // PARSING
  23974. addRegexToken('S', match1to3, match1);
  23975. addRegexToken('SS', match1to3, match2);
  23976. addRegexToken('SSS', match1to3, match3);
  23977. addRegexToken('SSSS', matchUnsigned);
  23978. addParseToken(['S', 'SS', 'SSS', 'SSSS'], function (input, array) {
  23979. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  23980. });
  23981. // MOMENTS
  23982. var getSetMillisecond = makeGetSet('Milliseconds', false);
  23983. addFormatToken('z', 0, 0, 'zoneAbbr');
  23984. addFormatToken('zz', 0, 0, 'zoneName');
  23985. // MOMENTS
  23986. function getZoneAbbr () {
  23987. return this._isUTC ? 'UTC' : '';
  23988. }
  23989. function getZoneName () {
  23990. return this._isUTC ? 'Coordinated Universal Time' : '';
  23991. }
  23992. var momentPrototype__proto = Moment.prototype;
  23993. momentPrototype__proto.add = add_subtract__add;
  23994. momentPrototype__proto.calendar = calendar__calendar;
  23995. momentPrototype__proto.clone = clone;
  23996. momentPrototype__proto.diff = diff;
  23997. momentPrototype__proto.endOf = endOf;
  23998. momentPrototype__proto.format = format;
  23999. momentPrototype__proto.from = from;
  24000. momentPrototype__proto.fromNow = fromNow;
  24001. momentPrototype__proto.get = getSet;
  24002. momentPrototype__proto.invalidAt = invalidAt;
  24003. momentPrototype__proto.isAfter = isAfter;
  24004. momentPrototype__proto.isBefore = isBefore;
  24005. momentPrototype__proto.isBetween = isBetween;
  24006. momentPrototype__proto.isSame = isSame;
  24007. momentPrototype__proto.isValid = moment_valid__isValid;
  24008. momentPrototype__proto.lang = lang;
  24009. momentPrototype__proto.locale = locale;
  24010. momentPrototype__proto.localeData = localeData;
  24011. momentPrototype__proto.max = prototypeMax;
  24012. momentPrototype__proto.min = prototypeMin;
  24013. momentPrototype__proto.parsingFlags = parsingFlags;
  24014. momentPrototype__proto.set = getSet;
  24015. momentPrototype__proto.startOf = startOf;
  24016. momentPrototype__proto.subtract = add_subtract__subtract;
  24017. momentPrototype__proto.toArray = toArray;
  24018. momentPrototype__proto.toDate = toDate;
  24019. momentPrototype__proto.toISOString = moment_format__toISOString;
  24020. momentPrototype__proto.toJSON = moment_format__toISOString;
  24021. momentPrototype__proto.toString = toString;
  24022. momentPrototype__proto.unix = unix;
  24023. momentPrototype__proto.valueOf = to_type__valueOf;
  24024. // Year
  24025. momentPrototype__proto.year = getSetYear;
  24026. momentPrototype__proto.isLeapYear = getIsLeapYear;
  24027. // Week Year
  24028. momentPrototype__proto.weekYear = getSetWeekYear;
  24029. momentPrototype__proto.isoWeekYear = getSetISOWeekYear;
  24030. // Quarter
  24031. momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter;
  24032. // Month
  24033. momentPrototype__proto.month = getSetMonth;
  24034. momentPrototype__proto.daysInMonth = getDaysInMonth;
  24035. // Week
  24036. momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek;
  24037. momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek;
  24038. momentPrototype__proto.weeksInYear = getWeeksInYear;
  24039. momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear;
  24040. // Day
  24041. momentPrototype__proto.date = getSetDayOfMonth;
  24042. momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek;
  24043. momentPrototype__proto.weekday = getSetLocaleDayOfWeek;
  24044. momentPrototype__proto.isoWeekday = getSetISODayOfWeek;
  24045. momentPrototype__proto.dayOfYear = getSetDayOfYear;
  24046. // Hour
  24047. momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour;
  24048. // Minute
  24049. momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute;
  24050. // Second
  24051. momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond;
  24052. // Millisecond
  24053. momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond;
  24054. // Offset
  24055. momentPrototype__proto.utcOffset = getSetOffset;
  24056. momentPrototype__proto.utc = setOffsetToUTC;
  24057. momentPrototype__proto.local = setOffsetToLocal;
  24058. momentPrototype__proto.parseZone = setOffsetToParsedOffset;
  24059. momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset;
  24060. momentPrototype__proto.isDST = isDaylightSavingTime;
  24061. momentPrototype__proto.isDSTShifted = isDaylightSavingTimeShifted;
  24062. momentPrototype__proto.isLocal = isLocal;
  24063. momentPrototype__proto.isUtcOffset = isUtcOffset;
  24064. momentPrototype__proto.isUtc = isUtc;
  24065. momentPrototype__proto.isUTC = isUtc;
  24066. // Timezone
  24067. momentPrototype__proto.zoneAbbr = getZoneAbbr;
  24068. momentPrototype__proto.zoneName = getZoneName;
  24069. // Deprecations
  24070. momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
  24071. momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
  24072. momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
  24073. momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone);
  24074. var momentPrototype = momentPrototype__proto;
  24075. function moment__createUnix (input) {
  24076. return local__createLocal(input * 1000);
  24077. }
  24078. function moment__createInZone () {
  24079. return local__createLocal.apply(null, arguments).parseZone();
  24080. }
  24081. var defaultCalendar = {
  24082. sameDay : '[Today at] LT',
  24083. nextDay : '[Tomorrow at] LT',
  24084. nextWeek : 'dddd [at] LT',
  24085. lastDay : '[Yesterday at] LT',
  24086. lastWeek : '[Last] dddd [at] LT',
  24087. sameElse : 'L'
  24088. };
  24089. function locale_calendar__calendar (key, mom, now) {
  24090. var output = this._calendar[key];
  24091. return typeof output === 'function' ? output.call(mom, now) : output;
  24092. }
  24093. var defaultLongDateFormat = {
  24094. LTS : 'h:mm:ss A',
  24095. LT : 'h:mm A',
  24096. L : 'MM/DD/YYYY',
  24097. LL : 'MMMM D, YYYY',
  24098. LLL : 'MMMM D, YYYY LT',
  24099. LLLL : 'dddd, MMMM D, YYYY LT'
  24100. };
  24101. function longDateFormat (key) {
  24102. var output = this._longDateFormat[key];
  24103. if (!output && this._longDateFormat[key.toUpperCase()]) {
  24104. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  24105. return val.slice(1);
  24106. });
  24107. this._longDateFormat[key] = output;
  24108. }
  24109. return output;
  24110. }
  24111. var defaultInvalidDate = 'Invalid date';
  24112. function invalidDate () {
  24113. return this._invalidDate;
  24114. }
  24115. var defaultOrdinal = '%d';
  24116. var defaultOrdinalParse = /\d{1,2}/;
  24117. function ordinal (number) {
  24118. return this._ordinal.replace('%d', number);
  24119. }
  24120. function preParsePostFormat (string) {
  24121. return string;
  24122. }
  24123. var defaultRelativeTime = {
  24124. future : 'in %s',
  24125. past : '%s ago',
  24126. s : 'a few seconds',
  24127. m : 'a minute',
  24128. mm : '%d minutes',
  24129. h : 'an hour',
  24130. hh : '%d hours',
  24131. d : 'a day',
  24132. dd : '%d days',
  24133. M : 'a month',
  24134. MM : '%d months',
  24135. y : 'a year',
  24136. yy : '%d years'
  24137. };
  24138. function relative__relativeTime (number, withoutSuffix, string, isFuture) {
  24139. var output = this._relativeTime[string];
  24140. return (typeof output === 'function') ?
  24141. output(number, withoutSuffix, string, isFuture) :
  24142. output.replace(/%d/i, number);
  24143. }
  24144. function pastFuture (diff, output) {
  24145. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  24146. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  24147. }
  24148. function set__set (config) {
  24149. var prop, i;
  24150. for (i in config) {
  24151. prop = config[i];
  24152. if (typeof prop === 'function') {
  24153. this[i] = prop;
  24154. } else {
  24155. this['_' + i] = prop;
  24156. }
  24157. }
  24158. // Lenient ordinal parsing accepts just a number in addition to
  24159. // number + (possibly) stuff coming from _ordinalParseLenient.
  24160. this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source);
  24161. }
  24162. var prototype__proto = Locale.prototype;
  24163. prototype__proto._calendar = defaultCalendar;
  24164. prototype__proto.calendar = locale_calendar__calendar;
  24165. prototype__proto._longDateFormat = defaultLongDateFormat;
  24166. prototype__proto.longDateFormat = longDateFormat;
  24167. prototype__proto._invalidDate = defaultInvalidDate;
  24168. prototype__proto.invalidDate = invalidDate;
  24169. prototype__proto._ordinal = defaultOrdinal;
  24170. prototype__proto.ordinal = ordinal;
  24171. prototype__proto._ordinalParse = defaultOrdinalParse;
  24172. prototype__proto.preparse = preParsePostFormat;
  24173. prototype__proto.postformat = preParsePostFormat;
  24174. prototype__proto._relativeTime = defaultRelativeTime;
  24175. prototype__proto.relativeTime = relative__relativeTime;
  24176. prototype__proto.pastFuture = pastFuture;
  24177. prototype__proto.set = set__set;
  24178. // Month
  24179. prototype__proto.months = localeMonths;
  24180. prototype__proto._months = defaultLocaleMonths;
  24181. prototype__proto.monthsShort = localeMonthsShort;
  24182. prototype__proto._monthsShort = defaultLocaleMonthsShort;
  24183. prototype__proto.monthsParse = localeMonthsParse;
  24184. // Week
  24185. prototype__proto.week = localeWeek;
  24186. prototype__proto._week = defaultLocaleWeek;
  24187. prototype__proto.firstDayOfYear = localeFirstDayOfYear;
  24188. prototype__proto.firstDayOfWeek = localeFirstDayOfWeek;
  24189. // Day of Week
  24190. prototype__proto.weekdays = localeWeekdays;
  24191. prototype__proto._weekdays = defaultLocaleWeekdays;
  24192. prototype__proto.weekdaysMin = localeWeekdaysMin;
  24193. prototype__proto._weekdaysMin = defaultLocaleWeekdaysMin;
  24194. prototype__proto.weekdaysShort = localeWeekdaysShort;
  24195. prototype__proto._weekdaysShort = defaultLocaleWeekdaysShort;
  24196. prototype__proto.weekdaysParse = localeWeekdaysParse;
  24197. // Hours
  24198. prototype__proto.isPM = localeIsPM;
  24199. prototype__proto._meridiemParse = defaultLocaleMeridiemParse;
  24200. prototype__proto.meridiem = localeMeridiem;
  24201. function lists__get (format, index, field, setter) {
  24202. var locale = locales__getLocale();
  24203. var utc = utc__createUTC().set(setter, index);
  24204. return locale[field](utc, format);
  24205. }
  24206. function list (format, index, field, count, setter) {
  24207. if (typeof format === 'number') {
  24208. index = format;
  24209. format = undefined;
  24210. }
  24211. format = format || '';
  24212. if (index != null) {
  24213. return lists__get(format, index, field, setter);
  24214. }
  24215. var i;
  24216. var out = [];
  24217. for (i = 0; i < count; i++) {
  24218. out[i] = lists__get(format, i, field, setter);
  24219. }
  24220. return out;
  24221. }
  24222. function lists__listMonths (format, index) {
  24223. return list(format, index, 'months', 12, 'month');
  24224. }
  24225. function lists__listMonthsShort (format, index) {
  24226. return list(format, index, 'monthsShort', 12, 'month');
  24227. }
  24228. function lists__listWeekdays (format, index) {
  24229. return list(format, index, 'weekdays', 7, 'day');
  24230. }
  24231. function lists__listWeekdaysShort (format, index) {
  24232. return list(format, index, 'weekdaysShort', 7, 'day');
  24233. }
  24234. function lists__listWeekdaysMin (format, index) {
  24235. return list(format, index, 'weekdaysMin', 7, 'day');
  24236. }
  24237. locales__getSetGlobalLocale('en', {
  24238. ordinalParse: /\d{1,2}(th|st|nd|rd)/,
  24239. ordinal : function (number) {
  24240. var b = number % 10,
  24241. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  24242. (b === 1) ? 'st' :
  24243. (b === 2) ? 'nd' :
  24244. (b === 3) ? 'rd' : 'th';
  24245. return number + output;
  24246. }
  24247. });
  24248. // Side effect imports
  24249. hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locales__getSetGlobalLocale);
  24250. hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locales__getLocale);
  24251. var mathAbs = Math.abs;
  24252. function abs__abs () {
  24253. var data = this._data;
  24254. this._milliseconds = mathAbs(this._milliseconds);
  24255. this._days = mathAbs(this._days);
  24256. this._months = mathAbs(this._months);
  24257. data.milliseconds = mathAbs(data.milliseconds);
  24258. data.seconds = mathAbs(data.seconds);
  24259. data.minutes = mathAbs(data.minutes);
  24260. data.hours = mathAbs(data.hours);
  24261. data.months = mathAbs(data.months);
  24262. data.years = mathAbs(data.years);
  24263. return this;
  24264. }
  24265. function duration_add_subtract__addSubtract (duration, input, value, direction) {
  24266. var other = create__createDuration(input, value);
  24267. duration._milliseconds += direction * other._milliseconds;
  24268. duration._days += direction * other._days;
  24269. duration._months += direction * other._months;
  24270. return duration._bubble();
  24271. }
  24272. // supports only 2.0-style add(1, 's') or add(duration)
  24273. function duration_add_subtract__add (input, value) {
  24274. return duration_add_subtract__addSubtract(this, input, value, 1);
  24275. }
  24276. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  24277. function duration_add_subtract__subtract (input, value) {
  24278. return duration_add_subtract__addSubtract(this, input, value, -1);
  24279. }
  24280. function bubble () {
  24281. var milliseconds = this._milliseconds;
  24282. var days = this._days;
  24283. var months = this._months;
  24284. var data = this._data;
  24285. var seconds, minutes, hours, years = 0;
  24286. // The following code bubbles up values, see the tests for
  24287. // examples of what that means.
  24288. data.milliseconds = milliseconds % 1000;
  24289. seconds = absFloor(milliseconds / 1000);
  24290. data.seconds = seconds % 60;
  24291. minutes = absFloor(seconds / 60);
  24292. data.minutes = minutes % 60;
  24293. hours = absFloor(minutes / 60);
  24294. data.hours = hours % 24;
  24295. days += absFloor(hours / 24);
  24296. // Accurately convert days to years, assume start from year 0.
  24297. years = absFloor(daysToYears(days));
  24298. days -= absFloor(yearsToDays(years));
  24299. // 30 days to a month
  24300. // TODO (iskren): Use anchor date (like 1st Jan) to compute this.
  24301. months += absFloor(days / 30);
  24302. days %= 30;
  24303. // 12 months -> 1 year
  24304. years += absFloor(months / 12);
  24305. months %= 12;
  24306. data.days = days;
  24307. data.months = months;
  24308. data.years = years;
  24309. return this;
  24310. }
  24311. function daysToYears (days) {
  24312. // 400 years have 146097 days (taking into account leap year rules)
  24313. return days * 400 / 146097;
  24314. }
  24315. function yearsToDays (years) {
  24316. // years * 365 + absFloor(years / 4) -
  24317. // absFloor(years / 100) + absFloor(years / 400);
  24318. return years * 146097 / 400;
  24319. }
  24320. function as (units) {
  24321. var days;
  24322. var months;
  24323. var milliseconds = this._milliseconds;
  24324. units = normalizeUnits(units);
  24325. if (units === 'month' || units === 'year') {
  24326. days = this._days + milliseconds / 864e5;
  24327. months = this._months + daysToYears(days) * 12;
  24328. return units === 'month' ? months : months / 12;
  24329. } else {
  24330. // handle milliseconds separately because of floating point math errors (issue #1867)
  24331. days = this._days + Math.round(yearsToDays(this._months / 12));
  24332. switch (units) {
  24333. case 'week' : return days / 7 + milliseconds / 6048e5;
  24334. case 'day' : return days + milliseconds / 864e5;
  24335. case 'hour' : return days * 24 + milliseconds / 36e5;
  24336. case 'minute' : return days * 24 * 60 + milliseconds / 6e4;
  24337. case 'second' : return days * 24 * 60 * 60 + milliseconds / 1000;
  24338. // Math.floor prevents floating point math errors here
  24339. case 'millisecond': return Math.floor(days * 24 * 60 * 60 * 1000) + milliseconds;
  24340. default: throw new Error('Unknown unit ' + units);
  24341. }
  24342. }
  24343. }
  24344. // TODO: Use this.as('ms')?
  24345. function as__valueOf () {
  24346. return (
  24347. this._milliseconds +
  24348. this._days * 864e5 +
  24349. (this._months % 12) * 2592e6 +
  24350. toInt(this._months / 12) * 31536e6
  24351. );
  24352. }
  24353. function makeAs (alias) {
  24354. return function () {
  24355. return this.as(alias);
  24356. };
  24357. }
  24358. var asMilliseconds = makeAs('ms');
  24359. var asSeconds = makeAs('s');
  24360. var asMinutes = makeAs('m');
  24361. var asHours = makeAs('h');
  24362. var asDays = makeAs('d');
  24363. var asWeeks = makeAs('w');
  24364. var asMonths = makeAs('M');
  24365. var asYears = makeAs('y');
  24366. function get__get (units) {
  24367. units = normalizeUnits(units);
  24368. return this[units + 's']();
  24369. }
  24370. function makeGetter(name) {
  24371. return function () {
  24372. return this._data[name];
  24373. };
  24374. }
  24375. var get__milliseconds = makeGetter('milliseconds');
  24376. var seconds = makeGetter('seconds');
  24377. var minutes = makeGetter('minutes');
  24378. var hours = makeGetter('hours');
  24379. var days = makeGetter('days');
  24380. var months = makeGetter('months');
  24381. var years = makeGetter('years');
  24382. function weeks () {
  24383. return absFloor(this.days() / 7);
  24384. }
  24385. var round = Math.round;
  24386. var thresholds = {
  24387. s: 45, // seconds to minute
  24388. m: 45, // minutes to hour
  24389. h: 22, // hours to day
  24390. d: 26, // days to month
  24391. M: 11 // months to year
  24392. };
  24393. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  24394. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  24395. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  24396. }
  24397. function humanize__relativeTime (posNegDuration, withoutSuffix, locale) {
  24398. var duration = create__createDuration(posNegDuration).abs();
  24399. var seconds = round(duration.as('s'));
  24400. var minutes = round(duration.as('m'));
  24401. var hours = round(duration.as('h'));
  24402. var days = round(duration.as('d'));
  24403. var months = round(duration.as('M'));
  24404. var years = round(duration.as('y'));
  24405. var a = seconds < thresholds.s && ['s', seconds] ||
  24406. minutes === 1 && ['m'] ||
  24407. minutes < thresholds.m && ['mm', minutes] ||
  24408. hours === 1 && ['h'] ||
  24409. hours < thresholds.h && ['hh', hours] ||
  24410. days === 1 && ['d'] ||
  24411. days < thresholds.d && ['dd', days] ||
  24412. months === 1 && ['M'] ||
  24413. months < thresholds.M && ['MM', months] ||
  24414. years === 1 && ['y'] || ['yy', years];
  24415. a[2] = withoutSuffix;
  24416. a[3] = +posNegDuration > 0;
  24417. a[4] = locale;
  24418. return substituteTimeAgo.apply(null, a);
  24419. }
  24420. // This function allows you to set a threshold for relative time strings
  24421. function humanize__getSetRelativeTimeThreshold (threshold, limit) {
  24422. if (thresholds[threshold] === undefined) {
  24423. return false;
  24424. }
  24425. if (limit === undefined) {
  24426. return thresholds[threshold];
  24427. }
  24428. thresholds[threshold] = limit;
  24429. return true;
  24430. }
  24431. function humanize (withSuffix) {
  24432. var locale = this.localeData();
  24433. var output = humanize__relativeTime(this, !withSuffix, locale);
  24434. if (withSuffix) {
  24435. output = locale.pastFuture(+this, output);
  24436. }
  24437. return locale.postformat(output);
  24438. }
  24439. var iso_string__abs = Math.abs;
  24440. function iso_string__toISOString() {
  24441. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  24442. var Y = iso_string__abs(this.years());
  24443. var M = iso_string__abs(this.months());
  24444. var D = iso_string__abs(this.days());
  24445. var h = iso_string__abs(this.hours());
  24446. var m = iso_string__abs(this.minutes());
  24447. var s = iso_string__abs(this.seconds() + this.milliseconds() / 1000);
  24448. var total = this.asSeconds();
  24449. if (!total) {
  24450. // this is the same as C#'s (Noda) and python (isodate)...
  24451. // but not other JS (goog.date)
  24452. return 'P0D';
  24453. }
  24454. return (total < 0 ? '-' : '') +
  24455. 'P' +
  24456. (Y ? Y + 'Y' : '') +
  24457. (M ? M + 'M' : '') +
  24458. (D ? D + 'D' : '') +
  24459. ((h || m || s) ? 'T' : '') +
  24460. (h ? h + 'H' : '') +
  24461. (m ? m + 'M' : '') +
  24462. (s ? s + 'S' : '');
  24463. }
  24464. var duration_prototype__proto = Duration.prototype;
  24465. duration_prototype__proto.abs = abs__abs;
  24466. duration_prototype__proto.add = duration_add_subtract__add;
  24467. duration_prototype__proto.subtract = duration_add_subtract__subtract;
  24468. duration_prototype__proto.as = as;
  24469. duration_prototype__proto.asMilliseconds = asMilliseconds;
  24470. duration_prototype__proto.asSeconds = asSeconds;
  24471. duration_prototype__proto.asMinutes = asMinutes;
  24472. duration_prototype__proto.asHours = asHours;
  24473. duration_prototype__proto.asDays = asDays;
  24474. duration_prototype__proto.asWeeks = asWeeks;
  24475. duration_prototype__proto.asMonths = asMonths;
  24476. duration_prototype__proto.asYears = asYears;
  24477. duration_prototype__proto.valueOf = as__valueOf;
  24478. duration_prototype__proto._bubble = bubble;
  24479. duration_prototype__proto.get = get__get;
  24480. duration_prototype__proto.milliseconds = get__milliseconds;
  24481. duration_prototype__proto.seconds = seconds;
  24482. duration_prototype__proto.minutes = minutes;
  24483. duration_prototype__proto.hours = hours;
  24484. duration_prototype__proto.days = days;
  24485. duration_prototype__proto.weeks = weeks;
  24486. duration_prototype__proto.months = months;
  24487. duration_prototype__proto.years = years;
  24488. duration_prototype__proto.humanize = humanize;
  24489. duration_prototype__proto.toISOString = iso_string__toISOString;
  24490. duration_prototype__proto.toString = iso_string__toISOString;
  24491. duration_prototype__proto.toJSON = iso_string__toISOString;
  24492. duration_prototype__proto.locale = locale;
  24493. duration_prototype__proto.localeData = localeData;
  24494. // Deprecations
  24495. duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString);
  24496. duration_prototype__proto.lang = lang;
  24497. // Side effect imports
  24498. addFormatToken('X', 0, 0, 'unix');
  24499. addFormatToken('x', 0, 0, 'valueOf');
  24500. // PARSING
  24501. addRegexToken('x', matchSigned);
  24502. addRegexToken('X', matchTimestamp);
  24503. addParseToken('X', function (input, array, config) {
  24504. config._d = new Date(parseFloat(input, 10) * 1000);
  24505. });
  24506. addParseToken('x', function (input, array, config) {
  24507. config._d = new Date(toInt(input));
  24508. });
  24509. // Side effect imports
  24510. hooks__hooks.version = '2.10.0';
  24511. setHookCallback(local__createLocal);
  24512. hooks__hooks.fn = momentPrototype;
  24513. hooks__hooks.min = min;
  24514. hooks__hooks.max = max;
  24515. hooks__hooks.utc = utc__createUTC;
  24516. hooks__hooks.unix = moment__createUnix;
  24517. hooks__hooks.months = lists__listMonths;
  24518. hooks__hooks.isDate = isDate;
  24519. hooks__hooks.locale = locales__getSetGlobalLocale;
  24520. hooks__hooks.invalid = valid__createInvalid;
  24521. hooks__hooks.duration = create__createDuration;
  24522. hooks__hooks.isMoment = isMoment;
  24523. hooks__hooks.weekdays = lists__listWeekdays;
  24524. hooks__hooks.parseZone = moment__createInZone;
  24525. hooks__hooks.localeData = locales__getLocale;
  24526. hooks__hooks.isDuration = isDuration;
  24527. hooks__hooks.monthsShort = lists__listMonthsShort;
  24528. hooks__hooks.weekdaysMin = lists__listWeekdaysMin;
  24529. hooks__hooks.defineLocale = defineLocale;
  24530. hooks__hooks.weekdaysShort = lists__listWeekdaysShort;
  24531. hooks__hooks.normalizeUnits = normalizeUnits;
  24532. hooks__hooks.relativeTimeThreshold = humanize__getSetRelativeTimeThreshold;
  24533. var _moment = hooks__hooks;
  24534. return _moment;
  24535. }));
  24536. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(71)(module)))
  24537. /***/ },
  24538. /* 59 */
  24539. /***/ function(module, exports, __webpack_require__) {
  24540. var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v1.1.3 - 2014-05-20
  24541. * http://eightmedia.github.io/hammer.js
  24542. *
  24543. * Copyright (c) 2014 Jorik Tangelder <j.tangelder@gmail.com>;
  24544. * Licensed under the MIT license */
  24545. (function(window, undefined) {
  24546. 'use strict';
  24547. /**
  24548. * @main
  24549. * @module hammer
  24550. *
  24551. * @class Hammer
  24552. * @static
  24553. */
  24554. /**
  24555. * Hammer, use this to create instances
  24556. * ````
  24557. * var hammertime = new Hammer(myElement);
  24558. * ````
  24559. *
  24560. * @method Hammer
  24561. * @param {HTMLElement} element
  24562. * @param {Object} [options={}]
  24563. * @return {Hammer.Instance}
  24564. */
  24565. var Hammer = function Hammer(element, options) {
  24566. return new Hammer.Instance(element, options || {});
  24567. };
  24568. /**
  24569. * version, as defined in package.json
  24570. * the value will be set at each build
  24571. * @property VERSION
  24572. * @final
  24573. * @type {String}
  24574. */
  24575. Hammer.VERSION = '1.1.3';
  24576. /**
  24577. * default settings.
  24578. * more settings are defined per gesture at `/gestures`. Each gesture can be disabled/enabled
  24579. * by setting it's name (like `swipe`) to false.
  24580. * You can set the defaults for all instances by changing this object before creating an instance.
  24581. * @example
  24582. * ````
  24583. * Hammer.defaults.drag = false;
  24584. * Hammer.defaults.behavior.touchAction = 'pan-y';
  24585. * delete Hammer.defaults.behavior.userSelect;
  24586. * ````
  24587. * @property defaults
  24588. * @type {Object}
  24589. */
  24590. Hammer.defaults = {
  24591. /**
  24592. * this setting object adds styles and attributes to the element to prevent the browser from doing
  24593. * its native behavior. The css properties are auto prefixed for the browsers when needed.
  24594. * @property defaults.behavior
  24595. * @type {Object}
  24596. */
  24597. behavior: {
  24598. /**
  24599. * Disables text selection to improve the dragging gesture. When the value is `none` it also sets
  24600. * `onselectstart=false` for IE on the element. Mainly for desktop browsers.
  24601. * @property defaults.behavior.userSelect
  24602. * @type {String}
  24603. * @default 'none'
  24604. */
  24605. userSelect: 'none',
  24606. /**
  24607. * Specifies whether and how a given region can be manipulated by the user (for instance, by panning or zooming).
  24608. * Used by Chrome 35> and IE10>. By default this makes the element blocking any touch event.
  24609. * @property defaults.behavior.touchAction
  24610. * @type {String}
  24611. * @default: 'pan-y'
  24612. */
  24613. touchAction: 'pan-y',
  24614. /**
  24615. * Disables the default callout shown when you touch and hold a touch target.
  24616. * On iOS, when you touch and hold a touch target such as a link, Safari displays
  24617. * a callout containing information about the link. This property allows you to disable that callout.
  24618. * @property defaults.behavior.touchCallout
  24619. * @type {String}
  24620. * @default 'none'
  24621. */
  24622. touchCallout: 'none',
  24623. /**
  24624. * Specifies whether zooming is enabled. Used by IE10>
  24625. * @property defaults.behavior.contentZooming
  24626. * @type {String}
  24627. * @default 'none'
  24628. */
  24629. contentZooming: 'none',
  24630. /**
  24631. * Specifies that an entire element should be draggable instead of its contents.
  24632. * Mainly for desktop browsers.
  24633. * @property defaults.behavior.userDrag
  24634. * @type {String}
  24635. * @default 'none'
  24636. */
  24637. userDrag: 'none',
  24638. /**
  24639. * Overrides the highlight color shown when the user taps a link or a JavaScript
  24640. * clickable element in Safari on iPhone. This property obeys the alpha value, if specified.
  24641. *
  24642. * If you don't specify an alpha value, Safari on iPhone applies a default alpha value
  24643. * to the color. To disable tap highlighting, set the alpha value to 0 (invisible).
  24644. * If you set the alpha value to 1.0 (opaque), the element is not visible when tapped.
  24645. * @property defaults.behavior.tapHighlightColor
  24646. * @type {String}
  24647. * @default 'rgba(0,0,0,0)'
  24648. */
  24649. tapHighlightColor: 'rgba(0,0,0,0)'
  24650. }
  24651. };
  24652. /**
  24653. * hammer document where the base events are added at
  24654. * @property DOCUMENT
  24655. * @type {HTMLElement}
  24656. * @default window.document
  24657. */
  24658. Hammer.DOCUMENT = document;
  24659. /**
  24660. * detect support for pointer events
  24661. * @property HAS_POINTEREVENTS
  24662. * @type {Boolean}
  24663. */
  24664. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  24665. /**
  24666. * detect support for touch events
  24667. * @property HAS_TOUCHEVENTS
  24668. * @type {Boolean}
  24669. */
  24670. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  24671. /**
  24672. * detect mobile browsers
  24673. * @property IS_MOBILE
  24674. * @type {Boolean}
  24675. */
  24676. Hammer.IS_MOBILE = /mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent);
  24677. /**
  24678. * detect if we want to support mouseevents at all
  24679. * @property NO_MOUSEEVENTS
  24680. * @type {Boolean}
  24681. */
  24682. Hammer.NO_MOUSEEVENTS = (Hammer.HAS_TOUCHEVENTS && Hammer.IS_MOBILE) || Hammer.HAS_POINTEREVENTS;
  24683. /**
  24684. * interval in which Hammer recalculates current velocity/direction/angle in ms
  24685. * @property CALCULATE_INTERVAL
  24686. * @type {Number}
  24687. * @default 25
  24688. */
  24689. Hammer.CALCULATE_INTERVAL = 25;
  24690. /**
  24691. * eventtypes per touchevent (start, move, end) are filled by `Event.determineEventTypes` on `setup`
  24692. * the object contains the DOM event names per type (`EVENT_START`, `EVENT_MOVE`, `EVENT_END`)
  24693. * @property EVENT_TYPES
  24694. * @private
  24695. * @writeOnce
  24696. * @type {Object}
  24697. */
  24698. var EVENT_TYPES = {};
  24699. /**
  24700. * direction strings, for safe comparisons
  24701. * @property DIRECTION_DOWN|LEFT|UP|RIGHT
  24702. * @final
  24703. * @type {String}
  24704. * @default 'down' 'left' 'up' 'right'
  24705. */
  24706. var DIRECTION_DOWN = Hammer.DIRECTION_DOWN = 'down';
  24707. var DIRECTION_LEFT = Hammer.DIRECTION_LEFT = 'left';
  24708. var DIRECTION_UP = Hammer.DIRECTION_UP = 'up';
  24709. var DIRECTION_RIGHT = Hammer.DIRECTION_RIGHT = 'right';
  24710. /**
  24711. * pointertype strings, for safe comparisons
  24712. * @property POINTER_MOUSE|TOUCH|PEN
  24713. * @final
  24714. * @type {String}
  24715. * @default 'mouse' 'touch' 'pen'
  24716. */
  24717. var POINTER_MOUSE = Hammer.POINTER_MOUSE = 'mouse';
  24718. var POINTER_TOUCH = Hammer.POINTER_TOUCH = 'touch';
  24719. var POINTER_PEN = Hammer.POINTER_PEN = 'pen';
  24720. /**
  24721. * eventtypes
  24722. * @property EVENT_START|MOVE|END|RELEASE|TOUCH
  24723. * @final
  24724. * @type {String}
  24725. * @default 'start' 'change' 'move' 'end' 'release' 'touch'
  24726. */
  24727. var EVENT_START = Hammer.EVENT_START = 'start';
  24728. var EVENT_MOVE = Hammer.EVENT_MOVE = 'move';
  24729. var EVENT_END = Hammer.EVENT_END = 'end';
  24730. var EVENT_RELEASE = Hammer.EVENT_RELEASE = 'release';
  24731. var EVENT_TOUCH = Hammer.EVENT_TOUCH = 'touch';
  24732. /**
  24733. * if the window events are set...
  24734. * @property READY
  24735. * @writeOnce
  24736. * @type {Boolean}
  24737. * @default false
  24738. */
  24739. Hammer.READY = false;
  24740. /**
  24741. * plugins namespace
  24742. * @property plugins
  24743. * @type {Object}
  24744. */
  24745. Hammer.plugins = Hammer.plugins || {};
  24746. /**
  24747. * gestures namespace
  24748. * see `/gestures` for the definitions
  24749. * @property gestures
  24750. * @type {Object}
  24751. */
  24752. Hammer.gestures = Hammer.gestures || {};
  24753. /**
  24754. * setup events to detect gestures on the document
  24755. * this function is called when creating an new instance
  24756. * @private
  24757. */
  24758. function setup() {
  24759. if(Hammer.READY) {
  24760. return;
  24761. }
  24762. // find what eventtypes we add listeners to
  24763. Event.determineEventTypes();
  24764. // Register all gestures inside Hammer.gestures
  24765. Utils.each(Hammer.gestures, function(gesture) {
  24766. Detection.register(gesture);
  24767. });
  24768. // Add touch events on the document
  24769. Event.onTouch(Hammer.DOCUMENT, EVENT_MOVE, Detection.detect);
  24770. Event.onTouch(Hammer.DOCUMENT, EVENT_END, Detection.detect);
  24771. // Hammer is ready...!
  24772. Hammer.READY = true;
  24773. }
  24774. /**
  24775. * @module hammer
  24776. *
  24777. * @class Utils
  24778. * @static
  24779. */
  24780. var Utils = Hammer.utils = {
  24781. /**
  24782. * extend method, could also be used for cloning when `dest` is an empty object.
  24783. * changes the dest object
  24784. * @method extend
  24785. * @param {Object} dest
  24786. * @param {Object} src
  24787. * @param {Boolean} [merge=false] do a merge
  24788. * @return {Object} dest
  24789. */
  24790. extend: function extend(dest, src, merge) {
  24791. for(var key in src) {
  24792. if(!src.hasOwnProperty(key) || (dest[key] !== undefined && merge)) {
  24793. continue;
  24794. }
  24795. dest[key] = src[key];
  24796. }
  24797. return dest;
  24798. },
  24799. /**
  24800. * simple addEventListener wrapper
  24801. * @method on
  24802. * @param {HTMLElement} element
  24803. * @param {String} type
  24804. * @param {Function} handler
  24805. */
  24806. on: function on(element, type, handler) {
  24807. element.addEventListener(type, handler, false);
  24808. },
  24809. /**
  24810. * simple removeEventListener wrapper
  24811. * @method off
  24812. * @param {HTMLElement} element
  24813. * @param {String} type
  24814. * @param {Function} handler
  24815. */
  24816. off: function off(element, type, handler) {
  24817. element.removeEventListener(type, handler, false);
  24818. },
  24819. /**
  24820. * forEach over arrays and objects
  24821. * @method each
  24822. * @param {Object|Array} obj
  24823. * @param {Function} iterator
  24824. * @param {any} iterator.item
  24825. * @param {Number} iterator.index
  24826. * @param {Object|Array} iterator.obj the source object
  24827. * @param {Object} context value to use as `this` in the iterator
  24828. */
  24829. each: function each(obj, iterator, context) {
  24830. var i, len;
  24831. // native forEach on arrays
  24832. if('forEach' in obj) {
  24833. obj.forEach(iterator, context);
  24834. // arrays
  24835. } else if(obj.length !== undefined) {
  24836. for(i = 0, len = obj.length; i < len; i++) {
  24837. if(iterator.call(context, obj[i], i, obj) === false) {
  24838. return;
  24839. }
  24840. }
  24841. // objects
  24842. } else {
  24843. for(i in obj) {
  24844. if(obj.hasOwnProperty(i) &&
  24845. iterator.call(context, obj[i], i, obj) === false) {
  24846. return;
  24847. }
  24848. }
  24849. }
  24850. },
  24851. /**
  24852. * find if a string contains the string using indexOf
  24853. * @method inStr
  24854. * @param {String} src
  24855. * @param {String} find
  24856. * @return {Boolean} found
  24857. */
  24858. inStr: function inStr(src, find) {
  24859. return src.indexOf(find) > -1;
  24860. },
  24861. /**
  24862. * find if a array contains the object using indexOf or a simple polyfill
  24863. * @method inArray
  24864. * @param {String} src
  24865. * @param {String} find
  24866. * @return {Boolean|Number} false when not found, or the index
  24867. */
  24868. inArray: function inArray(src, find) {
  24869. if(src.indexOf) {
  24870. var index = src.indexOf(find);
  24871. return (index === -1) ? false : index;
  24872. } else {
  24873. for(var i = 0, len = src.length; i < len; i++) {
  24874. if(src[i] === find) {
  24875. return i;
  24876. }
  24877. }
  24878. return false;
  24879. }
  24880. },
  24881. /**
  24882. * convert an array-like object (`arguments`, `touchlist`) to an array
  24883. * @method toArray
  24884. * @param {Object} obj
  24885. * @return {Array}
  24886. */
  24887. toArray: function toArray(obj) {
  24888. return Array.prototype.slice.call(obj, 0);
  24889. },
  24890. /**
  24891. * find if a node is in the given parent
  24892. * @method hasParent
  24893. * @param {HTMLElement} node
  24894. * @param {HTMLElement} parent
  24895. * @return {Boolean} found
  24896. */
  24897. hasParent: function hasParent(node, parent) {
  24898. while(node) {
  24899. if(node == parent) {
  24900. return true;
  24901. }
  24902. node = node.parentNode;
  24903. }
  24904. return false;
  24905. },
  24906. /**
  24907. * get the center of all the touches
  24908. * @method getCenter
  24909. * @param {Array} touches
  24910. * @return {Object} center contains `pageX`, `pageY`, `clientX` and `clientY` properties
  24911. */
  24912. getCenter: function getCenter(touches) {
  24913. var pageX = [],
  24914. pageY = [],
  24915. clientX = [],
  24916. clientY = [],
  24917. min = Math.min,
  24918. max = Math.max;
  24919. // no need to loop when only one touch
  24920. if(touches.length === 1) {
  24921. return {
  24922. pageX: touches[0].pageX,
  24923. pageY: touches[0].pageY,
  24924. clientX: touches[0].clientX,
  24925. clientY: touches[0].clientY
  24926. };
  24927. }
  24928. Utils.each(touches, function(touch) {
  24929. pageX.push(touch.pageX);
  24930. pageY.push(touch.pageY);
  24931. clientX.push(touch.clientX);
  24932. clientY.push(touch.clientY);
  24933. });
  24934. return {
  24935. pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2,
  24936. pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2,
  24937. clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2,
  24938. clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2
  24939. };
  24940. },
  24941. /**
  24942. * calculate the velocity between two points. unit is in px per ms.
  24943. * @method getVelocity
  24944. * @param {Number} deltaTime
  24945. * @param {Number} deltaX
  24946. * @param {Number} deltaY
  24947. * @return {Object} velocity `x` and `y`
  24948. */
  24949. getVelocity: function getVelocity(deltaTime, deltaX, deltaY) {
  24950. return {
  24951. x: Math.abs(deltaX / deltaTime) || 0,
  24952. y: Math.abs(deltaY / deltaTime) || 0
  24953. };
  24954. },
  24955. /**
  24956. * calculate the angle between two coordinates
  24957. * @method getAngle
  24958. * @param {Touch} touch1
  24959. * @param {Touch} touch2
  24960. * @return {Number} angle
  24961. */
  24962. getAngle: function getAngle(touch1, touch2) {
  24963. var x = touch2.clientX - touch1.clientX,
  24964. y = touch2.clientY - touch1.clientY;
  24965. return Math.atan2(y, x) * 180 / Math.PI;
  24966. },
  24967. /**
  24968. * do a small comparision to get the direction between two touches.
  24969. * @method getDirection
  24970. * @param {Touch} touch1
  24971. * @param {Touch} touch2
  24972. * @return {String} direction matches `DIRECTION_LEFT|RIGHT|UP|DOWN`
  24973. */
  24974. getDirection: function getDirection(touch1, touch2) {
  24975. var x = Math.abs(touch1.clientX - touch2.clientX),
  24976. y = Math.abs(touch1.clientY - touch2.clientY);
  24977. if(x >= y) {
  24978. return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  24979. }
  24980. return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN;
  24981. },
  24982. /**
  24983. * calculate the distance between two touches
  24984. * @method getDistance
  24985. * @param {Touch}touch1
  24986. * @param {Touch} touch2
  24987. * @return {Number} distance
  24988. */
  24989. getDistance: function getDistance(touch1, touch2) {
  24990. var x = touch2.clientX - touch1.clientX,
  24991. y = touch2.clientY - touch1.clientY;
  24992. return Math.sqrt((x * x) + (y * y));
  24993. },
  24994. /**
  24995. * calculate the scale factor between two touchLists
  24996. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  24997. * @method getScale
  24998. * @param {Array} start array of touches
  24999. * @param {Array} end array of touches
  25000. * @return {Number} scale
  25001. */
  25002. getScale: function getScale(start, end) {
  25003. // need two fingers...
  25004. if(start.length >= 2 && end.length >= 2) {
  25005. return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]);
  25006. }
  25007. return 1;
  25008. },
  25009. /**
  25010. * calculate the rotation degrees between two touchLists
  25011. * @method getRotation
  25012. * @param {Array} start array of touches
  25013. * @param {Array} end array of touches
  25014. * @return {Number} rotation
  25015. */
  25016. getRotation: function getRotation(start, end) {
  25017. // need two fingers
  25018. if(start.length >= 2 && end.length >= 2) {
  25019. return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]);
  25020. }
  25021. return 0;
  25022. },
  25023. /**
  25024. * find out if the direction is vertical *
  25025. * @method isVertical
  25026. * @param {String} direction matches `DIRECTION_UP|DOWN`
  25027. * @return {Boolean} is_vertical
  25028. */
  25029. isVertical: function isVertical(direction) {
  25030. return direction == DIRECTION_UP || direction == DIRECTION_DOWN;
  25031. },
  25032. /**
  25033. * set css properties with their prefixes
  25034. * @param {HTMLElement} element
  25035. * @param {String} prop
  25036. * @param {String} value
  25037. * @param {Boolean} [toggle=true]
  25038. * @return {Boolean}
  25039. */
  25040. setPrefixedCss: function setPrefixedCss(element, prop, value, toggle) {
  25041. var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms'];
  25042. prop = Utils.toCamelCase(prop);
  25043. for(var i = 0; i < prefixes.length; i++) {
  25044. var p = prop;
  25045. // prefixes
  25046. if(prefixes[i]) {
  25047. p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1);
  25048. }
  25049. // test the style
  25050. if(p in element.style) {
  25051. element.style[p] = (toggle == null || toggle) && value || '';
  25052. break;
  25053. }
  25054. }
  25055. },
  25056. /**
  25057. * toggle browser default behavior by setting css properties.
  25058. * `userSelect='none'` also sets `element.onselectstart` to false
  25059. * `userDrag='none'` also sets `element.ondragstart` to false
  25060. *
  25061. * @method toggleBehavior
  25062. * @param {HtmlElement} element
  25063. * @param {Object} props
  25064. * @param {Boolean} [toggle=true]
  25065. */
  25066. toggleBehavior: function toggleBehavior(element, props, toggle) {
  25067. if(!props || !element || !element.style) {
  25068. return;
  25069. }
  25070. // set the css properties
  25071. Utils.each(props, function(value, prop) {
  25072. Utils.setPrefixedCss(element, prop, value, toggle);
  25073. });
  25074. var falseFn = toggle && function() {
  25075. return false;
  25076. };
  25077. // also the disable onselectstart
  25078. if(props.userSelect == 'none') {
  25079. element.onselectstart = falseFn;
  25080. }
  25081. // and disable ondragstart
  25082. if(props.userDrag == 'none') {
  25083. element.ondragstart = falseFn;
  25084. }
  25085. },
  25086. /**
  25087. * convert a string with underscores to camelCase
  25088. * so prevent_default becomes preventDefault
  25089. * @param {String} str
  25090. * @return {String} camelCaseStr
  25091. */
  25092. toCamelCase: function toCamelCase(str) {
  25093. return str.replace(/[_-]([a-z])/g, function(s) {
  25094. return s[1].toUpperCase();
  25095. });
  25096. }
  25097. };
  25098. /**
  25099. * @module hammer
  25100. */
  25101. /**
  25102. * @class Event
  25103. * @static
  25104. */
  25105. var Event = Hammer.event = {
  25106. /**
  25107. * when touch events have been fired, this is true
  25108. * this is used to stop mouse events
  25109. * @property prevent_mouseevents
  25110. * @private
  25111. * @type {Boolean}
  25112. */
  25113. preventMouseEvents: false,
  25114. /**
  25115. * if EVENT_START has been fired
  25116. * @property started
  25117. * @private
  25118. * @type {Boolean}
  25119. */
  25120. started: false,
  25121. /**
  25122. * when the mouse is hold down, this is true
  25123. * @property should_detect
  25124. * @private
  25125. * @type {Boolean}
  25126. */
  25127. shouldDetect: false,
  25128. /**
  25129. * simple event binder with a hook and support for multiple types
  25130. * @method on
  25131. * @param {HTMLElement} element
  25132. * @param {String} type
  25133. * @param {Function} handler
  25134. * @param {Function} [hook]
  25135. * @param {Object} hook.type
  25136. */
  25137. on: function on(element, type, handler, hook) {
  25138. var types = type.split(' ');
  25139. Utils.each(types, function(type) {
  25140. Utils.on(element, type, handler);
  25141. hook && hook(type);
  25142. });
  25143. },
  25144. /**
  25145. * simple event unbinder with a hook and support for multiple types
  25146. * @method off
  25147. * @param {HTMLElement} element
  25148. * @param {String} type
  25149. * @param {Function} handler
  25150. * @param {Function} [hook]
  25151. * @param {Object} hook.type
  25152. */
  25153. off: function off(element, type, handler, hook) {
  25154. var types = type.split(' ');
  25155. Utils.each(types, function(type) {
  25156. Utils.off(element, type, handler);
  25157. hook && hook(type);
  25158. });
  25159. },
  25160. /**
  25161. * the core touch event handler.
  25162. * this finds out if we should to detect gestures
  25163. * @method onTouch
  25164. * @param {HTMLElement} element
  25165. * @param {String} eventType matches `EVENT_START|MOVE|END`
  25166. * @param {Function} handler
  25167. * @return onTouchHandler {Function} the core event handler
  25168. */
  25169. onTouch: function onTouch(element, eventType, handler) {
  25170. var self = this;
  25171. var onTouchHandler = function onTouchHandler(ev) {
  25172. var srcType = ev.type.toLowerCase(),
  25173. isPointer = Hammer.HAS_POINTEREVENTS,
  25174. isMouse = Utils.inStr(srcType, 'mouse'),
  25175. triggerType;
  25176. // if we are in a mouseevent, but there has been a touchevent triggered in this session
  25177. // we want to do nothing. simply break out of the event.
  25178. if(isMouse && self.preventMouseEvents) {
  25179. return;
  25180. // mousebutton must be down
  25181. } else if(isMouse && eventType == EVENT_START && ev.button === 0) {
  25182. self.preventMouseEvents = false;
  25183. self.shouldDetect = true;
  25184. } else if(isPointer && eventType == EVENT_START) {
  25185. self.shouldDetect = (ev.buttons === 1 || PointerEvent.matchType(POINTER_TOUCH, ev));
  25186. // just a valid start event, but no mouse
  25187. } else if(!isMouse && eventType == EVENT_START) {
  25188. self.preventMouseEvents = true;
  25189. self.shouldDetect = true;
  25190. }
  25191. // update the pointer event before entering the detection
  25192. if(isPointer && eventType != EVENT_END) {
  25193. PointerEvent.updatePointer(eventType, ev);
  25194. }
  25195. // we are in a touch/down state, so allowed detection of gestures
  25196. if(self.shouldDetect) {
  25197. triggerType = self.doDetect.call(self, ev, eventType, element, handler);
  25198. }
  25199. // ...and we are done with the detection
  25200. // so reset everything to start each detection totally fresh
  25201. if(triggerType == EVENT_END) {
  25202. self.preventMouseEvents = false;
  25203. self.shouldDetect = false;
  25204. PointerEvent.reset();
  25205. // update the pointerevent object after the detection
  25206. }
  25207. if(isPointer && eventType == EVENT_END) {
  25208. PointerEvent.updatePointer(eventType, ev);
  25209. }
  25210. };
  25211. this.on(element, EVENT_TYPES[eventType], onTouchHandler);
  25212. return onTouchHandler;
  25213. },
  25214. /**
  25215. * the core detection method
  25216. * this finds out what hammer-touch-events to trigger
  25217. * @method doDetect
  25218. * @param {Object} ev
  25219. * @param {String} eventType matches `EVENT_START|MOVE|END`
  25220. * @param {HTMLElement} element
  25221. * @param {Function} handler
  25222. * @return {String} triggerType matches `EVENT_START|MOVE|END`
  25223. */
  25224. doDetect: function doDetect(ev, eventType, element, handler) {
  25225. var touchList = this.getTouchList(ev, eventType);
  25226. var touchListLength = touchList.length;
  25227. var triggerType = eventType;
  25228. var triggerChange = touchList.trigger; // used by fakeMultitouch plugin
  25229. var changedLength = touchListLength;
  25230. // at each touchstart-like event we want also want to trigger a TOUCH event...
  25231. if(eventType == EVENT_START) {
  25232. triggerChange = EVENT_TOUCH;
  25233. // ...the same for a touchend-like event
  25234. } else if(eventType == EVENT_END) {
  25235. triggerChange = EVENT_RELEASE;
  25236. // keep track of how many touches have been removed
  25237. changedLength = touchList.length - ((ev.changedTouches) ? ev.changedTouches.length : 1);
  25238. }
  25239. // after there are still touches on the screen,
  25240. // we just want to trigger a MOVE event. so change the START or END to a MOVE
  25241. // but only after detection has been started, the first time we actualy want a START
  25242. if(changedLength > 0 && this.started) {
  25243. triggerType = EVENT_MOVE;
  25244. }
  25245. // detection has been started, we keep track of this, see above
  25246. this.started = true;
  25247. // generate some event data, some basic information
  25248. var evData = this.collectEventData(element, triggerType, touchList, ev);
  25249. // trigger the triggerType event before the change (TOUCH, RELEASE) events
  25250. // but the END event should be at last
  25251. if(eventType != EVENT_END) {
  25252. handler.call(Detection, evData);
  25253. }
  25254. // trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed
  25255. if(triggerChange) {
  25256. evData.changedLength = changedLength;
  25257. evData.eventType = triggerChange;
  25258. handler.call(Detection, evData);
  25259. evData.eventType = triggerType;
  25260. delete evData.changedLength;
  25261. }
  25262. // trigger the END event
  25263. if(triggerType == EVENT_END) {
  25264. handler.call(Detection, evData);
  25265. // ...and we are done with the detection
  25266. // so reset everything to start each detection totally fresh
  25267. this.started = false;
  25268. }
  25269. return triggerType;
  25270. },
  25271. /**
  25272. * we have different events for each device/browser
  25273. * determine what we need and set them in the EVENT_TYPES constant
  25274. * the `onTouch` method is bind to these properties.
  25275. * @method determineEventTypes
  25276. * @return {Object} events
  25277. */
  25278. determineEventTypes: function determineEventTypes() {
  25279. var types;
  25280. if(Hammer.HAS_POINTEREVENTS) {
  25281. if(window.PointerEvent) {
  25282. types = [
  25283. 'pointerdown',
  25284. 'pointermove',
  25285. 'pointerup pointercancel lostpointercapture'
  25286. ];
  25287. } else {
  25288. types = [
  25289. 'MSPointerDown',
  25290. 'MSPointerMove',
  25291. 'MSPointerUp MSPointerCancel MSLostPointerCapture'
  25292. ];
  25293. }
  25294. } else if(Hammer.NO_MOUSEEVENTS) {
  25295. types = [
  25296. 'touchstart',
  25297. 'touchmove',
  25298. 'touchend touchcancel'
  25299. ];
  25300. } else {
  25301. types = [
  25302. 'touchstart mousedown',
  25303. 'touchmove mousemove',
  25304. 'touchend touchcancel mouseup'
  25305. ];
  25306. }
  25307. EVENT_TYPES[EVENT_START] = types[0];
  25308. EVENT_TYPES[EVENT_MOVE] = types[1];
  25309. EVENT_TYPES[EVENT_END] = types[2];
  25310. return EVENT_TYPES;
  25311. },
  25312. /**
  25313. * create touchList depending on the event
  25314. * @method getTouchList
  25315. * @param {Object} ev
  25316. * @param {String} eventType
  25317. * @return {Array} touches
  25318. */
  25319. getTouchList: function getTouchList(ev, eventType) {
  25320. // get the fake pointerEvent touchlist
  25321. if(Hammer.HAS_POINTEREVENTS) {
  25322. return PointerEvent.getTouchList();
  25323. }
  25324. // get the touchlist
  25325. if(ev.touches) {
  25326. if(eventType == EVENT_MOVE) {
  25327. return ev.touches;
  25328. }
  25329. var identifiers = [];
  25330. var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches));
  25331. var touchList = [];
  25332. Utils.each(concat, function(touch) {
  25333. if(Utils.inArray(identifiers, touch.identifier) === false) {
  25334. touchList.push(touch);
  25335. }
  25336. identifiers.push(touch.identifier);
  25337. });
  25338. return touchList;
  25339. }
  25340. // make fake touchList from mouse position
  25341. ev.identifier = 1;
  25342. return [ev];
  25343. },
  25344. /**
  25345. * collect basic event data
  25346. * @method collectEventData
  25347. * @param {HTMLElement} element
  25348. * @param {String} eventType matches `EVENT_START|MOVE|END`
  25349. * @param {Array} touches
  25350. * @param {Object} ev
  25351. * @return {Object} ev
  25352. */
  25353. collectEventData: function collectEventData(element, eventType, touches, ev) {
  25354. // find out pointerType
  25355. var pointerType = POINTER_TOUCH;
  25356. if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) {
  25357. pointerType = POINTER_MOUSE;
  25358. } else if(PointerEvent.matchType(POINTER_PEN, ev)) {
  25359. pointerType = POINTER_PEN;
  25360. }
  25361. return {
  25362. center: Utils.getCenter(touches),
  25363. timeStamp: Date.now(),
  25364. target: ev.target,
  25365. touches: touches,
  25366. eventType: eventType,
  25367. pointerType: pointerType,
  25368. srcEvent: ev,
  25369. /**
  25370. * prevent the browser default actions
  25371. * mostly used to disable scrolling of the browser
  25372. */
  25373. preventDefault: function() {
  25374. var srcEvent = this.srcEvent;
  25375. srcEvent.preventManipulation && srcEvent.preventManipulation();
  25376. srcEvent.preventDefault && srcEvent.preventDefault();
  25377. },
  25378. /**
  25379. * stop bubbling the event up to its parents
  25380. */
  25381. stopPropagation: function() {
  25382. this.srcEvent.stopPropagation();
  25383. },
  25384. /**
  25385. * immediately stop gesture detection
  25386. * might be useful after a swipe was detected
  25387. * @return {*}
  25388. */
  25389. stopDetect: function() {
  25390. return Detection.stopDetect();
  25391. }
  25392. };
  25393. }
  25394. };
  25395. /**
  25396. * @module hammer
  25397. *
  25398. * @class PointerEvent
  25399. * @static
  25400. */
  25401. var PointerEvent = Hammer.PointerEvent = {
  25402. /**
  25403. * holds all pointers, by `identifier`
  25404. * @property pointers
  25405. * @type {Object}
  25406. */
  25407. pointers: {},
  25408. /**
  25409. * get the pointers as an array
  25410. * @method getTouchList
  25411. * @return {Array} touchlist
  25412. */
  25413. getTouchList: function getTouchList() {
  25414. var touchlist = [];
  25415. // we can use forEach since pointerEvents only is in IE10
  25416. Utils.each(this.pointers, function(pointer) {
  25417. touchlist.push(pointer);
  25418. });
  25419. return touchlist;
  25420. },
  25421. /**
  25422. * update the position of a pointer
  25423. * @method updatePointer
  25424. * @param {String} eventType matches `EVENT_START|MOVE|END`
  25425. * @param {Object} pointerEvent
  25426. */
  25427. updatePointer: function updatePointer(eventType, pointerEvent) {
  25428. if(eventType == EVENT_END || (eventType != EVENT_END && pointerEvent.buttons !== 1)) {
  25429. delete this.pointers[pointerEvent.pointerId];
  25430. } else {
  25431. pointerEvent.identifier = pointerEvent.pointerId;
  25432. this.pointers[pointerEvent.pointerId] = pointerEvent;
  25433. }
  25434. },
  25435. /**
  25436. * check if ev matches pointertype
  25437. * @method matchType
  25438. * @param {String} pointerType matches `POINTER_MOUSE|TOUCH|PEN`
  25439. * @param {PointerEvent} ev
  25440. */
  25441. matchType: function matchType(pointerType, ev) {
  25442. if(!ev.pointerType) {
  25443. return false;
  25444. }
  25445. var pt = ev.pointerType,
  25446. types = {};
  25447. types[POINTER_MOUSE] = (pt === (ev.MSPOINTER_TYPE_MOUSE || POINTER_MOUSE));
  25448. types[POINTER_TOUCH] = (pt === (ev.MSPOINTER_TYPE_TOUCH || POINTER_TOUCH));
  25449. types[POINTER_PEN] = (pt === (ev.MSPOINTER_TYPE_PEN || POINTER_PEN));
  25450. return types[pointerType];
  25451. },
  25452. /**
  25453. * reset the stored pointers
  25454. * @method reset
  25455. */
  25456. reset: function resetList() {
  25457. this.pointers = {};
  25458. }
  25459. };
  25460. /**
  25461. * @module hammer
  25462. *
  25463. * @class Detection
  25464. * @static
  25465. */
  25466. var Detection = Hammer.detection = {
  25467. // contains all registred Hammer.gestures in the correct order
  25468. gestures: [],
  25469. // data of the current Hammer.gesture detection session
  25470. current: null,
  25471. // the previous Hammer.gesture session data
  25472. // is a full clone of the previous gesture.current object
  25473. previous: null,
  25474. // when this becomes true, no gestures are fired
  25475. stopped: false,
  25476. /**
  25477. * start Hammer.gesture detection
  25478. * @method startDetect
  25479. * @param {Hammer.Instance} inst
  25480. * @param {Object} eventData
  25481. */
  25482. startDetect: function startDetect(inst, eventData) {
  25483. // already busy with a Hammer.gesture detection on an element
  25484. if(this.current) {
  25485. return;
  25486. }
  25487. this.stopped = false;
  25488. // holds current session
  25489. this.current = {
  25490. inst: inst, // reference to HammerInstance we're working for
  25491. startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc
  25492. lastEvent: false, // last eventData
  25493. lastCalcEvent: false, // last eventData for calculations.
  25494. futureCalcEvent: false, // last eventData for calculations.
  25495. lastCalcData: {}, // last lastCalcData
  25496. name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  25497. };
  25498. this.detect(eventData);
  25499. },
  25500. /**
  25501. * Hammer.gesture detection
  25502. * @method detect
  25503. * @param {Object} eventData
  25504. * @return {any}
  25505. */
  25506. detect: function detect(eventData) {
  25507. if(!this.current || this.stopped) {
  25508. return;
  25509. }
  25510. // extend event data with calculations about scale, distance etc
  25511. eventData = this.extendEventData(eventData);
  25512. // hammer instance and instance options
  25513. var inst = this.current.inst,
  25514. instOptions = inst.options;
  25515. // call Hammer.gesture handlers
  25516. Utils.each(this.gestures, function triggerGesture(gesture) {
  25517. // only when the instance options have enabled this gesture
  25518. if(!this.stopped && inst.enabled && instOptions[gesture.name]) {
  25519. gesture.handler.call(gesture, eventData, inst);
  25520. }
  25521. }, this);
  25522. // store as previous event event
  25523. if(this.current) {
  25524. this.current.lastEvent = eventData;
  25525. }
  25526. if(eventData.eventType == EVENT_END) {
  25527. this.stopDetect();
  25528. }
  25529. return eventData;
  25530. },
  25531. /**
  25532. * clear the Hammer.gesture vars
  25533. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  25534. * to stop other Hammer.gestures from being fired
  25535. * @method stopDetect
  25536. */
  25537. stopDetect: function stopDetect() {
  25538. // clone current data to the store as the previous gesture
  25539. // used for the double tap gesture, since this is an other gesture detect session
  25540. this.previous = Utils.extend({}, this.current);
  25541. // reset the current
  25542. this.current = null;
  25543. this.stopped = true;
  25544. },
  25545. /**
  25546. * calculate velocity, angle and direction
  25547. * @method getVelocityData
  25548. * @param {Object} ev
  25549. * @param {Object} center
  25550. * @param {Number} deltaTime
  25551. * @param {Number} deltaX
  25552. * @param {Number} deltaY
  25553. */
  25554. getCalculatedData: function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) {
  25555. var cur = this.current,
  25556. recalc = false,
  25557. calcEv = cur.lastCalcEvent,
  25558. calcData = cur.lastCalcData;
  25559. if(calcEv && ev.timeStamp - calcEv.timeStamp > Hammer.CALCULATE_INTERVAL) {
  25560. center = calcEv.center;
  25561. deltaTime = ev.timeStamp - calcEv.timeStamp;
  25562. deltaX = ev.center.clientX - calcEv.center.clientX;
  25563. deltaY = ev.center.clientY - calcEv.center.clientY;
  25564. recalc = true;
  25565. }
  25566. if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
  25567. cur.futureCalcEvent = ev;
  25568. }
  25569. if(!cur.lastCalcEvent || recalc) {
  25570. calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY);
  25571. calcData.angle = Utils.getAngle(center, ev.center);
  25572. calcData.direction = Utils.getDirection(center, ev.center);
  25573. cur.lastCalcEvent = cur.futureCalcEvent || ev;
  25574. cur.futureCalcEvent = ev;
  25575. }
  25576. ev.velocityX = calcData.velocity.x;
  25577. ev.velocityY = calcData.velocity.y;
  25578. ev.interimAngle = calcData.angle;
  25579. ev.interimDirection = calcData.direction;
  25580. },
  25581. /**
  25582. * extend eventData for Hammer.gestures
  25583. * @method extendEventData
  25584. * @param {Object} ev
  25585. * @return {Object} ev
  25586. */
  25587. extendEventData: function extendEventData(ev) {
  25588. var cur = this.current,
  25589. startEv = cur.startEvent,
  25590. lastEv = cur.lastEvent || startEv;
  25591. // update the start touchlist to calculate the scale/rotation
  25592. if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
  25593. startEv.touches = [];
  25594. Utils.each(ev.touches, function(touch) {
  25595. startEv.touches.push({
  25596. clientX: touch.clientX,
  25597. clientY: touch.clientY
  25598. });
  25599. });
  25600. }
  25601. var deltaTime = ev.timeStamp - startEv.timeStamp,
  25602. deltaX = ev.center.clientX - startEv.center.clientX,
  25603. deltaY = ev.center.clientY - startEv.center.clientY;
  25604. this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY);
  25605. Utils.extend(ev, {
  25606. startEvent: startEv,
  25607. deltaTime: deltaTime,
  25608. deltaX: deltaX,
  25609. deltaY: deltaY,
  25610. distance: Utils.getDistance(startEv.center, ev.center),
  25611. angle: Utils.getAngle(startEv.center, ev.center),
  25612. direction: Utils.getDirection(startEv.center, ev.center),
  25613. scale: Utils.getScale(startEv.touches, ev.touches),
  25614. rotation: Utils.getRotation(startEv.touches, ev.touches)
  25615. });
  25616. return ev;
  25617. },
  25618. /**
  25619. * register new gesture
  25620. * @method register
  25621. * @param {Object} gesture object, see `gestures/` for documentation
  25622. * @return {Array} gestures
  25623. */
  25624. register: function register(gesture) {
  25625. // add an enable gesture options if there is no given
  25626. var options = gesture.defaults || {};
  25627. if(options[gesture.name] === undefined) {
  25628. options[gesture.name] = true;
  25629. }
  25630. // extend Hammer default options with the Hammer.gesture options
  25631. Utils.extend(Hammer.defaults, options, true);
  25632. // set its index
  25633. gesture.index = gesture.index || 1000;
  25634. // add Hammer.gesture to the list
  25635. this.gestures.push(gesture);
  25636. // sort the list by index
  25637. this.gestures.sort(function(a, b) {
  25638. if(a.index < b.index) {
  25639. return -1;
  25640. }
  25641. if(a.index > b.index) {
  25642. return 1;
  25643. }
  25644. return 0;
  25645. });
  25646. return this.gestures;
  25647. }
  25648. };
  25649. /**
  25650. * @module hammer
  25651. */
  25652. /**
  25653. * create new hammer instance
  25654. * all methods should return the instance itself, so it is chainable.
  25655. *
  25656. * @class Instance
  25657. * @constructor
  25658. * @param {HTMLElement} element
  25659. * @param {Object} [options={}] options are merged with `Hammer.defaults`
  25660. * @return {Hammer.Instance}
  25661. */
  25662. Hammer.Instance = function(element, options) {
  25663. var self = this;
  25664. // setup HammerJS window events and register all gestures
  25665. // this also sets up the default options
  25666. setup();
  25667. /**
  25668. * @property element
  25669. * @type {HTMLElement}
  25670. */
  25671. this.element = element;
  25672. /**
  25673. * @property enabled
  25674. * @type {Boolean}
  25675. * @protected
  25676. */
  25677. this.enabled = true;
  25678. /**
  25679. * options, merged with the defaults
  25680. * options with an _ are converted to camelCase
  25681. * @property options
  25682. * @type {Object}
  25683. */
  25684. Utils.each(options, function(value, name) {
  25685. delete options[name];
  25686. options[Utils.toCamelCase(name)] = value;
  25687. });
  25688. this.options = Utils.extend(Utils.extend({}, Hammer.defaults), options || {});
  25689. // add some css to the element to prevent the browser from doing its native behavoir
  25690. if(this.options.behavior) {
  25691. Utils.toggleBehavior(this.element, this.options.behavior, true);
  25692. }
  25693. /**
  25694. * event start handler on the element to start the detection
  25695. * @property eventStartHandler
  25696. * @type {Object}
  25697. */
  25698. this.eventStartHandler = Event.onTouch(element, EVENT_START, function(ev) {
  25699. if(self.enabled && ev.eventType == EVENT_START) {
  25700. Detection.startDetect(self, ev);
  25701. } else if(ev.eventType == EVENT_TOUCH) {
  25702. Detection.detect(ev);
  25703. }
  25704. });
  25705. /**
  25706. * keep a list of user event handlers which needs to be removed when calling 'dispose'
  25707. * @property eventHandlers
  25708. * @type {Array}
  25709. */
  25710. this.eventHandlers = [];
  25711. };
  25712. Hammer.Instance.prototype = {
  25713. /**
  25714. * bind events to the instance
  25715. * @method on
  25716. * @chainable
  25717. * @param {String} gestures multiple gestures by splitting with a space
  25718. * @param {Function} handler
  25719. * @param {Object} handler.ev event object
  25720. */
  25721. on: function onEvent(gestures, handler) {
  25722. var self = this;
  25723. Event.on(self.element, gestures, handler, function(type) {
  25724. self.eventHandlers.push({ gesture: type, handler: handler });
  25725. });
  25726. return self;
  25727. },
  25728. /**
  25729. * unbind events to the instance
  25730. * @method off
  25731. * @chainable
  25732. * @param {String} gestures
  25733. * @param {Function} handler
  25734. */
  25735. off: function offEvent(gestures, handler) {
  25736. var self = this;
  25737. Event.off(self.element, gestures, handler, function(type) {
  25738. var index = Utils.inArray({ gesture: type, handler: handler });
  25739. if(index !== false) {
  25740. self.eventHandlers.splice(index, 1);
  25741. }
  25742. });
  25743. return self;
  25744. },
  25745. /**
  25746. * trigger gesture event
  25747. * @method trigger
  25748. * @chainable
  25749. * @param {String} gesture
  25750. * @param {Object} [eventData]
  25751. */
  25752. trigger: function triggerEvent(gesture, eventData) {
  25753. // optional
  25754. if(!eventData) {
  25755. eventData = {};
  25756. }
  25757. // create DOM event
  25758. var event = Hammer.DOCUMENT.createEvent('Event');
  25759. event.initEvent(gesture, true, true);
  25760. event.gesture = eventData;
  25761. // trigger on the target if it is in the instance element,
  25762. // this is for event delegation tricks
  25763. var element = this.element;
  25764. if(Utils.hasParent(eventData.target, element)) {
  25765. element = eventData.target;
  25766. }
  25767. element.dispatchEvent(event);
  25768. return this;
  25769. },
  25770. /**
  25771. * enable of disable hammer.js detection
  25772. * @method enable
  25773. * @chainable
  25774. * @param {Boolean} state
  25775. */
  25776. enable: function enable(state) {
  25777. this.enabled = state;
  25778. return this;
  25779. },
  25780. /**
  25781. * dispose this hammer instance
  25782. * @method dispose
  25783. * @return {Null}
  25784. */
  25785. dispose: function dispose() {
  25786. var i, eh;
  25787. // undo all changes made by stop_browser_behavior
  25788. Utils.toggleBehavior(this.element, this.options.behavior, false);
  25789. // unbind all custom event handlers
  25790. for(i = -1; (eh = this.eventHandlers[++i]);) {
  25791. Utils.off(this.element, eh.gesture, eh.handler);
  25792. }
  25793. this.eventHandlers = [];
  25794. // unbind the start event listener
  25795. Event.off(this.element, EVENT_TYPES[EVENT_START], this.eventStartHandler);
  25796. return null;
  25797. }
  25798. };
  25799. /**
  25800. * @module gestures
  25801. */
  25802. /**
  25803. * Move with x fingers (default 1) around on the page.
  25804. * Preventing the default browser behavior is a good way to improve feel and working.
  25805. * ````
  25806. * hammertime.on("drag", function(ev) {
  25807. * console.log(ev);
  25808. * ev.gesture.preventDefault();
  25809. * });
  25810. * ````
  25811. *
  25812. * @class Drag
  25813. * @static
  25814. */
  25815. /**
  25816. * @event drag
  25817. * @param {Object} ev
  25818. */
  25819. /**
  25820. * @event dragstart
  25821. * @param {Object} ev
  25822. */
  25823. /**
  25824. * @event dragend
  25825. * @param {Object} ev
  25826. */
  25827. /**
  25828. * @event drapleft
  25829. * @param {Object} ev
  25830. */
  25831. /**
  25832. * @event dragright
  25833. * @param {Object} ev
  25834. */
  25835. /**
  25836. * @event dragup
  25837. * @param {Object} ev
  25838. */
  25839. /**
  25840. * @event dragdown
  25841. * @param {Object} ev
  25842. */
  25843. /**
  25844. * @param {String} name
  25845. */
  25846. (function(name) {
  25847. var triggered = false;
  25848. function dragGesture(ev, inst) {
  25849. var cur = Detection.current;
  25850. // max touches
  25851. if(inst.options.dragMaxTouches > 0 &&
  25852. ev.touches.length > inst.options.dragMaxTouches) {
  25853. return;
  25854. }
  25855. switch(ev.eventType) {
  25856. case EVENT_START:
  25857. triggered = false;
  25858. break;
  25859. case EVENT_MOVE:
  25860. // when the distance we moved is too small we skip this gesture
  25861. // or we can be already in dragging
  25862. if(ev.distance < inst.options.dragMinDistance &&
  25863. cur.name != name) {
  25864. return;
  25865. }
  25866. var startCenter = cur.startEvent.center;
  25867. // we are dragging!
  25868. if(cur.name != name) {
  25869. cur.name = name;
  25870. if(inst.options.dragDistanceCorrection && ev.distance > 0) {
  25871. // When a drag is triggered, set the event center to dragMinDistance pixels from the original event center.
  25872. // Without this correction, the dragged distance would jumpstart at dragMinDistance pixels instead of at 0.
  25873. // It might be useful to save the original start point somewhere
  25874. var factor = Math.abs(inst.options.dragMinDistance / ev.distance);
  25875. startCenter.pageX += ev.deltaX * factor;
  25876. startCenter.pageY += ev.deltaY * factor;
  25877. startCenter.clientX += ev.deltaX * factor;
  25878. startCenter.clientY += ev.deltaY * factor;
  25879. // recalculate event data using new start point
  25880. ev = Detection.extendEventData(ev);
  25881. }
  25882. }
  25883. // lock drag to axis?
  25884. if(cur.lastEvent.dragLockToAxis ||
  25885. ( inst.options.dragLockToAxis &&
  25886. inst.options.dragLockMinDistance <= ev.distance
  25887. )) {
  25888. ev.dragLockToAxis = true;
  25889. }
  25890. // keep direction on the axis that the drag gesture started on
  25891. var lastDirection = cur.lastEvent.direction;
  25892. if(ev.dragLockToAxis && lastDirection !== ev.direction) {
  25893. if(Utils.isVertical(lastDirection)) {
  25894. ev.direction = (ev.deltaY < 0) ? DIRECTION_UP : DIRECTION_DOWN;
  25895. } else {
  25896. ev.direction = (ev.deltaX < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
  25897. }
  25898. }
  25899. // first time, trigger dragstart event
  25900. if(!triggered) {
  25901. inst.trigger(name + 'start', ev);
  25902. triggered = true;
  25903. }
  25904. // trigger events
  25905. inst.trigger(name, ev);
  25906. inst.trigger(name + ev.direction, ev);
  25907. var isVertical = Utils.isVertical(ev.direction);
  25908. // block the browser events
  25909. if((inst.options.dragBlockVertical && isVertical) ||
  25910. (inst.options.dragBlockHorizontal && !isVertical)) {
  25911. ev.preventDefault();
  25912. }
  25913. break;
  25914. case EVENT_RELEASE:
  25915. if(triggered && ev.changedLength <= inst.options.dragMaxTouches) {
  25916. inst.trigger(name + 'end', ev);
  25917. triggered = false;
  25918. }
  25919. break;
  25920. case EVENT_END:
  25921. triggered = false;
  25922. break;
  25923. }
  25924. }
  25925. Hammer.gestures.Drag = {
  25926. name: name,
  25927. index: 50,
  25928. handler: dragGesture,
  25929. defaults: {
  25930. /**
  25931. * minimal movement that have to be made before the drag event gets triggered
  25932. * @property dragMinDistance
  25933. * @type {Number}
  25934. * @default 10
  25935. */
  25936. dragMinDistance: 10,
  25937. /**
  25938. * Set dragDistanceCorrection to true to make the starting point of the drag
  25939. * be calculated from where the drag was triggered, not from where the touch started.
  25940. * Useful to avoid a jerk-starting drag, which can make fine-adjustments
  25941. * through dragging difficult, and be visually unappealing.
  25942. * @property dragDistanceCorrection
  25943. * @type {Boolean}
  25944. * @default true
  25945. */
  25946. dragDistanceCorrection: true,
  25947. /**
  25948. * set 0 for unlimited, but this can conflict with transform
  25949. * @property dragMaxTouches
  25950. * @type {Number}
  25951. * @default 1
  25952. */
  25953. dragMaxTouches: 1,
  25954. /**
  25955. * prevent default browser behavior when dragging occurs
  25956. * be careful with it, it makes the element a blocking element
  25957. * when you are using the drag gesture, it is a good practice to set this true
  25958. * @property dragBlockHorizontal
  25959. * @type {Boolean}
  25960. * @default false
  25961. */
  25962. dragBlockHorizontal: false,
  25963. /**
  25964. * same as `dragBlockHorizontal`, but for vertical movement
  25965. * @property dragBlockVertical
  25966. * @type {Boolean}
  25967. * @default false
  25968. */
  25969. dragBlockVertical: false,
  25970. /**
  25971. * dragLockToAxis keeps the drag gesture on the axis that it started on,
  25972. * It disallows vertical directions if the initial direction was horizontal, and vice versa.
  25973. * @property dragLockToAxis
  25974. * @type {Boolean}
  25975. * @default false
  25976. */
  25977. dragLockToAxis: false,
  25978. /**
  25979. * drag lock only kicks in when distance > dragLockMinDistance
  25980. * This way, locking occurs only when the distance has become large enough to reliably determine the direction
  25981. * @property dragLockMinDistance
  25982. * @type {Number}
  25983. * @default 25
  25984. */
  25985. dragLockMinDistance: 25
  25986. }
  25987. };
  25988. })('drag');
  25989. /**
  25990. * @module gestures
  25991. */
  25992. /**
  25993. * trigger a simple gesture event, so you can do anything in your handler.
  25994. * only usable if you know what your doing...
  25995. *
  25996. * @class Gesture
  25997. * @static
  25998. */
  25999. /**
  26000. * @event gesture
  26001. * @param {Object} ev
  26002. */
  26003. Hammer.gestures.Gesture = {
  26004. name: 'gesture',
  26005. index: 1337,
  26006. handler: function releaseGesture(ev, inst) {
  26007. inst.trigger(this.name, ev);
  26008. }
  26009. };
  26010. /**
  26011. * @module gestures
  26012. */
  26013. /**
  26014. * Touch stays at the same place for x time
  26015. *
  26016. * @class Hold
  26017. * @static
  26018. */
  26019. /**
  26020. * @event hold
  26021. * @param {Object} ev
  26022. */
  26023. /**
  26024. * @param {String} name
  26025. */
  26026. (function(name) {
  26027. var timer;
  26028. function holdGesture(ev, inst) {
  26029. var options = inst.options,
  26030. current = Detection.current;
  26031. switch(ev.eventType) {
  26032. case EVENT_START:
  26033. clearTimeout(timer);
  26034. // set the gesture so we can check in the timeout if it still is
  26035. current.name = name;
  26036. // set timer and if after the timeout it still is hold,
  26037. // we trigger the hold event
  26038. timer = setTimeout(function() {
  26039. if(current && current.name == name) {
  26040. inst.trigger(name, ev);
  26041. }
  26042. }, options.holdTimeout);
  26043. break;
  26044. case EVENT_MOVE:
  26045. if(ev.distance > options.holdThreshold) {
  26046. clearTimeout(timer);
  26047. }
  26048. break;
  26049. case EVENT_RELEASE:
  26050. clearTimeout(timer);
  26051. break;
  26052. }
  26053. }
  26054. Hammer.gestures.Hold = {
  26055. name: name,
  26056. index: 10,
  26057. defaults: {
  26058. /**
  26059. * @property holdTimeout
  26060. * @type {Number}
  26061. * @default 500
  26062. */
  26063. holdTimeout: 500,
  26064. /**
  26065. * movement allowed while holding
  26066. * @property holdThreshold
  26067. * @type {Number}
  26068. * @default 2
  26069. */
  26070. holdThreshold: 2
  26071. },
  26072. handler: holdGesture
  26073. };
  26074. })('hold');
  26075. /**
  26076. * @module gestures
  26077. */
  26078. /**
  26079. * when a touch is being released from the page
  26080. *
  26081. * @class Release
  26082. * @static
  26083. */
  26084. /**
  26085. * @event release
  26086. * @param {Object} ev
  26087. */
  26088. Hammer.gestures.Release = {
  26089. name: 'release',
  26090. index: Infinity,
  26091. handler: function releaseGesture(ev, inst) {
  26092. if(ev.eventType == EVENT_RELEASE) {
  26093. inst.trigger(this.name, ev);
  26094. }
  26095. }
  26096. };
  26097. /**
  26098. * @module gestures
  26099. */
  26100. /**
  26101. * triggers swipe events when the end velocity is above the threshold
  26102. * for best usage, set `preventDefault` (on the drag gesture) to `true`
  26103. * ````
  26104. * hammertime.on("dragleft swipeleft", function(ev) {
  26105. * console.log(ev);
  26106. * ev.gesture.preventDefault();
  26107. * });
  26108. * ````
  26109. *
  26110. * @class Swipe
  26111. * @static
  26112. */
  26113. /**
  26114. * @event swipe
  26115. * @param {Object} ev
  26116. */
  26117. /**
  26118. * @event swipeleft
  26119. * @param {Object} ev
  26120. */
  26121. /**
  26122. * @event swiperight
  26123. * @param {Object} ev
  26124. */
  26125. /**
  26126. * @event swipeup
  26127. * @param {Object} ev
  26128. */
  26129. /**
  26130. * @event swipedown
  26131. * @param {Object} ev
  26132. */
  26133. Hammer.gestures.Swipe = {
  26134. name: 'swipe',
  26135. index: 40,
  26136. defaults: {
  26137. /**
  26138. * @property swipeMinTouches
  26139. * @type {Number}
  26140. * @default 1
  26141. */
  26142. swipeMinTouches: 1,
  26143. /**
  26144. * @property swipeMaxTouches
  26145. * @type {Number}
  26146. * @default 1
  26147. */
  26148. swipeMaxTouches: 1,
  26149. /**
  26150. * horizontal swipe velocity
  26151. * @property swipeVelocityX
  26152. * @type {Number}
  26153. * @default 0.6
  26154. */
  26155. swipeVelocityX: 0.6,
  26156. /**
  26157. * vertical swipe velocity
  26158. * @property swipeVelocityY
  26159. * @type {Number}
  26160. * @default 0.6
  26161. */
  26162. swipeVelocityY: 0.6
  26163. },
  26164. handler: function swipeGesture(ev, inst) {
  26165. if(ev.eventType == EVENT_RELEASE) {
  26166. var touches = ev.touches.length,
  26167. options = inst.options;
  26168. // max touches
  26169. if(touches < options.swipeMinTouches ||
  26170. touches > options.swipeMaxTouches) {
  26171. return;
  26172. }
  26173. // when the distance we moved is too small we skip this gesture
  26174. // or we can be already in dragging
  26175. if(ev.velocityX > options.swipeVelocityX ||
  26176. ev.velocityY > options.swipeVelocityY) {
  26177. // trigger swipe events
  26178. inst.trigger(this.name, ev);
  26179. inst.trigger(this.name + ev.direction, ev);
  26180. }
  26181. }
  26182. }
  26183. };
  26184. /**
  26185. * @module gestures
  26186. */
  26187. /**
  26188. * Single tap and a double tap on a place
  26189. *
  26190. * @class Tap
  26191. * @static
  26192. */
  26193. /**
  26194. * @event tap
  26195. * @param {Object} ev
  26196. */
  26197. /**
  26198. * @event doubletap
  26199. * @param {Object} ev
  26200. */
  26201. /**
  26202. * @param {String} name
  26203. */
  26204. (function(name) {
  26205. var hasMoved = false;
  26206. function tapGesture(ev, inst) {
  26207. var options = inst.options,
  26208. current = Detection.current,
  26209. prev = Detection.previous,
  26210. sincePrev,
  26211. didDoubleTap;
  26212. switch(ev.eventType) {
  26213. case EVENT_START:
  26214. hasMoved = false;
  26215. break;
  26216. case EVENT_MOVE:
  26217. hasMoved = hasMoved || (ev.distance > options.tapMaxDistance);
  26218. break;
  26219. case EVENT_END:
  26220. if(!Utils.inStr(ev.srcEvent.type, 'cancel') && ev.deltaTime < options.tapMaxTime && !hasMoved) {
  26221. // previous gesture, for the double tap since these are two different gesture detections
  26222. sincePrev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp;
  26223. didDoubleTap = false;
  26224. // check if double tap
  26225. if(prev && prev.name == name &&
  26226. (sincePrev && sincePrev < options.doubleTapInterval) &&
  26227. ev.distance < options.doubleTapDistance) {
  26228. inst.trigger('doubletap', ev);
  26229. didDoubleTap = true;
  26230. }
  26231. // do a single tap
  26232. if(!didDoubleTap || options.tapAlways) {
  26233. current.name = name;
  26234. inst.trigger(current.name, ev);
  26235. }
  26236. }
  26237. break;
  26238. }
  26239. }
  26240. Hammer.gestures.Tap = {
  26241. name: name,
  26242. index: 100,
  26243. handler: tapGesture,
  26244. defaults: {
  26245. /**
  26246. * max time of a tap, this is for the slow tappers
  26247. * @property tapMaxTime
  26248. * @type {Number}
  26249. * @default 250
  26250. */
  26251. tapMaxTime: 250,
  26252. /**
  26253. * max distance of movement of a tap, this is for the slow tappers
  26254. * @property tapMaxDistance
  26255. * @type {Number}
  26256. * @default 10
  26257. */
  26258. tapMaxDistance: 10,
  26259. /**
  26260. * always trigger the `tap` event, even while double-tapping
  26261. * @property tapAlways
  26262. * @type {Boolean}
  26263. * @default true
  26264. */
  26265. tapAlways: true,
  26266. /**
  26267. * max distance between two taps
  26268. * @property doubleTapDistance
  26269. * @type {Number}
  26270. * @default 20
  26271. */
  26272. doubleTapDistance: 20,
  26273. /**
  26274. * max time between two taps
  26275. * @property doubleTapInterval
  26276. * @type {Number}
  26277. * @default 300
  26278. */
  26279. doubleTapInterval: 300
  26280. }
  26281. };
  26282. })('tap');
  26283. /**
  26284. * @module gestures
  26285. */
  26286. /**
  26287. * when a touch is being touched at the page
  26288. *
  26289. * @class Touch
  26290. * @static
  26291. */
  26292. /**
  26293. * @event touch
  26294. * @param {Object} ev
  26295. */
  26296. Hammer.gestures.Touch = {
  26297. name: 'touch',
  26298. index: -Infinity,
  26299. defaults: {
  26300. /**
  26301. * call preventDefault at touchstart, and makes the element blocking by disabling the scrolling of the page,
  26302. * but it improves gestures like transforming and dragging.
  26303. * be careful with using this, it can be very annoying for users to be stuck on the page
  26304. * @property preventDefault
  26305. * @type {Boolean}
  26306. * @default false
  26307. */
  26308. preventDefault: false,
  26309. /**
  26310. * disable mouse events, so only touch (or pen!) input triggers events
  26311. * @property preventMouse
  26312. * @type {Boolean}
  26313. * @default false
  26314. */
  26315. preventMouse: false
  26316. },
  26317. handler: function touchGesture(ev, inst) {
  26318. if(inst.options.preventMouse && ev.pointerType == POINTER_MOUSE) {
  26319. ev.stopDetect();
  26320. return;
  26321. }
  26322. if(inst.options.preventDefault) {
  26323. ev.preventDefault();
  26324. }
  26325. if(ev.eventType == EVENT_TOUCH) {
  26326. inst.trigger('touch', ev);
  26327. }
  26328. }
  26329. };
  26330. /**
  26331. * @module gestures
  26332. */
  26333. /**
  26334. * User want to scale or rotate with 2 fingers
  26335. * Preventing the default browser behavior is a good way to improve feel and working. This can be done with the
  26336. * `preventDefault` option.
  26337. *
  26338. * @class Transform
  26339. * @static
  26340. */
  26341. /**
  26342. * @event transform
  26343. * @param {Object} ev
  26344. */
  26345. /**
  26346. * @event transformstart
  26347. * @param {Object} ev
  26348. */
  26349. /**
  26350. * @event transformend
  26351. * @param {Object} ev
  26352. */
  26353. /**
  26354. * @event pinchin
  26355. * @param {Object} ev
  26356. */
  26357. /**
  26358. * @event pinchout
  26359. * @param {Object} ev
  26360. */
  26361. /**
  26362. * @event rotate
  26363. * @param {Object} ev
  26364. */
  26365. /**
  26366. * @param {String} name
  26367. */
  26368. (function(name) {
  26369. var triggered = false;
  26370. function transformGesture(ev, inst) {
  26371. switch(ev.eventType) {
  26372. case EVENT_START:
  26373. triggered = false;
  26374. break;
  26375. case EVENT_MOVE:
  26376. // at least multitouch
  26377. if(ev.touches.length < 2) {
  26378. return;
  26379. }
  26380. var scaleThreshold = Math.abs(1 - ev.scale);
  26381. var rotationThreshold = Math.abs(ev.rotation);
  26382. // when the distance we moved is too small we skip this gesture
  26383. // or we can be already in dragging
  26384. if(scaleThreshold < inst.options.transformMinScale &&
  26385. rotationThreshold < inst.options.transformMinRotation) {
  26386. return;
  26387. }
  26388. // we are transforming!
  26389. Detection.current.name = name;
  26390. // first time, trigger dragstart event
  26391. if(!triggered) {
  26392. inst.trigger(name + 'start', ev);
  26393. triggered = true;
  26394. }
  26395. inst.trigger(name, ev); // basic transform event
  26396. // trigger rotate event
  26397. if(rotationThreshold > inst.options.transformMinRotation) {
  26398. inst.trigger('rotate', ev);
  26399. }
  26400. // trigger pinch event
  26401. if(scaleThreshold > inst.options.transformMinScale) {
  26402. inst.trigger('pinch', ev);
  26403. inst.trigger('pinch' + (ev.scale < 1 ? 'in' : 'out'), ev);
  26404. }
  26405. break;
  26406. case EVENT_RELEASE:
  26407. if(triggered && ev.changedLength < 2) {
  26408. inst.trigger(name + 'end', ev);
  26409. triggered = false;
  26410. }
  26411. break;
  26412. }
  26413. }
  26414. Hammer.gestures.Transform = {
  26415. name: name,
  26416. index: 45,
  26417. defaults: {
  26418. /**
  26419. * minimal scale factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  26420. * @property transformMinScale
  26421. * @type {Number}
  26422. * @default 0.01
  26423. */
  26424. transformMinScale: 0.01,
  26425. /**
  26426. * rotation in degrees
  26427. * @property transformMinRotation
  26428. * @type {Number}
  26429. * @default 1
  26430. */
  26431. transformMinRotation: 1
  26432. },
  26433. handler: transformGesture
  26434. };
  26435. })('transform');
  26436. /**
  26437. * @module hammer
  26438. */
  26439. // AMD export
  26440. if(true) {
  26441. !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
  26442. return Hammer;
  26443. }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  26444. // commonjs export
  26445. } else if(typeof module !== 'undefined' && module.exports) {
  26446. module.exports = Hammer;
  26447. // browser export
  26448. } else {
  26449. window.Hammer = Hammer;
  26450. }
  26451. })(window);
  26452. /***/ },
  26453. /* 60 */
  26454. /***/ function(module, exports, __webpack_require__) {
  26455. var util = __webpack_require__(1);
  26456. var RepulsionMixin = __webpack_require__(68);
  26457. var HierarchialRepulsionMixin = __webpack_require__(69);
  26458. var BarnesHutMixin = __webpack_require__(70);
  26459. /**
  26460. * Toggling barnes Hut calculation on and off.
  26461. *
  26462. * @private
  26463. */
  26464. exports._toggleBarnesHut = function () {
  26465. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  26466. this._loadSelectedForceSolver();
  26467. this.moving = true;
  26468. this.start();
  26469. };
  26470. /**
  26471. * This loads the node force solver based on the barnes hut or repulsion algorithm
  26472. *
  26473. * @private
  26474. */
  26475. exports._loadSelectedForceSolver = function () {
  26476. // this overloads the this._calculateNodeForces
  26477. if (this.constants.physics.barnesHut.enabled == true) {
  26478. this._clearMixin(RepulsionMixin);
  26479. this._clearMixin(HierarchialRepulsionMixin);
  26480. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  26481. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  26482. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  26483. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  26484. this._loadMixin(BarnesHutMixin);
  26485. }
  26486. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  26487. this._clearMixin(BarnesHutMixin);
  26488. this._clearMixin(RepulsionMixin);
  26489. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  26490. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  26491. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  26492. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  26493. this._loadMixin(HierarchialRepulsionMixin);
  26494. }
  26495. else {
  26496. this._clearMixin(BarnesHutMixin);
  26497. this._clearMixin(HierarchialRepulsionMixin);
  26498. this.barnesHutTree = undefined;
  26499. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  26500. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  26501. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  26502. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  26503. this._loadMixin(RepulsionMixin);
  26504. }
  26505. };
  26506. /**
  26507. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  26508. * if there is more than one node. If it is just one node, we dont calculate anything.
  26509. *
  26510. * @private
  26511. */
  26512. exports._initializeForceCalculation = function () {
  26513. // stop calculation if there is only one node
  26514. if (this.nodeIndices.length == 1) {
  26515. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  26516. }
  26517. else {
  26518. // if there are too many nodes on screen, we cluster without repositioning
  26519. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  26520. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  26521. }
  26522. // we now start the force calculation
  26523. this._calculateForces();
  26524. }
  26525. };
  26526. /**
  26527. * Calculate the external forces acting on the nodes
  26528. * Forces are caused by: edges, repulsing forces between nodes, gravity
  26529. * @private
  26530. */
  26531. exports._calculateForces = function () {
  26532. // Gravity is required to keep separated groups from floating off
  26533. // the forces are reset to zero in this loop by using _setForce instead
  26534. // of _addForce
  26535. this._calculateGravitationalForces();
  26536. this._calculateNodeForces();
  26537. if (this.constants.physics.springConstant > 0) {
  26538. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  26539. this._calculateSpringForcesWithSupport();
  26540. }
  26541. else {
  26542. if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  26543. this._calculateHierarchicalSpringForces();
  26544. }
  26545. else {
  26546. this._calculateSpringForces();
  26547. }
  26548. }
  26549. }
  26550. };
  26551. /**
  26552. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  26553. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  26554. * This function joins the datanodes and invisible (called support) nodes into one object.
  26555. * We do this so we do not contaminate this.nodes with the support nodes.
  26556. *
  26557. * @private
  26558. */
  26559. exports._updateCalculationNodes = function () {
  26560. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  26561. this.calculationNodes = {};
  26562. this.calculationNodeIndices = [];
  26563. for (var nodeId in this.nodes) {
  26564. if (this.nodes.hasOwnProperty(nodeId)) {
  26565. this.calculationNodes[nodeId] = this.nodes[nodeId];
  26566. }
  26567. }
  26568. var supportNodes = this.sectors['support']['nodes'];
  26569. for (var supportNodeId in supportNodes) {
  26570. if (supportNodes.hasOwnProperty(supportNodeId)) {
  26571. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  26572. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  26573. }
  26574. else {
  26575. supportNodes[supportNodeId]._setForce(0, 0);
  26576. }
  26577. }
  26578. }
  26579. for (var idx in this.calculationNodes) {
  26580. if (this.calculationNodes.hasOwnProperty(idx)) {
  26581. this.calculationNodeIndices.push(idx);
  26582. }
  26583. }
  26584. }
  26585. else {
  26586. this.calculationNodes = this.nodes;
  26587. this.calculationNodeIndices = this.nodeIndices;
  26588. }
  26589. };
  26590. /**
  26591. * this function applies the central gravity effect to keep groups from floating off
  26592. *
  26593. * @private
  26594. */
  26595. exports._calculateGravitationalForces = function () {
  26596. var dx, dy, distance, node, i;
  26597. var nodes = this.calculationNodes;
  26598. var gravity = this.constants.physics.centralGravity;
  26599. var gravityForce = 0;
  26600. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  26601. node = nodes[this.calculationNodeIndices[i]];
  26602. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  26603. // gravity does not apply when we are in a pocket sector
  26604. if (this._sector() == "default" && gravity != 0) {
  26605. dx = -node.x;
  26606. dy = -node.y;
  26607. distance = Math.sqrt(dx * dx + dy * dy);
  26608. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  26609. node.fx = dx * gravityForce;
  26610. node.fy = dy * gravityForce;
  26611. }
  26612. else {
  26613. node.fx = 0;
  26614. node.fy = 0;
  26615. }
  26616. }
  26617. };
  26618. /**
  26619. * this function calculates the effects of the springs in the case of unsmooth curves.
  26620. *
  26621. * @private
  26622. */
  26623. exports._calculateSpringForces = function () {
  26624. var edgeLength, edge, edgeId;
  26625. var dx, dy, fx, fy, springForce, distance;
  26626. var edges = this.edges;
  26627. // forces caused by the edges, modelled as springs
  26628. for (edgeId in edges) {
  26629. if (edges.hasOwnProperty(edgeId)) {
  26630. edge = edges[edgeId];
  26631. if (edge.connected) {
  26632. // only calculate forces if nodes are in the same sector
  26633. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  26634. edgeLength = edge.physics.springLength;
  26635. // this implies that the edges between big clusters are longer
  26636. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  26637. dx = (edge.from.x - edge.to.x);
  26638. dy = (edge.from.y - edge.to.y);
  26639. distance = Math.sqrt(dx * dx + dy * dy);
  26640. if (distance == 0) {
  26641. distance = 0.01;
  26642. }
  26643. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  26644. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  26645. fx = dx * springForce;
  26646. fy = dy * springForce;
  26647. edge.from.fx += fx;
  26648. edge.from.fy += fy;
  26649. edge.to.fx -= fx;
  26650. edge.to.fy -= fy;
  26651. }
  26652. }
  26653. }
  26654. }
  26655. };
  26656. /**
  26657. * This function calculates the springforces on the nodes, accounting for the support nodes.
  26658. *
  26659. * @private
  26660. */
  26661. exports._calculateSpringForcesWithSupport = function () {
  26662. var edgeLength, edge, edgeId, combinedClusterSize;
  26663. var edges = this.edges;
  26664. // forces caused by the edges, modelled as springs
  26665. for (edgeId in edges) {
  26666. if (edges.hasOwnProperty(edgeId)) {
  26667. edge = edges[edgeId];
  26668. if (edge.connected) {
  26669. // only calculate forces if nodes are in the same sector
  26670. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  26671. if (edge.via != null) {
  26672. var node1 = edge.to;
  26673. var node2 = edge.via;
  26674. var node3 = edge.from;
  26675. edgeLength = edge.physics.springLength;
  26676. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  26677. // this implies that the edges between big clusters are longer
  26678. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  26679. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  26680. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  26681. }
  26682. }
  26683. }
  26684. }
  26685. }
  26686. };
  26687. /**
  26688. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  26689. *
  26690. * @param node1
  26691. * @param node2
  26692. * @param edgeLength
  26693. * @private
  26694. */
  26695. exports._calculateSpringForce = function (node1, node2, edgeLength) {
  26696. var dx, dy, fx, fy, springForce, distance;
  26697. dx = (node1.x - node2.x);
  26698. dy = (node1.y - node2.y);
  26699. distance = Math.sqrt(dx * dx + dy * dy);
  26700. if (distance == 0) {
  26701. distance = 0.01;
  26702. }
  26703. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  26704. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  26705. fx = dx * springForce;
  26706. fy = dy * springForce;
  26707. node1.fx += fx;
  26708. node1.fy += fy;
  26709. node2.fx -= fx;
  26710. node2.fy -= fy;
  26711. };
  26712. exports._cleanupPhysicsConfiguration = function() {
  26713. if (this.physicsConfiguration !== undefined) {
  26714. while (this.physicsConfiguration.hasChildNodes()) {
  26715. this.physicsConfiguration.removeChild(this.physicsConfiguration.firstChild);
  26716. }
  26717. this.physicsConfiguration.parentNode.removeChild(this.physicsConfiguration);
  26718. this.physicsConfiguration = undefined;
  26719. }
  26720. }
  26721. /**
  26722. * Load the HTML for the physics config and bind it
  26723. * @private
  26724. */
  26725. exports._loadPhysicsConfiguration = function () {
  26726. if (this.physicsConfiguration === undefined) {
  26727. this.backupConstants = {};
  26728. util.deepExtend(this.backupConstants,this.constants);
  26729. var maxGravitational = Math.max(20000, (-1 * this.constants.physics.barnesHut.gravitationalConstant) * 10);
  26730. var maxSpring = Math.min(0.05, this.constants.physics.barnesHut.springConstant * 10)
  26731. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  26732. this.physicsConfiguration = document.createElement('div');
  26733. this.physicsConfiguration.className = "PhysicsConfiguration";
  26734. this.physicsConfiguration.innerHTML = '' +
  26735. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  26736. '<tr>' +
  26737. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  26738. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  26739. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  26740. '</tr>' +
  26741. '</table>' +
  26742. '<table id="graph_BH_table" style="display:none">' +
  26743. '<tr><td><b>Barnes Hut</b></td></tr>' +
  26744. '<tr>' +
  26745. '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="0" max="'+maxGravitational+'" value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-'+maxGravitational+'</td><td><input value="' + (this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>' +
  26746. '</tr>' +
  26747. '<tr>' +
  26748. '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="6" value="' + this.constants.physics.barnesHut.centralGravity + '" step="0.05" style="width:300px" id="graph_BH_cg"></td><td>3</td><td><input value="' + this.constants.physics.barnesHut.centralGravity + '" id="graph_BH_cg_value" style="width:60px"></td>' +
  26749. '</tr>' +
  26750. '<tr>' +
  26751. '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.barnesHut.springLength + '" step="1" style="width:300px" id="graph_BH_sl"></td><td>500</td><td><input value="' + this.constants.physics.barnesHut.springLength + '" id="graph_BH_sl_value" style="width:60px"></td>' +
  26752. '</tr>' +
  26753. '<tr>' +
  26754. '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="'+maxSpring+'" value="' + this.constants.physics.barnesHut.springConstant + '" step="0.0001" style="width:300px" id="graph_BH_sc"></td><td>'+maxSpring+'</td><td><input value="' + this.constants.physics.barnesHut.springConstant + '" id="graph_BH_sc_value" style="width:60px"></td>' +
  26755. '</tr>' +
  26756. '<tr>' +
  26757. '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.barnesHut.damping + '" step="0.005" style="width:300px" id="graph_BH_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.barnesHut.damping + '" id="graph_BH_damp_value" style="width:60px"></td>' +
  26758. '</tr>' +
  26759. '</table>' +
  26760. '<table id="graph_R_table" style="display:none">' +
  26761. '<tr><td><b>Repulsion</b></td></tr>' +
  26762. '<tr>' +
  26763. '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.repulsion.nodeDistance + '" step="1" style="width:300px" id="graph_R_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.repulsion.nodeDistance + '" id="graph_R_nd_value" style="width:60px"></td>' +
  26764. '</tr>' +
  26765. '<tr>' +
  26766. '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.repulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_R_cg"></td><td>3</td><td><input value="' + this.constants.physics.repulsion.centralGravity + '" id="graph_R_cg_value" style="width:60px"></td>' +
  26767. '</tr>' +
  26768. '<tr>' +
  26769. '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.repulsion.springLength + '" step="1" style="width:300px" id="graph_R_sl"></td><td>500</td><td><input value="' + this.constants.physics.repulsion.springLength + '" id="graph_R_sl_value" style="width:60px"></td>' +
  26770. '</tr>' +
  26771. '<tr>' +
  26772. '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.repulsion.springConstant + '" step="0.001" style="width:300px" id="graph_R_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.repulsion.springConstant + '" id="graph_R_sc_value" style="width:60px"></td>' +
  26773. '</tr>' +
  26774. '<tr>' +
  26775. '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.repulsion.damping + '" step="0.005" style="width:300px" id="graph_R_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.repulsion.damping + '" id="graph_R_damp_value" style="width:60px"></td>' +
  26776. '</tr>' +
  26777. '</table>' +
  26778. '<table id="graph_H_table" style="display:none">' +
  26779. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  26780. '<tr>' +
  26781. '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" step="1" style="width:300px" id="graph_H_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" id="graph_H_nd_value" style="width:60px"></td>' +
  26782. '</tr>' +
  26783. '<tr>' +
  26784. '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_H_cg"></td><td>3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" id="graph_H_cg_value" style="width:60px"></td>' +
  26785. '</tr>' +
  26786. '<tr>' +
  26787. '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" step="1" style="width:300px" id="graph_H_sl"></td><td>500</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" id="graph_H_sl_value" style="width:60px"></td>' +
  26788. '</tr>' +
  26789. '<tr>' +
  26790. '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" step="0.001" style="width:300px" id="graph_H_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" id="graph_H_sc_value" style="width:60px"></td>' +
  26791. '</tr>' +
  26792. '<tr>' +
  26793. '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.hierarchicalRepulsion.damping + '" step="0.005" style="width:300px" id="graph_H_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.damping + '" id="graph_H_damp_value" style="width:60px"></td>' +
  26794. '</tr>' +
  26795. '<tr>' +
  26796. '<td width="150px">direction</td><td>1</td><td><input type="range" min="0" max="3" value="' + hierarchicalLayoutDirections.indexOf(this.constants.hierarchicalLayout.direction) + '" step="1" style="width:300px" id="graph_H_direction"></td><td>4</td><td><input value="' + this.constants.hierarchicalLayout.direction + '" id="graph_H_direction_value" style="width:60px"></td>' +
  26797. '</tr>' +
  26798. '<tr>' +
  26799. '<td width="150px">levelSeparation</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.levelSeparation + '" step="1" style="width:300px" id="graph_H_levsep"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.levelSeparation + '" id="graph_H_levsep_value" style="width:60px"></td>' +
  26800. '</tr>' +
  26801. '<tr>' +
  26802. '<td width="150px">nodeSpacing</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.nodeSpacing + '" step="1" style="width:300px" id="graph_H_nspac"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.nodeSpacing + '" id="graph_H_nspac_value" style="width:60px"></td>' +
  26803. '</tr>' +
  26804. '</table>' +
  26805. '<table><tr><td><b>Options:</b></td></tr>' +
  26806. '<tr>' +
  26807. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  26808. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  26809. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  26810. '</tr>' +
  26811. '</table>'
  26812. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  26813. this.optionsDiv = document.createElement("div");
  26814. this.optionsDiv.style.fontSize = "14px";
  26815. this.optionsDiv.style.fontFamily = "verdana";
  26816. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  26817. var rangeElement;
  26818. rangeElement = document.getElementById('graph_BH_gc');
  26819. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  26820. rangeElement = document.getElementById('graph_BH_cg');
  26821. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  26822. rangeElement = document.getElementById('graph_BH_sc');
  26823. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  26824. rangeElement = document.getElementById('graph_BH_sl');
  26825. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  26826. rangeElement = document.getElementById('graph_BH_damp');
  26827. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  26828. rangeElement = document.getElementById('graph_R_nd');
  26829. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  26830. rangeElement = document.getElementById('graph_R_cg');
  26831. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  26832. rangeElement = document.getElementById('graph_R_sc');
  26833. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  26834. rangeElement = document.getElementById('graph_R_sl');
  26835. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  26836. rangeElement = document.getElementById('graph_R_damp');
  26837. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  26838. rangeElement = document.getElementById('graph_H_nd');
  26839. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  26840. rangeElement = document.getElementById('graph_H_cg');
  26841. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  26842. rangeElement = document.getElementById('graph_H_sc');
  26843. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  26844. rangeElement = document.getElementById('graph_H_sl');
  26845. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  26846. rangeElement = document.getElementById('graph_H_damp');
  26847. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  26848. rangeElement = document.getElementById('graph_H_direction');
  26849. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  26850. rangeElement = document.getElementById('graph_H_levsep');
  26851. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  26852. rangeElement = document.getElementById('graph_H_nspac');
  26853. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  26854. var radioButton1 = document.getElementById("graph_physicsMethod1");
  26855. var radioButton2 = document.getElementById("graph_physicsMethod2");
  26856. var radioButton3 = document.getElementById("graph_physicsMethod3");
  26857. radioButton2.checked = true;
  26858. if (this.constants.physics.barnesHut.enabled) {
  26859. radioButton1.checked = true;
  26860. }
  26861. if (this.constants.hierarchicalLayout.enabled) {
  26862. radioButton3.checked = true;
  26863. }
  26864. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  26865. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  26866. var graph_generateOptions = document.getElementById("graph_generateOptions");
  26867. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  26868. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  26869. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  26870. if (this.constants.smoothCurves == true && this.constants.dynamicSmoothCurves == false) {
  26871. graph_toggleSmooth.style.background = "#A4FF56";
  26872. }
  26873. else {
  26874. graph_toggleSmooth.style.background = "#FF8532";
  26875. }
  26876. switchConfigurations.apply(this);
  26877. radioButton1.onchange = switchConfigurations.bind(this);
  26878. radioButton2.onchange = switchConfigurations.bind(this);
  26879. radioButton3.onchange = switchConfigurations.bind(this);
  26880. }
  26881. };
  26882. /**
  26883. * This overwrites the this.constants.
  26884. *
  26885. * @param constantsVariableName
  26886. * @param value
  26887. * @private
  26888. */
  26889. exports._overWriteGraphConstants = function (constantsVariableName, value) {
  26890. var nameArray = constantsVariableName.split("_");
  26891. if (nameArray.length == 1) {
  26892. this.constants[nameArray[0]] = value;
  26893. }
  26894. else if (nameArray.length == 2) {
  26895. this.constants[nameArray[0]][nameArray[1]] = value;
  26896. }
  26897. else if (nameArray.length == 3) {
  26898. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  26899. }
  26900. };
  26901. /**
  26902. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  26903. */
  26904. function graphToggleSmoothCurves () {
  26905. this.constants.smoothCurves.enabled = !this.constants.smoothCurves.enabled;
  26906. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  26907. if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  26908. else {graph_toggleSmooth.style.background = "#FF8532";}
  26909. this._configureSmoothCurves(false);
  26910. }
  26911. /**
  26912. * this function is used to scramble the nodes
  26913. *
  26914. */
  26915. function graphRepositionNodes () {
  26916. for (var nodeId in this.calculationNodes) {
  26917. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  26918. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  26919. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  26920. }
  26921. }
  26922. if (this.constants.hierarchicalLayout.enabled == true) {
  26923. this._setupHierarchicalLayout();
  26924. showValueOfRange.call(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  26925. showValueOfRange.call(this, 'graph_H_cg', 1, "physics_centralGravity");
  26926. showValueOfRange.call(this, 'graph_H_sc', 1, "physics_springConstant");
  26927. showValueOfRange.call(this, 'graph_H_sl', 1, "physics_springLength");
  26928. showValueOfRange.call(this, 'graph_H_damp', 1, "physics_damping");
  26929. }
  26930. else {
  26931. this.repositionNodes();
  26932. }
  26933. this.moving = true;
  26934. this.start();
  26935. }
  26936. /**
  26937. * this is used to generate an options file from the playing with physics system.
  26938. */
  26939. function graphGenerateOptions () {
  26940. var options = "No options are required, default values used.";
  26941. var optionsSpecific = [];
  26942. var radioButton1 = document.getElementById("graph_physicsMethod1");
  26943. var radioButton2 = document.getElementById("graph_physicsMethod2");
  26944. if (radioButton1.checked == true) {
  26945. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  26946. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  26947. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  26948. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  26949. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  26950. if (optionsSpecific.length != 0) {
  26951. options = "var options = {";
  26952. options += "physics: {barnesHut: {";
  26953. for (var i = 0; i < optionsSpecific.length; i++) {
  26954. options += optionsSpecific[i];
  26955. if (i < optionsSpecific.length - 1) {
  26956. options += ", "
  26957. }
  26958. }
  26959. options += '}}'
  26960. }
  26961. if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) {
  26962. if (optionsSpecific.length == 0) {options = "var options = {";}
  26963. else {options += ", "}
  26964. options += "smoothCurves: " + this.constants.smoothCurves.enabled;
  26965. }
  26966. if (options != "No options are required, default values used.") {
  26967. options += '};'
  26968. }
  26969. }
  26970. else if (radioButton2.checked == true) {
  26971. options = "var options = {";
  26972. options += "physics: {barnesHut: {enabled: false}";
  26973. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  26974. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  26975. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  26976. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  26977. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  26978. if (optionsSpecific.length != 0) {
  26979. options += ", repulsion: {";
  26980. for (var i = 0; i < optionsSpecific.length; i++) {
  26981. options += optionsSpecific[i];
  26982. if (i < optionsSpecific.length - 1) {
  26983. options += ", "
  26984. }
  26985. }
  26986. options += '}}'
  26987. }
  26988. if (optionsSpecific.length == 0) {options += "}"}
  26989. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  26990. options += ", smoothCurves: " + this.constants.smoothCurves;
  26991. }
  26992. options += '};'
  26993. }
  26994. else {
  26995. options = "var options = {";
  26996. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  26997. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  26998. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  26999. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  27000. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  27001. if (optionsSpecific.length != 0) {
  27002. options += "physics: {hierarchicalRepulsion: {";
  27003. for (var i = 0; i < optionsSpecific.length; i++) {
  27004. options += optionsSpecific[i];
  27005. if (i < optionsSpecific.length - 1) {
  27006. options += ", ";
  27007. }
  27008. }
  27009. options += '}},';
  27010. }
  27011. options += 'hierarchicalLayout: {';
  27012. optionsSpecific = [];
  27013. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  27014. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  27015. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  27016. if (optionsSpecific.length != 0) {
  27017. for (var i = 0; i < optionsSpecific.length; i++) {
  27018. options += optionsSpecific[i];
  27019. if (i < optionsSpecific.length - 1) {
  27020. options += ", "
  27021. }
  27022. }
  27023. options += '}'
  27024. }
  27025. else {
  27026. options += "enabled:true}";
  27027. }
  27028. options += '};'
  27029. }
  27030. this.optionsDiv.innerHTML = options;
  27031. }
  27032. /**
  27033. * this is used to switch between barnesHut, repulsion and hierarchical.
  27034. *
  27035. */
  27036. function switchConfigurations () {
  27037. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  27038. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  27039. var tableId = "graph_" + radioButton + "_table";
  27040. var table = document.getElementById(tableId);
  27041. table.style.display = "block";
  27042. for (var i = 0; i < ids.length; i++) {
  27043. if (ids[i] != tableId) {
  27044. table = document.getElementById(ids[i]);
  27045. table.style.display = "none";
  27046. }
  27047. }
  27048. this._restoreNodes();
  27049. if (radioButton == "R") {
  27050. this.constants.hierarchicalLayout.enabled = false;
  27051. this.constants.physics.hierarchicalRepulsion.enabled = false;
  27052. this.constants.physics.barnesHut.enabled = false;
  27053. }
  27054. else if (radioButton == "H") {
  27055. if (this.constants.hierarchicalLayout.enabled == false) {
  27056. this.constants.hierarchicalLayout.enabled = true;
  27057. this.constants.physics.hierarchicalRepulsion.enabled = true;
  27058. this.constants.physics.barnesHut.enabled = false;
  27059. this.constants.smoothCurves.enabled = false;
  27060. this._setupHierarchicalLayout();
  27061. }
  27062. }
  27063. else {
  27064. this.constants.hierarchicalLayout.enabled = false;
  27065. this.constants.physics.hierarchicalRepulsion.enabled = false;
  27066. this.constants.physics.barnesHut.enabled = true;
  27067. }
  27068. this._loadSelectedForceSolver();
  27069. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  27070. if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  27071. else {graph_toggleSmooth.style.background = "#FF8532";}
  27072. this.moving = true;
  27073. this.start();
  27074. }
  27075. /**
  27076. * this generates the ranges depending on the iniital values.
  27077. *
  27078. * @param id
  27079. * @param map
  27080. * @param constantsVariableName
  27081. */
  27082. function showValueOfRange (id,map,constantsVariableName) {
  27083. var valueId = id + "_value";
  27084. var rangeValue = document.getElementById(id).value;
  27085. if (Array.isArray(map)) {
  27086. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  27087. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  27088. }
  27089. else {
  27090. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  27091. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  27092. }
  27093. if (constantsVariableName == "hierarchicalLayout_direction" ||
  27094. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  27095. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  27096. this._setupHierarchicalLayout();
  27097. }
  27098. this.moving = true;
  27099. this.start();
  27100. }
  27101. /***/ },
  27102. /* 61 */
  27103. /***/ function(module, exports, __webpack_require__) {
  27104. /**
  27105. * Creation of the ClusterMixin var.
  27106. *
  27107. * This contains all the functions the Network object can use to employ clustering
  27108. */
  27109. /**
  27110. * This is only called in the constructor of the network object
  27111. *
  27112. */
  27113. exports.startWithClustering = function() {
  27114. // cluster if the data set is big
  27115. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  27116. // updates the lables after clustering
  27117. this.updateLabels();
  27118. // this is called here because if clusterin is disabled, the start and stabilize are called in
  27119. // the setData function.
  27120. if (this.constants.stabilize == true) {
  27121. this._stabilize();
  27122. }
  27123. this.start();
  27124. };
  27125. /**
  27126. * This function clusters until the initialMaxNodes has been reached
  27127. *
  27128. * @param {Number} maxNumberOfNodes
  27129. * @param {Boolean} reposition
  27130. */
  27131. exports.clusterToFit = function(maxNumberOfNodes, reposition) {
  27132. var numberOfNodes = this.nodeIndices.length;
  27133. var maxLevels = 50;
  27134. var level = 0;
  27135. // we first cluster the hubs, then we pull in the outliers, repeat
  27136. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  27137. if (level % 3 == 0.0) {
  27138. this.forceAggregateHubs(true);
  27139. this.normalizeClusterLevels();
  27140. }
  27141. else {
  27142. this.increaseClusterLevel(); // this also includes a cluster normalization
  27143. }
  27144. this.forceAggregateHubs(true);
  27145. numberOfNodes = this.nodeIndices.length;
  27146. level += 1;
  27147. }
  27148. // after the clustering we reposition the nodes to reduce the initial chaos
  27149. if (level > 0 && reposition == true) {
  27150. this.repositionNodes();
  27151. }
  27152. this._updateCalculationNodes();
  27153. };
  27154. /**
  27155. * This function can be called to open up a specific cluster.
  27156. * It will unpack the cluster back one level.
  27157. *
  27158. * @param node | Node object: cluster to open.
  27159. */
  27160. exports.openCluster = function(node) {
  27161. var isMovingBeforeClustering = this.moving;
  27162. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  27163. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  27164. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  27165. this._addSector(node);
  27166. var level = 0;
  27167. // we decluster until we reach a decent number of nodes
  27168. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  27169. this.decreaseClusterLevel();
  27170. level += 1;
  27171. }
  27172. }
  27173. else {
  27174. this._expandClusterNode(node,false,true);
  27175. // update the index list and labels
  27176. this._updateNodeIndexList();
  27177. this._updateCalculationNodes();
  27178. this.updateLabels();
  27179. }
  27180. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  27181. if (this.moving != isMovingBeforeClustering) {
  27182. this.start();
  27183. }
  27184. };
  27185. /**
  27186. * This calls the updateClustes with default arguments
  27187. */
  27188. exports.updateClustersDefault = function() {
  27189. if (this.constants.clustering.enabled == true && this.constants.clustering.clusterByZoom == true) {
  27190. this.updateClusters(0,false,false);
  27191. }
  27192. };
  27193. /**
  27194. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  27195. * be clustered with their connected node. This can be repeated as many times as needed.
  27196. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  27197. */
  27198. exports.increaseClusterLevel = function() {
  27199. this.updateClusters(-1,false,true);
  27200. };
  27201. /**
  27202. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  27203. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  27204. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  27205. */
  27206. exports.decreaseClusterLevel = function() {
  27207. this.updateClusters(1,false,true);
  27208. };
  27209. /**
  27210. * This is the main clustering function. It clusters and declusters on zoom or forced
  27211. * This function clusters on zoom, it can be called with a predefined zoom direction
  27212. * If out, check if we can form clusters, if in, check if we can open clusters.
  27213. * This function is only called from _zoom()
  27214. *
  27215. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  27216. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  27217. * @param {Boolean} force | enabled or disable forcing
  27218. * @param {Boolean} doNotStart | if true do not call start
  27219. *
  27220. */
  27221. exports.updateClusters = function(zoomDirection,recursive,force,doNotStart) {
  27222. var isMovingBeforeClustering = this.moving;
  27223. var amountOfNodes = this.nodeIndices.length;
  27224. var detectedZoomingIn = (this.previousScale < this.scale && zoomDirection == 0);
  27225. var detectedZoomingOut = (this.previousScale > this.scale && zoomDirection == 0);
  27226. // on zoom out collapse the sector if the scale is at the level the sector was made
  27227. if (detectedZoomingOut == true) {
  27228. this._collapseSector();
  27229. }
  27230. // check if we zoom in or out
  27231. if (detectedZoomingOut == true || zoomDirection == -1) { // zoom out
  27232. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  27233. // outer nodes determines if it is being clustered
  27234. this._formClusters(force);
  27235. }
  27236. else if (detectedZoomingIn == true || zoomDirection == 1) { // zoom in
  27237. if (force == true) {
  27238. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  27239. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  27240. this._openClusters(recursive,force);
  27241. }
  27242. else {
  27243. // if a cluster takes up a set percentage of the active window
  27244. //this._openClustersBySize();
  27245. this._openClusters(recursive, false);
  27246. }
  27247. }
  27248. this._updateNodeIndexList();
  27249. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  27250. if (this.nodeIndices.length == amountOfNodes && (detectedZoomingOut == true || zoomDirection == -1)) {
  27251. this._aggregateHubs(force);
  27252. this._updateNodeIndexList();
  27253. }
  27254. // we now reduce chains.
  27255. if (detectedZoomingOut == true || zoomDirection == -1) { // zoom out
  27256. this.handleChains();
  27257. this._updateNodeIndexList();
  27258. }
  27259. this.previousScale = this.scale;
  27260. // update labels
  27261. this.updateLabels();
  27262. // if a cluster was formed, we increase the clusterSession
  27263. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  27264. this.clusterSession += 1;
  27265. // if clusters have been made, we normalize the cluster level
  27266. this.normalizeClusterLevels();
  27267. }
  27268. if (doNotStart == false || doNotStart === undefined) {
  27269. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  27270. if (this.moving != isMovingBeforeClustering) {
  27271. this.start();
  27272. }
  27273. }
  27274. this._updateCalculationNodes();
  27275. };
  27276. /**
  27277. * This function handles the chains. It is called on every updateClusters().
  27278. */
  27279. exports.handleChains = function() {
  27280. // after clustering we check how many chains there are
  27281. var chainPercentage = this._getChainFraction();
  27282. if (chainPercentage > this.constants.clustering.chainThreshold) {
  27283. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  27284. }
  27285. };
  27286. /**
  27287. * this functions starts clustering by hubs
  27288. * The minimum hub threshold is set globally
  27289. *
  27290. * @private
  27291. */
  27292. exports._aggregateHubs = function(force) {
  27293. this._getHubSize();
  27294. this._formClustersByHub(force,false);
  27295. };
  27296. /**
  27297. * This function forces hubs to form.
  27298. *
  27299. */
  27300. exports.forceAggregateHubs = function(doNotStart) {
  27301. var isMovingBeforeClustering = this.moving;
  27302. var amountOfNodes = this.nodeIndices.length;
  27303. this._aggregateHubs(true);
  27304. // update the index list, dynamic edges and labels
  27305. this._updateNodeIndexList();
  27306. this.updateLabels();
  27307. this._updateCalculationNodes();
  27308. // if a cluster was formed, we increase the clusterSession
  27309. if (this.nodeIndices.length != amountOfNodes) {
  27310. this.clusterSession += 1;
  27311. }
  27312. if (doNotStart == false || doNotStart === undefined) {
  27313. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  27314. if (this.moving != isMovingBeforeClustering) {
  27315. this.start();
  27316. }
  27317. }
  27318. };
  27319. /**
  27320. * If a cluster takes up more than a set percentage of the screen, open the cluster
  27321. *
  27322. * @private
  27323. */
  27324. exports._openClustersBySize = function() {
  27325. if (this.constants.clustering.clusterByZoom == true) {
  27326. for (var nodeId in this.nodes) {
  27327. if (this.nodes.hasOwnProperty(nodeId)) {
  27328. var node = this.nodes[nodeId];
  27329. if (node.inView() == true) {
  27330. if ((node.width * this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  27331. (node.height * this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  27332. this.openCluster(node);
  27333. }
  27334. }
  27335. }
  27336. }
  27337. }
  27338. };
  27339. /**
  27340. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  27341. * has to be opened based on the current zoom level.
  27342. *
  27343. * @private
  27344. */
  27345. exports._openClusters = function(recursive,force) {
  27346. for (var i = 0; i < this.nodeIndices.length; i++) {
  27347. var node = this.nodes[this.nodeIndices[i]];
  27348. this._expandClusterNode(node,recursive,force);
  27349. this._updateCalculationNodes();
  27350. }
  27351. };
  27352. /**
  27353. * This function checks if a node has to be opened. This is done by checking the zoom level.
  27354. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  27355. * This recursive behaviour is optional and can be set by the recursive argument.
  27356. *
  27357. * @param {Node} parentNode | to check for cluster and expand
  27358. * @param {Boolean} recursive | enabled or disable recursive calling
  27359. * @param {Boolean} force | enabled or disable forcing
  27360. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  27361. * @private
  27362. */
  27363. exports._expandClusterNode = function(parentNode, recursive, force, openAll) {
  27364. // first check if node is a cluster
  27365. if (parentNode.clusterSize > 1) {
  27366. if (openAll === undefined) {
  27367. openAll = false;
  27368. }
  27369. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  27370. recursive = openAll || recursive;
  27371. // if the last child has been added on a smaller scale than current scale decluster
  27372. if (parentNode.formationScale < this.scale || force == true) {
  27373. // we will check if any of the contained child nodes should be removed from the cluster
  27374. for (var containedNodeId in parentNode.containedNodes) {
  27375. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  27376. var childNode = parentNode.containedNodes[containedNodeId];
  27377. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  27378. // the largest cluster is the one that comes from outside
  27379. if (force == true) {
  27380. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  27381. || openAll) {
  27382. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  27383. }
  27384. }
  27385. else {
  27386. if (this._nodeInActiveArea(parentNode)) {
  27387. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  27388. }
  27389. }
  27390. }
  27391. }
  27392. }
  27393. }
  27394. };
  27395. /**
  27396. * ONLY CALLED FROM _expandClusterNode
  27397. *
  27398. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  27399. * the child node from the parent contained_node object and put it back into the global nodes object.
  27400. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  27401. *
  27402. * @param {Node} parentNode | the parent node
  27403. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  27404. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  27405. * With force and recursive both true, the entire cluster is unpacked
  27406. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  27407. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  27408. * @private
  27409. */
  27410. exports._expelChildFromParent = function(parentNode, containedNodeId, recursive, force, openAll) {
  27411. var childNode = parentNode.containedNodes[containedNodeId]
  27412. // if child node has been added on smaller scale than current, kick out
  27413. if (childNode.formationScale < this.scale || force == true) {
  27414. // unselect all selected items
  27415. this._unselectAll();
  27416. // put the child node back in the global nodes object
  27417. this.nodes[containedNodeId] = childNode;
  27418. // release the contained edges from this childNode back into the global edges
  27419. this._releaseContainedEdges(parentNode,childNode);
  27420. // reconnect rerouted edges to the childNode
  27421. this._connectEdgeBackToChild(parentNode,childNode);
  27422. // validate all edges in dynamicEdges
  27423. this._validateEdges(parentNode);
  27424. // undo the changes from the clustering operation on the parent node
  27425. parentNode.options.mass -= childNode.options.mass;
  27426. parentNode.clusterSize -= childNode.clusterSize;
  27427. parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*(parentNode.clusterSize-1));
  27428. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  27429. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  27430. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  27431. // remove node from the list
  27432. delete parentNode.containedNodes[containedNodeId];
  27433. // check if there are other childs with this clusterSession in the parent.
  27434. var othersPresent = false;
  27435. for (var childNodeId in parentNode.containedNodes) {
  27436. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  27437. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  27438. othersPresent = true;
  27439. break;
  27440. }
  27441. }
  27442. }
  27443. // if there are no others, remove the cluster session from the list
  27444. if (othersPresent == false) {
  27445. parentNode.clusterSessions.pop();
  27446. }
  27447. this._repositionBezierNodes(childNode);
  27448. // this._repositionBezierNodes(parentNode);
  27449. // remove the clusterSession from the child node
  27450. childNode.clusterSession = 0;
  27451. // recalculate the size of the node on the next time the node is rendered
  27452. parentNode.clearSizeCache();
  27453. // restart the simulation to reorganise all nodes
  27454. this.moving = true;
  27455. }
  27456. // check if a further expansion step is possible if recursivity is enabled
  27457. if (recursive == true) {
  27458. this._expandClusterNode(childNode,recursive,force,openAll);
  27459. }
  27460. };
  27461. /**
  27462. * position the bezier nodes at the center of the edges
  27463. *
  27464. * @param node
  27465. * @private
  27466. */
  27467. exports._repositionBezierNodes = function(node) {
  27468. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27469. node.dynamicEdges[i].positionBezierNode();
  27470. }
  27471. };
  27472. /**
  27473. * This function checks if any nodes at the end of their trees have edges below a threshold length
  27474. * This function is called only from updateClusters()
  27475. * forceLevelCollapse ignores the length of the edge and collapses one level
  27476. * This means that a node with only one edge will be clustered with its connected node
  27477. *
  27478. * @private
  27479. * @param {Boolean} force
  27480. */
  27481. exports._formClusters = function(force) {
  27482. if (force == false) {
  27483. if (this.constants.clustering.clusterByZoom == true) {
  27484. this._formClustersByZoom();
  27485. }
  27486. }
  27487. else {
  27488. this._forceClustersByZoom();
  27489. }
  27490. };
  27491. /**
  27492. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  27493. *
  27494. * @private
  27495. */
  27496. exports._formClustersByZoom = function() {
  27497. var dx,dy,length;
  27498. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  27499. // check if any edges are shorter than minLength and start the clustering
  27500. // the clustering favours the node with the larger mass
  27501. for (var edgeId in this.edges) {
  27502. if (this.edges.hasOwnProperty(edgeId)) {
  27503. var edge = this.edges[edgeId];
  27504. if (edge.connected) {
  27505. if (edge.toId != edge.fromId) {
  27506. dx = (edge.to.x - edge.from.x);
  27507. dy = (edge.to.y - edge.from.y);
  27508. length = Math.sqrt(dx * dx + dy * dy);
  27509. if (length < minLength) {
  27510. // first check which node is larger
  27511. var parentNode = edge.from;
  27512. var childNode = edge.to;
  27513. if (edge.to.options.mass > edge.from.options.mass) {
  27514. parentNode = edge.to;
  27515. childNode = edge.from;
  27516. }
  27517. if (childNode.dynamicEdges.length == 1) {
  27518. this._addToCluster(parentNode,childNode,false);
  27519. }
  27520. else if (parentNode.dynamicEdges.length == 1) {
  27521. this._addToCluster(childNode,parentNode,false);
  27522. }
  27523. }
  27524. }
  27525. }
  27526. }
  27527. }
  27528. };
  27529. /**
  27530. * This function forces the network to cluster all nodes with only one connecting edge to their
  27531. * connected node.
  27532. *
  27533. * @private
  27534. */
  27535. exports._forceClustersByZoom = function() {
  27536. for (var nodeId in this.nodes) {
  27537. // another node could have absorbed this child.
  27538. if (this.nodes.hasOwnProperty(nodeId)) {
  27539. var childNode = this.nodes[nodeId];
  27540. // the edges can be swallowed by another decrease
  27541. if (childNode.dynamicEdges.length == 1) {
  27542. var edge = childNode.dynamicEdges[0];
  27543. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  27544. // group to the largest node
  27545. if (childNode.id != parentNode.id) {
  27546. if (parentNode.options.mass > childNode.options.mass) {
  27547. this._addToCluster(parentNode,childNode,true);
  27548. }
  27549. else {
  27550. this._addToCluster(childNode,parentNode,true);
  27551. }
  27552. }
  27553. }
  27554. }
  27555. }
  27556. };
  27557. /**
  27558. * To keep the nodes of roughly equal size we normalize the cluster levels.
  27559. * This function clusters a node to its smallest connected neighbour.
  27560. *
  27561. * @param node
  27562. * @private
  27563. */
  27564. exports._clusterToSmallestNeighbour = function(node) {
  27565. var smallestNeighbour = -1;
  27566. var smallestNeighbourNode = null;
  27567. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27568. if (node.dynamicEdges[i] !== undefined) {
  27569. var neighbour = null;
  27570. if (node.dynamicEdges[i].fromId != node.id) {
  27571. neighbour = node.dynamicEdges[i].from;
  27572. }
  27573. else if (node.dynamicEdges[i].toId != node.id) {
  27574. neighbour = node.dynamicEdges[i].to;
  27575. }
  27576. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  27577. smallestNeighbour = neighbour.clusterSessions.length;
  27578. smallestNeighbourNode = neighbour;
  27579. }
  27580. }
  27581. }
  27582. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  27583. this._addToCluster(neighbour, node, true);
  27584. }
  27585. };
  27586. /**
  27587. * This function forms clusters from hubs, it loops over all nodes
  27588. *
  27589. * @param {Boolean} force | Disregard zoom level
  27590. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  27591. * @private
  27592. */
  27593. exports._formClustersByHub = function(force, onlyEqual) {
  27594. // we loop over all nodes in the list
  27595. for (var nodeId in this.nodes) {
  27596. // we check if it is still available since it can be used by the clustering in this loop
  27597. if (this.nodes.hasOwnProperty(nodeId)) {
  27598. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  27599. }
  27600. }
  27601. };
  27602. /**
  27603. * This function forms a cluster from a specific preselected hub node
  27604. *
  27605. * @param {Node} hubNode | the node we will cluster as a hub
  27606. * @param {Boolean} force | Disregard zoom level
  27607. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  27608. * @param {Number} [absorptionSizeOffset] |
  27609. * @private
  27610. */
  27611. exports._formClusterFromHub = function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  27612. if (absorptionSizeOffset === undefined) {
  27613. absorptionSizeOffset = 0;
  27614. }
  27615. //this.hubThreshold = 43
  27616. //if (hubNode.dynamicEdgesLength < 0) {
  27617. // console.error(hubNode.dynamicEdgesLength, this.hubThreshold, onlyEqual)
  27618. //}
  27619. // we decide if the node is a hub
  27620. if ((hubNode.dynamicEdges.length >= this.hubThreshold && onlyEqual == false) ||
  27621. (hubNode.dynamicEdges.length == this.hubThreshold && onlyEqual == true)) {
  27622. // initialize variables
  27623. var dx,dy,length;
  27624. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  27625. var allowCluster = false;
  27626. // we create a list of edges because the dynamicEdges change over the course of this loop
  27627. var edgesIdarray = [];
  27628. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  27629. for (var j = 0; j < amountOfInitialEdges; j++) {
  27630. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  27631. }
  27632. // if the hub clustering is not forced, we check if one of the edges connected
  27633. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  27634. if (force == false) {
  27635. allowCluster = false;
  27636. for (j = 0; j < amountOfInitialEdges; j++) {
  27637. var edge = this.edges[edgesIdarray[j]];
  27638. if (edge !== undefined) {
  27639. if (edge.connected) {
  27640. if (edge.toId != edge.fromId) {
  27641. dx = (edge.to.x - edge.from.x);
  27642. dy = (edge.to.y - edge.from.y);
  27643. length = Math.sqrt(dx * dx + dy * dy);
  27644. if (length < minLength) {
  27645. allowCluster = true;
  27646. break;
  27647. }
  27648. }
  27649. }
  27650. }
  27651. }
  27652. }
  27653. // start the clustering if allowed
  27654. if ((!force && allowCluster) || force) {
  27655. var children = [];
  27656. var childrenIds = {};
  27657. // we loop over all edges INITIALLY connected to this hub to get a list of the childNodes
  27658. for (j = 0; j < amountOfInitialEdges; j++) {
  27659. edge = this.edges[edgesIdarray[j]];
  27660. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  27661. if (childrenIds[childNode.id] === undefined) {
  27662. childrenIds[childNode.id] = true;
  27663. children.push(childNode);
  27664. }
  27665. }
  27666. for (j = 0; j < children.length; j++) {
  27667. var childNode = children[j];
  27668. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  27669. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  27670. (childNode.id != hubNode.id)) {
  27671. this._addToCluster(hubNode,childNode,force);
  27672. }
  27673. else {
  27674. //console.log("WILL NOT MERGE:",childNode.dynamicEdges.length , (this.hubThreshold + absorptionSizeOffset))
  27675. }
  27676. }
  27677. }
  27678. }
  27679. };
  27680. /**
  27681. * This function adds the child node to the parent node, creating a cluster if it is not already.
  27682. *
  27683. * @param {Node} parentNode | this is the node that will house the child node
  27684. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  27685. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  27686. * @private
  27687. */
  27688. exports._addToCluster = function(parentNode, childNode, force) {
  27689. // join child node in the parent node
  27690. parentNode.containedNodes[childNode.id] = childNode;
  27691. //console.log(parentNode.id, childNode.id)
  27692. // manage all the edges connected to the child and parent nodes
  27693. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  27694. var edge = childNode.dynamicEdges[i];
  27695. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  27696. //console.log("COLLECT",parentNode.id, childNode.id, edge.toId, edge.fromId)
  27697. this._addToContainedEdges(parentNode,childNode,edge);
  27698. }
  27699. else {
  27700. //console.log("REWIRE",parentNode.id, childNode.id, edge.toId, edge.fromId)
  27701. this._connectEdgeToCluster(parentNode,childNode,edge);
  27702. }
  27703. }
  27704. // a contained node has no dynamic edges.
  27705. childNode.dynamicEdges = [];
  27706. // remove circular edges from clusters
  27707. this._containCircularEdgesFromNode(parentNode,childNode);
  27708. // remove the childNode from the global nodes object
  27709. delete this.nodes[childNode.id];
  27710. // update the properties of the child and parent
  27711. var massBefore = parentNode.options.mass;
  27712. childNode.clusterSession = this.clusterSession;
  27713. parentNode.options.mass += childNode.options.mass;
  27714. parentNode.clusterSize += childNode.clusterSize;
  27715. parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  27716. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  27717. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  27718. parentNode.clusterSessions.push(this.clusterSession);
  27719. }
  27720. // forced clusters only open from screen size and double tap
  27721. if (force == true) {
  27722. parentNode.formationScale = 0;
  27723. }
  27724. else {
  27725. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  27726. }
  27727. // recalculate the size of the node on the next time the node is rendered
  27728. parentNode.clearSizeCache();
  27729. // set the pop-out scale for the childnode
  27730. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  27731. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  27732. childNode.clearVelocity();
  27733. // the mass has altered, preservation of energy dictates the velocity to be updated
  27734. parentNode.updateVelocity(massBefore);
  27735. // restart the simulation to reorganise all nodes
  27736. this.moving = true;
  27737. };
  27738. /**
  27739. * This adds an edge from the childNode to the contained edges of the parent node
  27740. *
  27741. * @param parentNode | Node object
  27742. * @param childNode | Node object
  27743. * @param edge | Edge object
  27744. * @private
  27745. */
  27746. exports._addToContainedEdges = function(parentNode, childNode, edge) {
  27747. // create an array object if it does not yet exist for this childNode
  27748. if (parentNode.containedEdges[childNode.id] === undefined) {
  27749. parentNode.containedEdges[childNode.id] = []
  27750. }
  27751. // add this edge to the list
  27752. parentNode.containedEdges[childNode.id].push(edge);
  27753. // remove the edge from the global edges object
  27754. delete this.edges[edge.id];
  27755. // remove the edge from the parent object
  27756. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  27757. if (parentNode.dynamicEdges[i].id == edge.id) {
  27758. parentNode.dynamicEdges.splice(i,1);
  27759. break;
  27760. }
  27761. }
  27762. };
  27763. /**
  27764. * This function connects an edge that was connected to a child node to the parent node.
  27765. * It keeps track of which nodes it has been connected to with the originalId array.
  27766. *
  27767. * @param {Node} parentNode | Node object
  27768. * @param {Node} childNode | Node object
  27769. * @param {Edge} edge | Edge object
  27770. * @private
  27771. */
  27772. exports._connectEdgeToCluster = function(parentNode, childNode, edge) {
  27773. // handle circular edges
  27774. if (edge.toId == edge.fromId) {
  27775. this._addToContainedEdges(parentNode, childNode, edge);
  27776. }
  27777. else {
  27778. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  27779. edge.originalToId.push(childNode.id);
  27780. edge.to = parentNode;
  27781. edge.toId = parentNode.id;
  27782. }
  27783. else { // edge connected to other node with the "from" side
  27784. edge.originalFromId.push(childNode.id);
  27785. edge.from = parentNode;
  27786. edge.fromId = parentNode.id;
  27787. }
  27788. this._addToReroutedEdges(parentNode,childNode,edge);
  27789. }
  27790. };
  27791. /**
  27792. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  27793. * these edges inside of the cluster.
  27794. *
  27795. * @param parentNode
  27796. * @param childNode
  27797. * @private
  27798. */
  27799. exports._containCircularEdgesFromNode = function(parentNode, childNode) {
  27800. // manage all the edges connected to the child and parent nodes
  27801. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  27802. var edge = parentNode.dynamicEdges[i];
  27803. // handle circular edges
  27804. if (edge.toId == edge.fromId) {
  27805. this._addToContainedEdges(parentNode, childNode, edge);
  27806. }
  27807. }
  27808. };
  27809. /**
  27810. * This adds an edge from the childNode to the rerouted edges of the parent node
  27811. *
  27812. * @param parentNode | Node object
  27813. * @param childNode | Node object
  27814. * @param edge | Edge object
  27815. * @private
  27816. */
  27817. exports._addToReroutedEdges = function(parentNode, childNode, edge) {
  27818. // create an array object if it does not yet exist for this childNode
  27819. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  27820. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  27821. parentNode.reroutedEdges[childNode.id] = [];
  27822. }
  27823. parentNode.reroutedEdges[childNode.id].push(edge);
  27824. // this edge becomes part of the dynamicEdges of the cluster node
  27825. parentNode.dynamicEdges.push(edge);
  27826. };
  27827. /**
  27828. * This function connects an edge that was connected to a cluster node back to the child node.
  27829. *
  27830. * @param parentNode | Node object
  27831. * @param childNode | Node object
  27832. * @private
  27833. */
  27834. exports._connectEdgeBackToChild = function(parentNode, childNode) {
  27835. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  27836. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  27837. var edge = parentNode.reroutedEdges[childNode.id][i];
  27838. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  27839. edge.originalFromId.pop();
  27840. edge.fromId = childNode.id;
  27841. edge.from = childNode;
  27842. }
  27843. else {
  27844. edge.originalToId.pop();
  27845. edge.toId = childNode.id;
  27846. edge.to = childNode;
  27847. }
  27848. // append this edge to the list of edges connecting to the childnode
  27849. childNode.dynamicEdges.push(edge);
  27850. // remove the edge from the parent object
  27851. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  27852. if (parentNode.dynamicEdges[j].id == edge.id) {
  27853. parentNode.dynamicEdges.splice(j,1);
  27854. break;
  27855. }
  27856. }
  27857. }
  27858. // remove the entry from the rerouted edges
  27859. delete parentNode.reroutedEdges[childNode.id];
  27860. }
  27861. };
  27862. /**
  27863. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  27864. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  27865. * parentNode
  27866. *
  27867. * @param parentNode | Node object
  27868. * @private
  27869. */
  27870. exports._validateEdges = function(parentNode) {
  27871. var dynamicEdges = []
  27872. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  27873. var edge = parentNode.dynamicEdges[i];
  27874. if (parentNode.id == edge.toId || parentNode.id == edge.fromId) {
  27875. dynamicEdges.push(edge);
  27876. }
  27877. }
  27878. parentNode.dynamicEdges = dynamicEdges;
  27879. };
  27880. /**
  27881. * This function released the contained edges back into the global domain and puts them back into the
  27882. * dynamic edges of both parent and child.
  27883. *
  27884. * @param {Node} parentNode |
  27885. * @param {Node} childNode |
  27886. * @private
  27887. */
  27888. exports._releaseContainedEdges = function(parentNode, childNode) {
  27889. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  27890. var edge = parentNode.containedEdges[childNode.id][i];
  27891. // put the edge back in the global edges object
  27892. this.edges[edge.id] = edge;
  27893. // put the edge back in the dynamic edges of the child and parent
  27894. childNode.dynamicEdges.push(edge);
  27895. parentNode.dynamicEdges.push(edge);
  27896. }
  27897. // remove the entry from the contained edges
  27898. delete parentNode.containedEdges[childNode.id];
  27899. };
  27900. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  27901. /**
  27902. * This updates the node labels for all nodes (for debugging purposes)
  27903. */
  27904. exports.updateLabels = function() {
  27905. var nodeId;
  27906. // update node labels
  27907. for (nodeId in this.nodes) {
  27908. if (this.nodes.hasOwnProperty(nodeId)) {
  27909. var node = this.nodes[nodeId];
  27910. if (node.clusterSize > 1) {
  27911. node.label = "[".concat(String(node.clusterSize),"]");
  27912. }
  27913. }
  27914. }
  27915. // update node labels
  27916. for (nodeId in this.nodes) {
  27917. if (this.nodes.hasOwnProperty(nodeId)) {
  27918. node = this.nodes[nodeId];
  27919. if (node.clusterSize == 1) {
  27920. if (node.originalLabel !== undefined) {
  27921. node.label = node.originalLabel;
  27922. }
  27923. else {
  27924. node.label = String(node.id);
  27925. }
  27926. }
  27927. }
  27928. }
  27929. // /* Debug Override */
  27930. // for (nodeId in this.nodes) {
  27931. // if (this.nodes.hasOwnProperty(nodeId)) {
  27932. // node = this.nodes[nodeId];
  27933. // node.label = String(node.clusterSize + ":" + node.dynamicEdges.length);
  27934. // }
  27935. // }
  27936. };
  27937. /**
  27938. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  27939. * if the rest of the nodes are already a few cluster levels in.
  27940. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  27941. * clustered enough to the clusterToSmallestNeighbours function.
  27942. */
  27943. exports.normalizeClusterLevels = function() {
  27944. var maxLevel = 0;
  27945. var minLevel = 1e9;
  27946. var clusterLevel = 0;
  27947. var nodeId;
  27948. // we loop over all nodes in the list
  27949. for (nodeId in this.nodes) {
  27950. if (this.nodes.hasOwnProperty(nodeId)) {
  27951. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  27952. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  27953. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  27954. }
  27955. }
  27956. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  27957. var amountOfNodes = this.nodeIndices.length;
  27958. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  27959. // we loop over all nodes in the list
  27960. for (nodeId in this.nodes) {
  27961. if (this.nodes.hasOwnProperty(nodeId)) {
  27962. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  27963. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  27964. }
  27965. }
  27966. }
  27967. this._updateNodeIndexList();
  27968. // if a cluster was formed, we increase the clusterSession
  27969. if (this.nodeIndices.length != amountOfNodes) {
  27970. this.clusterSession += 1;
  27971. }
  27972. }
  27973. };
  27974. /**
  27975. * This function determines if the cluster we want to decluster is in the active area
  27976. * this means around the zoom center
  27977. *
  27978. * @param {Node} node
  27979. * @returns {boolean}
  27980. * @private
  27981. */
  27982. exports._nodeInActiveArea = function(node) {
  27983. return (
  27984. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  27985. &&
  27986. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  27987. )
  27988. };
  27989. /**
  27990. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  27991. * It puts large clusters away from the center and randomizes the order.
  27992. *
  27993. */
  27994. exports.repositionNodes = function() {
  27995. for (var i = 0; i < this.nodeIndices.length; i++) {
  27996. var node = this.nodes[this.nodeIndices[i]];
  27997. if ((node.xFixed == false || node.yFixed == false)) {
  27998. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.options.mass);
  27999. var angle = 2 * Math.PI * Math.random();
  28000. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  28001. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  28002. this._repositionBezierNodes(node);
  28003. }
  28004. }
  28005. };
  28006. /**
  28007. * We determine how many connections denote an important hub.
  28008. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  28009. *
  28010. * @private
  28011. */
  28012. exports._getHubSize = function() {
  28013. var average = 0;
  28014. var averageSquared = 0;
  28015. var hubCounter = 0;
  28016. var largestHub = 0;
  28017. for (var i = 0; i < this.nodeIndices.length; i++) {
  28018. var node = this.nodes[this.nodeIndices[i]];
  28019. if (node.dynamicEdges.length > largestHub) {
  28020. largestHub = node.dynamicEdges.length;
  28021. }
  28022. average += node.dynamicEdges.length;
  28023. averageSquared += Math.pow(node.dynamicEdges.length,2);
  28024. hubCounter += 1;
  28025. }
  28026. average = average / hubCounter;
  28027. averageSquared = averageSquared / hubCounter;
  28028. var variance = averageSquared - Math.pow(average,2);
  28029. var standardDeviation = Math.sqrt(variance);
  28030. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  28031. // always have at least one to cluster
  28032. if (this.hubThreshold > largestHub) {
  28033. this.hubThreshold = largestHub;
  28034. }
  28035. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  28036. // console.log("hubThreshold:",this.hubThreshold);
  28037. };
  28038. /**
  28039. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  28040. * with this amount we can cluster specifically on these chains.
  28041. *
  28042. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  28043. * @private
  28044. */
  28045. exports._reduceAmountOfChains = function(fraction) {
  28046. this.hubThreshold = 2;
  28047. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  28048. for (var nodeId in this.nodes) {
  28049. if (this.nodes.hasOwnProperty(nodeId)) {
  28050. if (this.nodes[nodeId].dynamicEdges.length == 2) {
  28051. if (reduceAmount > 0) {
  28052. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  28053. reduceAmount -= 1;
  28054. }
  28055. }
  28056. }
  28057. }
  28058. };
  28059. /**
  28060. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  28061. * with this amount we can cluster specifically on these chains.
  28062. *
  28063. * @private
  28064. */
  28065. exports._getChainFraction = function() {
  28066. var chains = 0;
  28067. var total = 0;
  28068. for (var nodeId in this.nodes) {
  28069. if (this.nodes.hasOwnProperty(nodeId)) {
  28070. if (this.nodes[nodeId].dynamicEdges.length == 2) {
  28071. chains += 1;
  28072. }
  28073. total += 1;
  28074. }
  28075. }
  28076. return chains/total;
  28077. };
  28078. /***/ },
  28079. /* 62 */
  28080. /***/ function(module, exports, __webpack_require__) {
  28081. var util = __webpack_require__(1);
  28082. var Node = __webpack_require__(40);
  28083. /**
  28084. * Creation of the SectorMixin var.
  28085. *
  28086. * This contains all the functions the Network object can use to employ the sector system.
  28087. * The sector system is always used by Network, though the benefits only apply to the use of clustering.
  28088. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  28089. */
  28090. /**
  28091. * This function is only called by the setData function of the Network object.
  28092. * This loads the global references into the active sector. This initializes the sector.
  28093. *
  28094. * @private
  28095. */
  28096. exports._putDataInSector = function() {
  28097. this.sectors["active"][this._sector()].nodes = this.nodes;
  28098. this.sectors["active"][this._sector()].edges = this.edges;
  28099. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  28100. };
  28101. /**
  28102. * /**
  28103. * This function sets the global references to nodes, edges and nodeIndices back to
  28104. * those of the supplied (active) sector. If a type is defined, do the specific type
  28105. *
  28106. * @param {String} sectorId
  28107. * @param {String} [sectorType] | "active" or "frozen"
  28108. * @private
  28109. */
  28110. exports._switchToSector = function(sectorId, sectorType) {
  28111. if (sectorType === undefined || sectorType == "active") {
  28112. this._switchToActiveSector(sectorId);
  28113. }
  28114. else {
  28115. this._switchToFrozenSector(sectorId);
  28116. }
  28117. };
  28118. /**
  28119. * This function sets the global references to nodes, edges and nodeIndices back to
  28120. * those of the supplied active sector.
  28121. *
  28122. * @param sectorId
  28123. * @private
  28124. */
  28125. exports._switchToActiveSector = function(sectorId) {
  28126. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  28127. this.nodes = this.sectors["active"][sectorId]["nodes"];
  28128. this.edges = this.sectors["active"][sectorId]["edges"];
  28129. };
  28130. /**
  28131. * This function sets the global references to nodes, edges and nodeIndices back to
  28132. * those of the supplied active sector.
  28133. *
  28134. * @private
  28135. */
  28136. exports._switchToSupportSector = function() {
  28137. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  28138. this.nodes = this.sectors["support"]["nodes"];
  28139. this.edges = this.sectors["support"]["edges"];
  28140. };
  28141. /**
  28142. * This function sets the global references to nodes, edges and nodeIndices back to
  28143. * those of the supplied frozen sector.
  28144. *
  28145. * @param sectorId
  28146. * @private
  28147. */
  28148. exports._switchToFrozenSector = function(sectorId) {
  28149. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  28150. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  28151. this.edges = this.sectors["frozen"][sectorId]["edges"];
  28152. };
  28153. /**
  28154. * This function sets the global references to nodes, edges and nodeIndices back to
  28155. * those of the currently active sector.
  28156. *
  28157. * @private
  28158. */
  28159. exports._loadLatestSector = function() {
  28160. this._switchToSector(this._sector());
  28161. };
  28162. /**
  28163. * This function returns the currently active sector Id
  28164. *
  28165. * @returns {String}
  28166. * @private
  28167. */
  28168. exports._sector = function() {
  28169. return this.activeSector[this.activeSector.length-1];
  28170. };
  28171. /**
  28172. * This function returns the previously active sector Id
  28173. *
  28174. * @returns {String}
  28175. * @private
  28176. */
  28177. exports._previousSector = function() {
  28178. if (this.activeSector.length > 1) {
  28179. return this.activeSector[this.activeSector.length-2];
  28180. }
  28181. else {
  28182. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  28183. }
  28184. };
  28185. /**
  28186. * We add the active sector at the end of the this.activeSector array
  28187. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  28188. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  28189. *
  28190. * @param newId
  28191. * @private
  28192. */
  28193. exports._setActiveSector = function(newId) {
  28194. this.activeSector.push(newId);
  28195. };
  28196. /**
  28197. * We remove the currently active sector id from the active sector stack. This happens when
  28198. * we reactivate the previously active sector
  28199. *
  28200. * @private
  28201. */
  28202. exports._forgetLastSector = function() {
  28203. this.activeSector.pop();
  28204. };
  28205. /**
  28206. * This function creates a new active sector with the supplied newId. This newId
  28207. * is the expanding node id.
  28208. *
  28209. * @param {String} newId | Id of the new active sector
  28210. * @private
  28211. */
  28212. exports._createNewSector = function(newId) {
  28213. // create the new sector
  28214. this.sectors["active"][newId] = {"nodes":{},
  28215. "edges":{},
  28216. "nodeIndices":[],
  28217. "formationScale": this.scale,
  28218. "drawingNode": undefined};
  28219. // create the new sector render node. This gives visual feedback that you are in a new sector.
  28220. this.sectors["active"][newId]['drawingNode'] = new Node(
  28221. {id:newId,
  28222. color: {
  28223. background: "#eaefef",
  28224. border: "495c5e"
  28225. }
  28226. },{},{},this.constants);
  28227. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  28228. };
  28229. /**
  28230. * This function removes the currently active sector. This is called when we create a new
  28231. * active sector.
  28232. *
  28233. * @param {String} sectorId | Id of the active sector that will be removed
  28234. * @private
  28235. */
  28236. exports._deleteActiveSector = function(sectorId) {
  28237. delete this.sectors["active"][sectorId];
  28238. };
  28239. /**
  28240. * This function removes the currently active sector. This is called when we reactivate
  28241. * the previously active sector.
  28242. *
  28243. * @param {String} sectorId | Id of the active sector that will be removed
  28244. * @private
  28245. */
  28246. exports._deleteFrozenSector = function(sectorId) {
  28247. delete this.sectors["frozen"][sectorId];
  28248. };
  28249. /**
  28250. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  28251. * We copy the references, then delete the active entree.
  28252. *
  28253. * @param sectorId
  28254. * @private
  28255. */
  28256. exports._freezeSector = function(sectorId) {
  28257. // we move the set references from the active to the frozen stack.
  28258. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  28259. // we have moved the sector data into the frozen set, we now remove it from the active set
  28260. this._deleteActiveSector(sectorId);
  28261. };
  28262. /**
  28263. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  28264. * object to the "active" object.
  28265. *
  28266. * @param sectorId
  28267. * @private
  28268. */
  28269. exports._activateSector = function(sectorId) {
  28270. // we move the set references from the frozen to the active stack.
  28271. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  28272. // we have moved the sector data into the active set, we now remove it from the frozen stack
  28273. this._deleteFrozenSector(sectorId);
  28274. };
  28275. /**
  28276. * This function merges the data from the currently active sector with a frozen sector. This is used
  28277. * in the process of reverting back to the previously active sector.
  28278. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  28279. * upon the creation of a new active sector.
  28280. *
  28281. * @param sectorId
  28282. * @private
  28283. */
  28284. exports._mergeThisWithFrozen = function(sectorId) {
  28285. // copy all nodes
  28286. for (var nodeId in this.nodes) {
  28287. if (this.nodes.hasOwnProperty(nodeId)) {
  28288. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  28289. }
  28290. }
  28291. // copy all edges (if not fully clustered, else there are no edges)
  28292. for (var edgeId in this.edges) {
  28293. if (this.edges.hasOwnProperty(edgeId)) {
  28294. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  28295. }
  28296. }
  28297. // merge the nodeIndices
  28298. for (var i = 0; i < this.nodeIndices.length; i++) {
  28299. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  28300. }
  28301. };
  28302. /**
  28303. * This clusters the sector to one cluster. It was a single cluster before this process started so
  28304. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  28305. *
  28306. * @private
  28307. */
  28308. exports._collapseThisToSingleCluster = function() {
  28309. this.clusterToFit(1,false);
  28310. };
  28311. /**
  28312. * We create a new active sector from the node that we want to open.
  28313. *
  28314. * @param node
  28315. * @private
  28316. */
  28317. exports._addSector = function(node) {
  28318. // this is the currently active sector
  28319. var sector = this._sector();
  28320. // // this should allow me to select nodes from a frozen set.
  28321. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  28322. // console.log("the node is part of the active sector");
  28323. // }
  28324. // else {
  28325. // console.log("I dont know what the fuck happened!!");
  28326. // }
  28327. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  28328. delete this.nodes[node.id];
  28329. var unqiueIdentifier = util.randomUUID();
  28330. // we fully freeze the currently active sector
  28331. this._freezeSector(sector);
  28332. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  28333. this._createNewSector(unqiueIdentifier);
  28334. // we add the active sector to the sectors array to be able to revert these steps later on
  28335. this._setActiveSector(unqiueIdentifier);
  28336. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  28337. this._switchToSector(this._sector());
  28338. // finally we add the node we removed from our previous active sector to the new active sector
  28339. this.nodes[node.id] = node;
  28340. };
  28341. /**
  28342. * We close the sector that is currently open and revert back to the one before.
  28343. * If the active sector is the "default" sector, nothing happens.
  28344. *
  28345. * @private
  28346. */
  28347. exports._collapseSector = function() {
  28348. // the currently active sector
  28349. var sector = this._sector();
  28350. // we cannot collapse the default sector
  28351. if (sector != "default") {
  28352. if ((this.nodeIndices.length == 1) ||
  28353. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  28354. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  28355. var previousSector = this._previousSector();
  28356. // we collapse the sector back to a single cluster
  28357. this._collapseThisToSingleCluster();
  28358. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  28359. // This previous sector is the one we will reactivate
  28360. this._mergeThisWithFrozen(previousSector);
  28361. // the previously active (frozen) sector now has all the data from the currently active sector.
  28362. // we can now delete the active sector.
  28363. this._deleteActiveSector(sector);
  28364. // we activate the previously active (and currently frozen) sector.
  28365. this._activateSector(previousSector);
  28366. // we load the references from the newly active sector into the global references
  28367. this._switchToSector(previousSector);
  28368. // we forget the previously active sector because we reverted to the one before
  28369. this._forgetLastSector();
  28370. // finally, we update the node index list.
  28371. this._updateNodeIndexList();
  28372. // we refresh the list with calulation nodes and calculation node indices.
  28373. this._updateCalculationNodes();
  28374. }
  28375. }
  28376. };
  28377. /**
  28378. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  28379. *
  28380. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  28381. * | we dont pass the function itself because then the "this" is the window object
  28382. * | instead of the Network object
  28383. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  28384. * @private
  28385. */
  28386. exports._doInAllActiveSectors = function(runFunction,argument) {
  28387. var returnValues = [];
  28388. if (argument === undefined) {
  28389. for (var sector in this.sectors["active"]) {
  28390. if (this.sectors["active"].hasOwnProperty(sector)) {
  28391. // switch the global references to those of this sector
  28392. this._switchToActiveSector(sector);
  28393. returnValues.push( this[runFunction]() );
  28394. }
  28395. }
  28396. }
  28397. else {
  28398. for (var sector in this.sectors["active"]) {
  28399. if (this.sectors["active"].hasOwnProperty(sector)) {
  28400. // switch the global references to those of this sector
  28401. this._switchToActiveSector(sector);
  28402. var args = Array.prototype.splice.call(arguments, 1);
  28403. if (args.length > 1) {
  28404. returnValues.push( this[runFunction](args[0],args[1]) );
  28405. }
  28406. else {
  28407. returnValues.push( this[runFunction](argument) );
  28408. }
  28409. }
  28410. }
  28411. }
  28412. // we revert the global references back to our active sector
  28413. this._loadLatestSector();
  28414. return returnValues;
  28415. };
  28416. /**
  28417. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  28418. *
  28419. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  28420. * | we dont pass the function itself because then the "this" is the window object
  28421. * | instead of the Network object
  28422. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  28423. * @private
  28424. */
  28425. exports._doInSupportSector = function(runFunction,argument) {
  28426. var returnValues = false;
  28427. if (argument === undefined) {
  28428. this._switchToSupportSector();
  28429. returnValues = this[runFunction]();
  28430. }
  28431. else {
  28432. this._switchToSupportSector();
  28433. var args = Array.prototype.splice.call(arguments, 1);
  28434. if (args.length > 1) {
  28435. returnValues = this[runFunction](args[0],args[1]);
  28436. }
  28437. else {
  28438. returnValues = this[runFunction](argument);
  28439. }
  28440. }
  28441. // we revert the global references back to our active sector
  28442. this._loadLatestSector();
  28443. return returnValues;
  28444. };
  28445. /**
  28446. * This runs a function in all frozen sectors. This is used in the _redraw().
  28447. *
  28448. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  28449. * | we don't pass the function itself because then the "this" is the window object
  28450. * | instead of the Network object
  28451. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  28452. * @private
  28453. */
  28454. exports._doInAllFrozenSectors = function(runFunction,argument) {
  28455. if (argument === undefined) {
  28456. for (var sector in this.sectors["frozen"]) {
  28457. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  28458. // switch the global references to those of this sector
  28459. this._switchToFrozenSector(sector);
  28460. this[runFunction]();
  28461. }
  28462. }
  28463. }
  28464. else {
  28465. for (var sector in this.sectors["frozen"]) {
  28466. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  28467. // switch the global references to those of this sector
  28468. this._switchToFrozenSector(sector);
  28469. var args = Array.prototype.splice.call(arguments, 1);
  28470. if (args.length > 1) {
  28471. this[runFunction](args[0],args[1]);
  28472. }
  28473. else {
  28474. this[runFunction](argument);
  28475. }
  28476. }
  28477. }
  28478. }
  28479. this._loadLatestSector();
  28480. };
  28481. /**
  28482. * This runs a function in all sectors. This is used in the _redraw().
  28483. *
  28484. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  28485. * | we don't pass the function itself because then the "this" is the window object
  28486. * | instead of the Network object
  28487. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  28488. * @private
  28489. */
  28490. exports._doInAllSectors = function(runFunction,argument) {
  28491. var args = Array.prototype.splice.call(arguments, 1);
  28492. if (argument === undefined) {
  28493. this._doInAllActiveSectors(runFunction);
  28494. this._doInAllFrozenSectors(runFunction);
  28495. }
  28496. else {
  28497. if (args.length > 1) {
  28498. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  28499. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  28500. }
  28501. else {
  28502. this._doInAllActiveSectors(runFunction,argument);
  28503. this._doInAllFrozenSectors(runFunction,argument);
  28504. }
  28505. }
  28506. };
  28507. /**
  28508. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  28509. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  28510. *
  28511. * @private
  28512. */
  28513. exports._clearNodeIndexList = function() {
  28514. var sector = this._sector();
  28515. this.sectors["active"][sector]["nodeIndices"] = [];
  28516. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  28517. };
  28518. /**
  28519. * Draw the encompassing sector node
  28520. *
  28521. * @param ctx
  28522. * @param sectorType
  28523. * @private
  28524. */
  28525. exports._drawSectorNodes = function(ctx,sectorType) {
  28526. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  28527. for (var sector in this.sectors[sectorType]) {
  28528. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  28529. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  28530. this._switchToSector(sector,sectorType);
  28531. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  28532. for (var nodeId in this.nodes) {
  28533. if (this.nodes.hasOwnProperty(nodeId)) {
  28534. node = this.nodes[nodeId];
  28535. node.resize(ctx);
  28536. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  28537. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  28538. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  28539. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  28540. }
  28541. }
  28542. node = this.sectors[sectorType][sector]["drawingNode"];
  28543. node.x = 0.5 * (maxX + minX);
  28544. node.y = 0.5 * (maxY + minY);
  28545. node.width = 2 * (node.x - minX);
  28546. node.height = 2 * (node.y - minY);
  28547. node.options.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  28548. node.setScale(this.scale);
  28549. node._drawCircle(ctx);
  28550. }
  28551. }
  28552. }
  28553. };
  28554. exports._drawAllSectorNodes = function(ctx) {
  28555. this._drawSectorNodes(ctx,"frozen");
  28556. this._drawSectorNodes(ctx,"active");
  28557. this._loadLatestSector();
  28558. };
  28559. /***/ },
  28560. /* 63 */
  28561. /***/ function(module, exports, __webpack_require__) {
  28562. var Node = __webpack_require__(40);
  28563. /**
  28564. * This function can be called from the _doInAllSectors function
  28565. *
  28566. * @param object
  28567. * @param overlappingNodes
  28568. * @private
  28569. */
  28570. exports._getNodesOverlappingWith = function(object, overlappingNodes) {
  28571. var nodes = this.nodes;
  28572. for (var nodeId in nodes) {
  28573. if (nodes.hasOwnProperty(nodeId)) {
  28574. if (nodes[nodeId].isOverlappingWith(object)) {
  28575. overlappingNodes.push(nodeId);
  28576. }
  28577. }
  28578. }
  28579. };
  28580. /**
  28581. * retrieve all nodes overlapping with given object
  28582. * @param {Object} object An object with parameters left, top, right, bottom
  28583. * @return {Number[]} An array with id's of the overlapping nodes
  28584. * @private
  28585. */
  28586. exports._getAllNodesOverlappingWith = function (object) {
  28587. var overlappingNodes = [];
  28588. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  28589. return overlappingNodes;
  28590. };
  28591. /**
  28592. * Return a position object in canvasspace from a single point in screenspace
  28593. *
  28594. * @param pointer
  28595. * @returns {{left: number, top: number, right: number, bottom: number}}
  28596. * @private
  28597. */
  28598. exports._pointerToPositionObject = function(pointer) {
  28599. var x = this._XconvertDOMtoCanvas(pointer.x);
  28600. var y = this._YconvertDOMtoCanvas(pointer.y);
  28601. return {
  28602. left: x,
  28603. top: y,
  28604. right: x,
  28605. bottom: y
  28606. };
  28607. };
  28608. /**
  28609. * Get the top node at the a specific point (like a click)
  28610. *
  28611. * @param {{x: Number, y: Number}} pointer
  28612. * @return {Node | null} node
  28613. * @private
  28614. */
  28615. exports._getNodeAt = function (pointer) {
  28616. // we first check if this is an navigation controls element
  28617. var positionObject = this._pointerToPositionObject(pointer);
  28618. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  28619. // if there are overlapping nodes, select the last one, this is the
  28620. // one which is drawn on top of the others
  28621. if (overlappingNodes.length > 0) {
  28622. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  28623. }
  28624. else {
  28625. return null;
  28626. }
  28627. };
  28628. /**
  28629. * retrieve all edges overlapping with given object, selector is around center
  28630. * @param {Object} object An object with parameters left, top, right, bottom
  28631. * @return {Number[]} An array with id's of the overlapping nodes
  28632. * @private
  28633. */
  28634. exports._getEdgesOverlappingWith = function (object, overlappingEdges) {
  28635. var edges = this.edges;
  28636. for (var edgeId in edges) {
  28637. if (edges.hasOwnProperty(edgeId)) {
  28638. if (edges[edgeId].isOverlappingWith(object)) {
  28639. overlappingEdges.push(edgeId);
  28640. }
  28641. }
  28642. }
  28643. };
  28644. /**
  28645. * retrieve all nodes overlapping with given object
  28646. * @param {Object} object An object with parameters left, top, right, bottom
  28647. * @return {Number[]} An array with id's of the overlapping nodes
  28648. * @private
  28649. */
  28650. exports._getAllEdgesOverlappingWith = function (object) {
  28651. var overlappingEdges = [];
  28652. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  28653. return overlappingEdges;
  28654. };
  28655. /**
  28656. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  28657. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  28658. *
  28659. * @param pointer
  28660. * @returns {null}
  28661. * @private
  28662. */
  28663. exports._getEdgeAt = function(pointer) {
  28664. var positionObject = this._pointerToPositionObject(pointer);
  28665. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  28666. if (overlappingEdges.length > 0) {
  28667. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  28668. }
  28669. else {
  28670. return null;
  28671. }
  28672. };
  28673. /**
  28674. * Add object to the selection array.
  28675. *
  28676. * @param obj
  28677. * @private
  28678. */
  28679. exports._addToSelection = function(obj) {
  28680. if (obj instanceof Node) {
  28681. this.selectionObj.nodes[obj.id] = obj;
  28682. }
  28683. else {
  28684. this.selectionObj.edges[obj.id] = obj;
  28685. }
  28686. };
  28687. /**
  28688. * Add object to the selection array.
  28689. *
  28690. * @param obj
  28691. * @private
  28692. */
  28693. exports._addToHover = function(obj) {
  28694. if (obj instanceof Node) {
  28695. this.hoverObj.nodes[obj.id] = obj;
  28696. }
  28697. else {
  28698. this.hoverObj.edges[obj.id] = obj;
  28699. }
  28700. };
  28701. /**
  28702. * Remove a single option from selection.
  28703. *
  28704. * @param {Object} obj
  28705. * @private
  28706. */
  28707. exports._removeFromSelection = function(obj) {
  28708. if (obj instanceof Node) {
  28709. delete this.selectionObj.nodes[obj.id];
  28710. }
  28711. else {
  28712. delete this.selectionObj.edges[obj.id];
  28713. }
  28714. };
  28715. /**
  28716. * Unselect all. The selectionObj is useful for this.
  28717. *
  28718. * @param {Boolean} [doNotTrigger] | ignore trigger
  28719. * @private
  28720. */
  28721. exports._unselectAll = function(doNotTrigger) {
  28722. if (doNotTrigger === undefined) {
  28723. doNotTrigger = false;
  28724. }
  28725. for(var nodeId in this.selectionObj.nodes) {
  28726. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  28727. this.selectionObj.nodes[nodeId].unselect();
  28728. }
  28729. }
  28730. for(var edgeId in this.selectionObj.edges) {
  28731. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  28732. this.selectionObj.edges[edgeId].unselect();
  28733. }
  28734. }
  28735. this.selectionObj = {nodes:{},edges:{}};
  28736. if (doNotTrigger == false) {
  28737. this.emit('select', this.getSelection());
  28738. }
  28739. };
  28740. /**
  28741. * Unselect all clusters. The selectionObj is useful for this.
  28742. *
  28743. * @param {Boolean} [doNotTrigger] | ignore trigger
  28744. * @private
  28745. */
  28746. exports._unselectClusters = function(doNotTrigger) {
  28747. if (doNotTrigger === undefined) {
  28748. doNotTrigger = false;
  28749. }
  28750. for (var nodeId in this.selectionObj.nodes) {
  28751. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  28752. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  28753. this.selectionObj.nodes[nodeId].unselect();
  28754. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  28755. }
  28756. }
  28757. }
  28758. if (doNotTrigger == false) {
  28759. this.emit('select', this.getSelection());
  28760. }
  28761. };
  28762. /**
  28763. * return the number of selected nodes
  28764. *
  28765. * @returns {number}
  28766. * @private
  28767. */
  28768. exports._getSelectedNodeCount = function() {
  28769. var count = 0;
  28770. for (var nodeId in this.selectionObj.nodes) {
  28771. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  28772. count += 1;
  28773. }
  28774. }
  28775. return count;
  28776. };
  28777. /**
  28778. * return the selected node
  28779. *
  28780. * @returns {number}
  28781. * @private
  28782. */
  28783. exports._getSelectedNode = function() {
  28784. for (var nodeId in this.selectionObj.nodes) {
  28785. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  28786. return this.selectionObj.nodes[nodeId];
  28787. }
  28788. }
  28789. return null;
  28790. };
  28791. /**
  28792. * return the selected edge
  28793. *
  28794. * @returns {number}
  28795. * @private
  28796. */
  28797. exports._getSelectedEdge = function() {
  28798. for (var edgeId in this.selectionObj.edges) {
  28799. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  28800. return this.selectionObj.edges[edgeId];
  28801. }
  28802. }
  28803. return null;
  28804. };
  28805. /**
  28806. * return the number of selected edges
  28807. *
  28808. * @returns {number}
  28809. * @private
  28810. */
  28811. exports._getSelectedEdgeCount = function() {
  28812. var count = 0;
  28813. for (var edgeId in this.selectionObj.edges) {
  28814. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  28815. count += 1;
  28816. }
  28817. }
  28818. return count;
  28819. };
  28820. /**
  28821. * return the number of selected objects.
  28822. *
  28823. * @returns {number}
  28824. * @private
  28825. */
  28826. exports._getSelectedObjectCount = function() {
  28827. var count = 0;
  28828. for(var nodeId in this.selectionObj.nodes) {
  28829. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  28830. count += 1;
  28831. }
  28832. }
  28833. for(var edgeId in this.selectionObj.edges) {
  28834. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  28835. count += 1;
  28836. }
  28837. }
  28838. return count;
  28839. };
  28840. /**
  28841. * Check if anything is selected
  28842. *
  28843. * @returns {boolean}
  28844. * @private
  28845. */
  28846. exports._selectionIsEmpty = function() {
  28847. for(var nodeId in this.selectionObj.nodes) {
  28848. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  28849. return false;
  28850. }
  28851. }
  28852. for(var edgeId in this.selectionObj.edges) {
  28853. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  28854. return false;
  28855. }
  28856. }
  28857. return true;
  28858. };
  28859. /**
  28860. * check if one of the selected nodes is a cluster.
  28861. *
  28862. * @returns {boolean}
  28863. * @private
  28864. */
  28865. exports._clusterInSelection = function() {
  28866. for(var nodeId in this.selectionObj.nodes) {
  28867. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  28868. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  28869. return true;
  28870. }
  28871. }
  28872. }
  28873. return false;
  28874. };
  28875. /**
  28876. * select the edges connected to the node that is being selected
  28877. *
  28878. * @param {Node} node
  28879. * @private
  28880. */
  28881. exports._selectConnectedEdges = function(node) {
  28882. for (var i = 0; i < node.dynamicEdges.length; i++) {
  28883. var edge = node.dynamicEdges[i];
  28884. edge.select();
  28885. this._addToSelection(edge);
  28886. }
  28887. };
  28888. /**
  28889. * select the edges connected to the node that is being selected
  28890. *
  28891. * @param {Node} node
  28892. * @private
  28893. */
  28894. exports._hoverConnectedEdges = function(node) {
  28895. for (var i = 0; i < node.dynamicEdges.length; i++) {
  28896. var edge = node.dynamicEdges[i];
  28897. edge.hover = true;
  28898. this._addToHover(edge);
  28899. }
  28900. };
  28901. /**
  28902. * unselect the edges connected to the node that is being selected
  28903. *
  28904. * @param {Node} node
  28905. * @private
  28906. */
  28907. exports._unselectConnectedEdges = function(node) {
  28908. for (var i = 0; i < node.dynamicEdges.length; i++) {
  28909. var edge = node.dynamicEdges[i];
  28910. edge.unselect();
  28911. this._removeFromSelection(edge);
  28912. }
  28913. };
  28914. /**
  28915. * This is called when someone clicks on a node. either select or deselect it.
  28916. * If there is an existing selection and we don't want to append to it, clear the existing selection
  28917. *
  28918. * @param {Node || Edge} object
  28919. * @param {Boolean} append
  28920. * @param {Boolean} [doNotTrigger] | ignore trigger
  28921. * @private
  28922. */
  28923. exports._selectObject = function(object, append, doNotTrigger, highlightEdges, overrideSelectable) {
  28924. if (doNotTrigger === undefined) {
  28925. doNotTrigger = false;
  28926. }
  28927. if (highlightEdges === undefined) {
  28928. highlightEdges = true;
  28929. }
  28930. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  28931. this._unselectAll(true);
  28932. }
  28933. // selectable allows the object to be selected. Override can be used if needed to bypass this.
  28934. if (object.selected == false && (this.constants.selectable == true || overrideSelectable)) {
  28935. object.select();
  28936. this._addToSelection(object);
  28937. if (object instanceof Node && this.blockConnectingEdgeSelection == false && highlightEdges == true) {
  28938. this._selectConnectedEdges(object);
  28939. }
  28940. }
  28941. // do not select the object if selectable is false, only add it to selection to allow drag to work
  28942. else if (object.selected == false) {
  28943. this._addToSelection(object);
  28944. doNotTrigger = true;
  28945. }
  28946. else {
  28947. object.unselect();
  28948. this._removeFromSelection(object);
  28949. }
  28950. if (doNotTrigger == false) {
  28951. this.emit('select', this.getSelection());
  28952. }
  28953. };
  28954. /**
  28955. * This is called when someone clicks on a node. either select or deselect it.
  28956. * If there is an existing selection and we don't want to append to it, clear the existing selection
  28957. *
  28958. * @param {Node || Edge} object
  28959. * @private
  28960. */
  28961. exports._blurObject = function(object) {
  28962. if (object.hover == true) {
  28963. object.hover = false;
  28964. this.emit("blurNode",{node:object.id});
  28965. }
  28966. };
  28967. /**
  28968. * This is called when someone clicks on a node. either select or deselect it.
  28969. * If there is an existing selection and we don't want to append to it, clear the existing selection
  28970. *
  28971. * @param {Node || Edge} object
  28972. * @private
  28973. */
  28974. exports._hoverObject = function(object) {
  28975. if (object.hover == false) {
  28976. object.hover = true;
  28977. this._addToHover(object);
  28978. if (object instanceof Node) {
  28979. this.emit("hoverNode",{node:object.id});
  28980. }
  28981. }
  28982. if (object instanceof Node) {
  28983. this._hoverConnectedEdges(object);
  28984. }
  28985. };
  28986. /**
  28987. * handles the selection part of the touch, only for navigation controls elements;
  28988. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  28989. * This is the most responsive solution
  28990. *
  28991. * @param {Object} pointer
  28992. * @private
  28993. */
  28994. exports._handleTouch = function(pointer) {
  28995. };
  28996. /**
  28997. * handles the selection part of the tap;
  28998. *
  28999. * @param {Object} pointer
  29000. * @private
  29001. */
  29002. exports._handleTap = function(pointer) {
  29003. var node = this._getNodeAt(pointer);
  29004. if (node != null) {
  29005. this._selectObject(node, false);
  29006. }
  29007. else {
  29008. var edge = this._getEdgeAt(pointer);
  29009. if (edge != null) {
  29010. this._selectObject(edge, false);
  29011. }
  29012. else {
  29013. this._unselectAll();
  29014. }
  29015. }
  29016. var properties = this.getSelection();
  29017. properties['pointer'] = {
  29018. DOM: {x: pointer.x, y: pointer.y},
  29019. canvas: {x: this._XconvertDOMtoCanvas(pointer.x), y: this._YconvertDOMtoCanvas(pointer.y)}
  29020. }
  29021. this.emit("click", properties);
  29022. this._requestRedraw();
  29023. };
  29024. /**
  29025. * handles the selection part of the double tap and opens a cluster if needed
  29026. *
  29027. * @param {Object} pointer
  29028. * @private
  29029. */
  29030. exports._handleDoubleTap = function(pointer) {
  29031. var node = this._getNodeAt(pointer);
  29032. if (node != null && node !== undefined) {
  29033. // we reset the areaCenter here so the opening of the node will occur
  29034. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  29035. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  29036. this.openCluster(node);
  29037. }
  29038. var properties = this.getSelection();
  29039. properties['pointer'] = {
  29040. DOM: {x: pointer.x, y: pointer.y},
  29041. canvas: {x: this._XconvertDOMtoCanvas(pointer.x), y: this._YconvertDOMtoCanvas(pointer.y)}
  29042. }
  29043. this.emit("doubleClick", properties);
  29044. };
  29045. /**
  29046. * Handle the onHold selection part
  29047. *
  29048. * @param pointer
  29049. * @private
  29050. */
  29051. exports._handleOnHold = function(pointer) {
  29052. var node = this._getNodeAt(pointer);
  29053. if (node != null) {
  29054. this._selectObject(node,true);
  29055. }
  29056. else {
  29057. var edge = this._getEdgeAt(pointer);
  29058. if (edge != null) {
  29059. this._selectObject(edge,true);
  29060. }
  29061. }
  29062. this._requestRedraw();
  29063. };
  29064. /**
  29065. * handle the onRelease event. These functions are here for the navigation controls module
  29066. * and data manipulation module.
  29067. *
  29068. * @private
  29069. */
  29070. exports._handleOnRelease = function(pointer) {
  29071. this._manipulationReleaseOverload(pointer);
  29072. this._navigationReleaseOverload(pointer);
  29073. };
  29074. exports._manipulationReleaseOverload = function (pointer) {};
  29075. exports._navigationReleaseOverload = function (pointer) {};
  29076. /**
  29077. *
  29078. * retrieve the currently selected objects
  29079. * @return {{nodes: Array.<String>, edges: Array.<String>}} selection
  29080. */
  29081. exports.getSelection = function() {
  29082. var nodeIds = this.getSelectedNodes();
  29083. var edgeIds = this.getSelectedEdges();
  29084. return {nodes:nodeIds, edges:edgeIds};
  29085. };
  29086. /**
  29087. *
  29088. * retrieve the currently selected nodes
  29089. * @return {String[]} selection An array with the ids of the
  29090. * selected nodes.
  29091. */
  29092. exports.getSelectedNodes = function() {
  29093. var idArray = [];
  29094. if (this.constants.selectable == true) {
  29095. for (var nodeId in this.selectionObj.nodes) {
  29096. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  29097. idArray.push(nodeId);
  29098. }
  29099. }
  29100. }
  29101. return idArray
  29102. };
  29103. /**
  29104. *
  29105. * retrieve the currently selected edges
  29106. * @return {Array} selection An array with the ids of the
  29107. * selected nodes.
  29108. */
  29109. exports.getSelectedEdges = function() {
  29110. var idArray = [];
  29111. if (this.constants.selectable == true) {
  29112. for (var edgeId in this.selectionObj.edges) {
  29113. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  29114. idArray.push(edgeId);
  29115. }
  29116. }
  29117. }
  29118. return idArray;
  29119. };
  29120. /**
  29121. * select zero or more nodes DEPRICATED
  29122. * @param {Number[] | String[]} selection An array with the ids of the
  29123. * selected nodes.
  29124. */
  29125. exports.setSelection = function() {
  29126. console.log("setSelection is deprecated. Please use selectNodes instead.")
  29127. };
  29128. /**
  29129. * select zero or more nodes with the option to highlight edges
  29130. * @param {Number[] | String[]} selection An array with the ids of the
  29131. * selected nodes.
  29132. * @param {boolean} [highlightEdges]
  29133. */
  29134. exports.selectNodes = function(selection, highlightEdges) {
  29135. var i, iMax, id;
  29136. if (!selection || (selection.length == undefined))
  29137. throw 'Selection must be an array with ids';
  29138. // first unselect any selected node
  29139. this._unselectAll(true);
  29140. for (i = 0, iMax = selection.length; i < iMax; i++) {
  29141. id = selection[i];
  29142. var node = this.nodes[id];
  29143. if (!node) {
  29144. throw new RangeError('Node with id "' + id + '" not found');
  29145. }
  29146. this._selectObject(node,true,true,highlightEdges,true);
  29147. }
  29148. this.redraw();
  29149. };
  29150. /**
  29151. * select zero or more edges
  29152. * @param {Number[] | String[]} selection An array with the ids of the
  29153. * selected nodes.
  29154. */
  29155. exports.selectEdges = function(selection) {
  29156. var i, iMax, id;
  29157. if (!selection || (selection.length == undefined))
  29158. throw 'Selection must be an array with ids';
  29159. // first unselect any selected node
  29160. this._unselectAll(true);
  29161. for (i = 0, iMax = selection.length; i < iMax; i++) {
  29162. id = selection[i];
  29163. var edge = this.edges[id];
  29164. if (!edge) {
  29165. throw new RangeError('Edge with id "' + id + '" not found');
  29166. }
  29167. this._selectObject(edge,true,true,false,true);
  29168. }
  29169. this.redraw();
  29170. };
  29171. /**
  29172. * Validate the selection: remove ids of nodes which no longer exist
  29173. * @private
  29174. */
  29175. exports._updateSelection = function () {
  29176. for(var nodeId in this.selectionObj.nodes) {
  29177. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  29178. if (!this.nodes.hasOwnProperty(nodeId)) {
  29179. delete this.selectionObj.nodes[nodeId];
  29180. }
  29181. }
  29182. }
  29183. for(var edgeId in this.selectionObj.edges) {
  29184. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  29185. if (!this.edges.hasOwnProperty(edgeId)) {
  29186. delete this.selectionObj.edges[edgeId];
  29187. }
  29188. }
  29189. }
  29190. };
  29191. /***/ },
  29192. /* 64 */
  29193. /***/ function(module, exports, __webpack_require__) {
  29194. var util = __webpack_require__(1);
  29195. var Node = __webpack_require__(40);
  29196. var Edge = __webpack_require__(37);
  29197. var Hammer = __webpack_require__(45);
  29198. /**
  29199. * clears the toolbar div element of children
  29200. *
  29201. * @private
  29202. */
  29203. exports._clearManipulatorBar = function() {
  29204. this._recursiveDOMDelete(this.manipulationDiv);
  29205. this.manipulationDOM = {};
  29206. this._cleanManipulatorHammers();
  29207. this._manipulationReleaseOverload = function () {};
  29208. delete this.sectors['support']['nodes']['targetNode'];
  29209. delete this.sectors['support']['nodes']['targetViaNode'];
  29210. this.controlNodesActive = false;
  29211. this.freezeSimulation(false);
  29212. };
  29213. exports._cleanManipulatorHammers = function() {
  29214. // clean hammer bindings
  29215. if (this.manipulationHammers.length != 0) {
  29216. for (var i = 0; i < this.manipulationHammers.length; i++) {
  29217. this.manipulationHammers[i].dispose();
  29218. }
  29219. this.manipulationHammers = [];
  29220. }
  29221. };
  29222. /**
  29223. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  29224. * these functions to their original functionality, we saved them in this.cachedFunctions.
  29225. * This function restores these functions to their original function.
  29226. *
  29227. * @private
  29228. */
  29229. exports._restoreOverloadedFunctions = function() {
  29230. for (var functionName in this.cachedFunctions) {
  29231. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  29232. this[functionName] = this.cachedFunctions[functionName];
  29233. delete this.cachedFunctions[functionName];
  29234. }
  29235. }
  29236. };
  29237. /**
  29238. * Enable or disable edit-mode.
  29239. *
  29240. * @private
  29241. */
  29242. exports._toggleEditMode = function() {
  29243. this.editMode = !this.editMode;
  29244. var toolbar = this.manipulationDiv;
  29245. var closeDiv = this.closeDiv;
  29246. var editModeDiv = this.editModeDiv;
  29247. if (this.editMode == true) {
  29248. toolbar.style.display="block";
  29249. closeDiv.style.display="block";
  29250. editModeDiv.style.display="none";
  29251. this._bindHammerToDiv(closeDiv,'_toggleEditMode');
  29252. }
  29253. else {
  29254. toolbar.style.display="none";
  29255. closeDiv.style.display="none";
  29256. editModeDiv.style.display="block";
  29257. }
  29258. this._createManipulatorBar()
  29259. };
  29260. /**
  29261. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  29262. *
  29263. * @private
  29264. */
  29265. exports._createManipulatorBar = function() {
  29266. // remove bound functions
  29267. if (this.boundFunction) {
  29268. this.off('select', this.boundFunction);
  29269. }
  29270. this._cleanManipulatorHammers();
  29271. var locale = this.constants.locales[this.constants.locale];
  29272. if (this.edgeBeingEdited !== undefined) {
  29273. this.edgeBeingEdited._disableControlNodes();
  29274. this.edgeBeingEdited = undefined;
  29275. this.selectedControlNode = null;
  29276. this.controlNodesActive = false;
  29277. this._redraw();
  29278. }
  29279. // restore overloaded functions
  29280. this._restoreOverloadedFunctions();
  29281. // resume calculation
  29282. this.freezeSimulation(false);
  29283. // reset global variables
  29284. this.blockConnectingEdgeSelection = false;
  29285. this.forceAppendSelection = false;
  29286. this.manipulationDOM = {};
  29287. if (this.editMode == true) {
  29288. while (this.manipulationDiv.hasChildNodes()) {
  29289. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  29290. }
  29291. this.manipulationDOM['addNodeSpan'] = document.createElement('div');
  29292. this.manipulationDOM['addNodeSpan'].className = 'network-manipulationUI add';
  29293. this.manipulationDOM['addNodeLabelSpan'] = document.createElement('div');
  29294. this.manipulationDOM['addNodeLabelSpan'].className = 'network-manipulationLabel';
  29295. this.manipulationDOM['addNodeLabelSpan'].innerHTML = locale['addNode'];
  29296. this.manipulationDOM['addNodeSpan'].appendChild(this.manipulationDOM['addNodeLabelSpan']);
  29297. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  29298. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  29299. this.manipulationDOM['addEdgeSpan'] = document.createElement('div');
  29300. this.manipulationDOM['addEdgeSpan'].className = 'network-manipulationUI connect';
  29301. this.manipulationDOM['addEdgeLabelSpan'] = document.createElement('div');
  29302. this.manipulationDOM['addEdgeLabelSpan'].className = 'network-manipulationLabel';
  29303. this.manipulationDOM['addEdgeLabelSpan'].innerHTML = locale['addEdge'];
  29304. this.manipulationDOM['addEdgeSpan'].appendChild(this.manipulationDOM['addEdgeLabelSpan']);
  29305. this.manipulationDiv.appendChild(this.manipulationDOM['addNodeSpan']);
  29306. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  29307. this.manipulationDiv.appendChild(this.manipulationDOM['addEdgeSpan']);
  29308. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  29309. this.manipulationDOM['seperatorLineDiv2'] = document.createElement('div');
  29310. this.manipulationDOM['seperatorLineDiv2'].className = 'network-seperatorLine';
  29311. this.manipulationDOM['editNodeSpan'] = document.createElement('div');
  29312. this.manipulationDOM['editNodeSpan'].className = 'network-manipulationUI edit node';
  29313. this.manipulationDOM['editNodeLabelSpan'] = document.createElement('div');
  29314. this.manipulationDOM['editNodeLabelSpan'].className = 'network-manipulationLabel';
  29315. this.manipulationDOM['editNodeLabelSpan'].innerHTML = locale['editNode'];
  29316. this.manipulationDOM['editNodeSpan'].appendChild(this.manipulationDOM['editNodeLabelSpan']);
  29317. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv2']);
  29318. this.manipulationDiv.appendChild(this.manipulationDOM['editNodeSpan']);
  29319. }
  29320. else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
  29321. this.manipulationDOM['seperatorLineDiv3'] = document.createElement('div');
  29322. this.manipulationDOM['seperatorLineDiv3'].className = 'network-seperatorLine';
  29323. this.manipulationDOM['editEdgeSpan'] = document.createElement('div');
  29324. this.manipulationDOM['editEdgeSpan'].className = 'network-manipulationUI edit edge';
  29325. this.manipulationDOM['editEdgeLabelSpan'] = document.createElement('div');
  29326. this.manipulationDOM['editEdgeLabelSpan'].className = 'network-manipulationLabel';
  29327. this.manipulationDOM['editEdgeLabelSpan'].innerHTML = locale['editEdge'];
  29328. this.manipulationDOM['editEdgeSpan'].appendChild(this.manipulationDOM['editEdgeLabelSpan']);
  29329. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv3']);
  29330. this.manipulationDiv.appendChild(this.manipulationDOM['editEdgeSpan']);
  29331. }
  29332. if (this._selectionIsEmpty() == false) {
  29333. this.manipulationDOM['seperatorLineDiv4'] = document.createElement('div');
  29334. this.manipulationDOM['seperatorLineDiv4'].className = 'network-seperatorLine';
  29335. this.manipulationDOM['deleteSpan'] = document.createElement('div');
  29336. this.manipulationDOM['deleteSpan'].className = 'network-manipulationUI delete';
  29337. this.manipulationDOM['deleteLabelSpan'] = document.createElement('div');
  29338. this.manipulationDOM['deleteLabelSpan'].className = 'network-manipulationLabel';
  29339. this.manipulationDOM['deleteLabelSpan'].innerHTML = locale['del'];
  29340. this.manipulationDOM['deleteSpan'].appendChild(this.manipulationDOM['deleteLabelSpan']);
  29341. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv4']);
  29342. this.manipulationDiv.appendChild(this.manipulationDOM['deleteSpan']);
  29343. }
  29344. // bind the icons
  29345. this._bindHammerToDiv(this.manipulationDOM['addNodeSpan'],'_createAddNodeToolbar');
  29346. this._bindHammerToDiv(this.manipulationDOM['addEdgeSpan'],'_createAddEdgeToolbar');
  29347. this._bindHammerToDiv(this.closeDiv,'_toggleEditMode');
  29348. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  29349. this._bindHammerToDiv(this.manipulationDOM['editNodeSpan'],'_editNode');
  29350. }
  29351. else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
  29352. this._bindHammerToDiv(this.manipulationDOM['editEdgeSpan'],'_createEditEdgeToolbar');
  29353. }
  29354. if (this._selectionIsEmpty() == false) {
  29355. this._bindHammerToDiv(this.manipulationDOM['deleteSpan'],'_deleteSelected');
  29356. }
  29357. var me = this;
  29358. this.boundFunction = me._createManipulatorBar;
  29359. this.on('select', this.boundFunction);
  29360. }
  29361. else {
  29362. while (this.editModeDiv.hasChildNodes()) {
  29363. this.editModeDiv.removeChild(this.editModeDiv.firstChild);
  29364. }
  29365. this.manipulationDOM['editModeSpan'] = document.createElement('div');
  29366. this.manipulationDOM['editModeSpan'].className = 'network-manipulationUI edit editmode';
  29367. this.manipulationDOM['editModeLabelSpan'] = document.createElement('div');
  29368. this.manipulationDOM['editModeLabelSpan'].className = 'network-manipulationLabel';
  29369. this.manipulationDOM['editModeLabelSpan'].innerHTML = locale['edit'];
  29370. this.manipulationDOM['editModeSpan'].appendChild(this.manipulationDOM['editModeLabelSpan']);
  29371. this.editModeDiv.appendChild(this.manipulationDOM['editModeSpan']);
  29372. this._bindHammerToDiv(this.manipulationDOM['editModeSpan'],'_toggleEditMode');
  29373. }
  29374. };
  29375. exports._bindHammerToDiv = function(domElement, funct) {
  29376. var hammer = Hammer(domElement, {prevent_default: true});
  29377. hammer.on('touch', this[funct].bind(this));
  29378. this.manipulationHammers.push(hammer);
  29379. }
  29380. /**
  29381. * Create the toolbar for adding Nodes
  29382. *
  29383. * @private
  29384. */
  29385. exports._createAddNodeToolbar = function() {
  29386. // clear the toolbar
  29387. this._clearManipulatorBar();
  29388. if (this.boundFunction) {
  29389. this.off('select', this.boundFunction);
  29390. }
  29391. var locale = this.constants.locales[this.constants.locale];
  29392. this.manipulationDOM = {};
  29393. this.manipulationDOM['backSpan'] = document.createElement('div');
  29394. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  29395. this.manipulationDOM['backLabelSpan'] = document.createElement('div');
  29396. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  29397. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  29398. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  29399. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  29400. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  29401. this.manipulationDOM['descriptionSpan'] = document.createElement('div');
  29402. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  29403. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('div');
  29404. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  29405. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['addDescription'];
  29406. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  29407. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  29408. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  29409. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  29410. // bind the icon
  29411. this._bindHammerToDiv(this.manipulationDOM['backSpan'],'_createManipulatorBar');
  29412. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  29413. var me = this;
  29414. this.boundFunction = me._addNode;
  29415. this.on('select', this.boundFunction);
  29416. };
  29417. /**
  29418. * create the toolbar to connect nodes
  29419. *
  29420. * @private
  29421. */
  29422. exports._createAddEdgeToolbar = function() {
  29423. // clear the toolbar
  29424. this._clearManipulatorBar();
  29425. this._unselectAll(true);
  29426. this.freezeSimulation(true);
  29427. if (this.boundFunction) {
  29428. this.off('select', this.boundFunction);
  29429. }
  29430. var locale = this.constants.locales[this.constants.locale];
  29431. this._unselectAll();
  29432. this.forceAppendSelection = false;
  29433. this.blockConnectingEdgeSelection = true;
  29434. this.manipulationDOM = {};
  29435. this.manipulationDOM['backSpan'] = document.createElement('div');
  29436. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  29437. this.manipulationDOM['backLabelSpan'] = document.createElement('div');
  29438. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  29439. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  29440. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  29441. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  29442. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  29443. this.manipulationDOM['descriptionSpan'] = document.createElement('div');
  29444. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  29445. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('div');
  29446. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  29447. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['edgeDescription'];
  29448. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  29449. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  29450. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  29451. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  29452. // bind the icon
  29453. this._bindHammerToDiv(this.manipulationDOM['backSpan'],'_createManipulatorBar');
  29454. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  29455. var me = this;
  29456. this.boundFunction = me._handleConnect;
  29457. this.on('select', this.boundFunction);
  29458. // temporarily overload functions
  29459. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  29460. this.cachedFunctions["_manipulationReleaseOverload"] = this._manipulationReleaseOverload;
  29461. this.cachedFunctions["_handleDragStart"] = this._handleDragStart;
  29462. this.cachedFunctions["_handleDragEnd"] = this._handleDragEnd;
  29463. this.cachedFunctions["_handleOnHold"] = this._handleOnHold;
  29464. this._handleTouch = this._handleConnect;
  29465. this._manipulationReleaseOverload = function () {};
  29466. this._handleOnHold = function () {};
  29467. this._handleDragStart = function () {};
  29468. this._handleDragEnd = this._finishConnect;
  29469. // redraw to show the unselect
  29470. this._redraw();
  29471. };
  29472. /**
  29473. * create the toolbar to edit edges
  29474. *
  29475. * @private
  29476. */
  29477. exports._createEditEdgeToolbar = function() {
  29478. // clear the toolbar
  29479. this._clearManipulatorBar();
  29480. this.controlNodesActive = true;
  29481. if (this.boundFunction) {
  29482. this.off('select', this.boundFunction);
  29483. }
  29484. this.edgeBeingEdited = this._getSelectedEdge();
  29485. this.edgeBeingEdited._enableControlNodes();
  29486. var locale = this.constants.locales[this.constants.locale];
  29487. this.manipulationDOM = {};
  29488. this.manipulationDOM['backSpan'] = document.createElement('div');
  29489. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  29490. this.manipulationDOM['backLabelSpan'] = document.createElement('div');
  29491. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  29492. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  29493. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  29494. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  29495. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  29496. this.manipulationDOM['descriptionSpan'] = document.createElement('div');
  29497. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  29498. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('div');
  29499. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  29500. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['editEdgeDescription'];
  29501. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  29502. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  29503. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  29504. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  29505. // bind the icon
  29506. this._bindHammerToDiv(this.manipulationDOM['backSpan'],'_createManipulatorBar');
  29507. // temporarily overload functions
  29508. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  29509. this.cachedFunctions["_manipulationReleaseOverload"] = this._manipulationReleaseOverload;
  29510. this.cachedFunctions["_handleTap"] = this._handleTap;
  29511. this.cachedFunctions["_handleDragStart"] = this._handleDragStart;
  29512. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  29513. this._handleTouch = this._selectControlNode;
  29514. this._handleTap = function () {};
  29515. this._handleOnDrag = this._controlNodeDrag;
  29516. this._handleDragStart = function () {}
  29517. this._manipulationReleaseOverload = this._releaseControlNode;
  29518. // redraw to show the unselect
  29519. this._redraw();
  29520. };
  29521. /**
  29522. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  29523. * to walk the user through the process.
  29524. *
  29525. * @private
  29526. */
  29527. exports._selectControlNode = function(pointer) {
  29528. this.edgeBeingEdited.controlNodes.from.unselect();
  29529. this.edgeBeingEdited.controlNodes.to.unselect();
  29530. this.selectedControlNode = this.edgeBeingEdited._getSelectedControlNode(this._XconvertDOMtoCanvas(pointer.x),this._YconvertDOMtoCanvas(pointer.y));
  29531. if (this.selectedControlNode !== null) {
  29532. this.selectedControlNode.select();
  29533. this.freezeSimulation(true);
  29534. }
  29535. this._redraw();
  29536. };
  29537. /**
  29538. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  29539. * to walk the user through the process.
  29540. *
  29541. * @private
  29542. */
  29543. exports._controlNodeDrag = function(event) {
  29544. var pointer = this._getPointer(event.gesture.center);
  29545. if (this.selectedControlNode !== null && this.selectedControlNode !== undefined) {
  29546. this.selectedControlNode.x = this._XconvertDOMtoCanvas(pointer.x);
  29547. this.selectedControlNode.y = this._YconvertDOMtoCanvas(pointer.y);
  29548. }
  29549. this._redraw();
  29550. };
  29551. /**
  29552. *
  29553. * @param pointer
  29554. * @private
  29555. */
  29556. exports._releaseControlNode = function(pointer) {
  29557. var newNode = this._getNodeAt(pointer);
  29558. if (newNode !== null) {
  29559. if (this.edgeBeingEdited.controlNodes.from.selected == true) {
  29560. this.edgeBeingEdited._restoreControlNodes();
  29561. this._editEdge(newNode.id, this.edgeBeingEdited.to.id);
  29562. this.edgeBeingEdited.controlNodes.from.unselect();
  29563. }
  29564. if (this.edgeBeingEdited.controlNodes.to.selected == true) {
  29565. this.edgeBeingEdited._restoreControlNodes();
  29566. this._editEdge(this.edgeBeingEdited.from.id, newNode.id);
  29567. this.edgeBeingEdited.controlNodes.to.unselect();
  29568. }
  29569. }
  29570. else {
  29571. this.edgeBeingEdited._restoreControlNodes();
  29572. }
  29573. this.freezeSimulation(false);
  29574. this._redraw();
  29575. };
  29576. /**
  29577. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  29578. * to walk the user through the process.
  29579. *
  29580. * @private
  29581. */
  29582. exports._handleConnect = function(pointer) {
  29583. if (this._getSelectedNodeCount() == 0) {
  29584. var node = this._getNodeAt(pointer);
  29585. if (node != null) {
  29586. if (node.clusterSize > 1) {
  29587. alert(this.constants.locales[this.constants.locale]['createEdgeError'])
  29588. }
  29589. else {
  29590. this._selectObject(node,false);
  29591. var supportNodes = this.sectors['support']['nodes'];
  29592. // create a node the temporary line can look at
  29593. supportNodes['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  29594. var targetNode = supportNodes['targetNode'];
  29595. targetNode.x = node.x;
  29596. targetNode.y = node.y;
  29597. // create a temporary edge
  29598. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:targetNode.id}, this, this.constants);
  29599. var connectionEdge = this.edges['connectionEdge'];
  29600. connectionEdge.from = node;
  29601. connectionEdge.connected = true;
  29602. connectionEdge.options.smoothCurves = {enabled: true,
  29603. dynamic: false,
  29604. type: "continuous",
  29605. roundness: 0.5
  29606. };
  29607. connectionEdge.selected = true;
  29608. connectionEdge.to = targetNode;
  29609. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  29610. var me = this;
  29611. this._handleOnDrag = function(event) {
  29612. var pointer = this._getPointer(event.gesture.center);
  29613. var connectionEdge = me.edges['connectionEdge'];
  29614. connectionEdge.to.x = me._XconvertDOMtoCanvas(pointer.x);
  29615. connectionEdge.to.y = me._YconvertDOMtoCanvas(pointer.y);
  29616. me._redraw();
  29617. };
  29618. this.moving = true;
  29619. this.start();
  29620. }
  29621. }
  29622. }
  29623. };
  29624. exports._finishConnect = function(event) {
  29625. if (this._getSelectedNodeCount() == 1) {
  29626. var pointer = this._getPointer(event.gesture.center);
  29627. // restore the drag function
  29628. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  29629. delete this.cachedFunctions["_handleOnDrag"];
  29630. // remember the edge id
  29631. var connectFromId = this.edges['connectionEdge'].fromId;
  29632. // remove the temporary nodes and edge
  29633. delete this.edges['connectionEdge'];
  29634. delete this.sectors['support']['nodes']['targetNode'];
  29635. delete this.sectors['support']['nodes']['targetViaNode'];
  29636. var node = this._getNodeAt(pointer);
  29637. if (node != null) {
  29638. if (node.clusterSize > 1) {
  29639. alert(this.constants.locales[this.constants.locale]["createEdgeError"])
  29640. }
  29641. else {
  29642. this._createEdge(connectFromId,node.id);
  29643. this._createManipulatorBar();
  29644. }
  29645. }
  29646. this._unselectAll();
  29647. }
  29648. };
  29649. /**
  29650. * Adds a node on the specified location
  29651. */
  29652. exports._addNode = function() {
  29653. if (this._selectionIsEmpty() && this.editMode == true) {
  29654. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  29655. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  29656. if (this.triggerFunctions.add) {
  29657. if (this.triggerFunctions.add.length == 2) {
  29658. var me = this;
  29659. this.triggerFunctions.add(defaultData, function(finalizedData) {
  29660. me.nodesData.add(finalizedData);
  29661. me._createManipulatorBar();
  29662. me.moving = true;
  29663. me.start();
  29664. });
  29665. }
  29666. else {
  29667. throw new Error('The function for add does not support two arguments (data,callback)');
  29668. this._createManipulatorBar();
  29669. this.moving = true;
  29670. this.start();
  29671. }
  29672. }
  29673. else {
  29674. this.nodesData.add(defaultData);
  29675. this._createManipulatorBar();
  29676. this.moving = true;
  29677. this.start();
  29678. }
  29679. }
  29680. };
  29681. /**
  29682. * connect two nodes with a new edge.
  29683. *
  29684. * @private
  29685. */
  29686. exports._createEdge = function(sourceNodeId,targetNodeId) {
  29687. if (this.editMode == true) {
  29688. var defaultData = {from:sourceNodeId, to:targetNodeId};
  29689. if (this.triggerFunctions.connect) {
  29690. if (this.triggerFunctions.connect.length == 2) {
  29691. var me = this;
  29692. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  29693. me.edgesData.add(finalizedData);
  29694. me.moving = true;
  29695. me.start();
  29696. });
  29697. }
  29698. else {
  29699. throw new Error('The function for connect does not support two arguments (data,callback)');
  29700. this.moving = true;
  29701. this.start();
  29702. }
  29703. }
  29704. else {
  29705. this.edgesData.add(defaultData);
  29706. this.moving = true;
  29707. this.start();
  29708. }
  29709. }
  29710. };
  29711. /**
  29712. * connect two nodes with a new edge.
  29713. *
  29714. * @private
  29715. */
  29716. exports._editEdge = function(sourceNodeId,targetNodeId) {
  29717. if (this.editMode == true) {
  29718. var defaultData = {id: this.edgeBeingEdited.id, from:sourceNodeId, to:targetNodeId};
  29719. if (this.triggerFunctions.editEdge) {
  29720. if (this.triggerFunctions.editEdge.length == 2) {
  29721. var me = this;
  29722. this.triggerFunctions.editEdge(defaultData, function(finalizedData) {
  29723. me.edgesData.update(finalizedData);
  29724. me.moving = true;
  29725. me.start();
  29726. });
  29727. }
  29728. else {
  29729. throw new Error('The function for edit does not support two arguments (data, callback)');
  29730. this.moving = true;
  29731. this.start();
  29732. }
  29733. }
  29734. else {
  29735. this.edgesData.update(defaultData);
  29736. this.moving = true;
  29737. this.start();
  29738. }
  29739. }
  29740. };
  29741. /**
  29742. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  29743. *
  29744. * @private
  29745. */
  29746. exports._editNode = function() {
  29747. if (this.triggerFunctions.edit && this.editMode == true) {
  29748. var node = this._getSelectedNode();
  29749. var data = {id:node.id,
  29750. label: node.label,
  29751. group: node.options.group,
  29752. shape: node.options.shape,
  29753. color: {
  29754. background:node.options.color.background,
  29755. border:node.options.color.border,
  29756. highlight: {
  29757. background:node.options.color.highlight.background,
  29758. border:node.options.color.highlight.border
  29759. }
  29760. }};
  29761. if (this.triggerFunctions.edit.length == 2) {
  29762. var me = this;
  29763. this.triggerFunctions.edit(data, function (finalizedData) {
  29764. me.nodesData.update(finalizedData);
  29765. me._createManipulatorBar();
  29766. me.moving = true;
  29767. me.start();
  29768. });
  29769. }
  29770. else {
  29771. throw new Error('The function for edit does not support two arguments (data, callback)');
  29772. }
  29773. }
  29774. else {
  29775. throw new Error('No edit function has been bound to this button');
  29776. }
  29777. };
  29778. /**
  29779. * delete everything in the selection
  29780. *
  29781. * @private
  29782. */
  29783. exports._deleteSelected = function() {
  29784. if (!this._selectionIsEmpty() && this.editMode == true) {
  29785. if (!this._clusterInSelection()) {
  29786. var selectedNodes = this.getSelectedNodes();
  29787. var selectedEdges = this.getSelectedEdges();
  29788. if (this.triggerFunctions.del) {
  29789. var me = this;
  29790. var data = {nodes: selectedNodes, edges: selectedEdges};
  29791. if (this.triggerFunctions.del.length == 2) {
  29792. this.triggerFunctions.del(data, function (finalizedData) {
  29793. me.edgesData.remove(finalizedData.edges);
  29794. me.nodesData.remove(finalizedData.nodes);
  29795. me._unselectAll();
  29796. me.moving = true;
  29797. me.start();
  29798. });
  29799. }
  29800. else {
  29801. throw new Error('The function for delete does not support two arguments (data, callback)')
  29802. }
  29803. }
  29804. else {
  29805. this.edgesData.remove(selectedEdges);
  29806. this.nodesData.remove(selectedNodes);
  29807. this._unselectAll();
  29808. this.moving = true;
  29809. this.start();
  29810. }
  29811. }
  29812. else {
  29813. alert(this.constants.locales[this.constants.locale]["deleteClusterError"]);
  29814. }
  29815. }
  29816. };
  29817. /***/ },
  29818. /* 65 */
  29819. /***/ function(module, exports, __webpack_require__) {
  29820. var util = __webpack_require__(1);
  29821. var Hammer = __webpack_require__(45);
  29822. exports._cleanNavigation = function() {
  29823. // clean hammer bindings
  29824. if (this.navigationHammers.length != 0) {
  29825. for (var i = 0; i < this.navigationHammers.length; i++) {
  29826. this.navigationHammers[i].dispose();
  29827. }
  29828. this.navigationHammers = [];
  29829. }
  29830. this._navigationReleaseOverload = function () {};
  29831. // clean up previous navigation items
  29832. if (this.navigationDOM && this.navigationDOM['wrapper'] && this.navigationDOM['wrapper'].parentNode) {
  29833. this.navigationDOM['wrapper'].parentNode.removeChild(this.navigationDOM['wrapper']);
  29834. }
  29835. };
  29836. /**
  29837. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  29838. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  29839. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  29840. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  29841. *
  29842. * @private
  29843. */
  29844. exports._loadNavigationElements = function() {
  29845. this._cleanNavigation();
  29846. this.navigationDOM = {};
  29847. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  29848. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','_zoomExtent'];
  29849. this.navigationDOM['wrapper'] = document.createElement('div');
  29850. this.frame.appendChild(this.navigationDOM['wrapper']);
  29851. for (var i = 0; i < navigationDivs.length; i++) {
  29852. this.navigationDOM[navigationDivs[i]] = document.createElement('div');
  29853. this.navigationDOM[navigationDivs[i]].className = 'network-navigation ' + navigationDivs[i];
  29854. this.navigationDOM['wrapper'].appendChild(this.navigationDOM[navigationDivs[i]]);
  29855. var hammer = Hammer(this.navigationDOM[navigationDivs[i]], {prevent_default: true});
  29856. hammer.on('touch', this[navigationDivActions[i]].bind(this));
  29857. this.navigationHammers.push(hammer);
  29858. }
  29859. this._navigationReleaseOverload = this._stopMovement;
  29860. };
  29861. /**
  29862. * this stops all movement induced by the navigation buttons
  29863. *
  29864. * @private
  29865. */
  29866. exports._zoomExtent = function(event) {
  29867. this.zoomExtent({duration:700});
  29868. event.stopPropagation();
  29869. };
  29870. /**
  29871. * this stops all movement induced by the navigation buttons
  29872. *
  29873. * @private
  29874. */
  29875. exports._stopMovement = function() {
  29876. this._xStopMoving();
  29877. this._yStopMoving();
  29878. this._stopZoom();
  29879. };
  29880. /**
  29881. * move the screen up
  29882. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  29883. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  29884. * To avoid this behaviour, we do the translation in the start loop.
  29885. *
  29886. * @private
  29887. */
  29888. exports._moveUp = function(event) {
  29889. this.yIncrement = this.constants.keyboard.speed.y;
  29890. this.start(); // if there is no node movement, the calculation wont be done
  29891. event.preventDefault();
  29892. };
  29893. /**
  29894. * move the screen down
  29895. * @private
  29896. */
  29897. exports._moveDown = function(event) {
  29898. this.yIncrement = -this.constants.keyboard.speed.y;
  29899. this.start(); // if there is no node movement, the calculation wont be done
  29900. event.preventDefault();
  29901. };
  29902. /**
  29903. * move the screen left
  29904. * @private
  29905. */
  29906. exports._moveLeft = function(event) {
  29907. this.xIncrement = this.constants.keyboard.speed.x;
  29908. this.start(); // if there is no node movement, the calculation wont be done
  29909. event.preventDefault();
  29910. };
  29911. /**
  29912. * move the screen right
  29913. * @private
  29914. */
  29915. exports._moveRight = function(event) {
  29916. this.xIncrement = -this.constants.keyboard.speed.y;
  29917. this.start(); // if there is no node movement, the calculation wont be done
  29918. event.preventDefault();
  29919. };
  29920. /**
  29921. * Zoom in, using the same method as the movement.
  29922. * @private
  29923. */
  29924. exports._zoomIn = function(event) {
  29925. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  29926. this.start(); // if there is no node movement, the calculation wont be done
  29927. event.preventDefault();
  29928. };
  29929. /**
  29930. * Zoom out
  29931. * @private
  29932. */
  29933. exports._zoomOut = function(event) {
  29934. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  29935. this.start(); // if there is no node movement, the calculation wont be done
  29936. event.preventDefault();
  29937. };
  29938. /**
  29939. * Stop zooming and unhighlight the zoom controls
  29940. * @private
  29941. */
  29942. exports._stopZoom = function(event) {
  29943. this.zoomIncrement = 0;
  29944. event && event.preventDefault();
  29945. };
  29946. /**
  29947. * Stop moving in the Y direction and unHighlight the up and down
  29948. * @private
  29949. */
  29950. exports._yStopMoving = function(event) {
  29951. this.yIncrement = 0;
  29952. event && event.preventDefault();
  29953. };
  29954. /**
  29955. * Stop moving in the X direction and unHighlight left and right.
  29956. * @private
  29957. */
  29958. exports._xStopMoving = function(event) {
  29959. this.xIncrement = 0;
  29960. event && event.preventDefault();
  29961. };
  29962. /***/ },
  29963. /* 66 */
  29964. /***/ function(module, exports, __webpack_require__) {
  29965. exports._resetLevels = function() {
  29966. for (var nodeId in this.nodes) {
  29967. if (this.nodes.hasOwnProperty(nodeId)) {
  29968. var node = this.nodes[nodeId];
  29969. if (node.preassignedLevel == false) {
  29970. node.level = -1;
  29971. node.hierarchyEnumerated = false;
  29972. }
  29973. }
  29974. }
  29975. };
  29976. /**
  29977. * This is the main function to layout the nodes in a hierarchical way.
  29978. * It checks if the node details are supplied correctly
  29979. *
  29980. * @private
  29981. */
  29982. exports._setupHierarchicalLayout = function() {
  29983. if (this.constants.hierarchicalLayout.enabled == true && this.nodeIndices.length > 0) {
  29984. // get the size of the largest hubs and check if the user has defined a level for a node.
  29985. var hubsize = 0;
  29986. var node, nodeId;
  29987. var definedLevel = false;
  29988. var undefinedLevel = false;
  29989. for (nodeId in this.nodes) {
  29990. if (this.nodes.hasOwnProperty(nodeId)) {
  29991. node = this.nodes[nodeId];
  29992. if (node.level != -1) {
  29993. definedLevel = true;
  29994. }
  29995. else {
  29996. undefinedLevel = true;
  29997. }
  29998. if (hubsize < node.edges.length) {
  29999. hubsize = node.edges.length;
  30000. }
  30001. }
  30002. }
  30003. // if the user defined some levels but not all, alert and run without hierarchical layout
  30004. if (undefinedLevel == true && definedLevel == true) {
  30005. throw new Error("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  30006. this.zoomExtent({duration:0},true,this.constants.clustering.enabled);
  30007. if (!this.constants.clustering.enabled) {
  30008. this.start();
  30009. }
  30010. }
  30011. else {
  30012. // setup the system to use hierarchical method.
  30013. this._changeConstants();
  30014. // define levels if undefined by the users. Based on hubsize
  30015. if (undefinedLevel == true) {
  30016. if (this.constants.hierarchicalLayout.layout == "hubsize") {
  30017. this._determineLevels(hubsize);
  30018. }
  30019. else {
  30020. this._determineLevelsDirected(false);
  30021. }
  30022. }
  30023. // check the distribution of the nodes per level.
  30024. var distribution = this._getDistribution();
  30025. // place the nodes on the canvas. This also stablilizes the system.
  30026. this._placeNodesByHierarchy(distribution);
  30027. // start the simulation.
  30028. this.start();
  30029. }
  30030. }
  30031. };
  30032. /**
  30033. * This function places the nodes on the canvas based on the hierarchial distribution.
  30034. *
  30035. * @param {Object} distribution | obtained by the function this._getDistribution()
  30036. * @private
  30037. */
  30038. exports._placeNodesByHierarchy = function(distribution) {
  30039. var nodeId, node;
  30040. // start placing all the level 0 nodes first. Then recursively position their branches.
  30041. for (var level in distribution) {
  30042. if (distribution.hasOwnProperty(level)) {
  30043. for (nodeId in distribution[level].nodes) {
  30044. if (distribution[level].nodes.hasOwnProperty(nodeId)) {
  30045. node = distribution[level].nodes[nodeId];
  30046. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  30047. if (node.xFixed) {
  30048. node.x = distribution[level].minPos;
  30049. node.xFixed = false;
  30050. distribution[level].minPos += distribution[level].nodeSpacing;
  30051. }
  30052. }
  30053. else {
  30054. if (node.yFixed) {
  30055. node.y = distribution[level].minPos;
  30056. node.yFixed = false;
  30057. distribution[level].minPos += distribution[level].nodeSpacing;
  30058. }
  30059. }
  30060. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  30061. }
  30062. }
  30063. }
  30064. }
  30065. // stabilize the system after positioning. This function calls zoomExtent.
  30066. this._stabilize();
  30067. };
  30068. /**
  30069. * This function get the distribution of levels based on hubsize
  30070. *
  30071. * @returns {Object}
  30072. * @private
  30073. */
  30074. exports._getDistribution = function() {
  30075. var distribution = {};
  30076. var nodeId, node, level;
  30077. // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time.
  30078. // the fix of X is removed after the x value has been set.
  30079. for (nodeId in this.nodes) {
  30080. if (this.nodes.hasOwnProperty(nodeId)) {
  30081. node = this.nodes[nodeId];
  30082. node.xFixed = true;
  30083. node.yFixed = true;
  30084. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  30085. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  30086. }
  30087. else {
  30088. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  30089. }
  30090. if (distribution[node.level] === undefined) {
  30091. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  30092. }
  30093. distribution[node.level].amount += 1;
  30094. distribution[node.level].nodes[nodeId] = node;
  30095. }
  30096. }
  30097. // determine the largest amount of nodes of all levels
  30098. var maxCount = 0;
  30099. for (level in distribution) {
  30100. if (distribution.hasOwnProperty(level)) {
  30101. if (maxCount < distribution[level].amount) {
  30102. maxCount = distribution[level].amount;
  30103. }
  30104. }
  30105. }
  30106. // set the initial position and spacing of each nodes accordingly
  30107. for (level in distribution) {
  30108. if (distribution.hasOwnProperty(level)) {
  30109. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  30110. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  30111. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  30112. }
  30113. }
  30114. return distribution;
  30115. };
  30116. /**
  30117. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  30118. *
  30119. * @param hubsize
  30120. * @private
  30121. */
  30122. exports._determineLevels = function(hubsize) {
  30123. var nodeId, node;
  30124. // determine hubs
  30125. for (nodeId in this.nodes) {
  30126. if (this.nodes.hasOwnProperty(nodeId)) {
  30127. node = this.nodes[nodeId];
  30128. if (node.edges.length == hubsize) {
  30129. node.level = 0;
  30130. }
  30131. }
  30132. }
  30133. // branch from hubs
  30134. for (nodeId in this.nodes) {
  30135. if (this.nodes.hasOwnProperty(nodeId)) {
  30136. node = this.nodes[nodeId];
  30137. if (node.level == 0) {
  30138. this._setLevel(1,node.edges,node.id);
  30139. }
  30140. }
  30141. }
  30142. };
  30143. /**
  30144. * this function allocates nodes in levels based on the direction of the edges
  30145. *
  30146. * @param hubsize
  30147. * @private
  30148. */
  30149. exports._determineLevelsDirected = function() {
  30150. var nodeId, node, firstNode;
  30151. var minLevel = 10000;
  30152. // set first node to source
  30153. firstNode = this.nodes[this.nodeIndices[0]];
  30154. firstNode.level = minLevel;
  30155. this._setLevelDirected(minLevel,firstNode.edges,firstNode.id);
  30156. // get the minimum level
  30157. for (nodeId in this.nodes) {
  30158. if (this.nodes.hasOwnProperty(nodeId)) {
  30159. node = this.nodes[nodeId];
  30160. minLevel = node.level < minLevel ? node.level : minLevel;
  30161. }
  30162. }
  30163. // subtract the minimum from the set so we have a range starting from 0
  30164. for (nodeId in this.nodes) {
  30165. if (this.nodes.hasOwnProperty(nodeId)) {
  30166. node = this.nodes[nodeId];
  30167. node.level -= minLevel;
  30168. }
  30169. }
  30170. };
  30171. /**
  30172. * Since hierarchical layout does not support:
  30173. * - smooth curves (based on the physics),
  30174. * - clustering (based on dynamic node counts)
  30175. *
  30176. * We disable both features so there will be no problems.
  30177. *
  30178. * @private
  30179. */
  30180. exports._changeConstants = function() {
  30181. this.constants.clustering.enabled = false;
  30182. this.constants.physics.barnesHut.enabled = false;
  30183. this.constants.physics.hierarchicalRepulsion.enabled = true;
  30184. this._loadSelectedForceSolver();
  30185. if (this.constants.smoothCurves.enabled == true) {
  30186. this.constants.smoothCurves.dynamic = false;
  30187. }
  30188. this._configureSmoothCurves();
  30189. var config = this.constants.hierarchicalLayout;
  30190. config.levelSeparation = Math.abs(config.levelSeparation);
  30191. if (config.direction == "RL" || config.direction == "DU") {
  30192. config.levelSeparation *= -1;
  30193. }
  30194. if (config.direction == "RL" || config.direction == "LR") {
  30195. if (this.constants.smoothCurves.enabled == true) {
  30196. this.constants.smoothCurves.type = "vertical";
  30197. }
  30198. }
  30199. else {
  30200. if (this.constants.smoothCurves.enabled == true) {
  30201. this.constants.smoothCurves.type = "horizontal";
  30202. }
  30203. }
  30204. };
  30205. /**
  30206. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  30207. * on a X position that ensures there will be no overlap.
  30208. *
  30209. * @param edges
  30210. * @param parentId
  30211. * @param distribution
  30212. * @param parentLevel
  30213. * @private
  30214. */
  30215. exports._placeBranchNodes = function(edges, parentId, distribution, parentLevel) {
  30216. for (var i = 0; i < edges.length; i++) {
  30217. var childNode = null;
  30218. if (edges[i].toId == parentId) {
  30219. childNode = edges[i].from;
  30220. }
  30221. else {
  30222. childNode = edges[i].to;
  30223. }
  30224. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  30225. var nodeMoved = false;
  30226. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  30227. if (childNode.xFixed && childNode.level > parentLevel) {
  30228. childNode.xFixed = false;
  30229. childNode.x = distribution[childNode.level].minPos;
  30230. nodeMoved = true;
  30231. }
  30232. }
  30233. else {
  30234. if (childNode.yFixed && childNode.level > parentLevel) {
  30235. childNode.yFixed = false;
  30236. childNode.y = distribution[childNode.level].minPos;
  30237. nodeMoved = true;
  30238. }
  30239. }
  30240. if (nodeMoved == true) {
  30241. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  30242. if (childNode.edges.length > 1) {
  30243. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  30244. }
  30245. }
  30246. }
  30247. };
  30248. /**
  30249. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  30250. *
  30251. * @param level
  30252. * @param edges
  30253. * @param parentId
  30254. * @private
  30255. */
  30256. exports._setLevel = function(level, edges, parentId) {
  30257. for (var i = 0; i < edges.length; i++) {
  30258. var childNode = null;
  30259. if (edges[i].toId == parentId) {
  30260. childNode = edges[i].from;
  30261. }
  30262. else {
  30263. childNode = edges[i].to;
  30264. }
  30265. if (childNode.level == -1 || childNode.level > level) {
  30266. childNode.level = level;
  30267. if (childNode.edges.length > 1) {
  30268. this._setLevel(level+1, childNode.edges, childNode.id);
  30269. }
  30270. }
  30271. }
  30272. };
  30273. /**
  30274. * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction
  30275. *
  30276. * @param level
  30277. * @param edges
  30278. * @param parentId
  30279. * @private
  30280. */
  30281. exports._setLevelDirected = function(level, edges, parentId) {
  30282. this.nodes[parentId].hierarchyEnumerated = true;
  30283. var childNode, direction;
  30284. for (var i = 0; i < edges.length; i++) {
  30285. direction = 1;
  30286. if (edges[i].toId == parentId) {
  30287. childNode = edges[i].from;
  30288. direction = -1;
  30289. }
  30290. else {
  30291. childNode = edges[i].to;
  30292. }
  30293. if (childNode.level == -1) {
  30294. childNode.level = level + direction;
  30295. }
  30296. }
  30297. for (var i = 0; i < edges.length; i++) {
  30298. if (edges[i].toId == parentId) {childNode = edges[i].from;}
  30299. else {childNode = edges[i].to;}
  30300. if (childNode.edges.length > 1 && childNode.hierarchyEnumerated === false) {
  30301. this._setLevelDirected(childNode.level, childNode.edges, childNode.id);
  30302. }
  30303. }
  30304. };
  30305. /**
  30306. * Unfix nodes
  30307. *
  30308. * @private
  30309. */
  30310. exports._restoreNodes = function() {
  30311. for (var nodeId in this.nodes) {
  30312. if (this.nodes.hasOwnProperty(nodeId)) {
  30313. this.nodes[nodeId].xFixed = false;
  30314. this.nodes[nodeId].yFixed = false;
  30315. }
  30316. }
  30317. };
  30318. /***/ },
  30319. /* 67 */
  30320. /***/ function(module, exports, __webpack_require__) {
  30321. function webpackContext(req) {
  30322. throw new Error("Cannot find module '" + req + "'.");
  30323. }
  30324. webpackContext.keys = function() { return []; };
  30325. webpackContext.resolve = webpackContext;
  30326. module.exports = webpackContext;
  30327. webpackContext.id = 67;
  30328. /***/ },
  30329. /* 68 */
  30330. /***/ function(module, exports, __webpack_require__) {
  30331. /**
  30332. * Calculate the forces the nodes apply on each other based on a repulsion field.
  30333. * This field is linearly approximated.
  30334. *
  30335. * @private
  30336. */
  30337. exports._calculateNodeForces = function () {
  30338. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  30339. repulsingForce, node1, node2, i, j;
  30340. var nodes = this.calculationNodes;
  30341. var nodeIndices = this.calculationNodeIndices;
  30342. // approximation constants
  30343. var a_base = -2 / 3;
  30344. var b = 4 / 3;
  30345. // repulsing forces between nodes
  30346. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  30347. var minimumDistance = nodeDistance;
  30348. // we loop from i over all but the last entree in the array
  30349. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  30350. for (i = 0; i < nodeIndices.length - 1; i++) {
  30351. node1 = nodes[nodeIndices[i]];
  30352. for (j = i + 1; j < nodeIndices.length; j++) {
  30353. node2 = nodes[nodeIndices[j]];
  30354. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  30355. dx = node2.x - node1.x;
  30356. dy = node2.y - node1.y;
  30357. distance = Math.sqrt(dx * dx + dy * dy);
  30358. // same condition as BarnesHut, making sure nodes are never 100% overlapping.
  30359. if (distance == 0) {
  30360. distance = 0.1*Math.random();
  30361. dx = distance;
  30362. }
  30363. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  30364. var a = a_base / minimumDistance;
  30365. if (distance < 2 * minimumDistance) {
  30366. if (distance < 0.5 * minimumDistance) {
  30367. repulsingForce = 1.0;
  30368. }
  30369. else {
  30370. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  30371. }
  30372. // amplify the repulsion for clusters.
  30373. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  30374. repulsingForce = repulsingForce / Math.max(distance,0.01*minimumDistance);
  30375. fx = dx * repulsingForce;
  30376. fy = dy * repulsingForce;
  30377. node1.fx -= fx;
  30378. node1.fy -= fy;
  30379. node2.fx += fx;
  30380. node2.fy += fy;
  30381. }
  30382. }
  30383. }
  30384. };
  30385. /***/ },
  30386. /* 69 */
  30387. /***/ function(module, exports, __webpack_require__) {
  30388. /**
  30389. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  30390. * This field is linearly approximated.
  30391. *
  30392. * @private
  30393. */
  30394. exports._calculateNodeForces = function () {
  30395. var dx, dy, distance, fx, fy,
  30396. repulsingForce, node1, node2, i, j;
  30397. var nodes = this.calculationNodes;
  30398. var nodeIndices = this.calculationNodeIndices;
  30399. // repulsing forces between nodes
  30400. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  30401. // we loop from i over all but the last entree in the array
  30402. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  30403. for (i = 0; i < nodeIndices.length - 1; i++) {
  30404. node1 = nodes[nodeIndices[i]];
  30405. for (j = i + 1; j < nodeIndices.length; j++) {
  30406. node2 = nodes[nodeIndices[j]];
  30407. // nodes only affect nodes on their level
  30408. if (node1.level == node2.level) {
  30409. dx = node2.x - node1.x;
  30410. dy = node2.y - node1.y;
  30411. distance = Math.sqrt(dx * dx + dy * dy);
  30412. var steepness = 0.05;
  30413. if (distance < nodeDistance) {
  30414. repulsingForce = -Math.pow(steepness*distance,2) + Math.pow(steepness*nodeDistance,2);
  30415. }
  30416. else {
  30417. repulsingForce = 0;
  30418. }
  30419. // normalize force with
  30420. if (distance == 0) {
  30421. distance = 0.01;
  30422. }
  30423. else {
  30424. repulsingForce = repulsingForce / distance;
  30425. }
  30426. fx = dx * repulsingForce;
  30427. fy = dy * repulsingForce;
  30428. node1.fx -= fx;
  30429. node1.fy -= fy;
  30430. node2.fx += fx;
  30431. node2.fy += fy;
  30432. }
  30433. }
  30434. }
  30435. };
  30436. /**
  30437. * this function calculates the effects of the springs in the case of unsmooth curves.
  30438. *
  30439. * @private
  30440. */
  30441. exports._calculateHierarchicalSpringForces = function () {
  30442. var edgeLength, edge, edgeId;
  30443. var dx, dy, fx, fy, springForce, distance;
  30444. var edges = this.edges;
  30445. var nodes = this.calculationNodes;
  30446. var nodeIndices = this.calculationNodeIndices;
  30447. for (var i = 0; i < nodeIndices.length; i++) {
  30448. var node1 = nodes[nodeIndices[i]];
  30449. node1.springFx = 0;
  30450. node1.springFy = 0;
  30451. }
  30452. // forces caused by the edges, modelled as springs
  30453. for (edgeId in edges) {
  30454. if (edges.hasOwnProperty(edgeId)) {
  30455. edge = edges[edgeId];
  30456. if (edge.connected) {
  30457. // only calculate forces if nodes are in the same sector
  30458. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  30459. edgeLength = edge.physics.springLength;
  30460. // this implies that the edges between big clusters are longer
  30461. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  30462. dx = (edge.from.x - edge.to.x);
  30463. dy = (edge.from.y - edge.to.y);
  30464. distance = Math.sqrt(dx * dx + dy * dy);
  30465. if (distance == 0) {
  30466. distance = 0.01;
  30467. }
  30468. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  30469. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  30470. fx = dx * springForce;
  30471. fy = dy * springForce;
  30472. if (edge.to.level != edge.from.level) {
  30473. edge.to.springFx -= fx;
  30474. edge.to.springFy -= fy;
  30475. edge.from.springFx += fx;
  30476. edge.from.springFy += fy;
  30477. }
  30478. else {
  30479. var factor = 0.5;
  30480. edge.to.fx -= factor*fx;
  30481. edge.to.fy -= factor*fy;
  30482. edge.from.fx += factor*fx;
  30483. edge.from.fy += factor*fy;
  30484. }
  30485. }
  30486. }
  30487. }
  30488. }
  30489. // normalize spring forces
  30490. var springForce = 1;
  30491. var springFx, springFy;
  30492. for (i = 0; i < nodeIndices.length; i++) {
  30493. var node = nodes[nodeIndices[i]];
  30494. springFx = Math.min(springForce,Math.max(-springForce,node.springFx));
  30495. springFy = Math.min(springForce,Math.max(-springForce,node.springFy));
  30496. node.fx += springFx;
  30497. node.fy += springFy;
  30498. }
  30499. // retain energy balance
  30500. var totalFx = 0;
  30501. var totalFy = 0;
  30502. for (i = 0; i < nodeIndices.length; i++) {
  30503. var node = nodes[nodeIndices[i]];
  30504. totalFx += node.fx;
  30505. totalFy += node.fy;
  30506. }
  30507. var correctionFx = totalFx / nodeIndices.length;
  30508. var correctionFy = totalFy / nodeIndices.length;
  30509. for (i = 0; i < nodeIndices.length; i++) {
  30510. var node = nodes[nodeIndices[i]];
  30511. node.fx -= correctionFx;
  30512. node.fy -= correctionFy;
  30513. }
  30514. };
  30515. /***/ },
  30516. /* 70 */
  30517. /***/ function(module, exports, __webpack_require__) {
  30518. /**
  30519. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  30520. * The Barnes Hut method is used to speed up this N-body simulation.
  30521. *
  30522. * @private
  30523. */
  30524. exports._calculateNodeForces = function() {
  30525. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  30526. var node;
  30527. var nodes = this.calculationNodes;
  30528. var nodeIndices = this.calculationNodeIndices;
  30529. var nodeCount = nodeIndices.length;
  30530. this._formBarnesHutTree(nodes,nodeIndices);
  30531. var barnesHutTree = this.barnesHutTree;
  30532. // place the nodes one by one recursively
  30533. for (var i = 0; i < nodeCount; i++) {
  30534. node = nodes[nodeIndices[i]];
  30535. if (node.options.mass > 0) {
  30536. // starting with root is irrelevant, it never passes the BarnesHut condition
  30537. this._getForceContribution(barnesHutTree.root.children.NW,node);
  30538. this._getForceContribution(barnesHutTree.root.children.NE,node);
  30539. this._getForceContribution(barnesHutTree.root.children.SW,node);
  30540. this._getForceContribution(barnesHutTree.root.children.SE,node);
  30541. }
  30542. }
  30543. }
  30544. };
  30545. /**
  30546. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  30547. * If a region contains a single node, we check if it is not itself, then we apply the force.
  30548. *
  30549. * @param parentBranch
  30550. * @param node
  30551. * @private
  30552. */
  30553. exports._getForceContribution = function(parentBranch,node) {
  30554. // we get no force contribution from an empty region
  30555. if (parentBranch.childrenCount > 0) {
  30556. var dx,dy,distance;
  30557. // get the distance from the center of mass to the node.
  30558. dx = parentBranch.centerOfMass.x - node.x;
  30559. dy = parentBranch.centerOfMass.y - node.y;
  30560. distance = Math.sqrt(dx * dx + dy * dy);
  30561. // BarnesHut condition
  30562. // original condition : s/d < thetaInverted = passed === d/s > 1/theta = passed
  30563. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  30564. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.thetaInverted) {
  30565. // duplicate code to reduce function calls to speed up program
  30566. if (distance == 0) {
  30567. distance = 0.1*Math.random();
  30568. dx = distance;
  30569. }
  30570. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance);
  30571. var fx = dx * gravityForce;
  30572. var fy = dy * gravityForce;
  30573. node.fx += fx;
  30574. node.fy += fy;
  30575. }
  30576. else {
  30577. // Did not pass the condition, go into children if available
  30578. if (parentBranch.childrenCount == 4) {
  30579. this._getForceContribution(parentBranch.children.NW,node);
  30580. this._getForceContribution(parentBranch.children.NE,node);
  30581. this._getForceContribution(parentBranch.children.SW,node);
  30582. this._getForceContribution(parentBranch.children.SE,node);
  30583. }
  30584. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  30585. if (parentBranch.children.data.id != node.id) { // if it is not self
  30586. // duplicate code to reduce function calls to speed up program
  30587. if (distance == 0) {
  30588. distance = 0.5*Math.random();
  30589. dx = distance;
  30590. }
  30591. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance);
  30592. var fx = dx * gravityForce;
  30593. var fy = dy * gravityForce;
  30594. node.fx += fx;
  30595. node.fy += fy;
  30596. }
  30597. }
  30598. }
  30599. }
  30600. };
  30601. /**
  30602. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  30603. *
  30604. * @param nodes
  30605. * @param nodeIndices
  30606. * @private
  30607. */
  30608. exports._formBarnesHutTree = function(nodes,nodeIndices) {
  30609. var node;
  30610. var nodeCount = nodeIndices.length;
  30611. var minX = Number.MAX_VALUE,
  30612. minY = Number.MAX_VALUE,
  30613. maxX =-Number.MAX_VALUE,
  30614. maxY =-Number.MAX_VALUE;
  30615. // get the range of the nodes
  30616. for (var i = 0; i < nodeCount; i++) {
  30617. var x = nodes[nodeIndices[i]].x;
  30618. var y = nodes[nodeIndices[i]].y;
  30619. if (nodes[nodeIndices[i]].options.mass > 0) {
  30620. if (x < minX) { minX = x; }
  30621. if (x > maxX) { maxX = x; }
  30622. if (y < minY) { minY = y; }
  30623. if (y > maxY) { maxY = y; }
  30624. }
  30625. }
  30626. // make the range a square
  30627. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  30628. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  30629. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  30630. var minimumTreeSize = 1e-5;
  30631. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  30632. var halfRootSize = 0.5 * rootSize;
  30633. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  30634. // construct the barnesHutTree
  30635. var barnesHutTree = {
  30636. root:{
  30637. centerOfMass: {x:0, y:0},
  30638. mass:0,
  30639. range: {
  30640. minX: centerX-halfRootSize,maxX:centerX+halfRootSize,
  30641. minY: centerY-halfRootSize,maxY:centerY+halfRootSize
  30642. },
  30643. size: rootSize,
  30644. calcSize: 1 / rootSize,
  30645. children: { data:null},
  30646. maxWidth: 0,
  30647. level: 0,
  30648. childrenCount: 4
  30649. }
  30650. };
  30651. this._splitBranch(barnesHutTree.root);
  30652. // place the nodes one by one recursively
  30653. for (i = 0; i < nodeCount; i++) {
  30654. node = nodes[nodeIndices[i]];
  30655. if (node.options.mass > 0) {
  30656. this._placeInTree(barnesHutTree.root,node);
  30657. }
  30658. }
  30659. // make global
  30660. this.barnesHutTree = barnesHutTree
  30661. };
  30662. /**
  30663. * this updates the mass of a branch. this is increased by adding a node.
  30664. *
  30665. * @param parentBranch
  30666. * @param node
  30667. * @private
  30668. */
  30669. exports._updateBranchMass = function(parentBranch, node) {
  30670. var totalMass = parentBranch.mass + node.options.mass;
  30671. var totalMassInv = 1/totalMass;
  30672. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass;
  30673. parentBranch.centerOfMass.x *= totalMassInv;
  30674. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass;
  30675. parentBranch.centerOfMass.y *= totalMassInv;
  30676. parentBranch.mass = totalMass;
  30677. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  30678. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  30679. };
  30680. /**
  30681. * determine in which branch the node will be placed.
  30682. *
  30683. * @param parentBranch
  30684. * @param node
  30685. * @param skipMassUpdate
  30686. * @private
  30687. */
  30688. exports._placeInTree = function(parentBranch,node,skipMassUpdate) {
  30689. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  30690. // update the mass of the branch.
  30691. this._updateBranchMass(parentBranch,node);
  30692. }
  30693. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  30694. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  30695. this._placeInRegion(parentBranch,node,"NW");
  30696. }
  30697. else { // in SW
  30698. this._placeInRegion(parentBranch,node,"SW");
  30699. }
  30700. }
  30701. else { // in NE or SE
  30702. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  30703. this._placeInRegion(parentBranch,node,"NE");
  30704. }
  30705. else { // in SE
  30706. this._placeInRegion(parentBranch,node,"SE");
  30707. }
  30708. }
  30709. };
  30710. /**
  30711. * actually place the node in a region (or branch)
  30712. *
  30713. * @param parentBranch
  30714. * @param node
  30715. * @param region
  30716. * @private
  30717. */
  30718. exports._placeInRegion = function(parentBranch,node,region) {
  30719. switch (parentBranch.children[region].childrenCount) {
  30720. case 0: // place node here
  30721. parentBranch.children[region].children.data = node;
  30722. parentBranch.children[region].childrenCount = 1;
  30723. this._updateBranchMass(parentBranch.children[region],node);
  30724. break;
  30725. case 1: // convert into children
  30726. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  30727. // we move one node a pixel and we do not put it in the tree.
  30728. if (parentBranch.children[region].children.data.x == node.x &&
  30729. parentBranch.children[region].children.data.y == node.y) {
  30730. node.x += Math.random();
  30731. node.y += Math.random();
  30732. }
  30733. else {
  30734. this._splitBranch(parentBranch.children[region]);
  30735. this._placeInTree(parentBranch.children[region],node);
  30736. }
  30737. break;
  30738. case 4: // place in branch
  30739. this._placeInTree(parentBranch.children[region],node);
  30740. break;
  30741. }
  30742. };
  30743. /**
  30744. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  30745. * after the split is complete.
  30746. *
  30747. * @param parentBranch
  30748. * @private
  30749. */
  30750. exports._splitBranch = function(parentBranch) {
  30751. // if the branch is shaded with a node, replace the node in the new subset.
  30752. var containedNode = null;
  30753. if (parentBranch.childrenCount == 1) {
  30754. containedNode = parentBranch.children.data;
  30755. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  30756. }
  30757. parentBranch.childrenCount = 4;
  30758. parentBranch.children.data = null;
  30759. this._insertRegion(parentBranch,"NW");
  30760. this._insertRegion(parentBranch,"NE");
  30761. this._insertRegion(parentBranch,"SW");
  30762. this._insertRegion(parentBranch,"SE");
  30763. if (containedNode != null) {
  30764. this._placeInTree(parentBranch,containedNode);
  30765. }
  30766. };
  30767. /**
  30768. * This function subdivides the region into four new segments.
  30769. * Specifically, this inserts a single new segment.
  30770. * It fills the children section of the parentBranch
  30771. *
  30772. * @param parentBranch
  30773. * @param region
  30774. * @param parentRange
  30775. * @private
  30776. */
  30777. exports._insertRegion = function(parentBranch, region) {
  30778. var minX,maxX,minY,maxY;
  30779. var childSize = 0.5 * parentBranch.size;
  30780. switch (region) {
  30781. case "NW":
  30782. minX = parentBranch.range.minX;
  30783. maxX = parentBranch.range.minX + childSize;
  30784. minY = parentBranch.range.minY;
  30785. maxY = parentBranch.range.minY + childSize;
  30786. break;
  30787. case "NE":
  30788. minX = parentBranch.range.minX + childSize;
  30789. maxX = parentBranch.range.maxX;
  30790. minY = parentBranch.range.minY;
  30791. maxY = parentBranch.range.minY + childSize;
  30792. break;
  30793. case "SW":
  30794. minX = parentBranch.range.minX;
  30795. maxX = parentBranch.range.minX + childSize;
  30796. minY = parentBranch.range.minY + childSize;
  30797. maxY = parentBranch.range.maxY;
  30798. break;
  30799. case "SE":
  30800. minX = parentBranch.range.minX + childSize;
  30801. maxX = parentBranch.range.maxX;
  30802. minY = parentBranch.range.minY + childSize;
  30803. maxY = parentBranch.range.maxY;
  30804. break;
  30805. }
  30806. parentBranch.children[region] = {
  30807. centerOfMass:{x:0,y:0},
  30808. mass:0,
  30809. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  30810. size: 0.5 * parentBranch.size,
  30811. calcSize: 2 * parentBranch.calcSize,
  30812. children: {data:null},
  30813. maxWidth: 0,
  30814. level: parentBranch.level+1,
  30815. childrenCount: 0
  30816. };
  30817. };
  30818. /**
  30819. * This function is for debugging purposed, it draws the tree.
  30820. *
  30821. * @param ctx
  30822. * @param color
  30823. * @private
  30824. */
  30825. exports._drawTree = function(ctx,color) {
  30826. if (this.barnesHutTree !== undefined) {
  30827. ctx.lineWidth = 1;
  30828. this._drawBranch(this.barnesHutTree.root,ctx,color);
  30829. }
  30830. };
  30831. /**
  30832. * This function is for debugging purposes. It draws the branches recursively.
  30833. *
  30834. * @param branch
  30835. * @param ctx
  30836. * @param color
  30837. * @private
  30838. */
  30839. exports._drawBranch = function(branch,ctx,color) {
  30840. if (color === undefined) {
  30841. color = "#FF0000";
  30842. }
  30843. if (branch.childrenCount == 4) {
  30844. this._drawBranch(branch.children.NW,ctx);
  30845. this._drawBranch(branch.children.NE,ctx);
  30846. this._drawBranch(branch.children.SE,ctx);
  30847. this._drawBranch(branch.children.SW,ctx);
  30848. }
  30849. ctx.strokeStyle = color;
  30850. ctx.beginPath();
  30851. ctx.moveTo(branch.range.minX,branch.range.minY);
  30852. ctx.lineTo(branch.range.maxX,branch.range.minY);
  30853. ctx.stroke();
  30854. ctx.beginPath();
  30855. ctx.moveTo(branch.range.maxX,branch.range.minY);
  30856. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  30857. ctx.stroke();
  30858. ctx.beginPath();
  30859. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  30860. ctx.lineTo(branch.range.minX,branch.range.maxY);
  30861. ctx.stroke();
  30862. ctx.beginPath();
  30863. ctx.moveTo(branch.range.minX,branch.range.maxY);
  30864. ctx.lineTo(branch.range.minX,branch.range.minY);
  30865. ctx.stroke();
  30866. /*
  30867. if (branch.mass > 0) {
  30868. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  30869. ctx.stroke();
  30870. }
  30871. */
  30872. };
  30873. /***/ },
  30874. /* 71 */
  30875. /***/ function(module, exports, __webpack_require__) {
  30876. module.exports = function(module) {
  30877. if(!module.webpackPolyfill) {
  30878. module.deprecate = function() {};
  30879. module.paths = [];
  30880. // module.parent = undefined by default
  30881. module.children = [];
  30882. module.webpackPolyfill = 1;
  30883. }
  30884. return module;
  30885. }
  30886. /***/ }
  30887. /******/ ])
  30888. });
  30889. ;