vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34470 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.8.0
  8. * @date 2015-01-09
  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. /******/
  40. /******/ // The require function
  41. /******/ function __webpack_require__(moduleId) {
  42. /******/
  43. /******/ // Check if module is in cache
  44. /******/ if(installedModules[moduleId])
  45. /******/ return installedModules[moduleId].exports;
  46. /******/
  47. /******/ // Create a new module (and put it into the cache)
  48. /******/ var module = installedModules[moduleId] = {
  49. /******/ exports: {},
  50. /******/ id: moduleId,
  51. /******/ loaded: false
  52. /******/ };
  53. /******/
  54. /******/ // Execute the module function
  55. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  56. /******/
  57. /******/ // Flag the module as loaded
  58. /******/ module.loaded = true;
  59. /******/
  60. /******/ // Return the exports of the module
  61. /******/ return module.exports;
  62. /******/ }
  63. /******/
  64. /******/
  65. /******/ // expose the modules object (__webpack_modules__)
  66. /******/ __webpack_require__.m = modules;
  67. /******/
  68. /******/ // expose the module cache
  69. /******/ __webpack_require__.c = installedModules;
  70. /******/
  71. /******/ // __webpack_public_path__
  72. /******/ __webpack_require__.p = "";
  73. /******/
  74. /******/ // Load entry module and return exports
  75. /******/ return __webpack_require__(0);
  76. /******/ })
  77. /************************************************************************/
  78. /******/ ([
  79. /* 0 */
  80. /***/ function(module, exports, __webpack_require__) {
  81. // utils
  82. exports.util = __webpack_require__(1);
  83. exports.DOMutil = __webpack_require__(2);
  84. // data
  85. exports.DataSet = __webpack_require__(3);
  86. exports.DataView = __webpack_require__(4);
  87. exports.Queue = __webpack_require__(5);
  88. // Graph3d
  89. exports.Graph3d = __webpack_require__(6);
  90. exports.graph3d = {
  91. Camera: __webpack_require__(7),
  92. Filter: __webpack_require__(8),
  93. Point2d: __webpack_require__(9),
  94. Point3d: __webpack_require__(10),
  95. Slider: __webpack_require__(11),
  96. StepNumber: __webpack_require__(12)
  97. };
  98. // Timeline
  99. exports.Timeline = __webpack_require__(13);
  100. exports.Graph2d = __webpack_require__(14);
  101. exports.timeline = {
  102. DateUtil: __webpack_require__(15),
  103. DataStep: __webpack_require__(16),
  104. Range: __webpack_require__(17),
  105. stack: __webpack_require__(18),
  106. TimeStep: __webpack_require__(19),
  107. components: {
  108. items: {
  109. Item: __webpack_require__(31),
  110. BackgroundItem: __webpack_require__(32),
  111. BoxItem: __webpack_require__(33),
  112. PointItem: __webpack_require__(34),
  113. RangeItem: __webpack_require__(35)
  114. },
  115. Component: __webpack_require__(20),
  116. CurrentTime: __webpack_require__(21),
  117. CustomTime: __webpack_require__(22),
  118. DataAxis: __webpack_require__(23),
  119. GraphGroup: __webpack_require__(24),
  120. Group: __webpack_require__(25),
  121. BackgroundGroup: __webpack_require__(26),
  122. ItemSet: __webpack_require__(27),
  123. Legend: __webpack_require__(28),
  124. LineGraph: __webpack_require__(29),
  125. TimeAxis: __webpack_require__(30)
  126. }
  127. };
  128. // Network
  129. exports.Network = __webpack_require__(36);
  130. exports.network = {
  131. Edge: __webpack_require__(37),
  132. Groups: __webpack_require__(38),
  133. Images: __webpack_require__(39),
  134. Node: __webpack_require__(40),
  135. Popup: __webpack_require__(41),
  136. dotparser: __webpack_require__(42),
  137. gephiParser: __webpack_require__(43)
  138. };
  139. // Deprecated since v3.0.0
  140. exports.Graph = function () {
  141. throw new Error('Graph is renamed to Network. Please create a graph as new vis.Network(...)');
  142. };
  143. // bundled external libraries
  144. exports.moment = __webpack_require__(44);
  145. exports.hammer = __webpack_require__(45);
  146. /***/ },
  147. /* 1 */
  148. /***/ function(module, exports, __webpack_require__) {
  149. // utility functions
  150. // first check if moment.js is already loaded in the browser window, if so,
  151. // use this instance. Else, load via commonjs.
  152. var moment = __webpack_require__(44);
  153. /**
  154. * Test whether given object is a number
  155. * @param {*} object
  156. * @return {Boolean} isNumber
  157. */
  158. exports.isNumber = function(object) {
  159. return (object instanceof Number || typeof object == 'number');
  160. };
  161. /**
  162. * Test whether given object is a string
  163. * @param {*} object
  164. * @return {Boolean} isString
  165. */
  166. exports.isString = function(object) {
  167. return (object instanceof String || typeof object == 'string');
  168. };
  169. /**
  170. * Test whether given object is a Date, or a String containing a Date
  171. * @param {Date | String} object
  172. * @return {Boolean} isDate
  173. */
  174. exports.isDate = function(object) {
  175. if (object instanceof Date) {
  176. return true;
  177. }
  178. else if (exports.isString(object)) {
  179. // test whether this string contains a date
  180. var match = ASPDateRegex.exec(object);
  181. if (match) {
  182. return true;
  183. }
  184. else if (!isNaN(Date.parse(object))) {
  185. return true;
  186. }
  187. }
  188. return false;
  189. };
  190. /**
  191. * Test whether given object is an instance of google.visualization.DataTable
  192. * @param {*} object
  193. * @return {Boolean} isDataTable
  194. */
  195. exports.isDataTable = function(object) {
  196. return (typeof (google) !== 'undefined') &&
  197. (google.visualization) &&
  198. (google.visualization.DataTable) &&
  199. (object instanceof google.visualization.DataTable);
  200. };
  201. /**
  202. * Create a semi UUID
  203. * source: http://stackoverflow.com/a/105074/1262753
  204. * @return {String} uuid
  205. */
  206. exports.randomUUID = function() {
  207. var S4 = function () {
  208. return Math.floor(
  209. Math.random() * 0x10000 /* 65536 */
  210. ).toString(16);
  211. };
  212. return (
  213. S4() + S4() + '-' +
  214. S4() + '-' +
  215. S4() + '-' +
  216. S4() + '-' +
  217. S4() + S4() + S4()
  218. );
  219. };
  220. /**
  221. * Extend object a with the properties of object b or a series of objects
  222. * Only properties with defined values are copied
  223. * @param {Object} a
  224. * @param {... Object} b
  225. * @return {Object} a
  226. */
  227. exports.extend = function (a, b) {
  228. for (var i = 1, len = arguments.length; i < len; i++) {
  229. var other = arguments[i];
  230. for (var prop in other) {
  231. if (other.hasOwnProperty(prop)) {
  232. a[prop] = other[prop];
  233. }
  234. }
  235. }
  236. return a;
  237. };
  238. /**
  239. * Extend object a with selected properties of object b or a series of objects
  240. * Only properties with defined values are copied
  241. * @param {Array.<String>} props
  242. * @param {Object} a
  243. * @param {... Object} b
  244. * @return {Object} a
  245. */
  246. exports.selectiveExtend = function (props, a, b) {
  247. if (!Array.isArray(props)) {
  248. throw new Error('Array with property names expected as first argument');
  249. }
  250. for (var i = 2; i < arguments.length; i++) {
  251. var other = arguments[i];
  252. for (var p = 0; p < props.length; p++) {
  253. var prop = props[p];
  254. if (other.hasOwnProperty(prop)) {
  255. a[prop] = other[prop];
  256. }
  257. }
  258. }
  259. return a;
  260. };
  261. /**
  262. * Extend object a with selected properties of object b or a series of objects
  263. * Only properties with defined values are copied
  264. * @param {Array.<String>} props
  265. * @param {Object} a
  266. * @param {... Object} b
  267. * @return {Object} a
  268. */
  269. exports.selectiveDeepExtend = function (props, a, b) {
  270. // TODO: add support for Arrays to deepExtend
  271. if (Array.isArray(b)) {
  272. throw new TypeError('Arrays are not supported by deepExtend');
  273. }
  274. for (var i = 2; i < arguments.length; i++) {
  275. var other = arguments[i];
  276. for (var p = 0; p < props.length; p++) {
  277. var prop = props[p];
  278. if (other.hasOwnProperty(prop)) {
  279. if (b[prop] && b[prop].constructor === Object) {
  280. if (a[prop] === undefined) {
  281. a[prop] = {};
  282. }
  283. if (a[prop].constructor === Object) {
  284. exports.deepExtend(a[prop], b[prop]);
  285. }
  286. else {
  287. a[prop] = b[prop];
  288. }
  289. } else if (Array.isArray(b[prop])) {
  290. throw new TypeError('Arrays are not supported by deepExtend');
  291. } else {
  292. a[prop] = b[prop];
  293. }
  294. }
  295. }
  296. }
  297. return a;
  298. };
  299. /**
  300. * Extend object a with selected properties of object b or a series of objects
  301. * Only properties with defined values are copied
  302. * @param {Array.<String>} props
  303. * @param {Object} a
  304. * @param {... Object} b
  305. * @return {Object} a
  306. */
  307. exports.selectiveNotDeepExtend = function (props, a, b) {
  308. // TODO: add support for Arrays to deepExtend
  309. if (Array.isArray(b)) {
  310. throw new TypeError('Arrays are not supported by deepExtend');
  311. }
  312. for (var prop in b) {
  313. if (b.hasOwnProperty(prop)) {
  314. if (props.indexOf(prop) == -1) {
  315. if (b[prop] && b[prop].constructor === Object) {
  316. if (a[prop] === undefined) {
  317. a[prop] = {};
  318. }
  319. if (a[prop].constructor === Object) {
  320. exports.deepExtend(a[prop], b[prop]);
  321. }
  322. else {
  323. a[prop] = b[prop];
  324. }
  325. } else if (Array.isArray(b[prop])) {
  326. throw new TypeError('Arrays are not supported by deepExtend');
  327. } else {
  328. a[prop] = b[prop];
  329. }
  330. }
  331. }
  332. }
  333. return a;
  334. };
  335. /**
  336. * Deep extend an object a with the properties of object b
  337. * @param {Object} a
  338. * @param {Object} b
  339. * @returns {Object}
  340. */
  341. exports.deepExtend = function(a, b) {
  342. // TODO: add support for Arrays to deepExtend
  343. if (Array.isArray(b)) {
  344. throw new TypeError('Arrays are not supported by deepExtend');
  345. }
  346. for (var prop in b) {
  347. if (b.hasOwnProperty(prop)) {
  348. if (b[prop] && b[prop].constructor === Object) {
  349. if (a[prop] === undefined) {
  350. a[prop] = {};
  351. }
  352. if (a[prop].constructor === Object) {
  353. exports.deepExtend(a[prop], b[prop]);
  354. }
  355. else {
  356. a[prop] = b[prop];
  357. }
  358. } else if (Array.isArray(b[prop])) {
  359. throw new TypeError('Arrays are not supported by deepExtend');
  360. } else {
  361. a[prop] = b[prop];
  362. }
  363. }
  364. }
  365. return a;
  366. };
  367. /**
  368. * Test whether all elements in two arrays are equal.
  369. * @param {Array} a
  370. * @param {Array} b
  371. * @return {boolean} Returns true if both arrays have the same length and same
  372. * elements.
  373. */
  374. exports.equalArray = function (a, b) {
  375. if (a.length != b.length) return false;
  376. for (var i = 0, len = a.length; i < len; i++) {
  377. if (a[i] != b[i]) return false;
  378. }
  379. return true;
  380. };
  381. /**
  382. * Convert an object to another type
  383. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  384. * @param {String | undefined} type Name of the type. Available types:
  385. * 'Boolean', 'Number', 'String',
  386. * 'Date', 'Moment', ISODate', 'ASPDate'.
  387. * @return {*} object
  388. * @throws Error
  389. */
  390. exports.convert = function(object, type) {
  391. var match;
  392. if (object === undefined) {
  393. return undefined;
  394. }
  395. if (object === null) {
  396. return null;
  397. }
  398. if (!type) {
  399. return object;
  400. }
  401. if (!(typeof type === 'string') && !(type instanceof String)) {
  402. throw new Error('Type must be a string');
  403. }
  404. //noinspection FallthroughInSwitchStatementJS
  405. switch (type) {
  406. case 'boolean':
  407. case 'Boolean':
  408. return Boolean(object);
  409. case 'number':
  410. case 'Number':
  411. return Number(object.valueOf());
  412. case 'string':
  413. case 'String':
  414. return String(object);
  415. case 'Date':
  416. if (exports.isNumber(object)) {
  417. return new Date(object);
  418. }
  419. if (object instanceof Date) {
  420. return new Date(object.valueOf());
  421. }
  422. else if (moment.isMoment(object)) {
  423. return new Date(object.valueOf());
  424. }
  425. if (exports.isString(object)) {
  426. match = ASPDateRegex.exec(object);
  427. if (match) {
  428. // object is an ASP date
  429. return new Date(Number(match[1])); // parse number
  430. }
  431. else {
  432. return moment(object).toDate(); // parse string
  433. }
  434. }
  435. else {
  436. throw new Error(
  437. 'Cannot convert object of type ' + exports.getType(object) +
  438. ' to type Date');
  439. }
  440. case 'Moment':
  441. if (exports.isNumber(object)) {
  442. return moment(object);
  443. }
  444. if (object instanceof Date) {
  445. return moment(object.valueOf());
  446. }
  447. else if (moment.isMoment(object)) {
  448. return moment(object);
  449. }
  450. if (exports.isString(object)) {
  451. match = ASPDateRegex.exec(object);
  452. if (match) {
  453. // object is an ASP date
  454. return moment(Number(match[1])); // parse number
  455. }
  456. else {
  457. return moment(object); // parse string
  458. }
  459. }
  460. else {
  461. throw new Error(
  462. 'Cannot convert object of type ' + exports.getType(object) +
  463. ' to type Date');
  464. }
  465. case 'ISODate':
  466. if (exports.isNumber(object)) {
  467. return new Date(object);
  468. }
  469. else if (object instanceof Date) {
  470. return object.toISOString();
  471. }
  472. else if (moment.isMoment(object)) {
  473. return object.toDate().toISOString();
  474. }
  475. else if (exports.isString(object)) {
  476. match = ASPDateRegex.exec(object);
  477. if (match) {
  478. // object is an ASP date
  479. return new Date(Number(match[1])).toISOString(); // parse number
  480. }
  481. else {
  482. return new Date(object).toISOString(); // parse string
  483. }
  484. }
  485. else {
  486. throw new Error(
  487. 'Cannot convert object of type ' + exports.getType(object) +
  488. ' to type ISODate');
  489. }
  490. case 'ASPDate':
  491. if (exports.isNumber(object)) {
  492. return '/Date(' + object + ')/';
  493. }
  494. else if (object instanceof Date) {
  495. return '/Date(' + object.valueOf() + ')/';
  496. }
  497. else if (exports.isString(object)) {
  498. match = ASPDateRegex.exec(object);
  499. var value;
  500. if (match) {
  501. // object is an ASP date
  502. value = new Date(Number(match[1])).valueOf(); // parse number
  503. }
  504. else {
  505. value = new Date(object).valueOf(); // parse string
  506. }
  507. return '/Date(' + value + ')/';
  508. }
  509. else {
  510. throw new Error(
  511. 'Cannot convert object of type ' + exports.getType(object) +
  512. ' to type ASPDate');
  513. }
  514. default:
  515. throw new Error('Unknown type "' + type + '"');
  516. }
  517. };
  518. // parse ASP.Net Date pattern,
  519. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  520. // code from http://momentjs.com/
  521. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  522. /**
  523. * Get the type of an object, for example exports.getType([]) returns 'Array'
  524. * @param {*} object
  525. * @return {String} type
  526. */
  527. exports.getType = function(object) {
  528. var type = typeof object;
  529. if (type == 'object') {
  530. if (object == null) {
  531. return 'null';
  532. }
  533. if (object instanceof Boolean) {
  534. return 'Boolean';
  535. }
  536. if (object instanceof Number) {
  537. return 'Number';
  538. }
  539. if (object instanceof String) {
  540. return 'String';
  541. }
  542. if (Array.isArray(object)) {
  543. return 'Array';
  544. }
  545. if (object instanceof Date) {
  546. return 'Date';
  547. }
  548. return 'Object';
  549. }
  550. else if (type == 'number') {
  551. return 'Number';
  552. }
  553. else if (type == 'boolean') {
  554. return 'Boolean';
  555. }
  556. else if (type == 'string') {
  557. return 'String';
  558. }
  559. return type;
  560. };
  561. /**
  562. * Retrieve the absolute left value of a DOM element
  563. * @param {Element} elem A dom element, for example a div
  564. * @return {number} left The absolute left position of this element
  565. * in the browser page.
  566. */
  567. exports.getAbsoluteLeft = function(elem) {
  568. return elem.getBoundingClientRect().left + window.pageXOffset;
  569. };
  570. /**
  571. * Retrieve the absolute top value of a DOM element
  572. * @param {Element} elem A dom element, for example a div
  573. * @return {number} top The absolute top position of this element
  574. * in the browser page.
  575. */
  576. exports.getAbsoluteTop = function(elem) {
  577. return elem.getBoundingClientRect().top + window.pageYOffset;
  578. };
  579. /**
  580. * add a className to the given elements style
  581. * @param {Element} elem
  582. * @param {String} className
  583. */
  584. exports.addClassName = function(elem, className) {
  585. var classes = elem.className.split(' ');
  586. if (classes.indexOf(className) == -1) {
  587. classes.push(className); // add the class to the array
  588. elem.className = classes.join(' ');
  589. }
  590. };
  591. /**
  592. * add a className to the given elements style
  593. * @param {Element} elem
  594. * @param {String} className
  595. */
  596. exports.removeClassName = function(elem, className) {
  597. var classes = elem.className.split(' ');
  598. var index = classes.indexOf(className);
  599. if (index != -1) {
  600. classes.splice(index, 1); // remove the class from the array
  601. elem.className = classes.join(' ');
  602. }
  603. };
  604. /**
  605. * For each method for both arrays and objects.
  606. * In case of an array, the built-in Array.forEach() is applied.
  607. * In case of an Object, the method loops over all properties of the object.
  608. * @param {Object | Array} object An Object or Array
  609. * @param {function} callback Callback method, called for each item in
  610. * the object or array with three parameters:
  611. * callback(value, index, object)
  612. */
  613. exports.forEach = function(object, callback) {
  614. var i,
  615. len;
  616. if (Array.isArray(object)) {
  617. // array
  618. for (i = 0, len = object.length; i < len; i++) {
  619. callback(object[i], i, object);
  620. }
  621. }
  622. else {
  623. // object
  624. for (i in object) {
  625. if (object.hasOwnProperty(i)) {
  626. callback(object[i], i, object);
  627. }
  628. }
  629. }
  630. };
  631. /**
  632. * Convert an object into an array: all objects properties are put into the
  633. * array. The resulting array is unordered.
  634. * @param {Object} object
  635. * @param {Array} array
  636. */
  637. exports.toArray = function(object) {
  638. var array = [];
  639. for (var prop in object) {
  640. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  641. }
  642. return array;
  643. }
  644. /**
  645. * Update a property in an object
  646. * @param {Object} object
  647. * @param {String} key
  648. * @param {*} value
  649. * @return {Boolean} changed
  650. */
  651. exports.updateProperty = function(object, key, value) {
  652. if (object[key] !== value) {
  653. object[key] = value;
  654. return true;
  655. }
  656. else {
  657. return false;
  658. }
  659. };
  660. /**
  661. * Add and event listener. Works for all browsers
  662. * @param {Element} element An html element
  663. * @param {string} action The action, for example "click",
  664. * without the prefix "on"
  665. * @param {function} listener The callback function to be executed
  666. * @param {boolean} [useCapture]
  667. */
  668. exports.addEventListener = function(element, action, listener, useCapture) {
  669. if (element.addEventListener) {
  670. if (useCapture === undefined)
  671. useCapture = false;
  672. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  673. action = "DOMMouseScroll"; // For Firefox
  674. }
  675. element.addEventListener(action, listener, useCapture);
  676. } else {
  677. element.attachEvent("on" + action, listener); // IE browsers
  678. }
  679. };
  680. /**
  681. * Remove an event listener from an element
  682. * @param {Element} element An html dom element
  683. * @param {string} action The name of the event, for example "mousedown"
  684. * @param {function} listener The listener function
  685. * @param {boolean} [useCapture]
  686. */
  687. exports.removeEventListener = function(element, action, listener, useCapture) {
  688. if (element.removeEventListener) {
  689. // non-IE browsers
  690. if (useCapture === undefined)
  691. useCapture = false;
  692. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  693. action = "DOMMouseScroll"; // For Firefox
  694. }
  695. element.removeEventListener(action, listener, useCapture);
  696. } else {
  697. // IE browsers
  698. element.detachEvent("on" + action, listener);
  699. }
  700. };
  701. /**
  702. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  703. */
  704. exports.preventDefault = function (event) {
  705. if (!event)
  706. event = window.event;
  707. if (event.preventDefault) {
  708. event.preventDefault(); // non-IE browsers
  709. }
  710. else {
  711. event.returnValue = false; // IE browsers
  712. }
  713. };
  714. /**
  715. * Get HTML element which is the target of the event
  716. * @param {Event} event
  717. * @return {Element} target element
  718. */
  719. exports.getTarget = function(event) {
  720. // code from http://www.quirksmode.org/js/events_properties.html
  721. if (!event) {
  722. event = window.event;
  723. }
  724. var target;
  725. if (event.target) {
  726. target = event.target;
  727. }
  728. else if (event.srcElement) {
  729. target = event.srcElement;
  730. }
  731. if (target.nodeType != undefined && target.nodeType == 3) {
  732. // defeat Safari bug
  733. target = target.parentNode;
  734. }
  735. return target;
  736. };
  737. exports.option = {};
  738. /**
  739. * Convert a value into a boolean
  740. * @param {Boolean | function | undefined} value
  741. * @param {Boolean} [defaultValue]
  742. * @returns {Boolean} bool
  743. */
  744. exports.option.asBoolean = function (value, defaultValue) {
  745. if (typeof value == 'function') {
  746. value = value();
  747. }
  748. if (value != null) {
  749. return (value != false);
  750. }
  751. return defaultValue || null;
  752. };
  753. /**
  754. * Convert a value into a number
  755. * @param {Boolean | function | undefined} value
  756. * @param {Number} [defaultValue]
  757. * @returns {Number} number
  758. */
  759. exports.option.asNumber = function (value, defaultValue) {
  760. if (typeof value == 'function') {
  761. value = value();
  762. }
  763. if (value != null) {
  764. return Number(value) || defaultValue || null;
  765. }
  766. return defaultValue || null;
  767. };
  768. /**
  769. * Convert a value into a string
  770. * @param {String | function | undefined} value
  771. * @param {String} [defaultValue]
  772. * @returns {String} str
  773. */
  774. exports.option.asString = function (value, defaultValue) {
  775. if (typeof value == 'function') {
  776. value = value();
  777. }
  778. if (value != null) {
  779. return String(value);
  780. }
  781. return defaultValue || null;
  782. };
  783. /**
  784. * Convert a size or location into a string with pixels or a percentage
  785. * @param {String | Number | function | undefined} value
  786. * @param {String} [defaultValue]
  787. * @returns {String} size
  788. */
  789. exports.option.asSize = function (value, defaultValue) {
  790. if (typeof value == 'function') {
  791. value = value();
  792. }
  793. if (exports.isString(value)) {
  794. return value;
  795. }
  796. else if (exports.isNumber(value)) {
  797. return value + 'px';
  798. }
  799. else {
  800. return defaultValue || null;
  801. }
  802. };
  803. /**
  804. * Convert a value into a DOM element
  805. * @param {HTMLElement | function | undefined} value
  806. * @param {HTMLElement} [defaultValue]
  807. * @returns {HTMLElement | null} dom
  808. */
  809. exports.option.asElement = function (value, defaultValue) {
  810. if (typeof value == 'function') {
  811. value = value();
  812. }
  813. return value || defaultValue || null;
  814. };
  815. exports.GiveDec = function(Hex) {
  816. var Value;
  817. if (Hex == "A")
  818. Value = 10;
  819. else if (Hex == "B")
  820. Value = 11;
  821. else if (Hex == "C")
  822. Value = 12;
  823. else if (Hex == "D")
  824. Value = 13;
  825. else if (Hex == "E")
  826. Value = 14;
  827. else if (Hex == "F")
  828. Value = 15;
  829. else
  830. Value = eval(Hex);
  831. return Value;
  832. };
  833. exports.GiveHex = function(Dec) {
  834. var Value;
  835. if(Dec == 10)
  836. Value = "A";
  837. else if (Dec == 11)
  838. Value = "B";
  839. else if (Dec == 12)
  840. Value = "C";
  841. else if (Dec == 13)
  842. Value = "D";
  843. else if (Dec == 14)
  844. Value = "E";
  845. else if (Dec == 15)
  846. Value = "F";
  847. else
  848. Value = "" + Dec;
  849. return Value;
  850. };
  851. /**
  852. * Parse a color property into an object with border, background, and
  853. * highlight colors
  854. * @param {Object | String} color
  855. * @return {Object} colorObject
  856. */
  857. exports.parseColor = function(color) {
  858. var c;
  859. if (exports.isString(color)) {
  860. if (exports.isValidRGB(color)) {
  861. var rgb = color.substr(4).substr(0,color.length-5).split(',');
  862. color = exports.RGBToHex(rgb[0],rgb[1],rgb[2]);
  863. }
  864. if (exports.isValidHex(color)) {
  865. var hsv = exports.hexToHSV(color);
  866. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  867. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  868. var darkerColorHex = exports.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  869. var lighterColorHex = exports.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  870. c = {
  871. background: color,
  872. border:darkerColorHex,
  873. highlight: {
  874. background:lighterColorHex,
  875. border:darkerColorHex
  876. },
  877. hover: {
  878. background:lighterColorHex,
  879. border:darkerColorHex
  880. }
  881. };
  882. }
  883. else {
  884. c = {
  885. background:color,
  886. border:color,
  887. highlight: {
  888. background:color,
  889. border:color
  890. },
  891. hover: {
  892. background:color,
  893. border:color
  894. }
  895. };
  896. }
  897. }
  898. else {
  899. c = {};
  900. c.background = color.background || 'white';
  901. c.border = color.border || c.background;
  902. if (exports.isString(color.highlight)) {
  903. c.highlight = {
  904. border: color.highlight,
  905. background: color.highlight
  906. }
  907. }
  908. else {
  909. c.highlight = {};
  910. c.highlight.background = color.highlight && color.highlight.background || c.background;
  911. c.highlight.border = color.highlight && color.highlight.border || c.border;
  912. }
  913. if (exports.isString(color.hover)) {
  914. c.hover = {
  915. border: color.hover,
  916. background: color.hover
  917. }
  918. }
  919. else {
  920. c.hover = {};
  921. c.hover.background = color.hover && color.hover.background || c.background;
  922. c.hover.border = color.hover && color.hover.border || c.border;
  923. }
  924. }
  925. return c;
  926. };
  927. /**
  928. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  929. *
  930. * @param {String} hex
  931. * @returns {{r: *, g: *, b: *}}
  932. */
  933. exports.hexToRGB = function(hex) {
  934. hex = hex.replace("#","").toUpperCase();
  935. var a = exports.GiveDec(hex.substring(0, 1));
  936. var b = exports.GiveDec(hex.substring(1, 2));
  937. var c = exports.GiveDec(hex.substring(2, 3));
  938. var d = exports.GiveDec(hex.substring(3, 4));
  939. var e = exports.GiveDec(hex.substring(4, 5));
  940. var f = exports.GiveDec(hex.substring(5, 6));
  941. var r = (a * 16) + b;
  942. var g = (c * 16) + d;
  943. var b = (e * 16) + f;
  944. return {r:r,g:g,b:b};
  945. };
  946. exports.RGBToHex = function(red,green,blue) {
  947. var a = exports.GiveHex(Math.floor(red / 16));
  948. var b = exports.GiveHex(red % 16);
  949. var c = exports.GiveHex(Math.floor(green / 16));
  950. var d = exports.GiveHex(green % 16);
  951. var e = exports.GiveHex(Math.floor(blue / 16));
  952. var f = exports.GiveHex(blue % 16);
  953. var hex = a + b + c + d + e + f;
  954. return "#" + hex;
  955. };
  956. /**
  957. * http://www.javascripter.net/faq/rgb2hsv.htm
  958. *
  959. * @param red
  960. * @param green
  961. * @param blue
  962. * @returns {*}
  963. * @constructor
  964. */
  965. exports.RGBToHSV = function(red,green,blue) {
  966. red=red/255; green=green/255; blue=blue/255;
  967. var minRGB = Math.min(red,Math.min(green,blue));
  968. var maxRGB = Math.max(red,Math.max(green,blue));
  969. // Black-gray-white
  970. if (minRGB == maxRGB) {
  971. return {h:0,s:0,v:minRGB};
  972. }
  973. // Colors other than black-gray-white:
  974. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  975. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  976. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  977. var saturation = (maxRGB - minRGB)/maxRGB;
  978. var value = maxRGB;
  979. return {h:hue,s:saturation,v:value};
  980. };
  981. var cssUtil = {
  982. // split a string with css styles into an object with key/values
  983. split: function (cssText) {
  984. var styles = {};
  985. cssText.split(';').forEach(function (style) {
  986. if (style.trim() != '') {
  987. var parts = style.split(':');
  988. var key = parts[0].trim();
  989. var value = parts[1].trim();
  990. styles[key] = value;
  991. }
  992. });
  993. return styles;
  994. },
  995. // build a css text string from an object with key/values
  996. join: function (styles) {
  997. return Object.keys(styles)
  998. .map(function (key) {
  999. return key + ': ' + styles[key];
  1000. })
  1001. .join('; ');
  1002. }
  1003. };
  1004. /**
  1005. * Append a string with css styles to an element
  1006. * @param {Element} element
  1007. * @param {String} cssText
  1008. */
  1009. exports.addCssText = function (element, cssText) {
  1010. var currentStyles = cssUtil.split(element.style.cssText);
  1011. var newStyles = cssUtil.split(cssText);
  1012. var styles = exports.extend(currentStyles, newStyles);
  1013. element.style.cssText = cssUtil.join(styles);
  1014. };
  1015. /**
  1016. * Remove a string with css styles from an element
  1017. * @param {Element} element
  1018. * @param {String} cssText
  1019. */
  1020. exports.removeCssText = function (element, cssText) {
  1021. var styles = cssUtil.split(element.style.cssText);
  1022. var removeStyles = cssUtil.split(cssText);
  1023. for (var key in removeStyles) {
  1024. if (removeStyles.hasOwnProperty(key)) {
  1025. delete styles[key];
  1026. }
  1027. }
  1028. element.style.cssText = cssUtil.join(styles);
  1029. };
  1030. /**
  1031. * https://gist.github.com/mjijackson/5311256
  1032. * @param h
  1033. * @param s
  1034. * @param v
  1035. * @returns {{r: number, g: number, b: number}}
  1036. * @constructor
  1037. */
  1038. exports.HSVToRGB = function(h, s, v) {
  1039. var r, g, b;
  1040. var i = Math.floor(h * 6);
  1041. var f = h * 6 - i;
  1042. var p = v * (1 - s);
  1043. var q = v * (1 - f * s);
  1044. var t = v * (1 - (1 - f) * s);
  1045. switch (i % 6) {
  1046. case 0: r = v, g = t, b = p; break;
  1047. case 1: r = q, g = v, b = p; break;
  1048. case 2: r = p, g = v, b = t; break;
  1049. case 3: r = p, g = q, b = v; break;
  1050. case 4: r = t, g = p, b = v; break;
  1051. case 5: r = v, g = p, b = q; break;
  1052. }
  1053. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1054. };
  1055. exports.HSVToHex = function(h, s, v) {
  1056. var rgb = exports.HSVToRGB(h, s, v);
  1057. return exports.RGBToHex(rgb.r, rgb.g, rgb.b);
  1058. };
  1059. exports.hexToHSV = function(hex) {
  1060. var rgb = exports.hexToRGB(hex);
  1061. return exports.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1062. };
  1063. exports.isValidHex = function(hex) {
  1064. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1065. return isOk;
  1066. };
  1067. exports.isValidRGB = function(rgb) {
  1068. rgb = rgb.replace(" ","");
  1069. var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb);
  1070. return isOk;
  1071. }
  1072. /**
  1073. * This recursively redirects the prototype of JSON objects to the referenceObject
  1074. * This is used for default options.
  1075. *
  1076. * @param referenceObject
  1077. * @returns {*}
  1078. */
  1079. exports.selectiveBridgeObject = function(fields, referenceObject) {
  1080. if (typeof referenceObject == "object") {
  1081. var objectTo = Object.create(referenceObject);
  1082. for (var i = 0; i < fields.length; i++) {
  1083. if (referenceObject.hasOwnProperty(fields[i])) {
  1084. if (typeof referenceObject[fields[i]] == "object") {
  1085. objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]);
  1086. }
  1087. }
  1088. }
  1089. return objectTo;
  1090. }
  1091. else {
  1092. return null;
  1093. }
  1094. };
  1095. /**
  1096. * This recursively redirects the prototype of JSON objects to the referenceObject
  1097. * This is used for default options.
  1098. *
  1099. * @param referenceObject
  1100. * @returns {*}
  1101. */
  1102. exports.bridgeObject = function(referenceObject) {
  1103. if (typeof referenceObject == "object") {
  1104. var objectTo = Object.create(referenceObject);
  1105. for (var i in referenceObject) {
  1106. if (referenceObject.hasOwnProperty(i)) {
  1107. if (typeof referenceObject[i] == "object") {
  1108. objectTo[i] = exports.bridgeObject(referenceObject[i]);
  1109. }
  1110. }
  1111. }
  1112. return objectTo;
  1113. }
  1114. else {
  1115. return null;
  1116. }
  1117. };
  1118. /**
  1119. * this is used to set the options of subobjects in the options object. A requirement of these subobjects
  1120. * is that they have an 'enabled' element which is optional for the user but mandatory for the program.
  1121. *
  1122. * @param [object] mergeTarget | this is either this.options or the options used for the groups.
  1123. * @param [object] options | options
  1124. * @param [String] option | this is the option key in the options argument
  1125. * @private
  1126. */
  1127. exports.mergeOptions = function (mergeTarget, options, option) {
  1128. if (options[option] !== undefined) {
  1129. if (typeof options[option] == 'boolean') {
  1130. mergeTarget[option].enabled = options[option];
  1131. }
  1132. else {
  1133. mergeTarget[option].enabled = true;
  1134. for (var prop in options[option]) {
  1135. if (options[option].hasOwnProperty(prop)) {
  1136. mergeTarget[option][prop] = options[option][prop];
  1137. }
  1138. }
  1139. }
  1140. }
  1141. }
  1142. /**
  1143. * This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
  1144. * this function will then iterate in both directions over this sorted list to find all visible items.
  1145. *
  1146. * @param {Item[]} orderedItems | Items ordered by start
  1147. * @param {function} searchFunction | -1 is lower, 0 is found, 1 is higher
  1148. * @param {String} field
  1149. * @param {String} field2
  1150. * @returns {number}
  1151. * @private
  1152. */
  1153. exports.binarySearchCustom = function(orderedItems, searchFunction, field, field2) {
  1154. var maxIterations = 10000;
  1155. var iteration = 0;
  1156. var low = 0;
  1157. var high = orderedItems.length - 1;
  1158. while (low <= high && iteration < maxIterations) {
  1159. var middle = Math.floor((low + high) / 2);
  1160. var item = orderedItems[middle];
  1161. var value = (field2 === undefined) ? item[field] : item[field][field2];
  1162. var searchResult = searchFunction(value);
  1163. if (searchResult == 0) { // jihaa, found a visible item!
  1164. return middle;
  1165. }
  1166. else if (searchResult == -1) { // it is too small --> increase low
  1167. low = middle + 1;
  1168. }
  1169. else { // it is too big --> decrease high
  1170. high = middle - 1;
  1171. }
  1172. iteration++;
  1173. }
  1174. return -1;
  1175. };
  1176. /**
  1177. * This function does a binary search for a specific value in a sorted array. If it does not exist but is in between of
  1178. * two values, we return either the one before or the one after, depending on user input
  1179. * If it is found, we return the index, else -1.
  1180. *
  1181. * @param {Array} orderedItems
  1182. * @param {{start: number, end: number}} target
  1183. * @param {String} field
  1184. * @param {String} sidePreference 'before' or 'after'
  1185. * @returns {number}
  1186. * @private
  1187. */
  1188. exports.binarySearchValue = function(orderedItems, target, field, sidePreference) {
  1189. var maxIterations = 10000;
  1190. var iteration = 0;
  1191. var low = 0;
  1192. var high = orderedItems.length - 1;
  1193. var prevValue, value, nextValue, middle;
  1194. while (low <= high && iteration < maxIterations) {
  1195. // get a new guess
  1196. middle = Math.floor(0.5*(high+low));
  1197. prevValue = orderedItems[Math.max(0,middle - 1)][field];
  1198. value = orderedItems[middle][field];
  1199. nextValue = orderedItems[Math.min(orderedItems.length-1,middle + 1)][field];
  1200. if (value == target) { // we found the target
  1201. return middle;
  1202. }
  1203. else if (prevValue < target && value > target) { // target is in between of the previous and the current
  1204. return sidePreference == 'before' ? Math.max(0,middle - 1) : middle;
  1205. }
  1206. else if (value < target && nextValue > target) { // target is in between of the current and the next
  1207. return sidePreference == 'before' ? middle : Math.min(orderedItems.length-1,middle + 1);
  1208. }
  1209. else { // didnt find the target, we need to change our boundaries.
  1210. if (value < target) { // it is too small --> increase low
  1211. low = middle + 1;
  1212. }
  1213. else { // it is too big --> decrease high
  1214. high = middle - 1;
  1215. }
  1216. }
  1217. iteration++;
  1218. }
  1219. // didnt find anything. Return -1.
  1220. return -1;
  1221. };
  1222. /**
  1223. * Quadratic ease-in-out
  1224. * http://gizma.com/easing/
  1225. * @param {number} t Current time
  1226. * @param {number} start Start value
  1227. * @param {number} end End value
  1228. * @param {number} duration Duration
  1229. * @returns {number} Value corresponding with current time
  1230. */
  1231. exports.easeInOutQuad = function (t, start, end, duration) {
  1232. var change = end - start;
  1233. t /= duration/2;
  1234. if (t < 1) return change/2*t*t + start;
  1235. t--;
  1236. return -change/2 * (t*(t-2) - 1) + start;
  1237. };
  1238. /*
  1239. * Easing Functions - inspired from http://gizma.com/easing/
  1240. * only considering the t value for the range [0, 1] => [0, 1]
  1241. * https://gist.github.com/gre/1650294
  1242. */
  1243. exports.easingFunctions = {
  1244. // no easing, no acceleration
  1245. linear: function (t) {
  1246. return t
  1247. },
  1248. // accelerating from zero velocity
  1249. easeInQuad: function (t) {
  1250. return t * t
  1251. },
  1252. // decelerating to zero velocity
  1253. easeOutQuad: function (t) {
  1254. return t * (2 - t)
  1255. },
  1256. // acceleration until halfway, then deceleration
  1257. easeInOutQuad: function (t) {
  1258. return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t
  1259. },
  1260. // accelerating from zero velocity
  1261. easeInCubic: function (t) {
  1262. return t * t * t
  1263. },
  1264. // decelerating to zero velocity
  1265. easeOutCubic: function (t) {
  1266. return (--t) * t * t + 1
  1267. },
  1268. // acceleration until halfway, then deceleration
  1269. easeInOutCubic: function (t) {
  1270. return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
  1271. },
  1272. // accelerating from zero velocity
  1273. easeInQuart: function (t) {
  1274. return t * t * t * t
  1275. },
  1276. // decelerating to zero velocity
  1277. easeOutQuart: function (t) {
  1278. return 1 - (--t) * t * t * t
  1279. },
  1280. // acceleration until halfway, then deceleration
  1281. easeInOutQuart: function (t) {
  1282. return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t
  1283. },
  1284. // accelerating from zero velocity
  1285. easeInQuint: function (t) {
  1286. return t * t * t * t * t
  1287. },
  1288. // decelerating to zero velocity
  1289. easeOutQuint: function (t) {
  1290. return 1 + (--t) * t * t * t * t
  1291. },
  1292. // acceleration until halfway, then deceleration
  1293. easeInOutQuint: function (t) {
  1294. return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t
  1295. }
  1296. };
  1297. /***/ },
  1298. /* 2 */
  1299. /***/ function(module, exports, __webpack_require__) {
  1300. // DOM utility methods
  1301. /**
  1302. * this prepares the JSON container for allocating SVG elements
  1303. * @param JSONcontainer
  1304. * @private
  1305. */
  1306. exports.prepareElements = function(JSONcontainer) {
  1307. // cleanup the redundant svgElements;
  1308. for (var elementType in JSONcontainer) {
  1309. if (JSONcontainer.hasOwnProperty(elementType)) {
  1310. JSONcontainer[elementType].redundant = JSONcontainer[elementType].used;
  1311. JSONcontainer[elementType].used = [];
  1312. }
  1313. }
  1314. };
  1315. /**
  1316. * this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from
  1317. * which to remove the redundant elements.
  1318. *
  1319. * @param JSONcontainer
  1320. * @private
  1321. */
  1322. exports.cleanupElements = function(JSONcontainer) {
  1323. // cleanup the redundant svgElements;
  1324. for (var elementType in JSONcontainer) {
  1325. if (JSONcontainer.hasOwnProperty(elementType)) {
  1326. if (JSONcontainer[elementType].redundant) {
  1327. for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) {
  1328. JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]);
  1329. }
  1330. JSONcontainer[elementType].redundant = [];
  1331. }
  1332. }
  1333. }
  1334. };
  1335. /**
  1336. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  1337. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  1338. *
  1339. * @param elementType
  1340. * @param JSONcontainer
  1341. * @param svgContainer
  1342. * @returns {*}
  1343. * @private
  1344. */
  1345. exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
  1346. var element;
  1347. // allocate SVG element, if it doesnt yet exist, create one.
  1348. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
  1349. // check if there is an redundant element
  1350. if (JSONcontainer[elementType].redundant.length > 0) {
  1351. element = JSONcontainer[elementType].redundant[0];
  1352. JSONcontainer[elementType].redundant.shift();
  1353. }
  1354. else {
  1355. // create a new element and add it to the SVG
  1356. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  1357. svgContainer.appendChild(element);
  1358. }
  1359. }
  1360. else {
  1361. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  1362. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  1363. JSONcontainer[elementType] = {used: [], redundant: []};
  1364. svgContainer.appendChild(element);
  1365. }
  1366. JSONcontainer[elementType].used.push(element);
  1367. return element;
  1368. };
  1369. /**
  1370. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  1371. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  1372. *
  1373. * @param elementType
  1374. * @param JSONcontainer
  1375. * @param DOMContainer
  1376. * @returns {*}
  1377. * @private
  1378. */
  1379. exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer, insertBefore) {
  1380. var element;
  1381. // allocate DOM element, if it doesnt yet exist, create one.
  1382. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
  1383. // check if there is an redundant element
  1384. if (JSONcontainer[elementType].redundant.length > 0) {
  1385. element = JSONcontainer[elementType].redundant[0];
  1386. JSONcontainer[elementType].redundant.shift();
  1387. }
  1388. else {
  1389. // create a new element and add it to the SVG
  1390. element = document.createElement(elementType);
  1391. if (insertBefore !== undefined) {
  1392. DOMContainer.insertBefore(element, insertBefore);
  1393. }
  1394. else {
  1395. DOMContainer.appendChild(element);
  1396. }
  1397. }
  1398. }
  1399. else {
  1400. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  1401. element = document.createElement(elementType);
  1402. JSONcontainer[elementType] = {used: [], redundant: []};
  1403. if (insertBefore !== undefined) {
  1404. DOMContainer.insertBefore(element, insertBefore);
  1405. }
  1406. else {
  1407. DOMContainer.appendChild(element);
  1408. }
  1409. }
  1410. JSONcontainer[elementType].used.push(element);
  1411. return element;
  1412. };
  1413. /**
  1414. * draw a point object. this is a seperate function because it can also be called by the legend.
  1415. * The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions
  1416. * as well.
  1417. *
  1418. * @param x
  1419. * @param y
  1420. * @param group
  1421. * @param JSONcontainer
  1422. * @param svgContainer
  1423. * @returns {*}
  1424. */
  1425. exports.drawPoint = function(x, y, group, JSONcontainer, svgContainer) {
  1426. var point;
  1427. if (group.options.drawPoints.style == 'circle') {
  1428. point = exports.getSVGElement('circle',JSONcontainer,svgContainer);
  1429. point.setAttributeNS(null, "cx", x);
  1430. point.setAttributeNS(null, "cy", y);
  1431. point.setAttributeNS(null, "r", 0.5 * group.options.drawPoints.size);
  1432. }
  1433. else {
  1434. point = exports.getSVGElement('rect',JSONcontainer,svgContainer);
  1435. point.setAttributeNS(null, "x", x - 0.5*group.options.drawPoints.size);
  1436. point.setAttributeNS(null, "y", y - 0.5*group.options.drawPoints.size);
  1437. point.setAttributeNS(null, "width", group.options.drawPoints.size);
  1438. point.setAttributeNS(null, "height", group.options.drawPoints.size);
  1439. }
  1440. if(group.options.drawPoints.styles !== undefined) {
  1441. point.setAttributeNS(null, "style", group.group.options.drawPoints.styles);
  1442. }
  1443. point.setAttributeNS(null, "class", group.className + " point");
  1444. return point;
  1445. };
  1446. /**
  1447. * draw a bar SVG element centered on the X coordinate
  1448. *
  1449. * @param x
  1450. * @param y
  1451. * @param className
  1452. */
  1453. exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer) {
  1454. if (height != 0) {
  1455. if (height < 0) {
  1456. height *= -1;
  1457. y -= height;
  1458. }
  1459. var rect = exports.getSVGElement('rect',JSONcontainer, svgContainer);
  1460. rect.setAttributeNS(null, "x", x - 0.5 * width);
  1461. rect.setAttributeNS(null, "y", y);
  1462. rect.setAttributeNS(null, "width", width);
  1463. rect.setAttributeNS(null, "height", height);
  1464. rect.setAttributeNS(null, "class", className);
  1465. }
  1466. };
  1467. /***/ },
  1468. /* 3 */
  1469. /***/ function(module, exports, __webpack_require__) {
  1470. var util = __webpack_require__(1);
  1471. var Queue = __webpack_require__(5);
  1472. /**
  1473. * DataSet
  1474. *
  1475. * Usage:
  1476. * var dataSet = new DataSet({
  1477. * fieldId: '_id',
  1478. * type: {
  1479. * // ...
  1480. * }
  1481. * });
  1482. *
  1483. * dataSet.add(item);
  1484. * dataSet.add(data);
  1485. * dataSet.update(item);
  1486. * dataSet.update(data);
  1487. * dataSet.remove(id);
  1488. * dataSet.remove(ids);
  1489. * var data = dataSet.get();
  1490. * var data = dataSet.get(id);
  1491. * var data = dataSet.get(ids);
  1492. * var data = dataSet.get(ids, options, data);
  1493. * dataSet.clear();
  1494. *
  1495. * A data set can:
  1496. * - add/remove/update data
  1497. * - gives triggers upon changes in the data
  1498. * - can import/export data in various data formats
  1499. *
  1500. * @param {Array | DataTable} [data] Optional array with initial data
  1501. * @param {Object} [options] Available options:
  1502. * {String} fieldId Field name of the id in the
  1503. * items, 'id' by default.
  1504. * {Object.<String, String} type
  1505. * A map with field names as key,
  1506. * and the field type as value.
  1507. * {Object} queue Queue changes to the DataSet,
  1508. * flush them all at once.
  1509. * Queue options:
  1510. * - {number} delay Delay in ms, null by default
  1511. * - {number} max Maximum number of entries in the queue, Infinity by default
  1512. * @constructor DataSet
  1513. */
  1514. // TODO: add a DataSet constructor DataSet(data, options)
  1515. function DataSet (data, options) {
  1516. // correctly read optional arguments
  1517. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  1518. options = data;
  1519. data = null;
  1520. }
  1521. this._options = options || {};
  1522. this._data = {}; // map with data indexed by id
  1523. this._fieldId = this._options.fieldId || 'id'; // name of the field containing id
  1524. this._type = {}; // internal field types (NOTE: this can differ from this._options.type)
  1525. // all variants of a Date are internally stored as Date, so we can convert
  1526. // from everything to everything (also from ISODate to Number for example)
  1527. if (this._options.type) {
  1528. for (var field in this._options.type) {
  1529. if (this._options.type.hasOwnProperty(field)) {
  1530. var value = this._options.type[field];
  1531. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1532. this._type[field] = 'Date';
  1533. }
  1534. else {
  1535. this._type[field] = value;
  1536. }
  1537. }
  1538. }
  1539. }
  1540. // TODO: deprecated since version 1.1.1 (or 2.0.0?)
  1541. if (this._options.convert) {
  1542. throw new Error('Option "convert" is deprecated. Use "type" instead.');
  1543. }
  1544. this._subscribers = {}; // event subscribers
  1545. // add initial data when provided
  1546. if (data) {
  1547. this.add(data);
  1548. }
  1549. this.setOptions(options);
  1550. }
  1551. /**
  1552. * @param {Object} [options] Available options:
  1553. * {Object} queue Queue changes to the DataSet,
  1554. * flush them all at once.
  1555. * Queue options:
  1556. * - {number} delay Delay in ms, null by default
  1557. * - {number} max Maximum number of entries in the queue, Infinity by default
  1558. * @param options
  1559. */
  1560. DataSet.prototype.setOptions = function(options) {
  1561. if (options && options.queue !== undefined) {
  1562. if (options.queue === false) {
  1563. // delete queue if loaded
  1564. if (this._queue) {
  1565. this._queue.destroy();
  1566. delete this._queue;
  1567. }
  1568. }
  1569. else {
  1570. // create queue and update its options
  1571. if (!this._queue) {
  1572. this._queue = Queue.extend(this, {
  1573. replace: ['add', 'update', 'remove']
  1574. });
  1575. }
  1576. if (typeof options.queue === 'object') {
  1577. this._queue.setOptions(options.queue);
  1578. }
  1579. }
  1580. }
  1581. };
  1582. /**
  1583. * Subscribe to an event, add an event listener
  1584. * @param {String} event Event name. Available events: 'put', 'update',
  1585. * 'remove'
  1586. * @param {function} callback Callback method. Called with three parameters:
  1587. * {String} event
  1588. * {Object | null} params
  1589. * {String | Number} senderId
  1590. */
  1591. DataSet.prototype.on = function(event, callback) {
  1592. var subscribers = this._subscribers[event];
  1593. if (!subscribers) {
  1594. subscribers = [];
  1595. this._subscribers[event] = subscribers;
  1596. }
  1597. subscribers.push({
  1598. callback: callback
  1599. });
  1600. };
  1601. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1602. DataSet.prototype.subscribe = DataSet.prototype.on;
  1603. /**
  1604. * Unsubscribe from an event, remove an event listener
  1605. * @param {String} event
  1606. * @param {function} callback
  1607. */
  1608. DataSet.prototype.off = function(event, callback) {
  1609. var subscribers = this._subscribers[event];
  1610. if (subscribers) {
  1611. this._subscribers[event] = subscribers.filter(function (listener) {
  1612. return (listener.callback != callback);
  1613. });
  1614. }
  1615. };
  1616. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1617. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1618. /**
  1619. * Trigger an event
  1620. * @param {String} event
  1621. * @param {Object | null} params
  1622. * @param {String} [senderId] Optional id of the sender.
  1623. * @private
  1624. */
  1625. DataSet.prototype._trigger = function (event, params, senderId) {
  1626. if (event == '*') {
  1627. throw new Error('Cannot trigger event *');
  1628. }
  1629. var subscribers = [];
  1630. if (event in this._subscribers) {
  1631. subscribers = subscribers.concat(this._subscribers[event]);
  1632. }
  1633. if ('*' in this._subscribers) {
  1634. subscribers = subscribers.concat(this._subscribers['*']);
  1635. }
  1636. for (var i = 0; i < subscribers.length; i++) {
  1637. var subscriber = subscribers[i];
  1638. if (subscriber.callback) {
  1639. subscriber.callback(event, params, senderId || null);
  1640. }
  1641. }
  1642. };
  1643. /**
  1644. * Add data.
  1645. * Adding an item will fail when there already is an item with the same id.
  1646. * @param {Object | Array | DataTable} data
  1647. * @param {String} [senderId] Optional sender id
  1648. * @return {Array} addedIds Array with the ids of the added items
  1649. */
  1650. DataSet.prototype.add = function (data, senderId) {
  1651. var addedIds = [],
  1652. id,
  1653. me = this;
  1654. if (Array.isArray(data)) {
  1655. // Array
  1656. for (var i = 0, len = data.length; i < len; i++) {
  1657. id = me._addItem(data[i]);
  1658. addedIds.push(id);
  1659. }
  1660. }
  1661. else if (util.isDataTable(data)) {
  1662. // Google DataTable
  1663. var columns = this._getColumnNames(data);
  1664. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1665. var item = {};
  1666. for (var col = 0, cols = columns.length; col < cols; col++) {
  1667. var field = columns[col];
  1668. item[field] = data.getValue(row, col);
  1669. }
  1670. id = me._addItem(item);
  1671. addedIds.push(id);
  1672. }
  1673. }
  1674. else if (data instanceof Object) {
  1675. // Single item
  1676. id = me._addItem(data);
  1677. addedIds.push(id);
  1678. }
  1679. else {
  1680. throw new Error('Unknown dataType');
  1681. }
  1682. if (addedIds.length) {
  1683. this._trigger('add', {items: addedIds}, senderId);
  1684. }
  1685. return addedIds;
  1686. };
  1687. /**
  1688. * Update existing items. When an item does not exist, it will be created
  1689. * @param {Object | Array | DataTable} data
  1690. * @param {String} [senderId] Optional sender id
  1691. * @return {Array} updatedIds The ids of the added or updated items
  1692. */
  1693. DataSet.prototype.update = function (data, senderId) {
  1694. var addedIds = [];
  1695. var updatedIds = [];
  1696. var updatedData = [];
  1697. var me = this;
  1698. var fieldId = me._fieldId;
  1699. var addOrUpdate = function (item) {
  1700. var id = item[fieldId];
  1701. if (me._data[id]) {
  1702. // update item
  1703. id = me._updateItem(item);
  1704. updatedIds.push(id);
  1705. updatedData.push(item);
  1706. }
  1707. else {
  1708. // add new item
  1709. id = me._addItem(item);
  1710. addedIds.push(id);
  1711. }
  1712. };
  1713. if (Array.isArray(data)) {
  1714. // Array
  1715. for (var i = 0, len = data.length; i < len; i++) {
  1716. addOrUpdate(data[i]);
  1717. }
  1718. }
  1719. else if (util.isDataTable(data)) {
  1720. // Google DataTable
  1721. var columns = this._getColumnNames(data);
  1722. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1723. var item = {};
  1724. for (var col = 0, cols = columns.length; col < cols; col++) {
  1725. var field = columns[col];
  1726. item[field] = data.getValue(row, col);
  1727. }
  1728. addOrUpdate(item);
  1729. }
  1730. }
  1731. else if (data instanceof Object) {
  1732. // Single item
  1733. addOrUpdate(data);
  1734. }
  1735. else {
  1736. throw new Error('Unknown dataType');
  1737. }
  1738. if (addedIds.length) {
  1739. this._trigger('add', {items: addedIds}, senderId);
  1740. }
  1741. if (updatedIds.length) {
  1742. this._trigger('update', {items: updatedIds, data: updatedData}, senderId);
  1743. }
  1744. return addedIds.concat(updatedIds);
  1745. };
  1746. /**
  1747. * Get a data item or multiple items.
  1748. *
  1749. * Usage:
  1750. *
  1751. * get()
  1752. * get(options: Object)
  1753. * get(options: Object, data: Array | DataTable)
  1754. *
  1755. * get(id: Number | String)
  1756. * get(id: Number | String, options: Object)
  1757. * get(id: Number | String, options: Object, data: Array | DataTable)
  1758. *
  1759. * get(ids: Number[] | String[])
  1760. * get(ids: Number[] | String[], options: Object)
  1761. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1762. *
  1763. * Where:
  1764. *
  1765. * {Number | String} id The id of an item
  1766. * {Number[] | String{}} ids An array with ids of items
  1767. * {Object} options An Object with options. Available options:
  1768. * {String} [returnType] Type of data to be
  1769. * returned. Can be 'DataTable' or 'Array' (default)
  1770. * {Object.<String, String>} [type]
  1771. * {String[]} [fields] field names to be returned
  1772. * {function} [filter] filter items
  1773. * {String | function} [order] Order the items by
  1774. * a field name or custom sort function.
  1775. * {Array | DataTable} [data] If provided, items will be appended to this
  1776. * array or table. Required in case of Google
  1777. * DataTable.
  1778. *
  1779. * @throws Error
  1780. */
  1781. DataSet.prototype.get = function (args) {
  1782. var me = this;
  1783. // parse the arguments
  1784. var id, ids, options, data;
  1785. var firstType = util.getType(arguments[0]);
  1786. if (firstType == 'String' || firstType == 'Number') {
  1787. // get(id [, options] [, data])
  1788. id = arguments[0];
  1789. options = arguments[1];
  1790. data = arguments[2];
  1791. }
  1792. else if (firstType == 'Array') {
  1793. // get(ids [, options] [, data])
  1794. ids = arguments[0];
  1795. options = arguments[1];
  1796. data = arguments[2];
  1797. }
  1798. else {
  1799. // get([, options] [, data])
  1800. options = arguments[0];
  1801. data = arguments[1];
  1802. }
  1803. // determine the return type
  1804. var returnType;
  1805. if (options && options.returnType) {
  1806. var allowedValues = ["DataTable", "Array", "Object"];
  1807. returnType = allowedValues.indexOf(options.returnType) == -1 ? "Array" : options.returnType;
  1808. if (data && (returnType != util.getType(data))) {
  1809. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1810. 'does not correspond with specified options.type (' + options.type + ')');
  1811. }
  1812. if (returnType == 'DataTable' && !util.isDataTable(data)) {
  1813. throw new Error('Parameter "data" must be a DataTable ' +
  1814. 'when options.type is "DataTable"');
  1815. }
  1816. }
  1817. else if (data) {
  1818. returnType = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1819. }
  1820. else {
  1821. returnType = 'Array';
  1822. }
  1823. // build options
  1824. var type = options && options.type || this._options.type;
  1825. var filter = options && options.filter;
  1826. var items = [], item, itemId, i, len;
  1827. // convert items
  1828. if (id != undefined) {
  1829. // return a single item
  1830. item = me._getItem(id, type);
  1831. if (filter && !filter(item)) {
  1832. item = null;
  1833. }
  1834. }
  1835. else if (ids != undefined) {
  1836. // return a subset of items
  1837. for (i = 0, len = ids.length; i < len; i++) {
  1838. item = me._getItem(ids[i], type);
  1839. if (!filter || filter(item)) {
  1840. items.push(item);
  1841. }
  1842. }
  1843. }
  1844. else {
  1845. // return all items
  1846. for (itemId in this._data) {
  1847. if (this._data.hasOwnProperty(itemId)) {
  1848. item = me._getItem(itemId, type);
  1849. if (!filter || filter(item)) {
  1850. items.push(item);
  1851. }
  1852. }
  1853. }
  1854. }
  1855. // order the results
  1856. if (options && options.order && id == undefined) {
  1857. this._sort(items, options.order);
  1858. }
  1859. // filter fields of the items
  1860. if (options && options.fields) {
  1861. var fields = options.fields;
  1862. if (id != undefined) {
  1863. item = this._filterFields(item, fields);
  1864. }
  1865. else {
  1866. for (i = 0, len = items.length; i < len; i++) {
  1867. items[i] = this._filterFields(items[i], fields);
  1868. }
  1869. }
  1870. }
  1871. // return the results
  1872. if (returnType == 'DataTable') {
  1873. var columns = this._getColumnNames(data);
  1874. if (id != undefined) {
  1875. // append a single item to the data table
  1876. me._appendRow(data, columns, item);
  1877. }
  1878. else {
  1879. // copy the items to the provided data table
  1880. for (i = 0; i < items.length; i++) {
  1881. me._appendRow(data, columns, items[i]);
  1882. }
  1883. }
  1884. return data;
  1885. }
  1886. else if (returnType == "Object") {
  1887. var result = {};
  1888. for (i = 0; i < items.length; i++) {
  1889. result[items[i].id] = items[i];
  1890. }
  1891. return result;
  1892. }
  1893. else {
  1894. // return an array
  1895. if (id != undefined) {
  1896. // a single item
  1897. return item;
  1898. }
  1899. else {
  1900. // multiple items
  1901. if (data) {
  1902. // copy the items to the provided array
  1903. for (i = 0, len = items.length; i < len; i++) {
  1904. data.push(items[i]);
  1905. }
  1906. return data;
  1907. }
  1908. else {
  1909. // just return our array
  1910. return items;
  1911. }
  1912. }
  1913. }
  1914. };
  1915. /**
  1916. * Get ids of all items or from a filtered set of items.
  1917. * @param {Object} [options] An Object with options. Available options:
  1918. * {function} [filter] filter items
  1919. * {String | function} [order] Order the items by
  1920. * a field name or custom sort function.
  1921. * @return {Array} ids
  1922. */
  1923. DataSet.prototype.getIds = function (options) {
  1924. var data = this._data,
  1925. filter = options && options.filter,
  1926. order = options && options.order,
  1927. type = options && options.type || this._options.type,
  1928. i,
  1929. len,
  1930. id,
  1931. item,
  1932. items,
  1933. ids = [];
  1934. if (filter) {
  1935. // get filtered items
  1936. if (order) {
  1937. // create ordered list
  1938. items = [];
  1939. for (id in data) {
  1940. if (data.hasOwnProperty(id)) {
  1941. item = this._getItem(id, type);
  1942. if (filter(item)) {
  1943. items.push(item);
  1944. }
  1945. }
  1946. }
  1947. this._sort(items, order);
  1948. for (i = 0, len = items.length; i < len; i++) {
  1949. ids[i] = items[i][this._fieldId];
  1950. }
  1951. }
  1952. else {
  1953. // create unordered list
  1954. for (id in data) {
  1955. if (data.hasOwnProperty(id)) {
  1956. item = this._getItem(id, type);
  1957. if (filter(item)) {
  1958. ids.push(item[this._fieldId]);
  1959. }
  1960. }
  1961. }
  1962. }
  1963. }
  1964. else {
  1965. // get all items
  1966. if (order) {
  1967. // create an ordered list
  1968. items = [];
  1969. for (id in data) {
  1970. if (data.hasOwnProperty(id)) {
  1971. items.push(data[id]);
  1972. }
  1973. }
  1974. this._sort(items, order);
  1975. for (i = 0, len = items.length; i < len; i++) {
  1976. ids[i] = items[i][this._fieldId];
  1977. }
  1978. }
  1979. else {
  1980. // create unordered list
  1981. for (id in data) {
  1982. if (data.hasOwnProperty(id)) {
  1983. item = data[id];
  1984. ids.push(item[this._fieldId]);
  1985. }
  1986. }
  1987. }
  1988. }
  1989. return ids;
  1990. };
  1991. /**
  1992. * Returns the DataSet itself. Is overwritten for example by the DataView,
  1993. * which returns the DataSet it is connected to instead.
  1994. */
  1995. DataSet.prototype.getDataSet = function () {
  1996. return this;
  1997. };
  1998. /**
  1999. * Execute a callback function for every item in the dataset.
  2000. * @param {function} callback
  2001. * @param {Object} [options] Available options:
  2002. * {Object.<String, String>} [type]
  2003. * {String[]} [fields] filter fields
  2004. * {function} [filter] filter items
  2005. * {String | function} [order] Order the items by
  2006. * a field name or custom sort function.
  2007. */
  2008. DataSet.prototype.forEach = function (callback, options) {
  2009. var filter = options && options.filter,
  2010. type = options && options.type || this._options.type,
  2011. data = this._data,
  2012. item,
  2013. id;
  2014. if (options && options.order) {
  2015. // execute forEach on ordered list
  2016. var items = this.get(options);
  2017. for (var i = 0, len = items.length; i < len; i++) {
  2018. item = items[i];
  2019. id = item[this._fieldId];
  2020. callback(item, id);
  2021. }
  2022. }
  2023. else {
  2024. // unordered
  2025. for (id in data) {
  2026. if (data.hasOwnProperty(id)) {
  2027. item = this._getItem(id, type);
  2028. if (!filter || filter(item)) {
  2029. callback(item, id);
  2030. }
  2031. }
  2032. }
  2033. }
  2034. };
  2035. /**
  2036. * Map every item in the dataset.
  2037. * @param {function} callback
  2038. * @param {Object} [options] Available options:
  2039. * {Object.<String, String>} [type]
  2040. * {String[]} [fields] filter fields
  2041. * {function} [filter] filter items
  2042. * {String | function} [order] Order the items by
  2043. * a field name or custom sort function.
  2044. * @return {Object[]} mappedItems
  2045. */
  2046. DataSet.prototype.map = function (callback, options) {
  2047. var filter = options && options.filter,
  2048. type = options && options.type || this._options.type,
  2049. mappedItems = [],
  2050. data = this._data,
  2051. item;
  2052. // convert and filter items
  2053. for (var id in data) {
  2054. if (data.hasOwnProperty(id)) {
  2055. item = this._getItem(id, type);
  2056. if (!filter || filter(item)) {
  2057. mappedItems.push(callback(item, id));
  2058. }
  2059. }
  2060. }
  2061. // order items
  2062. if (options && options.order) {
  2063. this._sort(mappedItems, options.order);
  2064. }
  2065. return mappedItems;
  2066. };
  2067. /**
  2068. * Filter the fields of an item
  2069. * @param {Object} item
  2070. * @param {String[]} fields Field names
  2071. * @return {Object} filteredItem
  2072. * @private
  2073. */
  2074. DataSet.prototype._filterFields = function (item, fields) {
  2075. var filteredItem = {};
  2076. for (var field in item) {
  2077. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  2078. filteredItem[field] = item[field];
  2079. }
  2080. }
  2081. return filteredItem;
  2082. };
  2083. /**
  2084. * Sort the provided array with items
  2085. * @param {Object[]} items
  2086. * @param {String | function} order A field name or custom sort function.
  2087. * @private
  2088. */
  2089. DataSet.prototype._sort = function (items, order) {
  2090. if (util.isString(order)) {
  2091. // order by provided field name
  2092. var name = order; // field name
  2093. items.sort(function (a, b) {
  2094. var av = a[name];
  2095. var bv = b[name];
  2096. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  2097. });
  2098. }
  2099. else if (typeof order === 'function') {
  2100. // order by sort function
  2101. items.sort(order);
  2102. }
  2103. // TODO: extend order by an Object {field:String, direction:String}
  2104. // where direction can be 'asc' or 'desc'
  2105. else {
  2106. throw new TypeError('Order must be a function or a string');
  2107. }
  2108. };
  2109. /**
  2110. * Remove an object by pointer or by id
  2111. * @param {String | Number | Object | Array} id Object or id, or an array with
  2112. * objects or ids to be removed
  2113. * @param {String} [senderId] Optional sender id
  2114. * @return {Array} removedIds
  2115. */
  2116. DataSet.prototype.remove = function (id, senderId) {
  2117. var removedIds = [],
  2118. i, len, removedId;
  2119. if (Array.isArray(id)) {
  2120. for (i = 0, len = id.length; i < len; i++) {
  2121. removedId = this._remove(id[i]);
  2122. if (removedId != null) {
  2123. removedIds.push(removedId);
  2124. }
  2125. }
  2126. }
  2127. else {
  2128. removedId = this._remove(id);
  2129. if (removedId != null) {
  2130. removedIds.push(removedId);
  2131. }
  2132. }
  2133. if (removedIds.length) {
  2134. this._trigger('remove', {items: removedIds}, senderId);
  2135. }
  2136. return removedIds;
  2137. };
  2138. /**
  2139. * Remove an item by its id
  2140. * @param {Number | String | Object} id id or item
  2141. * @returns {Number | String | null} id
  2142. * @private
  2143. */
  2144. DataSet.prototype._remove = function (id) {
  2145. if (util.isNumber(id) || util.isString(id)) {
  2146. if (this._data[id]) {
  2147. delete this._data[id];
  2148. return id;
  2149. }
  2150. }
  2151. else if (id instanceof Object) {
  2152. var itemId = id[this._fieldId];
  2153. if (itemId && this._data[itemId]) {
  2154. delete this._data[itemId];
  2155. return itemId;
  2156. }
  2157. }
  2158. return null;
  2159. };
  2160. /**
  2161. * Clear the data
  2162. * @param {String} [senderId] Optional sender id
  2163. * @return {Array} removedIds The ids of all removed items
  2164. */
  2165. DataSet.prototype.clear = function (senderId) {
  2166. var ids = Object.keys(this._data);
  2167. this._data = {};
  2168. this._trigger('remove', {items: ids}, senderId);
  2169. return ids;
  2170. };
  2171. /**
  2172. * Find the item with maximum value of a specified field
  2173. * @param {String} field
  2174. * @return {Object | null} item Item containing max value, or null if no items
  2175. */
  2176. DataSet.prototype.max = function (field) {
  2177. var data = this._data,
  2178. max = null,
  2179. maxField = null;
  2180. for (var id in data) {
  2181. if (data.hasOwnProperty(id)) {
  2182. var item = data[id];
  2183. var itemField = item[field];
  2184. if (itemField != null && (!max || itemField > maxField)) {
  2185. max = item;
  2186. maxField = itemField;
  2187. }
  2188. }
  2189. }
  2190. return max;
  2191. };
  2192. /**
  2193. * Find the item with minimum value of a specified field
  2194. * @param {String} field
  2195. * @return {Object | null} item Item containing max value, or null if no items
  2196. */
  2197. DataSet.prototype.min = function (field) {
  2198. var data = this._data,
  2199. min = null,
  2200. minField = null;
  2201. for (var id in data) {
  2202. if (data.hasOwnProperty(id)) {
  2203. var item = data[id];
  2204. var itemField = item[field];
  2205. if (itemField != null && (!min || itemField < minField)) {
  2206. min = item;
  2207. minField = itemField;
  2208. }
  2209. }
  2210. }
  2211. return min;
  2212. };
  2213. /**
  2214. * Find all distinct values of a specified field
  2215. * @param {String} field
  2216. * @return {Array} values Array containing all distinct values. If data items
  2217. * do not contain the specified field are ignored.
  2218. * The returned array is unordered.
  2219. */
  2220. DataSet.prototype.distinct = function (field) {
  2221. var data = this._data;
  2222. var values = [];
  2223. var fieldType = this._options.type && this._options.type[field] || null;
  2224. var count = 0;
  2225. var i;
  2226. for (var prop in data) {
  2227. if (data.hasOwnProperty(prop)) {
  2228. var item = data[prop];
  2229. var value = item[field];
  2230. var exists = false;
  2231. for (i = 0; i < count; i++) {
  2232. if (values[i] == value) {
  2233. exists = true;
  2234. break;
  2235. }
  2236. }
  2237. if (!exists && (value !== undefined)) {
  2238. values[count] = value;
  2239. count++;
  2240. }
  2241. }
  2242. }
  2243. if (fieldType) {
  2244. for (i = 0; i < values.length; i++) {
  2245. values[i] = util.convert(values[i], fieldType);
  2246. }
  2247. }
  2248. return values;
  2249. };
  2250. /**
  2251. * Add a single item. Will fail when an item with the same id already exists.
  2252. * @param {Object} item
  2253. * @return {String} id
  2254. * @private
  2255. */
  2256. DataSet.prototype._addItem = function (item) {
  2257. var id = item[this._fieldId];
  2258. if (id != undefined) {
  2259. // check whether this id is already taken
  2260. if (this._data[id]) {
  2261. // item already exists
  2262. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  2263. }
  2264. }
  2265. else {
  2266. // generate an id
  2267. id = util.randomUUID();
  2268. item[this._fieldId] = id;
  2269. }
  2270. var d = {};
  2271. for (var field in item) {
  2272. if (item.hasOwnProperty(field)) {
  2273. var fieldType = this._type[field]; // type may be undefined
  2274. d[field] = util.convert(item[field], fieldType);
  2275. }
  2276. }
  2277. this._data[id] = d;
  2278. return id;
  2279. };
  2280. /**
  2281. * Get an item. Fields can be converted to a specific type
  2282. * @param {String} id
  2283. * @param {Object.<String, String>} [types] field types to convert
  2284. * @return {Object | null} item
  2285. * @private
  2286. */
  2287. DataSet.prototype._getItem = function (id, types) {
  2288. var field, value;
  2289. // get the item from the dataset
  2290. var raw = this._data[id];
  2291. if (!raw) {
  2292. return null;
  2293. }
  2294. // convert the items field types
  2295. var converted = {};
  2296. if (types) {
  2297. for (field in raw) {
  2298. if (raw.hasOwnProperty(field)) {
  2299. value = raw[field];
  2300. converted[field] = util.convert(value, types[field]);
  2301. }
  2302. }
  2303. }
  2304. else {
  2305. // no field types specified, no converting needed
  2306. for (field in raw) {
  2307. if (raw.hasOwnProperty(field)) {
  2308. value = raw[field];
  2309. converted[field] = value;
  2310. }
  2311. }
  2312. }
  2313. return converted;
  2314. };
  2315. /**
  2316. * Update a single item: merge with existing item.
  2317. * Will fail when the item has no id, or when there does not exist an item
  2318. * with the same id.
  2319. * @param {Object} item
  2320. * @return {String} id
  2321. * @private
  2322. */
  2323. DataSet.prototype._updateItem = function (item) {
  2324. var id = item[this._fieldId];
  2325. if (id == undefined) {
  2326. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  2327. }
  2328. var d = this._data[id];
  2329. if (!d) {
  2330. // item doesn't exist
  2331. throw new Error('Cannot update item: no item with id ' + id + ' found');
  2332. }
  2333. // merge with current item
  2334. for (var field in item) {
  2335. if (item.hasOwnProperty(field)) {
  2336. var fieldType = this._type[field]; // type may be undefined
  2337. d[field] = util.convert(item[field], fieldType);
  2338. }
  2339. }
  2340. return id;
  2341. };
  2342. /**
  2343. * Get an array with the column names of a Google DataTable
  2344. * @param {DataTable} dataTable
  2345. * @return {String[]} columnNames
  2346. * @private
  2347. */
  2348. DataSet.prototype._getColumnNames = function (dataTable) {
  2349. var columns = [];
  2350. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  2351. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  2352. }
  2353. return columns;
  2354. };
  2355. /**
  2356. * Append an item as a row to the dataTable
  2357. * @param dataTable
  2358. * @param columns
  2359. * @param item
  2360. * @private
  2361. */
  2362. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  2363. var row = dataTable.addRow();
  2364. for (var col = 0, cols = columns.length; col < cols; col++) {
  2365. var field = columns[col];
  2366. dataTable.setValue(row, col, item[field]);
  2367. }
  2368. };
  2369. module.exports = DataSet;
  2370. /***/ },
  2371. /* 4 */
  2372. /***/ function(module, exports, __webpack_require__) {
  2373. var util = __webpack_require__(1);
  2374. var DataSet = __webpack_require__(3);
  2375. /**
  2376. * DataView
  2377. *
  2378. * a dataview offers a filtered view on a dataset or an other dataview.
  2379. *
  2380. * @param {DataSet | DataView} data
  2381. * @param {Object} [options] Available options: see method get
  2382. *
  2383. * @constructor DataView
  2384. */
  2385. function DataView (data, options) {
  2386. this._data = null;
  2387. this._ids = {}; // ids of the items currently in memory (just contains a boolean true)
  2388. this._options = options || {};
  2389. this._fieldId = 'id'; // name of the field containing id
  2390. this._subscribers = {}; // event subscribers
  2391. var me = this;
  2392. this.listener = function () {
  2393. me._onEvent.apply(me, arguments);
  2394. };
  2395. this.setData(data);
  2396. }
  2397. // TODO: implement a function .config() to dynamically update things like configured filter
  2398. // and trigger changes accordingly
  2399. /**
  2400. * Set a data source for the view
  2401. * @param {DataSet | DataView} data
  2402. */
  2403. DataView.prototype.setData = function (data) {
  2404. var ids, i, len;
  2405. if (this._data) {
  2406. // unsubscribe from current dataset
  2407. if (this._data.unsubscribe) {
  2408. this._data.unsubscribe('*', this.listener);
  2409. }
  2410. // trigger a remove of all items in memory
  2411. ids = [];
  2412. for (var id in this._ids) {
  2413. if (this._ids.hasOwnProperty(id)) {
  2414. ids.push(id);
  2415. }
  2416. }
  2417. this._ids = {};
  2418. this._trigger('remove', {items: ids});
  2419. }
  2420. this._data = data;
  2421. if (this._data) {
  2422. // update fieldId
  2423. this._fieldId = this._options.fieldId ||
  2424. (this._data && this._data.options && this._data.options.fieldId) ||
  2425. 'id';
  2426. // trigger an add of all added items
  2427. ids = this._data.getIds({filter: this._options && this._options.filter});
  2428. for (i = 0, len = ids.length; i < len; i++) {
  2429. id = ids[i];
  2430. this._ids[id] = true;
  2431. }
  2432. this._trigger('add', {items: ids});
  2433. // subscribe to new dataset
  2434. if (this._data.on) {
  2435. this._data.on('*', this.listener);
  2436. }
  2437. }
  2438. };
  2439. /**
  2440. * Get data from the data view
  2441. *
  2442. * Usage:
  2443. *
  2444. * get()
  2445. * get(options: Object)
  2446. * get(options: Object, data: Array | DataTable)
  2447. *
  2448. * get(id: Number)
  2449. * get(id: Number, options: Object)
  2450. * get(id: Number, options: Object, data: Array | DataTable)
  2451. *
  2452. * get(ids: Number[])
  2453. * get(ids: Number[], options: Object)
  2454. * get(ids: Number[], options: Object, data: Array | DataTable)
  2455. *
  2456. * Where:
  2457. *
  2458. * {Number | String} id The id of an item
  2459. * {Number[] | String{}} ids An array with ids of items
  2460. * {Object} options An Object with options. Available options:
  2461. * {String} [type] Type of data to be returned. Can
  2462. * be 'DataTable' or 'Array' (default)
  2463. * {Object.<String, String>} [convert]
  2464. * {String[]} [fields] field names to be returned
  2465. * {function} [filter] filter items
  2466. * {String | function} [order] Order the items by
  2467. * a field name or custom sort function.
  2468. * {Array | DataTable} [data] If provided, items will be appended to this
  2469. * array or table. Required in case of Google
  2470. * DataTable.
  2471. * @param args
  2472. */
  2473. DataView.prototype.get = function (args) {
  2474. var me = this;
  2475. // parse the arguments
  2476. var ids, options, data;
  2477. var firstType = util.getType(arguments[0]);
  2478. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2479. // get(id(s) [, options] [, data])
  2480. ids = arguments[0]; // can be a single id or an array with ids
  2481. options = arguments[1];
  2482. data = arguments[2];
  2483. }
  2484. else {
  2485. // get([, options] [, data])
  2486. options = arguments[0];
  2487. data = arguments[1];
  2488. }
  2489. // extend the options with the default options and provided options
  2490. var viewOptions = util.extend({}, this._options, options);
  2491. // create a combined filter method when needed
  2492. if (this._options.filter && options && options.filter) {
  2493. viewOptions.filter = function (item) {
  2494. return me._options.filter(item) && options.filter(item);
  2495. }
  2496. }
  2497. // build up the call to the linked data set
  2498. var getArguments = [];
  2499. if (ids != undefined) {
  2500. getArguments.push(ids);
  2501. }
  2502. getArguments.push(viewOptions);
  2503. getArguments.push(data);
  2504. return this._data && this._data.get.apply(this._data, getArguments);
  2505. };
  2506. /**
  2507. * Get ids of all items or from a filtered set of items.
  2508. * @param {Object} [options] An Object with options. Available options:
  2509. * {function} [filter] filter items
  2510. * {String | function} [order] Order the items by
  2511. * a field name or custom sort function.
  2512. * @return {Array} ids
  2513. */
  2514. DataView.prototype.getIds = function (options) {
  2515. var ids;
  2516. if (this._data) {
  2517. var defaultFilter = this._options.filter;
  2518. var filter;
  2519. if (options && options.filter) {
  2520. if (defaultFilter) {
  2521. filter = function (item) {
  2522. return defaultFilter(item) && options.filter(item);
  2523. }
  2524. }
  2525. else {
  2526. filter = options.filter;
  2527. }
  2528. }
  2529. else {
  2530. filter = defaultFilter;
  2531. }
  2532. ids = this._data.getIds({
  2533. filter: filter,
  2534. order: options && options.order
  2535. });
  2536. }
  2537. else {
  2538. ids = [];
  2539. }
  2540. return ids;
  2541. };
  2542. /**
  2543. * Get the DataSet to which this DataView is connected. In case there is a chain
  2544. * of multiple DataViews, the root DataSet of this chain is returned.
  2545. * @return {DataSet} dataSet
  2546. */
  2547. DataView.prototype.getDataSet = function () {
  2548. var dataSet = this;
  2549. while (dataSet instanceof DataView) {
  2550. dataSet = dataSet._data;
  2551. }
  2552. return dataSet || null;
  2553. };
  2554. /**
  2555. * Event listener. Will propagate all events from the connected data set to
  2556. * the subscribers of the DataView, but will filter the items and only trigger
  2557. * when there are changes in the filtered data set.
  2558. * @param {String} event
  2559. * @param {Object | null} params
  2560. * @param {String} senderId
  2561. * @private
  2562. */
  2563. DataView.prototype._onEvent = function (event, params, senderId) {
  2564. var i, len, id, item,
  2565. ids = params && params.items,
  2566. data = this._data,
  2567. added = [],
  2568. updated = [],
  2569. removed = [];
  2570. if (ids && data) {
  2571. switch (event) {
  2572. case 'add':
  2573. // filter the ids of the added items
  2574. for (i = 0, len = ids.length; i < len; i++) {
  2575. id = ids[i];
  2576. item = this.get(id);
  2577. if (item) {
  2578. this._ids[id] = true;
  2579. added.push(id);
  2580. }
  2581. }
  2582. break;
  2583. case 'update':
  2584. // determine the event from the views viewpoint: an updated
  2585. // item can be added, updated, or removed from this view.
  2586. for (i = 0, len = ids.length; i < len; i++) {
  2587. id = ids[i];
  2588. item = this.get(id);
  2589. if (item) {
  2590. if (this._ids[id]) {
  2591. updated.push(id);
  2592. }
  2593. else {
  2594. this._ids[id] = true;
  2595. added.push(id);
  2596. }
  2597. }
  2598. else {
  2599. if (this._ids[id]) {
  2600. delete this._ids[id];
  2601. removed.push(id);
  2602. }
  2603. else {
  2604. // nothing interesting for me :-(
  2605. }
  2606. }
  2607. }
  2608. break;
  2609. case 'remove':
  2610. // filter the ids of the removed items
  2611. for (i = 0, len = ids.length; i < len; i++) {
  2612. id = ids[i];
  2613. if (this._ids[id]) {
  2614. delete this._ids[id];
  2615. removed.push(id);
  2616. }
  2617. }
  2618. break;
  2619. }
  2620. if (added.length) {
  2621. this._trigger('add', {items: added}, senderId);
  2622. }
  2623. if (updated.length) {
  2624. this._trigger('update', {items: updated}, senderId);
  2625. }
  2626. if (removed.length) {
  2627. this._trigger('remove', {items: removed}, senderId);
  2628. }
  2629. }
  2630. };
  2631. // copy subscription functionality from DataSet
  2632. DataView.prototype.on = DataSet.prototype.on;
  2633. DataView.prototype.off = DataSet.prototype.off;
  2634. DataView.prototype._trigger = DataSet.prototype._trigger;
  2635. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2636. DataView.prototype.subscribe = DataView.prototype.on;
  2637. DataView.prototype.unsubscribe = DataView.prototype.off;
  2638. module.exports = DataView;
  2639. /***/ },
  2640. /* 5 */
  2641. /***/ function(module, exports, __webpack_require__) {
  2642. /**
  2643. * A queue
  2644. * @param {Object} options
  2645. * Available options:
  2646. * - delay: number When provided, the queue will be flushed
  2647. * automatically after an inactivity of this delay
  2648. * in milliseconds.
  2649. * Default value is null.
  2650. * - max: number When the queue exceeds the given maximum number
  2651. * of entries, the queue is flushed automatically.
  2652. * Default value of max is Infinity.
  2653. * @constructor
  2654. */
  2655. function Queue(options) {
  2656. // options
  2657. this.delay = null;
  2658. this.max = Infinity;
  2659. // properties
  2660. this._queue = [];
  2661. this._timeout = null;
  2662. this._extended = null;
  2663. this.setOptions(options);
  2664. }
  2665. /**
  2666. * Update the configuration of the queue
  2667. * @param {Object} options
  2668. * Available options:
  2669. * - delay: number When provided, the queue will be flushed
  2670. * automatically after an inactivity of this delay
  2671. * in milliseconds.
  2672. * Default value is null.
  2673. * - max: number When the queue exceeds the given maximum number
  2674. * of entries, the queue is flushed automatically.
  2675. * Default value of max is Infinity.
  2676. * @param options
  2677. */
  2678. Queue.prototype.setOptions = function (options) {
  2679. if (options && typeof options.delay !== 'undefined') {
  2680. this.delay = options.delay;
  2681. }
  2682. if (options && typeof options.max !== 'undefined') {
  2683. this.max = options.max;
  2684. }
  2685. this._flushIfNeeded();
  2686. };
  2687. /**
  2688. * Extend an object with queuing functionality.
  2689. * The object will be extended with a function flush, and the methods provided
  2690. * in options.replace will be replaced with queued ones.
  2691. * @param {Object} object
  2692. * @param {Object} options
  2693. * Available options:
  2694. * - replace: Array.<string>
  2695. * A list with method names of the methods
  2696. * on the object to be replaced with queued ones.
  2697. * - delay: number When provided, the queue will be flushed
  2698. * automatically after an inactivity of this delay
  2699. * in milliseconds.
  2700. * Default value is null.
  2701. * - max: number When the queue exceeds the given maximum number
  2702. * of entries, the queue is flushed automatically.
  2703. * Default value of max is Infinity.
  2704. * @return {Queue} Returns the created queue
  2705. */
  2706. Queue.extend = function (object, options) {
  2707. var queue = new Queue(options);
  2708. if (object.flush !== undefined) {
  2709. throw new Error('Target object already has a property flush');
  2710. }
  2711. object.flush = function () {
  2712. queue.flush();
  2713. };
  2714. var methods = [{
  2715. name: 'flush',
  2716. original: undefined
  2717. }];
  2718. if (options && options.replace) {
  2719. for (var i = 0; i < options.replace.length; i++) {
  2720. var name = options.replace[i];
  2721. methods.push({
  2722. name: name,
  2723. original: object[name]
  2724. });
  2725. queue.replace(object, name);
  2726. }
  2727. }
  2728. queue._extended = {
  2729. object: object,
  2730. methods: methods
  2731. };
  2732. return queue;
  2733. };
  2734. /**
  2735. * Destroy the queue. The queue will first flush all queued actions, and in
  2736. * case it has extended an object, will restore the original object.
  2737. */
  2738. Queue.prototype.destroy = function () {
  2739. this.flush();
  2740. if (this._extended) {
  2741. var object = this._extended.object;
  2742. var methods = this._extended.methods;
  2743. for (var i = 0; i < methods.length; i++) {
  2744. var method = methods[i];
  2745. if (method.original) {
  2746. object[method.name] = method.original;
  2747. }
  2748. else {
  2749. delete object[method.name];
  2750. }
  2751. }
  2752. this._extended = null;
  2753. }
  2754. };
  2755. /**
  2756. * Replace a method on an object with a queued version
  2757. * @param {Object} object Object having the method
  2758. * @param {string} method The method name
  2759. */
  2760. Queue.prototype.replace = function(object, method) {
  2761. var me = this;
  2762. var original = object[method];
  2763. if (!original) {
  2764. throw new Error('Method ' + method + ' undefined');
  2765. }
  2766. object[method] = function () {
  2767. // create an Array with the arguments
  2768. var args = [];
  2769. for (var i = 0; i < arguments.length; i++) {
  2770. args[i] = arguments[i];
  2771. }
  2772. // add this call to the queue
  2773. me.queue({
  2774. args: args,
  2775. fn: original,
  2776. context: this
  2777. });
  2778. };
  2779. };
  2780. /**
  2781. * Queue a call
  2782. * @param {function | {fn: function, args: Array} | {fn: function, args: Array, context: Object}} entry
  2783. */
  2784. Queue.prototype.queue = function(entry) {
  2785. if (typeof entry === 'function') {
  2786. this._queue.push({fn: entry});
  2787. }
  2788. else {
  2789. this._queue.push(entry);
  2790. }
  2791. this._flushIfNeeded();
  2792. };
  2793. /**
  2794. * Check whether the queue needs to be flushed
  2795. * @private
  2796. */
  2797. Queue.prototype._flushIfNeeded = function () {
  2798. // flush when the maximum is exceeded.
  2799. if (this._queue.length > this.max) {
  2800. this.flush();
  2801. }
  2802. // flush after a period of inactivity when a delay is configured
  2803. clearTimeout(this._timeout);
  2804. if (this.queue.length > 0 && typeof this.delay === 'number') {
  2805. var me = this;
  2806. this._timeout = setTimeout(function () {
  2807. me.flush();
  2808. }, this.delay);
  2809. }
  2810. };
  2811. /**
  2812. * Flush all queued calls
  2813. */
  2814. Queue.prototype.flush = function () {
  2815. while (this._queue.length > 0) {
  2816. var entry = this._queue.shift();
  2817. entry.fn.apply(entry.context || entry.fn, entry.args || []);
  2818. }
  2819. };
  2820. module.exports = Queue;
  2821. /***/ },
  2822. /* 6 */
  2823. /***/ function(module, exports, __webpack_require__) {
  2824. var Emitter = __webpack_require__(56);
  2825. var DataSet = __webpack_require__(3);
  2826. var DataView = __webpack_require__(4);
  2827. var util = __webpack_require__(1);
  2828. var Point3d = __webpack_require__(10);
  2829. var Point2d = __webpack_require__(9);
  2830. var Camera = __webpack_require__(7);
  2831. var Filter = __webpack_require__(8);
  2832. var Slider = __webpack_require__(11);
  2833. var StepNumber = __webpack_require__(12);
  2834. /**
  2835. * @constructor Graph3d
  2836. * Graph3d displays data in 3d.
  2837. *
  2838. * Graph3d is developed in javascript as a Google Visualization Chart.
  2839. *
  2840. * @param {Element} container The DOM element in which the Graph3d will
  2841. * be created. Normally a div element.
  2842. * @param {DataSet | DataView | Array} [data]
  2843. * @param {Object} [options]
  2844. */
  2845. function Graph3d(container, data, options) {
  2846. if (!(this instanceof Graph3d)) {
  2847. throw new SyntaxError('Constructor must be called with the new operator');
  2848. }
  2849. // create variables and set default values
  2850. this.containerElement = container;
  2851. this.width = '400px';
  2852. this.height = '400px';
  2853. this.margin = 10; // px
  2854. this.defaultXCenter = '55%';
  2855. this.defaultYCenter = '50%';
  2856. this.xLabel = 'x';
  2857. this.yLabel = 'y';
  2858. this.zLabel = 'z';
  2859. var passValueFn = function(v) { return v; };
  2860. this.xValueLabel = passValueFn;
  2861. this.yValueLabel = passValueFn;
  2862. this.zValueLabel = passValueFn;
  2863. this.filterLabel = 'time';
  2864. this.legendLabel = 'value';
  2865. this.style = Graph3d.STYLE.DOT;
  2866. this.showPerspective = true;
  2867. this.showGrid = true;
  2868. this.keepAspectRatio = true;
  2869. this.showShadow = false;
  2870. this.showGrayBottom = false; // TODO: this does not work correctly
  2871. this.showTooltip = false;
  2872. this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube'
  2873. this.animationInterval = 1000; // milliseconds
  2874. this.animationPreload = false;
  2875. this.camera = new Camera();
  2876. this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window?
  2877. this.dataTable = null; // The original data table
  2878. this.dataPoints = null; // The table with point objects
  2879. // the column indexes
  2880. this.colX = undefined;
  2881. this.colY = undefined;
  2882. this.colZ = undefined;
  2883. this.colValue = undefined;
  2884. this.colFilter = undefined;
  2885. this.xMin = 0;
  2886. this.xStep = undefined; // auto by default
  2887. this.xMax = 1;
  2888. this.yMin = 0;
  2889. this.yStep = undefined; // auto by default
  2890. this.yMax = 1;
  2891. this.zMin = 0;
  2892. this.zStep = undefined; // auto by default
  2893. this.zMax = 1;
  2894. this.valueMin = 0;
  2895. this.valueMax = 1;
  2896. this.xBarWidth = 1;
  2897. this.yBarWidth = 1;
  2898. // TODO: customize axis range
  2899. // constants
  2900. this.colorAxis = '#4D4D4D';
  2901. this.colorGrid = '#D3D3D3';
  2902. this.colorDot = '#7DC1FF';
  2903. this.colorDotBorder = '#3267D2';
  2904. // create a frame and canvas
  2905. this.create();
  2906. // apply options (also when undefined)
  2907. this.setOptions(options);
  2908. // apply data
  2909. if (data) {
  2910. this.setData(data);
  2911. }
  2912. }
  2913. // Extend Graph3d with an Emitter mixin
  2914. Emitter(Graph3d.prototype);
  2915. /**
  2916. * Calculate the scaling values, dependent on the range in x, y, and z direction
  2917. */
  2918. Graph3d.prototype._setScale = function() {
  2919. this.scale = new Point3d(1 / (this.xMax - this.xMin),
  2920. 1 / (this.yMax - this.yMin),
  2921. 1 / (this.zMax - this.zMin));
  2922. // keep aspect ration between x and y scale if desired
  2923. if (this.keepAspectRatio) {
  2924. if (this.scale.x < this.scale.y) {
  2925. //noinspection JSSuspiciousNameCombination
  2926. this.scale.y = this.scale.x;
  2927. }
  2928. else {
  2929. //noinspection JSSuspiciousNameCombination
  2930. this.scale.x = this.scale.y;
  2931. }
  2932. }
  2933. // scale the vertical axis
  2934. this.scale.z *= this.verticalRatio;
  2935. // TODO: can this be automated? verticalRatio?
  2936. // determine scale for (optional) value
  2937. this.scale.value = 1 / (this.valueMax - this.valueMin);
  2938. // position the camera arm
  2939. var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x;
  2940. var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y;
  2941. var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z;
  2942. this.camera.setArmLocation(xCenter, yCenter, zCenter);
  2943. };
  2944. /**
  2945. * Convert a 3D location to a 2D location on screen
  2946. * http://en.wikipedia.org/wiki/3D_projection
  2947. * @param {Point3d} point3d A 3D point with parameters x, y, z
  2948. * @return {Point2d} point2d A 2D point with parameters x, y
  2949. */
  2950. Graph3d.prototype._convert3Dto2D = function(point3d) {
  2951. var translation = this._convertPointToTranslation(point3d);
  2952. return this._convertTranslationToScreen(translation);
  2953. };
  2954. /**
  2955. * Convert a 3D location its translation seen from the camera
  2956. * http://en.wikipedia.org/wiki/3D_projection
  2957. * @param {Point3d} point3d A 3D point with parameters x, y, z
  2958. * @return {Point3d} translation A 3D point with parameters x, y, z This is
  2959. * the translation of the point, seen from the
  2960. * camera
  2961. */
  2962. Graph3d.prototype._convertPointToTranslation = function(point3d) {
  2963. var ax = point3d.x * this.scale.x,
  2964. ay = point3d.y * this.scale.y,
  2965. az = point3d.z * this.scale.z,
  2966. cx = this.camera.getCameraLocation().x,
  2967. cy = this.camera.getCameraLocation().y,
  2968. cz = this.camera.getCameraLocation().z,
  2969. // calculate angles
  2970. sinTx = Math.sin(this.camera.getCameraRotation().x),
  2971. cosTx = Math.cos(this.camera.getCameraRotation().x),
  2972. sinTy = Math.sin(this.camera.getCameraRotation().y),
  2973. cosTy = Math.cos(this.camera.getCameraRotation().y),
  2974. sinTz = Math.sin(this.camera.getCameraRotation().z),
  2975. cosTz = Math.cos(this.camera.getCameraRotation().z),
  2976. // calculate translation
  2977. dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
  2978. dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)),
  2979. dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx));
  2980. return new Point3d(dx, dy, dz);
  2981. };
  2982. /**
  2983. * Convert a translation point to a point on the screen
  2984. * @param {Point3d} translation A 3D point with parameters x, y, z This is
  2985. * the translation of the point, seen from the
  2986. * camera
  2987. * @return {Point2d} point2d A 2D point with parameters x, y
  2988. */
  2989. Graph3d.prototype._convertTranslationToScreen = function(translation) {
  2990. var ex = this.eye.x,
  2991. ey = this.eye.y,
  2992. ez = this.eye.z,
  2993. dx = translation.x,
  2994. dy = translation.y,
  2995. dz = translation.z;
  2996. // calculate position on screen from translation
  2997. var bx;
  2998. var by;
  2999. if (this.showPerspective) {
  3000. bx = (dx - ex) * (ez / dz);
  3001. by = (dy - ey) * (ez / dz);
  3002. }
  3003. else {
  3004. bx = dx * -(ez / this.camera.getArmLength());
  3005. by = dy * -(ez / this.camera.getArmLength());
  3006. }
  3007. // shift and scale the point to the center of the screen
  3008. // use the width of the graph to scale both horizontally and vertically.
  3009. return new Point2d(
  3010. this.xcenter + bx * this.frame.canvas.clientWidth,
  3011. this.ycenter - by * this.frame.canvas.clientWidth);
  3012. };
  3013. /**
  3014. * Set the background styling for the graph
  3015. * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor
  3016. */
  3017. Graph3d.prototype._setBackgroundColor = function(backgroundColor) {
  3018. var fill = 'white';
  3019. var stroke = 'gray';
  3020. var strokeWidth = 1;
  3021. if (typeof(backgroundColor) === 'string') {
  3022. fill = backgroundColor;
  3023. stroke = 'none';
  3024. strokeWidth = 0;
  3025. }
  3026. else if (typeof(backgroundColor) === 'object') {
  3027. if (backgroundColor.fill !== undefined) fill = backgroundColor.fill;
  3028. if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke;
  3029. if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth;
  3030. }
  3031. else if (backgroundColor === undefined) {
  3032. // use use defaults
  3033. }
  3034. else {
  3035. throw 'Unsupported type of backgroundColor';
  3036. }
  3037. this.frame.style.backgroundColor = fill;
  3038. this.frame.style.borderColor = stroke;
  3039. this.frame.style.borderWidth = strokeWidth + 'px';
  3040. this.frame.style.borderStyle = 'solid';
  3041. };
  3042. /// enumerate the available styles
  3043. Graph3d.STYLE = {
  3044. BAR: 0,
  3045. BARCOLOR: 1,
  3046. BARSIZE: 2,
  3047. DOT : 3,
  3048. DOTLINE : 4,
  3049. DOTCOLOR: 5,
  3050. DOTSIZE: 6,
  3051. GRID : 7,
  3052. LINE: 8,
  3053. SURFACE : 9
  3054. };
  3055. /**
  3056. * Retrieve the style index from given styleName
  3057. * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line'
  3058. * @return {Number} styleNumber Enumeration value representing the style, or -1
  3059. * when not found
  3060. */
  3061. Graph3d.prototype._getStyleNumber = function(styleName) {
  3062. switch (styleName) {
  3063. case 'dot': return Graph3d.STYLE.DOT;
  3064. case 'dot-line': return Graph3d.STYLE.DOTLINE;
  3065. case 'dot-color': return Graph3d.STYLE.DOTCOLOR;
  3066. case 'dot-size': return Graph3d.STYLE.DOTSIZE;
  3067. case 'line': return Graph3d.STYLE.LINE;
  3068. case 'grid': return Graph3d.STYLE.GRID;
  3069. case 'surface': return Graph3d.STYLE.SURFACE;
  3070. case 'bar': return Graph3d.STYLE.BAR;
  3071. case 'bar-color': return Graph3d.STYLE.BARCOLOR;
  3072. case 'bar-size': return Graph3d.STYLE.BARSIZE;
  3073. }
  3074. return -1;
  3075. };
  3076. /**
  3077. * Determine the indexes of the data columns, based on the given style and data
  3078. * @param {DataSet} data
  3079. * @param {Number} style
  3080. */
  3081. Graph3d.prototype._determineColumnIndexes = function(data, style) {
  3082. if (this.style === Graph3d.STYLE.DOT ||
  3083. this.style === Graph3d.STYLE.DOTLINE ||
  3084. this.style === Graph3d.STYLE.LINE ||
  3085. this.style === Graph3d.STYLE.GRID ||
  3086. this.style === Graph3d.STYLE.SURFACE ||
  3087. this.style === Graph3d.STYLE.BAR) {
  3088. // 3 columns expected, and optionally a 4th with filter values
  3089. this.colX = 0;
  3090. this.colY = 1;
  3091. this.colZ = 2;
  3092. this.colValue = undefined;
  3093. if (data.getNumberOfColumns() > 3) {
  3094. this.colFilter = 3;
  3095. }
  3096. }
  3097. else if (this.style === Graph3d.STYLE.DOTCOLOR ||
  3098. this.style === Graph3d.STYLE.DOTSIZE ||
  3099. this.style === Graph3d.STYLE.BARCOLOR ||
  3100. this.style === Graph3d.STYLE.BARSIZE) {
  3101. // 4 columns expected, and optionally a 5th with filter values
  3102. this.colX = 0;
  3103. this.colY = 1;
  3104. this.colZ = 2;
  3105. this.colValue = 3;
  3106. if (data.getNumberOfColumns() > 4) {
  3107. this.colFilter = 4;
  3108. }
  3109. }
  3110. else {
  3111. throw 'Unknown style "' + this.style + '"';
  3112. }
  3113. };
  3114. Graph3d.prototype.getNumberOfRows = function(data) {
  3115. return data.length;
  3116. }
  3117. Graph3d.prototype.getNumberOfColumns = function(data) {
  3118. var counter = 0;
  3119. for (var column in data[0]) {
  3120. if (data[0].hasOwnProperty(column)) {
  3121. counter++;
  3122. }
  3123. }
  3124. return counter;
  3125. }
  3126. Graph3d.prototype.getDistinctValues = function(data, column) {
  3127. var distinctValues = [];
  3128. for (var i = 0; i < data.length; i++) {
  3129. if (distinctValues.indexOf(data[i][column]) == -1) {
  3130. distinctValues.push(data[i][column]);
  3131. }
  3132. }
  3133. return distinctValues;
  3134. }
  3135. Graph3d.prototype.getColumnRange = function(data,column) {
  3136. var minMax = {min:data[0][column],max:data[0][column]};
  3137. for (var i = 0; i < data.length; i++) {
  3138. if (minMax.min > data[i][column]) { minMax.min = data[i][column]; }
  3139. if (minMax.max < data[i][column]) { minMax.max = data[i][column]; }
  3140. }
  3141. return minMax;
  3142. };
  3143. /**
  3144. * Initialize the data from the data table. Calculate minimum and maximum values
  3145. * and column index values
  3146. * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph.
  3147. * @param {Number} style Style Number
  3148. */
  3149. Graph3d.prototype._dataInitialize = function (rawData, style) {
  3150. var me = this;
  3151. // unsubscribe from the dataTable
  3152. if (this.dataSet) {
  3153. this.dataSet.off('*', this._onChange);
  3154. }
  3155. if (rawData === undefined)
  3156. return;
  3157. if (Array.isArray(rawData)) {
  3158. rawData = new DataSet(rawData);
  3159. }
  3160. var data;
  3161. if (rawData instanceof DataSet || rawData instanceof DataView) {
  3162. data = rawData.get();
  3163. }
  3164. else {
  3165. throw new Error('Array, DataSet, or DataView expected');
  3166. }
  3167. if (data.length == 0)
  3168. return;
  3169. this.dataSet = rawData;
  3170. this.dataTable = data;
  3171. // subscribe to changes in the dataset
  3172. this._onChange = function () {
  3173. me.setData(me.dataSet);
  3174. };
  3175. this.dataSet.on('*', this._onChange);
  3176. // _determineColumnIndexes
  3177. // getNumberOfRows (points)
  3178. // getNumberOfColumns (x,y,z,v,t,t1,t2...)
  3179. // getDistinctValues (unique values?)
  3180. // getColumnRange
  3181. // determine the location of x,y,z,value,filter columns
  3182. this.colX = 'x';
  3183. this.colY = 'y';
  3184. this.colZ = 'z';
  3185. this.colValue = 'style';
  3186. this.colFilter = 'filter';
  3187. // check if a filter column is provided
  3188. if (data[0].hasOwnProperty('filter')) {
  3189. if (this.dataFilter === undefined) {
  3190. this.dataFilter = new Filter(rawData, this.colFilter, this);
  3191. this.dataFilter.setOnLoadCallback(function() {me.redraw();});
  3192. }
  3193. }
  3194. var withBars = this.style == Graph3d.STYLE.BAR ||
  3195. this.style == Graph3d.STYLE.BARCOLOR ||
  3196. this.style == Graph3d.STYLE.BARSIZE;
  3197. // determine barWidth from data
  3198. if (withBars) {
  3199. if (this.defaultXBarWidth !== undefined) {
  3200. this.xBarWidth = this.defaultXBarWidth;
  3201. }
  3202. else {
  3203. var dataX = this.getDistinctValues(data,this.colX);
  3204. this.xBarWidth = (dataX[1] - dataX[0]) || 1;
  3205. }
  3206. if (this.defaultYBarWidth !== undefined) {
  3207. this.yBarWidth = this.defaultYBarWidth;
  3208. }
  3209. else {
  3210. var dataY = this.getDistinctValues(data,this.colY);
  3211. this.yBarWidth = (dataY[1] - dataY[0]) || 1;
  3212. }
  3213. }
  3214. // calculate minimums and maximums
  3215. var xRange = this.getColumnRange(data,this.colX);
  3216. if (withBars) {
  3217. xRange.min -= this.xBarWidth / 2;
  3218. xRange.max += this.xBarWidth / 2;
  3219. }
  3220. this.xMin = (this.defaultXMin !== undefined) ? this.defaultXMin : xRange.min;
  3221. this.xMax = (this.defaultXMax !== undefined) ? this.defaultXMax : xRange.max;
  3222. if (this.xMax <= this.xMin) this.xMax = this.xMin + 1;
  3223. this.xStep = (this.defaultXStep !== undefined) ? this.defaultXStep : (this.xMax-this.xMin)/5;
  3224. var yRange = this.getColumnRange(data,this.colY);
  3225. if (withBars) {
  3226. yRange.min -= this.yBarWidth / 2;
  3227. yRange.max += this.yBarWidth / 2;
  3228. }
  3229. this.yMin = (this.defaultYMin !== undefined) ? this.defaultYMin : yRange.min;
  3230. this.yMax = (this.defaultYMax !== undefined) ? this.defaultYMax : yRange.max;
  3231. if (this.yMax <= this.yMin) this.yMax = this.yMin + 1;
  3232. this.yStep = (this.defaultYStep !== undefined) ? this.defaultYStep : (this.yMax-this.yMin)/5;
  3233. var zRange = this.getColumnRange(data,this.colZ);
  3234. this.zMin = (this.defaultZMin !== undefined) ? this.defaultZMin : zRange.min;
  3235. this.zMax = (this.defaultZMax !== undefined) ? this.defaultZMax : zRange.max;
  3236. if (this.zMax <= this.zMin) this.zMax = this.zMin + 1;
  3237. this.zStep = (this.defaultZStep !== undefined) ? this.defaultZStep : (this.zMax-this.zMin)/5;
  3238. if (this.colValue !== undefined) {
  3239. var valueRange = this.getColumnRange(data,this.colValue);
  3240. this.valueMin = (this.defaultValueMin !== undefined) ? this.defaultValueMin : valueRange.min;
  3241. this.valueMax = (this.defaultValueMax !== undefined) ? this.defaultValueMax : valueRange.max;
  3242. if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1;
  3243. }
  3244. // set the scale dependent on the ranges.
  3245. this._setScale();
  3246. };
  3247. /**
  3248. * Filter the data based on the current filter
  3249. * @param {Array} data
  3250. * @return {Array} dataPoints Array with point objects which can be drawn on screen
  3251. */
  3252. Graph3d.prototype._getDataPoints = function (data) {
  3253. // TODO: store the created matrix dataPoints in the filters instead of reloading each time
  3254. var x, y, i, z, obj, point;
  3255. var dataPoints = [];
  3256. if (this.style === Graph3d.STYLE.GRID ||
  3257. this.style === Graph3d.STYLE.SURFACE) {
  3258. // copy all values from the google data table to a matrix
  3259. // the provided values are supposed to form a grid of (x,y) positions
  3260. // create two lists with all present x and y values
  3261. var dataX = [];
  3262. var dataY = [];
  3263. for (i = 0; i < this.getNumberOfRows(data); i++) {
  3264. x = data[i][this.colX] || 0;
  3265. y = data[i][this.colY] || 0;
  3266. if (dataX.indexOf(x) === -1) {
  3267. dataX.push(x);
  3268. }
  3269. if (dataY.indexOf(y) === -1) {
  3270. dataY.push(y);
  3271. }
  3272. }
  3273. var sortNumber = function (a, b) {
  3274. return a - b;
  3275. };
  3276. dataX.sort(sortNumber);
  3277. dataY.sort(sortNumber);
  3278. // create a grid, a 2d matrix, with all values.
  3279. var dataMatrix = []; // temporary data matrix
  3280. for (i = 0; i < data.length; i++) {
  3281. x = data[i][this.colX] || 0;
  3282. y = data[i][this.colY] || 0;
  3283. z = data[i][this.colZ] || 0;
  3284. var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer
  3285. var yIndex = dataY.indexOf(y);
  3286. if (dataMatrix[xIndex] === undefined) {
  3287. dataMatrix[xIndex] = [];
  3288. }
  3289. var point3d = new Point3d();
  3290. point3d.x = x;
  3291. point3d.y = y;
  3292. point3d.z = z;
  3293. obj = {};
  3294. obj.point = point3d;
  3295. obj.trans = undefined;
  3296. obj.screen = undefined;
  3297. obj.bottom = new Point3d(x, y, this.zMin);
  3298. dataMatrix[xIndex][yIndex] = obj;
  3299. dataPoints.push(obj);
  3300. }
  3301. // fill in the pointers to the neighbors.
  3302. for (x = 0; x < dataMatrix.length; x++) {
  3303. for (y = 0; y < dataMatrix[x].length; y++) {
  3304. if (dataMatrix[x][y]) {
  3305. dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined;
  3306. dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined;
  3307. dataMatrix[x][y].pointCross =
  3308. (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ?
  3309. dataMatrix[x+1][y+1] :
  3310. undefined;
  3311. }
  3312. }
  3313. }
  3314. }
  3315. else { // 'dot', 'dot-line', etc.
  3316. // copy all values from the google data table to a list with Point3d objects
  3317. for (i = 0; i < data.length; i++) {
  3318. point = new Point3d();
  3319. point.x = data[i][this.colX] || 0;
  3320. point.y = data[i][this.colY] || 0;
  3321. point.z = data[i][this.colZ] || 0;
  3322. if (this.colValue !== undefined) {
  3323. point.value = data[i][this.colValue] || 0;
  3324. }
  3325. obj = {};
  3326. obj.point = point;
  3327. obj.bottom = new Point3d(point.x, point.y, this.zMin);
  3328. obj.trans = undefined;
  3329. obj.screen = undefined;
  3330. dataPoints.push(obj);
  3331. }
  3332. }
  3333. return dataPoints;
  3334. };
  3335. /**
  3336. * Create the main frame for the Graph3d.
  3337. * This function is executed once when a Graph3d object is created. The frame
  3338. * contains a canvas, and this canvas contains all objects like the axis and
  3339. * nodes.
  3340. */
  3341. Graph3d.prototype.create = function () {
  3342. // remove all elements from the container element.
  3343. while (this.containerElement.hasChildNodes()) {
  3344. this.containerElement.removeChild(this.containerElement.firstChild);
  3345. }
  3346. this.frame = document.createElement('div');
  3347. this.frame.style.position = 'relative';
  3348. this.frame.style.overflow = 'hidden';
  3349. // create the graph canvas (HTML canvas element)
  3350. this.frame.canvas = document.createElement( 'canvas' );
  3351. this.frame.canvas.style.position = 'relative';
  3352. this.frame.appendChild(this.frame.canvas);
  3353. //if (!this.frame.canvas.getContext) {
  3354. {
  3355. var noCanvas = document.createElement( 'DIV' );
  3356. noCanvas.style.color = 'red';
  3357. noCanvas.style.fontWeight = 'bold' ;
  3358. noCanvas.style.padding = '10px';
  3359. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  3360. this.frame.canvas.appendChild(noCanvas);
  3361. }
  3362. this.frame.filter = document.createElement( 'div' );
  3363. this.frame.filter.style.position = 'absolute';
  3364. this.frame.filter.style.bottom = '0px';
  3365. this.frame.filter.style.left = '0px';
  3366. this.frame.filter.style.width = '100%';
  3367. this.frame.appendChild(this.frame.filter);
  3368. // add event listeners to handle moving and zooming the contents
  3369. var me = this;
  3370. var onmousedown = function (event) {me._onMouseDown(event);};
  3371. var ontouchstart = function (event) {me._onTouchStart(event);};
  3372. var onmousewheel = function (event) {me._onWheel(event);};
  3373. var ontooltip = function (event) {me._onTooltip(event);};
  3374. // TODO: these events are never cleaned up... can give a 'memory leakage'
  3375. util.addEventListener(this.frame.canvas, 'keydown', onkeydown);
  3376. util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
  3377. util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
  3378. util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
  3379. util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
  3380. // add the new graph to the container element
  3381. this.containerElement.appendChild(this.frame);
  3382. };
  3383. /**
  3384. * Set a new size for the graph
  3385. * @param {string} width Width in pixels or percentage (for example '800px'
  3386. * or '50%')
  3387. * @param {string} height Height in pixels or percentage (for example '400px'
  3388. * or '30%')
  3389. */
  3390. Graph3d.prototype.setSize = function(width, height) {
  3391. this.frame.style.width = width;
  3392. this.frame.style.height = height;
  3393. this._resizeCanvas();
  3394. };
  3395. /**
  3396. * Resize the canvas to the current size of the frame
  3397. */
  3398. Graph3d.prototype._resizeCanvas = function() {
  3399. this.frame.canvas.style.width = '100%';
  3400. this.frame.canvas.style.height = '100%';
  3401. this.frame.canvas.width = this.frame.canvas.clientWidth;
  3402. this.frame.canvas.height = this.frame.canvas.clientHeight;
  3403. // adjust with for margin
  3404. this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px';
  3405. };
  3406. /**
  3407. * Start animation
  3408. */
  3409. Graph3d.prototype.animationStart = function() {
  3410. if (!this.frame.filter || !this.frame.filter.slider)
  3411. throw 'No animation available';
  3412. this.frame.filter.slider.play();
  3413. };
  3414. /**
  3415. * Stop animation
  3416. */
  3417. Graph3d.prototype.animationStop = function() {
  3418. if (!this.frame.filter || !this.frame.filter.slider) return;
  3419. this.frame.filter.slider.stop();
  3420. };
  3421. /**
  3422. * Resize the center position based on the current values in this.defaultXCenter
  3423. * and this.defaultYCenter (which are strings with a percentage or a value
  3424. * in pixels). The center positions are the variables this.xCenter
  3425. * and this.yCenter
  3426. */
  3427. Graph3d.prototype._resizeCenter = function() {
  3428. // calculate the horizontal center position
  3429. if (this.defaultXCenter.charAt(this.defaultXCenter.length-1) === '%') {
  3430. this.xcenter =
  3431. parseFloat(this.defaultXCenter) / 100 *
  3432. this.frame.canvas.clientWidth;
  3433. }
  3434. else {
  3435. this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px
  3436. }
  3437. // calculate the vertical center position
  3438. if (this.defaultYCenter.charAt(this.defaultYCenter.length-1) === '%') {
  3439. this.ycenter =
  3440. parseFloat(this.defaultYCenter) / 100 *
  3441. (this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
  3442. }
  3443. else {
  3444. this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px
  3445. }
  3446. };
  3447. /**
  3448. * Set the rotation and distance of the camera
  3449. * @param {Object} pos An object with the camera position. The object
  3450. * contains three parameters:
  3451. * - horizontal {Number}
  3452. * The horizontal rotation, between 0 and 2*PI.
  3453. * Optional, can be left undefined.
  3454. * - vertical {Number}
  3455. * The vertical rotation, between 0 and 0.5*PI
  3456. * if vertical=0.5*PI, the graph is shown from the
  3457. * top. Optional, can be left undefined.
  3458. * - distance {Number}
  3459. * The (normalized) distance of the camera to the
  3460. * center of the graph, a value between 0.71 and 5.0.
  3461. * Optional, can be left undefined.
  3462. */
  3463. Graph3d.prototype.setCameraPosition = function(pos) {
  3464. if (pos === undefined) {
  3465. return;
  3466. }
  3467. if (pos.horizontal !== undefined && pos.vertical !== undefined) {
  3468. this.camera.setArmRotation(pos.horizontal, pos.vertical);
  3469. }
  3470. if (pos.distance !== undefined) {
  3471. this.camera.setArmLength(pos.distance);
  3472. }
  3473. this.redraw();
  3474. };
  3475. /**
  3476. * Retrieve the current camera rotation
  3477. * @return {object} An object with parameters horizontal, vertical, and
  3478. * distance
  3479. */
  3480. Graph3d.prototype.getCameraPosition = function() {
  3481. var pos = this.camera.getArmRotation();
  3482. pos.distance = this.camera.getArmLength();
  3483. return pos;
  3484. };
  3485. /**
  3486. * Load data into the 3D Graph
  3487. */
  3488. Graph3d.prototype._readData = function(data) {
  3489. // read the data
  3490. this._dataInitialize(data, this.style);
  3491. if (this.dataFilter) {
  3492. // apply filtering
  3493. this.dataPoints = this.dataFilter._getDataPoints();
  3494. }
  3495. else {
  3496. // no filtering. load all data
  3497. this.dataPoints = this._getDataPoints(this.dataTable);
  3498. }
  3499. // draw the filter
  3500. this._redrawFilter();
  3501. };
  3502. /**
  3503. * Replace the dataset of the Graph3d
  3504. * @param {Array | DataSet | DataView} data
  3505. */
  3506. Graph3d.prototype.setData = function (data) {
  3507. this._readData(data);
  3508. this.redraw();
  3509. // start animation when option is true
  3510. if (this.animationAutoStart && this.dataFilter) {
  3511. this.animationStart();
  3512. }
  3513. };
  3514. /**
  3515. * Update the options. Options will be merged with current options
  3516. * @param {Object} options
  3517. */
  3518. Graph3d.prototype.setOptions = function (options) {
  3519. var cameraPosition = undefined;
  3520. this.animationStop();
  3521. if (options !== undefined) {
  3522. // retrieve parameter values
  3523. if (options.width !== undefined) this.width = options.width;
  3524. if (options.height !== undefined) this.height = options.height;
  3525. if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter;
  3526. if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter;
  3527. if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel;
  3528. if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel;
  3529. if (options.xLabel !== undefined) this.xLabel = options.xLabel;
  3530. if (options.yLabel !== undefined) this.yLabel = options.yLabel;
  3531. if (options.zLabel !== undefined) this.zLabel = options.zLabel;
  3532. if (options.xValueLabel !== undefined) this.xValueLabel = options.xValueLabel;
  3533. if (options.yValueLabel !== undefined) this.yValueLabel = options.yValueLabel;
  3534. if (options.zValueLabel !== undefined) this.zValueLabel = options.zValueLabel;
  3535. if (options.style !== undefined) {
  3536. var styleNumber = this._getStyleNumber(options.style);
  3537. if (styleNumber !== -1) {
  3538. this.style = styleNumber;
  3539. }
  3540. }
  3541. if (options.showGrid !== undefined) this.showGrid = options.showGrid;
  3542. if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective;
  3543. if (options.showShadow !== undefined) this.showShadow = options.showShadow;
  3544. if (options.tooltip !== undefined) this.showTooltip = options.tooltip;
  3545. if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls;
  3546. if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio;
  3547. if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio;
  3548. if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval;
  3549. if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload;
  3550. if (options.animationAutoStart !== undefined)this.animationAutoStart = options.animationAutoStart;
  3551. if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth;
  3552. if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth;
  3553. if (options.xMin !== undefined) this.defaultXMin = options.xMin;
  3554. if (options.xStep !== undefined) this.defaultXStep = options.xStep;
  3555. if (options.xMax !== undefined) this.defaultXMax = options.xMax;
  3556. if (options.yMin !== undefined) this.defaultYMin = options.yMin;
  3557. if (options.yStep !== undefined) this.defaultYStep = options.yStep;
  3558. if (options.yMax !== undefined) this.defaultYMax = options.yMax;
  3559. if (options.zMin !== undefined) this.defaultZMin = options.zMin;
  3560. if (options.zStep !== undefined) this.defaultZStep = options.zStep;
  3561. if (options.zMax !== undefined) this.defaultZMax = options.zMax;
  3562. if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin;
  3563. if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax;
  3564. if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition;
  3565. if (cameraPosition !== undefined) {
  3566. this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical);
  3567. this.camera.setArmLength(cameraPosition.distance);
  3568. }
  3569. else {
  3570. this.camera.setArmRotation(1.0, 0.5);
  3571. this.camera.setArmLength(1.7);
  3572. }
  3573. }
  3574. this._setBackgroundColor(options && options.backgroundColor);
  3575. this.setSize(this.width, this.height);
  3576. // re-load the data
  3577. if (this.dataTable) {
  3578. this.setData(this.dataTable);
  3579. }
  3580. // start animation when option is true
  3581. if (this.animationAutoStart && this.dataFilter) {
  3582. this.animationStart();
  3583. }
  3584. };
  3585. /**
  3586. * Redraw the Graph.
  3587. */
  3588. Graph3d.prototype.redraw = function() {
  3589. if (this.dataPoints === undefined) {
  3590. throw 'Error: graph data not initialized';
  3591. }
  3592. this._resizeCanvas();
  3593. this._resizeCenter();
  3594. this._redrawSlider();
  3595. this._redrawClear();
  3596. this._redrawAxis();
  3597. if (this.style === Graph3d.STYLE.GRID ||
  3598. this.style === Graph3d.STYLE.SURFACE) {
  3599. this._redrawDataGrid();
  3600. }
  3601. else if (this.style === Graph3d.STYLE.LINE) {
  3602. this._redrawDataLine();
  3603. }
  3604. else if (this.style === Graph3d.STYLE.BAR ||
  3605. this.style === Graph3d.STYLE.BARCOLOR ||
  3606. this.style === Graph3d.STYLE.BARSIZE) {
  3607. this._redrawDataBar();
  3608. }
  3609. else {
  3610. // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE
  3611. this._redrawDataDot();
  3612. }
  3613. this._redrawInfo();
  3614. this._redrawLegend();
  3615. };
  3616. /**
  3617. * Clear the canvas before redrawing
  3618. */
  3619. Graph3d.prototype._redrawClear = function() {
  3620. var canvas = this.frame.canvas;
  3621. var ctx = canvas.getContext('2d');
  3622. ctx.clearRect(0, 0, canvas.width, canvas.height);
  3623. };
  3624. /**
  3625. * Redraw the legend showing the colors
  3626. */
  3627. Graph3d.prototype._redrawLegend = function() {
  3628. var y;
  3629. if (this.style === Graph3d.STYLE.DOTCOLOR ||
  3630. this.style === Graph3d.STYLE.DOTSIZE) {
  3631. var dotSize = this.frame.clientWidth * 0.02;
  3632. var widthMin, widthMax;
  3633. if (this.style === Graph3d.STYLE.DOTSIZE) {
  3634. widthMin = dotSize / 2; // px
  3635. widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function
  3636. }
  3637. else {
  3638. widthMin = 20; // px
  3639. widthMax = 20; // px
  3640. }
  3641. var height = Math.max(this.frame.clientHeight * 0.25, 100);
  3642. var top = this.margin;
  3643. var right = this.frame.clientWidth - this.margin;
  3644. var left = right - widthMax;
  3645. var bottom = top + height;
  3646. }
  3647. var canvas = this.frame.canvas;
  3648. var ctx = canvas.getContext('2d');
  3649. ctx.lineWidth = 1;
  3650. ctx.font = '14px arial'; // TODO: put in options
  3651. if (this.style === Graph3d.STYLE.DOTCOLOR) {
  3652. // draw the color bar
  3653. var ymin = 0;
  3654. var ymax = height; // Todo: make height customizable
  3655. for (y = ymin; y < ymax; y++) {
  3656. var f = (y - ymin) / (ymax - ymin);
  3657. //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function
  3658. var hue = f * 240;
  3659. var color = this._hsv2rgb(hue, 1, 1);
  3660. ctx.strokeStyle = color;
  3661. ctx.beginPath();
  3662. ctx.moveTo(left, top + y);
  3663. ctx.lineTo(right, top + y);
  3664. ctx.stroke();
  3665. }
  3666. ctx.strokeStyle = this.colorAxis;
  3667. ctx.strokeRect(left, top, widthMax, height);
  3668. }
  3669. if (this.style === Graph3d.STYLE.DOTSIZE) {
  3670. // draw border around color bar
  3671. ctx.strokeStyle = this.colorAxis;
  3672. ctx.fillStyle = this.colorDot;
  3673. ctx.beginPath();
  3674. ctx.moveTo(left, top);
  3675. ctx.lineTo(right, top);
  3676. ctx.lineTo(right - widthMax + widthMin, bottom);
  3677. ctx.lineTo(left, bottom);
  3678. ctx.closePath();
  3679. ctx.fill();
  3680. ctx.stroke();
  3681. }
  3682. if (this.style === Graph3d.STYLE.DOTCOLOR ||
  3683. this.style === Graph3d.STYLE.DOTSIZE) {
  3684. // print values along the color bar
  3685. var gridLineLen = 5; // px
  3686. var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax-this.valueMin)/5, true);
  3687. step.start();
  3688. if (step.getCurrent() < this.valueMin) {
  3689. step.next();
  3690. }
  3691. while (!step.end()) {
  3692. y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height;
  3693. ctx.beginPath();
  3694. ctx.moveTo(left - gridLineLen, y);
  3695. ctx.lineTo(left, y);
  3696. ctx.stroke();
  3697. ctx.textAlign = 'right';
  3698. ctx.textBaseline = 'middle';
  3699. ctx.fillStyle = this.colorAxis;
  3700. ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
  3701. step.next();
  3702. }
  3703. ctx.textAlign = 'right';
  3704. ctx.textBaseline = 'top';
  3705. var label = this.legendLabel;
  3706. ctx.fillText(label, right, bottom + this.margin);
  3707. }
  3708. };
  3709. /**
  3710. * Redraw the filter
  3711. */
  3712. Graph3d.prototype._redrawFilter = function() {
  3713. this.frame.filter.innerHTML = '';
  3714. if (this.dataFilter) {
  3715. var options = {
  3716. 'visible': this.showAnimationControls
  3717. };
  3718. var slider = new Slider(this.frame.filter, options);
  3719. this.frame.filter.slider = slider;
  3720. // TODO: css here is not nice here...
  3721. this.frame.filter.style.padding = '10px';
  3722. //this.frame.filter.style.backgroundColor = '#EFEFEF';
  3723. slider.setValues(this.dataFilter.values);
  3724. slider.setPlayInterval(this.animationInterval);
  3725. // create an event handler
  3726. var me = this;
  3727. var onchange = function () {
  3728. var index = slider.getIndex();
  3729. me.dataFilter.selectValue(index);
  3730. me.dataPoints = me.dataFilter._getDataPoints();
  3731. me.redraw();
  3732. };
  3733. slider.setOnChangeCallback(onchange);
  3734. }
  3735. else {
  3736. this.frame.filter.slider = undefined;
  3737. }
  3738. };
  3739. /**
  3740. * Redraw the slider
  3741. */
  3742. Graph3d.prototype._redrawSlider = function() {
  3743. if ( this.frame.filter.slider !== undefined) {
  3744. this.frame.filter.slider.redraw();
  3745. }
  3746. };
  3747. /**
  3748. * Redraw common information
  3749. */
  3750. Graph3d.prototype._redrawInfo = function() {
  3751. if (this.dataFilter) {
  3752. var canvas = this.frame.canvas;
  3753. var ctx = canvas.getContext('2d');
  3754. ctx.font = '14px arial'; // TODO: put in options
  3755. ctx.lineStyle = 'gray';
  3756. ctx.fillStyle = 'gray';
  3757. ctx.textAlign = 'left';
  3758. ctx.textBaseline = 'top';
  3759. var x = this.margin;
  3760. var y = this.margin;
  3761. ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y);
  3762. }
  3763. };
  3764. /**
  3765. * Redraw the axis
  3766. */
  3767. Graph3d.prototype._redrawAxis = function() {
  3768. var canvas = this.frame.canvas,
  3769. ctx = canvas.getContext('2d'),
  3770. from, to, step, prettyStep,
  3771. text, xText, yText, zText,
  3772. offset, xOffset, yOffset,
  3773. xMin2d, xMax2d;
  3774. // TODO: get the actual rendered style of the containerElement
  3775. //ctx.font = this.containerElement.style.font;
  3776. ctx.font = 24 / this.camera.getArmLength() + 'px arial';
  3777. // calculate the length for the short grid lines
  3778. var gridLenX = 0.025 / this.scale.x;
  3779. var gridLenY = 0.025 / this.scale.y;
  3780. var textMargin = 5 / this.camera.getArmLength(); // px
  3781. var armAngle = this.camera.getArmRotation().horizontal;
  3782. // draw x-grid lines
  3783. ctx.lineWidth = 1;
  3784. prettyStep = (this.defaultXStep === undefined);
  3785. step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep);
  3786. step.start();
  3787. if (step.getCurrent() < this.xMin) {
  3788. step.next();
  3789. }
  3790. while (!step.end()) {
  3791. var x = step.getCurrent();
  3792. if (this.showGrid) {
  3793. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  3794. to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  3795. ctx.strokeStyle = this.colorGrid;
  3796. ctx.beginPath();
  3797. ctx.moveTo(from.x, from.y);
  3798. ctx.lineTo(to.x, to.y);
  3799. ctx.stroke();
  3800. }
  3801. else {
  3802. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  3803. to = this._convert3Dto2D(new Point3d(x, this.yMin+gridLenX, this.zMin));
  3804. ctx.strokeStyle = this.colorAxis;
  3805. ctx.beginPath();
  3806. ctx.moveTo(from.x, from.y);
  3807. ctx.lineTo(to.x, to.y);
  3808. ctx.stroke();
  3809. from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  3810. to = this._convert3Dto2D(new Point3d(x, this.yMax-gridLenX, this.zMin));
  3811. ctx.strokeStyle = this.colorAxis;
  3812. ctx.beginPath();
  3813. ctx.moveTo(from.x, from.y);
  3814. ctx.lineTo(to.x, to.y);
  3815. ctx.stroke();
  3816. }
  3817. yText = (Math.cos(armAngle) > 0) ? this.yMin : this.yMax;
  3818. text = this._convert3Dto2D(new Point3d(x, yText, this.zMin));
  3819. if (Math.cos(armAngle * 2) > 0) {
  3820. ctx.textAlign = 'center';
  3821. ctx.textBaseline = 'top';
  3822. text.y += textMargin;
  3823. }
  3824. else if (Math.sin(armAngle * 2) < 0){
  3825. ctx.textAlign = 'right';
  3826. ctx.textBaseline = 'middle';
  3827. }
  3828. else {
  3829. ctx.textAlign = 'left';
  3830. ctx.textBaseline = 'middle';
  3831. }
  3832. ctx.fillStyle = this.colorAxis;
  3833. ctx.fillText(' ' + this.xValueLabel(step.getCurrent()) + ' ', text.x, text.y);
  3834. step.next();
  3835. }
  3836. // draw y-grid lines
  3837. ctx.lineWidth = 1;
  3838. prettyStep = (this.defaultYStep === undefined);
  3839. step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep);
  3840. step.start();
  3841. if (step.getCurrent() < this.yMin) {
  3842. step.next();
  3843. }
  3844. while (!step.end()) {
  3845. if (this.showGrid) {
  3846. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  3847. to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  3848. ctx.strokeStyle = this.colorGrid;
  3849. ctx.beginPath();
  3850. ctx.moveTo(from.x, from.y);
  3851. ctx.lineTo(to.x, to.y);
  3852. ctx.stroke();
  3853. }
  3854. else {
  3855. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  3856. to = this._convert3Dto2D(new Point3d(this.xMin+gridLenY, step.getCurrent(), this.zMin));
  3857. ctx.strokeStyle = this.colorAxis;
  3858. ctx.beginPath();
  3859. ctx.moveTo(from.x, from.y);
  3860. ctx.lineTo(to.x, to.y);
  3861. ctx.stroke();
  3862. from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  3863. to = this._convert3Dto2D(new Point3d(this.xMax-gridLenY, step.getCurrent(), this.zMin));
  3864. ctx.strokeStyle = this.colorAxis;
  3865. ctx.beginPath();
  3866. ctx.moveTo(from.x, from.y);
  3867. ctx.lineTo(to.x, to.y);
  3868. ctx.stroke();
  3869. }
  3870. xText = (Math.sin(armAngle ) > 0) ? this.xMin : this.xMax;
  3871. text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin));
  3872. if (Math.cos(armAngle * 2) < 0) {
  3873. ctx.textAlign = 'center';
  3874. ctx.textBaseline = 'top';
  3875. text.y += textMargin;
  3876. }
  3877. else if (Math.sin(armAngle * 2) > 0){
  3878. ctx.textAlign = 'right';
  3879. ctx.textBaseline = 'middle';
  3880. }
  3881. else {
  3882. ctx.textAlign = 'left';
  3883. ctx.textBaseline = 'middle';
  3884. }
  3885. ctx.fillStyle = this.colorAxis;
  3886. ctx.fillText(' ' + this.yValueLabel(step.getCurrent()) + ' ', text.x, text.y);
  3887. step.next();
  3888. }
  3889. // draw z-grid lines and axis
  3890. ctx.lineWidth = 1;
  3891. prettyStep = (this.defaultZStep === undefined);
  3892. step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep);
  3893. step.start();
  3894. if (step.getCurrent() < this.zMin) {
  3895. step.next();
  3896. }
  3897. xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
  3898. yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
  3899. while (!step.end()) {
  3900. // TODO: make z-grid lines really 3d?
  3901. from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent()));
  3902. ctx.strokeStyle = this.colorAxis;
  3903. ctx.beginPath();
  3904. ctx.moveTo(from.x, from.y);
  3905. ctx.lineTo(from.x - textMargin, from.y);
  3906. ctx.stroke();
  3907. ctx.textAlign = 'right';
  3908. ctx.textBaseline = 'middle';
  3909. ctx.fillStyle = this.colorAxis;
  3910. ctx.fillText(this.zValueLabel(step.getCurrent()) + ' ', from.x - 5, from.y);
  3911. step.next();
  3912. }
  3913. ctx.lineWidth = 1;
  3914. from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  3915. to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax));
  3916. ctx.strokeStyle = this.colorAxis;
  3917. ctx.beginPath();
  3918. ctx.moveTo(from.x, from.y);
  3919. ctx.lineTo(to.x, to.y);
  3920. ctx.stroke();
  3921. // draw x-axis
  3922. ctx.lineWidth = 1;
  3923. // line at yMin
  3924. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  3925. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  3926. ctx.strokeStyle = this.colorAxis;
  3927. ctx.beginPath();
  3928. ctx.moveTo(xMin2d.x, xMin2d.y);
  3929. ctx.lineTo(xMax2d.x, xMax2d.y);
  3930. ctx.stroke();
  3931. // line at ymax
  3932. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  3933. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  3934. ctx.strokeStyle = this.colorAxis;
  3935. ctx.beginPath();
  3936. ctx.moveTo(xMin2d.x, xMin2d.y);
  3937. ctx.lineTo(xMax2d.x, xMax2d.y);
  3938. ctx.stroke();
  3939. // draw y-axis
  3940. ctx.lineWidth = 1;
  3941. // line at xMin
  3942. from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  3943. to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, 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. // line at xMax
  3950. from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  3951. to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  3952. ctx.strokeStyle = this.colorAxis;
  3953. ctx.beginPath();
  3954. ctx.moveTo(from.x, from.y);
  3955. ctx.lineTo(to.x, to.y);
  3956. ctx.stroke();
  3957. // draw x-label
  3958. var xLabel = this.xLabel;
  3959. if (xLabel.length > 0) {
  3960. yOffset = 0.1 / this.scale.y;
  3961. xText = (this.xMin + this.xMax) / 2;
  3962. yText = (Math.cos(armAngle) > 0) ? this.yMin - yOffset: this.yMax + yOffset;
  3963. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  3964. if (Math.cos(armAngle * 2) > 0) {
  3965. ctx.textAlign = 'center';
  3966. ctx.textBaseline = 'top';
  3967. }
  3968. else if (Math.sin(armAngle * 2) < 0){
  3969. ctx.textAlign = 'right';
  3970. ctx.textBaseline = 'middle';
  3971. }
  3972. else {
  3973. ctx.textAlign = 'left';
  3974. ctx.textBaseline = 'middle';
  3975. }
  3976. ctx.fillStyle = this.colorAxis;
  3977. ctx.fillText(xLabel, text.x, text.y);
  3978. }
  3979. // draw y-label
  3980. var yLabel = this.yLabel;
  3981. if (yLabel.length > 0) {
  3982. xOffset = 0.1 / this.scale.x;
  3983. xText = (Math.sin(armAngle ) > 0) ? this.xMin - xOffset : this.xMax + xOffset;
  3984. yText = (this.yMin + this.yMax) / 2;
  3985. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  3986. if (Math.cos(armAngle * 2) < 0) {
  3987. ctx.textAlign = 'center';
  3988. ctx.textBaseline = 'top';
  3989. }
  3990. else if (Math.sin(armAngle * 2) > 0){
  3991. ctx.textAlign = 'right';
  3992. ctx.textBaseline = 'middle';
  3993. }
  3994. else {
  3995. ctx.textAlign = 'left';
  3996. ctx.textBaseline = 'middle';
  3997. }
  3998. ctx.fillStyle = this.colorAxis;
  3999. ctx.fillText(yLabel, text.x, text.y);
  4000. }
  4001. // draw z-label
  4002. var zLabel = this.zLabel;
  4003. if (zLabel.length > 0) {
  4004. offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
  4005. xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
  4006. yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
  4007. zText = (this.zMin + this.zMax) / 2;
  4008. text = this._convert3Dto2D(new Point3d(xText, yText, zText));
  4009. ctx.textAlign = 'right';
  4010. ctx.textBaseline = 'middle';
  4011. ctx.fillStyle = this.colorAxis;
  4012. ctx.fillText(zLabel, text.x - offset, text.y);
  4013. }
  4014. };
  4015. /**
  4016. * Calculate the color based on the given value.
  4017. * @param {Number} H Hue, a value be between 0 and 360
  4018. * @param {Number} S Saturation, a value between 0 and 1
  4019. * @param {Number} V Value, a value between 0 and 1
  4020. */
  4021. Graph3d.prototype._hsv2rgb = function(H, S, V) {
  4022. var R, G, B, C, Hi, X;
  4023. C = V * S;
  4024. Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5
  4025. X = C * (1 - Math.abs(((H/60) % 2) - 1));
  4026. switch (Hi) {
  4027. case 0: R = C; G = X; B = 0; break;
  4028. case 1: R = X; G = C; B = 0; break;
  4029. case 2: R = 0; G = C; B = X; break;
  4030. case 3: R = 0; G = X; B = C; break;
  4031. case 4: R = X; G = 0; B = C; break;
  4032. case 5: R = C; G = 0; B = X; break;
  4033. default: R = 0; G = 0; B = 0; break;
  4034. }
  4035. return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')';
  4036. };
  4037. /**
  4038. * Draw all datapoints as a grid
  4039. * This function can be used when the style is 'grid'
  4040. */
  4041. Graph3d.prototype._redrawDataGrid = function() {
  4042. var canvas = this.frame.canvas,
  4043. ctx = canvas.getContext('2d'),
  4044. point, right, top, cross,
  4045. i,
  4046. topSideVisible, fillStyle, strokeStyle, lineWidth,
  4047. h, s, v, zAvg;
  4048. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  4049. return; // TODO: throw exception?
  4050. // calculate the translations and screen position of all points
  4051. for (i = 0; i < this.dataPoints.length; i++) {
  4052. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  4053. var screen = this._convertTranslationToScreen(trans);
  4054. this.dataPoints[i].trans = trans;
  4055. this.dataPoints[i].screen = screen;
  4056. // calculate the translation of the point at the bottom (needed for sorting)
  4057. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  4058. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  4059. }
  4060. // sort the points on depth of their (x,y) position (not on z)
  4061. var sortDepth = function (a, b) {
  4062. return b.dist - a.dist;
  4063. };
  4064. this.dataPoints.sort(sortDepth);
  4065. if (this.style === Graph3d.STYLE.SURFACE) {
  4066. for (i = 0; i < this.dataPoints.length; i++) {
  4067. point = this.dataPoints[i];
  4068. right = this.dataPoints[i].pointRight;
  4069. top = this.dataPoints[i].pointTop;
  4070. cross = this.dataPoints[i].pointCross;
  4071. if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) {
  4072. if (this.showGrayBottom || this.showShadow) {
  4073. // calculate the cross product of the two vectors from center
  4074. // to left and right, in order to know whether we are looking at the
  4075. // bottom or at the top side. We can also use the cross product
  4076. // for calculating light intensity
  4077. var aDiff = Point3d.subtract(cross.trans, point.trans);
  4078. var bDiff = Point3d.subtract(top.trans, right.trans);
  4079. var crossproduct = Point3d.crossProduct(aDiff, bDiff);
  4080. var len = crossproduct.length();
  4081. // FIXME: there is a bug with determining the surface side (shadow or colored)
  4082. topSideVisible = (crossproduct.z > 0);
  4083. }
  4084. else {
  4085. topSideVisible = true;
  4086. }
  4087. if (topSideVisible) {
  4088. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4089. zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
  4090. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4091. s = 1; // saturation
  4092. if (this.showShadow) {
  4093. v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale
  4094. fillStyle = this._hsv2rgb(h, s, v);
  4095. strokeStyle = fillStyle;
  4096. }
  4097. else {
  4098. v = 1;
  4099. fillStyle = this._hsv2rgb(h, s, v);
  4100. strokeStyle = this.colorAxis;
  4101. }
  4102. }
  4103. else {
  4104. fillStyle = 'gray';
  4105. strokeStyle = this.colorAxis;
  4106. }
  4107. lineWidth = 0.5;
  4108. ctx.lineWidth = lineWidth;
  4109. ctx.fillStyle = fillStyle;
  4110. ctx.strokeStyle = strokeStyle;
  4111. ctx.beginPath();
  4112. ctx.moveTo(point.screen.x, point.screen.y);
  4113. ctx.lineTo(right.screen.x, right.screen.y);
  4114. ctx.lineTo(cross.screen.x, cross.screen.y);
  4115. ctx.lineTo(top.screen.x, top.screen.y);
  4116. ctx.closePath();
  4117. ctx.fill();
  4118. ctx.stroke();
  4119. }
  4120. }
  4121. }
  4122. else { // grid style
  4123. for (i = 0; i < this.dataPoints.length; i++) {
  4124. point = this.dataPoints[i];
  4125. right = this.dataPoints[i].pointRight;
  4126. top = this.dataPoints[i].pointTop;
  4127. if (point !== undefined) {
  4128. if (this.showPerspective) {
  4129. lineWidth = 2 / -point.trans.z;
  4130. }
  4131. else {
  4132. lineWidth = 2 * -(this.eye.z / this.camera.getArmLength());
  4133. }
  4134. }
  4135. if (point !== undefined && right !== undefined) {
  4136. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4137. zAvg = (point.point.z + right.point.z) / 2;
  4138. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4139. ctx.lineWidth = lineWidth;
  4140. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  4141. ctx.beginPath();
  4142. ctx.moveTo(point.screen.x, point.screen.y);
  4143. ctx.lineTo(right.screen.x, right.screen.y);
  4144. ctx.stroke();
  4145. }
  4146. if (point !== undefined && top !== undefined) {
  4147. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4148. zAvg = (point.point.z + top.point.z) / 2;
  4149. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4150. ctx.lineWidth = lineWidth;
  4151. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  4152. ctx.beginPath();
  4153. ctx.moveTo(point.screen.x, point.screen.y);
  4154. ctx.lineTo(top.screen.x, top.screen.y);
  4155. ctx.stroke();
  4156. }
  4157. }
  4158. }
  4159. };
  4160. /**
  4161. * Draw all datapoints as dots.
  4162. * This function can be used when the style is 'dot' or 'dot-line'
  4163. */
  4164. Graph3d.prototype._redrawDataDot = function() {
  4165. var canvas = this.frame.canvas;
  4166. var ctx = canvas.getContext('2d');
  4167. var i;
  4168. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  4169. return; // TODO: throw exception?
  4170. // calculate the translations of all points
  4171. for (i = 0; i < this.dataPoints.length; i++) {
  4172. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  4173. var screen = this._convertTranslationToScreen(trans);
  4174. this.dataPoints[i].trans = trans;
  4175. this.dataPoints[i].screen = screen;
  4176. // calculate the distance from the point at the bottom to the camera
  4177. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  4178. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  4179. }
  4180. // order the translated points by depth
  4181. var sortDepth = function (a, b) {
  4182. return b.dist - a.dist;
  4183. };
  4184. this.dataPoints.sort(sortDepth);
  4185. // draw the datapoints as colored circles
  4186. var dotSize = this.frame.clientWidth * 0.02; // px
  4187. for (i = 0; i < this.dataPoints.length; i++) {
  4188. var point = this.dataPoints[i];
  4189. if (this.style === Graph3d.STYLE.DOTLINE) {
  4190. // draw a vertical line from the bottom to the graph value
  4191. //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin));
  4192. var from = this._convert3Dto2D(point.bottom);
  4193. ctx.lineWidth = 1;
  4194. ctx.strokeStyle = this.colorGrid;
  4195. ctx.beginPath();
  4196. ctx.moveTo(from.x, from.y);
  4197. ctx.lineTo(point.screen.x, point.screen.y);
  4198. ctx.stroke();
  4199. }
  4200. // calculate radius for the circle
  4201. var size;
  4202. if (this.style === Graph3d.STYLE.DOTSIZE) {
  4203. size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin);
  4204. }
  4205. else {
  4206. size = dotSize;
  4207. }
  4208. var radius;
  4209. if (this.showPerspective) {
  4210. radius = size / -point.trans.z;
  4211. }
  4212. else {
  4213. radius = size * -(this.eye.z / this.camera.getArmLength());
  4214. }
  4215. if (radius < 0) {
  4216. radius = 0;
  4217. }
  4218. var hue, color, borderColor;
  4219. if (this.style === Graph3d.STYLE.DOTCOLOR ) {
  4220. // calculate the color based on the value
  4221. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  4222. color = this._hsv2rgb(hue, 1, 1);
  4223. borderColor = this._hsv2rgb(hue, 1, 0.8);
  4224. }
  4225. else if (this.style === Graph3d.STYLE.DOTSIZE) {
  4226. color = this.colorDot;
  4227. borderColor = this.colorDotBorder;
  4228. }
  4229. else {
  4230. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4231. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4232. color = this._hsv2rgb(hue, 1, 1);
  4233. borderColor = this._hsv2rgb(hue, 1, 0.8);
  4234. }
  4235. // draw the circle
  4236. ctx.lineWidth = 1.0;
  4237. ctx.strokeStyle = borderColor;
  4238. ctx.fillStyle = color;
  4239. ctx.beginPath();
  4240. ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true);
  4241. ctx.fill();
  4242. ctx.stroke();
  4243. }
  4244. };
  4245. /**
  4246. * Draw all datapoints as bars.
  4247. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size'
  4248. */
  4249. Graph3d.prototype._redrawDataBar = function() {
  4250. var canvas = this.frame.canvas;
  4251. var ctx = canvas.getContext('2d');
  4252. var i, j, surface, corners;
  4253. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  4254. return; // TODO: throw exception?
  4255. // calculate the translations of all points
  4256. for (i = 0; i < this.dataPoints.length; i++) {
  4257. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  4258. var screen = this._convertTranslationToScreen(trans);
  4259. this.dataPoints[i].trans = trans;
  4260. this.dataPoints[i].screen = screen;
  4261. // calculate the distance from the point at the bottom to the camera
  4262. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  4263. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  4264. }
  4265. // order the translated points by depth
  4266. var sortDepth = function (a, b) {
  4267. return b.dist - a.dist;
  4268. };
  4269. this.dataPoints.sort(sortDepth);
  4270. // draw the datapoints as bars
  4271. var xWidth = this.xBarWidth / 2;
  4272. var yWidth = this.yBarWidth / 2;
  4273. for (i = 0; i < this.dataPoints.length; i++) {
  4274. var point = this.dataPoints[i];
  4275. // determine color
  4276. var hue, color, borderColor;
  4277. if (this.style === Graph3d.STYLE.BARCOLOR ) {
  4278. // calculate the color based on the value
  4279. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  4280. color = this._hsv2rgb(hue, 1, 1);
  4281. borderColor = this._hsv2rgb(hue, 1, 0.8);
  4282. }
  4283. else if (this.style === Graph3d.STYLE.BARSIZE) {
  4284. color = this.colorDot;
  4285. borderColor = this.colorDotBorder;
  4286. }
  4287. else {
  4288. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  4289. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  4290. color = this._hsv2rgb(hue, 1, 1);
  4291. borderColor = this._hsv2rgb(hue, 1, 0.8);
  4292. }
  4293. // calculate size for the bar
  4294. if (this.style === Graph3d.STYLE.BARSIZE) {
  4295. xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  4296. yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  4297. }
  4298. // calculate all corner points
  4299. var me = this;
  4300. var point3d = point.point;
  4301. var top = [
  4302. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)},
  4303. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)},
  4304. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)},
  4305. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)}
  4306. ];
  4307. var bottom = [
  4308. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin)},
  4309. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin)},
  4310. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)},
  4311. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)}
  4312. ];
  4313. // calculate screen location of the points
  4314. top.forEach(function (obj) {
  4315. obj.screen = me._convert3Dto2D(obj.point);
  4316. });
  4317. bottom.forEach(function (obj) {
  4318. obj.screen = me._convert3Dto2D(obj.point);
  4319. });
  4320. // create five sides, calculate both corner points and center points
  4321. var surfaces = [
  4322. {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)},
  4323. {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)},
  4324. {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)},
  4325. {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)},
  4326. {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)}
  4327. ];
  4328. point.surfaces = surfaces;
  4329. // calculate the distance of each of the surface centers to the camera
  4330. for (j = 0; j < surfaces.length; j++) {
  4331. surface = surfaces[j];
  4332. var transCenter = this._convertPointToTranslation(surface.center);
  4333. surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
  4334. // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
  4335. // but the current solution is fast/simple and works in 99.9% of all cases
  4336. // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
  4337. }
  4338. // order the surfaces by their (translated) depth
  4339. surfaces.sort(function (a, b) {
  4340. var diff = b.dist - a.dist;
  4341. if (diff) return diff;
  4342. // if equal depth, sort the top surface last
  4343. if (a.corners === top) return 1;
  4344. if (b.corners === top) return -1;
  4345. // both are equal
  4346. return 0;
  4347. });
  4348. // draw the ordered surfaces
  4349. ctx.lineWidth = 1;
  4350. ctx.strokeStyle = borderColor;
  4351. ctx.fillStyle = color;
  4352. // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
  4353. for (j = 2; j < surfaces.length; j++) {
  4354. surface = surfaces[j];
  4355. corners = surface.corners;
  4356. ctx.beginPath();
  4357. ctx.moveTo(corners[3].screen.x, corners[3].screen.y);
  4358. ctx.lineTo(corners[0].screen.x, corners[0].screen.y);
  4359. ctx.lineTo(corners[1].screen.x, corners[1].screen.y);
  4360. ctx.lineTo(corners[2].screen.x, corners[2].screen.y);
  4361. ctx.lineTo(corners[3].screen.x, corners[3].screen.y);
  4362. ctx.fill();
  4363. ctx.stroke();
  4364. }
  4365. }
  4366. };
  4367. /**
  4368. * Draw a line through all datapoints.
  4369. * This function can be used when the style is 'line'
  4370. */
  4371. Graph3d.prototype._redrawDataLine = function() {
  4372. var canvas = this.frame.canvas,
  4373. ctx = canvas.getContext('2d'),
  4374. point, i;
  4375. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  4376. return; // TODO: throw exception?
  4377. // calculate the translations of all points
  4378. for (i = 0; i < this.dataPoints.length; i++) {
  4379. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  4380. var screen = this._convertTranslationToScreen(trans);
  4381. this.dataPoints[i].trans = trans;
  4382. this.dataPoints[i].screen = screen;
  4383. }
  4384. // start the line
  4385. if (this.dataPoints.length > 0) {
  4386. point = this.dataPoints[0];
  4387. ctx.lineWidth = 1; // TODO: make customizable
  4388. ctx.strokeStyle = 'blue'; // TODO: make customizable
  4389. ctx.beginPath();
  4390. ctx.moveTo(point.screen.x, point.screen.y);
  4391. }
  4392. // draw the datapoints as colored circles
  4393. for (i = 1; i < this.dataPoints.length; i++) {
  4394. point = this.dataPoints[i];
  4395. ctx.lineTo(point.screen.x, point.screen.y);
  4396. }
  4397. // finish the line
  4398. if (this.dataPoints.length > 0) {
  4399. ctx.stroke();
  4400. }
  4401. };
  4402. /**
  4403. * Start a moving operation inside the provided parent element
  4404. * @param {Event} event The event that occurred (required for
  4405. * retrieving the mouse position)
  4406. */
  4407. Graph3d.prototype._onMouseDown = function(event) {
  4408. event = event || window.event;
  4409. // check if mouse is still down (may be up when focus is lost for example
  4410. // in an iframe)
  4411. if (this.leftButtonDown) {
  4412. this._onMouseUp(event);
  4413. }
  4414. // only react on left mouse button down
  4415. this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  4416. if (!this.leftButtonDown && !this.touchDown) return;
  4417. // get mouse position (different code for IE and all other browsers)
  4418. this.startMouseX = getMouseX(event);
  4419. this.startMouseY = getMouseY(event);
  4420. this.startStart = new Date(this.start);
  4421. this.startEnd = new Date(this.end);
  4422. this.startArmRotation = this.camera.getArmRotation();
  4423. this.frame.style.cursor = 'move';
  4424. // add event listeners to handle moving the contents
  4425. // we store the function onmousemove and onmouseup in the graph, so we can
  4426. // remove the eventlisteners lateron in the function mouseUp()
  4427. var me = this;
  4428. this.onmousemove = function (event) {me._onMouseMove(event);};
  4429. this.onmouseup = function (event) {me._onMouseUp(event);};
  4430. util.addEventListener(document, 'mousemove', me.onmousemove);
  4431. util.addEventListener(document, 'mouseup', me.onmouseup);
  4432. util.preventDefault(event);
  4433. };
  4434. /**
  4435. * Perform moving operating.
  4436. * This function activated from within the funcion Graph.mouseDown().
  4437. * @param {Event} event Well, eehh, the event
  4438. */
  4439. Graph3d.prototype._onMouseMove = function (event) {
  4440. event = event || window.event;
  4441. // calculate change in mouse position
  4442. var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
  4443. var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
  4444. var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
  4445. var verticalNew = this.startArmRotation.vertical + diffY / 200;
  4446. var snapAngle = 4; // degrees
  4447. var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
  4448. // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
  4449. // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
  4450. if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
  4451. horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001;
  4452. }
  4453. if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
  4454. horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001;
  4455. }
  4456. // snap vertically to nice angles
  4457. if (Math.abs(Math.sin(verticalNew)) < snapValue) {
  4458. verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI;
  4459. }
  4460. if (Math.abs(Math.cos(verticalNew)) < snapValue) {
  4461. verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI;
  4462. }
  4463. this.camera.setArmRotation(horizontalNew, verticalNew);
  4464. this.redraw();
  4465. // fire a cameraPositionChange event
  4466. var parameters = this.getCameraPosition();
  4467. this.emit('cameraPositionChange', parameters);
  4468. util.preventDefault(event);
  4469. };
  4470. /**
  4471. * Stop moving operating.
  4472. * This function activated from within the funcion Graph.mouseDown().
  4473. * @param {event} event The event
  4474. */
  4475. Graph3d.prototype._onMouseUp = function (event) {
  4476. this.frame.style.cursor = 'auto';
  4477. this.leftButtonDown = false;
  4478. // remove event listeners here
  4479. util.removeEventListener(document, 'mousemove', this.onmousemove);
  4480. util.removeEventListener(document, 'mouseup', this.onmouseup);
  4481. util.preventDefault(event);
  4482. };
  4483. /**
  4484. * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
  4485. * @param {Event} event A mouse move event
  4486. */
  4487. Graph3d.prototype._onTooltip = function (event) {
  4488. var delay = 300; // ms
  4489. var boundingRect = this.frame.getBoundingClientRect();
  4490. var mouseX = getMouseX(event) - boundingRect.left;
  4491. var mouseY = getMouseY(event) - boundingRect.top;
  4492. if (!this.showTooltip) {
  4493. return;
  4494. }
  4495. if (this.tooltipTimeout) {
  4496. clearTimeout(this.tooltipTimeout);
  4497. }
  4498. // (delayed) display of a tooltip only if no mouse button is down
  4499. if (this.leftButtonDown) {
  4500. this._hideTooltip();
  4501. return;
  4502. }
  4503. if (this.tooltip && this.tooltip.dataPoint) {
  4504. // tooltip is currently visible
  4505. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  4506. if (dataPoint !== this.tooltip.dataPoint) {
  4507. // datapoint changed
  4508. if (dataPoint) {
  4509. this._showTooltip(dataPoint);
  4510. }
  4511. else {
  4512. this._hideTooltip();
  4513. }
  4514. }
  4515. }
  4516. else {
  4517. // tooltip is currently not visible
  4518. var me = this;
  4519. this.tooltipTimeout = setTimeout(function () {
  4520. me.tooltipTimeout = null;
  4521. // show a tooltip if we have a data point
  4522. var dataPoint = me._dataPointFromXY(mouseX, mouseY);
  4523. if (dataPoint) {
  4524. me._showTooltip(dataPoint);
  4525. }
  4526. }, delay);
  4527. }
  4528. };
  4529. /**
  4530. * Event handler for touchstart event on mobile devices
  4531. */
  4532. Graph3d.prototype._onTouchStart = function(event) {
  4533. this.touchDown = true;
  4534. var me = this;
  4535. this.ontouchmove = function (event) {me._onTouchMove(event);};
  4536. this.ontouchend = function (event) {me._onTouchEnd(event);};
  4537. util.addEventListener(document, 'touchmove', me.ontouchmove);
  4538. util.addEventListener(document, 'touchend', me.ontouchend);
  4539. this._onMouseDown(event);
  4540. };
  4541. /**
  4542. * Event handler for touchmove event on mobile devices
  4543. */
  4544. Graph3d.prototype._onTouchMove = function(event) {
  4545. this._onMouseMove(event);
  4546. };
  4547. /**
  4548. * Event handler for touchend event on mobile devices
  4549. */
  4550. Graph3d.prototype._onTouchEnd = function(event) {
  4551. this.touchDown = false;
  4552. util.removeEventListener(document, 'touchmove', this.ontouchmove);
  4553. util.removeEventListener(document, 'touchend', this.ontouchend);
  4554. this._onMouseUp(event);
  4555. };
  4556. /**
  4557. * Event handler for mouse wheel event, used to zoom the graph
  4558. * Code from http://adomas.org/javascript-mouse-wheel/
  4559. * @param {event} event The event
  4560. */
  4561. Graph3d.prototype._onWheel = function(event) {
  4562. if (!event) /* For IE. */
  4563. event = window.event;
  4564. // retrieve delta
  4565. var delta = 0;
  4566. if (event.wheelDelta) { /* IE/Opera. */
  4567. delta = event.wheelDelta/120;
  4568. } else if (event.detail) { /* Mozilla case. */
  4569. // In Mozilla, sign of delta is different than in IE.
  4570. // Also, delta is multiple of 3.
  4571. delta = -event.detail/3;
  4572. }
  4573. // If delta is nonzero, handle it.
  4574. // Basically, delta is now positive if wheel was scrolled up,
  4575. // and negative, if wheel was scrolled down.
  4576. if (delta) {
  4577. var oldLength = this.camera.getArmLength();
  4578. var newLength = oldLength * (1 - delta / 10);
  4579. this.camera.setArmLength(newLength);
  4580. this.redraw();
  4581. this._hideTooltip();
  4582. }
  4583. // fire a cameraPositionChange event
  4584. var parameters = this.getCameraPosition();
  4585. this.emit('cameraPositionChange', parameters);
  4586. // Prevent default actions caused by mouse wheel.
  4587. // That might be ugly, but we handle scrolls somehow
  4588. // anyway, so don't bother here..
  4589. util.preventDefault(event);
  4590. };
  4591. /**
  4592. * Test whether a point lies inside given 2D triangle
  4593. * @param {Point2d} point
  4594. * @param {Point2d[]} triangle
  4595. * @return {boolean} Returns true if given point lies inside or on the edge of the triangle
  4596. * @private
  4597. */
  4598. Graph3d.prototype._insideTriangle = function (point, triangle) {
  4599. var a = triangle[0],
  4600. b = triangle[1],
  4601. c = triangle[2];
  4602. function sign (x) {
  4603. return x > 0 ? 1 : x < 0 ? -1 : 0;
  4604. }
  4605. var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
  4606. var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
  4607. var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
  4608. // each of the three signs must be either equal to each other or zero
  4609. return (as == 0 || bs == 0 || as == bs) &&
  4610. (bs == 0 || cs == 0 || bs == cs) &&
  4611. (as == 0 || cs == 0 || as == cs);
  4612. };
  4613. /**
  4614. * Find a data point close to given screen position (x, y)
  4615. * @param {Number} x
  4616. * @param {Number} y
  4617. * @return {Object | null} The closest data point or null if not close to any data point
  4618. * @private
  4619. */
  4620. Graph3d.prototype._dataPointFromXY = function (x, y) {
  4621. var i,
  4622. distMax = 100, // px
  4623. dataPoint = null,
  4624. closestDataPoint = null,
  4625. closestDist = null,
  4626. center = new Point2d(x, y);
  4627. if (this.style === Graph3d.STYLE.BAR ||
  4628. this.style === Graph3d.STYLE.BARCOLOR ||
  4629. this.style === Graph3d.STYLE.BARSIZE) {
  4630. // the data points are ordered from far away to closest
  4631. for (i = this.dataPoints.length - 1; i >= 0; i--) {
  4632. dataPoint = this.dataPoints[i];
  4633. var surfaces = dataPoint.surfaces;
  4634. if (surfaces) {
  4635. for (var s = surfaces.length - 1; s >= 0; s--) {
  4636. // split each surface in two triangles, and see if the center point is inside one of these
  4637. var surface = surfaces[s];
  4638. var corners = surface.corners;
  4639. var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
  4640. var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
  4641. if (this._insideTriangle(center, triangle1) ||
  4642. this._insideTriangle(center, triangle2)) {
  4643. // return immediately at the first hit
  4644. return dataPoint;
  4645. }
  4646. }
  4647. }
  4648. }
  4649. }
  4650. else {
  4651. // find the closest data point, using distance to the center of the point on 2d screen
  4652. for (i = 0; i < this.dataPoints.length; i++) {
  4653. dataPoint = this.dataPoints[i];
  4654. var point = dataPoint.screen;
  4655. if (point) {
  4656. var distX = Math.abs(x - point.x);
  4657. var distY = Math.abs(y - point.y);
  4658. var dist = Math.sqrt(distX * distX + distY * distY);
  4659. if ((closestDist === null || dist < closestDist) && dist < distMax) {
  4660. closestDist = dist;
  4661. closestDataPoint = dataPoint;
  4662. }
  4663. }
  4664. }
  4665. }
  4666. return closestDataPoint;
  4667. };
  4668. /**
  4669. * Display a tooltip for given data point
  4670. * @param {Object} dataPoint
  4671. * @private
  4672. */
  4673. Graph3d.prototype._showTooltip = function (dataPoint) {
  4674. var content, line, dot;
  4675. if (!this.tooltip) {
  4676. content = document.createElement('div');
  4677. content.style.position = 'absolute';
  4678. content.style.padding = '10px';
  4679. content.style.border = '1px solid #4d4d4d';
  4680. content.style.color = '#1a1a1a';
  4681. content.style.background = 'rgba(255,255,255,0.7)';
  4682. content.style.borderRadius = '2px';
  4683. content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)';
  4684. line = document.createElement('div');
  4685. line.style.position = 'absolute';
  4686. line.style.height = '40px';
  4687. line.style.width = '0';
  4688. line.style.borderLeft = '1px solid #4d4d4d';
  4689. dot = document.createElement('div');
  4690. dot.style.position = 'absolute';
  4691. dot.style.height = '0';
  4692. dot.style.width = '0';
  4693. dot.style.border = '5px solid #4d4d4d';
  4694. dot.style.borderRadius = '5px';
  4695. this.tooltip = {
  4696. dataPoint: null,
  4697. dom: {
  4698. content: content,
  4699. line: line,
  4700. dot: dot
  4701. }
  4702. };
  4703. }
  4704. else {
  4705. content = this.tooltip.dom.content;
  4706. line = this.tooltip.dom.line;
  4707. dot = this.tooltip.dom.dot;
  4708. }
  4709. this._hideTooltip();
  4710. this.tooltip.dataPoint = dataPoint;
  4711. if (typeof this.showTooltip === 'function') {
  4712. content.innerHTML = this.showTooltip(dataPoint.point);
  4713. }
  4714. else {
  4715. content.innerHTML = '<table>' +
  4716. '<tr><td>x:</td><td>' + dataPoint.point.x + '</td></tr>' +
  4717. '<tr><td>y:</td><td>' + dataPoint.point.y + '</td></tr>' +
  4718. '<tr><td>z:</td><td>' + dataPoint.point.z + '</td></tr>' +
  4719. '</table>';
  4720. }
  4721. content.style.left = '0';
  4722. content.style.top = '0';
  4723. this.frame.appendChild(content);
  4724. this.frame.appendChild(line);
  4725. this.frame.appendChild(dot);
  4726. // calculate sizes
  4727. var contentWidth = content.offsetWidth;
  4728. var contentHeight = content.offsetHeight;
  4729. var lineHeight = line.offsetHeight;
  4730. var dotWidth = dot.offsetWidth;
  4731. var dotHeight = dot.offsetHeight;
  4732. var left = dataPoint.screen.x - contentWidth / 2;
  4733. left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
  4734. line.style.left = dataPoint.screen.x + 'px';
  4735. line.style.top = (dataPoint.screen.y - lineHeight) + 'px';
  4736. content.style.left = left + 'px';
  4737. content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px';
  4738. dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px';
  4739. dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px';
  4740. };
  4741. /**
  4742. * Hide the tooltip when displayed
  4743. * @private
  4744. */
  4745. Graph3d.prototype._hideTooltip = function () {
  4746. if (this.tooltip) {
  4747. this.tooltip.dataPoint = null;
  4748. for (var prop in this.tooltip.dom) {
  4749. if (this.tooltip.dom.hasOwnProperty(prop)) {
  4750. var elem = this.tooltip.dom[prop];
  4751. if (elem && elem.parentNode) {
  4752. elem.parentNode.removeChild(elem);
  4753. }
  4754. }
  4755. }
  4756. }
  4757. };
  4758. /**--------------------------------------------------------------------------**/
  4759. /**
  4760. * Get the horizontal mouse position from a mouse event
  4761. * @param {Event} event
  4762. * @return {Number} mouse x
  4763. */
  4764. function getMouseX (event) {
  4765. if ('clientX' in event) return event.clientX;
  4766. return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
  4767. }
  4768. /**
  4769. * Get the vertical mouse position from a mouse event
  4770. * @param {Event} event
  4771. * @return {Number} mouse y
  4772. */
  4773. function getMouseY (event) {
  4774. if ('clientY' in event) return event.clientY;
  4775. return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
  4776. }
  4777. module.exports = Graph3d;
  4778. /***/ },
  4779. /* 7 */
  4780. /***/ function(module, exports, __webpack_require__) {
  4781. var Point3d = __webpack_require__(10);
  4782. /**
  4783. * @class Camera
  4784. * The camera is mounted on a (virtual) camera arm. The camera arm can rotate
  4785. * The camera is always looking in the direction of the origin of the arm.
  4786. * This way, the camera always rotates around one fixed point, the location
  4787. * of the camera arm.
  4788. *
  4789. * Documentation:
  4790. * http://en.wikipedia.org/wiki/3D_projection
  4791. */
  4792. function Camera() {
  4793. this.armLocation = new Point3d();
  4794. this.armRotation = {};
  4795. this.armRotation.horizontal = 0;
  4796. this.armRotation.vertical = 0;
  4797. this.armLength = 1.7;
  4798. this.cameraLocation = new Point3d();
  4799. this.cameraRotation = new Point3d(0.5*Math.PI, 0, 0);
  4800. this.calculateCameraOrientation();
  4801. }
  4802. /**
  4803. * Set the location (origin) of the arm
  4804. * @param {Number} x Normalized value of x
  4805. * @param {Number} y Normalized value of y
  4806. * @param {Number} z Normalized value of z
  4807. */
  4808. Camera.prototype.setArmLocation = function(x, y, z) {
  4809. this.armLocation.x = x;
  4810. this.armLocation.y = y;
  4811. this.armLocation.z = z;
  4812. this.calculateCameraOrientation();
  4813. };
  4814. /**
  4815. * Set the rotation of the camera arm
  4816. * @param {Number} horizontal The horizontal rotation, between 0 and 2*PI.
  4817. * Optional, can be left undefined.
  4818. * @param {Number} vertical The vertical rotation, between 0 and 0.5*PI
  4819. * if vertical=0.5*PI, the graph is shown from the
  4820. * top. Optional, can be left undefined.
  4821. */
  4822. Camera.prototype.setArmRotation = function(horizontal, vertical) {
  4823. if (horizontal !== undefined) {
  4824. this.armRotation.horizontal = horizontal;
  4825. }
  4826. if (vertical !== undefined) {
  4827. this.armRotation.vertical = vertical;
  4828. if (this.armRotation.vertical < 0) this.armRotation.vertical = 0;
  4829. if (this.armRotation.vertical > 0.5*Math.PI) this.armRotation.vertical = 0.5*Math.PI;
  4830. }
  4831. if (horizontal !== undefined || vertical !== undefined) {
  4832. this.calculateCameraOrientation();
  4833. }
  4834. };
  4835. /**
  4836. * Retrieve the current arm rotation
  4837. * @return {object} An object with parameters horizontal and vertical
  4838. */
  4839. Camera.prototype.getArmRotation = function() {
  4840. var rot = {};
  4841. rot.horizontal = this.armRotation.horizontal;
  4842. rot.vertical = this.armRotation.vertical;
  4843. return rot;
  4844. };
  4845. /**
  4846. * Set the (normalized) length of the camera arm.
  4847. * @param {Number} length A length between 0.71 and 5.0
  4848. */
  4849. Camera.prototype.setArmLength = function(length) {
  4850. if (length === undefined)
  4851. return;
  4852. this.armLength = length;
  4853. // Radius must be larger than the corner of the graph,
  4854. // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the
  4855. // graph
  4856. if (this.armLength < 0.71) this.armLength = 0.71;
  4857. if (this.armLength > 5.0) this.armLength = 5.0;
  4858. this.calculateCameraOrientation();
  4859. };
  4860. /**
  4861. * Retrieve the arm length
  4862. * @return {Number} length
  4863. */
  4864. Camera.prototype.getArmLength = function() {
  4865. return this.armLength;
  4866. };
  4867. /**
  4868. * Retrieve the camera location
  4869. * @return {Point3d} cameraLocation
  4870. */
  4871. Camera.prototype.getCameraLocation = function() {
  4872. return this.cameraLocation;
  4873. };
  4874. /**
  4875. * Retrieve the camera rotation
  4876. * @return {Point3d} cameraRotation
  4877. */
  4878. Camera.prototype.getCameraRotation = function() {
  4879. return this.cameraRotation;
  4880. };
  4881. /**
  4882. * Calculate the location and rotation of the camera based on the
  4883. * position and orientation of the camera arm
  4884. */
  4885. Camera.prototype.calculateCameraOrientation = function() {
  4886. // calculate location of the camera
  4887. this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  4888. this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  4889. this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical);
  4890. // calculate rotation of the camera
  4891. this.cameraRotation.x = Math.PI/2 - this.armRotation.vertical;
  4892. this.cameraRotation.y = 0;
  4893. this.cameraRotation.z = -this.armRotation.horizontal;
  4894. };
  4895. module.exports = Camera;
  4896. /***/ },
  4897. /* 8 */
  4898. /***/ function(module, exports, __webpack_require__) {
  4899. var DataView = __webpack_require__(4);
  4900. /**
  4901. * @class Filter
  4902. *
  4903. * @param {DataSet} data The google data table
  4904. * @param {Number} column The index of the column to be filtered
  4905. * @param {Graph} graph The graph
  4906. */
  4907. function Filter (data, column, graph) {
  4908. this.data = data;
  4909. this.column = column;
  4910. this.graph = graph; // the parent graph
  4911. this.index = undefined;
  4912. this.value = undefined;
  4913. // read all distinct values and select the first one
  4914. this.values = graph.getDistinctValues(data.get(), this.column);
  4915. // sort both numeric and string values correctly
  4916. this.values.sort(function (a, b) {
  4917. return a > b ? 1 : a < b ? -1 : 0;
  4918. });
  4919. if (this.values.length > 0) {
  4920. this.selectValue(0);
  4921. }
  4922. // create an array with the filtered datapoints. this will be loaded afterwards
  4923. this.dataPoints = [];
  4924. this.loaded = false;
  4925. this.onLoadCallback = undefined;
  4926. if (graph.animationPreload) {
  4927. this.loaded = false;
  4928. this.loadInBackground();
  4929. }
  4930. else {
  4931. this.loaded = true;
  4932. }
  4933. };
  4934. /**
  4935. * Return the label
  4936. * @return {string} label
  4937. */
  4938. Filter.prototype.isLoaded = function() {
  4939. return this.loaded;
  4940. };
  4941. /**
  4942. * Return the loaded progress
  4943. * @return {Number} percentage between 0 and 100
  4944. */
  4945. Filter.prototype.getLoadedProgress = function() {
  4946. var len = this.values.length;
  4947. var i = 0;
  4948. while (this.dataPoints[i]) {
  4949. i++;
  4950. }
  4951. return Math.round(i / len * 100);
  4952. };
  4953. /**
  4954. * Return the label
  4955. * @return {string} label
  4956. */
  4957. Filter.prototype.getLabel = function() {
  4958. return this.graph.filterLabel;
  4959. };
  4960. /**
  4961. * Return the columnIndex of the filter
  4962. * @return {Number} columnIndex
  4963. */
  4964. Filter.prototype.getColumn = function() {
  4965. return this.column;
  4966. };
  4967. /**
  4968. * Return the currently selected value. Returns undefined if there is no selection
  4969. * @return {*} value
  4970. */
  4971. Filter.prototype.getSelectedValue = function() {
  4972. if (this.index === undefined)
  4973. return undefined;
  4974. return this.values[this.index];
  4975. };
  4976. /**
  4977. * Retrieve all values of the filter
  4978. * @return {Array} values
  4979. */
  4980. Filter.prototype.getValues = function() {
  4981. return this.values;
  4982. };
  4983. /**
  4984. * Retrieve one value of the filter
  4985. * @param {Number} index
  4986. * @return {*} value
  4987. */
  4988. Filter.prototype.getValue = function(index) {
  4989. if (index >= this.values.length)
  4990. throw 'Error: index out of range';
  4991. return this.values[index];
  4992. };
  4993. /**
  4994. * Retrieve the (filtered) dataPoints for the currently selected filter index
  4995. * @param {Number} [index] (optional)
  4996. * @return {Array} dataPoints
  4997. */
  4998. Filter.prototype._getDataPoints = function(index) {
  4999. if (index === undefined)
  5000. index = this.index;
  5001. if (index === undefined)
  5002. return [];
  5003. var dataPoints;
  5004. if (this.dataPoints[index]) {
  5005. dataPoints = this.dataPoints[index];
  5006. }
  5007. else {
  5008. var f = {};
  5009. f.column = this.column;
  5010. f.value = this.values[index];
  5011. var dataView = new DataView(this.data,{filter: function (item) {return (item[f.column] == f.value);}}).get();
  5012. dataPoints = this.graph._getDataPoints(dataView);
  5013. this.dataPoints[index] = dataPoints;
  5014. }
  5015. return dataPoints;
  5016. };
  5017. /**
  5018. * Set a callback function when the filter is fully loaded.
  5019. */
  5020. Filter.prototype.setOnLoadCallback = function(callback) {
  5021. this.onLoadCallback = callback;
  5022. };
  5023. /**
  5024. * Add a value to the list with available values for this filter
  5025. * No double entries will be created.
  5026. * @param {Number} index
  5027. */
  5028. Filter.prototype.selectValue = function(index) {
  5029. if (index >= this.values.length)
  5030. throw 'Error: index out of range';
  5031. this.index = index;
  5032. this.value = this.values[index];
  5033. };
  5034. /**
  5035. * Load all filtered rows in the background one by one
  5036. * Start this method without providing an index!
  5037. */
  5038. Filter.prototype.loadInBackground = function(index) {
  5039. if (index === undefined)
  5040. index = 0;
  5041. var frame = this.graph.frame;
  5042. if (index < this.values.length) {
  5043. var dataPointsTemp = this._getDataPoints(index);
  5044. //this.graph.redrawInfo(); // TODO: not neat
  5045. // create a progress box
  5046. if (frame.progress === undefined) {
  5047. frame.progress = document.createElement('DIV');
  5048. frame.progress.style.position = 'absolute';
  5049. frame.progress.style.color = 'gray';
  5050. frame.appendChild(frame.progress);
  5051. }
  5052. var progress = this.getLoadedProgress();
  5053. frame.progress.innerHTML = 'Loading animation... ' + progress + '%';
  5054. // TODO: this is no nice solution...
  5055. frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider
  5056. frame.progress.style.left = 10 + 'px';
  5057. var me = this;
  5058. setTimeout(function() {me.loadInBackground(index+1);}, 10);
  5059. this.loaded = false;
  5060. }
  5061. else {
  5062. this.loaded = true;
  5063. // remove the progress box
  5064. if (frame.progress !== undefined) {
  5065. frame.removeChild(frame.progress);
  5066. frame.progress = undefined;
  5067. }
  5068. if (this.onLoadCallback)
  5069. this.onLoadCallback();
  5070. }
  5071. };
  5072. module.exports = Filter;
  5073. /***/ },
  5074. /* 9 */
  5075. /***/ function(module, exports, __webpack_require__) {
  5076. /**
  5077. * @prototype Point2d
  5078. * @param {Number} [x]
  5079. * @param {Number} [y]
  5080. */
  5081. function Point2d (x, y) {
  5082. this.x = x !== undefined ? x : 0;
  5083. this.y = y !== undefined ? y : 0;
  5084. }
  5085. module.exports = Point2d;
  5086. /***/ },
  5087. /* 10 */
  5088. /***/ function(module, exports, __webpack_require__) {
  5089. /**
  5090. * @prototype Point3d
  5091. * @param {Number} [x]
  5092. * @param {Number} [y]
  5093. * @param {Number} [z]
  5094. */
  5095. function Point3d(x, y, z) {
  5096. this.x = x !== undefined ? x : 0;
  5097. this.y = y !== undefined ? y : 0;
  5098. this.z = z !== undefined ? z : 0;
  5099. };
  5100. /**
  5101. * Subtract the two provided points, returns a-b
  5102. * @param {Point3d} a
  5103. * @param {Point3d} b
  5104. * @return {Point3d} a-b
  5105. */
  5106. Point3d.subtract = function(a, b) {
  5107. var sub = new Point3d();
  5108. sub.x = a.x - b.x;
  5109. sub.y = a.y - b.y;
  5110. sub.z = a.z - b.z;
  5111. return sub;
  5112. };
  5113. /**
  5114. * Add the two provided points, returns a+b
  5115. * @param {Point3d} a
  5116. * @param {Point3d} b
  5117. * @return {Point3d} a+b
  5118. */
  5119. Point3d.add = function(a, b) {
  5120. var sum = new Point3d();
  5121. sum.x = a.x + b.x;
  5122. sum.y = a.y + b.y;
  5123. sum.z = a.z + b.z;
  5124. return sum;
  5125. };
  5126. /**
  5127. * Calculate the average of two 3d points
  5128. * @param {Point3d} a
  5129. * @param {Point3d} b
  5130. * @return {Point3d} The average, (a+b)/2
  5131. */
  5132. Point3d.avg = function(a, b) {
  5133. return new Point3d(
  5134. (a.x + b.x) / 2,
  5135. (a.y + b.y) / 2,
  5136. (a.z + b.z) / 2
  5137. );
  5138. };
  5139. /**
  5140. * Calculate the cross product of the two provided points, returns axb
  5141. * Documentation: http://en.wikipedia.org/wiki/Cross_product
  5142. * @param {Point3d} a
  5143. * @param {Point3d} b
  5144. * @return {Point3d} cross product axb
  5145. */
  5146. Point3d.crossProduct = function(a, b) {
  5147. var crossproduct = new Point3d();
  5148. crossproduct.x = a.y * b.z - a.z * b.y;
  5149. crossproduct.y = a.z * b.x - a.x * b.z;
  5150. crossproduct.z = a.x * b.y - a.y * b.x;
  5151. return crossproduct;
  5152. };
  5153. /**
  5154. * Rtrieve the length of the vector (or the distance from this point to the origin
  5155. * @return {Number} length
  5156. */
  5157. Point3d.prototype.length = function() {
  5158. return Math.sqrt(
  5159. this.x * this.x +
  5160. this.y * this.y +
  5161. this.z * this.z
  5162. );
  5163. };
  5164. module.exports = Point3d;
  5165. /***/ },
  5166. /* 11 */
  5167. /***/ function(module, exports, __webpack_require__) {
  5168. var util = __webpack_require__(1);
  5169. /**
  5170. * @constructor Slider
  5171. *
  5172. * An html slider control with start/stop/prev/next buttons
  5173. * @param {Element} container The element where the slider will be created
  5174. * @param {Object} options Available options:
  5175. * {boolean} visible If true (default) the
  5176. * slider is visible.
  5177. */
  5178. function Slider(container, options) {
  5179. if (container === undefined) {
  5180. throw 'Error: No container element defined';
  5181. }
  5182. this.container = container;
  5183. this.visible = (options && options.visible != undefined) ? options.visible : true;
  5184. if (this.visible) {
  5185. this.frame = document.createElement('DIV');
  5186. //this.frame.style.backgroundColor = '#E5E5E5';
  5187. this.frame.style.width = '100%';
  5188. this.frame.style.position = 'relative';
  5189. this.container.appendChild(this.frame);
  5190. this.frame.prev = document.createElement('INPUT');
  5191. this.frame.prev.type = 'BUTTON';
  5192. this.frame.prev.value = 'Prev';
  5193. this.frame.appendChild(this.frame.prev);
  5194. this.frame.play = document.createElement('INPUT');
  5195. this.frame.play.type = 'BUTTON';
  5196. this.frame.play.value = 'Play';
  5197. this.frame.appendChild(this.frame.play);
  5198. this.frame.next = document.createElement('INPUT');
  5199. this.frame.next.type = 'BUTTON';
  5200. this.frame.next.value = 'Next';
  5201. this.frame.appendChild(this.frame.next);
  5202. this.frame.bar = document.createElement('INPUT');
  5203. this.frame.bar.type = 'BUTTON';
  5204. this.frame.bar.style.position = 'absolute';
  5205. this.frame.bar.style.border = '1px solid red';
  5206. this.frame.bar.style.width = '100px';
  5207. this.frame.bar.style.height = '6px';
  5208. this.frame.bar.style.borderRadius = '2px';
  5209. this.frame.bar.style.MozBorderRadius = '2px';
  5210. this.frame.bar.style.border = '1px solid #7F7F7F';
  5211. this.frame.bar.style.backgroundColor = '#E5E5E5';
  5212. this.frame.appendChild(this.frame.bar);
  5213. this.frame.slide = document.createElement('INPUT');
  5214. this.frame.slide.type = 'BUTTON';
  5215. this.frame.slide.style.margin = '0px';
  5216. this.frame.slide.value = ' ';
  5217. this.frame.slide.style.position = 'relative';
  5218. this.frame.slide.style.left = '-100px';
  5219. this.frame.appendChild(this.frame.slide);
  5220. // create events
  5221. var me = this;
  5222. this.frame.slide.onmousedown = function (event) {me._onMouseDown(event);};
  5223. this.frame.prev.onclick = function (event) {me.prev(event);};
  5224. this.frame.play.onclick = function (event) {me.togglePlay(event);};
  5225. this.frame.next.onclick = function (event) {me.next(event);};
  5226. }
  5227. this.onChangeCallback = undefined;
  5228. this.values = [];
  5229. this.index = undefined;
  5230. this.playTimeout = undefined;
  5231. this.playInterval = 1000; // milliseconds
  5232. this.playLoop = true;
  5233. }
  5234. /**
  5235. * Select the previous index
  5236. */
  5237. Slider.prototype.prev = function() {
  5238. var index = this.getIndex();
  5239. if (index > 0) {
  5240. index--;
  5241. this.setIndex(index);
  5242. }
  5243. };
  5244. /**
  5245. * Select the next index
  5246. */
  5247. Slider.prototype.next = function() {
  5248. var index = this.getIndex();
  5249. if (index < this.values.length - 1) {
  5250. index++;
  5251. this.setIndex(index);
  5252. }
  5253. };
  5254. /**
  5255. * Select the next index
  5256. */
  5257. Slider.prototype.playNext = function() {
  5258. var start = new Date();
  5259. var index = this.getIndex();
  5260. if (index < this.values.length - 1) {
  5261. index++;
  5262. this.setIndex(index);
  5263. }
  5264. else if (this.playLoop) {
  5265. // jump to the start
  5266. index = 0;
  5267. this.setIndex(index);
  5268. }
  5269. var end = new Date();
  5270. var diff = (end - start);
  5271. // calculate how much time it to to set the index and to execute the callback
  5272. // function.
  5273. var interval = Math.max(this.playInterval - diff, 0);
  5274. // document.title = diff // TODO: cleanup
  5275. var me = this;
  5276. this.playTimeout = setTimeout(function() {me.playNext();}, interval);
  5277. };
  5278. /**
  5279. * Toggle start or stop playing
  5280. */
  5281. Slider.prototype.togglePlay = function() {
  5282. if (this.playTimeout === undefined) {
  5283. this.play();
  5284. } else {
  5285. this.stop();
  5286. }
  5287. };
  5288. /**
  5289. * Start playing
  5290. */
  5291. Slider.prototype.play = function() {
  5292. // Test whether already playing
  5293. if (this.playTimeout) return;
  5294. this.playNext();
  5295. if (this.frame) {
  5296. this.frame.play.value = 'Stop';
  5297. }
  5298. };
  5299. /**
  5300. * Stop playing
  5301. */
  5302. Slider.prototype.stop = function() {
  5303. clearInterval(this.playTimeout);
  5304. this.playTimeout = undefined;
  5305. if (this.frame) {
  5306. this.frame.play.value = 'Play';
  5307. }
  5308. };
  5309. /**
  5310. * Set a callback function which will be triggered when the value of the
  5311. * slider bar has changed.
  5312. */
  5313. Slider.prototype.setOnChangeCallback = function(callback) {
  5314. this.onChangeCallback = callback;
  5315. };
  5316. /**
  5317. * Set the interval for playing the list
  5318. * @param {Number} interval The interval in milliseconds
  5319. */
  5320. Slider.prototype.setPlayInterval = function(interval) {
  5321. this.playInterval = interval;
  5322. };
  5323. /**
  5324. * Retrieve the current play interval
  5325. * @return {Number} interval The interval in milliseconds
  5326. */
  5327. Slider.prototype.getPlayInterval = function(interval) {
  5328. return this.playInterval;
  5329. };
  5330. /**
  5331. * Set looping on or off
  5332. * @pararm {boolean} doLoop If true, the slider will jump to the start when
  5333. * the end is passed, and will jump to the end
  5334. * when the start is passed.
  5335. */
  5336. Slider.prototype.setPlayLoop = function(doLoop) {
  5337. this.playLoop = doLoop;
  5338. };
  5339. /**
  5340. * Execute the onchange callback function
  5341. */
  5342. Slider.prototype.onChange = function() {
  5343. if (this.onChangeCallback !== undefined) {
  5344. this.onChangeCallback();
  5345. }
  5346. };
  5347. /**
  5348. * redraw the slider on the correct place
  5349. */
  5350. Slider.prototype.redraw = function() {
  5351. if (this.frame) {
  5352. // resize the bar
  5353. this.frame.bar.style.top = (this.frame.clientHeight/2 -
  5354. this.frame.bar.offsetHeight/2) + 'px';
  5355. this.frame.bar.style.width = (this.frame.clientWidth -
  5356. this.frame.prev.clientWidth -
  5357. this.frame.play.clientWidth -
  5358. this.frame.next.clientWidth - 30) + 'px';
  5359. // position the slider button
  5360. var left = this.indexToLeft(this.index);
  5361. this.frame.slide.style.left = (left) + 'px';
  5362. }
  5363. };
  5364. /**
  5365. * Set the list with values for the slider
  5366. * @param {Array} values A javascript array with values (any type)
  5367. */
  5368. Slider.prototype.setValues = function(values) {
  5369. this.values = values;
  5370. if (this.values.length > 0)
  5371. this.setIndex(0);
  5372. else
  5373. this.index = undefined;
  5374. };
  5375. /**
  5376. * Select a value by its index
  5377. * @param {Number} index
  5378. */
  5379. Slider.prototype.setIndex = function(index) {
  5380. if (index < this.values.length) {
  5381. this.index = index;
  5382. this.redraw();
  5383. this.onChange();
  5384. }
  5385. else {
  5386. throw 'Error: index out of range';
  5387. }
  5388. };
  5389. /**
  5390. * retrieve the index of the currently selected vaue
  5391. * @return {Number} index
  5392. */
  5393. Slider.prototype.getIndex = function() {
  5394. return this.index;
  5395. };
  5396. /**
  5397. * retrieve the currently selected value
  5398. * @return {*} value
  5399. */
  5400. Slider.prototype.get = function() {
  5401. return this.values[this.index];
  5402. };
  5403. Slider.prototype._onMouseDown = function(event) {
  5404. // only react on left mouse button down
  5405. var leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  5406. if (!leftButtonDown) return;
  5407. this.startClientX = event.clientX;
  5408. this.startSlideX = parseFloat(this.frame.slide.style.left);
  5409. this.frame.style.cursor = 'move';
  5410. // add event listeners to handle moving the contents
  5411. // we store the function onmousemove and onmouseup in the graph, so we can
  5412. // remove the eventlisteners lateron in the function mouseUp()
  5413. var me = this;
  5414. this.onmousemove = function (event) {me._onMouseMove(event);};
  5415. this.onmouseup = function (event) {me._onMouseUp(event);};
  5416. util.addEventListener(document, 'mousemove', this.onmousemove);
  5417. util.addEventListener(document, 'mouseup', this.onmouseup);
  5418. util.preventDefault(event);
  5419. };
  5420. Slider.prototype.leftToIndex = function (left) {
  5421. var width = parseFloat(this.frame.bar.style.width) -
  5422. this.frame.slide.clientWidth - 10;
  5423. var x = left - 3;
  5424. var index = Math.round(x / width * (this.values.length-1));
  5425. if (index < 0) index = 0;
  5426. if (index > this.values.length-1) index = this.values.length-1;
  5427. return index;
  5428. };
  5429. Slider.prototype.indexToLeft = function (index) {
  5430. var width = parseFloat(this.frame.bar.style.width) -
  5431. this.frame.slide.clientWidth - 10;
  5432. var x = index / (this.values.length-1) * width;
  5433. var left = x + 3;
  5434. return left;
  5435. };
  5436. Slider.prototype._onMouseMove = function (event) {
  5437. var diff = event.clientX - this.startClientX;
  5438. var x = this.startSlideX + diff;
  5439. var index = this.leftToIndex(x);
  5440. this.setIndex(index);
  5441. util.preventDefault();
  5442. };
  5443. Slider.prototype._onMouseUp = function (event) {
  5444. this.frame.style.cursor = 'auto';
  5445. // remove event listeners
  5446. util.removeEventListener(document, 'mousemove', this.onmousemove);
  5447. util.removeEventListener(document, 'mouseup', this.onmouseup);
  5448. util.preventDefault();
  5449. };
  5450. module.exports = Slider;
  5451. /***/ },
  5452. /* 12 */
  5453. /***/ function(module, exports, __webpack_require__) {
  5454. /**
  5455. * @prototype StepNumber
  5456. * The class StepNumber is an iterator for Numbers. You provide a start and end
  5457. * value, and a best step size. StepNumber itself rounds to fixed values and
  5458. * a finds the step that best fits the provided step.
  5459. *
  5460. * If prettyStep is true, the step size is chosen as close as possible to the
  5461. * provided step, but being a round value like 1, 2, 5, 10, 20, 50, ....
  5462. *
  5463. * Example usage:
  5464. * var step = new StepNumber(0, 10, 2.5, true);
  5465. * step.start();
  5466. * while (!step.end()) {
  5467. * alert(step.getCurrent());
  5468. * step.next();
  5469. * }
  5470. *
  5471. * Version: 1.0
  5472. *
  5473. * @param {Number} start The start value
  5474. * @param {Number} end The end value
  5475. * @param {Number} step Optional. Step size. Must be a positive value.
  5476. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  5477. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  5478. */
  5479. function StepNumber(start, end, step, prettyStep) {
  5480. // set default values
  5481. this._start = 0;
  5482. this._end = 0;
  5483. this._step = 1;
  5484. this.prettyStep = true;
  5485. this.precision = 5;
  5486. this._current = 0;
  5487. this.setRange(start, end, step, prettyStep);
  5488. };
  5489. /**
  5490. * Set a new range: start, end and step.
  5491. *
  5492. * @param {Number} start The start value
  5493. * @param {Number} end The end value
  5494. * @param {Number} step Optional. Step size. Must be a positive value.
  5495. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  5496. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  5497. */
  5498. StepNumber.prototype.setRange = function(start, end, step, prettyStep) {
  5499. this._start = start ? start : 0;
  5500. this._end = end ? end : 0;
  5501. this.setStep(step, prettyStep);
  5502. };
  5503. /**
  5504. * Set a new step size
  5505. * @param {Number} step New step size. Must be a positive value
  5506. * @param {boolean} prettyStep Optional. If true, the provided step is rounded
  5507. * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  5508. */
  5509. StepNumber.prototype.setStep = function(step, prettyStep) {
  5510. if (step === undefined || step <= 0)
  5511. return;
  5512. if (prettyStep !== undefined)
  5513. this.prettyStep = prettyStep;
  5514. if (this.prettyStep === true)
  5515. this._step = StepNumber.calculatePrettyStep(step);
  5516. else
  5517. this._step = step;
  5518. };
  5519. /**
  5520. * Calculate a nice step size, closest to the desired step size.
  5521. * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an
  5522. * integer Number. For example 1, 2, 5, 10, 20, 50, etc...
  5523. * @param {Number} step Desired step size
  5524. * @return {Number} Nice step size
  5525. */
  5526. StepNumber.calculatePrettyStep = function (step) {
  5527. var log10 = function (x) {return Math.log(x) / Math.LN10;};
  5528. // try three steps (multiple of 1, 2, or 5
  5529. var step1 = Math.pow(10, Math.round(log10(step))),
  5530. step2 = 2 * Math.pow(10, Math.round(log10(step / 2))),
  5531. step5 = 5 * Math.pow(10, Math.round(log10(step / 5)));
  5532. // choose the best step (closest to minimum step)
  5533. var prettyStep = step1;
  5534. if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2;
  5535. if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5;
  5536. // for safety
  5537. if (prettyStep <= 0) {
  5538. prettyStep = 1;
  5539. }
  5540. return prettyStep;
  5541. };
  5542. /**
  5543. * returns the current value of the step
  5544. * @return {Number} current value
  5545. */
  5546. StepNumber.prototype.getCurrent = function () {
  5547. return parseFloat(this._current.toPrecision(this.precision));
  5548. };
  5549. /**
  5550. * returns the current step size
  5551. * @return {Number} current step size
  5552. */
  5553. StepNumber.prototype.getStep = function () {
  5554. return this._step;
  5555. };
  5556. /**
  5557. * Set the current value to the largest value smaller than start, which
  5558. * is a multiple of the step size
  5559. */
  5560. StepNumber.prototype.start = function() {
  5561. this._current = this._start - this._start % this._step;
  5562. };
  5563. /**
  5564. * Do a step, add the step size to the current value
  5565. */
  5566. StepNumber.prototype.next = function () {
  5567. this._current += this._step;
  5568. };
  5569. /**
  5570. * Returns true whether the end is reached
  5571. * @return {boolean} True if the current value has passed the end value.
  5572. */
  5573. StepNumber.prototype.end = function () {
  5574. return (this._current > this._end);
  5575. };
  5576. module.exports = StepNumber;
  5577. /***/ },
  5578. /* 13 */
  5579. /***/ function(module, exports, __webpack_require__) {
  5580. var Emitter = __webpack_require__(56);
  5581. var Hammer = __webpack_require__(45);
  5582. var util = __webpack_require__(1);
  5583. var DataSet = __webpack_require__(3);
  5584. var DataView = __webpack_require__(4);
  5585. var Range = __webpack_require__(17);
  5586. var Core = __webpack_require__(46);
  5587. var TimeAxis = __webpack_require__(30);
  5588. var CurrentTime = __webpack_require__(21);
  5589. var CustomTime = __webpack_require__(22);
  5590. var ItemSet = __webpack_require__(27);
  5591. /**
  5592. * Create a timeline visualization
  5593. * @param {HTMLElement} container
  5594. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  5595. * @param {vis.DataSet | Array | google.visualization.DataTable} [groups]
  5596. * @param {Object} [options] See Timeline.setOptions for the available options.
  5597. * @constructor
  5598. * @extends Core
  5599. */
  5600. function Timeline (container, items, groups, options) {
  5601. if (!(this instanceof Timeline)) {
  5602. throw new SyntaxError('Constructor must be called with the new operator');
  5603. }
  5604. // if the third element is options, the forth is groups (optionally);
  5605. if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) {
  5606. var forthArgument = options;
  5607. options = groups;
  5608. groups = forthArgument;
  5609. }
  5610. var me = this;
  5611. this.defaultOptions = {
  5612. start: null,
  5613. end: null,
  5614. autoResize: true,
  5615. orientation: 'bottom',
  5616. width: null,
  5617. height: null,
  5618. maxHeight: null,
  5619. minHeight: null
  5620. };
  5621. this.options = util.deepExtend({}, this.defaultOptions);
  5622. // Create the DOM, props, and emitter
  5623. this._create(container);
  5624. // all components listed here will be repainted automatically
  5625. this.components = [];
  5626. this.body = {
  5627. dom: this.dom,
  5628. domProps: this.props,
  5629. emitter: {
  5630. on: this.on.bind(this),
  5631. off: this.off.bind(this),
  5632. emit: this.emit.bind(this)
  5633. },
  5634. hiddenDates: [],
  5635. util: {
  5636. snap: null, // will be specified after TimeAxis is created
  5637. toScreen: me._toScreen.bind(me),
  5638. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  5639. toTime: me._toTime.bind(me),
  5640. toGlobalTime : me._toGlobalTime.bind(me)
  5641. }
  5642. };
  5643. // range
  5644. this.range = new Range(this.body);
  5645. this.components.push(this.range);
  5646. this.body.range = this.range;
  5647. // time axis
  5648. this.timeAxis = new TimeAxis(this.body);
  5649. this.components.push(this.timeAxis);
  5650. this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
  5651. // current time bar
  5652. this.currentTime = new CurrentTime(this.body);
  5653. this.components.push(this.currentTime);
  5654. // custom time bar
  5655. // Note: time bar will be attached in this.setOptions when selected
  5656. this.customTime = new CustomTime(this.body);
  5657. this.components.push(this.customTime);
  5658. // item set
  5659. this.itemSet = new ItemSet(this.body);
  5660. this.components.push(this.itemSet);
  5661. this.itemsData = null; // DataSet
  5662. this.groupsData = null; // DataSet
  5663. // apply options
  5664. if (options) {
  5665. this.setOptions(options);
  5666. }
  5667. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  5668. if (groups) {
  5669. this.setGroups(groups);
  5670. }
  5671. // create itemset
  5672. if (items) {
  5673. this.setItems(items);
  5674. }
  5675. else {
  5676. this.redraw();
  5677. }
  5678. }
  5679. // Extend the functionality from Core
  5680. Timeline.prototype = new Core();
  5681. /**
  5682. * Set items
  5683. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  5684. */
  5685. Timeline.prototype.setItems = function(items) {
  5686. var initialLoad = (this.itemsData == null);
  5687. // convert to type DataSet when needed
  5688. var newDataSet;
  5689. if (!items) {
  5690. newDataSet = null;
  5691. }
  5692. else if (items instanceof DataSet || items instanceof DataView) {
  5693. newDataSet = items;
  5694. }
  5695. else {
  5696. // turn an array into a dataset
  5697. newDataSet = new DataSet(items, {
  5698. type: {
  5699. start: 'Date',
  5700. end: 'Date'
  5701. }
  5702. });
  5703. }
  5704. // set items
  5705. this.itemsData = newDataSet;
  5706. this.itemSet && this.itemSet.setItems(newDataSet);
  5707. if (initialLoad) {
  5708. if (this.options.start != undefined || this.options.end != undefined) {
  5709. if (this.options.start == undefined || this.options.end == undefined) {
  5710. var dataRange = this._getDataRange();
  5711. }
  5712. var start = this.options.start != undefined ? this.options.start : dataRange.start;
  5713. var end = this.options.end != undefined ? this.options.end : dataRange.end;
  5714. this.setWindow(start, end, {animate: false});
  5715. }
  5716. else {
  5717. this.fit({animate: false});
  5718. }
  5719. }
  5720. };
  5721. /**
  5722. * Set groups
  5723. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  5724. */
  5725. Timeline.prototype.setGroups = function(groups) {
  5726. // convert to type DataSet when needed
  5727. var newDataSet;
  5728. if (!groups) {
  5729. newDataSet = null;
  5730. }
  5731. else if (groups instanceof DataSet || groups instanceof DataView) {
  5732. newDataSet = groups;
  5733. }
  5734. else {
  5735. // turn an array into a dataset
  5736. newDataSet = new DataSet(groups);
  5737. }
  5738. this.groupsData = newDataSet;
  5739. this.itemSet.setGroups(newDataSet);
  5740. };
  5741. /**
  5742. * Set selected items by their id. Replaces the current selection
  5743. * Unknown id's are silently ignored.
  5744. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  5745. * selected. If ids is an empty array, all items will be
  5746. * unselected.
  5747. * @param {Object} [options] Available options:
  5748. * `focus: boolean`
  5749. * If true, focus will be set to the selected item(s)
  5750. * `animate: boolean | number`
  5751. * If true (default), the range is animated
  5752. * smoothly to the new window.
  5753. * If a number, the number is taken as duration
  5754. * for the animation. Default duration is 500 ms.
  5755. * Only applicable when option focus is true.
  5756. */
  5757. Timeline.prototype.setSelection = function(ids, options) {
  5758. this.itemSet && this.itemSet.setSelection(ids);
  5759. if (options && options.focus) {
  5760. this.focus(ids, options);
  5761. }
  5762. };
  5763. /**
  5764. * Get the selected items by their id
  5765. * @return {Array} ids The ids of the selected items
  5766. */
  5767. Timeline.prototype.getSelection = function() {
  5768. return this.itemSet && this.itemSet.getSelection() || [];
  5769. };
  5770. /**
  5771. * Adjust the visible window such that the selected item (or multiple items)
  5772. * are centered on screen.
  5773. * @param {String | String[]} id An item id or array with item ids
  5774. * @param {Object} [options] Available options:
  5775. * `animate: boolean | number`
  5776. * If true (default), the range is animated
  5777. * smoothly to the new window.
  5778. * If a number, the number is taken as duration
  5779. * for the animation. Default duration is 500 ms.
  5780. * Only applicable when option focus is true
  5781. */
  5782. Timeline.prototype.focus = function(id, options) {
  5783. if (!this.itemsData || id == undefined) return;
  5784. var ids = Array.isArray(id) ? id : [id];
  5785. // get the specified item(s)
  5786. var itemsData = this.itemsData.getDataSet().get(ids, {
  5787. type: {
  5788. start: 'Date',
  5789. end: 'Date'
  5790. }
  5791. });
  5792. // calculate minimum start and maximum end of specified items
  5793. var start = null;
  5794. var end = null;
  5795. itemsData.forEach(function (itemData) {
  5796. var s = itemData.start.valueOf();
  5797. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  5798. if (start === null || s < start) {
  5799. start = s;
  5800. }
  5801. if (end === null || e > end) {
  5802. end = e;
  5803. }
  5804. });
  5805. if (start !== null && end !== null) {
  5806. // calculate the new middle and interval for the window
  5807. var middle = (start + end) / 2;
  5808. var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
  5809. var animate = (options && options.animate !== undefined) ? options.animate : true;
  5810. this.range.setRange(middle - interval / 2, middle + interval / 2, animate);
  5811. }
  5812. };
  5813. /**
  5814. * Get the data range of the item set.
  5815. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  5816. * When no minimum is found, min==null
  5817. * When no maximum is found, max==null
  5818. */
  5819. Timeline.prototype.getItemRange = function() {
  5820. // calculate min from start filed
  5821. var dataset = this.itemsData.getDataSet(),
  5822. min = null,
  5823. max = null;
  5824. if (dataset) {
  5825. // calculate the minimum value of the field 'start'
  5826. var minItem = dataset.min('start');
  5827. min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null;
  5828. // Note: we convert first to Date and then to number because else
  5829. // a conversion from ISODate to Number will fail
  5830. // calculate maximum value of fields 'start' and 'end'
  5831. var maxStartItem = dataset.max('start');
  5832. if (maxStartItem) {
  5833. max = util.convert(maxStartItem.start, 'Date').valueOf();
  5834. }
  5835. var maxEndItem = dataset.max('end');
  5836. if (maxEndItem) {
  5837. if (max == null) {
  5838. max = util.convert(maxEndItem.end, 'Date').valueOf();
  5839. }
  5840. else {
  5841. max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf());
  5842. }
  5843. }
  5844. }
  5845. return {
  5846. min: (min != null) ? new Date(min) : null,
  5847. max: (max != null) ? new Date(max) : null
  5848. };
  5849. };
  5850. module.exports = Timeline;
  5851. /***/ },
  5852. /* 14 */
  5853. /***/ function(module, exports, __webpack_require__) {
  5854. var Emitter = __webpack_require__(56);
  5855. var Hammer = __webpack_require__(45);
  5856. var util = __webpack_require__(1);
  5857. var DataSet = __webpack_require__(3);
  5858. var DataView = __webpack_require__(4);
  5859. var Range = __webpack_require__(17);
  5860. var Core = __webpack_require__(46);
  5861. var TimeAxis = __webpack_require__(30);
  5862. var CurrentTime = __webpack_require__(21);
  5863. var CustomTime = __webpack_require__(22);
  5864. var LineGraph = __webpack_require__(29);
  5865. /**
  5866. * Create a timeline visualization
  5867. * @param {HTMLElement} container
  5868. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  5869. * @param {Object} [options] See Graph2d.setOptions for the available options.
  5870. * @constructor
  5871. * @extends Core
  5872. */
  5873. function Graph2d (container, items, groups, options) {
  5874. // if the third element is options, the forth is groups (optionally);
  5875. if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) {
  5876. var forthArgument = options;
  5877. options = groups;
  5878. groups = forthArgument;
  5879. }
  5880. var me = this;
  5881. this.defaultOptions = {
  5882. start: null,
  5883. end: null,
  5884. autoResize: true,
  5885. orientation: 'bottom',
  5886. width: null,
  5887. height: null,
  5888. maxHeight: null,
  5889. minHeight: null
  5890. };
  5891. this.options = util.deepExtend({}, this.defaultOptions);
  5892. // Create the DOM, props, and emitter
  5893. this._create(container);
  5894. // all components listed here will be repainted automatically
  5895. this.components = [];
  5896. this.body = {
  5897. dom: this.dom,
  5898. domProps: this.props,
  5899. emitter: {
  5900. on: this.on.bind(this),
  5901. off: this.off.bind(this),
  5902. emit: this.emit.bind(this)
  5903. },
  5904. hiddenDates: [],
  5905. util: {
  5906. snap: null, // will be specified after TimeAxis is created
  5907. toScreen: me._toScreen.bind(me),
  5908. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  5909. toTime: me._toTime.bind(me),
  5910. toGlobalTime : me._toGlobalTime.bind(me)
  5911. }
  5912. };
  5913. // range
  5914. this.range = new Range(this.body);
  5915. this.components.push(this.range);
  5916. this.body.range = this.range;
  5917. // time axis
  5918. this.timeAxis = new TimeAxis(this.body);
  5919. this.components.push(this.timeAxis);
  5920. this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
  5921. // current time bar
  5922. this.currentTime = new CurrentTime(this.body);
  5923. this.components.push(this.currentTime);
  5924. // custom time bar
  5925. // Note: time bar will be attached in this.setOptions when selected
  5926. this.customTime = new CustomTime(this.body);
  5927. this.components.push(this.customTime);
  5928. // item set
  5929. this.linegraph = new LineGraph(this.body);
  5930. this.components.push(this.linegraph);
  5931. this.itemsData = null; // DataSet
  5932. this.groupsData = null; // DataSet
  5933. // apply options
  5934. if (options) {
  5935. this.setOptions(options);
  5936. }
  5937. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  5938. if (groups) {
  5939. this.setGroups(groups);
  5940. }
  5941. // create itemset
  5942. if (items) {
  5943. this.setItems(items);
  5944. }
  5945. else {
  5946. this.redraw();
  5947. }
  5948. }
  5949. // Extend the functionality from Core
  5950. Graph2d.prototype = new Core();
  5951. /**
  5952. * Set items
  5953. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  5954. */
  5955. Graph2d.prototype.setItems = function(items) {
  5956. var initialLoad = (this.itemsData == null);
  5957. // convert to type DataSet when needed
  5958. var newDataSet;
  5959. if (!items) {
  5960. newDataSet = null;
  5961. }
  5962. else if (items instanceof DataSet || items instanceof DataView) {
  5963. newDataSet = items;
  5964. }
  5965. else {
  5966. // turn an array into a dataset
  5967. newDataSet = new DataSet(items, {
  5968. type: {
  5969. start: 'Date',
  5970. end: 'Date'
  5971. }
  5972. });
  5973. }
  5974. // set items
  5975. this.itemsData = newDataSet;
  5976. this.linegraph && this.linegraph.setItems(newDataSet);
  5977. if (initialLoad) {
  5978. if (this.options.start != undefined || this.options.end != undefined) {
  5979. var start = this.options.start != undefined ? this.options.start : null;
  5980. var end = this.options.end != undefined ? this.options.end : null;
  5981. this.setWindow(start, end, {animate: false});
  5982. }
  5983. else {
  5984. this.fit({animate: false});
  5985. }
  5986. }
  5987. };
  5988. /**
  5989. * Set groups
  5990. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  5991. */
  5992. Graph2d.prototype.setGroups = function(groups) {
  5993. // convert to type DataSet when needed
  5994. var newDataSet;
  5995. if (!groups) {
  5996. newDataSet = null;
  5997. }
  5998. else if (groups instanceof DataSet || groups instanceof DataView) {
  5999. newDataSet = groups;
  6000. }
  6001. else {
  6002. // turn an array into a dataset
  6003. newDataSet = new DataSet(groups);
  6004. }
  6005. this.groupsData = newDataSet;
  6006. this.linegraph.setGroups(newDataSet);
  6007. };
  6008. /**
  6009. * 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).
  6010. * @param groupId
  6011. * @param width
  6012. * @param height
  6013. */
  6014. Graph2d.prototype.getLegend = function(groupId, width, height) {
  6015. if (width === undefined) {width = 15;}
  6016. if (height === undefined) {height = 15;}
  6017. if (this.linegraph.groups[groupId] !== undefined) {
  6018. return this.linegraph.groups[groupId].getLegend(width,height);
  6019. }
  6020. else {
  6021. return "cannot find group:" + groupId;
  6022. }
  6023. }
  6024. /**
  6025. * This checks if the visible option of the supplied group (by ID) is true or false.
  6026. * @param groupId
  6027. * @returns {*}
  6028. */
  6029. Graph2d.prototype.isGroupVisible = function(groupId) {
  6030. if (this.linegraph.groups[groupId] !== undefined) {
  6031. return (this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true));
  6032. }
  6033. else {
  6034. return false;
  6035. }
  6036. }
  6037. /**
  6038. * Get the data range of the item set.
  6039. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6040. * When no minimum is found, min==null
  6041. * When no maximum is found, max==null
  6042. */
  6043. Graph2d.prototype.getItemRange = function() {
  6044. var min = null;
  6045. var max = null;
  6046. // calculate min from start filed
  6047. for (var groupId in this.linegraph.groups) {
  6048. if (this.linegraph.groups.hasOwnProperty(groupId)) {
  6049. if (this.linegraph.groups[groupId].visible == true) {
  6050. for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) {
  6051. var item = this.linegraph.groups[groupId].itemsData[i];
  6052. var value = util.convert(item.x, 'Date').valueOf();
  6053. min = min == null ? value : min > value ? value : min;
  6054. max = max == null ? value : max < value ? value : max;
  6055. }
  6056. }
  6057. }
  6058. }
  6059. return {
  6060. min: (min != null) ? new Date(min) : null,
  6061. max: (max != null) ? new Date(max) : null
  6062. };
  6063. };
  6064. module.exports = Graph2d;
  6065. /***/ },
  6066. /* 15 */
  6067. /***/ function(module, exports, __webpack_require__) {
  6068. /**
  6069. * Created by Alex on 10/3/2014.
  6070. */
  6071. var moment = __webpack_require__(44);
  6072. /**
  6073. * used in Core to convert the options into a volatile variable
  6074. *
  6075. * @param Core
  6076. */
  6077. exports.convertHiddenOptions = function(body, hiddenDates) {
  6078. body.hiddenDates = [];
  6079. if (hiddenDates) {
  6080. if (Array.isArray(hiddenDates) == true) {
  6081. for (var i = 0; i < hiddenDates.length; i++) {
  6082. if (hiddenDates[i].repeat === undefined) {
  6083. var dateItem = {};
  6084. dateItem.start = moment(hiddenDates[i].start).toDate().valueOf();
  6085. dateItem.end = moment(hiddenDates[i].end).toDate().valueOf();
  6086. body.hiddenDates.push(dateItem);
  6087. }
  6088. }
  6089. body.hiddenDates.sort(function (a, b) {
  6090. return a.start - b.start;
  6091. }); // sort by start time
  6092. }
  6093. }
  6094. };
  6095. /**
  6096. * create new entrees for the repeating hidden dates
  6097. * @param body
  6098. * @param hiddenDates
  6099. */
  6100. exports.updateHiddenDates = function (body, hiddenDates) {
  6101. if (hiddenDates && body.domProps.centerContainer.width !== undefined) {
  6102. exports.convertHiddenOptions(body, hiddenDates);
  6103. var start = moment(body.range.start);
  6104. var end = moment(body.range.end);
  6105. var totalRange = (body.range.end - body.range.start);
  6106. var pixelTime = totalRange / body.domProps.centerContainer.width;
  6107. for (var i = 0; i < hiddenDates.length; i++) {
  6108. if (hiddenDates[i].repeat !== undefined) {
  6109. var startDate = moment(hiddenDates[i].start);
  6110. var endDate = moment(hiddenDates[i].end);
  6111. if (startDate._d == "Invalid Date") {
  6112. throw new Error("Supplied start date is not valid: " + hiddenDates[i].start);
  6113. }
  6114. if (endDate._d == "Invalid Date") {
  6115. throw new Error("Supplied end date is not valid: " + hiddenDates[i].end);
  6116. }
  6117. var duration = endDate - startDate;
  6118. if (duration >= 4 * pixelTime) {
  6119. var offset = 0;
  6120. var runUntil = end.clone();
  6121. switch (hiddenDates[i].repeat) {
  6122. case "daily": // case of time
  6123. if (startDate.day() != endDate.day()) {
  6124. offset = 1;
  6125. }
  6126. startDate.dayOfYear(start.dayOfYear());
  6127. startDate.year(start.year());
  6128. startDate.subtract(7,'days');
  6129. endDate.dayOfYear(start.dayOfYear());
  6130. endDate.year(start.year());
  6131. endDate.subtract(7 - offset,'days');
  6132. runUntil.add(1, 'weeks');
  6133. break;
  6134. case "weekly":
  6135. var dayOffset = endDate.diff(startDate,'days')
  6136. var day = startDate.day();
  6137. // set the start date to the range.start
  6138. startDate.date(start.date());
  6139. startDate.month(start.month());
  6140. startDate.year(start.year());
  6141. endDate = startDate.clone();
  6142. // force
  6143. startDate.day(day);
  6144. endDate.day(day);
  6145. endDate.add(dayOffset,'days');
  6146. startDate.subtract(1,'weeks');
  6147. endDate.subtract(1,'weeks');
  6148. runUntil.add(1, 'weeks');
  6149. break
  6150. case "monthly":
  6151. if (startDate.month() != endDate.month()) {
  6152. offset = 1;
  6153. }
  6154. startDate.month(start.month());
  6155. startDate.year(start.year());
  6156. startDate.subtract(1,'months');
  6157. endDate.month(start.month());
  6158. endDate.year(start.year());
  6159. endDate.subtract(1,'months');
  6160. endDate.add(offset,'months');
  6161. runUntil.add(1, 'months');
  6162. break;
  6163. case "yearly":
  6164. if (startDate.year() != endDate.year()) {
  6165. offset = 1;
  6166. }
  6167. startDate.year(start.year());
  6168. startDate.subtract(1,'years');
  6169. endDate.year(start.year());
  6170. endDate.subtract(1,'years');
  6171. endDate.add(offset,'years');
  6172. runUntil.add(1, 'years');
  6173. break;
  6174. default:
  6175. console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
  6176. return;
  6177. }
  6178. while (startDate < runUntil) {
  6179. body.hiddenDates.push({start: startDate.valueOf(), end: endDate.valueOf()});
  6180. switch (hiddenDates[i].repeat) {
  6181. case "daily":
  6182. startDate.add(1, 'days');
  6183. endDate.add(1, 'days');
  6184. break;
  6185. case "weekly":
  6186. startDate.add(1, 'weeks');
  6187. endDate.add(1, 'weeks');
  6188. break
  6189. case "monthly":
  6190. startDate.add(1, 'months');
  6191. endDate.add(1, 'months');
  6192. break;
  6193. case "yearly":
  6194. startDate.add(1, 'y');
  6195. endDate.add(1, 'y');
  6196. break;
  6197. default:
  6198. console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
  6199. return;
  6200. }
  6201. }
  6202. body.hiddenDates.push({start: startDate.valueOf(), end: endDate.valueOf()});
  6203. }
  6204. }
  6205. }
  6206. // remove duplicates, merge where possible
  6207. exports.removeDuplicates(body);
  6208. // ensure the new positions are not on hidden dates
  6209. var startHidden = exports.isHidden(body.range.start, body.hiddenDates);
  6210. var endHidden = exports.isHidden(body.range.end,body.hiddenDates);
  6211. var rangeStart = body.range.start;
  6212. var rangeEnd = body.range.end;
  6213. if (startHidden.hidden == true) {rangeStart = body.range.startToFront == true ? startHidden.startDate - 1 : startHidden.endDate + 1;}
  6214. if (endHidden.hidden == true) {rangeEnd = body.range.endToFront == true ? endHidden.startDate - 1 : endHidden.endDate + 1;}
  6215. if (startHidden.hidden == true || endHidden.hidden == true) {
  6216. body.range._applyRange(rangeStart, rangeEnd);
  6217. }
  6218. }
  6219. }
  6220. /**
  6221. * remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up.
  6222. * Scales with N^2
  6223. * @param body
  6224. */
  6225. exports.removeDuplicates = function(body) {
  6226. var hiddenDates = body.hiddenDates;
  6227. var safeDates = [];
  6228. for (var i = 0; i < hiddenDates.length; i++) {
  6229. for (var j = 0; j < hiddenDates.length; j++) {
  6230. if (i != j && hiddenDates[j].remove != true && hiddenDates[i].remove != true) {
  6231. // j inside i
  6232. if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
  6233. hiddenDates[j].remove = true;
  6234. }
  6235. // j start inside i
  6236. else if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].start <= hiddenDates[i].end) {
  6237. hiddenDates[i].end = hiddenDates[j].end;
  6238. hiddenDates[j].remove = true;
  6239. }
  6240. // j end inside i
  6241. else if (hiddenDates[j].end >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
  6242. hiddenDates[i].start = hiddenDates[j].start;
  6243. hiddenDates[j].remove = true;
  6244. }
  6245. }
  6246. }
  6247. }
  6248. for (var i = 0; i < hiddenDates.length; i++) {
  6249. if (hiddenDates[i].remove !== true) {
  6250. safeDates.push(hiddenDates[i]);
  6251. }
  6252. }
  6253. body.hiddenDates = safeDates;
  6254. body.hiddenDates.sort(function (a, b) {
  6255. return a.start - b.start;
  6256. }); // sort by start time
  6257. }
  6258. exports.printDates = function(dates) {
  6259. for (var i =0; i < dates.length; i++) {
  6260. console.log(i, new Date(dates[i].start),new Date(dates[i].end), dates[i].start, dates[i].end, dates[i].remove);
  6261. }
  6262. }
  6263. /**
  6264. * Used in TimeStep to avoid the hidden times.
  6265. * @param timeStep
  6266. * @param previousTime
  6267. */
  6268. exports.stepOverHiddenDates = function(timeStep, previousTime) {
  6269. var stepInHidden = false;
  6270. var currentValue = timeStep.current.valueOf();
  6271. for (var i = 0; i < timeStep.hiddenDates.length; i++) {
  6272. var startDate = timeStep.hiddenDates[i].start;
  6273. var endDate = timeStep.hiddenDates[i].end;
  6274. if (currentValue >= startDate && currentValue < endDate) {
  6275. stepInHidden = true;
  6276. break;
  6277. }
  6278. }
  6279. if (stepInHidden == true && currentValue < timeStep._end.valueOf() && currentValue != previousTime) {
  6280. var prevValue = moment(previousTime);
  6281. var newValue = moment(endDate);
  6282. //check if the next step should be major
  6283. if (prevValue.year() != newValue.year()) {timeStep.switchedYear = true;}
  6284. else if (prevValue.month() != newValue.month()) {timeStep.switchedMonth = true;}
  6285. else if (prevValue.dayOfYear() != newValue.dayOfYear()) {timeStep.switchedDay = true;}
  6286. timeStep.current = newValue.toDate();
  6287. }
  6288. };
  6289. ///**
  6290. // * Used in TimeStep to avoid the hidden times.
  6291. // * @param timeStep
  6292. // * @param previousTime
  6293. // */
  6294. //exports.checkFirstStep = function(timeStep) {
  6295. // var stepInHidden = false;
  6296. // var currentValue = timeStep.current.valueOf();
  6297. // for (var i = 0; i < timeStep.hiddenDates.length; i++) {
  6298. // var startDate = timeStep.hiddenDates[i].start;
  6299. // var endDate = timeStep.hiddenDates[i].end;
  6300. // if (currentValue >= startDate && currentValue < endDate) {
  6301. // stepInHidden = true;
  6302. // break;
  6303. // }
  6304. // }
  6305. //
  6306. // if (stepInHidden == true && currentValue <= timeStep._end.valueOf()) {
  6307. // var newValue = moment(endDate);
  6308. // timeStep.current = newValue.toDate();
  6309. // }
  6310. //};
  6311. /**
  6312. * replaces the Core toScreen methods
  6313. * @param Core
  6314. * @param time
  6315. * @param width
  6316. * @returns {number}
  6317. */
  6318. exports.toScreen = function(Core, time, width) {
  6319. if (Core.body.hiddenDates.length == 0) {
  6320. var conversion = Core.range.conversion(width);
  6321. return (time.valueOf() - conversion.offset) * conversion.scale;
  6322. }
  6323. else {
  6324. var hidden = exports.isHidden(time, Core.body.hiddenDates)
  6325. if (hidden.hidden == true) {
  6326. time = hidden.startDate;
  6327. }
  6328. var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
  6329. time = exports.correctTimeForHidden(Core.body.hiddenDates, Core.range, time);
  6330. var conversion = Core.range.conversion(width, duration);
  6331. return (time.valueOf() - conversion.offset) * conversion.scale;
  6332. }
  6333. };
  6334. /**
  6335. * Replaces the core toTime methods
  6336. * @param body
  6337. * @param range
  6338. * @param x
  6339. * @param width
  6340. * @returns {Date}
  6341. */
  6342. exports.toTime = function(Core, x, width) {
  6343. if (Core.body.hiddenDates.length == 0) {
  6344. var conversion = Core.range.conversion(width);
  6345. return new Date(x / conversion.scale + conversion.offset);
  6346. }
  6347. else {
  6348. var hiddenDuration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
  6349. var totalDuration = Core.range.end - Core.range.start - hiddenDuration;
  6350. var partialDuration = totalDuration * x / width;
  6351. var accumulatedHiddenDuration = exports.getAccumulatedHiddenDuration(Core.body.hiddenDates, Core.range, partialDuration);
  6352. var newTime = new Date(accumulatedHiddenDuration + partialDuration + Core.range.start);
  6353. return newTime;
  6354. }
  6355. };
  6356. /**
  6357. * Support function
  6358. *
  6359. * @param hiddenDates
  6360. * @param range
  6361. * @returns {number}
  6362. */
  6363. exports.getHiddenDurationBetween = function(hiddenDates, start, end) {
  6364. var duration = 0;
  6365. for (var i = 0; i < hiddenDates.length; i++) {
  6366. var startDate = hiddenDates[i].start;
  6367. var endDate = hiddenDates[i].end;
  6368. // if time after the cutout, and the
  6369. if (startDate >= start && endDate < end) {
  6370. duration += endDate - startDate;
  6371. }
  6372. }
  6373. return duration;
  6374. };
  6375. /**
  6376. * Support function
  6377. * @param hiddenDates
  6378. * @param range
  6379. * @param time
  6380. * @returns {{duration: number, time: *, offset: number}}
  6381. */
  6382. exports.correctTimeForHidden = function(hiddenDates, range, time) {
  6383. time = moment(time).toDate().valueOf();
  6384. time -= exports.getHiddenDurationBefore(hiddenDates,range,time);
  6385. return time;
  6386. };
  6387. exports.getHiddenDurationBefore = function(hiddenDates, range, time) {
  6388. var timeOffset = 0;
  6389. time = moment(time).toDate().valueOf();
  6390. for (var i = 0; i < hiddenDates.length; i++) {
  6391. var startDate = hiddenDates[i].start;
  6392. var endDate = hiddenDates[i].end;
  6393. // if time after the cutout, and the
  6394. if (startDate >= range.start && endDate < range.end) {
  6395. if (time >= endDate) {
  6396. timeOffset += (endDate - startDate);
  6397. }
  6398. }
  6399. }
  6400. return timeOffset;
  6401. }
  6402. /**
  6403. * sum the duration from start to finish, including the hidden duration,
  6404. * until the required amount has been reached, return the accumulated hidden duration
  6405. * @param hiddenDates
  6406. * @param range
  6407. * @param time
  6408. * @returns {{duration: number, time: *, offset: number}}
  6409. */
  6410. exports.getAccumulatedHiddenDuration = function(hiddenDates, range, requiredDuration) {
  6411. var hiddenDuration = 0;
  6412. var duration = 0;
  6413. var previousPoint = range.start;
  6414. //exports.printDates(hiddenDates)
  6415. for (var i = 0; i < hiddenDates.length; i++) {
  6416. var startDate = hiddenDates[i].start;
  6417. var endDate = hiddenDates[i].end;
  6418. // if time after the cutout, and the
  6419. if (startDate >= range.start && endDate < range.end) {
  6420. duration += startDate - previousPoint;
  6421. previousPoint = endDate;
  6422. if (duration >= requiredDuration) {
  6423. break;
  6424. }
  6425. else {
  6426. hiddenDuration += endDate - startDate;
  6427. }
  6428. }
  6429. }
  6430. return hiddenDuration;
  6431. };
  6432. /**
  6433. * used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true
  6434. * @param hiddenDates
  6435. * @param time
  6436. * @param direction
  6437. * @param correctionEnabled
  6438. * @returns {*}
  6439. */
  6440. exports.snapAwayFromHidden = function(hiddenDates, time, direction, correctionEnabled) {
  6441. var isHidden = exports.isHidden(time, hiddenDates);
  6442. if (isHidden.hidden == true) {
  6443. if (direction < 0) {
  6444. if (correctionEnabled == true) {
  6445. return isHidden.startDate - (isHidden.endDate - time) - 1;
  6446. }
  6447. else {
  6448. return isHidden.startDate - 1;
  6449. }
  6450. }
  6451. else {
  6452. if (correctionEnabled == true) {
  6453. return isHidden.endDate + (time - isHidden.startDate) + 1;
  6454. }
  6455. else {
  6456. return isHidden.endDate + 1;
  6457. }
  6458. }
  6459. }
  6460. else {
  6461. return time;
  6462. }
  6463. }
  6464. /**
  6465. * Check if a time is hidden
  6466. *
  6467. * @param time
  6468. * @param hiddenDates
  6469. * @returns {{hidden: boolean, startDate: Window.start, endDate: *}}
  6470. */
  6471. exports.isHidden = function(time, hiddenDates) {
  6472. for (var i = 0; i < hiddenDates.length; i++) {
  6473. var startDate = hiddenDates[i].start;
  6474. var endDate = hiddenDates[i].end;
  6475. if (time >= startDate && time < endDate) { // if the start is entering a hidden zone
  6476. return {hidden: true, startDate: startDate, endDate: endDate};
  6477. break;
  6478. }
  6479. }
  6480. return {hidden: false, startDate: startDate, endDate: endDate};
  6481. }
  6482. /***/ },
  6483. /* 16 */
  6484. /***/ function(module, exports, __webpack_require__) {
  6485. /**
  6486. * @constructor DataStep
  6487. * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an
  6488. * end data point. The class itself determines the best scale (step size) based on the
  6489. * provided start Date, end Date, and minimumStep.
  6490. *
  6491. * If minimumStep is provided, the step size is chosen as close as possible
  6492. * to the minimumStep but larger than minimumStep. If minimumStep is not
  6493. * provided, the scale is set to 1 DAY.
  6494. * The minimumStep should correspond with the onscreen size of about 6 characters
  6495. *
  6496. * Alternatively, you can set a scale by hand.
  6497. * After creation, you can initialize the class by executing first(). Then you
  6498. * can iterate from the start date to the end date via next(). You can check if
  6499. * the end date is reached with the function hasNext(). After each step, you can
  6500. * retrieve the current date via getCurrent().
  6501. * The DataStep has scales ranging from milliseconds, seconds, minutes, hours,
  6502. * days, to years.
  6503. *
  6504. * Version: 1.2
  6505. *
  6506. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  6507. * or new Date(2010, 9, 21, 23, 45, 00)
  6508. * @param {Date} [end] The end date
  6509. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  6510. */
  6511. function DataStep(start, end, minimumStep, containerHeight, customRange, alignZeros) {
  6512. // variables
  6513. this.current = 0;
  6514. this.autoScale = true;
  6515. this.stepIndex = 0;
  6516. this.step = 1;
  6517. this.scale = 1;
  6518. this.marginStart;
  6519. this.marginEnd;
  6520. this.deadSpace = 0;
  6521. this.majorSteps = [1, 2, 5, 10];
  6522. this.minorSteps = [0.25, 0.5, 1, 2];
  6523. this.alignZeros = alignZeros;
  6524. this.setRange(start, end, minimumStep, containerHeight, customRange);
  6525. }
  6526. /**
  6527. * Set a new range
  6528. * If minimumStep is provided, the step size is chosen as close as possible
  6529. * to the minimumStep but larger than minimumStep. If minimumStep is not
  6530. * provided, the scale is set to 1 DAY.
  6531. * The minimumStep should correspond with the onscreen size of about 6 characters
  6532. * @param {Number} [start] The start date and time.
  6533. * @param {Number} [end] The end date and time.
  6534. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  6535. */
  6536. DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight, customRange) {
  6537. this._start = customRange.min === undefined ? start : customRange.min;
  6538. this._end = customRange.max === undefined ? end : customRange.max;
  6539. if (this._start == this._end) {
  6540. this._start -= 0.75;
  6541. this._end += 1;
  6542. }
  6543. if (this.autoScale == true) {
  6544. this.setMinimumStep(minimumStep, containerHeight);
  6545. }
  6546. this.setFirst(customRange);
  6547. };
  6548. /**
  6549. * Automatically determine the scale that bests fits the provided minimum step
  6550. * @param {Number} [minimumStep] The minimum step size in milliseconds
  6551. */
  6552. DataStep.prototype.setMinimumStep = function(minimumStep, containerHeight) {
  6553. // round to floor
  6554. var size = this._end - this._start;
  6555. var safeSize = size * 1.2;
  6556. var minimumStepValue = minimumStep * (safeSize / containerHeight);
  6557. var orderOfMagnitude = Math.round(Math.log(safeSize)/Math.LN10);
  6558. var minorStepIdx = -1;
  6559. var magnitudefactor = Math.pow(10,orderOfMagnitude);
  6560. var start = 0;
  6561. if (orderOfMagnitude < 0) {
  6562. start = orderOfMagnitude;
  6563. }
  6564. var solutionFound = false;
  6565. for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) {
  6566. magnitudefactor = Math.pow(10,i);
  6567. for (var j = 0; j < this.minorSteps.length; j++) {
  6568. var stepSize = magnitudefactor * this.minorSteps[j];
  6569. if (stepSize >= minimumStepValue) {
  6570. solutionFound = true;
  6571. minorStepIdx = j;
  6572. break;
  6573. }
  6574. }
  6575. if (solutionFound == true) {
  6576. break;
  6577. }
  6578. }
  6579. this.stepIndex = minorStepIdx;
  6580. this.scale = magnitudefactor;
  6581. this.step = magnitudefactor * this.minorSteps[minorStepIdx];
  6582. };
  6583. /**
  6584. * Round the current date to the first minor date value
  6585. * This must be executed once when the current date is set to start Date
  6586. */
  6587. DataStep.prototype.setFirst = function(customRange) {
  6588. if (customRange === undefined) {
  6589. customRange = {};
  6590. }
  6591. var niceStart = customRange.min === undefined ? this._start - (this.scale * 2 * this.minorSteps[this.stepIndex]) : customRange.min;
  6592. var niceEnd = customRange.max === undefined ? this._end + (this.scale * this.minorSteps[this.stepIndex]) : customRange.max;
  6593. this.marginEnd = customRange.max === undefined ? this.roundToMinor(niceEnd) : customRange.max;
  6594. this.marginStart = customRange.min === undefined ? this.roundToMinor(niceStart) : customRange.min;
  6595. // if we need to align the zero's we need to make sure that there is a zero to use.
  6596. if (this.alignZeros == true && (this.marginEnd - this.marginStart) % this.step != 0) {
  6597. this.marginEnd += this.marginEnd % this.step;
  6598. }
  6599. this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart;
  6600. this.marginRange = this.marginEnd - this.marginStart;
  6601. this.current = this.marginEnd;
  6602. };
  6603. DataStep.prototype.roundToMinor = function(value) {
  6604. var rounded = value - (value % (this.scale * this.minorSteps[this.stepIndex]));
  6605. if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) {
  6606. return rounded + (this.scale * this.minorSteps[this.stepIndex]);
  6607. }
  6608. else {
  6609. return rounded;
  6610. }
  6611. }
  6612. /**
  6613. * Check if the there is a next step
  6614. * @return {boolean} true if the current date has not passed the end date
  6615. */
  6616. DataStep.prototype.hasNext = function () {
  6617. return (this.current >= this.marginStart);
  6618. };
  6619. /**
  6620. * Do the next step
  6621. */
  6622. DataStep.prototype.next = function() {
  6623. var prev = this.current;
  6624. this.current -= this.step;
  6625. // safety mechanism: if current time is still unchanged, move to the end
  6626. if (this.current == prev) {
  6627. this.current = this._end;
  6628. }
  6629. };
  6630. /**
  6631. * Do the next step
  6632. */
  6633. DataStep.prototype.previous = function() {
  6634. this.current += this.step;
  6635. this.marginEnd += this.step;
  6636. this.marginRange = this.marginEnd - this.marginStart;
  6637. };
  6638. /**
  6639. * Get the current datetime
  6640. * @return {String} current The current date
  6641. */
  6642. DataStep.prototype.getCurrent = function(decimals) {
  6643. // prevent round-off errors when close to zero
  6644. var current = (Math.abs(this.current) < this.step / 2) ? 0 : this.current;
  6645. var toPrecision = '' + Number(current).toPrecision(5);
  6646. // If decimals is specified, then limit or extend the string as required
  6647. if(decimals !== undefined && !isNaN(Number(decimals))) {
  6648. // If string includes exponent, then we need to add it to the end
  6649. var exp = "";
  6650. var index = toPrecision.indexOf("e");
  6651. if(index != -1) {
  6652. // Get the exponent
  6653. exp = toPrecision.slice(index);
  6654. // Remove the exponent in case we need to zero-extend
  6655. toPrecision = toPrecision.slice(0, index);
  6656. }
  6657. index = Math.max(toPrecision.indexOf(","), toPrecision.indexOf("."));
  6658. if(index === -1) {
  6659. // No decimal found - if we want decimals, then we need to add it
  6660. if(decimals !== 0) {
  6661. toPrecision += '.';
  6662. }
  6663. // Calculate how long the string should be
  6664. index = toPrecision.length + decimals;
  6665. }
  6666. else if(decimals !== 0) {
  6667. // Calculate how long the string should be - accounting for the decimal place
  6668. index += decimals + 1;
  6669. }
  6670. if(index > toPrecision.length) {
  6671. // We need to add zeros!
  6672. for(var cnt = index - toPrecision.length; cnt > 0; cnt--) {
  6673. toPrecision += '0';
  6674. }
  6675. }
  6676. else {
  6677. // we need to remove characters
  6678. toPrecision = toPrecision.slice(0, index);
  6679. }
  6680. // Add the exponent if there is one
  6681. toPrecision += exp;
  6682. }
  6683. else {
  6684. if (toPrecision.indexOf(",") != -1 || toPrecision.indexOf(".") != -1) {
  6685. // If no decimal is specified, and there are decimal places, remove trailing zeros
  6686. for (var i = toPrecision.length - 1; i > 0; i--) {
  6687. if (toPrecision[i] == "0") {
  6688. toPrecision = toPrecision.slice(0, i);
  6689. }
  6690. else if (toPrecision[i] == "." || toPrecision[i] == ",") {
  6691. toPrecision = toPrecision.slice(0, i);
  6692. break;
  6693. }
  6694. else {
  6695. break;
  6696. }
  6697. }
  6698. }
  6699. }
  6700. return toPrecision;
  6701. };
  6702. /**
  6703. * Snap a date to a rounded value.
  6704. * The snap intervals are dependent on the current scale and step.
  6705. * @param {Date} date the date to be snapped.
  6706. * @return {Date} snappedDate
  6707. */
  6708. DataStep.prototype.snap = function(date) {
  6709. };
  6710. /**
  6711. * Check if the current value is a major value (for example when the step
  6712. * is DAY, a major value is each first day of the MONTH)
  6713. * @return {boolean} true if current date is major, else false.
  6714. */
  6715. DataStep.prototype.isMajor = function() {
  6716. return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0);
  6717. };
  6718. module.exports = DataStep;
  6719. /***/ },
  6720. /* 17 */
  6721. /***/ function(module, exports, __webpack_require__) {
  6722. var util = __webpack_require__(1);
  6723. var hammerUtil = __webpack_require__(47);
  6724. var moment = __webpack_require__(44);
  6725. var Component = __webpack_require__(20);
  6726. var DateUtil = __webpack_require__(15);
  6727. /**
  6728. * @constructor Range
  6729. * A Range controls a numeric range with a start and end value.
  6730. * The Range adjusts the range based on mouse events or programmatic changes,
  6731. * and triggers events when the range is changing or has been changed.
  6732. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body
  6733. * @param {Object} [options] See description at Range.setOptions
  6734. */
  6735. function Range(body, options) {
  6736. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6737. this.start = now.clone().add(-3, 'days').valueOf(); // Number
  6738. this.end = now.clone().add(4, 'days').valueOf(); // Number
  6739. this.body = body;
  6740. this.deltaDifference = 0;
  6741. this.scaleOffset = 0;
  6742. this.startToFront = false;
  6743. this.endToFront = true;
  6744. // default options
  6745. this.defaultOptions = {
  6746. start: null,
  6747. end: null,
  6748. direction: 'horizontal', // 'horizontal' or 'vertical'
  6749. moveable: true,
  6750. zoomable: true,
  6751. min: null,
  6752. max: null,
  6753. zoomMin: 10, // milliseconds
  6754. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds
  6755. };
  6756. this.options = util.extend({}, this.defaultOptions);
  6757. this.props = {
  6758. touch: {}
  6759. };
  6760. this.animateTimer = null;
  6761. // drag listeners for dragging
  6762. this.body.emitter.on('dragstart', this._onDragStart.bind(this));
  6763. this.body.emitter.on('drag', this._onDrag.bind(this));
  6764. this.body.emitter.on('dragend', this._onDragEnd.bind(this));
  6765. // ignore dragging when holding
  6766. this.body.emitter.on('hold', this._onHold.bind(this));
  6767. // mouse wheel for zooming
  6768. this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
  6769. this.body.emitter.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  6770. // pinch to zoom
  6771. this.body.emitter.on('touch', this._onTouch.bind(this));
  6772. this.body.emitter.on('pinch', this._onPinch.bind(this));
  6773. this.setOptions(options);
  6774. }
  6775. Range.prototype = new Component();
  6776. /**
  6777. * Set options for the range controller
  6778. * @param {Object} options Available options:
  6779. * {Number | Date | String} start Start date for the range
  6780. * {Number | Date | String} end End date for the range
  6781. * {Number} min Minimum value for start
  6782. * {Number} max Maximum value for end
  6783. * {Number} zoomMin Set a minimum value for
  6784. * (end - start).
  6785. * {Number} zoomMax Set a maximum value for
  6786. * (end - start).
  6787. * {Boolean} moveable Enable moving of the range
  6788. * by dragging. True by default
  6789. * {Boolean} zoomable Enable zooming of the range
  6790. * by pinching/scrolling. True by default
  6791. */
  6792. Range.prototype.setOptions = function (options) {
  6793. if (options) {
  6794. // copy the options that we know
  6795. var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate', 'hiddenDates'];
  6796. util.selectiveExtend(fields, this.options, options);
  6797. if ('start' in options || 'end' in options) {
  6798. // apply a new range. both start and end are optional
  6799. this.setRange(options.start, options.end);
  6800. }
  6801. }
  6802. };
  6803. /**
  6804. * Test whether direction has a valid value
  6805. * @param {String} direction 'horizontal' or 'vertical'
  6806. */
  6807. function validateDirection (direction) {
  6808. if (direction != 'horizontal' && direction != 'vertical') {
  6809. throw new TypeError('Unknown direction "' + direction + '". ' +
  6810. 'Choose "horizontal" or "vertical".');
  6811. }
  6812. }
  6813. /**
  6814. * Set a new start and end range
  6815. * @param {Date | Number | String} [start]
  6816. * @param {Date | Number | String} [end]
  6817. * @param {boolean | number} [animate=false] If true, the range is animated
  6818. * smoothly to the new window.
  6819. * If animate is a number, the
  6820. * number is taken as duration
  6821. * Default duration is 500 ms.
  6822. *
  6823. */
  6824. Range.prototype.setRange = function(start, end, animate) {
  6825. var _start = start != undefined ? util.convert(start, 'Date').valueOf() : null;
  6826. var _end = end != undefined ? util.convert(end, 'Date').valueOf() : null;
  6827. this._cancelAnimation();
  6828. if (animate) {
  6829. var me = this;
  6830. var initStart = this.start;
  6831. var initEnd = this.end;
  6832. var duration = typeof animate === 'number' ? animate : 500;
  6833. var initTime = new Date().valueOf();
  6834. var anyChanged = false;
  6835. var next = function () {
  6836. if (!me.props.touch.dragging) {
  6837. var now = new Date().valueOf();
  6838. var time = now - initTime;
  6839. var done = time > duration;
  6840. var s = (done || _start === null) ? _start : util.easeInOutQuad(time, initStart, _start, duration);
  6841. var e = (done || _end === null) ? _end : util.easeInOutQuad(time, initEnd, _end, duration);
  6842. changed = me._applyRange(s, e);
  6843. DateUtil.updateHiddenDates(me.body, me.options.hiddenDates);
  6844. anyChanged = anyChanged || changed;
  6845. if (changed) {
  6846. me.body.emitter.emit('rangechange', {start: new Date(me.start), end: new Date(me.end)});
  6847. }
  6848. if (done) {
  6849. if (anyChanged) {
  6850. me.body.emitter.emit('rangechanged', {start: new Date(me.start), end: new Date(me.end)});
  6851. }
  6852. }
  6853. else {
  6854. // animate with as high as possible frame rate, leave 20 ms in between
  6855. // each to prevent the browser from blocking
  6856. me.animateTimer = setTimeout(next, 20);
  6857. }
  6858. }
  6859. }
  6860. return next();
  6861. }
  6862. else {
  6863. var changed = this._applyRange(_start, _end);
  6864. DateUtil.updateHiddenDates(this.body, this.options.hiddenDates);
  6865. if (changed) {
  6866. var params = {start: new Date(this.start), end: new Date(this.end)};
  6867. this.body.emitter.emit('rangechange', params);
  6868. this.body.emitter.emit('rangechanged', params);
  6869. }
  6870. }
  6871. };
  6872. /**
  6873. * Stop an animation
  6874. * @private
  6875. */
  6876. Range.prototype._cancelAnimation = function () {
  6877. if (this.animateTimer) {
  6878. clearTimeout(this.animateTimer);
  6879. this.animateTimer = null;
  6880. }
  6881. };
  6882. /**
  6883. * Set a new start and end range. This method is the same as setRange, but
  6884. * does not trigger a range change and range changed event, and it returns
  6885. * true when the range is changed
  6886. * @param {Number} [start]
  6887. * @param {Number} [end]
  6888. * @return {Boolean} changed
  6889. * @private
  6890. */
  6891. Range.prototype._applyRange = function(start, end) {
  6892. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  6893. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  6894. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  6895. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  6896. diff;
  6897. // check for valid number
  6898. if (isNaN(newStart) || newStart === null) {
  6899. throw new Error('Invalid start "' + start + '"');
  6900. }
  6901. if (isNaN(newEnd) || newEnd === null) {
  6902. throw new Error('Invalid end "' + end + '"');
  6903. }
  6904. // prevent start < end
  6905. if (newEnd < newStart) {
  6906. newEnd = newStart;
  6907. }
  6908. // prevent start < min
  6909. if (min !== null) {
  6910. if (newStart < min) {
  6911. diff = (min - newStart);
  6912. newStart += diff;
  6913. newEnd += diff;
  6914. // prevent end > max
  6915. if (max != null) {
  6916. if (newEnd > max) {
  6917. newEnd = max;
  6918. }
  6919. }
  6920. }
  6921. }
  6922. // prevent end > max
  6923. if (max !== null) {
  6924. if (newEnd > max) {
  6925. diff = (newEnd - max);
  6926. newStart -= diff;
  6927. newEnd -= diff;
  6928. // prevent start < min
  6929. if (min != null) {
  6930. if (newStart < min) {
  6931. newStart = min;
  6932. }
  6933. }
  6934. }
  6935. }
  6936. // prevent (end-start) < zoomMin
  6937. if (this.options.zoomMin !== null) {
  6938. var zoomMin = parseFloat(this.options.zoomMin);
  6939. if (zoomMin < 0) {
  6940. zoomMin = 0;
  6941. }
  6942. if ((newEnd - newStart) < zoomMin) {
  6943. if ((this.end - this.start) === zoomMin) {
  6944. // ignore this action, we are already zoomed to the minimum
  6945. newStart = this.start;
  6946. newEnd = this.end;
  6947. }
  6948. else {
  6949. // zoom to the minimum
  6950. diff = (zoomMin - (newEnd - newStart));
  6951. newStart -= diff / 2;
  6952. newEnd += diff / 2;
  6953. }
  6954. }
  6955. }
  6956. // prevent (end-start) > zoomMax
  6957. if (this.options.zoomMax !== null) {
  6958. var zoomMax = parseFloat(this.options.zoomMax);
  6959. if (zoomMax < 0) {
  6960. zoomMax = 0;
  6961. }
  6962. if ((newEnd - newStart) > zoomMax) {
  6963. if ((this.end - this.start) === zoomMax) {
  6964. // ignore this action, we are already zoomed to the maximum
  6965. newStart = this.start;
  6966. newEnd = this.end;
  6967. }
  6968. else {
  6969. // zoom to the maximum
  6970. diff = ((newEnd - newStart) - zoomMax);
  6971. newStart += diff / 2;
  6972. newEnd -= diff / 2;
  6973. }
  6974. }
  6975. }
  6976. var changed = (this.start != newStart || this.end != newEnd);
  6977. // 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 neccesarily of type Range)
  6978. if (!((newStart >= this.start && newStart <= this.end) || (newEnd >= this.start && newEnd <= this.end)) &&
  6979. !((this.start >= newStart && this.start <= newEnd) || (this.end >= newStart && this.end <= newEnd) )) {
  6980. this.body.emitter.emit('checkRangedItems');
  6981. }
  6982. this.start = newStart;
  6983. this.end = newEnd;
  6984. return changed;
  6985. };
  6986. /**
  6987. * Retrieve the current range.
  6988. * @return {Object} An object with start and end properties
  6989. */
  6990. Range.prototype.getRange = function() {
  6991. return {
  6992. start: this.start,
  6993. end: this.end
  6994. };
  6995. };
  6996. /**
  6997. * Calculate the conversion offset and scale for current range, based on
  6998. * the provided width
  6999. * @param {Number} width
  7000. * @returns {{offset: number, scale: number}} conversion
  7001. */
  7002. Range.prototype.conversion = function (width, totalHidden) {
  7003. return Range.conversion(this.start, this.end, width, totalHidden);
  7004. };
  7005. /**
  7006. * Static method to calculate the conversion offset and scale for a range,
  7007. * based on the provided start, end, and width
  7008. * @param {Number} start
  7009. * @param {Number} end
  7010. * @param {Number} width
  7011. * @returns {{offset: number, scale: number}} conversion
  7012. */
  7013. Range.conversion = function (start, end, width, totalHidden) {
  7014. if (totalHidden === undefined) {
  7015. totalHidden = 0;
  7016. }
  7017. if (width != 0 && (end - start != 0)) {
  7018. return {
  7019. offset: start,
  7020. scale: width / (end - start - totalHidden)
  7021. }
  7022. }
  7023. else {
  7024. return {
  7025. offset: 0,
  7026. scale: 1
  7027. };
  7028. }
  7029. };
  7030. /**
  7031. * Start dragging horizontally or vertically
  7032. * @param {Event} event
  7033. * @private
  7034. */
  7035. Range.prototype._onDragStart = function(event) {
  7036. this.deltaDifference = 0;
  7037. this.previousDelta = 0;
  7038. // only allow dragging when configured as movable
  7039. if (!this.options.moveable) return;
  7040. // refuse to drag when we where pinching to prevent the timeline make a jump
  7041. // when releasing the fingers in opposite order from the touch screen
  7042. if (!this.props.touch.allowDragging) return;
  7043. this.props.touch.start = this.start;
  7044. this.props.touch.end = this.end;
  7045. this.props.touch.dragging = true;
  7046. if (this.body.dom.root) {
  7047. this.body.dom.root.style.cursor = 'move';
  7048. }
  7049. };
  7050. /**
  7051. * Perform dragging operation
  7052. * @param {Event} event
  7053. * @private
  7054. */
  7055. Range.prototype._onDrag = function (event) {
  7056. // only allow dragging when configured as movable
  7057. if (!this.options.moveable) return;
  7058. // refuse to drag when we where pinching to prevent the timeline make a jump
  7059. // when releasing the fingers in opposite order from the touch screen
  7060. if (!this.props.touch.allowDragging) return;
  7061. var direction = this.options.direction;
  7062. validateDirection(direction);
  7063. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY;
  7064. delta -= this.deltaDifference;
  7065. var interval = (this.props.touch.end - this.props.touch.start);
  7066. // normalize dragging speed if cutout is in between.
  7067. var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  7068. interval -= duration;
  7069. var width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height;
  7070. var diffRange = -delta / width * interval;
  7071. var newStart = this.props.touch.start + diffRange;
  7072. var newEnd = this.props.touch.end + diffRange;
  7073. // snapping times away from hidden zones
  7074. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, this.previousDelta-delta, true);
  7075. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, this.previousDelta-delta, true);
  7076. if (safeStart != newStart || safeEnd != newEnd) {
  7077. this.deltaDifference += delta;
  7078. this.props.touch.start = safeStart;
  7079. this.props.touch.end = safeEnd;
  7080. this._onDrag(event);
  7081. return;
  7082. }
  7083. this.previousDelta = delta;
  7084. this._applyRange(newStart, newEnd);
  7085. // fire a rangechange event
  7086. this.body.emitter.emit('rangechange', {
  7087. start: new Date(this.start),
  7088. end: new Date(this.end)
  7089. });
  7090. };
  7091. /**
  7092. * Stop dragging operation
  7093. * @param {event} event
  7094. * @private
  7095. */
  7096. Range.prototype._onDragEnd = function (event) {
  7097. // only allow dragging when configured as movable
  7098. if (!this.options.moveable) return;
  7099. // refuse to drag when we where pinching to prevent the timeline make a jump
  7100. // when releasing the fingers in opposite order from the touch screen
  7101. if (!this.props.touch.allowDragging) return;
  7102. this.props.touch.dragging = false;
  7103. if (this.body.dom.root) {
  7104. this.body.dom.root.style.cursor = 'auto';
  7105. }
  7106. // fire a rangechanged event
  7107. this.body.emitter.emit('rangechanged', {
  7108. start: new Date(this.start),
  7109. end: new Date(this.end)
  7110. });
  7111. };
  7112. /**
  7113. * Event handler for mouse wheel event, used to zoom
  7114. * Code from http://adomas.org/javascript-mouse-wheel/
  7115. * @param {Event} event
  7116. * @private
  7117. */
  7118. Range.prototype._onMouseWheel = function(event) {
  7119. // only allow zooming when configured as zoomable and moveable
  7120. if (!(this.options.zoomable && this.options.moveable)) return;
  7121. // retrieve delta
  7122. var delta = 0;
  7123. if (event.wheelDelta) { /* IE/Opera. */
  7124. delta = event.wheelDelta / 120;
  7125. } else if (event.detail) { /* Mozilla case. */
  7126. // In Mozilla, sign of delta is different than in IE.
  7127. // Also, delta is multiple of 3.
  7128. delta = -event.detail / 3;
  7129. }
  7130. // If delta is nonzero, handle it.
  7131. // Basically, delta is now positive if wheel was scrolled up,
  7132. // and negative, if wheel was scrolled down.
  7133. if (delta) {
  7134. // perform the zoom action. Delta is normally 1 or -1
  7135. // adjust a negative delta such that zooming in with delta 0.1
  7136. // equals zooming out with a delta -0.1
  7137. var scale;
  7138. if (delta < 0) {
  7139. scale = 1 - (delta / 5);
  7140. }
  7141. else {
  7142. scale = 1 / (1 + (delta / 5)) ;
  7143. }
  7144. // calculate center, the date to zoom around
  7145. var gesture = hammerUtil.fakeGesture(this, event),
  7146. pointer = getPointer(gesture.center, this.body.dom.center),
  7147. pointerDate = this._pointerToDate(pointer);
  7148. this.zoom(scale, pointerDate, delta);
  7149. }
  7150. // Prevent default actions caused by mouse wheel
  7151. // (else the page and timeline both zoom and scroll)
  7152. event.preventDefault();
  7153. };
  7154. /**
  7155. * Start of a touch gesture
  7156. * @private
  7157. */
  7158. Range.prototype._onTouch = function (event) {
  7159. this.props.touch.start = this.start;
  7160. this.props.touch.end = this.end;
  7161. this.props.touch.allowDragging = true;
  7162. this.props.touch.center = null;
  7163. this.scaleOffset = 0;
  7164. this.deltaDifference = 0;
  7165. };
  7166. /**
  7167. * On start of a hold gesture
  7168. * @private
  7169. */
  7170. Range.prototype._onHold = function () {
  7171. this.props.touch.allowDragging = false;
  7172. };
  7173. /**
  7174. * Handle pinch event
  7175. * @param {Event} event
  7176. * @private
  7177. */
  7178. Range.prototype._onPinch = function (event) {
  7179. // only allow zooming when configured as zoomable and moveable
  7180. if (!(this.options.zoomable && this.options.moveable)) return;
  7181. this.props.touch.allowDragging = false;
  7182. if (event.gesture.touches.length > 1) {
  7183. if (!this.props.touch.center) {
  7184. this.props.touch.center = getPointer(event.gesture.center, this.body.dom.center);
  7185. }
  7186. var scale = 1 / (event.gesture.scale + this.scaleOffset);
  7187. var centerDate = this._pointerToDate(this.props.touch.center);
  7188. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  7189. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, centerDate);
  7190. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  7191. // calculate new start and end
  7192. var newStart = (centerDate - hiddenDurationBefore) + (this.props.touch.start - (centerDate - hiddenDurationBefore)) * scale;
  7193. var newEnd = (centerDate + hiddenDurationAfter) + (this.props.touch.end - (centerDate + hiddenDurationAfter)) * scale;
  7194. // snapping times away from hidden zones
  7195. this.startToFront = 1 - scale > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  7196. this.endToFront = scale - 1 > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  7197. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, 1 - scale, true);
  7198. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, scale - 1, true);
  7199. if (safeStart != newStart || safeEnd != newEnd) {
  7200. this.props.touch.start = safeStart;
  7201. this.props.touch.end = safeEnd;
  7202. this.scaleOffset = 1 - event.gesture.scale;
  7203. newStart = safeStart;
  7204. newEnd = safeEnd;
  7205. }
  7206. this.setRange(newStart, newEnd);
  7207. this.startToFront = false; // revert to default
  7208. this.endToFront = true; // revert to default
  7209. }
  7210. };
  7211. /**
  7212. * Helper function to calculate the center date for zooming
  7213. * @param {{x: Number, y: Number}} pointer
  7214. * @return {number} date
  7215. * @private
  7216. */
  7217. Range.prototype._pointerToDate = function (pointer) {
  7218. var conversion;
  7219. var direction = this.options.direction;
  7220. validateDirection(direction);
  7221. if (direction == 'horizontal') {
  7222. return this.body.util.toTime(pointer.x).valueOf();
  7223. }
  7224. else {
  7225. var height = this.body.domProps.center.height;
  7226. conversion = this.conversion(height);
  7227. return pointer.y / conversion.scale + conversion.offset;
  7228. }
  7229. };
  7230. /**
  7231. * Get the pointer location relative to the location of the dom element
  7232. * @param {{pageX: Number, pageY: Number}} touch
  7233. * @param {Element} element HTML DOM element
  7234. * @return {{x: Number, y: Number}} pointer
  7235. * @private
  7236. */
  7237. function getPointer (touch, element) {
  7238. return {
  7239. x: touch.pageX - util.getAbsoluteLeft(element),
  7240. y: touch.pageY - util.getAbsoluteTop(element)
  7241. };
  7242. }
  7243. /**
  7244. * Zoom the range the given scale in or out. Start and end date will
  7245. * be adjusted, and the timeline will be redrawn. You can optionally give a
  7246. * date around which to zoom.
  7247. * For example, try scale = 0.9 or 1.1
  7248. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  7249. * values below 1 will zoom in.
  7250. * @param {Number} [center] Value representing a date around which will
  7251. * be zoomed.
  7252. */
  7253. Range.prototype.zoom = function(scale, center, delta) {
  7254. // if centerDate is not provided, take it half between start Date and end Date
  7255. if (center == null) {
  7256. center = (this.start + this.end) / 2;
  7257. }
  7258. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  7259. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, center);
  7260. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  7261. // calculate new start and end
  7262. var newStart = (center-hiddenDurationBefore) + (this.start - (center-hiddenDurationBefore)) * scale;
  7263. var newEnd = (center+hiddenDurationAfter) + (this.end - (center+hiddenDurationAfter)) * scale;
  7264. // snapping times away from hidden zones
  7265. this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  7266. this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  7267. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, delta, true);
  7268. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, -delta, true);
  7269. if (safeStart != newStart || safeEnd != newEnd) {
  7270. newStart = safeStart;
  7271. newEnd = safeEnd;
  7272. }
  7273. this.setRange(newStart, newEnd);
  7274. this.startToFront = false; // revert to default
  7275. this.endToFront = true; // revert to default
  7276. };
  7277. /**
  7278. * Move the range with a given delta to the left or right. Start and end
  7279. * value will be adjusted. For example, try delta = 0.1 or -0.1
  7280. * @param {Number} delta Moving amount. Positive value will move right,
  7281. * negative value will move left
  7282. */
  7283. Range.prototype.move = function(delta) {
  7284. // zoom start Date and end Date relative to the centerDate
  7285. var diff = (this.end - this.start);
  7286. // apply new values
  7287. var newStart = this.start + diff * delta;
  7288. var newEnd = this.end + diff * delta;
  7289. // TODO: reckon with min and max range
  7290. this.start = newStart;
  7291. this.end = newEnd;
  7292. };
  7293. /**
  7294. * Move the range to a new center point
  7295. * @param {Number} moveTo New center point of the range
  7296. */
  7297. Range.prototype.moveTo = function(moveTo) {
  7298. var center = (this.start + this.end) / 2;
  7299. var diff = center - moveTo;
  7300. // calculate new start and end
  7301. var newStart = this.start - diff;
  7302. var newEnd = this.end - diff;
  7303. this.setRange(newStart, newEnd);
  7304. };
  7305. module.exports = Range;
  7306. /***/ },
  7307. /* 18 */
  7308. /***/ function(module, exports, __webpack_require__) {
  7309. // Utility functions for ordering and stacking of items
  7310. var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors
  7311. /**
  7312. * Order items by their start data
  7313. * @param {Item[]} items
  7314. */
  7315. exports.orderByStart = function(items) {
  7316. items.sort(function (a, b) {
  7317. return a.data.start - b.data.start;
  7318. });
  7319. };
  7320. /**
  7321. * Order items by their end date. If they have no end date, their start date
  7322. * is used.
  7323. * @param {Item[]} items
  7324. */
  7325. exports.orderByEnd = function(items) {
  7326. items.sort(function (a, b) {
  7327. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  7328. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  7329. return aTime - bTime;
  7330. });
  7331. };
  7332. /**
  7333. * Adjust vertical positions of the items such that they don't overlap each
  7334. * other.
  7335. * @param {Item[]} items
  7336. * All visible items
  7337. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  7338. * Margins between items and between items and the axis.
  7339. * @param {boolean} [force=false]
  7340. * If true, all items will be repositioned. If false (default), only
  7341. * items having a top===null will be re-stacked
  7342. */
  7343. exports.stack = function(items, margin, force) {
  7344. var i, iMax;
  7345. if (force) {
  7346. // reset top position of all items
  7347. for (i = 0, iMax = items.length; i < iMax; i++) {
  7348. items[i].top = null;
  7349. }
  7350. }
  7351. // calculate new, non-overlapping positions
  7352. for (i = 0, iMax = items.length; i < iMax; i++) {
  7353. var item = items[i];
  7354. if (item.stack && item.top === null) {
  7355. // initialize top position
  7356. item.top = margin.axis;
  7357. do {
  7358. // TODO: optimize checking for overlap. when there is a gap without items,
  7359. // you only need to check for items from the next item on, not from zero
  7360. var collidingItem = null;
  7361. for (var j = 0, jj = items.length; j < jj; j++) {
  7362. var other = items[j];
  7363. if (other.top !== null && other !== item && other.stack && exports.collision(item, other, margin.item)) {
  7364. collidingItem = other;
  7365. break;
  7366. }
  7367. }
  7368. if (collidingItem != null) {
  7369. // There is a collision. Reposition the items above the colliding element
  7370. item.top = collidingItem.top + collidingItem.height + margin.item.vertical;
  7371. }
  7372. } while (collidingItem);
  7373. }
  7374. }
  7375. };
  7376. /**
  7377. * Adjust vertical positions of the items without stacking them
  7378. * @param {Item[]} items
  7379. * All visible items
  7380. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  7381. * Margins between items and between items and the axis.
  7382. */
  7383. exports.nostack = function(items, margin, subgroups) {
  7384. var i, iMax, newTop;
  7385. // reset top position of all items
  7386. for (i = 0, iMax = items.length; i < iMax; i++) {
  7387. if (items[i].data.subgroup !== undefined) {
  7388. newTop = margin.axis;
  7389. for (var subgroup in subgroups) {
  7390. if (subgroups.hasOwnProperty(subgroup)) {
  7391. if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroups[items[i].data.subgroup].index) {
  7392. newTop += subgroups[subgroup].height + margin.item.vertical;
  7393. }
  7394. }
  7395. }
  7396. items[i].top = newTop;
  7397. }
  7398. else {
  7399. items[i].top = margin.axis;
  7400. }
  7401. }
  7402. };
  7403. /**
  7404. * Test if the two provided items collide
  7405. * The items must have parameters left, width, top, and height.
  7406. * @param {Item} a The first item
  7407. * @param {Item} b The second item
  7408. * @param {{horizontal: number, vertical: number}} margin
  7409. * An object containing a horizontal and vertical
  7410. * minimum required margin.
  7411. * @return {boolean} true if a and b collide, else false
  7412. */
  7413. exports.collision = function(a, b, margin) {
  7414. return ((a.left - margin.horizontal + EPSILON) < (b.left + b.width) &&
  7415. (a.left + a.width + margin.horizontal - EPSILON) > b.left &&
  7416. (a.top - margin.vertical + EPSILON) < (b.top + b.height) &&
  7417. (a.top + a.height + margin.vertical - EPSILON) > b.top);
  7418. };
  7419. /***/ },
  7420. /* 19 */
  7421. /***/ function(module, exports, __webpack_require__) {
  7422. var moment = __webpack_require__(44);
  7423. var DateUtil = __webpack_require__(15);
  7424. var util = __webpack_require__(1);
  7425. /**
  7426. * @constructor TimeStep
  7427. * The class TimeStep is an iterator for dates. You provide a start date and an
  7428. * end date. The class itself determines the best scale (step size) based on the
  7429. * provided start Date, end Date, and minimumStep.
  7430. *
  7431. * If minimumStep is provided, the step size is chosen as close as possible
  7432. * to the minimumStep but larger than minimumStep. If minimumStep is not
  7433. * provided, the scale is set to 1 DAY.
  7434. * The minimumStep should correspond with the onscreen size of about 6 characters
  7435. *
  7436. * Alternatively, you can set a scale by hand.
  7437. * After creation, you can initialize the class by executing first(). Then you
  7438. * can iterate from the start date to the end date via next(). You can check if
  7439. * the end date is reached with the function hasNext(). After each step, you can
  7440. * retrieve the current date via getCurrent().
  7441. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  7442. * days, to years.
  7443. *
  7444. * Version: 1.2
  7445. *
  7446. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  7447. * or new Date(2010, 9, 21, 23, 45, 00)
  7448. * @param {Date} [end] The end date
  7449. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  7450. */
  7451. function TimeStep(start, end, minimumStep, hiddenDates) {
  7452. // variables
  7453. this.current = new Date();
  7454. this._start = new Date();
  7455. this._end = new Date();
  7456. this.autoScale = true;
  7457. this.scale = 'day';
  7458. this.step = 1;
  7459. // initialize the range
  7460. this.setRange(start, end, minimumStep);
  7461. // hidden Dates options
  7462. this.switchedDay = false;
  7463. this.switchedMonth = false;
  7464. this.switchedYear = false;
  7465. this.hiddenDates = hiddenDates;
  7466. if (hiddenDates === undefined) {
  7467. this.hiddenDates = [];
  7468. }
  7469. this.format = TimeStep.FORMAT; // default formatting
  7470. }
  7471. // Time formatting
  7472. TimeStep.FORMAT = {
  7473. minorLabels: {
  7474. millisecond:'SSS',
  7475. second: 's',
  7476. minute: 'HH:mm',
  7477. hour: 'HH:mm',
  7478. weekday: 'ddd D',
  7479. day: 'D',
  7480. month: 'MMM',
  7481. year: 'YYYY'
  7482. },
  7483. majorLabels: {
  7484. millisecond:'HH:mm:ss',
  7485. second: 'D MMMM HH:mm',
  7486. minute: 'ddd D MMMM',
  7487. hour: 'ddd D MMMM',
  7488. weekday: 'MMMM YYYY',
  7489. day: 'MMMM YYYY',
  7490. month: 'YYYY',
  7491. year: ''
  7492. }
  7493. };
  7494. /**
  7495. * Set custom formatting for the minor an major labels of the TimeStep.
  7496. * Both `minorLabels` and `majorLabels` are an Object with properties:
  7497. * 'millisecond, 'second, 'minute', 'hour', 'weekday, 'day, 'month, 'year'.
  7498. * @param {{minorLabels: Object, majorLabels: Object}} format
  7499. */
  7500. TimeStep.prototype.setFormat = function (format) {
  7501. var defaultFormat = util.deepExtend({}, TimeStep.FORMAT);
  7502. this.format = util.deepExtend(defaultFormat, format);
  7503. };
  7504. /**
  7505. * Set a new range
  7506. * If minimumStep is provided, the step size is chosen as close as possible
  7507. * to the minimumStep but larger than minimumStep. If minimumStep is not
  7508. * provided, the scale is set to 1 DAY.
  7509. * The minimumStep should correspond with the onscreen size of about 6 characters
  7510. * @param {Date} [start] The start date and time.
  7511. * @param {Date} [end] The end date and time.
  7512. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  7513. */
  7514. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  7515. if (!(start instanceof Date) || !(end instanceof Date)) {
  7516. throw "No legal start or end date in method setRange";
  7517. }
  7518. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  7519. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  7520. if (this.autoScale) {
  7521. this.setMinimumStep(minimumStep);
  7522. }
  7523. };
  7524. /**
  7525. * Set the range iterator to the start date.
  7526. */
  7527. TimeStep.prototype.first = function() {
  7528. this.current = new Date(this._start.valueOf());
  7529. this.roundToMinor();
  7530. };
  7531. /**
  7532. * Round the current date to the first minor date value
  7533. * This must be executed once when the current date is set to start Date
  7534. */
  7535. TimeStep.prototype.roundToMinor = function() {
  7536. // round to floor
  7537. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  7538. // noinspection FallThroughInSwitchStatementJS
  7539. switch (this.scale) {
  7540. case 'year':
  7541. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  7542. this.current.setMonth(0);
  7543. case 'month': this.current.setDate(1);
  7544. case 'day': // intentional fall through
  7545. case 'weekday': this.current.setHours(0);
  7546. case 'hour': this.current.setMinutes(0);
  7547. case 'minute': this.current.setSeconds(0);
  7548. case 'second': this.current.setMilliseconds(0);
  7549. //case 'millisecond': // nothing to do for milliseconds
  7550. }
  7551. if (this.step != 1) {
  7552. // round down to the first minor value that is a multiple of the current step size
  7553. switch (this.scale) {
  7554. case 'millisecond': this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  7555. case 'second': this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  7556. case 'minute': this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  7557. case 'hour': this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  7558. case 'weekday': // intentional fall through
  7559. case 'day': this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  7560. case 'month': this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  7561. case 'year': this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  7562. default: break;
  7563. }
  7564. }
  7565. };
  7566. /**
  7567. * Check if the there is a next step
  7568. * @return {boolean} true if the current date has not passed the end date
  7569. */
  7570. TimeStep.prototype.hasNext = function () {
  7571. return (this.current.valueOf() <= this._end.valueOf());
  7572. };
  7573. /**
  7574. * Do the next step
  7575. */
  7576. TimeStep.prototype.next = function() {
  7577. var prev = this.current.valueOf();
  7578. // Two cases, needed to prevent issues with switching daylight savings
  7579. // (end of March and end of October)
  7580. if (this.current.getMonth() < 6) {
  7581. switch (this.scale) {
  7582. case 'millisecond':
  7583. this.current = new Date(this.current.valueOf() + this.step); break;
  7584. case 'second': this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  7585. case 'minute': this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  7586. case 'hour':
  7587. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  7588. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  7589. var h = this.current.getHours();
  7590. this.current.setHours(h - (h % this.step));
  7591. break;
  7592. case 'weekday': // intentional fall through
  7593. case 'day': this.current.setDate(this.current.getDate() + this.step); break;
  7594. case 'month': this.current.setMonth(this.current.getMonth() + this.step); break;
  7595. case 'year': this.current.setFullYear(this.current.getFullYear() + this.step); break;
  7596. default: break;
  7597. }
  7598. }
  7599. else {
  7600. switch (this.scale) {
  7601. case 'millisecond': this.current = new Date(this.current.valueOf() + this.step); break;
  7602. case 'second': this.current.setSeconds(this.current.getSeconds() + this.step); break;
  7603. case 'minute': this.current.setMinutes(this.current.getMinutes() + this.step); break;
  7604. case 'hour': this.current.setHours(this.current.getHours() + this.step); break;
  7605. case 'weekday': // intentional fall through
  7606. case 'day': this.current.setDate(this.current.getDate() + this.step); break;
  7607. case 'month': this.current.setMonth(this.current.getMonth() + this.step); break;
  7608. case 'year': this.current.setFullYear(this.current.getFullYear() + this.step); break;
  7609. default: break;
  7610. }
  7611. }
  7612. if (this.step != 1) {
  7613. // round down to the correct major value
  7614. switch (this.scale) {
  7615. case 'millisecond': if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  7616. case 'second': if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  7617. case 'minute': if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  7618. case 'hour': if(this.current.getHours() < this.step) this.current.setHours(0); break;
  7619. case 'weekday': // intentional fall through
  7620. case 'day': if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  7621. case 'month': if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  7622. case 'year': break; // nothing to do for year
  7623. default: break;
  7624. }
  7625. }
  7626. // safety mechanism: if current time is still unchanged, move to the end
  7627. if (this.current.valueOf() == prev) {
  7628. this.current = new Date(this._end.valueOf());
  7629. }
  7630. DateUtil.stepOverHiddenDates(this, prev);
  7631. };
  7632. /**
  7633. * Get the current datetime
  7634. * @return {Date} current The current date
  7635. */
  7636. TimeStep.prototype.getCurrent = function() {
  7637. return this.current;
  7638. };
  7639. /**
  7640. * Set a custom scale. Autoscaling will be disabled.
  7641. * For example setScale(SCALE.MINUTES, 5) will result
  7642. * in minor steps of 5 minutes, and major steps of an hour.
  7643. *
  7644. * @param {string} newScale
  7645. * A scale. Choose from 'millisecond, 'second,
  7646. * 'minute', 'hour', 'weekday, 'day, 'month, 'year'.
  7647. * @param {Number} newStep A step size, by default 1. Choose for
  7648. * example 1, 2, 5, or 10.
  7649. */
  7650. TimeStep.prototype.setScale = function(newScale, newStep) {
  7651. this.scale = newScale;
  7652. if (newStep > 0) {
  7653. this.step = newStep;
  7654. }
  7655. this.autoScale = false;
  7656. };
  7657. /**
  7658. * Enable or disable autoscaling
  7659. * @param {boolean} enable If true, autoascaling is set true
  7660. */
  7661. TimeStep.prototype.setAutoScale = function (enable) {
  7662. this.autoScale = enable;
  7663. };
  7664. /**
  7665. * Automatically determine the scale that bests fits the provided minimum step
  7666. * @param {Number} [minimumStep] The minimum step size in milliseconds
  7667. */
  7668. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  7669. if (minimumStep == undefined) {
  7670. return;
  7671. }
  7672. //var b = asc + ds;
  7673. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  7674. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  7675. var stepDay = (1000 * 60 * 60 * 24);
  7676. var stepHour = (1000 * 60 * 60);
  7677. var stepMinute = (1000 * 60);
  7678. var stepSecond = (1000);
  7679. var stepMillisecond= (1);
  7680. // find the smallest step that is larger than the provided minimumStep
  7681. if (stepYear*1000 > minimumStep) {this.scale = 'year'; this.step = 1000;}
  7682. if (stepYear*500 > minimumStep) {this.scale = 'year'; this.step = 500;}
  7683. if (stepYear*100 > minimumStep) {this.scale = 'year'; this.step = 100;}
  7684. if (stepYear*50 > minimumStep) {this.scale = 'year'; this.step = 50;}
  7685. if (stepYear*10 > minimumStep) {this.scale = 'year'; this.step = 10;}
  7686. if (stepYear*5 > minimumStep) {this.scale = 'year'; this.step = 5;}
  7687. if (stepYear > minimumStep) {this.scale = 'year'; this.step = 1;}
  7688. if (stepMonth*3 > minimumStep) {this.scale = 'month'; this.step = 3;}
  7689. if (stepMonth > minimumStep) {this.scale = 'month'; this.step = 1;}
  7690. if (stepDay*5 > minimumStep) {this.scale = 'day'; this.step = 5;}
  7691. if (stepDay*2 > minimumStep) {this.scale = 'day'; this.step = 2;}
  7692. if (stepDay > minimumStep) {this.scale = 'day'; this.step = 1;}
  7693. if (stepDay/2 > minimumStep) {this.scale = 'weekday'; this.step = 1;}
  7694. if (stepHour*4 > minimumStep) {this.scale = 'hour'; this.step = 4;}
  7695. if (stepHour > minimumStep) {this.scale = 'hour'; this.step = 1;}
  7696. if (stepMinute*15 > minimumStep) {this.scale = 'minute'; this.step = 15;}
  7697. if (stepMinute*10 > minimumStep) {this.scale = 'minute'; this.step = 10;}
  7698. if (stepMinute*5 > minimumStep) {this.scale = 'minute'; this.step = 5;}
  7699. if (stepMinute > minimumStep) {this.scale = 'minute'; this.step = 1;}
  7700. if (stepSecond*15 > minimumStep) {this.scale = 'second'; this.step = 15;}
  7701. if (stepSecond*10 > minimumStep) {this.scale = 'second'; this.step = 10;}
  7702. if (stepSecond*5 > minimumStep) {this.scale = 'second'; this.step = 5;}
  7703. if (stepSecond > minimumStep) {this.scale = 'second'; this.step = 1;}
  7704. if (stepMillisecond*200 > minimumStep) {this.scale = 'millisecond'; this.step = 200;}
  7705. if (stepMillisecond*100 > minimumStep) {this.scale = 'millisecond'; this.step = 100;}
  7706. if (stepMillisecond*50 > minimumStep) {this.scale = 'millisecond'; this.step = 50;}
  7707. if (stepMillisecond*10 > minimumStep) {this.scale = 'millisecond'; this.step = 10;}
  7708. if (stepMillisecond*5 > minimumStep) {this.scale = 'millisecond'; this.step = 5;}
  7709. if (stepMillisecond > minimumStep) {this.scale = 'millisecond'; this.step = 1;}
  7710. };
  7711. /**
  7712. * Snap a date to a rounded value.
  7713. * The snap intervals are dependent on the current scale and step.
  7714. * @param {Date} date the date to be snapped.
  7715. * @return {Date} snappedDate
  7716. */
  7717. TimeStep.prototype.snap = function(date) {
  7718. var clone = new Date(date.valueOf());
  7719. if (this.scale == 'year') {
  7720. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  7721. clone.setFullYear(Math.round(year / this.step) * this.step);
  7722. clone.setMonth(0);
  7723. clone.setDate(0);
  7724. clone.setHours(0);
  7725. clone.setMinutes(0);
  7726. clone.setSeconds(0);
  7727. clone.setMilliseconds(0);
  7728. }
  7729. else if (this.scale == 'month') {
  7730. if (clone.getDate() > 15) {
  7731. clone.setDate(1);
  7732. clone.setMonth(clone.getMonth() + 1);
  7733. // important: first set Date to 1, after that change the month.
  7734. }
  7735. else {
  7736. clone.setDate(1);
  7737. }
  7738. clone.setHours(0);
  7739. clone.setMinutes(0);
  7740. clone.setSeconds(0);
  7741. clone.setMilliseconds(0);
  7742. }
  7743. else if (this.scale == 'day') {
  7744. //noinspection FallthroughInSwitchStatementJS
  7745. switch (this.step) {
  7746. case 5:
  7747. case 2:
  7748. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  7749. default:
  7750. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  7751. }
  7752. clone.setMinutes(0);
  7753. clone.setSeconds(0);
  7754. clone.setMilliseconds(0);
  7755. }
  7756. else if (this.scale == 'weekday') {
  7757. //noinspection FallthroughInSwitchStatementJS
  7758. switch (this.step) {
  7759. case 5:
  7760. case 2:
  7761. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  7762. default:
  7763. clone.setHours(Math.round(clone.getHours() / 6) * 6); break;
  7764. }
  7765. clone.setMinutes(0);
  7766. clone.setSeconds(0);
  7767. clone.setMilliseconds(0);
  7768. }
  7769. else if (this.scale == 'hour') {
  7770. switch (this.step) {
  7771. case 4:
  7772. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  7773. default:
  7774. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  7775. }
  7776. clone.setSeconds(0);
  7777. clone.setMilliseconds(0);
  7778. } else if (this.scale == 'minute') {
  7779. //noinspection FallthroughInSwitchStatementJS
  7780. switch (this.step) {
  7781. case 15:
  7782. case 10:
  7783. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  7784. clone.setSeconds(0);
  7785. break;
  7786. case 5:
  7787. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  7788. default:
  7789. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  7790. }
  7791. clone.setMilliseconds(0);
  7792. }
  7793. else if (this.scale == 'second') {
  7794. //noinspection FallthroughInSwitchStatementJS
  7795. switch (this.step) {
  7796. case 15:
  7797. case 10:
  7798. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  7799. clone.setMilliseconds(0);
  7800. break;
  7801. case 5:
  7802. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  7803. default:
  7804. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  7805. }
  7806. }
  7807. else if (this.scale == 'millisecond') {
  7808. var step = this.step > 5 ? this.step / 2 : 1;
  7809. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  7810. }
  7811. return clone;
  7812. };
  7813. /**
  7814. * Check if the current value is a major value (for example when the step
  7815. * is DAY, a major value is each first day of the MONTH)
  7816. * @return {boolean} true if current date is major, else false.
  7817. */
  7818. TimeStep.prototype.isMajor = function() {
  7819. if (this.switchedYear == true) {
  7820. this.switchedYear = false;
  7821. switch (this.scale) {
  7822. case 'year':
  7823. case 'month':
  7824. case 'weekday':
  7825. case 'day':
  7826. case 'hour':
  7827. case 'minute':
  7828. case 'second':
  7829. case 'millisecond':
  7830. return true;
  7831. default:
  7832. return false;
  7833. }
  7834. }
  7835. else if (this.switchedMonth == true) {
  7836. this.switchedMonth = false;
  7837. switch (this.scale) {
  7838. case 'weekday':
  7839. case 'day':
  7840. case 'hour':
  7841. case 'minute':
  7842. case 'second':
  7843. case 'millisecond':
  7844. return true;
  7845. default:
  7846. return false;
  7847. }
  7848. }
  7849. else if (this.switchedDay == true) {
  7850. this.switchedDay = false;
  7851. switch (this.scale) {
  7852. case 'millisecond':
  7853. case 'second':
  7854. case 'minute':
  7855. case 'hour':
  7856. return true;
  7857. default:
  7858. return false;
  7859. }
  7860. }
  7861. switch (this.scale) {
  7862. case 'millisecond':
  7863. return (this.current.getMilliseconds() == 0);
  7864. case 'second':
  7865. return (this.current.getSeconds() == 0);
  7866. case 'minute':
  7867. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  7868. case 'hour':
  7869. return (this.current.getHours() == 0);
  7870. case 'weekday': // intentional fall through
  7871. case 'day':
  7872. return (this.current.getDate() == 1);
  7873. case 'month':
  7874. return (this.current.getMonth() == 0);
  7875. case 'year':
  7876. return false;
  7877. default:
  7878. return false;
  7879. }
  7880. };
  7881. /**
  7882. * Returns formatted text for the minor axislabel, depending on the current
  7883. * date and the scale. For example when scale is MINUTE, the current time is
  7884. * formatted as "hh:mm".
  7885. * @param {Date} [date] custom date. if not provided, current date is taken
  7886. */
  7887. TimeStep.prototype.getLabelMinor = function(date) {
  7888. if (date == undefined) {
  7889. date = this.current;
  7890. }
  7891. var format = this.format.minorLabels[this.scale];
  7892. return (format && format.length > 0) ? moment(date).format(format) : '';
  7893. };
  7894. /**
  7895. * Returns formatted text for the major axis label, depending on the current
  7896. * date and the scale. For example when scale is MINUTE, the major scale is
  7897. * hours, and the hour will be formatted as "hh".
  7898. * @param {Date} [date] custom date. if not provided, current date is taken
  7899. */
  7900. TimeStep.prototype.getLabelMajor = function(date) {
  7901. if (date == undefined) {
  7902. date = this.current;
  7903. }
  7904. var format = this.format.majorLabels[this.scale];
  7905. return (format && format.length > 0) ? moment(date).format(format) : '';
  7906. };
  7907. TimeStep.prototype.getClassName = function() {
  7908. var m = moment(this.current);
  7909. var date = m.locale ? m.locale('en') : m.lang('en'); // old versions of moment have .lang() function
  7910. var step = this.step;
  7911. function even(value) {
  7912. return (value / step % 2 == 0) ? ' even' : ' odd';
  7913. }
  7914. function today(date) {
  7915. if (date.isSame(new Date(), 'day')) {
  7916. return ' today';
  7917. }
  7918. if (date.isSame(moment().add(1, 'day'), 'day')) {
  7919. return ' tomorrow';
  7920. }
  7921. if (date.isSame(moment().add(-1, 'day'), 'day')) {
  7922. return ' yesterday';
  7923. }
  7924. return '';
  7925. }
  7926. function currentWeek(date) {
  7927. return date.isSame(new Date(), 'week') ? ' current-week' : '';
  7928. }
  7929. function currentMonth(date) {
  7930. return date.isSame(new Date(), 'month') ? ' current-month' : '';
  7931. }
  7932. function currentYear(date) {
  7933. return date.isSame(new Date(), 'year') ? ' current-year' : '';
  7934. }
  7935. switch (this.scale) {
  7936. case 'millisecond':
  7937. return even(date.milliseconds()).trim();
  7938. case 'second':
  7939. return even(date.seconds()).trim();
  7940. case 'minute':
  7941. return even(date.minutes()).trim();
  7942. case 'hour':
  7943. var hours = date.hours();
  7944. if (this.step == 4) {
  7945. hours = hours + '-' + (hours + 4);
  7946. }
  7947. return hours + 'h' + today(date) + even(date.hours());
  7948. case 'weekday':
  7949. return date.format('dddd').toLowerCase() +
  7950. today(date) + currentWeek(date) + even(date.date());
  7951. case 'day':
  7952. var day = date.date();
  7953. var month = date.format('MMMM').toLowerCase();
  7954. return 'day' + day + ' ' + month + currentMonth(date) + even(day - 1);
  7955. case 'month':
  7956. return date.format('MMMM').toLowerCase() +
  7957. currentMonth(date) + even(date.month());
  7958. case 'year':
  7959. var year = date.year();
  7960. return 'year' + year + currentYear(date)+ even(year);
  7961. default:
  7962. return '';
  7963. }
  7964. };
  7965. module.exports = TimeStep;
  7966. /***/ },
  7967. /* 20 */
  7968. /***/ function(module, exports, __webpack_require__) {
  7969. /**
  7970. * Prototype for visual components
  7971. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body]
  7972. * @param {Object} [options]
  7973. */
  7974. function Component (body, options) {
  7975. this.options = null;
  7976. this.props = null;
  7977. }
  7978. /**
  7979. * Set options for the component. The new options will be merged into the
  7980. * current options.
  7981. * @param {Object} options
  7982. */
  7983. Component.prototype.setOptions = function(options) {
  7984. if (options) {
  7985. util.extend(this.options, options);
  7986. }
  7987. };
  7988. /**
  7989. * Repaint the component
  7990. * @return {boolean} Returns true if the component is resized
  7991. */
  7992. Component.prototype.redraw = function() {
  7993. // should be implemented by the component
  7994. return false;
  7995. };
  7996. /**
  7997. * Destroy the component. Cleanup DOM and event listeners
  7998. */
  7999. Component.prototype.destroy = function() {
  8000. // should be implemented by the component
  8001. };
  8002. /**
  8003. * Test whether the component is resized since the last time _isResized() was
  8004. * called.
  8005. * @return {Boolean} Returns true if the component is resized
  8006. * @protected
  8007. */
  8008. Component.prototype._isResized = function() {
  8009. var resized = (this.props._previousWidth !== this.props.width ||
  8010. this.props._previousHeight !== this.props.height);
  8011. this.props._previousWidth = this.props.width;
  8012. this.props._previousHeight = this.props.height;
  8013. return resized;
  8014. };
  8015. module.exports = Component;
  8016. /***/ },
  8017. /* 21 */
  8018. /***/ function(module, exports, __webpack_require__) {
  8019. var util = __webpack_require__(1);
  8020. var Component = __webpack_require__(20);
  8021. var moment = __webpack_require__(44);
  8022. var locales = __webpack_require__(48);
  8023. /**
  8024. * A current time bar
  8025. * @param {{range: Range, dom: Object, domProps: Object}} body
  8026. * @param {Object} [options] Available parameters:
  8027. * {Boolean} [showCurrentTime]
  8028. * @constructor CurrentTime
  8029. * @extends Component
  8030. */
  8031. function CurrentTime (body, options) {
  8032. this.body = body;
  8033. // default options
  8034. this.defaultOptions = {
  8035. showCurrentTime: true,
  8036. locales: locales,
  8037. locale: 'en'
  8038. };
  8039. this.options = util.extend({}, this.defaultOptions);
  8040. this.offset = 0;
  8041. this._create();
  8042. this.setOptions(options);
  8043. }
  8044. CurrentTime.prototype = new Component();
  8045. /**
  8046. * Create the HTML DOM for the current time bar
  8047. * @private
  8048. */
  8049. CurrentTime.prototype._create = function() {
  8050. var bar = document.createElement('div');
  8051. bar.className = 'currenttime';
  8052. bar.style.position = 'absolute';
  8053. bar.style.top = '0px';
  8054. bar.style.height = '100%';
  8055. this.bar = bar;
  8056. };
  8057. /**
  8058. * Destroy the CurrentTime bar
  8059. */
  8060. CurrentTime.prototype.destroy = function () {
  8061. this.options.showCurrentTime = false;
  8062. this.redraw(); // will remove the bar from the DOM and stop refreshing
  8063. this.body = null;
  8064. };
  8065. /**
  8066. * Set options for the component. Options will be merged in current options.
  8067. * @param {Object} options Available parameters:
  8068. * {boolean} [showCurrentTime]
  8069. */
  8070. CurrentTime.prototype.setOptions = function(options) {
  8071. if (options) {
  8072. // copy all options that we know
  8073. util.selectiveExtend(['showCurrentTime', 'locale', 'locales'], this.options, options);
  8074. }
  8075. };
  8076. /**
  8077. * Repaint the component
  8078. * @return {boolean} Returns true if the component is resized
  8079. */
  8080. CurrentTime.prototype.redraw = function() {
  8081. if (this.options.showCurrentTime) {
  8082. var parent = this.body.dom.backgroundVertical;
  8083. if (this.bar.parentNode != parent) {
  8084. // attach to the dom
  8085. if (this.bar.parentNode) {
  8086. this.bar.parentNode.removeChild(this.bar);
  8087. }
  8088. parent.appendChild(this.bar);
  8089. this.start();
  8090. }
  8091. var now = new Date(new Date().valueOf() + this.offset);
  8092. var x = this.body.util.toScreen(now);
  8093. var locale = this.options.locales[this.options.locale];
  8094. var title = locale.current + ' ' + locale.time + ': ' + moment(now).format('dddd, MMMM Do YYYY, H:mm:ss');
  8095. title = title.charAt(0).toUpperCase() + title.substring(1);
  8096. this.bar.style.left = x + 'px';
  8097. this.bar.title = title;
  8098. }
  8099. else {
  8100. // remove the line from the DOM
  8101. if (this.bar.parentNode) {
  8102. this.bar.parentNode.removeChild(this.bar);
  8103. }
  8104. this.stop();
  8105. }
  8106. return false;
  8107. };
  8108. /**
  8109. * Start auto refreshing the current time bar
  8110. */
  8111. CurrentTime.prototype.start = function() {
  8112. var me = this;
  8113. function update () {
  8114. me.stop();
  8115. // determine interval to refresh
  8116. var scale = me.body.range.conversion(me.body.domProps.center.width).scale;
  8117. var interval = 1 / scale / 10;
  8118. if (interval < 30) interval = 30;
  8119. if (interval > 1000) interval = 1000;
  8120. me.redraw();
  8121. // start a timer to adjust for the new time
  8122. me.currentTimeTimer = setTimeout(update, interval);
  8123. }
  8124. update();
  8125. };
  8126. /**
  8127. * Stop auto refreshing the current time bar
  8128. */
  8129. CurrentTime.prototype.stop = function() {
  8130. if (this.currentTimeTimer !== undefined) {
  8131. clearTimeout(this.currentTimeTimer);
  8132. delete this.currentTimeTimer;
  8133. }
  8134. };
  8135. /**
  8136. * Set a current time. This can be used for example to ensure that a client's
  8137. * time is synchronized with a shared server time.
  8138. * @param {Date | String | Number} time A Date, unix timestamp, or
  8139. * ISO date string.
  8140. */
  8141. CurrentTime.prototype.setCurrentTime = function(time) {
  8142. var t = util.convert(time, 'Date').valueOf();
  8143. var now = new Date().valueOf();
  8144. this.offset = t - now;
  8145. this.redraw();
  8146. };
  8147. /**
  8148. * Get the current time.
  8149. * @return {Date} Returns the current time.
  8150. */
  8151. CurrentTime.prototype.getCurrentTime = function() {
  8152. return new Date(new Date().valueOf() + this.offset);
  8153. };
  8154. module.exports = CurrentTime;
  8155. /***/ },
  8156. /* 22 */
  8157. /***/ function(module, exports, __webpack_require__) {
  8158. var Hammer = __webpack_require__(45);
  8159. var util = __webpack_require__(1);
  8160. var Component = __webpack_require__(20);
  8161. var moment = __webpack_require__(44);
  8162. var locales = __webpack_require__(48);
  8163. /**
  8164. * A custom time bar
  8165. * @param {{range: Range, dom: Object}} body
  8166. * @param {Object} [options] Available parameters:
  8167. * {Boolean} [showCustomTime]
  8168. * @constructor CustomTime
  8169. * @extends Component
  8170. */
  8171. function CustomTime (body, options) {
  8172. this.body = body;
  8173. // default options
  8174. this.defaultOptions = {
  8175. showCustomTime: false,
  8176. locales: locales,
  8177. locale: 'en'
  8178. };
  8179. this.options = util.extend({}, this.defaultOptions);
  8180. this.customTime = new Date();
  8181. this.eventParams = {}; // stores state parameters while dragging the bar
  8182. // create the DOM
  8183. this._create();
  8184. this.setOptions(options);
  8185. }
  8186. CustomTime.prototype = new Component();
  8187. /**
  8188. * Set options for the component. Options will be merged in current options.
  8189. * @param {Object} options Available parameters:
  8190. * {boolean} [showCustomTime]
  8191. */
  8192. CustomTime.prototype.setOptions = function(options) {
  8193. if (options) {
  8194. // copy all options that we know
  8195. util.selectiveExtend(['showCustomTime', 'locale', 'locales'], this.options, options);
  8196. }
  8197. };
  8198. /**
  8199. * Create the DOM for the custom time
  8200. * @private
  8201. */
  8202. CustomTime.prototype._create = function() {
  8203. var bar = document.createElement('div');
  8204. bar.className = 'customtime';
  8205. bar.style.position = 'absolute';
  8206. bar.style.top = '0px';
  8207. bar.style.height = '100%';
  8208. this.bar = bar;
  8209. var drag = document.createElement('div');
  8210. drag.style.position = 'relative';
  8211. drag.style.top = '0px';
  8212. drag.style.left = '-10px';
  8213. drag.style.height = '100%';
  8214. drag.style.width = '20px';
  8215. bar.appendChild(drag);
  8216. // attach event listeners
  8217. this.hammer = Hammer(bar, {
  8218. prevent_default: true
  8219. });
  8220. this.hammer.on('dragstart', this._onDragStart.bind(this));
  8221. this.hammer.on('drag', this._onDrag.bind(this));
  8222. this.hammer.on('dragend', this._onDragEnd.bind(this));
  8223. };
  8224. /**
  8225. * Destroy the CustomTime bar
  8226. */
  8227. CustomTime.prototype.destroy = function () {
  8228. this.options.showCustomTime = false;
  8229. this.redraw(); // will remove the bar from the DOM
  8230. this.hammer.enable(false);
  8231. this.hammer = null;
  8232. this.body = null;
  8233. };
  8234. /**
  8235. * Repaint the component
  8236. * @return {boolean} Returns true if the component is resized
  8237. */
  8238. CustomTime.prototype.redraw = function () {
  8239. if (this.options.showCustomTime) {
  8240. var parent = this.body.dom.backgroundVertical;
  8241. if (this.bar.parentNode != parent) {
  8242. // attach to the dom
  8243. if (this.bar.parentNode) {
  8244. this.bar.parentNode.removeChild(this.bar);
  8245. }
  8246. parent.appendChild(this.bar);
  8247. }
  8248. var x = this.body.util.toScreen(this.customTime);
  8249. var locale = this.options.locales[this.options.locale];
  8250. var title = locale.time + ': ' + moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss');
  8251. title = title.charAt(0).toUpperCase() + title.substring(1);
  8252. this.bar.style.left = x + 'px';
  8253. this.bar.title = title;
  8254. }
  8255. else {
  8256. // remove the line from the DOM
  8257. if (this.bar.parentNode) {
  8258. this.bar.parentNode.removeChild(this.bar);
  8259. }
  8260. }
  8261. return false;
  8262. };
  8263. /**
  8264. * Set custom time.
  8265. * @param {Date | number | string} time
  8266. */
  8267. CustomTime.prototype.setCustomTime = function(time) {
  8268. this.customTime = util.convert(time, 'Date');
  8269. this.redraw();
  8270. };
  8271. /**
  8272. * Retrieve the current custom time.
  8273. * @return {Date} customTime
  8274. */
  8275. CustomTime.prototype.getCustomTime = function() {
  8276. return new Date(this.customTime.valueOf());
  8277. };
  8278. /**
  8279. * Start moving horizontally
  8280. * @param {Event} event
  8281. * @private
  8282. */
  8283. CustomTime.prototype._onDragStart = function(event) {
  8284. this.eventParams.dragging = true;
  8285. this.eventParams.customTime = this.customTime;
  8286. event.stopPropagation();
  8287. event.preventDefault();
  8288. };
  8289. /**
  8290. * Perform moving operating.
  8291. * @param {Event} event
  8292. * @private
  8293. */
  8294. CustomTime.prototype._onDrag = function (event) {
  8295. if (!this.eventParams.dragging) return;
  8296. var deltaX = event.gesture.deltaX,
  8297. x = this.body.util.toScreen(this.eventParams.customTime) + deltaX,
  8298. time = this.body.util.toTime(x);
  8299. this.setCustomTime(time);
  8300. // fire a timechange event
  8301. this.body.emitter.emit('timechange', {
  8302. time: new Date(this.customTime.valueOf())
  8303. });
  8304. event.stopPropagation();
  8305. event.preventDefault();
  8306. };
  8307. /**
  8308. * Stop moving operating.
  8309. * @param {event} event
  8310. * @private
  8311. */
  8312. CustomTime.prototype._onDragEnd = function (event) {
  8313. if (!this.eventParams.dragging) return;
  8314. // fire a timechanged event
  8315. this.body.emitter.emit('timechanged', {
  8316. time: new Date(this.customTime.valueOf())
  8317. });
  8318. event.stopPropagation();
  8319. event.preventDefault();
  8320. };
  8321. module.exports = CustomTime;
  8322. /***/ },
  8323. /* 23 */
  8324. /***/ function(module, exports, __webpack_require__) {
  8325. var util = __webpack_require__(1);
  8326. var DOMutil = __webpack_require__(2);
  8327. var Component = __webpack_require__(20);
  8328. var DataStep = __webpack_require__(16);
  8329. /**
  8330. * A horizontal time axis
  8331. * @param {Object} [options] See DataAxis.setOptions for the available
  8332. * options.
  8333. * @constructor DataAxis
  8334. * @extends Component
  8335. * @param body
  8336. */
  8337. function DataAxis (body, options, svg, linegraphOptions) {
  8338. this.id = util.randomUUID();
  8339. this.body = body;
  8340. this.defaultOptions = {
  8341. orientation: 'left', // supported: 'left', 'right'
  8342. showMinorLabels: true,
  8343. showMajorLabels: true,
  8344. icons: true,
  8345. majorLinesOffset: 7,
  8346. minorLinesOffset: 4,
  8347. labelOffsetX: 10,
  8348. labelOffsetY: 2,
  8349. iconWidth: 20,
  8350. width: '40px',
  8351. visible: true,
  8352. alignZeros: true,
  8353. customRange: {
  8354. left: {min:undefined, max:undefined},
  8355. right: {min:undefined, max:undefined}
  8356. },
  8357. title: {
  8358. left: {text:undefined},
  8359. right: {text:undefined}
  8360. },
  8361. format: {
  8362. left: {decimals: undefined},
  8363. right: {decimals: undefined}
  8364. }
  8365. };
  8366. this.linegraphOptions = linegraphOptions;
  8367. this.linegraphSVG = svg;
  8368. this.props = {};
  8369. this.DOMelements = { // dynamic elements
  8370. lines: {},
  8371. labels: {},
  8372. title: {}
  8373. };
  8374. this.dom = {};
  8375. this.range = {start:0, end:0};
  8376. this.options = util.extend({}, this.defaultOptions);
  8377. this.conversionFactor = 1;
  8378. this.setOptions(options);
  8379. this.width = Number(('' + this.options.width).replace("px",""));
  8380. this.minWidth = this.width;
  8381. this.height = this.linegraphSVG.offsetHeight;
  8382. this.hidden = false;
  8383. this.stepPixels = 25;
  8384. this.stepPixelsForced = 25;
  8385. this.zeroCrossing = -1;
  8386. this.lineOffset = 0;
  8387. this.master = true;
  8388. this.svgElements = {};
  8389. this.iconsRemoved = false;
  8390. this.groups = {};
  8391. this.amountOfGroups = 0;
  8392. // create the HTML DOM
  8393. this._create();
  8394. var me = this;
  8395. this.body.emitter.on("verticalDrag", function() {
  8396. me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px';
  8397. });
  8398. }
  8399. DataAxis.prototype = new Component();
  8400. DataAxis.prototype.addGroup = function(label, graphOptions) {
  8401. if (!this.groups.hasOwnProperty(label)) {
  8402. this.groups[label] = graphOptions;
  8403. }
  8404. this.amountOfGroups += 1;
  8405. };
  8406. DataAxis.prototype.updateGroup = function(label, graphOptions) {
  8407. this.groups[label] = graphOptions;
  8408. };
  8409. DataAxis.prototype.removeGroup = function(label) {
  8410. if (this.groups.hasOwnProperty(label)) {
  8411. delete this.groups[label];
  8412. this.amountOfGroups -= 1;
  8413. }
  8414. };
  8415. DataAxis.prototype.setOptions = function (options) {
  8416. if (options) {
  8417. var redraw = false;
  8418. if (this.options.orientation != options.orientation && options.orientation !== undefined) {
  8419. redraw = true;
  8420. }
  8421. var fields = [
  8422. 'orientation',
  8423. 'showMinorLabels',
  8424. 'showMajorLabels',
  8425. 'icons',
  8426. 'majorLinesOffset',
  8427. 'minorLinesOffset',
  8428. 'labelOffsetX',
  8429. 'labelOffsetY',
  8430. 'iconWidth',
  8431. 'width',
  8432. 'visible',
  8433. 'customRange',
  8434. 'title',
  8435. 'format',
  8436. 'alignZeros'
  8437. ];
  8438. util.selectiveExtend(fields, this.options, options);
  8439. this.minWidth = Number(('' + this.options.width).replace("px",""));
  8440. if (redraw == true && this.dom.frame) {
  8441. this.hide();
  8442. this.show();
  8443. }
  8444. }
  8445. };
  8446. /**
  8447. * Create the HTML DOM for the DataAxis
  8448. */
  8449. DataAxis.prototype._create = function() {
  8450. this.dom.frame = document.createElement('div');
  8451. this.dom.frame.style.width = this.options.width;
  8452. this.dom.frame.style.height = this.height;
  8453. this.dom.lineContainer = document.createElement('div');
  8454. this.dom.lineContainer.style.width = '100%';
  8455. this.dom.lineContainer.style.height = this.height;
  8456. this.dom.lineContainer.style.position = 'relative';
  8457. // create svg element for graph drawing.
  8458. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  8459. this.svg.style.position = "absolute";
  8460. this.svg.style.top = '0px';
  8461. this.svg.style.height = '100%';
  8462. this.svg.style.width = '100%';
  8463. this.svg.style.display = "block";
  8464. this.dom.frame.appendChild(this.svg);
  8465. };
  8466. DataAxis.prototype._redrawGroupIcons = function () {
  8467. DOMutil.prepareElements(this.svgElements);
  8468. var x;
  8469. var iconWidth = this.options.iconWidth;
  8470. var iconHeight = 15;
  8471. var iconOffset = 4;
  8472. var y = iconOffset + 0.5 * iconHeight;
  8473. if (this.options.orientation == 'left') {
  8474. x = iconOffset;
  8475. }
  8476. else {
  8477. x = this.width - iconWidth - iconOffset;
  8478. }
  8479. for (var groupId in this.groups) {
  8480. if (this.groups.hasOwnProperty(groupId)) {
  8481. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  8482. this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight);
  8483. y += iconHeight + iconOffset;
  8484. }
  8485. }
  8486. }
  8487. DOMutil.cleanupElements(this.svgElements);
  8488. this.iconsRemoved = false;
  8489. };
  8490. DataAxis.prototype._cleanupIcons = function() {
  8491. if (this.iconsRemoved == false) {
  8492. DOMutil.prepareElements(this.svgElements);
  8493. DOMutil.cleanupElements(this.svgElements);
  8494. this.iconsRemoved = true;
  8495. }
  8496. }
  8497. /**
  8498. * Create the HTML DOM for the DataAxis
  8499. */
  8500. DataAxis.prototype.show = function() {
  8501. this.hidden = false;
  8502. if (!this.dom.frame.parentNode) {
  8503. if (this.options.orientation == 'left') {
  8504. this.body.dom.left.appendChild(this.dom.frame);
  8505. }
  8506. else {
  8507. this.body.dom.right.appendChild(this.dom.frame);
  8508. }
  8509. }
  8510. if (!this.dom.lineContainer.parentNode) {
  8511. this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer);
  8512. }
  8513. };
  8514. /**
  8515. * Create the HTML DOM for the DataAxis
  8516. */
  8517. DataAxis.prototype.hide = function() {
  8518. this.hidden = true;
  8519. if (this.dom.frame.parentNode) {
  8520. this.dom.frame.parentNode.removeChild(this.dom.frame);
  8521. }
  8522. if (this.dom.lineContainer.parentNode) {
  8523. this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer);
  8524. }
  8525. };
  8526. /**
  8527. * Set a range (start and end)
  8528. * @param end
  8529. * @param start
  8530. * @param end
  8531. */
  8532. DataAxis.prototype.setRange = function (start, end) {
  8533. if (this.master == false && this.options.alignZeros == true && this.zeroCrossing != -1) {
  8534. if (start > 0) {
  8535. start = 0;
  8536. }
  8537. }
  8538. this.range.start = start;
  8539. this.range.end = end;
  8540. };
  8541. /**
  8542. * Repaint the component
  8543. * @return {boolean} Returns true if the component is resized
  8544. */
  8545. DataAxis.prototype.redraw = function () {
  8546. var resized = false;
  8547. var activeGroups = 0;
  8548. // Make sure the line container adheres to the vertical scrolling.
  8549. this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px';
  8550. for (var groupId in this.groups) {
  8551. if (this.groups.hasOwnProperty(groupId)) {
  8552. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  8553. activeGroups++;
  8554. }
  8555. }
  8556. }
  8557. if (this.amountOfGroups == 0 || activeGroups == 0) {
  8558. this.hide();
  8559. }
  8560. else {
  8561. this.show();
  8562. this.height = Number(this.linegraphSVG.style.height.replace("px",""));
  8563. // svg offsetheight did not work in firefox and explorer...
  8564. this.dom.lineContainer.style.height = this.height + 'px';
  8565. this.width = this.options.visible == true ? Number(('' + this.options.width).replace("px","")) : 0;
  8566. var props = this.props;
  8567. var frame = this.dom.frame;
  8568. // update classname
  8569. frame.className = 'dataaxis';
  8570. // calculate character width and height
  8571. this._calculateCharSize();
  8572. var orientation = this.options.orientation;
  8573. var showMinorLabels = this.options.showMinorLabels;
  8574. var showMajorLabels = this.options.showMajorLabels;
  8575. // determine the width and height of the elements for the axis
  8576. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  8577. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  8578. props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset;
  8579. props.minorLineHeight = 1;
  8580. props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset;
  8581. props.majorLineHeight = 1;
  8582. // take frame offline while updating (is almost twice as fast)
  8583. if (orientation == 'left') {
  8584. frame.style.top = '0';
  8585. frame.style.left = '0';
  8586. frame.style.bottom = '';
  8587. frame.style.width = this.width + 'px';
  8588. frame.style.height = this.height + "px";
  8589. this.props.width = this.body.domProps.left.width;
  8590. this.props.height = this.body.domProps.left.height;
  8591. }
  8592. else { // right
  8593. frame.style.top = '';
  8594. frame.style.bottom = '0';
  8595. frame.style.left = '0';
  8596. frame.style.width = this.width + 'px';
  8597. frame.style.height = this.height + "px";
  8598. this.props.width = this.body.domProps.right.width;
  8599. this.props.height = this.body.domProps.right.height;
  8600. }
  8601. resized = this._redrawLabels();
  8602. resized = this._isResized() || resized;
  8603. if (this.options.icons == true) {
  8604. this._redrawGroupIcons();
  8605. }
  8606. else {
  8607. this._cleanupIcons();
  8608. }
  8609. this._redrawTitle(orientation);
  8610. }
  8611. return resized;
  8612. };
  8613. /**
  8614. * Repaint major and minor text labels and vertical grid lines
  8615. * @private
  8616. */
  8617. DataAxis.prototype._redrawLabels = function () {
  8618. var resized = false;
  8619. DOMutil.prepareElements(this.DOMelements.lines);
  8620. DOMutil.prepareElements(this.DOMelements.labels);
  8621. var orientation = this.options['orientation'];
  8622. // calculate range and step (step such that we have space for 7 characters per label)
  8623. var minimumStep = this.master ? this.props.majorCharHeight || 10 : this.stepPixelsForced;
  8624. var step = new DataStep(
  8625. this.range.start,
  8626. this.range.end,
  8627. minimumStep,
  8628. this.dom.frame.offsetHeight,
  8629. this.options.customRange[this.options.orientation],
  8630. this.master == false && this.options.alignZeros // doess the step have to align zeros? only if not master and the options is on
  8631. );
  8632. this.step = step;
  8633. // get the distance in pixels for a step
  8634. // dead space is space that is "left over" after a step
  8635. var stepPixels = (this.dom.frame.offsetHeight - (step.deadSpace * (this.dom.frame.offsetHeight / step.marginRange))) / (((step.marginRange - step.deadSpace) / step.step));
  8636. this.stepPixels = stepPixels;
  8637. var amountOfSteps = this.height / stepPixels;
  8638. var stepDifference = 0;
  8639. // the slave axis needs to use the same horizontal lines as the master axis.
  8640. if (this.master == false) {
  8641. stepPixels = this.stepPixelsForced;
  8642. stepDifference = Math.round((this.dom.frame.offsetHeight / stepPixels) - amountOfSteps);
  8643. for (var i = 0; i < 0.5 * stepDifference; i++) {
  8644. step.previous();
  8645. }
  8646. amountOfSteps = this.height / stepPixels;
  8647. if (this.zeroCrossing != -1 && this.options.alignZeros == true) {
  8648. var zeroStepDifference = (step.marginEnd / step.step) - this.zeroCrossing;
  8649. if (zeroStepDifference > 0) {
  8650. for (var i = 0; i < zeroStepDifference; i++) {step.next();}
  8651. }
  8652. else if (zeroStepDifference < 0) {
  8653. for (var i = 0; i < -zeroStepDifference; i++) {step.previous();}
  8654. }
  8655. }
  8656. }
  8657. else {
  8658. amountOfSteps += 0.25;
  8659. }
  8660. this.valueAtZero = step.marginEnd;
  8661. var marginStartPos = 0;
  8662. // do not draw the first label
  8663. var max = 1;
  8664. // Get the number of decimal places
  8665. var decimals;
  8666. if(this.options.format[orientation] !== undefined) {
  8667. decimals = this.options.format[orientation].decimals;
  8668. }
  8669. this.maxLabelSize = 0;
  8670. var y = 0;
  8671. while (max < Math.round(amountOfSteps)) {
  8672. step.next();
  8673. y = Math.round(max * stepPixels);
  8674. marginStartPos = max * stepPixels;
  8675. var isMajor = step.isMajor();
  8676. if (this.options['showMinorLabels'] && isMajor == false || this.master == false && this.options['showMinorLabels'] == true) {
  8677. this._redrawLabel(y - 2, step.getCurrent(decimals), orientation, 'yAxis minor', this.props.minorCharHeight);
  8678. }
  8679. if (isMajor && this.options['showMajorLabels'] && this.master == true ||
  8680. this.options['showMinorLabels'] == false && this.master == false && isMajor == true) {
  8681. if (y >= 0) {
  8682. this._redrawLabel(y - 2, step.getCurrent(decimals), orientation, 'yAxis major', this.props.majorCharHeight);
  8683. }
  8684. this._redrawLine(y, orientation, 'grid horizontal major', this.options.majorLinesOffset, this.props.majorLineWidth);
  8685. }
  8686. else {
  8687. this._redrawLine(y, orientation, 'grid horizontal minor', this.options.minorLinesOffset, this.props.minorLineWidth);
  8688. }
  8689. if (this.master == true && step.current == 0) {
  8690. this.zeroCrossing = max;
  8691. }
  8692. max++;
  8693. }
  8694. if (this.master == false) {
  8695. this.conversionFactor = y / (this.valueAtZero - step.current);
  8696. }
  8697. else {
  8698. this.conversionFactor = this.dom.frame.offsetHeight / step.marginRange;
  8699. }
  8700. // Note that title is rotated, so we're using the height, not width!
  8701. var titleWidth = 0;
  8702. if (this.options.title[orientation] !== undefined && this.options.title[orientation].text !== undefined) {
  8703. titleWidth = this.props.titleCharHeight;
  8704. }
  8705. var offset = this.options.icons == true ? Math.max(this.options.iconWidth, titleWidth) + this.options.labelOffsetX + 15 : titleWidth + this.options.labelOffsetX + 15;
  8706. // this will resize the yAxis to accommodate the labels.
  8707. if (this.maxLabelSize > (this.width - offset) && this.options.visible == true) {
  8708. this.width = this.maxLabelSize + offset;
  8709. this.options.width = this.width + "px";
  8710. DOMutil.cleanupElements(this.DOMelements.lines);
  8711. DOMutil.cleanupElements(this.DOMelements.labels);
  8712. this.redraw();
  8713. resized = true;
  8714. }
  8715. // this will resize the yAxis if it is too big for the labels.
  8716. else if (this.maxLabelSize < (this.width - offset) && this.options.visible == true && this.width > this.minWidth) {
  8717. this.width = Math.max(this.minWidth,this.maxLabelSize + offset);
  8718. this.options.width = this.width + "px";
  8719. DOMutil.cleanupElements(this.DOMelements.lines);
  8720. DOMutil.cleanupElements(this.DOMelements.labels);
  8721. this.redraw();
  8722. resized = true;
  8723. }
  8724. else {
  8725. DOMutil.cleanupElements(this.DOMelements.lines);
  8726. DOMutil.cleanupElements(this.DOMelements.labels);
  8727. resized = false;
  8728. }
  8729. return resized;
  8730. };
  8731. DataAxis.prototype.convertValue = function (value) {
  8732. var invertedValue = this.valueAtZero - value;
  8733. var convertedValue = invertedValue * this.conversionFactor;
  8734. return convertedValue;
  8735. };
  8736. /**
  8737. * Create a label for the axis at position x
  8738. * @private
  8739. * @param y
  8740. * @param text
  8741. * @param orientation
  8742. * @param className
  8743. * @param characterHeight
  8744. */
  8745. DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) {
  8746. // reuse redundant label
  8747. var label = DOMutil.getDOMElement('div',this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift();
  8748. label.className = className;
  8749. label.innerHTML = text;
  8750. if (orientation == 'left') {
  8751. label.style.left = '-' + this.options.labelOffsetX + 'px';
  8752. label.style.textAlign = "right";
  8753. }
  8754. else {
  8755. label.style.right = '-' + this.options.labelOffsetX + 'px';
  8756. label.style.textAlign = "left";
  8757. }
  8758. label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px';
  8759. text += '';
  8760. var largestWidth = Math.max(this.props.majorCharWidth,this.props.minorCharWidth);
  8761. if (this.maxLabelSize < text.length * largestWidth) {
  8762. this.maxLabelSize = text.length * largestWidth;
  8763. }
  8764. };
  8765. /**
  8766. * Create a minor line for the axis at position y
  8767. * @param y
  8768. * @param orientation
  8769. * @param className
  8770. * @param offset
  8771. * @param width
  8772. */
  8773. DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) {
  8774. if (this.master == true) {
  8775. var line = DOMutil.getDOMElement('div',this.DOMelements.lines, this.dom.lineContainer);//this.dom.redundant.lines.shift();
  8776. line.className = className;
  8777. line.innerHTML = '';
  8778. if (orientation == 'left') {
  8779. line.style.left = (this.width - offset) + 'px';
  8780. }
  8781. else {
  8782. line.style.right = (this.width - offset) + 'px';
  8783. }
  8784. line.style.width = width + 'px';
  8785. line.style.top = y + 'px';
  8786. }
  8787. };
  8788. /**
  8789. * Create a title for the axis
  8790. * @private
  8791. * @param orientation
  8792. */
  8793. DataAxis.prototype._redrawTitle = function (orientation) {
  8794. DOMutil.prepareElements(this.DOMelements.title);
  8795. // Check if the title is defined for this axes
  8796. if (this.options.title[orientation] !== undefined && this.options.title[orientation].text !== undefined) {
  8797. var title = DOMutil.getDOMElement('div', this.DOMelements.title, this.dom.frame);
  8798. title.className = 'yAxis title ' + orientation;
  8799. title.innerHTML = this.options.title[orientation].text;
  8800. // Add style - if provided
  8801. if (this.options.title[orientation].style !== undefined) {
  8802. util.addCssText(title, this.options.title[orientation].style);
  8803. }
  8804. if (orientation == 'left') {
  8805. title.style.left = this.props.titleCharHeight + 'px';
  8806. }
  8807. else {
  8808. title.style.right = this.props.titleCharHeight + 'px';
  8809. }
  8810. title.style.width = this.height + 'px';
  8811. }
  8812. // we need to clean up in case we did not use all elements.
  8813. DOMutil.cleanupElements(this.DOMelements.title);
  8814. };
  8815. /**
  8816. * Determine the size of text on the axis (both major and minor axis).
  8817. * The size is calculated only once and then cached in this.props.
  8818. * @private
  8819. */
  8820. DataAxis.prototype._calculateCharSize = function () {
  8821. // determine the char width and height on the minor axis
  8822. if (!('minorCharHeight' in this.props)) {
  8823. var textMinor = document.createTextNode('0');
  8824. var measureCharMinor = document.createElement('div');
  8825. measureCharMinor.className = 'yAxis minor measure';
  8826. measureCharMinor.appendChild(textMinor);
  8827. this.dom.frame.appendChild(measureCharMinor);
  8828. this.props.minorCharHeight = measureCharMinor.clientHeight;
  8829. this.props.minorCharWidth = measureCharMinor.clientWidth;
  8830. this.dom.frame.removeChild(measureCharMinor);
  8831. }
  8832. if (!('majorCharHeight' in this.props)) {
  8833. var textMajor = document.createTextNode('0');
  8834. var measureCharMajor = document.createElement('div');
  8835. measureCharMajor.className = 'yAxis major measure';
  8836. measureCharMajor.appendChild(textMajor);
  8837. this.dom.frame.appendChild(measureCharMajor);
  8838. this.props.majorCharHeight = measureCharMajor.clientHeight;
  8839. this.props.majorCharWidth = measureCharMajor.clientWidth;
  8840. this.dom.frame.removeChild(measureCharMajor);
  8841. }
  8842. if (!('titleCharHeight' in this.props)) {
  8843. var textTitle = document.createTextNode('0');
  8844. var measureCharTitle = document.createElement('div');
  8845. measureCharTitle.className = 'yAxis title measure';
  8846. measureCharTitle.appendChild(textTitle);
  8847. this.dom.frame.appendChild(measureCharTitle);
  8848. this.props.titleCharHeight = measureCharTitle.clientHeight;
  8849. this.props.titleCharWidth = measureCharTitle.clientWidth;
  8850. this.dom.frame.removeChild(measureCharTitle);
  8851. }
  8852. };
  8853. /**
  8854. * Snap a date to a rounded value.
  8855. * The snap intervals are dependent on the current scale and step.
  8856. * @param {Date} date the date to be snapped.
  8857. * @return {Date} snappedDate
  8858. */
  8859. DataAxis.prototype.snap = function(date) {
  8860. return this.step.snap(date);
  8861. };
  8862. module.exports = DataAxis;
  8863. /***/ },
  8864. /* 24 */
  8865. /***/ function(module, exports, __webpack_require__) {
  8866. var util = __webpack_require__(1);
  8867. var DOMutil = __webpack_require__(2);
  8868. var Line = __webpack_require__(51);
  8869. var Bar = __webpack_require__(52);
  8870. var Points = __webpack_require__(53);
  8871. /**
  8872. * /**
  8873. * @param {object} group | the object of the group from the dataset
  8874. * @param {string} groupId | ID of the group
  8875. * @param {object} options | the default options
  8876. * @param {array} groupsUsingDefaultStyles | this array has one entree.
  8877. * It is passed as an array so it is passed by reference.
  8878. * It enumerates through the default styles
  8879. * @constructor
  8880. */
  8881. function GraphGroup (group, groupId, options, groupsUsingDefaultStyles) {
  8882. this.id = groupId;
  8883. var fields = ['sampling','style','sort','yAxisOrientation','barChart','drawPoints','shaded','catmullRom']
  8884. this.options = util.selectiveBridgeObject(fields,options);
  8885. this.usingDefaultStyle = group.className === undefined;
  8886. this.groupsUsingDefaultStyles = groupsUsingDefaultStyles;
  8887. this.zeroPosition = 0;
  8888. this.update(group);
  8889. if (this.usingDefaultStyle == true) {
  8890. this.groupsUsingDefaultStyles[0] += 1;
  8891. }
  8892. this.itemsData = [];
  8893. this.visible = group.visible === undefined ? true : group.visible;
  8894. }
  8895. /**
  8896. * this loads a reference to all items in this group into this group.
  8897. * @param {array} items
  8898. */
  8899. GraphGroup.prototype.setItems = function(items) {
  8900. if (items != null) {
  8901. this.itemsData = items;
  8902. if (this.options.sort == true) {
  8903. this.itemsData.sort(function (a,b) {return a.x - b.x;})
  8904. }
  8905. }
  8906. else {
  8907. this.itemsData = [];
  8908. }
  8909. };
  8910. /**
  8911. * this is used for plotting barcharts, this way, we only have to calculate it once.
  8912. * @param pos
  8913. */
  8914. GraphGroup.prototype.setZeroPosition = function(pos) {
  8915. this.zeroPosition = pos;
  8916. };
  8917. /**
  8918. * set the options of the graph group over the default options.
  8919. * @param options
  8920. */
  8921. GraphGroup.prototype.setOptions = function(options) {
  8922. if (options !== undefined) {
  8923. var fields = ['sampling','style','sort','yAxisOrientation','barChart'];
  8924. util.selectiveDeepExtend(fields, this.options, options);
  8925. util.mergeOptions(this.options, options,'catmullRom');
  8926. util.mergeOptions(this.options, options,'drawPoints');
  8927. util.mergeOptions(this.options, options,'shaded');
  8928. if (options.catmullRom) {
  8929. if (typeof options.catmullRom == 'object') {
  8930. if (options.catmullRom.parametrization) {
  8931. if (options.catmullRom.parametrization == 'uniform') {
  8932. this.options.catmullRom.alpha = 0;
  8933. }
  8934. else if (options.catmullRom.parametrization == 'chordal') {
  8935. this.options.catmullRom.alpha = 1.0;
  8936. }
  8937. else {
  8938. this.options.catmullRom.parametrization = 'centripetal';
  8939. this.options.catmullRom.alpha = 0.5;
  8940. }
  8941. }
  8942. }
  8943. }
  8944. }
  8945. if (this.options.style == 'line') {
  8946. this.type = new Line(this.id, this.options);
  8947. }
  8948. else if (this.options.style == 'bar') {
  8949. this.type = new Bar(this.id, this.options);
  8950. }
  8951. else if (this.options.style == 'points') {
  8952. this.type = new Points(this.id, this.options);
  8953. }
  8954. };
  8955. /**
  8956. * this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph
  8957. * @param group
  8958. */
  8959. GraphGroup.prototype.update = function(group) {
  8960. this.group = group;
  8961. this.content = group.content || 'graph';
  8962. this.className = group.className || this.className || "graphGroup" + this.groupsUsingDefaultStyles[0] % 10;
  8963. this.visible = group.visible === undefined ? true : group.visible;
  8964. this.style = group.style;
  8965. this.setOptions(group.options);
  8966. };
  8967. /**
  8968. * draw the icon for the legend.
  8969. *
  8970. * @param x
  8971. * @param y
  8972. * @param JSONcontainer
  8973. * @param SVGcontainer
  8974. * @param iconWidth
  8975. * @param iconHeight
  8976. */
  8977. GraphGroup.prototype.drawIcon = function(x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) {
  8978. var fillHeight = iconHeight * 0.5;
  8979. var path, fillPath;
  8980. var outline = DOMutil.getSVGElement("rect", JSONcontainer, SVGcontainer);
  8981. outline.setAttributeNS(null, "x", x);
  8982. outline.setAttributeNS(null, "y", y - fillHeight);
  8983. outline.setAttributeNS(null, "width", iconWidth);
  8984. outline.setAttributeNS(null, "height", 2*fillHeight);
  8985. outline.setAttributeNS(null, "class", "outline");
  8986. if (this.options.style == 'line') {
  8987. path = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
  8988. path.setAttributeNS(null, "class", this.className);
  8989. if(this.style !== undefined) {
  8990. path.setAttributeNS(null, "style", this.style);
  8991. }
  8992. path.setAttributeNS(null, "d", "M" + x + ","+y+" L" + (x + iconWidth) + ","+y+"");
  8993. if (this.options.shaded.enabled == true) {
  8994. fillPath = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
  8995. if (this.options.shaded.orientation == 'top') {
  8996. fillPath.setAttributeNS(null, "d", "M"+x+", " + (y - fillHeight) +
  8997. "L"+x+","+y+" L"+ (x + iconWidth) + ","+y+" L"+ (x + iconWidth) + "," + (y - fillHeight));
  8998. }
  8999. else {
  9000. fillPath.setAttributeNS(null, "d", "M"+x+","+y+" " +
  9001. "L"+x+"," + (y + fillHeight) + " " +
  9002. "L"+ (x + iconWidth) + "," + (y + fillHeight) +
  9003. "L"+ (x + iconWidth) + ","+y);
  9004. }
  9005. fillPath.setAttributeNS(null, "class", this.className + " iconFill");
  9006. }
  9007. if (this.options.drawPoints.enabled == true) {
  9008. DOMutil.drawPoint(x + 0.5 * iconWidth,y, this, JSONcontainer, SVGcontainer);
  9009. }
  9010. }
  9011. else {
  9012. var barWidth = Math.round(0.3 * iconWidth);
  9013. var bar1Height = Math.round(0.4 * iconHeight);
  9014. var bar2Height = Math.round(0.75 * iconHeight);
  9015. var offset = Math.round((iconWidth - (2 * barWidth))/3);
  9016. DOMutil.drawBar(x + 0.5*barWidth + offset , y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' bar', JSONcontainer, SVGcontainer);
  9017. DOMutil.drawBar(x + 1.5*barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' bar', JSONcontainer, SVGcontainer);
  9018. }
  9019. };
  9020. /**
  9021. * return the legend entree for this group.
  9022. *
  9023. * @param iconWidth
  9024. * @param iconHeight
  9025. * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}}
  9026. */
  9027. GraphGroup.prototype.getLegend = function(iconWidth, iconHeight) {
  9028. var svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  9029. this.drawIcon(0,0.5*iconHeight,[],svg,iconWidth,iconHeight);
  9030. return {icon: svg, label: this.content, orientation:this.options.yAxisOrientation};
  9031. }
  9032. GraphGroup.prototype.getYRange = function(groupData) {
  9033. return this.type.getYRange(groupData);
  9034. }
  9035. GraphGroup.prototype.draw = function(dataset, group, framework) {
  9036. this.type.draw(dataset, group, framework);
  9037. }
  9038. module.exports = GraphGroup;
  9039. /***/ },
  9040. /* 25 */
  9041. /***/ function(module, exports, __webpack_require__) {
  9042. var util = __webpack_require__(1);
  9043. var stack = __webpack_require__(18);
  9044. var RangeItem = __webpack_require__(35);
  9045. /**
  9046. * @constructor Group
  9047. * @param {Number | String} groupId
  9048. * @param {Object} data
  9049. * @param {ItemSet} itemSet
  9050. */
  9051. function Group (groupId, data, itemSet) {
  9052. this.groupId = groupId;
  9053. this.subgroups = {};
  9054. this.subgroupIndex = 0;
  9055. this.subgroupOrderer = data && data.subgroupOrder;
  9056. this.itemSet = itemSet;
  9057. this.dom = {};
  9058. this.props = {
  9059. label: {
  9060. width: 0,
  9061. height: 0
  9062. }
  9063. };
  9064. this.className = null;
  9065. this.items = {}; // items filtered by groupId of this group
  9066. this.visibleItems = []; // items currently visible in window
  9067. this.orderedItems = {
  9068. byStart: [],
  9069. byEnd: []
  9070. };
  9071. this.checkRangedItems = false; // needed to refresh the ranged items if the window is programatically changed with NO overlap.
  9072. var me = this;
  9073. this.itemSet.body.emitter.on("checkRangedItems", function () {
  9074. me.checkRangedItems = true;
  9075. })
  9076. this._create();
  9077. this.setData(data);
  9078. }
  9079. /**
  9080. * Create DOM elements for the group
  9081. * @private
  9082. */
  9083. Group.prototype._create = function() {
  9084. var label = document.createElement('div');
  9085. label.className = 'vlabel';
  9086. this.dom.label = label;
  9087. var inner = document.createElement('div');
  9088. inner.className = 'inner';
  9089. label.appendChild(inner);
  9090. this.dom.inner = inner;
  9091. var foreground = document.createElement('div');
  9092. foreground.className = 'group';
  9093. foreground['timeline-group'] = this;
  9094. this.dom.foreground = foreground;
  9095. this.dom.background = document.createElement('div');
  9096. this.dom.background.className = 'group';
  9097. this.dom.axis = document.createElement('div');
  9098. this.dom.axis.className = 'group';
  9099. // create a hidden marker to detect when the Timelines container is attached
  9100. // to the DOM, or the style of a parent of the Timeline is changed from
  9101. // display:none is changed to visible.
  9102. this.dom.marker = document.createElement('div');
  9103. this.dom.marker.style.visibility = 'hidden'; // TODO: ask jos why this is not none?
  9104. this.dom.marker.innerHTML = '?';
  9105. this.dom.background.appendChild(this.dom.marker);
  9106. };
  9107. /**
  9108. * Set the group data for this group
  9109. * @param {Object} data Group data, can contain properties content and className
  9110. */
  9111. Group.prototype.setData = function(data) {
  9112. // update contents
  9113. var content = data && data.content;
  9114. if (content instanceof Element) {
  9115. this.dom.inner.appendChild(content);
  9116. }
  9117. else if (content !== undefined && content !== null) {
  9118. this.dom.inner.innerHTML = content;
  9119. }
  9120. else {
  9121. this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null
  9122. }
  9123. // update title
  9124. this.dom.label.title = data && data.title || '';
  9125. if (!this.dom.inner.firstChild) {
  9126. util.addClassName(this.dom.inner, 'hidden');
  9127. }
  9128. else {
  9129. util.removeClassName(this.dom.inner, 'hidden');
  9130. }
  9131. // update className
  9132. var className = data && data.className || null;
  9133. if (className != this.className) {
  9134. if (this.className) {
  9135. util.removeClassName(this.dom.label, this.className);
  9136. util.removeClassName(this.dom.foreground, this.className);
  9137. util.removeClassName(this.dom.background, this.className);
  9138. util.removeClassName(this.dom.axis, this.className);
  9139. }
  9140. util.addClassName(this.dom.label, className);
  9141. util.addClassName(this.dom.foreground, className);
  9142. util.addClassName(this.dom.background, className);
  9143. util.addClassName(this.dom.axis, className);
  9144. this.className = className;
  9145. }
  9146. // update style
  9147. if (this.style) {
  9148. util.removeCssText(this.dom.label, this.style);
  9149. this.style = null;
  9150. }
  9151. if (data && data.style) {
  9152. util.addCssText(this.dom.label, data.style);
  9153. this.style = data.style;
  9154. }
  9155. };
  9156. /**
  9157. * Get the width of the group label
  9158. * @return {number} width
  9159. */
  9160. Group.prototype.getLabelWidth = function() {
  9161. return this.props.label.width;
  9162. };
  9163. /**
  9164. * Repaint this group
  9165. * @param {{start: number, end: number}} range
  9166. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  9167. * @param {boolean} [restack=false] Force restacking of all items
  9168. * @return {boolean} Returns true if the group is resized
  9169. */
  9170. Group.prototype.redraw = function(range, margin, restack) {
  9171. var resized = false;
  9172. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  9173. // force recalculation of the height of the items when the marker height changed
  9174. // (due to the Timeline being attached to the DOM or changed from display:none to visible)
  9175. var markerHeight = this.dom.marker.clientHeight;
  9176. if (markerHeight != this.lastMarkerHeight) {
  9177. this.lastMarkerHeight = markerHeight;
  9178. util.forEach(this.items, function (item) {
  9179. item.dirty = true;
  9180. if (item.displayed) item.redraw();
  9181. });
  9182. restack = true;
  9183. }
  9184. // reposition visible items vertically
  9185. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  9186. stack.stack(this.visibleItems, margin, restack);
  9187. }
  9188. else { // no stacking
  9189. stack.nostack(this.visibleItems, margin, this.subgroups);
  9190. }
  9191. // recalculate the height of the group
  9192. var height = this._calculateHeight(margin);
  9193. // calculate actual size and position
  9194. var foreground = this.dom.foreground;
  9195. this.top = foreground.offsetTop;
  9196. this.left = foreground.offsetLeft;
  9197. this.width = foreground.offsetWidth;
  9198. resized = util.updateProperty(this, 'height', height) || resized;
  9199. // recalculate size of label
  9200. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  9201. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  9202. // apply new height
  9203. this.dom.background.style.height = height + 'px';
  9204. this.dom.foreground.style.height = height + 'px';
  9205. this.dom.label.style.height = height + 'px';
  9206. // update vertical position of items after they are re-stacked and the height of the group is calculated
  9207. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  9208. var item = this.visibleItems[i];
  9209. item.repositionY(margin);
  9210. }
  9211. return resized;
  9212. };
  9213. /**
  9214. * recalculate the height of the group
  9215. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  9216. * @returns {number} Returns the height
  9217. * @private
  9218. */
  9219. Group.prototype._calculateHeight = function (margin) {
  9220. // recalculate the height of the group
  9221. var height;
  9222. var visibleItems = this.visibleItems;
  9223. //var visibleSubgroups = [];
  9224. //this.visibleSubgroups = 0;
  9225. this.resetSubgroups();
  9226. var me = this;
  9227. if (visibleItems.length) {
  9228. var min = visibleItems[0].top;
  9229. var max = visibleItems[0].top + visibleItems[0].height;
  9230. util.forEach(visibleItems, function (item) {
  9231. min = Math.min(min, item.top);
  9232. max = Math.max(max, (item.top + item.height));
  9233. if (item.data.subgroup !== undefined) {
  9234. me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height,item.height);
  9235. me.subgroups[item.data.subgroup].visible = true;
  9236. //if (visibleSubgroups.indexOf(item.data.subgroup) == -1){
  9237. // visibleSubgroups.push(item.data.subgroup);
  9238. // me.visibleSubgroups += 1;
  9239. //}
  9240. }
  9241. });
  9242. if (min > margin.axis) {
  9243. // there is an empty gap between the lowest item and the axis
  9244. var offset = min - margin.axis;
  9245. max -= offset;
  9246. util.forEach(visibleItems, function (item) {
  9247. item.top -= offset;
  9248. });
  9249. }
  9250. height = max + margin.item.vertical / 2;
  9251. }
  9252. else {
  9253. height = margin.axis + margin.item.vertical;
  9254. }
  9255. height = Math.max(height, this.props.label.height);
  9256. return height;
  9257. };
  9258. /**
  9259. * Show this group: attach to the DOM
  9260. */
  9261. Group.prototype.show = function() {
  9262. if (!this.dom.label.parentNode) {
  9263. this.itemSet.dom.labelSet.appendChild(this.dom.label);
  9264. }
  9265. if (!this.dom.foreground.parentNode) {
  9266. this.itemSet.dom.foreground.appendChild(this.dom.foreground);
  9267. }
  9268. if (!this.dom.background.parentNode) {
  9269. this.itemSet.dom.background.appendChild(this.dom.background);
  9270. }
  9271. if (!this.dom.axis.parentNode) {
  9272. this.itemSet.dom.axis.appendChild(this.dom.axis);
  9273. }
  9274. };
  9275. /**
  9276. * Hide this group: remove from the DOM
  9277. */
  9278. Group.prototype.hide = function() {
  9279. var label = this.dom.label;
  9280. if (label.parentNode) {
  9281. label.parentNode.removeChild(label);
  9282. }
  9283. var foreground = this.dom.foreground;
  9284. if (foreground.parentNode) {
  9285. foreground.parentNode.removeChild(foreground);
  9286. }
  9287. var background = this.dom.background;
  9288. if (background.parentNode) {
  9289. background.parentNode.removeChild(background);
  9290. }
  9291. var axis = this.dom.axis;
  9292. if (axis.parentNode) {
  9293. axis.parentNode.removeChild(axis);
  9294. }
  9295. };
  9296. /**
  9297. * Add an item to the group
  9298. * @param {Item} item
  9299. */
  9300. Group.prototype.add = function(item) {
  9301. this.items[item.id] = item;
  9302. item.setParent(this);
  9303. // add to
  9304. if (item.data.subgroup !== undefined) {
  9305. if (this.subgroups[item.data.subgroup] === undefined) {
  9306. this.subgroups[item.data.subgroup] = {height:0, visible: false, index:this.subgroupIndex, items: []};
  9307. this.subgroupIndex++;
  9308. }
  9309. this.subgroups[item.data.subgroup].items.push(item);
  9310. }
  9311. this.orderSubgroups();
  9312. if (this.visibleItems.indexOf(item) == -1) {
  9313. var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
  9314. this._checkIfVisible(item, this.visibleItems, range);
  9315. }
  9316. };
  9317. Group.prototype.orderSubgroups = function() {
  9318. if (this.subgroupOrderer !== undefined) {
  9319. var sortArray = [];
  9320. if (typeof this.subgroupOrderer == 'string') {
  9321. for (var subgroup in this.subgroups) {
  9322. sortArray.push({subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer]})
  9323. }
  9324. sortArray.sort(function (a, b) {
  9325. return a.sortField - b.sortField;
  9326. })
  9327. }
  9328. else if (typeof this.subgroupOrderer == 'function') {
  9329. for (var subgroup in this.subgroups) {
  9330. sortArray.push(this.subgroups[subgroup].items[0].data);
  9331. }
  9332. sortArray.sort(this.subgroupOrderer);
  9333. }
  9334. if (sortArray.length > 0) {
  9335. for (var i = 0; i < sortArray.length; i++) {
  9336. this.subgroups[sortArray[i].subgroup].index = i;
  9337. }
  9338. }
  9339. }
  9340. };
  9341. Group.prototype.resetSubgroups = function() {
  9342. for (var subgroup in this.subgroups) {
  9343. if (this.subgroups.hasOwnProperty(subgroup)) {
  9344. this.subgroups[subgroup].visible = false;
  9345. }
  9346. }
  9347. };
  9348. /**
  9349. * Remove an item from the group
  9350. * @param {Item} item
  9351. */
  9352. Group.prototype.remove = function(item) {
  9353. delete this.items[item.id];
  9354. item.setParent(null);
  9355. // remove from visible items
  9356. var index = this.visibleItems.indexOf(item);
  9357. if (index != -1) this.visibleItems.splice(index, 1);
  9358. // TODO: also remove from ordered items?
  9359. };
  9360. /**
  9361. * Remove an item from the corresponding DataSet
  9362. * @param {Item} item
  9363. */
  9364. Group.prototype.removeFromDataSet = function(item) {
  9365. this.itemSet.removeItem(item.id);
  9366. };
  9367. /**
  9368. * Reorder the items
  9369. */
  9370. Group.prototype.order = function() {
  9371. var array = util.toArray(this.items);
  9372. var startArray = [];
  9373. var endArray = [];
  9374. for (var i = 0; i < array.length; i++) {
  9375. if (array[i].data.end !== undefined) {
  9376. endArray.push(array[i]);
  9377. }
  9378. startArray.push(array[i]);
  9379. }
  9380. this.orderedItems = {
  9381. byStart: startArray,
  9382. byEnd: endArray
  9383. };
  9384. stack.orderByStart(this.orderedItems.byStart);
  9385. stack.orderByEnd(this.orderedItems.byEnd);
  9386. };
  9387. /**
  9388. * Update the visible items
  9389. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  9390. * @param {Item[]} visibleItems The previously visible items.
  9391. * @param {{start: number, end: number}} range Visible range
  9392. * @return {Item[]} visibleItems The new visible items.
  9393. * @private
  9394. */
  9395. Group.prototype._updateVisibleItems = function(orderedItems, oldVisibleItems, range) {
  9396. var visibleItems = [];
  9397. var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
  9398. var interval = (range.end - range.start) / 4;
  9399. var lowerBound = range.start - interval;
  9400. var upperBound = range.end + interval;
  9401. var item, i;
  9402. // this function is used to do the binary search.
  9403. var searchFunction = function (value) {
  9404. if (value < lowerBound) {return -1;}
  9405. else if (value <= upperBound) {return 0;}
  9406. else {return 1;}
  9407. }
  9408. // first check if the items that were in view previously are still in view.
  9409. // IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
  9410. // also cleans up invisible items.
  9411. if (oldVisibleItems.length > 0) {
  9412. for (i = 0; i < oldVisibleItems.length; i++) {
  9413. this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
  9414. }
  9415. }
  9416. // we do a binary search for the items that have only start values.
  9417. var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data','start');
  9418. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
  9419. this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
  9420. return (item.data.start < lowerBound || item.data.start > upperBound);
  9421. });
  9422. // if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
  9423. // We therefore have to brute force check all items in the byEnd list
  9424. if (this.checkRangedItems == true) {
  9425. this.checkRangedItems = false;
  9426. for (i = 0; i < orderedItems.byEnd.length; i++) {
  9427. this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
  9428. }
  9429. }
  9430. else {
  9431. // we do a binary search for the items that have defined end times.
  9432. var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data','end');
  9433. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
  9434. this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
  9435. return (item.data.end < lowerBound || item.data.end > upperBound);
  9436. });
  9437. }
  9438. // finally, we reposition all the visible items.
  9439. for (i = 0; i < visibleItems.length; i++) {
  9440. item = visibleItems[i];
  9441. if (!item.displayed) item.show();
  9442. // reposition item horizontally
  9443. item.repositionX();
  9444. }
  9445. // debug
  9446. //console.log("new line")
  9447. //if (this.groupId == null) {
  9448. // for (i = 0; i < orderedItems.byStart.length; i++) {
  9449. // item = orderedItems.byStart[i].data;
  9450. // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "")
  9451. // }
  9452. // for (i = 0; i < orderedItems.byEnd.length; i++) {
  9453. // item = orderedItems.byEnd[i].data;
  9454. // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "")
  9455. // }
  9456. //}
  9457. return visibleItems;
  9458. };
  9459. Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
  9460. var item;
  9461. var i;
  9462. if (initialPos != -1) {
  9463. for (i = initialPos; i >= 0; i--) {
  9464. item = items[i];
  9465. if (breakCondition(item)) {
  9466. break;
  9467. }
  9468. else {
  9469. if (visibleItemsLookup[item.id] === undefined) {
  9470. visibleItemsLookup[item.id] = true;
  9471. visibleItems.push(item);
  9472. }
  9473. }
  9474. }
  9475. for (i = initialPos + 1; i < items.length; i++) {
  9476. item = items[i];
  9477. if (breakCondition(item)) {
  9478. break;
  9479. }
  9480. else {
  9481. if (visibleItemsLookup[item.id] === undefined) {
  9482. visibleItemsLookup[item.id] = true;
  9483. visibleItems.push(item);
  9484. }
  9485. }
  9486. }
  9487. }
  9488. }
  9489. /**
  9490. * this function is very similar to the _checkIfInvisible() but it does not
  9491. * return booleans, hides the item if it should not be seen and always adds to
  9492. * the visibleItems.
  9493. * this one is for brute forcing and hiding.
  9494. *
  9495. * @param {Item} item
  9496. * @param {Array} visibleItems
  9497. * @param {{start:number, end:number}} range
  9498. * @private
  9499. */
  9500. Group.prototype._checkIfVisible = function(item, visibleItems, range) {
  9501. if (item.isVisible(range)) {
  9502. if (!item.displayed) item.show();
  9503. // reposition item horizontally
  9504. item.repositionX();
  9505. visibleItems.push(item);
  9506. }
  9507. else {
  9508. if (item.displayed) item.hide();
  9509. }
  9510. };
  9511. /**
  9512. * this function is very similar to the _checkIfInvisible() but it does not
  9513. * return booleans, hides the item if it should not be seen and always adds to
  9514. * the visibleItems.
  9515. * this one is for brute forcing and hiding.
  9516. *
  9517. * @param {Item} item
  9518. * @param {Array} visibleItems
  9519. * @param {{start:number, end:number}} range
  9520. * @private
  9521. */
  9522. Group.prototype._checkIfVisibleWithReference = function(item, visibleItems, visibleItemsLookup, range) {
  9523. if (item.isVisible(range)) {
  9524. if (visibleItemsLookup[item.id] === undefined) {
  9525. visibleItemsLookup[item.id] = true;
  9526. visibleItems.push(item);
  9527. }
  9528. }
  9529. else {
  9530. if (item.displayed) item.hide();
  9531. }
  9532. };
  9533. module.exports = Group;
  9534. /***/ },
  9535. /* 26 */
  9536. /***/ function(module, exports, __webpack_require__) {
  9537. var util = __webpack_require__(1);
  9538. var Group = __webpack_require__(25);
  9539. /**
  9540. * @constructor BackgroundGroup
  9541. * @param {Number | String} groupId
  9542. * @param {Object} data
  9543. * @param {ItemSet} itemSet
  9544. */
  9545. function BackgroundGroup (groupId, data, itemSet) {
  9546. Group.call(this, groupId, data, itemSet);
  9547. this.width = 0;
  9548. this.height = 0;
  9549. this.top = 0;
  9550. this.left = 0;
  9551. }
  9552. BackgroundGroup.prototype = Object.create(Group.prototype);
  9553. /**
  9554. * Repaint this group
  9555. * @param {{start: number, end: number}} range
  9556. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  9557. * @param {boolean} [restack=false] Force restacking of all items
  9558. * @return {boolean} Returns true if the group is resized
  9559. */
  9560. BackgroundGroup.prototype.redraw = function(range, margin, restack) {
  9561. var resized = false;
  9562. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  9563. // calculate actual size
  9564. this.width = this.dom.background.offsetWidth;
  9565. // apply new height (just always zero for BackgroundGroup
  9566. this.dom.background.style.height = '0';
  9567. // update vertical position of items after they are re-stacked and the height of the group is calculated
  9568. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  9569. var item = this.visibleItems[i];
  9570. item.repositionY(margin);
  9571. }
  9572. return resized;
  9573. };
  9574. /**
  9575. * Show this group: attach to the DOM
  9576. */
  9577. BackgroundGroup.prototype.show = function() {
  9578. if (!this.dom.background.parentNode) {
  9579. this.itemSet.dom.background.appendChild(this.dom.background);
  9580. }
  9581. };
  9582. module.exports = BackgroundGroup;
  9583. /***/ },
  9584. /* 27 */
  9585. /***/ function(module, exports, __webpack_require__) {
  9586. var Hammer = __webpack_require__(45);
  9587. var util = __webpack_require__(1);
  9588. var DataSet = __webpack_require__(3);
  9589. var DataView = __webpack_require__(4);
  9590. var Component = __webpack_require__(20);
  9591. var Group = __webpack_require__(25);
  9592. var BackgroundGroup = __webpack_require__(26);
  9593. var BoxItem = __webpack_require__(33);
  9594. var PointItem = __webpack_require__(34);
  9595. var RangeItem = __webpack_require__(35);
  9596. var BackgroundItem = __webpack_require__(32);
  9597. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  9598. var BACKGROUND = '__background__'; // reserved group id for background items without group
  9599. /**
  9600. * An ItemSet holds a set of items and ranges which can be displayed in a
  9601. * range. The width is determined by the parent of the ItemSet, and the height
  9602. * is determined by the size of the items.
  9603. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  9604. * @param {Object} [options] See ItemSet.setOptions for the available options.
  9605. * @constructor ItemSet
  9606. * @extends Component
  9607. */
  9608. function ItemSet(body, options) {
  9609. this.body = body;
  9610. this.defaultOptions = {
  9611. type: null, // 'box', 'point', 'range', 'background'
  9612. orientation: 'bottom', // 'top' or 'bottom'
  9613. align: 'auto', // alignment of box items
  9614. stack: true,
  9615. groupOrder: null,
  9616. selectable: true,
  9617. editable: {
  9618. updateTime: false,
  9619. updateGroup: false,
  9620. add: false,
  9621. remove: false
  9622. },
  9623. onAdd: function (item, callback) {
  9624. callback(item);
  9625. },
  9626. onUpdate: function (item, callback) {
  9627. callback(item);
  9628. },
  9629. onMove: function (item, callback) {
  9630. callback(item);
  9631. },
  9632. onRemove: function (item, callback) {
  9633. callback(item);
  9634. },
  9635. onMoving: function (item, callback) {
  9636. callback(item);
  9637. },
  9638. margin: {
  9639. item: {
  9640. horizontal: 10,
  9641. vertical: 10
  9642. },
  9643. axis: 20
  9644. },
  9645. padding: 5
  9646. };
  9647. // options is shared by this ItemSet and all its items
  9648. this.options = util.extend({}, this.defaultOptions);
  9649. // options for getting items from the DataSet with the correct type
  9650. this.itemOptions = {
  9651. type: {start: 'Date', end: 'Date'}
  9652. };
  9653. this.conversion = {
  9654. toScreen: body.util.toScreen,
  9655. toTime: body.util.toTime
  9656. };
  9657. this.dom = {};
  9658. this.props = {};
  9659. this.hammer = null;
  9660. var me = this;
  9661. this.itemsData = null; // DataSet
  9662. this.groupsData = null; // DataSet
  9663. // listeners for the DataSet of the items
  9664. this.itemListeners = {
  9665. 'add': function (event, params, senderId) {
  9666. me._onAdd(params.items);
  9667. },
  9668. 'update': function (event, params, senderId) {
  9669. me._onUpdate(params.items);
  9670. },
  9671. 'remove': function (event, params, senderId) {
  9672. me._onRemove(params.items);
  9673. }
  9674. };
  9675. // listeners for the DataSet of the groups
  9676. this.groupListeners = {
  9677. 'add': function (event, params, senderId) {
  9678. me._onAddGroups(params.items);
  9679. },
  9680. 'update': function (event, params, senderId) {
  9681. me._onUpdateGroups(params.items);
  9682. },
  9683. 'remove': function (event, params, senderId) {
  9684. me._onRemoveGroups(params.items);
  9685. }
  9686. };
  9687. this.items = {}; // object with an Item for every data item
  9688. this.groups = {}; // Group object for every group
  9689. this.groupIds = [];
  9690. this.selection = []; // list with the ids of all selected nodes
  9691. this.stackDirty = true; // if true, all items will be restacked on next redraw
  9692. this.touchParams = {}; // stores properties while dragging
  9693. // create the HTML DOM
  9694. this._create();
  9695. this.setOptions(options);
  9696. }
  9697. ItemSet.prototype = new Component();
  9698. // available item types will be registered here
  9699. ItemSet.types = {
  9700. background: BackgroundItem,
  9701. box: BoxItem,
  9702. range: RangeItem,
  9703. point: PointItem
  9704. };
  9705. /**
  9706. * Create the HTML DOM for the ItemSet
  9707. */
  9708. ItemSet.prototype._create = function(){
  9709. var frame = document.createElement('div');
  9710. frame.className = 'itemset';
  9711. frame['timeline-itemset'] = this;
  9712. this.dom.frame = frame;
  9713. // create background panel
  9714. var background = document.createElement('div');
  9715. background.className = 'background';
  9716. frame.appendChild(background);
  9717. this.dom.background = background;
  9718. // create foreground panel
  9719. var foreground = document.createElement('div');
  9720. foreground.className = 'foreground';
  9721. frame.appendChild(foreground);
  9722. this.dom.foreground = foreground;
  9723. // create axis panel
  9724. var axis = document.createElement('div');
  9725. axis.className = 'axis';
  9726. this.dom.axis = axis;
  9727. // create labelset
  9728. var labelSet = document.createElement('div');
  9729. labelSet.className = 'labelset';
  9730. this.dom.labelSet = labelSet;
  9731. // create ungrouped Group
  9732. this._updateUngrouped();
  9733. // create background Group
  9734. var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
  9735. backgroundGroup.show();
  9736. this.groups[BACKGROUND] = backgroundGroup;
  9737. // attach event listeners
  9738. // Note: we bind to the centerContainer for the case where the height
  9739. // of the center container is larger than of the ItemSet, so we
  9740. // can click in the empty area to create a new item or deselect an item.
  9741. this.hammer = Hammer(this.body.dom.centerContainer, {
  9742. preventDefault: true
  9743. });
  9744. // drag items when selected
  9745. this.hammer.on('touch', this._onTouch.bind(this));
  9746. this.hammer.on('dragstart', this._onDragStart.bind(this));
  9747. this.hammer.on('drag', this._onDrag.bind(this));
  9748. this.hammer.on('dragend', this._onDragEnd.bind(this));
  9749. // single select (or unselect) when tapping an item
  9750. this.hammer.on('tap', this._onSelectItem.bind(this));
  9751. // multi select when holding mouse/touch, or on ctrl+click
  9752. this.hammer.on('hold', this._onMultiSelectItem.bind(this));
  9753. // add item on doubletap
  9754. this.hammer.on('doubletap', this._onAddItem.bind(this));
  9755. // attach to the DOM
  9756. this.show();
  9757. };
  9758. /**
  9759. * Set options for the ItemSet. Existing options will be extended/overwritten.
  9760. * @param {Object} [options] The following options are available:
  9761. * {String} type
  9762. * Default type for the items. Choose from 'box'
  9763. * (default), 'point', 'range', or 'background'.
  9764. * The default style can be overwritten by
  9765. * individual items.
  9766. * {String} align
  9767. * Alignment for the items, only applicable for
  9768. * BoxItem. Choose 'center' (default), 'left', or
  9769. * 'right'.
  9770. * {String} orientation
  9771. * Orientation of the item set. Choose 'top' or
  9772. * 'bottom' (default).
  9773. * {Function} groupOrder
  9774. * A sorting function for ordering groups
  9775. * {Boolean} stack
  9776. * If true (deafult), items will be stacked on
  9777. * top of each other.
  9778. * {Number} margin.axis
  9779. * Margin between the axis and the items in pixels.
  9780. * Default is 20.
  9781. * {Number} margin.item.horizontal
  9782. * Horizontal margin between items in pixels.
  9783. * Default is 10.
  9784. * {Number} margin.item.vertical
  9785. * Vertical Margin between items in pixels.
  9786. * Default is 10.
  9787. * {Number} margin.item
  9788. * Margin between items in pixels in both horizontal
  9789. * and vertical direction. Default is 10.
  9790. * {Number} margin
  9791. * Set margin for both axis and items in pixels.
  9792. * {Number} padding
  9793. * Padding of the contents of an item in pixels.
  9794. * Must correspond with the items css. Default is 5.
  9795. * {Boolean} selectable
  9796. * If true (default), items can be selected.
  9797. * {Boolean} editable
  9798. * Set all editable options to true or false
  9799. * {Boolean} editable.updateTime
  9800. * Allow dragging an item to an other moment in time
  9801. * {Boolean} editable.updateGroup
  9802. * Allow dragging an item to an other group
  9803. * {Boolean} editable.add
  9804. * Allow creating new items on double tap
  9805. * {Boolean} editable.remove
  9806. * Allow removing items by clicking the delete button
  9807. * top right of a selected item.
  9808. * {Function(item: Item, callback: Function)} onAdd
  9809. * Callback function triggered when an item is about to be added:
  9810. * when the user double taps an empty space in the Timeline.
  9811. * {Function(item: Item, callback: Function)} onUpdate
  9812. * Callback function fired when an item is about to be updated.
  9813. * This function typically has to show a dialog where the user
  9814. * change the item. If not implemented, nothing happens.
  9815. * {Function(item: Item, callback: Function)} onMove
  9816. * Fired when an item has been moved. If not implemented,
  9817. * the move action will be accepted.
  9818. * {Function(item: Item, callback: Function)} onRemove
  9819. * Fired when an item is about to be deleted.
  9820. * If not implemented, the item will be always removed.
  9821. */
  9822. ItemSet.prototype.setOptions = function(options) {
  9823. if (options) {
  9824. // copy all options that we know
  9825. var fields = ['type', 'align', 'orientation', 'padding', 'stack', 'selectable', 'groupOrder', 'dataAttributes', 'template','hide'];
  9826. util.selectiveExtend(fields, this.options, options);
  9827. if ('margin' in options) {
  9828. if (typeof options.margin === 'number') {
  9829. this.options.margin.axis = options.margin;
  9830. this.options.margin.item.horizontal = options.margin;
  9831. this.options.margin.item.vertical = options.margin;
  9832. }
  9833. else if (typeof options.margin === 'object') {
  9834. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  9835. if ('item' in options.margin) {
  9836. if (typeof options.margin.item === 'number') {
  9837. this.options.margin.item.horizontal = options.margin.item;
  9838. this.options.margin.item.vertical = options.margin.item;
  9839. }
  9840. else if (typeof options.margin.item === 'object') {
  9841. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  9842. }
  9843. }
  9844. }
  9845. }
  9846. if ('editable' in options) {
  9847. if (typeof options.editable === 'boolean') {
  9848. this.options.editable.updateTime = options.editable;
  9849. this.options.editable.updateGroup = options.editable;
  9850. this.options.editable.add = options.editable;
  9851. this.options.editable.remove = options.editable;
  9852. }
  9853. else if (typeof options.editable === 'object') {
  9854. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable);
  9855. }
  9856. }
  9857. // callback functions
  9858. var addCallback = (function (name) {
  9859. var fn = options[name];
  9860. if (fn) {
  9861. if (!(fn instanceof Function)) {
  9862. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  9863. }
  9864. this.options[name] = fn;
  9865. }
  9866. }).bind(this);
  9867. ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving'].forEach(addCallback);
  9868. // force the itemSet to refresh: options like orientation and margins may be changed
  9869. this.markDirty();
  9870. }
  9871. };
  9872. /**
  9873. * Mark the ItemSet dirty so it will refresh everything with next redraw
  9874. */
  9875. ItemSet.prototype.markDirty = function() {
  9876. this.groupIds = [];
  9877. this.stackDirty = true;
  9878. };
  9879. /**
  9880. * Destroy the ItemSet
  9881. */
  9882. ItemSet.prototype.destroy = function() {
  9883. this.hide();
  9884. this.setItems(null);
  9885. this.setGroups(null);
  9886. this.hammer = null;
  9887. this.body = null;
  9888. this.conversion = null;
  9889. };
  9890. /**
  9891. * Hide the component from the DOM
  9892. */
  9893. ItemSet.prototype.hide = function() {
  9894. // remove the frame containing the items
  9895. if (this.dom.frame.parentNode) {
  9896. this.dom.frame.parentNode.removeChild(this.dom.frame);
  9897. }
  9898. // remove the axis with dots
  9899. if (this.dom.axis.parentNode) {
  9900. this.dom.axis.parentNode.removeChild(this.dom.axis);
  9901. }
  9902. // remove the labelset containing all group labels
  9903. if (this.dom.labelSet.parentNode) {
  9904. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  9905. }
  9906. };
  9907. /**
  9908. * Show the component in the DOM (when not already visible).
  9909. * @return {Boolean} changed
  9910. */
  9911. ItemSet.prototype.show = function() {
  9912. // show frame containing the items
  9913. if (!this.dom.frame.parentNode) {
  9914. this.body.dom.center.appendChild(this.dom.frame);
  9915. }
  9916. // show axis with dots
  9917. if (!this.dom.axis.parentNode) {
  9918. this.body.dom.backgroundVertical.appendChild(this.dom.axis);
  9919. }
  9920. // show labelset containing labels
  9921. if (!this.dom.labelSet.parentNode) {
  9922. this.body.dom.left.appendChild(this.dom.labelSet);
  9923. }
  9924. };
  9925. /**
  9926. * Set selected items by their id. Replaces the current selection
  9927. * Unknown id's are silently ignored.
  9928. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  9929. * selected, or a single item id. If ids is undefined
  9930. * or an empty array, all items will be unselected.
  9931. */
  9932. ItemSet.prototype.setSelection = function(ids) {
  9933. var i, ii, id, item;
  9934. if (ids == undefined) ids = [];
  9935. if (!Array.isArray(ids)) ids = [ids];
  9936. // unselect currently selected items
  9937. for (i = 0, ii = this.selection.length; i < ii; i++) {
  9938. id = this.selection[i];
  9939. item = this.items[id];
  9940. if (item) item.unselect();
  9941. }
  9942. // select items
  9943. this.selection = [];
  9944. for (i = 0, ii = ids.length; i < ii; i++) {
  9945. id = ids[i];
  9946. item = this.items[id];
  9947. if (item) {
  9948. this.selection.push(id);
  9949. item.select();
  9950. }
  9951. }
  9952. };
  9953. /**
  9954. * Get the selected items by their id
  9955. * @return {Array} ids The ids of the selected items
  9956. */
  9957. ItemSet.prototype.getSelection = function() {
  9958. return this.selection.concat([]);
  9959. };
  9960. /**
  9961. * Get the id's of the currently visible items.
  9962. * @returns {Array} The ids of the visible items
  9963. */
  9964. ItemSet.prototype.getVisibleItems = function() {
  9965. var range = this.body.range.getRange();
  9966. var left = this.body.util.toScreen(range.start);
  9967. var right = this.body.util.toScreen(range.end);
  9968. var ids = [];
  9969. for (var groupId in this.groups) {
  9970. if (this.groups.hasOwnProperty(groupId)) {
  9971. var group = this.groups[groupId];
  9972. var rawVisibleItems = group.visibleItems;
  9973. // filter the "raw" set with visibleItems into a set which is really
  9974. // visible by pixels
  9975. for (var i = 0; i < rawVisibleItems.length; i++) {
  9976. var item = rawVisibleItems[i];
  9977. // TODO: also check whether visible vertically
  9978. if ((item.left < right) && (item.left + item.width > left)) {
  9979. ids.push(item.id);
  9980. }
  9981. }
  9982. }
  9983. }
  9984. return ids;
  9985. };
  9986. /**
  9987. * Deselect a selected item
  9988. * @param {String | Number} id
  9989. * @private
  9990. */
  9991. ItemSet.prototype._deselect = function(id) {
  9992. var selection = this.selection;
  9993. for (var i = 0, ii = selection.length; i < ii; i++) {
  9994. if (selection[i] == id) { // non-strict comparison!
  9995. selection.splice(i, 1);
  9996. break;
  9997. }
  9998. }
  9999. };
  10000. /**
  10001. * Repaint the component
  10002. * @return {boolean} Returns true if the component is resized
  10003. */
  10004. ItemSet.prototype.redraw = function() {
  10005. var margin = this.options.margin,
  10006. range = this.body.range,
  10007. asSize = util.option.asSize,
  10008. options = this.options,
  10009. orientation = options.orientation,
  10010. resized = false,
  10011. frame = this.dom.frame,
  10012. editable = options.editable.updateTime || options.editable.updateGroup;
  10013. // recalculate absolute position (before redrawing groups)
  10014. this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
  10015. this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
  10016. // update class name
  10017. frame.className = 'itemset' + (editable ? ' editable' : '');
  10018. // reorder the groups (if needed)
  10019. resized = this._orderGroups() || resized;
  10020. // check whether zoomed (in that case we need to re-stack everything)
  10021. // TODO: would be nicer to get this as a trigger from Range
  10022. var visibleInterval = range.end - range.start;
  10023. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth);
  10024. if (zoomed) this.stackDirty = true;
  10025. this.lastVisibleInterval = visibleInterval;
  10026. this.props.lastWidth = this.props.width;
  10027. var restack = this.stackDirty;
  10028. var firstGroup = this._firstGroup();
  10029. var firstMargin = {
  10030. item: margin.item,
  10031. axis: margin.axis
  10032. };
  10033. var nonFirstMargin = {
  10034. item: margin.item,
  10035. axis: margin.item.vertical / 2
  10036. };
  10037. var height = 0;
  10038. var minHeight = margin.axis + margin.item.vertical;
  10039. // redraw the background group
  10040. this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack);
  10041. // redraw all regular groups
  10042. util.forEach(this.groups, function (group) {
  10043. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  10044. var groupResized = group.redraw(range, groupMargin, restack);
  10045. resized = groupResized || resized;
  10046. height += group.height;
  10047. });
  10048. height = Math.max(height, minHeight);
  10049. this.stackDirty = false;
  10050. // update frame height
  10051. frame.style.height = asSize(height);
  10052. // calculate actual size
  10053. this.props.width = frame.offsetWidth;
  10054. this.props.height = height;
  10055. // reposition axis
  10056. this.dom.axis.style.top = asSize((orientation == 'top') ?
  10057. (this.body.domProps.top.height + this.body.domProps.border.top) :
  10058. (this.body.domProps.top.height + this.body.domProps.centerContainer.height));
  10059. this.dom.axis.style.left = '0';
  10060. // check if this component is resized
  10061. resized = this._isResized() || resized;
  10062. return resized;
  10063. };
  10064. /**
  10065. * Get the first group, aligned with the axis
  10066. * @return {Group | null} firstGroup
  10067. * @private
  10068. */
  10069. ItemSet.prototype._firstGroup = function() {
  10070. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  10071. var firstGroupId = this.groupIds[firstGroupIndex];
  10072. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  10073. return firstGroup || null;
  10074. };
  10075. /**
  10076. * Create or delete the group holding all ungrouped items. This group is used when
  10077. * there are no groups specified.
  10078. * @protected
  10079. */
  10080. ItemSet.prototype._updateUngrouped = function() {
  10081. var ungrouped = this.groups[UNGROUPED];
  10082. var background = this.groups[BACKGROUND];
  10083. var item, itemId;
  10084. if (this.groupsData) {
  10085. // remove the group holding all ungrouped items
  10086. if (ungrouped) {
  10087. ungrouped.hide();
  10088. delete this.groups[UNGROUPED];
  10089. for (itemId in this.items) {
  10090. if (this.items.hasOwnProperty(itemId)) {
  10091. item = this.items[itemId];
  10092. item.parent && item.parent.remove(item);
  10093. var groupId = this._getGroupId(item.data);
  10094. var group = this.groups[groupId];
  10095. group && group.add(item) || item.hide();
  10096. }
  10097. }
  10098. }
  10099. }
  10100. else {
  10101. // create a group holding all (unfiltered) items
  10102. if (!ungrouped) {
  10103. var id = null;
  10104. var data = null;
  10105. ungrouped = new Group(id, data, this);
  10106. this.groups[UNGROUPED] = ungrouped;
  10107. for (itemId in this.items) {
  10108. if (this.items.hasOwnProperty(itemId)) {
  10109. item = this.items[itemId];
  10110. ungrouped.add(item);
  10111. }
  10112. }
  10113. ungrouped.show();
  10114. }
  10115. }
  10116. };
  10117. /**
  10118. * Get the element for the labelset
  10119. * @return {HTMLElement} labelSet
  10120. */
  10121. ItemSet.prototype.getLabelSet = function() {
  10122. return this.dom.labelSet;
  10123. };
  10124. /**
  10125. * Set items
  10126. * @param {vis.DataSet | null} items
  10127. */
  10128. ItemSet.prototype.setItems = function(items) {
  10129. var me = this,
  10130. ids,
  10131. oldItemsData = this.itemsData;
  10132. // replace the dataset
  10133. if (!items) {
  10134. this.itemsData = null;
  10135. }
  10136. else if (items instanceof DataSet || items instanceof DataView) {
  10137. this.itemsData = items;
  10138. }
  10139. else {
  10140. throw new TypeError('Data must be an instance of DataSet or DataView');
  10141. }
  10142. if (oldItemsData) {
  10143. // unsubscribe from old dataset
  10144. util.forEach(this.itemListeners, function (callback, event) {
  10145. oldItemsData.off(event, callback);
  10146. });
  10147. // remove all drawn items
  10148. ids = oldItemsData.getIds();
  10149. this._onRemove(ids);
  10150. }
  10151. if (this.itemsData) {
  10152. // subscribe to new dataset
  10153. var id = this.id;
  10154. util.forEach(this.itemListeners, function (callback, event) {
  10155. me.itemsData.on(event, callback, id);
  10156. });
  10157. // add all new items
  10158. ids = this.itemsData.getIds();
  10159. this._onAdd(ids);
  10160. // update the group holding all ungrouped items
  10161. this._updateUngrouped();
  10162. }
  10163. };
  10164. /**
  10165. * Get the current items
  10166. * @returns {vis.DataSet | null}
  10167. */
  10168. ItemSet.prototype.getItems = function() {
  10169. return this.itemsData;
  10170. };
  10171. /**
  10172. * Set groups
  10173. * @param {vis.DataSet} groups
  10174. */
  10175. ItemSet.prototype.setGroups = function(groups) {
  10176. var me = this,
  10177. ids;
  10178. // unsubscribe from current dataset
  10179. if (this.groupsData) {
  10180. util.forEach(this.groupListeners, function (callback, event) {
  10181. me.groupsData.unsubscribe(event, callback);
  10182. });
  10183. // remove all drawn groups
  10184. ids = this.groupsData.getIds();
  10185. this.groupsData = null;
  10186. this._onRemoveGroups(ids); // note: this will cause a redraw
  10187. }
  10188. // replace the dataset
  10189. if (!groups) {
  10190. this.groupsData = null;
  10191. }
  10192. else if (groups instanceof DataSet || groups instanceof DataView) {
  10193. this.groupsData = groups;
  10194. }
  10195. else {
  10196. throw new TypeError('Data must be an instance of DataSet or DataView');
  10197. }
  10198. if (this.groupsData) {
  10199. // subscribe to new dataset
  10200. var id = this.id;
  10201. util.forEach(this.groupListeners, function (callback, event) {
  10202. me.groupsData.on(event, callback, id);
  10203. });
  10204. // draw all ms
  10205. ids = this.groupsData.getIds();
  10206. this._onAddGroups(ids);
  10207. }
  10208. // update the group holding all ungrouped items
  10209. this._updateUngrouped();
  10210. // update the order of all items in each group
  10211. this._order();
  10212. this.body.emitter.emit('change', {queue: true});
  10213. };
  10214. /**
  10215. * Get the current groups
  10216. * @returns {vis.DataSet | null} groups
  10217. */
  10218. ItemSet.prototype.getGroups = function() {
  10219. return this.groupsData;
  10220. };
  10221. /**
  10222. * Remove an item by its id
  10223. * @param {String | Number} id
  10224. */
  10225. ItemSet.prototype.removeItem = function(id) {
  10226. var item = this.itemsData.get(id),
  10227. dataset = this.itemsData.getDataSet();
  10228. if (item) {
  10229. // confirm deletion
  10230. this.options.onRemove(item, function (item) {
  10231. if (item) {
  10232. // remove by id here, it is possible that an item has no id defined
  10233. // itself, so better not delete by the item itself
  10234. dataset.remove(id);
  10235. }
  10236. });
  10237. }
  10238. };
  10239. /**
  10240. * Get the time of an item based on it's data and options.type
  10241. * @param {Object} itemData
  10242. * @returns {string} Returns the type
  10243. * @private
  10244. */
  10245. ItemSet.prototype._getType = function (itemData) {
  10246. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  10247. };
  10248. /**
  10249. * Get the group id for an item
  10250. * @param {Object} itemData
  10251. * @returns {string} Returns the groupId
  10252. * @private
  10253. */
  10254. ItemSet.prototype._getGroupId = function (itemData) {
  10255. var type = this._getType(itemData);
  10256. if (type == 'background' && itemData.group == undefined) {
  10257. return BACKGROUND;
  10258. }
  10259. else {
  10260. return this.groupsData ? itemData.group : UNGROUPED;
  10261. }
  10262. };
  10263. /**
  10264. * Handle updated items
  10265. * @param {Number[]} ids
  10266. * @protected
  10267. */
  10268. ItemSet.prototype._onUpdate = function(ids) {
  10269. var me = this;
  10270. ids.forEach(function (id) {
  10271. var itemData = me.itemsData.get(id, me.itemOptions);
  10272. var item = me.items[id];
  10273. var type = me._getType(itemData);
  10274. var constructor = ItemSet.types[type];
  10275. if (item) {
  10276. // update item
  10277. if (!constructor || !(item instanceof constructor)) {
  10278. // item type has changed, delete the item and recreate it
  10279. me._removeItem(item);
  10280. item = null;
  10281. }
  10282. else {
  10283. me._updateItem(item, itemData);
  10284. }
  10285. }
  10286. if (!item) {
  10287. // create item
  10288. if (constructor) {
  10289. item = new constructor(itemData, me.conversion, me.options);
  10290. item.id = id; // TODO: not so nice setting id afterwards
  10291. me._addItem(item);
  10292. }
  10293. else if (type == 'rangeoverflow') {
  10294. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  10295. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  10296. '.vis.timeline .item.range .content {overflow: visible;}');
  10297. }
  10298. else {
  10299. throw new TypeError('Unknown item type "' + type + '"');
  10300. }
  10301. }
  10302. });
  10303. this._order();
  10304. this.stackDirty = true; // force re-stacking of all items next redraw
  10305. this.body.emitter.emit('change', {queue: true});
  10306. };
  10307. /**
  10308. * Handle added items
  10309. * @param {Number[]} ids
  10310. * @protected
  10311. */
  10312. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  10313. /**
  10314. * Handle removed items
  10315. * @param {Number[]} ids
  10316. * @protected
  10317. */
  10318. ItemSet.prototype._onRemove = function(ids) {
  10319. var count = 0;
  10320. var me = this;
  10321. ids.forEach(function (id) {
  10322. var item = me.items[id];
  10323. if (item) {
  10324. count++;
  10325. me._removeItem(item);
  10326. }
  10327. });
  10328. if (count) {
  10329. // update order
  10330. this._order();
  10331. this.stackDirty = true; // force re-stacking of all items next redraw
  10332. this.body.emitter.emit('change', {queue: true});
  10333. }
  10334. };
  10335. /**
  10336. * Update the order of item in all groups
  10337. * @private
  10338. */
  10339. ItemSet.prototype._order = function() {
  10340. // reorder the items in all groups
  10341. // TODO: optimization: only reorder groups affected by the changed items
  10342. util.forEach(this.groups, function (group) {
  10343. group.order();
  10344. });
  10345. };
  10346. /**
  10347. * Handle updated groups
  10348. * @param {Number[]} ids
  10349. * @private
  10350. */
  10351. ItemSet.prototype._onUpdateGroups = function(ids) {
  10352. this._onAddGroups(ids);
  10353. };
  10354. /**
  10355. * Handle changed groups (added or updated)
  10356. * @param {Number[]} ids
  10357. * @private
  10358. */
  10359. ItemSet.prototype._onAddGroups = function(ids) {
  10360. var me = this;
  10361. ids.forEach(function (id) {
  10362. var groupData = me.groupsData.get(id);
  10363. var group = me.groups[id];
  10364. if (!group) {
  10365. // check for reserved ids
  10366. if (id == UNGROUPED || id == BACKGROUND) {
  10367. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  10368. }
  10369. var groupOptions = Object.create(me.options);
  10370. util.extend(groupOptions, {
  10371. height: null
  10372. });
  10373. group = new Group(id, groupData, me);
  10374. me.groups[id] = group;
  10375. // add items with this groupId to the new group
  10376. for (var itemId in me.items) {
  10377. if (me.items.hasOwnProperty(itemId)) {
  10378. var item = me.items[itemId];
  10379. if (item.data.group == id) {
  10380. group.add(item);
  10381. }
  10382. }
  10383. }
  10384. group.order();
  10385. group.show();
  10386. }
  10387. else {
  10388. // update group
  10389. group.setData(groupData);
  10390. }
  10391. });
  10392. this.body.emitter.emit('change', {queue: true});
  10393. };
  10394. /**
  10395. * Handle removed groups
  10396. * @param {Number[]} ids
  10397. * @private
  10398. */
  10399. ItemSet.prototype._onRemoveGroups = function(ids) {
  10400. var groups = this.groups;
  10401. ids.forEach(function (id) {
  10402. var group = groups[id];
  10403. if (group) {
  10404. group.hide();
  10405. delete groups[id];
  10406. }
  10407. });
  10408. this.markDirty();
  10409. this.body.emitter.emit('change', {queue: true});
  10410. };
  10411. /**
  10412. * Reorder the groups if needed
  10413. * @return {boolean} changed
  10414. * @private
  10415. */
  10416. ItemSet.prototype._orderGroups = function () {
  10417. if (this.groupsData) {
  10418. // reorder the groups
  10419. var groupIds = this.groupsData.getIds({
  10420. order: this.options.groupOrder
  10421. });
  10422. var changed = !util.equalArray(groupIds, this.groupIds);
  10423. if (changed) {
  10424. // hide all groups, removes them from the DOM
  10425. var groups = this.groups;
  10426. groupIds.forEach(function (groupId) {
  10427. groups[groupId].hide();
  10428. });
  10429. // show the groups again, attach them to the DOM in correct order
  10430. groupIds.forEach(function (groupId) {
  10431. groups[groupId].show();
  10432. });
  10433. this.groupIds = groupIds;
  10434. }
  10435. return changed;
  10436. }
  10437. else {
  10438. return false;
  10439. }
  10440. };
  10441. /**
  10442. * Add a new item
  10443. * @param {Item} item
  10444. * @private
  10445. */
  10446. ItemSet.prototype._addItem = function(item) {
  10447. this.items[item.id] = item;
  10448. // add to group
  10449. var groupId = this._getGroupId(item.data);
  10450. var group = this.groups[groupId];
  10451. if (group) group.add(item);
  10452. };
  10453. /**
  10454. * Update an existing item
  10455. * @param {Item} item
  10456. * @param {Object} itemData
  10457. * @private
  10458. */
  10459. ItemSet.prototype._updateItem = function(item, itemData) {
  10460. var oldGroupId = item.data.group;
  10461. // update the items data (will redraw the item when displayed)
  10462. item.setData(itemData);
  10463. // update group
  10464. if (oldGroupId != item.data.group) {
  10465. var oldGroup = this.groups[oldGroupId];
  10466. if (oldGroup) oldGroup.remove(item);
  10467. var groupId = this._getGroupId(item.data);
  10468. var group = this.groups[groupId];
  10469. if (group) group.add(item);
  10470. }
  10471. };
  10472. /**
  10473. * Delete an item from the ItemSet: remove it from the DOM, from the map
  10474. * with items, and from the map with visible items, and from the selection
  10475. * @param {Item} item
  10476. * @private
  10477. */
  10478. ItemSet.prototype._removeItem = function(item) {
  10479. // remove from DOM
  10480. item.hide();
  10481. // remove from items
  10482. delete this.items[item.id];
  10483. // remove from selection
  10484. var index = this.selection.indexOf(item.id);
  10485. if (index != -1) this.selection.splice(index, 1);
  10486. // remove from group
  10487. item.parent && item.parent.remove(item);
  10488. };
  10489. /**
  10490. * Create an array containing all items being a range (having an end date)
  10491. * @param array
  10492. * @returns {Array}
  10493. * @private
  10494. */
  10495. ItemSet.prototype._constructByEndArray = function(array) {
  10496. var endArray = [];
  10497. for (var i = 0; i < array.length; i++) {
  10498. if (array[i] instanceof RangeItem) {
  10499. endArray.push(array[i]);
  10500. }
  10501. }
  10502. return endArray;
  10503. };
  10504. /**
  10505. * Register the clicked item on touch, before dragStart is initiated.
  10506. *
  10507. * dragStart is initiated from a mousemove event, which can have left the item
  10508. * already resulting in an item == null
  10509. *
  10510. * @param {Event} event
  10511. * @private
  10512. */
  10513. ItemSet.prototype._onTouch = function (event) {
  10514. // store the touched item, used in _onDragStart
  10515. this.touchParams.item = ItemSet.itemFromTarget(event);
  10516. };
  10517. /**
  10518. * Start dragging the selected events
  10519. * @param {Event} event
  10520. * @private
  10521. */
  10522. ItemSet.prototype._onDragStart = function (event) {
  10523. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  10524. return;
  10525. }
  10526. var item = this.touchParams.item || null;
  10527. var me = this;
  10528. var props;
  10529. if (item && item.selected) {
  10530. var dragLeftItem = event.target.dragLeftItem;
  10531. var dragRightItem = event.target.dragRightItem;
  10532. if (dragLeftItem) {
  10533. props = {
  10534. item: dragLeftItem,
  10535. initialX: event.gesture.center.clientX
  10536. };
  10537. if (me.options.editable.updateTime) {
  10538. props.start = item.data.start.valueOf();
  10539. }
  10540. if (me.options.editable.updateGroup) {
  10541. if ('group' in item.data) props.group = item.data.group;
  10542. }
  10543. this.touchParams.itemProps = [props];
  10544. }
  10545. else if (dragRightItem) {
  10546. props = {
  10547. item: dragRightItem,
  10548. initialX: event.gesture.center.clientX
  10549. };
  10550. if (me.options.editable.updateTime) {
  10551. props.end = item.data.end.valueOf();
  10552. }
  10553. if (me.options.editable.updateGroup) {
  10554. if ('group' in item.data) props.group = item.data.group;
  10555. }
  10556. this.touchParams.itemProps = [props];
  10557. }
  10558. else {
  10559. this.touchParams.itemProps = this.getSelection().map(function (id) {
  10560. var item = me.items[id];
  10561. var props = {
  10562. item: item,
  10563. initialX: event.gesture.center.clientX
  10564. };
  10565. if (me.options.editable.updateTime) {
  10566. if ('start' in item.data) props.start = item.data.start.valueOf();
  10567. if ('end' in item.data) props.end = item.data.end.valueOf();
  10568. }
  10569. if (me.options.editable.updateGroup) {
  10570. if ('group' in item.data) props.group = item.data.group;
  10571. }
  10572. return props;
  10573. });
  10574. }
  10575. event.stopPropagation();
  10576. }
  10577. };
  10578. /**
  10579. * Drag selected items
  10580. * @param {Event} event
  10581. * @private
  10582. */
  10583. ItemSet.prototype._onDrag = function (event) {
  10584. event.preventDefault()
  10585. if (this.touchParams.itemProps) {
  10586. var me = this;
  10587. var snap = this.body.util.snap || null;
  10588. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  10589. // move
  10590. this.touchParams.itemProps.forEach(function (props) {
  10591. var newProps = {};
  10592. var current = me.body.util.toTime(event.gesture.center.clientX - xOffset);
  10593. var initial = me.body.util.toTime(props.initialX - xOffset);
  10594. var offset = current - initial;
  10595. if ('start' in props) {
  10596. var start = new Date(props.start + offset);
  10597. newProps.start = snap ? snap(start) : start;
  10598. }
  10599. if ('end' in props) {
  10600. var end = new Date(props.end + offset);
  10601. newProps.end = snap ? snap(end) : end;
  10602. }
  10603. if ('group' in props) {
  10604. // drag from one group to another
  10605. var group = ItemSet.groupFromTarget(event);
  10606. newProps.group = group && group.groupId;
  10607. }
  10608. // confirm moving the item
  10609. var itemData = util.extend({}, props.item.data, newProps);
  10610. me.options.onMoving(itemData, function (itemData) {
  10611. if (itemData) {
  10612. me._updateItemProps(props.item, itemData);
  10613. }
  10614. });
  10615. });
  10616. this.stackDirty = true; // force re-stacking of all items next redraw
  10617. this.body.emitter.emit('change');
  10618. event.stopPropagation();
  10619. }
  10620. };
  10621. /**
  10622. * Update an items properties
  10623. * @param {Item} item
  10624. * @param {Object} props Can contain properties start, end, and group.
  10625. * @private
  10626. */
  10627. ItemSet.prototype._updateItemProps = function(item, props) {
  10628. // TODO: copy all properties from props to item? (also new ones)
  10629. if ('start' in props) item.data.start = props.start;
  10630. if ('end' in props) item.data.end = props.end;
  10631. if ('group' in props && item.data.group != props.group) {
  10632. this._moveToGroup(item, props.group)
  10633. }
  10634. };
  10635. /**
  10636. * Move an item to another group
  10637. * @param {Item} item
  10638. * @param {String | Number} groupId
  10639. * @private
  10640. */
  10641. ItemSet.prototype._moveToGroup = function(item, groupId) {
  10642. var group = this.groups[groupId];
  10643. if (group && group.groupId != item.data.group) {
  10644. var oldGroup = item.parent;
  10645. oldGroup.remove(item);
  10646. oldGroup.order();
  10647. group.add(item);
  10648. group.order();
  10649. item.data.group = group.groupId;
  10650. }
  10651. };
  10652. /**
  10653. * End of dragging selected items
  10654. * @param {Event} event
  10655. * @private
  10656. */
  10657. ItemSet.prototype._onDragEnd = function (event) {
  10658. event.preventDefault()
  10659. if (this.touchParams.itemProps) {
  10660. // prepare a change set for the changed items
  10661. var changes = [],
  10662. me = this,
  10663. dataset = this.itemsData.getDataSet();
  10664. var itemProps = this.touchParams.itemProps ;
  10665. this.touchParams.itemProps = null;
  10666. itemProps.forEach(function (props) {
  10667. var id = props.item.id,
  10668. itemData = me.itemsData.get(id, me.itemOptions);
  10669. var changed = false;
  10670. if ('start' in props.item.data) {
  10671. changed = (props.start != props.item.data.start.valueOf());
  10672. itemData.start = util.convert(props.item.data.start,
  10673. dataset._options.type && dataset._options.type.start || 'Date');
  10674. }
  10675. if ('end' in props.item.data) {
  10676. changed = changed || (props.end != props.item.data.end.valueOf());
  10677. itemData.end = util.convert(props.item.data.end,
  10678. dataset._options.type && dataset._options.type.end || 'Date');
  10679. }
  10680. if ('group' in props.item.data) {
  10681. changed = changed || (props.group != props.item.data.group);
  10682. itemData.group = props.item.data.group;
  10683. }
  10684. // only apply changes when start or end is actually changed
  10685. if (changed) {
  10686. me.options.onMove(itemData, function (itemData) {
  10687. if (itemData) {
  10688. // apply changes
  10689. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  10690. changes.push(itemData);
  10691. }
  10692. else {
  10693. // restore original values
  10694. me._updateItemProps(props.item, props);
  10695. me.stackDirty = true; // force re-stacking of all items next redraw
  10696. me.body.emitter.emit('change');
  10697. }
  10698. });
  10699. }
  10700. });
  10701. // apply the changes to the data (if there are changes)
  10702. if (changes.length) {
  10703. dataset.update(changes);
  10704. }
  10705. event.stopPropagation();
  10706. }
  10707. };
  10708. /**
  10709. * Handle selecting/deselecting an item when tapping it
  10710. * @param {Event} event
  10711. * @private
  10712. */
  10713. ItemSet.prototype._onSelectItem = function (event) {
  10714. if (!this.options.selectable) return;
  10715. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  10716. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  10717. if (ctrlKey || shiftKey) {
  10718. this._onMultiSelectItem(event);
  10719. return;
  10720. }
  10721. var oldSelection = this.getSelection();
  10722. var item = ItemSet.itemFromTarget(event);
  10723. var selection = item ? [item.id] : [];
  10724. this.setSelection(selection);
  10725. var newSelection = this.getSelection();
  10726. // emit a select event,
  10727. // except when old selection is empty and new selection is still empty
  10728. if (newSelection.length > 0 || oldSelection.length > 0) {
  10729. this.body.emitter.emit('select', {
  10730. items: newSelection
  10731. });
  10732. }
  10733. };
  10734. /**
  10735. * Handle creation and updates of an item on double tap
  10736. * @param event
  10737. * @private
  10738. */
  10739. ItemSet.prototype._onAddItem = function (event) {
  10740. if (!this.options.selectable) return;
  10741. if (!this.options.editable.add) return;
  10742. var me = this,
  10743. snap = this.body.util.snap || null,
  10744. item = ItemSet.itemFromTarget(event);
  10745. if (item) {
  10746. // update item
  10747. // execute async handler to update the item (or cancel it)
  10748. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  10749. this.options.onUpdate(itemData, function (itemData) {
  10750. if (itemData) {
  10751. me.itemsData.getDataSet().update(itemData);
  10752. }
  10753. });
  10754. }
  10755. else {
  10756. // add item
  10757. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  10758. var x = event.gesture.center.pageX - xAbs;
  10759. var start = this.body.util.toTime(x);
  10760. var newItem = {
  10761. start: snap ? snap(start) : start,
  10762. content: 'new item'
  10763. };
  10764. // when default type is a range, add a default end date to the new item
  10765. if (this.options.type === 'range') {
  10766. var end = this.body.util.toTime(x + this.props.width / 5);
  10767. newItem.end = snap ? snap(end) : end;
  10768. }
  10769. newItem[this.itemsData._fieldId] = util.randomUUID();
  10770. var group = ItemSet.groupFromTarget(event);
  10771. if (group) {
  10772. newItem.group = group.groupId;
  10773. }
  10774. // execute async handler to customize (or cancel) adding an item
  10775. this.options.onAdd(newItem, function (item) {
  10776. if (item) {
  10777. me.itemsData.getDataSet().add(item);
  10778. // TODO: need to trigger a redraw?
  10779. }
  10780. });
  10781. }
  10782. };
  10783. /**
  10784. * Handle selecting/deselecting multiple items when holding an item
  10785. * @param {Event} event
  10786. * @private
  10787. */
  10788. ItemSet.prototype._onMultiSelectItem = function (event) {
  10789. if (!this.options.selectable) return;
  10790. var selection,
  10791. item = ItemSet.itemFromTarget(event);
  10792. if (item) {
  10793. // multi select items
  10794. selection = this.getSelection(); // current selection
  10795. var shiftKey = event.gesture.touches[0] && event.gesture.touches[0].shiftKey || false;
  10796. if (shiftKey) {
  10797. // select all items between the old selection and the tapped item
  10798. // determine the selection range
  10799. selection.push(item.id);
  10800. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  10801. // select all items within the selection range
  10802. selection = [];
  10803. for (var id in this.items) {
  10804. if (this.items.hasOwnProperty(id)) {
  10805. var _item = this.items[id];
  10806. var start = _item.data.start;
  10807. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  10808. if (start >= range.min && end <= range.max) {
  10809. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  10810. }
  10811. }
  10812. }
  10813. }
  10814. else {
  10815. // add/remove this item from the current selection
  10816. var index = selection.indexOf(item.id);
  10817. if (index == -1) {
  10818. // item is not yet selected -> select it
  10819. selection.push(item.id);
  10820. }
  10821. else {
  10822. // item is already selected -> deselect it
  10823. selection.splice(index, 1);
  10824. }
  10825. }
  10826. this.setSelection(selection);
  10827. this.body.emitter.emit('select', {
  10828. items: this.getSelection()
  10829. });
  10830. }
  10831. };
  10832. /**
  10833. * Calculate the time range of a list of items
  10834. * @param {Array.<Object>} itemsData
  10835. * @return {{min: Date, max: Date}} Returns the range of the provided items
  10836. * @private
  10837. */
  10838. ItemSet._getItemRange = function(itemsData) {
  10839. var max = null;
  10840. var min = null;
  10841. itemsData.forEach(function (data) {
  10842. if (min == null || data.start < min) {
  10843. min = data.start;
  10844. }
  10845. if (data.end != undefined) {
  10846. if (max == null || data.end > max) {
  10847. max = data.end;
  10848. }
  10849. }
  10850. else {
  10851. if (max == null || data.start > max) {
  10852. max = data.start;
  10853. }
  10854. }
  10855. });
  10856. return {
  10857. min: min,
  10858. max: max
  10859. }
  10860. };
  10861. /**
  10862. * Find an item from an event target:
  10863. * searches for the attribute 'timeline-item' in the event target's element tree
  10864. * @param {Event} event
  10865. * @return {Item | null} item
  10866. */
  10867. ItemSet.itemFromTarget = function(event) {
  10868. var target = event.target;
  10869. while (target) {
  10870. if (target.hasOwnProperty('timeline-item')) {
  10871. return target['timeline-item'];
  10872. }
  10873. target = target.parentNode;
  10874. }
  10875. return null;
  10876. };
  10877. /**
  10878. * Find the Group from an event target:
  10879. * searches for the attribute 'timeline-group' in the event target's element tree
  10880. * @param {Event} event
  10881. * @return {Group | null} group
  10882. */
  10883. ItemSet.groupFromTarget = function(event) {
  10884. var target = event.target;
  10885. while (target) {
  10886. if (target.hasOwnProperty('timeline-group')) {
  10887. return target['timeline-group'];
  10888. }
  10889. target = target.parentNode;
  10890. }
  10891. return null;
  10892. };
  10893. /**
  10894. * Find the ItemSet from an event target:
  10895. * searches for the attribute 'timeline-itemset' in the event target's element tree
  10896. * @param {Event} event
  10897. * @return {ItemSet | null} item
  10898. */
  10899. ItemSet.itemSetFromTarget = function(event) {
  10900. var target = event.target;
  10901. while (target) {
  10902. if (target.hasOwnProperty('timeline-itemset')) {
  10903. return target['timeline-itemset'];
  10904. }
  10905. target = target.parentNode;
  10906. }
  10907. return null;
  10908. };
  10909. module.exports = ItemSet;
  10910. /***/ },
  10911. /* 28 */
  10912. /***/ function(module, exports, __webpack_require__) {
  10913. var util = __webpack_require__(1);
  10914. var DOMutil = __webpack_require__(2);
  10915. var Component = __webpack_require__(20);
  10916. /**
  10917. * Legend for Graph2d
  10918. */
  10919. function Legend(body, options, side, linegraphOptions) {
  10920. this.body = body;
  10921. this.defaultOptions = {
  10922. enabled: true,
  10923. icons: true,
  10924. iconSize: 20,
  10925. iconSpacing: 6,
  10926. left: {
  10927. visible: true,
  10928. position: 'top-left' // top/bottom - left,center,right
  10929. },
  10930. right: {
  10931. visible: true,
  10932. position: 'top-left' // top/bottom - left,center,right
  10933. }
  10934. }
  10935. this.side = side;
  10936. this.options = util.extend({},this.defaultOptions);
  10937. this.linegraphOptions = linegraphOptions;
  10938. this.svgElements = {};
  10939. this.dom = {};
  10940. this.groups = {};
  10941. this.amountOfGroups = 0;
  10942. this._create();
  10943. this.setOptions(options);
  10944. }
  10945. Legend.prototype = new Component();
  10946. Legend.prototype.clear = function() {
  10947. this.groups = {};
  10948. this.amountOfGroups = 0;
  10949. }
  10950. Legend.prototype.addGroup = function(label, graphOptions) {
  10951. if (!this.groups.hasOwnProperty(label)) {
  10952. this.groups[label] = graphOptions;
  10953. }
  10954. this.amountOfGroups += 1;
  10955. };
  10956. Legend.prototype.updateGroup = function(label, graphOptions) {
  10957. this.groups[label] = graphOptions;
  10958. };
  10959. Legend.prototype.removeGroup = function(label) {
  10960. if (this.groups.hasOwnProperty(label)) {
  10961. delete this.groups[label];
  10962. this.amountOfGroups -= 1;
  10963. }
  10964. };
  10965. Legend.prototype._create = function() {
  10966. this.dom.frame = document.createElement('div');
  10967. this.dom.frame.className = 'legend';
  10968. this.dom.frame.style.position = "absolute";
  10969. this.dom.frame.style.top = "10px";
  10970. this.dom.frame.style.display = "block";
  10971. this.dom.textArea = document.createElement('div');
  10972. this.dom.textArea.className = 'legendText';
  10973. this.dom.textArea.style.position = "relative";
  10974. this.dom.textArea.style.top = "0px";
  10975. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  10976. this.svg.style.position = 'absolute';
  10977. this.svg.style.top = 0 +'px';
  10978. this.svg.style.width = this.options.iconSize + 5 + 'px';
  10979. this.svg.style.height = '100%';
  10980. this.dom.frame.appendChild(this.svg);
  10981. this.dom.frame.appendChild(this.dom.textArea);
  10982. };
  10983. /**
  10984. * Hide the component from the DOM
  10985. */
  10986. Legend.prototype.hide = function() {
  10987. // remove the frame containing the items
  10988. if (this.dom.frame.parentNode) {
  10989. this.dom.frame.parentNode.removeChild(this.dom.frame);
  10990. }
  10991. };
  10992. /**
  10993. * Show the component in the DOM (when not already visible).
  10994. * @return {Boolean} changed
  10995. */
  10996. Legend.prototype.show = function() {
  10997. // show frame containing the items
  10998. if (!this.dom.frame.parentNode) {
  10999. this.body.dom.center.appendChild(this.dom.frame);
  11000. }
  11001. };
  11002. Legend.prototype.setOptions = function(options) {
  11003. var fields = ['enabled','orientation','icons','left','right'];
  11004. util.selectiveDeepExtend(fields, this.options, options);
  11005. };
  11006. Legend.prototype.redraw = function() {
  11007. var activeGroups = 0;
  11008. for (var groupId in this.groups) {
  11009. if (this.groups.hasOwnProperty(groupId)) {
  11010. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  11011. activeGroups++;
  11012. }
  11013. }
  11014. }
  11015. if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) {
  11016. this.hide();
  11017. }
  11018. else {
  11019. this.show();
  11020. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') {
  11021. this.dom.frame.style.left = '4px';
  11022. this.dom.frame.style.textAlign = "left";
  11023. this.dom.textArea.style.textAlign = "left";
  11024. this.dom.textArea.style.left = (this.options.iconSize + 15) + 'px';
  11025. this.dom.textArea.style.right = '';
  11026. this.svg.style.left = 0 +'px';
  11027. this.svg.style.right = '';
  11028. }
  11029. else {
  11030. this.dom.frame.style.right = '4px';
  11031. this.dom.frame.style.textAlign = "right";
  11032. this.dom.textArea.style.textAlign = "right";
  11033. this.dom.textArea.style.right = (this.options.iconSize + 15) + 'px';
  11034. this.dom.textArea.style.left = '';
  11035. this.svg.style.right = 0 +'px';
  11036. this.svg.style.left = '';
  11037. }
  11038. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') {
  11039. this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px';
  11040. this.dom.frame.style.bottom = '';
  11041. }
  11042. else {
  11043. var scrollableHeight = this.body.domProps.center.height - this.body.domProps.centerContainer.height;
  11044. this.dom.frame.style.bottom = 4 + scrollableHeight + Number(this.body.dom.center.style.top.replace("px","")) + 'px';
  11045. this.dom.frame.style.top = '';
  11046. }
  11047. if (this.options.icons == false) {
  11048. this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px';
  11049. this.dom.textArea.style.right = '';
  11050. this.dom.textArea.style.left = '';
  11051. this.svg.style.width = '0px';
  11052. }
  11053. else {
  11054. this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px'
  11055. this.drawLegendIcons();
  11056. }
  11057. var content = '';
  11058. for (var groupId in this.groups) {
  11059. if (this.groups.hasOwnProperty(groupId)) {
  11060. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  11061. content += this.groups[groupId].content + '<br />';
  11062. }
  11063. }
  11064. }
  11065. this.dom.textArea.innerHTML = content;
  11066. this.dom.textArea.style.lineHeight = ((0.75 * this.options.iconSize) + this.options.iconSpacing) + 'px';
  11067. }
  11068. };
  11069. Legend.prototype.drawLegendIcons = function() {
  11070. if (this.dom.frame.parentNode) {
  11071. DOMutil.prepareElements(this.svgElements);
  11072. var padding = window.getComputedStyle(this.dom.frame).paddingTop;
  11073. var iconOffset = Number(padding.replace('px',''));
  11074. var x = iconOffset;
  11075. var iconWidth = this.options.iconSize;
  11076. var iconHeight = 0.75 * this.options.iconSize;
  11077. var y = iconOffset + 0.5 * iconHeight + 3;
  11078. this.svg.style.width = iconWidth + 5 + iconOffset + 'px';
  11079. for (var groupId in this.groups) {
  11080. if (this.groups.hasOwnProperty(groupId)) {
  11081. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  11082. this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight);
  11083. y += iconHeight + this.options.iconSpacing;
  11084. }
  11085. }
  11086. }
  11087. DOMutil.cleanupElements(this.svgElements);
  11088. }
  11089. };
  11090. module.exports = Legend;
  11091. /***/ },
  11092. /* 29 */
  11093. /***/ function(module, exports, __webpack_require__) {
  11094. var util = __webpack_require__(1);
  11095. var DOMutil = __webpack_require__(2);
  11096. var DataSet = __webpack_require__(3);
  11097. var DataView = __webpack_require__(4);
  11098. var Component = __webpack_require__(20);
  11099. var DataAxis = __webpack_require__(23);
  11100. var GraphGroup = __webpack_require__(24);
  11101. var Legend = __webpack_require__(28);
  11102. var BarGraphFunctions = __webpack_require__(52);
  11103. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  11104. /**
  11105. * This is the constructor of the LineGraph. It requires a Timeline body and options.
  11106. *
  11107. * @param body
  11108. * @param options
  11109. * @constructor
  11110. */
  11111. function LineGraph(body, options) {
  11112. this.id = util.randomUUID();
  11113. this.body = body;
  11114. this.defaultOptions = {
  11115. yAxisOrientation: 'left',
  11116. defaultGroup: 'default',
  11117. sort: true,
  11118. sampling: true,
  11119. graphHeight: '400px',
  11120. shaded: {
  11121. enabled: false,
  11122. orientation: 'bottom' // top, bottom
  11123. },
  11124. style: 'line', // line, bar
  11125. barChart: {
  11126. width: 50,
  11127. handleOverlap: 'overlap',
  11128. align: 'center' // left, center, right
  11129. },
  11130. catmullRom: {
  11131. enabled: true,
  11132. parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  11133. alpha: 0.5
  11134. },
  11135. drawPoints: {
  11136. enabled: true,
  11137. size: 6,
  11138. style: 'square' // square, circle
  11139. },
  11140. dataAxis: {
  11141. showMinorLabels: true,
  11142. showMajorLabels: true,
  11143. icons: false,
  11144. width: '40px',
  11145. visible: true,
  11146. alignZeros: true,
  11147. customRange: {
  11148. left: {min:undefined, max:undefined},
  11149. right: {min:undefined, max:undefined}
  11150. }
  11151. //, these options are not set by default, but this shows the format they will be in
  11152. //format: {
  11153. // left: {decimals: 2},
  11154. // right: {decimals: 2}
  11155. //},
  11156. //title: {
  11157. // left: {
  11158. // text: 'left',
  11159. // style: 'color:black;'
  11160. // },
  11161. // right: {
  11162. // text: 'right',
  11163. // style: 'color:black;'
  11164. // }
  11165. //}
  11166. },
  11167. legend: {
  11168. enabled: false,
  11169. icons: true,
  11170. left: {
  11171. visible: true,
  11172. position: 'top-left' // top/bottom - left,right
  11173. },
  11174. right: {
  11175. visible: true,
  11176. position: 'top-right' // top/bottom - left,right
  11177. }
  11178. },
  11179. groups: {
  11180. visibility: {}
  11181. }
  11182. };
  11183. // options is shared by this ItemSet and all its items
  11184. this.options = util.extend({}, this.defaultOptions);
  11185. this.dom = {};
  11186. this.props = {};
  11187. this.hammer = null;
  11188. this.groups = {};
  11189. this.abortedGraphUpdate = false;
  11190. this.updateSVGheight = false;
  11191. this.updateSVGheightOnResize = false;
  11192. var me = this;
  11193. this.itemsData = null; // DataSet
  11194. this.groupsData = null; // DataSet
  11195. // listeners for the DataSet of the items
  11196. this.itemListeners = {
  11197. 'add': function (event, params, senderId) {
  11198. me._onAdd(params.items);
  11199. },
  11200. 'update': function (event, params, senderId) {
  11201. me._onUpdate(params.items);
  11202. },
  11203. 'remove': function (event, params, senderId) {
  11204. me._onRemove(params.items);
  11205. }
  11206. };
  11207. // listeners for the DataSet of the groups
  11208. this.groupListeners = {
  11209. 'add': function (event, params, senderId) {
  11210. me._onAddGroups(params.items);
  11211. },
  11212. 'update': function (event, params, senderId) {
  11213. me._onUpdateGroups(params.items);
  11214. },
  11215. 'remove': function (event, params, senderId) {
  11216. me._onRemoveGroups(params.items);
  11217. }
  11218. };
  11219. this.items = {}; // object with an Item for every data item
  11220. this.selection = []; // list with the ids of all selected nodes
  11221. this.lastStart = this.body.range.start;
  11222. this.touchParams = {}; // stores properties while dragging
  11223. this.svgElements = {};
  11224. this.setOptions(options);
  11225. this.groupsUsingDefaultStyles = [0];
  11226. this.COUNTER = 0;
  11227. this.body.emitter.on('rangechanged', function() {
  11228. me.lastStart = me.body.range.start;
  11229. me.svg.style.left = util.option.asSize(-me.props.width);
  11230. me.redraw.call(me,true);
  11231. });
  11232. // create the HTML DOM
  11233. this._create();
  11234. this.framework = {svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups};
  11235. this.body.emitter.emit('change');
  11236. }
  11237. LineGraph.prototype = new Component();
  11238. /**
  11239. * Create the HTML DOM for the ItemSet
  11240. */
  11241. LineGraph.prototype._create = function(){
  11242. var frame = document.createElement('div');
  11243. frame.className = 'LineGraph';
  11244. this.dom.frame = frame;
  11245. // create svg element for graph drawing.
  11246. this.svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
  11247. this.svg.style.position = 'relative';
  11248. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  11249. this.svg.style.display = 'block';
  11250. frame.appendChild(this.svg);
  11251. // data axis
  11252. this.options.dataAxis.orientation = 'left';
  11253. this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  11254. this.options.dataAxis.orientation = 'right';
  11255. this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  11256. delete this.options.dataAxis.orientation;
  11257. // legends
  11258. this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups);
  11259. this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups);
  11260. this.show();
  11261. };
  11262. /**
  11263. * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
  11264. * @param {object} options
  11265. */
  11266. LineGraph.prototype.setOptions = function(options) {
  11267. if (options) {
  11268. var fields = ['sampling','defaultGroup','height','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort','groups'];
  11269. if (options.graphHeight === undefined && options.height !== undefined && this.body.domProps.centerContainer.height !== undefined) {
  11270. this.updateSVGheight = true;
  11271. this.updateSVGheightOnResize = true;
  11272. }
  11273. else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) {
  11274. if (parseInt((options.graphHeight + '').replace("px",'')) < this.body.domProps.centerContainer.height) {
  11275. this.updateSVGheight = true;
  11276. }
  11277. }
  11278. util.selectiveDeepExtend(fields, this.options, options);
  11279. util.mergeOptions(this.options, options,'catmullRom');
  11280. util.mergeOptions(this.options, options,'drawPoints');
  11281. util.mergeOptions(this.options, options,'shaded');
  11282. util.mergeOptions(this.options, options,'legend');
  11283. if (options.catmullRom) {
  11284. if (typeof options.catmullRom == 'object') {
  11285. if (options.catmullRom.parametrization) {
  11286. if (options.catmullRom.parametrization == 'uniform') {
  11287. this.options.catmullRom.alpha = 0;
  11288. }
  11289. else if (options.catmullRom.parametrization == 'chordal') {
  11290. this.options.catmullRom.alpha = 1.0;
  11291. }
  11292. else {
  11293. this.options.catmullRom.parametrization = 'centripetal';
  11294. this.options.catmullRom.alpha = 0.5;
  11295. }
  11296. }
  11297. }
  11298. }
  11299. if (this.yAxisLeft) {
  11300. if (options.dataAxis !== undefined) {
  11301. this.yAxisLeft.setOptions(this.options.dataAxis);
  11302. this.yAxisRight.setOptions(this.options.dataAxis);
  11303. }
  11304. }
  11305. if (this.legendLeft) {
  11306. if (options.legend !== undefined) {
  11307. this.legendLeft.setOptions(this.options.legend);
  11308. this.legendRight.setOptions(this.options.legend);
  11309. }
  11310. }
  11311. if (this.groups.hasOwnProperty(UNGROUPED)) {
  11312. this.groups[UNGROUPED].setOptions(options);
  11313. }
  11314. }
  11315. // this is used to redraw the graph if the visibility of the groups is changed.
  11316. if (this.dom.frame) {
  11317. this.redraw(true);
  11318. }
  11319. };
  11320. /**
  11321. * Hide the component from the DOM
  11322. */
  11323. LineGraph.prototype.hide = function() {
  11324. // remove the frame containing the items
  11325. if (this.dom.frame.parentNode) {
  11326. this.dom.frame.parentNode.removeChild(this.dom.frame);
  11327. }
  11328. };
  11329. /**
  11330. * Show the component in the DOM (when not already visible).
  11331. * @return {Boolean} changed
  11332. */
  11333. LineGraph.prototype.show = function() {
  11334. // show frame containing the items
  11335. if (!this.dom.frame.parentNode) {
  11336. this.body.dom.center.appendChild(this.dom.frame);
  11337. }
  11338. };
  11339. /**
  11340. * Set items
  11341. * @param {vis.DataSet | null} items
  11342. */
  11343. LineGraph.prototype.setItems = function(items) {
  11344. var me = this,
  11345. ids,
  11346. oldItemsData = this.itemsData;
  11347. // replace the dataset
  11348. if (!items) {
  11349. this.itemsData = null;
  11350. }
  11351. else if (items instanceof DataSet || items instanceof DataView) {
  11352. this.itemsData = items;
  11353. }
  11354. else {
  11355. throw new TypeError('Data must be an instance of DataSet or DataView');
  11356. }
  11357. if (oldItemsData) {
  11358. // unsubscribe from old dataset
  11359. util.forEach(this.itemListeners, function (callback, event) {
  11360. oldItemsData.off(event, callback);
  11361. });
  11362. // remove all drawn items
  11363. ids = oldItemsData.getIds();
  11364. this._onRemove(ids);
  11365. }
  11366. if (this.itemsData) {
  11367. // subscribe to new dataset
  11368. var id = this.id;
  11369. util.forEach(this.itemListeners, function (callback, event) {
  11370. me.itemsData.on(event, callback, id);
  11371. });
  11372. // add all new items
  11373. ids = this.itemsData.getIds();
  11374. this._onAdd(ids);
  11375. }
  11376. this._updateUngrouped();
  11377. //this._updateGraph();
  11378. this.redraw(true);
  11379. };
  11380. /**
  11381. * Set groups
  11382. * @param {vis.DataSet} groups
  11383. */
  11384. LineGraph.prototype.setGroups = function(groups) {
  11385. var me = this;
  11386. var ids;
  11387. // unsubscribe from current dataset
  11388. if (this.groupsData) {
  11389. util.forEach(this.groupListeners, function (callback, event) {
  11390. me.groupsData.unsubscribe(event, callback);
  11391. });
  11392. // remove all drawn groups
  11393. ids = this.groupsData.getIds();
  11394. this.groupsData = null;
  11395. this._onRemoveGroups(ids); // note: this will cause a redraw
  11396. }
  11397. // replace the dataset
  11398. if (!groups) {
  11399. this.groupsData = null;
  11400. }
  11401. else if (groups instanceof DataSet || groups instanceof DataView) {
  11402. this.groupsData = groups;
  11403. }
  11404. else {
  11405. throw new TypeError('Data must be an instance of DataSet or DataView');
  11406. }
  11407. if (this.groupsData) {
  11408. // subscribe to new dataset
  11409. var id = this.id;
  11410. util.forEach(this.groupListeners, function (callback, event) {
  11411. me.groupsData.on(event, callback, id);
  11412. });
  11413. // draw all ms
  11414. ids = this.groupsData.getIds();
  11415. this._onAddGroups(ids);
  11416. }
  11417. this._onUpdate();
  11418. };
  11419. /**
  11420. * Update the data
  11421. * @param [ids]
  11422. * @private
  11423. */
  11424. LineGraph.prototype._onUpdate = function(ids) {
  11425. this._updateUngrouped();
  11426. this._updateAllGroupData();
  11427. //this._updateGraph();
  11428. this.redraw(true);
  11429. };
  11430. LineGraph.prototype._onAdd = function (ids) {this._onUpdate(ids);};
  11431. LineGraph.prototype._onRemove = function (ids) {this._onUpdate(ids);};
  11432. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  11433. for (var i = 0; i < groupIds.length; i++) {
  11434. var group = this.groupsData.get(groupIds[i]);
  11435. this._updateGroup(group, groupIds[i]);
  11436. }
  11437. //this._updateGraph();
  11438. this.redraw(true);
  11439. };
  11440. LineGraph.prototype._onAddGroups = function (groupIds) {this._onUpdateGroups(groupIds);};
  11441. /**
  11442. * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph
  11443. * @param {Array} groupIds
  11444. * @private
  11445. */
  11446. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  11447. for (var i = 0; i < groupIds.length; i++) {
  11448. if (this.groups.hasOwnProperty(groupIds[i])) {
  11449. if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') {
  11450. this.yAxisRight.removeGroup(groupIds[i]);
  11451. this.legendRight.removeGroup(groupIds[i]);
  11452. this.legendRight.redraw();
  11453. }
  11454. else {
  11455. this.yAxisLeft.removeGroup(groupIds[i]);
  11456. this.legendLeft.removeGroup(groupIds[i]);
  11457. this.legendLeft.redraw();
  11458. }
  11459. delete this.groups[groupIds[i]];
  11460. }
  11461. }
  11462. this._updateUngrouped();
  11463. //this._updateGraph();
  11464. this.redraw(true);
  11465. };
  11466. /**
  11467. * update a group object with the group dataset entree
  11468. *
  11469. * @param group
  11470. * @param groupId
  11471. * @private
  11472. */
  11473. LineGraph.prototype._updateGroup = function (group, groupId) {
  11474. if (!this.groups.hasOwnProperty(groupId)) {
  11475. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  11476. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  11477. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  11478. this.legendRight.addGroup(groupId, this.groups[groupId]);
  11479. }
  11480. else {
  11481. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  11482. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  11483. }
  11484. }
  11485. else {
  11486. this.groups[groupId].update(group);
  11487. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  11488. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  11489. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  11490. }
  11491. else {
  11492. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  11493. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  11494. }
  11495. }
  11496. this.legendLeft.redraw();
  11497. this.legendRight.redraw();
  11498. };
  11499. /**
  11500. * this updates all groups, it is used when there is an update the the itemset.
  11501. *
  11502. * @private
  11503. */
  11504. LineGraph.prototype._updateAllGroupData = function () {
  11505. if (this.itemsData != null) {
  11506. var groupsContent = {};
  11507. var groupId;
  11508. for (groupId in this.groups) {
  11509. if (this.groups.hasOwnProperty(groupId)) {
  11510. groupsContent[groupId] = [];
  11511. }
  11512. }
  11513. for (var itemId in this.itemsData._data) {
  11514. if (this.itemsData._data.hasOwnProperty(itemId)) {
  11515. var item = this.itemsData._data[itemId];
  11516. if (groupsContent[item.group] === undefined) {
  11517. 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.')
  11518. }
  11519. item.x = util.convert(item.x,'Date');
  11520. groupsContent[item.group].push(item);
  11521. }
  11522. }
  11523. for (groupId in this.groups) {
  11524. if (this.groups.hasOwnProperty(groupId)) {
  11525. this.groups[groupId].setItems(groupsContent[groupId]);
  11526. }
  11527. }
  11528. }
  11529. };
  11530. /**
  11531. * Create or delete the group holding all ungrouped items. This group is used when
  11532. * there are no groups specified. This anonymous group is called 'graph'.
  11533. * @protected
  11534. */
  11535. LineGraph.prototype._updateUngrouped = function() {
  11536. if (this.itemsData && this.itemsData != null) {
  11537. var ungroupedCounter = 0;
  11538. for (var itemId in this.itemsData._data) {
  11539. if (this.itemsData._data.hasOwnProperty(itemId)) {
  11540. var item = this.itemsData._data[itemId];
  11541. if (item != undefined) {
  11542. if (item.hasOwnProperty('group')) {
  11543. if (item.group === undefined) {
  11544. item.group = UNGROUPED;
  11545. }
  11546. }
  11547. else {
  11548. item.group = UNGROUPED;
  11549. }
  11550. ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter;
  11551. }
  11552. }
  11553. }
  11554. if (ungroupedCounter == 0) {
  11555. delete this.groups[UNGROUPED];
  11556. this.legendLeft.removeGroup(UNGROUPED);
  11557. this.legendRight.removeGroup(UNGROUPED);
  11558. this.yAxisLeft.removeGroup(UNGROUPED);
  11559. this.yAxisRight.removeGroup(UNGROUPED);
  11560. }
  11561. else {
  11562. var group = {id: UNGROUPED, content: this.options.defaultGroup};
  11563. this._updateGroup(group, UNGROUPED);
  11564. }
  11565. }
  11566. else {
  11567. delete this.groups[UNGROUPED];
  11568. this.legendLeft.removeGroup(UNGROUPED);
  11569. this.legendRight.removeGroup(UNGROUPED);
  11570. this.yAxisLeft.removeGroup(UNGROUPED);
  11571. this.yAxisRight.removeGroup(UNGROUPED);
  11572. }
  11573. this.legendLeft.redraw();
  11574. this.legendRight.redraw();
  11575. };
  11576. /**
  11577. * Redraw the component, mandatory function
  11578. * @return {boolean} Returns true if the component is resized
  11579. */
  11580. LineGraph.prototype.redraw = function(forceGraphUpdate) {
  11581. var resized = false;
  11582. // calculate actual size and position
  11583. this.props.width = this.dom.frame.offsetWidth;
  11584. this.props.height = this.body.domProps.centerContainer.height;
  11585. // update the graph if there is no lastWidth or with, used for the initial draw
  11586. if (this.lastWidth === undefined && this.props.width) {
  11587. forceGraphUpdate = true;
  11588. }
  11589. // check if this component is resized
  11590. resized = this._isResized() || resized;
  11591. // check whether zoomed (in that case we need to re-stack everything)
  11592. var visibleInterval = this.body.range.end - this.body.range.start;
  11593. var zoomed = (visibleInterval != this.lastVisibleInterval);
  11594. this.lastVisibleInterval = visibleInterval;
  11595. // the svg element is three times as big as the width, this allows for fully dragging left and right
  11596. // without reloading the graph. the controls for this are bound to events in the constructor
  11597. if (resized == true) {
  11598. this.svg.style.width = util.option.asSize(3*this.props.width);
  11599. this.svg.style.left = util.option.asSize(-this.props.width);
  11600. // if the height of the graph is set as proportional, change the height of the svg
  11601. if ((this.options.height + '').indexOf("%") != -1 || this.updateSVGheightOnResize == true) {
  11602. this.updateSVGheight = true;
  11603. }
  11604. }
  11605. // update the height of the graph on each redraw of the graph.
  11606. if (this.updateSVGheight == true) {
  11607. if (this.options.graphHeight != this.body.domProps.centerContainer.height + 'px') {
  11608. this.options.graphHeight = this.body.domProps.centerContainer.height + 'px';
  11609. this.svg.style.height = this.body.domProps.centerContainer.height + 'px';
  11610. }
  11611. this.updateSVGheight = false;
  11612. }
  11613. else {
  11614. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  11615. }
  11616. // zoomed is here to ensure that animations are shown correctly.
  11617. if (resized == true || zoomed == true || this.abortedGraphUpdate == true || forceGraphUpdate == true) {
  11618. resized = this._updateGraph() || resized;
  11619. }
  11620. else {
  11621. // move the whole svg while dragging
  11622. if (this.lastStart != 0) {
  11623. var offset = this.body.range.start - this.lastStart;
  11624. var range = this.body.range.end - this.body.range.start;
  11625. if (this.props.width != 0) {
  11626. var rangePerPixelInv = this.props.width/range;
  11627. var xOffset = offset * rangePerPixelInv;
  11628. this.svg.style.left = (-this.props.width - xOffset) + 'px';
  11629. }
  11630. }
  11631. }
  11632. this.legendLeft.redraw();
  11633. this.legendRight.redraw();
  11634. return resized;
  11635. };
  11636. /**
  11637. * Update and redraw the graph.
  11638. *
  11639. */
  11640. LineGraph.prototype._updateGraph = function () {
  11641. // reset the svg elements
  11642. DOMutil.prepareElements(this.svgElements);
  11643. if (this.props.width != 0 && this.itemsData != null) {
  11644. var group, i;
  11645. var preprocessedGroupData = {};
  11646. var processedGroupData = {};
  11647. var groupRanges = {};
  11648. var changeCalled = false;
  11649. // getting group Ids
  11650. var groupIds = [];
  11651. for (var groupId in this.groups) {
  11652. if (this.groups.hasOwnProperty(groupId)) {
  11653. group = this.groups[groupId];
  11654. if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) {
  11655. groupIds.push(groupId);
  11656. }
  11657. }
  11658. }
  11659. if (groupIds.length > 0) {
  11660. // this is the range of the SVG canvas
  11661. var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width);
  11662. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  11663. var groupsData = {};
  11664. // fill groups data, this only loads the data we require based on the timewindow
  11665. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  11666. // apply sampling, if disabled, it will pass through this function.
  11667. this._applySampling(groupIds, groupsData);
  11668. // we transform the X coordinates to detect collisions
  11669. for (i = 0; i < groupIds.length; i++) {
  11670. preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]);
  11671. }
  11672. // now all needed data has been collected we start the processing.
  11673. this._getYRanges(groupIds, preprocessedGroupData, groupRanges);
  11674. // update the Y axis first, we use this data to draw at the correct Y points
  11675. // changeCalled is required to clean the SVG on a change emit.
  11676. changeCalled = this._updateYAxis(groupIds, groupRanges);
  11677. var MAX_CYCLES = 5;
  11678. if (changeCalled == true && this.COUNTER < MAX_CYCLES) {
  11679. DOMutil.cleanupElements(this.svgElements);
  11680. this.abortedGraphUpdate = true;
  11681. this.COUNTER++;
  11682. this.body.emitter.emit('change');
  11683. return true;
  11684. }
  11685. else {
  11686. if (this.COUNTER > MAX_CYCLES) {
  11687. console.log("WARNING: there may be an infinite loop in the _updateGraph emitter cycle.")
  11688. }
  11689. this.COUNTER = 0;
  11690. this.abortedGraphUpdate = false;
  11691. // With the yAxis scaled correctly, use this to get the Y values of the points.
  11692. for (i = 0; i < groupIds.length; i++) {
  11693. group = this.groups[groupIds[i]];
  11694. processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group);
  11695. }
  11696. // draw the groups
  11697. for (i = 0; i < groupIds.length; i++) {
  11698. group = this.groups[groupIds[i]];
  11699. if (group.options.style != 'bar') { // bar needs to be drawn enmasse
  11700. group.draw(processedGroupData[groupIds[i]], group, this.framework);
  11701. }
  11702. }
  11703. BarGraphFunctions.draw(groupIds, processedGroupData, this.framework);
  11704. }
  11705. }
  11706. }
  11707. // cleanup unused svg elements
  11708. DOMutil.cleanupElements(this.svgElements);
  11709. return false;
  11710. };
  11711. /**
  11712. * first select and preprocess the data from the datasets.
  11713. * the groups have their preselection of data, we now loop over this data to see
  11714. * what data we need to draw. Sorted data is much faster.
  11715. * more optimization is possible by doing the sampling before and using the binary search
  11716. * to find the end date to determine the increment.
  11717. *
  11718. * @param {array} groupIds
  11719. * @param {object} groupsData
  11720. * @param {date} minDate
  11721. * @param {date} maxDate
  11722. * @private
  11723. */
  11724. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  11725. var group, i, j, item;
  11726. if (groupIds.length > 0) {
  11727. for (i = 0; i < groupIds.length; i++) {
  11728. group = this.groups[groupIds[i]];
  11729. groupsData[groupIds[i]] = [];
  11730. var dataContainer = groupsData[groupIds[i]];
  11731. // optimization for sorted data
  11732. if (group.options.sort == true) {
  11733. var guess = Math.max(0, util.binarySearchValue(group.itemsData, minDate, 'x', 'before'));
  11734. for (j = guess; j < group.itemsData.length; j++) {
  11735. item = group.itemsData[j];
  11736. if (item !== undefined) {
  11737. if (item.x > maxDate) {
  11738. dataContainer.push(item);
  11739. break;
  11740. }
  11741. else {
  11742. dataContainer.push(item);
  11743. }
  11744. }
  11745. }
  11746. }
  11747. else {
  11748. for (j = 0; j < group.itemsData.length; j++) {
  11749. item = group.itemsData[j];
  11750. if (item !== undefined) {
  11751. if (item.x > minDate && item.x < maxDate) {
  11752. dataContainer.push(item);
  11753. }
  11754. }
  11755. }
  11756. }
  11757. }
  11758. }
  11759. };
  11760. /**
  11761. *
  11762. * @param groupIds
  11763. * @param groupsData
  11764. * @private
  11765. */
  11766. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  11767. var group;
  11768. if (groupIds.length > 0) {
  11769. for (var i = 0; i < groupIds.length; i++) {
  11770. group = this.groups[groupIds[i]];
  11771. if (group.options.sampling == true) {
  11772. var dataContainer = groupsData[groupIds[i]];
  11773. if (dataContainer.length > 0) {
  11774. var increment = 1;
  11775. var amountOfPoints = dataContainer.length;
  11776. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  11777. // of width changing of the yAxis.
  11778. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  11779. var pointsPerPixel = amountOfPoints / xDistance;
  11780. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  11781. var sampledData = [];
  11782. for (var j = 0; j < amountOfPoints; j += increment) {
  11783. sampledData.push(dataContainer[j]);
  11784. }
  11785. groupsData[groupIds[i]] = sampledData;
  11786. }
  11787. }
  11788. }
  11789. }
  11790. };
  11791. /**
  11792. *
  11793. *
  11794. * @param {array} groupIds
  11795. * @param {object} groupsData
  11796. * @param {object} groupRanges | this is being filled here
  11797. * @private
  11798. */
  11799. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  11800. var groupData, group, i;
  11801. var barCombinedDataLeft = [];
  11802. var barCombinedDataRight = [];
  11803. var options;
  11804. if (groupIds.length > 0) {
  11805. for (i = 0; i < groupIds.length; i++) {
  11806. groupData = groupsData[groupIds[i]];
  11807. options = this.groups[groupIds[i]].options;
  11808. if (groupData.length > 0) {
  11809. group = this.groups[groupIds[i]];
  11810. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  11811. if (options.barChart.handleOverlap == 'stack' && options.style == 'bar') {
  11812. if (options.yAxisOrientation == 'left') {barCombinedDataLeft = barCombinedDataLeft.concat(group.getYRange(groupData)) ;}
  11813. else {barCombinedDataRight = barCombinedDataRight.concat(group.getYRange(groupData));}
  11814. }
  11815. else {
  11816. groupRanges[groupIds[i]] = group.getYRange(groupData,groupIds[i]);
  11817. }
  11818. }
  11819. }
  11820. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  11821. BarGraphFunctions.getStackedBarYRange(barCombinedDataLeft , groupRanges, groupIds, '__barchartLeft' , 'left' );
  11822. BarGraphFunctions.getStackedBarYRange(barCombinedDataRight, groupRanges, groupIds, '__barchartRight', 'right');
  11823. }
  11824. };
  11825. /**
  11826. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  11827. * @param {Array} groupIds
  11828. * @param {Object} groupRanges
  11829. * @private
  11830. */
  11831. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  11832. var resized = false;
  11833. var yAxisLeftUsed = false;
  11834. var yAxisRightUsed = false;
  11835. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  11836. // if groups are present
  11837. if (groupIds.length > 0) {
  11838. // 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.
  11839. for (var i = 0; i < groupIds.length; i++) {
  11840. var group = this.groups[groupIds[i]];
  11841. if (group && group.options.yAxisOrientation != 'right') {
  11842. yAxisLeftUsed = true;
  11843. minLeft = 0;
  11844. maxLeft = 0;
  11845. }
  11846. else if (group && group.options.yAxisOrientation) {
  11847. yAxisRightUsed = true;
  11848. minRight = 0;
  11849. maxRight = 0;
  11850. }
  11851. }
  11852. // if there are items:
  11853. for (var i = 0; i < groupIds.length; i++) {
  11854. if (groupRanges.hasOwnProperty(groupIds[i])) {
  11855. if (groupRanges[groupIds[i]].ignore !== true) {
  11856. minVal = groupRanges[groupIds[i]].min;
  11857. maxVal = groupRanges[groupIds[i]].max;
  11858. if (groupRanges[groupIds[i]].yAxisOrientation != 'right') {
  11859. yAxisLeftUsed = true;
  11860. minLeft = minLeft > minVal ? minVal : minLeft;
  11861. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  11862. }
  11863. else {
  11864. yAxisRightUsed = true;
  11865. minRight = minRight > minVal ? minVal : minRight;
  11866. maxRight = maxRight < maxVal ? maxVal : maxRight;
  11867. }
  11868. }
  11869. }
  11870. }
  11871. if (yAxisLeftUsed == true) {
  11872. this.yAxisLeft.setRange(minLeft, maxLeft);
  11873. }
  11874. if (yAxisRightUsed == true) {
  11875. this.yAxisRight.setRange(minRight, maxRight);
  11876. }
  11877. }
  11878. resized = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || resized;
  11879. resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized;
  11880. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  11881. this.yAxisLeft.drawIcons = true;
  11882. this.yAxisRight.drawIcons = true;
  11883. }
  11884. else {
  11885. this.yAxisLeft.drawIcons = false;
  11886. this.yAxisRight.drawIcons = false;
  11887. }
  11888. this.yAxisRight.master = !yAxisLeftUsed;
  11889. if (this.yAxisRight.master == false) {
  11890. if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;}
  11891. else {this.yAxisLeft.lineOffset = 0;}
  11892. resized = this.yAxisLeft.redraw() || resized;
  11893. this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels;
  11894. this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing;
  11895. resized = this.yAxisRight.redraw() || resized;
  11896. }
  11897. else {
  11898. resized = this.yAxisRight.redraw() || resized;
  11899. }
  11900. // clean the accumulated lists
  11901. if (groupIds.indexOf('__barchartLeft') != -1) {
  11902. groupIds.splice(groupIds.indexOf('__barchartLeft'),1);
  11903. }
  11904. if (groupIds.indexOf('__barchartRight') != -1) {
  11905. groupIds.splice(groupIds.indexOf('__barchartRight'),1);
  11906. }
  11907. return resized;
  11908. };
  11909. /**
  11910. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  11911. *
  11912. * @param {boolean} axisUsed
  11913. * @returns {boolean}
  11914. * @private
  11915. * @param axis
  11916. */
  11917. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  11918. var changed = false;
  11919. if (axisUsed == false) {
  11920. if (axis.dom.frame.parentNode && axis.hidden == false) {
  11921. axis.hide()
  11922. changed = true;
  11923. }
  11924. }
  11925. else {
  11926. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  11927. axis.show();
  11928. changed = true;
  11929. }
  11930. }
  11931. return changed;
  11932. };
  11933. /**
  11934. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  11935. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  11936. * the yAxis.
  11937. *
  11938. * @param datapoints
  11939. * @returns {Array}
  11940. * @private
  11941. */
  11942. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  11943. var extractedData = [];
  11944. var xValue, yValue;
  11945. var toScreen = this.body.util.toScreen;
  11946. for (var i = 0; i < datapoints.length; i++) {
  11947. xValue = toScreen(datapoints[i].x) + this.props.width;
  11948. yValue = datapoints[i].y;
  11949. extractedData.push({x: xValue, y: yValue});
  11950. }
  11951. return extractedData;
  11952. };
  11953. /**
  11954. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  11955. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  11956. * the yAxis.
  11957. *
  11958. * @param datapoints
  11959. * @param group
  11960. * @returns {Array}
  11961. * @private
  11962. */
  11963. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  11964. var extractedData = [];
  11965. var xValue, yValue;
  11966. var toScreen = this.body.util.toScreen;
  11967. var axis = this.yAxisLeft;
  11968. var svgHeight = Number(this.svg.style.height.replace('px',''));
  11969. if (group.options.yAxisOrientation == 'right') {
  11970. axis = this.yAxisRight;
  11971. }
  11972. for (var i = 0; i < datapoints.length; i++) {
  11973. xValue = toScreen(datapoints[i].x) + this.props.width;
  11974. yValue = Math.round(axis.convertValue(datapoints[i].y));
  11975. extractedData.push({x: xValue, y: yValue});
  11976. }
  11977. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  11978. return extractedData;
  11979. };
  11980. module.exports = LineGraph;
  11981. /***/ },
  11982. /* 30 */
  11983. /***/ function(module, exports, __webpack_require__) {
  11984. var util = __webpack_require__(1);
  11985. var Component = __webpack_require__(20);
  11986. var TimeStep = __webpack_require__(19);
  11987. var DateUtil = __webpack_require__(15);
  11988. var moment = __webpack_require__(44);
  11989. /**
  11990. * A horizontal time axis
  11991. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  11992. * @param {Object} [options] See TimeAxis.setOptions for the available
  11993. * options.
  11994. * @constructor TimeAxis
  11995. * @extends Component
  11996. */
  11997. function TimeAxis (body, options) {
  11998. this.dom = {
  11999. foreground: null,
  12000. lines: [],
  12001. majorTexts: [],
  12002. minorTexts: [],
  12003. redundant: {
  12004. lines: [],
  12005. majorTexts: [],
  12006. minorTexts: []
  12007. }
  12008. };
  12009. this.props = {
  12010. range: {
  12011. start: 0,
  12012. end: 0,
  12013. minimumStep: 0
  12014. },
  12015. lineTop: 0
  12016. };
  12017. this.defaultOptions = {
  12018. orientation: 'bottom', // supported: 'top', 'bottom'
  12019. // TODO: implement timeaxis orientations 'left' and 'right'
  12020. showMinorLabels: true,
  12021. showMajorLabels: true,
  12022. format: null
  12023. };
  12024. this.options = util.extend({}, this.defaultOptions);
  12025. this.body = body;
  12026. // create the HTML DOM
  12027. this._create();
  12028. this.setOptions(options);
  12029. }
  12030. TimeAxis.prototype = new Component();
  12031. /**
  12032. * Set options for the TimeAxis.
  12033. * Parameters will be merged in current options.
  12034. * @param {Object} options Available options:
  12035. * {string} [orientation]
  12036. * {boolean} [showMinorLabels]
  12037. * {boolean} [showMajorLabels]
  12038. */
  12039. TimeAxis.prototype.setOptions = function(options) {
  12040. if (options) {
  12041. // copy all options that we know
  12042. util.selectiveExtend([
  12043. 'orientation',
  12044. 'showMinorLabels',
  12045. 'showMajorLabels',
  12046. 'hiddenDates',
  12047. 'format'
  12048. ], this.options, options);
  12049. // apply locale to moment.js
  12050. // TODO: not so nice, this is applied globally to moment.js
  12051. if ('locale' in options) {
  12052. if (typeof moment.locale === 'function') {
  12053. // moment.js 2.8.1+
  12054. moment.locale(options.locale);
  12055. }
  12056. else {
  12057. moment.lang(options.locale);
  12058. }
  12059. }
  12060. }
  12061. };
  12062. /**
  12063. * Create the HTML DOM for the TimeAxis
  12064. */
  12065. TimeAxis.prototype._create = function() {
  12066. this.dom.foreground = document.createElement('div');
  12067. this.dom.background = document.createElement('div');
  12068. this.dom.foreground.className = 'timeaxis foreground';
  12069. this.dom.background.className = 'timeaxis background';
  12070. };
  12071. /**
  12072. * Destroy the TimeAxis
  12073. */
  12074. TimeAxis.prototype.destroy = function() {
  12075. // remove from DOM
  12076. if (this.dom.foreground.parentNode) {
  12077. this.dom.foreground.parentNode.removeChild(this.dom.foreground);
  12078. }
  12079. if (this.dom.background.parentNode) {
  12080. this.dom.background.parentNode.removeChild(this.dom.background);
  12081. }
  12082. this.body = null;
  12083. };
  12084. /**
  12085. * Repaint the component
  12086. * @return {boolean} Returns true if the component is resized
  12087. */
  12088. TimeAxis.prototype.redraw = function () {
  12089. var options = this.options;
  12090. var props = this.props;
  12091. var foreground = this.dom.foreground;
  12092. var background = this.dom.background;
  12093. // determine the correct parent DOM element (depending on option orientation)
  12094. var parent = (options.orientation == 'top') ? this.body.dom.top : this.body.dom.bottom;
  12095. var parentChanged = (foreground.parentNode !== parent);
  12096. // calculate character width and height
  12097. this._calculateCharSize();
  12098. // TODO: recalculate sizes only needed when parent is resized or options is changed
  12099. var orientation = this.options.orientation,
  12100. showMinorLabels = this.options.showMinorLabels,
  12101. showMajorLabels = this.options.showMajorLabels;
  12102. // determine the width and height of the elemens for the axis
  12103. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  12104. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  12105. props.height = props.minorLabelHeight + props.majorLabelHeight;
  12106. props.width = foreground.offsetWidth;
  12107. props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight -
  12108. (options.orientation == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height);
  12109. props.minorLineWidth = 1; // TODO: really calculate width
  12110. props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight;
  12111. props.majorLineWidth = 1; // TODO: really calculate width
  12112. // take foreground and background offline while updating (is almost twice as fast)
  12113. var foregroundNextSibling = foreground.nextSibling;
  12114. var backgroundNextSibling = background.nextSibling;
  12115. foreground.parentNode && foreground.parentNode.removeChild(foreground);
  12116. background.parentNode && background.parentNode.removeChild(background);
  12117. foreground.style.height = this.props.height + 'px';
  12118. this._repaintLabels();
  12119. // put DOM online again (at the same place)
  12120. if (foregroundNextSibling) {
  12121. parent.insertBefore(foreground, foregroundNextSibling);
  12122. }
  12123. else {
  12124. parent.appendChild(foreground)
  12125. }
  12126. if (backgroundNextSibling) {
  12127. this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling);
  12128. }
  12129. else {
  12130. this.body.dom.backgroundVertical.appendChild(background)
  12131. }
  12132. return this._isResized() || parentChanged;
  12133. };
  12134. /**
  12135. * Repaint major and minor text labels and vertical grid lines
  12136. * @private
  12137. */
  12138. TimeAxis.prototype._repaintLabels = function () {
  12139. var orientation = this.options.orientation;
  12140. // calculate range and step (step such that we have space for 7 characters per label)
  12141. var start = util.convert(this.body.range.start, 'Number');
  12142. var end = util.convert(this.body.range.end, 'Number');
  12143. var timeLabelsize = this.body.util.toTime((this.props.minorCharWidth || 10) * 7).valueOf();
  12144. var minimumStep = timeLabelsize - DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this.body.range, timeLabelsize);
  12145. minimumStep -= this.body.util.toTime(0).valueOf();
  12146. var step = new TimeStep(new Date(start), new Date(end), minimumStep, this.body.hiddenDates);
  12147. if (this.options.format) {
  12148. step.setFormat(this.options.format);
  12149. }
  12150. this.step = step;
  12151. // Move all DOM elements to a "redundant" list, where they
  12152. // can be picked for re-use, and clear the lists with lines and texts.
  12153. // At the end of the function _repaintLabels, left over elements will be cleaned up
  12154. var dom = this.dom;
  12155. dom.redundant.lines = dom.lines;
  12156. dom.redundant.majorTexts = dom.majorTexts;
  12157. dom.redundant.minorTexts = dom.minorTexts;
  12158. dom.lines = [];
  12159. dom.majorTexts = [];
  12160. dom.minorTexts = [];
  12161. var cur;
  12162. var x = 0;
  12163. var isMajor;
  12164. var xPrev = 0;
  12165. var width = 0;
  12166. var prevLine;
  12167. var xFirstMajorLabel = undefined;
  12168. var max = 0;
  12169. var className;
  12170. step.first();
  12171. while (step.hasNext() && max < 1000) {
  12172. max++;
  12173. cur = step.getCurrent();
  12174. isMajor = step.isMajor();
  12175. className = step.getClassName();
  12176. xPrev = x;
  12177. x = this.body.util.toScreen(cur);
  12178. width = x - xPrev;
  12179. if (prevLine) {
  12180. prevLine.style.width = width + 'px';
  12181. }
  12182. if (this.options.showMinorLabels) {
  12183. this._repaintMinorText(x, step.getLabelMinor(), orientation, className);
  12184. }
  12185. if (isMajor && this.options.showMajorLabels) {
  12186. if (x > 0) {
  12187. if (xFirstMajorLabel == undefined) {
  12188. xFirstMajorLabel = x;
  12189. }
  12190. this._repaintMajorText(x, step.getLabelMajor(), orientation, className);
  12191. }
  12192. prevLine = this._repaintMajorLine(x, orientation, className);
  12193. }
  12194. else {
  12195. prevLine = this._repaintMinorLine(x, orientation, className);
  12196. }
  12197. step.next();
  12198. }
  12199. // create a major label on the left when needed
  12200. if (this.options.showMajorLabels) {
  12201. var leftTime = this.body.util.toTime(0),
  12202. leftText = step.getLabelMajor(leftTime),
  12203. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  12204. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  12205. this._repaintMajorText(0, leftText, orientation, className);
  12206. }
  12207. }
  12208. // Cleanup leftover DOM elements from the redundant list
  12209. util.forEach(this.dom.redundant, function (arr) {
  12210. while (arr.length) {
  12211. var elem = arr.pop();
  12212. if (elem && elem.parentNode) {
  12213. elem.parentNode.removeChild(elem);
  12214. }
  12215. }
  12216. });
  12217. };
  12218. /**
  12219. * Create a minor label for the axis at position x
  12220. * @param {Number} x
  12221. * @param {String} text
  12222. * @param {String} orientation "top" or "bottom" (default)
  12223. * @param {String} className
  12224. * @private
  12225. */
  12226. TimeAxis.prototype._repaintMinorText = function (x, text, orientation, className) {
  12227. // reuse redundant label
  12228. var label = this.dom.redundant.minorTexts.shift();
  12229. if (!label) {
  12230. // create new label
  12231. var content = document.createTextNode('');
  12232. label = document.createElement('div');
  12233. label.appendChild(content);
  12234. this.dom.foreground.appendChild(label);
  12235. }
  12236. this.dom.minorTexts.push(label);
  12237. label.childNodes[0].nodeValue = text;
  12238. label.style.top = (orientation == 'top') ? (this.props.majorLabelHeight + 'px') : '0';
  12239. label.style.left = x + 'px';
  12240. label.className = 'text minor ' + className;
  12241. //label.title = title; // TODO: this is a heavy operation
  12242. };
  12243. /**
  12244. * Create a Major label for the axis at position x
  12245. * @param {Number} x
  12246. * @param {String} text
  12247. * @param {String} orientation "top" or "bottom" (default)
  12248. * @param {String} className
  12249. * @private
  12250. */
  12251. TimeAxis.prototype._repaintMajorText = function (x, text, orientation, className) {
  12252. // reuse redundant label
  12253. var label = this.dom.redundant.majorTexts.shift();
  12254. if (!label) {
  12255. // create label
  12256. var content = document.createTextNode(text);
  12257. label = document.createElement('div');
  12258. label.appendChild(content);
  12259. this.dom.foreground.appendChild(label);
  12260. }
  12261. this.dom.majorTexts.push(label);
  12262. label.childNodes[0].nodeValue = text;
  12263. label.className = 'text major ' + className;
  12264. //label.title = title; // TODO: this is a heavy operation
  12265. label.style.top = (orientation == 'top') ? '0' : (this.props.minorLabelHeight + 'px');
  12266. label.style.left = x + 'px';
  12267. };
  12268. /**
  12269. * Create a minor line for the axis at position x
  12270. * @param {Number} x
  12271. * @param {String} orientation "top" or "bottom" (default)
  12272. * @param {String} className
  12273. * @return {Element} Returns the created line
  12274. * @private
  12275. */
  12276. TimeAxis.prototype._repaintMinorLine = function (x, orientation, className) {
  12277. // reuse redundant line
  12278. var line = this.dom.redundant.lines.shift();
  12279. if (!line) {
  12280. // create vertical line
  12281. line = document.createElement('div');
  12282. this.dom.background.appendChild(line);
  12283. }
  12284. this.dom.lines.push(line);
  12285. var props = this.props;
  12286. if (orientation == 'top') {
  12287. line.style.top = props.majorLabelHeight + 'px';
  12288. }
  12289. else {
  12290. line.style.top = this.body.domProps.top.height + 'px';
  12291. }
  12292. line.style.height = props.minorLineHeight + 'px';
  12293. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  12294. line.className = 'grid vertical minor ' + className;
  12295. return line;
  12296. };
  12297. /**
  12298. * Create a Major line for the axis at position x
  12299. * @param {Number} x
  12300. * @param {String} orientation "top" or "bottom" (default)
  12301. * @param {String} className
  12302. * @return {Element} Returns the created line
  12303. * @private
  12304. */
  12305. TimeAxis.prototype._repaintMajorLine = function (x, orientation, className) {
  12306. // reuse redundant line
  12307. var line = this.dom.redundant.lines.shift();
  12308. if (!line) {
  12309. // create vertical line
  12310. line = document.createElement('div');
  12311. this.dom.background.appendChild(line);
  12312. }
  12313. this.dom.lines.push(line);
  12314. var props = this.props;
  12315. if (orientation == 'top') {
  12316. line.style.top = '0';
  12317. }
  12318. else {
  12319. line.style.top = this.body.domProps.top.height + 'px';
  12320. }
  12321. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  12322. line.style.height = props.majorLineHeight + 'px';
  12323. line.className = 'grid vertical major ' + className;
  12324. return line;
  12325. };
  12326. /**
  12327. * Determine the size of text on the axis (both major and minor axis).
  12328. * The size is calculated only once and then cached in this.props.
  12329. * @private
  12330. */
  12331. TimeAxis.prototype._calculateCharSize = function () {
  12332. // Note: We calculate char size with every redraw. Size may change, for
  12333. // example when any of the timelines parents had display:none for example.
  12334. // determine the char width and height on the minor axis
  12335. if (!this.dom.measureCharMinor) {
  12336. this.dom.measureCharMinor = document.createElement('DIV');
  12337. this.dom.measureCharMinor.className = 'text minor measure';
  12338. this.dom.measureCharMinor.style.position = 'absolute';
  12339. this.dom.measureCharMinor.appendChild(document.createTextNode('0'));
  12340. this.dom.foreground.appendChild(this.dom.measureCharMinor);
  12341. }
  12342. this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight;
  12343. this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth;
  12344. // determine the char width and height on the major axis
  12345. if (!this.dom.measureCharMajor) {
  12346. this.dom.measureCharMajor = document.createElement('DIV');
  12347. this.dom.measureCharMajor.className = 'text major measure';
  12348. this.dom.measureCharMajor.style.position = 'absolute';
  12349. this.dom.measureCharMajor.appendChild(document.createTextNode('0'));
  12350. this.dom.foreground.appendChild(this.dom.measureCharMajor);
  12351. }
  12352. this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight;
  12353. this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth;
  12354. };
  12355. /**
  12356. * Snap a date to a rounded value.
  12357. * The snap intervals are dependent on the current scale and step.
  12358. * @param {Date} date the date to be snapped.
  12359. * @return {Date} snappedDate
  12360. */
  12361. TimeAxis.prototype.snap = function(date) {
  12362. return this.step.snap(date);
  12363. };
  12364. module.exports = TimeAxis;
  12365. /***/ },
  12366. /* 31 */
  12367. /***/ function(module, exports, __webpack_require__) {
  12368. var Hammer = __webpack_require__(45);
  12369. var util = __webpack_require__(1);
  12370. /**
  12371. * @constructor Item
  12372. * @param {Object} data Object containing (optional) parameters type,
  12373. * start, end, content, group, className.
  12374. * @param {{toScreen: function, toTime: function}} conversion
  12375. * Conversion functions from time to screen and vice versa
  12376. * @param {Object} options Configuration options
  12377. * // TODO: describe available options
  12378. */
  12379. function Item (data, conversion, options) {
  12380. this.id = null;
  12381. this.parent = null;
  12382. this.data = data;
  12383. this.dom = null;
  12384. this.conversion = conversion || {};
  12385. this.options = options || {};
  12386. this.selected = false;
  12387. this.displayed = false;
  12388. this.dirty = true;
  12389. this.top = null;
  12390. this.left = null;
  12391. this.width = null;
  12392. this.height = null;
  12393. }
  12394. Item.prototype.stack = true;
  12395. /**
  12396. * Select current item
  12397. */
  12398. Item.prototype.select = function() {
  12399. this.selected = true;
  12400. this.dirty = true;
  12401. if (this.displayed) this.redraw();
  12402. };
  12403. /**
  12404. * Unselect current item
  12405. */
  12406. Item.prototype.unselect = function() {
  12407. this.selected = false;
  12408. this.dirty = true;
  12409. if (this.displayed) this.redraw();
  12410. };
  12411. /**
  12412. * Set data for the item. Existing data will be updated. The id should not
  12413. * be changed. When the item is displayed, it will be redrawn immediately.
  12414. * @param {Object} data
  12415. */
  12416. Item.prototype.setData = function(data) {
  12417. this.data = data;
  12418. this.dirty = true;
  12419. if (this.displayed) this.redraw();
  12420. };
  12421. /**
  12422. * Set a parent for the item
  12423. * @param {ItemSet | Group} parent
  12424. */
  12425. Item.prototype.setParent = function(parent) {
  12426. if (this.displayed) {
  12427. this.hide();
  12428. this.parent = parent;
  12429. if (this.parent) {
  12430. this.show();
  12431. }
  12432. }
  12433. else {
  12434. this.parent = parent;
  12435. }
  12436. };
  12437. /**
  12438. * Check whether this item is visible inside given range
  12439. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  12440. * @returns {boolean} True if visible
  12441. */
  12442. Item.prototype.isVisible = function(range) {
  12443. // Should be implemented by Item implementations
  12444. return false;
  12445. };
  12446. /**
  12447. * Show the Item in the DOM (when not already visible)
  12448. * @return {Boolean} changed
  12449. */
  12450. Item.prototype.show = function() {
  12451. return false;
  12452. };
  12453. /**
  12454. * Hide the Item from the DOM (when visible)
  12455. * @return {Boolean} changed
  12456. */
  12457. Item.prototype.hide = function() {
  12458. return false;
  12459. };
  12460. /**
  12461. * Repaint the item
  12462. */
  12463. Item.prototype.redraw = function() {
  12464. // should be implemented by the item
  12465. };
  12466. /**
  12467. * Reposition the Item horizontally
  12468. */
  12469. Item.prototype.repositionX = function() {
  12470. // should be implemented by the item
  12471. };
  12472. /**
  12473. * Reposition the Item vertically
  12474. */
  12475. Item.prototype.repositionY = function() {
  12476. // should be implemented by the item
  12477. };
  12478. /**
  12479. * Repaint a delete button on the top right of the item when the item is selected
  12480. * @param {HTMLElement} anchor
  12481. * @protected
  12482. */
  12483. Item.prototype._repaintDeleteButton = function (anchor) {
  12484. if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
  12485. // create and show button
  12486. var me = this;
  12487. var deleteButton = document.createElement('div');
  12488. deleteButton.className = 'delete';
  12489. deleteButton.title = 'Delete this item';
  12490. Hammer(deleteButton, {
  12491. preventDefault: true
  12492. }).on('tap', function (event) {
  12493. me.parent.removeFromDataSet(me);
  12494. event.stopPropagation();
  12495. });
  12496. anchor.appendChild(deleteButton);
  12497. this.dom.deleteButton = deleteButton;
  12498. }
  12499. else if (!this.selected && this.dom.deleteButton) {
  12500. // remove button
  12501. if (this.dom.deleteButton.parentNode) {
  12502. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  12503. }
  12504. this.dom.deleteButton = null;
  12505. }
  12506. };
  12507. /**
  12508. * Set HTML contents for the item
  12509. * @param {Element} element HTML element to fill with the contents
  12510. * @private
  12511. */
  12512. Item.prototype._updateContents = function (element) {
  12513. var content;
  12514. if (this.options.template) {
  12515. var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset
  12516. content = this.options.template(itemData);
  12517. }
  12518. else {
  12519. content = this.data.content;
  12520. }
  12521. if(content !== this.content) {
  12522. // only replace the content when changed
  12523. if (content instanceof Element) {
  12524. element.innerHTML = '';
  12525. element.appendChild(content);
  12526. }
  12527. else if (content != undefined) {
  12528. element.innerHTML = content;
  12529. }
  12530. else {
  12531. if (!(this.data.type == 'background' && this.data.content === undefined)) {
  12532. throw new Error('Property "content" missing in item ' + this.id);
  12533. }
  12534. }
  12535. this.content = content;
  12536. }
  12537. };
  12538. /**
  12539. * Set HTML contents for the item
  12540. * @param {Element} element HTML element to fill with the contents
  12541. * @private
  12542. */
  12543. Item.prototype._updateTitle = function (element) {
  12544. if (this.data.title != null) {
  12545. element.title = this.data.title || '';
  12546. }
  12547. else {
  12548. element.removeAttribute('title');
  12549. }
  12550. };
  12551. /**
  12552. * Process dataAttributes timeline option and set as data- attributes on dom.content
  12553. * @param {Element} element HTML element to which the attributes will be attached
  12554. * @private
  12555. */
  12556. Item.prototype._updateDataAttributes = function(element) {
  12557. if (this.options.dataAttributes && this.options.dataAttributes.length > 0) {
  12558. var attributes = [];
  12559. if (Array.isArray(this.options.dataAttributes)) {
  12560. attributes = this.options.dataAttributes;
  12561. }
  12562. else if (this.options.dataAttributes == 'all') {
  12563. attributes = Object.keys(this.data);
  12564. }
  12565. else {
  12566. return;
  12567. }
  12568. for (var i = 0; i < attributes.length; i++) {
  12569. var name = attributes[i];
  12570. var value = this.data[name];
  12571. if (value != null) {
  12572. element.setAttribute('data-' + name, value);
  12573. }
  12574. else {
  12575. element.removeAttribute('data-' + name);
  12576. }
  12577. }
  12578. }
  12579. };
  12580. /**
  12581. * Update custom styles of the element
  12582. * @param element
  12583. * @private
  12584. */
  12585. Item.prototype._updateStyle = function(element) {
  12586. // remove old styles
  12587. if (this.style) {
  12588. util.removeCssText(element, this.style);
  12589. this.style = null;
  12590. }
  12591. // append new styles
  12592. if (this.data.style) {
  12593. util.addCssText(element, this.data.style);
  12594. this.style = this.data.style;
  12595. }
  12596. };
  12597. module.exports = Item;
  12598. /***/ },
  12599. /* 32 */
  12600. /***/ function(module, exports, __webpack_require__) {
  12601. var Hammer = __webpack_require__(45);
  12602. var Item = __webpack_require__(31);
  12603. var BackgroundGroup = __webpack_require__(26);
  12604. var RangeItem = __webpack_require__(35);
  12605. /**
  12606. * @constructor BackgroundItem
  12607. * @extends Item
  12608. * @param {Object} data Object containing parameters start, end
  12609. * content, className.
  12610. * @param {{toScreen: function, toTime: function}} conversion
  12611. * Conversion functions from time to screen and vice versa
  12612. * @param {Object} [options] Configuration options
  12613. * // TODO: describe options
  12614. */
  12615. // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation
  12616. function BackgroundItem (data, conversion, options) {
  12617. this.props = {
  12618. content: {
  12619. width: 0
  12620. }
  12621. };
  12622. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  12623. // validate data
  12624. if (data) {
  12625. if (data.start == undefined) {
  12626. throw new Error('Property "start" missing in item ' + data.id);
  12627. }
  12628. if (data.end == undefined) {
  12629. throw new Error('Property "end" missing in item ' + data.id);
  12630. }
  12631. }
  12632. Item.call(this, data, conversion, options);
  12633. this.emptyContent = false;
  12634. }
  12635. BackgroundItem.prototype = new Item (null, null, null);
  12636. BackgroundItem.prototype.baseClassName = 'item background';
  12637. BackgroundItem.prototype.stack = false;
  12638. /**
  12639. * Check whether this item is visible inside given range
  12640. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  12641. * @returns {boolean} True if visible
  12642. */
  12643. BackgroundItem.prototype.isVisible = function(range) {
  12644. // determine visibility
  12645. return (this.data.start < range.end) && (this.data.end > range.start);
  12646. };
  12647. /**
  12648. * Repaint the item
  12649. */
  12650. BackgroundItem.prototype.redraw = function() {
  12651. var dom = this.dom;
  12652. if (!dom) {
  12653. // create DOM
  12654. this.dom = {};
  12655. dom = this.dom;
  12656. // background box
  12657. dom.box = document.createElement('div');
  12658. // className is updated in redraw()
  12659. // contents box
  12660. dom.content = document.createElement('div');
  12661. dom.content.className = 'content';
  12662. dom.box.appendChild(dom.content);
  12663. // Note: we do NOT attach this item as attribute to the DOM,
  12664. // such that background items cannot be selected
  12665. //dom.box['timeline-item'] = this;
  12666. this.dirty = true;
  12667. }
  12668. // append DOM to parent DOM
  12669. if (!this.parent) {
  12670. throw new Error('Cannot redraw item: no parent attached');
  12671. }
  12672. if (!dom.box.parentNode) {
  12673. var background = this.parent.dom.background;
  12674. if (!background) {
  12675. throw new Error('Cannot redraw item: parent has no background container element');
  12676. }
  12677. background.appendChild(dom.box);
  12678. }
  12679. this.displayed = true;
  12680. // Update DOM when item is marked dirty. An item is marked dirty when:
  12681. // - the item is not yet rendered
  12682. // - the item's data is changed
  12683. // - the item is selected/deselected
  12684. if (this.dirty) {
  12685. this._updateContents(this.dom.content);
  12686. this._updateTitle(this.dom.content);
  12687. this._updateDataAttributes(this.dom.content);
  12688. this._updateStyle(this.dom.box);
  12689. // update class
  12690. var className = (this.data.className ? (' ' + this.data.className) : '') +
  12691. (this.selected ? ' selected' : '');
  12692. dom.box.className = this.baseClassName + className;
  12693. // determine from css whether this box has overflow
  12694. this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden';
  12695. // recalculate size
  12696. this.props.content.width = this.dom.content.offsetWidth;
  12697. this.height = 0; // set height zero, so this item will be ignored when stacking items
  12698. this.dirty = false;
  12699. }
  12700. };
  12701. /**
  12702. * Show the item in the DOM (when not already visible). The items DOM will
  12703. * be created when needed.
  12704. */
  12705. BackgroundItem.prototype.show = RangeItem.prototype.show;
  12706. /**
  12707. * Hide the item from the DOM (when visible)
  12708. * @return {Boolean} changed
  12709. */
  12710. BackgroundItem.prototype.hide = RangeItem.prototype.hide;
  12711. /**
  12712. * Reposition the item horizontally
  12713. * @Override
  12714. */
  12715. BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX;
  12716. /**
  12717. * Reposition the item vertically
  12718. * @Override
  12719. */
  12720. BackgroundItem.prototype.repositionY = function(margin) {
  12721. var onTop = this.options.orientation === 'top';
  12722. this.dom.content.style.top = onTop ? '' : '0';
  12723. this.dom.content.style.bottom = onTop ? '0' : '';
  12724. var height;
  12725. // special positioning for subgroups
  12726. if (this.data.subgroup !== undefined) {
  12727. var itemSubgroup = this.data.subgroup;
  12728. var subgroups = this.parent.subgroups;
  12729. var subgroupIndex = subgroups[itemSubgroup].index;
  12730. // if the orientation is top, we need to take the difference in height into account.
  12731. if (onTop == true) {
  12732. // the first subgroup will have to account for the distance from the top to the first item.
  12733. height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical;
  12734. height += subgroupIndex == 0 ? margin.axis - 0.5*margin.item.vertical : 0;
  12735. var newTop = this.parent.top;
  12736. for (var subgroup in subgroups) {
  12737. if (subgroups.hasOwnProperty(subgroup)) {
  12738. if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroupIndex) {
  12739. newTop += subgroups[subgroup].height + margin.item.vertical;
  12740. }
  12741. }
  12742. }
  12743. // the others will have to be offset downwards with this same distance.
  12744. newTop += subgroupIndex != 0 ? margin.axis - 0.5 * margin.item.vertical : 0;
  12745. this.dom.box.style.top = newTop + 'px';
  12746. this.dom.box.style.bottom = '';
  12747. }
  12748. // and when the orientation is bottom:
  12749. else {
  12750. var newTop = this.parent.top;
  12751. for (var subgroup in subgroups) {
  12752. if (subgroups.hasOwnProperty(subgroup)) {
  12753. if (subgroups[subgroup].visible == true && subgroups[subgroup].index > subgroupIndex) {
  12754. newTop += subgroups[subgroup].height + margin.item.vertical;
  12755. }
  12756. }
  12757. }
  12758. height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical;
  12759. this.dom.box.style.top = newTop + 'px';
  12760. this.dom.box.style.bottom = '';
  12761. }
  12762. }
  12763. // and in the case of no subgroups:
  12764. else {
  12765. // we want backgrounds with groups to only show in groups.
  12766. if (this.parent instanceof BackgroundGroup) {
  12767. // if the item is not in a group:
  12768. height = Math.max(this.parent.height,
  12769. this.parent.itemSet.body.domProps.center.height,
  12770. this.parent.itemSet.body.domProps.centerContainer.height);
  12771. this.dom.box.style.top = onTop ? '0' : '';
  12772. this.dom.box.style.bottom = onTop ? '' : '0';
  12773. }
  12774. else {
  12775. height = this.parent.height;
  12776. // same alignment for items when orientation is top or bottom
  12777. this.dom.box.style.top = this.parent.top + 'px';
  12778. this.dom.box.style.bottom = '';
  12779. }
  12780. }
  12781. this.dom.box.style.height = height + 'px';
  12782. };
  12783. module.exports = BackgroundItem;
  12784. /***/ },
  12785. /* 33 */
  12786. /***/ function(module, exports, __webpack_require__) {
  12787. var Item = __webpack_require__(31);
  12788. var util = __webpack_require__(1);
  12789. /**
  12790. * @constructor BoxItem
  12791. * @extends Item
  12792. * @param {Object} data Object containing parameters start
  12793. * content, className.
  12794. * @param {{toScreen: function, toTime: function}} conversion
  12795. * Conversion functions from time to screen and vice versa
  12796. * @param {Object} [options] Configuration options
  12797. * // TODO: describe available options
  12798. */
  12799. function BoxItem (data, conversion, options) {
  12800. this.props = {
  12801. dot: {
  12802. width: 0,
  12803. height: 0
  12804. },
  12805. line: {
  12806. width: 0,
  12807. height: 0
  12808. }
  12809. };
  12810. // validate data
  12811. if (data) {
  12812. if (data.start == undefined) {
  12813. throw new Error('Property "start" missing in item ' + data);
  12814. }
  12815. }
  12816. Item.call(this, data, conversion, options);
  12817. }
  12818. BoxItem.prototype = new Item (null, null, null);
  12819. /**
  12820. * Check whether this item is visible inside given range
  12821. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  12822. * @returns {boolean} True if visible
  12823. */
  12824. BoxItem.prototype.isVisible = function(range) {
  12825. // determine visibility
  12826. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  12827. var interval = (range.end - range.start) / 4;
  12828. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  12829. };
  12830. /**
  12831. * Repaint the item
  12832. */
  12833. BoxItem.prototype.redraw = function() {
  12834. var dom = this.dom;
  12835. if (!dom) {
  12836. // create DOM
  12837. this.dom = {};
  12838. dom = this.dom;
  12839. // create main box
  12840. dom.box = document.createElement('DIV');
  12841. // contents box (inside the background box). used for making margins
  12842. dom.content = document.createElement('DIV');
  12843. dom.content.className = 'content';
  12844. dom.box.appendChild(dom.content);
  12845. // line to axis
  12846. dom.line = document.createElement('DIV');
  12847. dom.line.className = 'line';
  12848. // dot on axis
  12849. dom.dot = document.createElement('DIV');
  12850. dom.dot.className = 'dot';
  12851. // attach this item as attribute
  12852. dom.box['timeline-item'] = this;
  12853. this.dirty = true;
  12854. }
  12855. // append DOM to parent DOM
  12856. if (!this.parent) {
  12857. throw new Error('Cannot redraw item: no parent attached');
  12858. }
  12859. if (!dom.box.parentNode) {
  12860. var foreground = this.parent.dom.foreground;
  12861. if (!foreground) throw new Error('Cannot redraw item: parent has no foreground container element');
  12862. foreground.appendChild(dom.box);
  12863. }
  12864. if (!dom.line.parentNode) {
  12865. var background = this.parent.dom.background;
  12866. if (!background) throw new Error('Cannot redraw item: parent has no background container element');
  12867. background.appendChild(dom.line);
  12868. }
  12869. if (!dom.dot.parentNode) {
  12870. var axis = this.parent.dom.axis;
  12871. if (!background) throw new Error('Cannot redraw item: parent has no axis container element');
  12872. axis.appendChild(dom.dot);
  12873. }
  12874. this.displayed = true;
  12875. // Update DOM when item is marked dirty. An item is marked dirty when:
  12876. // - the item is not yet rendered
  12877. // - the item's data is changed
  12878. // - the item is selected/deselected
  12879. if (this.dirty) {
  12880. this._updateContents(this.dom.content);
  12881. this._updateTitle(this.dom.box);
  12882. this._updateDataAttributes(this.dom.box);
  12883. this._updateStyle(this.dom.box);
  12884. // update class
  12885. var className = (this.data.className? ' ' + this.data.className : '') +
  12886. (this.selected ? ' selected' : '');
  12887. dom.box.className = 'item box' + className;
  12888. dom.line.className = 'item line' + className;
  12889. dom.dot.className = 'item dot' + className;
  12890. // recalculate size
  12891. this.props.dot.height = dom.dot.offsetHeight;
  12892. this.props.dot.width = dom.dot.offsetWidth;
  12893. this.props.line.width = dom.line.offsetWidth;
  12894. this.width = dom.box.offsetWidth;
  12895. this.height = dom.box.offsetHeight;
  12896. this.dirty = false;
  12897. }
  12898. this._repaintDeleteButton(dom.box);
  12899. };
  12900. /**
  12901. * Show the item in the DOM (when not already displayed). The items DOM will
  12902. * be created when needed.
  12903. */
  12904. BoxItem.prototype.show = function() {
  12905. if (!this.displayed) {
  12906. this.redraw();
  12907. }
  12908. };
  12909. /**
  12910. * Hide the item from the DOM (when visible)
  12911. */
  12912. BoxItem.prototype.hide = function() {
  12913. if (this.displayed) {
  12914. var dom = this.dom;
  12915. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  12916. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  12917. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  12918. this.top = null;
  12919. this.left = null;
  12920. this.displayed = false;
  12921. }
  12922. };
  12923. /**
  12924. * Reposition the item horizontally
  12925. * @Override
  12926. */
  12927. BoxItem.prototype.repositionX = function() {
  12928. var start = this.conversion.toScreen(this.data.start);
  12929. var align = this.options.align;
  12930. var left;
  12931. var box = this.dom.box;
  12932. var line = this.dom.line;
  12933. var dot = this.dom.dot;
  12934. // calculate left position of the box
  12935. if (align == 'right') {
  12936. this.left = start - this.width;
  12937. }
  12938. else if (align == 'left') {
  12939. this.left = start;
  12940. }
  12941. else {
  12942. // default or 'center'
  12943. this.left = start - this.width / 2;
  12944. }
  12945. // reposition box
  12946. box.style.left = this.left + 'px';
  12947. // reposition line
  12948. line.style.left = (start - this.props.line.width / 2) + 'px';
  12949. // reposition dot
  12950. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  12951. };
  12952. /**
  12953. * Reposition the item vertically
  12954. * @Override
  12955. */
  12956. BoxItem.prototype.repositionY = function() {
  12957. var orientation = this.options.orientation;
  12958. var box = this.dom.box;
  12959. var line = this.dom.line;
  12960. var dot = this.dom.dot;
  12961. if (orientation == 'top') {
  12962. box.style.top = (this.top || 0) + 'px';
  12963. line.style.top = '0';
  12964. line.style.height = (this.parent.top + this.top + 1) + 'px';
  12965. line.style.bottom = '';
  12966. }
  12967. else { // orientation 'bottom'
  12968. var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty
  12969. var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top;
  12970. box.style.top = (this.parent.height - this.top - this.height || 0) + 'px';
  12971. line.style.top = (itemSetHeight - lineHeight) + 'px';
  12972. line.style.bottom = '0';
  12973. }
  12974. dot.style.top = (-this.props.dot.height / 2) + 'px';
  12975. };
  12976. module.exports = BoxItem;
  12977. /***/ },
  12978. /* 34 */
  12979. /***/ function(module, exports, __webpack_require__) {
  12980. var Item = __webpack_require__(31);
  12981. /**
  12982. * @constructor PointItem
  12983. * @extends Item
  12984. * @param {Object} data Object containing parameters start
  12985. * content, className.
  12986. * @param {{toScreen: function, toTime: function}} conversion
  12987. * Conversion functions from time to screen and vice versa
  12988. * @param {Object} [options] Configuration options
  12989. * // TODO: describe available options
  12990. */
  12991. function PointItem (data, conversion, options) {
  12992. this.props = {
  12993. dot: {
  12994. top: 0,
  12995. width: 0,
  12996. height: 0
  12997. },
  12998. content: {
  12999. height: 0,
  13000. marginLeft: 0
  13001. }
  13002. };
  13003. // validate data
  13004. if (data) {
  13005. if (data.start == undefined) {
  13006. throw new Error('Property "start" missing in item ' + data);
  13007. }
  13008. }
  13009. Item.call(this, data, conversion, options);
  13010. }
  13011. PointItem.prototype = new Item (null, null, null);
  13012. /**
  13013. * Check whether this item is visible inside given range
  13014. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  13015. * @returns {boolean} True if visible
  13016. */
  13017. PointItem.prototype.isVisible = function(range) {
  13018. // determine visibility
  13019. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  13020. var interval = (range.end - range.start) / 4;
  13021. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  13022. };
  13023. /**
  13024. * Repaint the item
  13025. */
  13026. PointItem.prototype.redraw = function() {
  13027. var dom = this.dom;
  13028. if (!dom) {
  13029. // create DOM
  13030. this.dom = {};
  13031. dom = this.dom;
  13032. // background box
  13033. dom.point = document.createElement('div');
  13034. // className is updated in redraw()
  13035. // contents box, right from the dot
  13036. dom.content = document.createElement('div');
  13037. dom.content.className = 'content';
  13038. dom.point.appendChild(dom.content);
  13039. // dot at start
  13040. dom.dot = document.createElement('div');
  13041. dom.point.appendChild(dom.dot);
  13042. // attach this item as attribute
  13043. dom.point['timeline-item'] = this;
  13044. this.dirty = true;
  13045. }
  13046. // append DOM to parent DOM
  13047. if (!this.parent) {
  13048. throw new Error('Cannot redraw item: no parent attached');
  13049. }
  13050. if (!dom.point.parentNode) {
  13051. var foreground = this.parent.dom.foreground;
  13052. if (!foreground) {
  13053. throw new Error('Cannot redraw item: parent has no foreground container element');
  13054. }
  13055. foreground.appendChild(dom.point);
  13056. }
  13057. this.displayed = true;
  13058. // Update DOM when item is marked dirty. An item is marked dirty when:
  13059. // - the item is not yet rendered
  13060. // - the item's data is changed
  13061. // - the item is selected/deselected
  13062. if (this.dirty) {
  13063. this._updateContents(this.dom.content);
  13064. this._updateTitle(this.dom.point);
  13065. this._updateDataAttributes(this.dom.point);
  13066. this._updateStyle(this.dom.point);
  13067. // update class
  13068. var className = (this.data.className? ' ' + this.data.className : '') +
  13069. (this.selected ? ' selected' : '');
  13070. dom.point.className = 'item point' + className;
  13071. dom.dot.className = 'item dot' + className;
  13072. // recalculate size
  13073. this.width = dom.point.offsetWidth;
  13074. this.height = dom.point.offsetHeight;
  13075. this.props.dot.width = dom.dot.offsetWidth;
  13076. this.props.dot.height = dom.dot.offsetHeight;
  13077. this.props.content.height = dom.content.offsetHeight;
  13078. // resize contents
  13079. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  13080. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  13081. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  13082. dom.dot.style.left = (this.props.dot.width / 2) + 'px';
  13083. this.dirty = false;
  13084. }
  13085. this._repaintDeleteButton(dom.point);
  13086. };
  13087. /**
  13088. * Show the item in the DOM (when not already visible). The items DOM will
  13089. * be created when needed.
  13090. */
  13091. PointItem.prototype.show = function() {
  13092. if (!this.displayed) {
  13093. this.redraw();
  13094. }
  13095. };
  13096. /**
  13097. * Hide the item from the DOM (when visible)
  13098. */
  13099. PointItem.prototype.hide = function() {
  13100. if (this.displayed) {
  13101. if (this.dom.point.parentNode) {
  13102. this.dom.point.parentNode.removeChild(this.dom.point);
  13103. }
  13104. this.top = null;
  13105. this.left = null;
  13106. this.displayed = false;
  13107. }
  13108. };
  13109. /**
  13110. * Reposition the item horizontally
  13111. * @Override
  13112. */
  13113. PointItem.prototype.repositionX = function() {
  13114. var start = this.conversion.toScreen(this.data.start);
  13115. this.left = start - this.props.dot.width;
  13116. // reposition point
  13117. this.dom.point.style.left = this.left + 'px';
  13118. };
  13119. /**
  13120. * Reposition the item vertically
  13121. * @Override
  13122. */
  13123. PointItem.prototype.repositionY = function() {
  13124. var orientation = this.options.orientation,
  13125. point = this.dom.point;
  13126. if (orientation == 'top') {
  13127. point.style.top = this.top + 'px';
  13128. }
  13129. else {
  13130. point.style.top = (this.parent.height - this.top - this.height) + 'px';
  13131. }
  13132. };
  13133. module.exports = PointItem;
  13134. /***/ },
  13135. /* 35 */
  13136. /***/ function(module, exports, __webpack_require__) {
  13137. var Hammer = __webpack_require__(45);
  13138. var Item = __webpack_require__(31);
  13139. /**
  13140. * @constructor RangeItem
  13141. * @extends Item
  13142. * @param {Object} data Object containing parameters start, end
  13143. * content, className.
  13144. * @param {{toScreen: function, toTime: function}} conversion
  13145. * Conversion functions from time to screen and vice versa
  13146. * @param {Object} [options] Configuration options
  13147. * // TODO: describe options
  13148. */
  13149. function RangeItem (data, conversion, options) {
  13150. this.props = {
  13151. content: {
  13152. width: 0
  13153. }
  13154. };
  13155. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  13156. // validate data
  13157. if (data) {
  13158. if (data.start == undefined) {
  13159. throw new Error('Property "start" missing in item ' + data.id);
  13160. }
  13161. if (data.end == undefined) {
  13162. throw new Error('Property "end" missing in item ' + data.id);
  13163. }
  13164. }
  13165. Item.call(this, data, conversion, options);
  13166. }
  13167. RangeItem.prototype = new Item (null, null, null);
  13168. RangeItem.prototype.baseClassName = 'item range';
  13169. /**
  13170. * Check whether this item is visible inside given range
  13171. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  13172. * @returns {boolean} True if visible
  13173. */
  13174. RangeItem.prototype.isVisible = function(range) {
  13175. // determine visibility
  13176. return (this.data.start < range.end) && (this.data.end > range.start);
  13177. };
  13178. /**
  13179. * Repaint the item
  13180. */
  13181. RangeItem.prototype.redraw = function() {
  13182. var dom = this.dom;
  13183. if (!dom) {
  13184. // create DOM
  13185. this.dom = {};
  13186. dom = this.dom;
  13187. // background box
  13188. dom.box = document.createElement('div');
  13189. // className is updated in redraw()
  13190. // contents box
  13191. dom.content = document.createElement('div');
  13192. dom.content.className = 'content';
  13193. dom.box.appendChild(dom.content);
  13194. // attach this item as attribute
  13195. dom.box['timeline-item'] = this;
  13196. this.dirty = true;
  13197. }
  13198. // append DOM to parent DOM
  13199. if (!this.parent) {
  13200. throw new Error('Cannot redraw item: no parent attached');
  13201. }
  13202. if (!dom.box.parentNode) {
  13203. var foreground = this.parent.dom.foreground;
  13204. if (!foreground) {
  13205. throw new Error('Cannot redraw item: parent has no foreground container element');
  13206. }
  13207. foreground.appendChild(dom.box);
  13208. }
  13209. this.displayed = true;
  13210. // Update DOM when item is marked dirty. An item is marked dirty when:
  13211. // - the item is not yet rendered
  13212. // - the item's data is changed
  13213. // - the item is selected/deselected
  13214. if (this.dirty) {
  13215. this._updateContents(this.dom.content);
  13216. this._updateTitle(this.dom.box);
  13217. this._updateDataAttributes(this.dom.box);
  13218. this._updateStyle(this.dom.box);
  13219. // update class
  13220. var className = (this.data.className ? (' ' + this.data.className) : '') +
  13221. (this.selected ? ' selected' : '');
  13222. dom.box.className = this.baseClassName + className;
  13223. // determine from css whether this box has overflow
  13224. this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden';
  13225. // recalculate size
  13226. // turn off max-width to be able to calculate the real width
  13227. // this causes an extra browser repaint/reflow, but so be it
  13228. this.dom.content.style.maxWidth = 'none';
  13229. this.props.content.width = this.dom.content.offsetWidth;
  13230. this.height = this.dom.box.offsetHeight;
  13231. this.dom.content.style.maxWidth = '';
  13232. this.dirty = false;
  13233. }
  13234. this._repaintDeleteButton(dom.box);
  13235. this._repaintDragLeft();
  13236. this._repaintDragRight();
  13237. };
  13238. /**
  13239. * Show the item in the DOM (when not already visible). The items DOM will
  13240. * be created when needed.
  13241. */
  13242. RangeItem.prototype.show = function() {
  13243. if (!this.displayed) {
  13244. this.redraw();
  13245. }
  13246. };
  13247. /**
  13248. * Hide the item from the DOM (when visible)
  13249. * @return {Boolean} changed
  13250. */
  13251. RangeItem.prototype.hide = function() {
  13252. if (this.displayed) {
  13253. var box = this.dom.box;
  13254. if (box.parentNode) {
  13255. box.parentNode.removeChild(box);
  13256. }
  13257. this.top = null;
  13258. this.left = null;
  13259. this.displayed = false;
  13260. }
  13261. };
  13262. /**
  13263. * Reposition the item horizontally
  13264. * @Override
  13265. */
  13266. RangeItem.prototype.repositionX = function() {
  13267. var parentWidth = this.parent.width;
  13268. var start = this.conversion.toScreen(this.data.start);
  13269. var end = this.conversion.toScreen(this.data.end);
  13270. var contentLeft;
  13271. var contentWidth;
  13272. // limit the width of the this, as browsers cannot draw very wide divs
  13273. if (start < -parentWidth) {
  13274. start = -parentWidth;
  13275. }
  13276. if (end > 2 * parentWidth) {
  13277. end = 2 * parentWidth;
  13278. }
  13279. var boxWidth = Math.max(end - start, 1);
  13280. if (this.overflow) {
  13281. this.left = start;
  13282. this.width = boxWidth + this.props.content.width;
  13283. contentWidth = this.props.content.width;
  13284. // Note: The calculation of width is an optimistic calculation, giving
  13285. // a width which will not change when moving the Timeline
  13286. // So no re-stacking needed, which is nicer for the eye;
  13287. }
  13288. else {
  13289. this.left = start;
  13290. this.width = boxWidth;
  13291. contentWidth = Math.min(end - start - 2 * this.options.padding, this.props.content.width);
  13292. }
  13293. this.dom.box.style.left = this.left + 'px';
  13294. this.dom.box.style.width = boxWidth + 'px';
  13295. switch (this.options.align) {
  13296. case 'left':
  13297. this.dom.content.style.left = '0';
  13298. break;
  13299. case 'right':
  13300. this.dom.content.style.left = Math.max((boxWidth - contentWidth - 2 * this.options.padding), 0) + 'px';
  13301. break;
  13302. case 'center':
  13303. this.dom.content.style.left = Math.max((boxWidth - contentWidth - 2 * this.options.padding) / 2, 0) + 'px';
  13304. break;
  13305. default: // 'auto'
  13306. // when range exceeds left of the window, position the contents at the left of the visible area
  13307. if (this.overflow) {
  13308. if (end > 0) {
  13309. contentLeft = Math.max(-start, 0);
  13310. }
  13311. else {
  13312. contentLeft = -contentWidth; // ensure it's not visible anymore
  13313. }
  13314. }
  13315. else {
  13316. if (start < 0) {
  13317. contentLeft = Math.min(-start,
  13318. (end - start - contentWidth - 2 * this.options.padding));
  13319. // TODO: remove the need for options.padding. it's terrible.
  13320. }
  13321. else {
  13322. contentLeft = 0;
  13323. }
  13324. }
  13325. this.dom.content.style.left = contentLeft + 'px';
  13326. }
  13327. };
  13328. /**
  13329. * Reposition the item vertically
  13330. * @Override
  13331. */
  13332. RangeItem.prototype.repositionY = function() {
  13333. var orientation = this.options.orientation,
  13334. box = this.dom.box;
  13335. if (orientation == 'top') {
  13336. box.style.top = this.top + 'px';
  13337. }
  13338. else {
  13339. box.style.top = (this.parent.height - this.top - this.height) + 'px';
  13340. }
  13341. };
  13342. /**
  13343. * Repaint a drag area on the left side of the range when the range is selected
  13344. * @protected
  13345. */
  13346. RangeItem.prototype._repaintDragLeft = function () {
  13347. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  13348. // create and show drag area
  13349. var dragLeft = document.createElement('div');
  13350. dragLeft.className = 'drag-left';
  13351. dragLeft.dragLeftItem = this;
  13352. // TODO: this should be redundant?
  13353. Hammer(dragLeft, {
  13354. preventDefault: true
  13355. }).on('drag', function () {
  13356. //console.log('drag left')
  13357. });
  13358. this.dom.box.appendChild(dragLeft);
  13359. this.dom.dragLeft = dragLeft;
  13360. }
  13361. else if (!this.selected && this.dom.dragLeft) {
  13362. // delete drag area
  13363. if (this.dom.dragLeft.parentNode) {
  13364. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  13365. }
  13366. this.dom.dragLeft = null;
  13367. }
  13368. };
  13369. /**
  13370. * Repaint a drag area on the right side of the range when the range is selected
  13371. * @protected
  13372. */
  13373. RangeItem.prototype._repaintDragRight = function () {
  13374. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  13375. // create and show drag area
  13376. var dragRight = document.createElement('div');
  13377. dragRight.className = 'drag-right';
  13378. dragRight.dragRightItem = this;
  13379. // TODO: this should be redundant?
  13380. Hammer(dragRight, {
  13381. preventDefault: true
  13382. }).on('drag', function () {
  13383. //console.log('drag right')
  13384. });
  13385. this.dom.box.appendChild(dragRight);
  13386. this.dom.dragRight = dragRight;
  13387. }
  13388. else if (!this.selected && this.dom.dragRight) {
  13389. // delete drag area
  13390. if (this.dom.dragRight.parentNode) {
  13391. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  13392. }
  13393. this.dom.dragRight = null;
  13394. }
  13395. };
  13396. module.exports = RangeItem;
  13397. /***/ },
  13398. /* 36 */
  13399. /***/ function(module, exports, __webpack_require__) {
  13400. var Emitter = __webpack_require__(56);
  13401. var Hammer = __webpack_require__(45);
  13402. var keycharm = __webpack_require__(57);
  13403. var util = __webpack_require__(1);
  13404. var hammerUtil = __webpack_require__(47);
  13405. var DataSet = __webpack_require__(3);
  13406. var DataView = __webpack_require__(4);
  13407. var dotparser = __webpack_require__(42);
  13408. var gephiParser = __webpack_require__(43);
  13409. var Groups = __webpack_require__(38);
  13410. var Images = __webpack_require__(39);
  13411. var Node = __webpack_require__(40);
  13412. var Edge = __webpack_require__(37);
  13413. var Popup = __webpack_require__(41);
  13414. var MixinLoader = __webpack_require__(54);
  13415. var Activator = __webpack_require__(55);
  13416. var locales = __webpack_require__(49);
  13417. // Load custom shapes into CanvasRenderingContext2D
  13418. __webpack_require__(50);
  13419. /**
  13420. * @constructor Network
  13421. * Create a network visualization, displaying nodes and edges.
  13422. *
  13423. * @param {Element} container The DOM element in which the Network will
  13424. * be created. Normally a div element.
  13425. * @param {Object} data An object containing parameters
  13426. * {Array} nodes
  13427. * {Array} edges
  13428. * @param {Object} options Options
  13429. */
  13430. function Network (container, data, options) {
  13431. if (!(this instanceof Network)) {
  13432. throw new SyntaxError('Constructor must be called with the new operator');
  13433. }
  13434. this._determineBrowserMethod();
  13435. this._initializeMixinLoaders();
  13436. // create variables and set default values
  13437. this.containerElement = container;
  13438. // render and calculation settings
  13439. this.renderRefreshRate = 60; // hz (fps)
  13440. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13441. this.renderTime = 0; // measured time it takes to render a frame
  13442. this.physicsTime = 0; // measured time it takes to render a frame
  13443. this.runDoubleSpeed = false;
  13444. this.physicsDiscreteStepsize = 0.50; // discrete stepsize of the simulation
  13445. this.initializing = true;
  13446. this.triggerFunctions = {add:null,edit:null,editEdge:null,connect:null,del:null};
  13447. // set constant values
  13448. this.defaultOptions = {
  13449. nodes: {
  13450. mass: 1,
  13451. radiusMin: 10,
  13452. radiusMax: 30,
  13453. radius: 10,
  13454. shape: 'ellipse',
  13455. image: undefined,
  13456. widthMin: 16, // px
  13457. widthMax: 64, // px
  13458. fontColor: 'black',
  13459. fontSize: 14, // px
  13460. fontFace: 'verdana',
  13461. fontFill: undefined,
  13462. level: -1,
  13463. color: {
  13464. border: '#2B7CE9',
  13465. background: '#97C2FC',
  13466. highlight: {
  13467. border: '#2B7CE9',
  13468. background: '#D2E5FF'
  13469. },
  13470. hover: {
  13471. border: '#2B7CE9',
  13472. background: '#D2E5FF'
  13473. }
  13474. },
  13475. group: undefined,
  13476. borderWidth: 1,
  13477. borderWidthSelected: undefined
  13478. },
  13479. edges: {
  13480. widthMin: 1, //
  13481. widthMax: 15,//
  13482. width: 1,
  13483. widthSelectionMultiplier: 2,
  13484. hoverWidth: 1.5,
  13485. style: 'line',
  13486. color: {
  13487. color:'#848484',
  13488. highlight:'#848484',
  13489. hover: '#848484'
  13490. },
  13491. fontColor: '#343434',
  13492. fontSize: 14, // px
  13493. fontFace: 'arial',
  13494. fontFill: 'white',
  13495. arrowScaleFactor: 1,
  13496. dash: {
  13497. length: 10,
  13498. gap: 5,
  13499. altLength: undefined
  13500. },
  13501. inheritColor: "from" // to, from, false, true (== from)
  13502. },
  13503. configurePhysics:false,
  13504. physics: {
  13505. barnesHut: {
  13506. enabled: true,
  13507. thetaInverted: 1 / 0.5, // inverted to save time during calculation
  13508. gravitationalConstant: -2000,
  13509. centralGravity: 0.3,
  13510. springLength: 95,
  13511. springConstant: 0.04,
  13512. damping: 0.09
  13513. },
  13514. repulsion: {
  13515. centralGravity: 0.0,
  13516. springLength: 200,
  13517. springConstant: 0.05,
  13518. nodeDistance: 100,
  13519. damping: 0.09
  13520. },
  13521. hierarchicalRepulsion: {
  13522. enabled: false,
  13523. centralGravity: 0.0,
  13524. springLength: 100,
  13525. springConstant: 0.01,
  13526. nodeDistance: 150,
  13527. damping: 0.09
  13528. },
  13529. damping: null,
  13530. centralGravity: null,
  13531. springLength: null,
  13532. springConstant: null
  13533. },
  13534. clustering: { // Per Node in Cluster = PNiC
  13535. enabled: false, // (Boolean) | global on/off switch for clustering.
  13536. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13537. 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
  13538. 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
  13539. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13540. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13541. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13542. 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.
  13543. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13544. maxFontSize: 1000,
  13545. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13546. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13547. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13548. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13549. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13550. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13551. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13552. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13553. clusterLevelDifference: 2
  13554. },
  13555. navigation: {
  13556. enabled: false
  13557. },
  13558. keyboard: {
  13559. enabled: false,
  13560. speed: {x: 10, y: 10, zoom: 0.02}
  13561. },
  13562. dataManipulation: {
  13563. enabled: false,
  13564. initiallyVisible: false
  13565. },
  13566. hierarchicalLayout: {
  13567. enabled:false,
  13568. levelSeparation: 150,
  13569. nodeSpacing: 100,
  13570. direction: "UD", // UD, DU, LR, RL
  13571. layout: "hubsize" // hubsize, directed
  13572. },
  13573. freezeForStabilization: false,
  13574. smoothCurves: {
  13575. enabled: true,
  13576. dynamic: true,
  13577. type: "continuous",
  13578. roundness: 0.5
  13579. },
  13580. maxVelocity: 30,
  13581. minVelocity: 0.1, // px/s
  13582. stabilize: true, // stabilize before displaying the network
  13583. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  13584. zoomExtentOnStabilize: true,
  13585. locale: 'en',
  13586. locales: locales,
  13587. tooltip: {
  13588. delay: 300,
  13589. fontColor: 'black',
  13590. fontSize: 14, // px
  13591. fontFace: 'verdana',
  13592. color: {
  13593. border: '#666',
  13594. background: '#FFFFC6'
  13595. }
  13596. },
  13597. dragNetwork: true,
  13598. dragNodes: true,
  13599. zoomable: true,
  13600. hover: false,
  13601. hideEdgesOnDrag: false,
  13602. hideNodesOnDrag: false,
  13603. width : '100%',
  13604. height : '100%',
  13605. selectable: true
  13606. };
  13607. this.constants = util.extend({}, this.defaultOptions);
  13608. this.pixelRatio = 1;
  13609. this.hoverObj = {nodes:{},edges:{}};
  13610. this.controlNodesActive = false;
  13611. this.navigationHammers = {existing:[], _new: []};
  13612. // animation properties
  13613. this.animationSpeed = 1/this.renderRefreshRate;
  13614. this.animationEasingFunction = "easeInOutQuint";
  13615. this.easingTime = 0;
  13616. this.sourceScale = 0;
  13617. this.targetScale = 0;
  13618. this.sourceTranslation = 0;
  13619. this.targetTranslation = 0;
  13620. this.lockedOnNodeId = null;
  13621. this.lockedOnNodeOffset = null;
  13622. this.touchTime = 0;
  13623. // Node variables
  13624. var network = this;
  13625. this.groups = new Groups(); // object with groups
  13626. this.images = new Images(); // object with images
  13627. this.images.setOnloadCallback(function (status) {
  13628. network._redraw();
  13629. });
  13630. // keyboard navigation variables
  13631. this.xIncrement = 0;
  13632. this.yIncrement = 0;
  13633. this.zoomIncrement = 0;
  13634. // loading all the mixins:
  13635. // load the force calculation functions, grouped under the physics system.
  13636. this._loadPhysicsSystem();
  13637. // create a frame and canvas
  13638. this._create();
  13639. // load the sector system. (mandatory, fully integrated with Network)
  13640. this._loadSectorSystem();
  13641. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13642. this._loadClusterSystem();
  13643. // load the selection system. (mandatory, required by Network)
  13644. this._loadSelectionSystem();
  13645. // load the selection system. (mandatory, required by Network)
  13646. this._loadHierarchySystem();
  13647. // apply options
  13648. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  13649. this._setScale(1);
  13650. this.setOptions(options);
  13651. // other vars
  13652. this.freezeSimulation = false;// freeze the simulation
  13653. this.cachedFunctions = {};
  13654. this.startedStabilization = false;
  13655. this.stabilized = false;
  13656. this.stabilizationIterations = null;
  13657. this.draggingNodes = false;
  13658. // containers for nodes and edges
  13659. this.calculationNodes = {};
  13660. this.calculationNodeIndices = [];
  13661. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13662. this.nodes = {}; // object with Node objects
  13663. this.edges = {}; // object with Edge objects
  13664. // position and scale variables and objects
  13665. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13666. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13667. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13668. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13669. this.scale = 1; // defining the global scale variable in the constructor
  13670. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13671. // datasets or dataviews
  13672. this.nodesData = null; // A DataSet or DataView
  13673. this.edgesData = null; // A DataSet or DataView
  13674. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13675. this.nodesListeners = {
  13676. 'add': function (event, params) {
  13677. network._addNodes(params.items);
  13678. network.start();
  13679. },
  13680. 'update': function (event, params) {
  13681. network._updateNodes(params.items, params.data);
  13682. network.start();
  13683. },
  13684. 'remove': function (event, params) {
  13685. network._removeNodes(params.items);
  13686. network.start();
  13687. }
  13688. };
  13689. this.edgesListeners = {
  13690. 'add': function (event, params) {
  13691. network._addEdges(params.items);
  13692. network.start();
  13693. },
  13694. 'update': function (event, params) {
  13695. network._updateEdges(params.items);
  13696. network.start();
  13697. },
  13698. 'remove': function (event, params) {
  13699. network._removeEdges(params.items);
  13700. network.start();
  13701. }
  13702. };
  13703. // properties for the animation
  13704. this.moving = true;
  13705. this.timer = undefined; // Scheduling function. Is definded in this.start();
  13706. // load data (the disable start variable will be the same as the enabled clustering)
  13707. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  13708. // hierarchical layout
  13709. this.initializing = false;
  13710. if (this.constants.hierarchicalLayout.enabled == true) {
  13711. this._setupHierarchicalLayout();
  13712. }
  13713. else {
  13714. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  13715. if (this.constants.stabilize == false) {
  13716. this.zoomExtent(undefined, true,this.constants.clustering.enabled);
  13717. }
  13718. }
  13719. // if clustering is disabled, the simulation will have started in the setData function
  13720. if (this.constants.clustering.enabled) {
  13721. this.startWithClustering();
  13722. }
  13723. }
  13724. // Extend Network with an Emitter mixin
  13725. Emitter(Network.prototype);
  13726. /**
  13727. * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because
  13728. * some implementations (safari and IE9) did not support requestAnimationFrame
  13729. * @private
  13730. */
  13731. Network.prototype._determineBrowserMethod = function() {
  13732. var browserType = navigator.userAgent.toLowerCase();
  13733. this.requiresTimeout = false;
  13734. if (browserType.indexOf('msie 9.0') != -1) { // IE 9
  13735. this.requiresTimeout = true;
  13736. }
  13737. else if (browserType.indexOf('safari') != -1) { // safari
  13738. if (browserType.indexOf('chrome') <= -1) {
  13739. this.requiresTimeout = true;
  13740. }
  13741. }
  13742. }
  13743. /**
  13744. * Get the script path where the vis.js library is located
  13745. *
  13746. * @returns {string | null} path Path or null when not found. Path does not
  13747. * end with a slash.
  13748. * @private
  13749. */
  13750. Network.prototype._getScriptPath = function() {
  13751. var scripts = document.getElementsByTagName( 'script' );
  13752. // find script named vis.js or vis.min.js
  13753. for (var i = 0; i < scripts.length; i++) {
  13754. var src = scripts[i].src;
  13755. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  13756. if (match) {
  13757. // return path without the script name
  13758. return src.substring(0, src.length - match[0].length);
  13759. }
  13760. }
  13761. return null;
  13762. };
  13763. /**
  13764. * Find the center position of the network
  13765. * @private
  13766. */
  13767. Network.prototype._getRange = function() {
  13768. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  13769. for (var nodeId in this.nodes) {
  13770. if (this.nodes.hasOwnProperty(nodeId)) {
  13771. node = this.nodes[nodeId];
  13772. if (minX > (node.boundingBox.left)) {minX = node.boundingBox.left;}
  13773. if (maxX < (node.boundingBox.right)) {maxX = node.boundingBox.right;}
  13774. if (minY > (node.boundingBox.bottom)) {minY = node.boundingBox.bottom;}
  13775. if (maxY < (node.boundingBox.top)) {maxY = node.boundingBox.top;}
  13776. }
  13777. }
  13778. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  13779. minY = 0, maxY = 0, minX = 0, maxX = 0;
  13780. }
  13781. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13782. };
  13783. /**
  13784. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13785. * @returns {{x: number, y: number}}
  13786. * @private
  13787. */
  13788. Network.prototype._findCenter = function(range) {
  13789. return {x: (0.5 * (range.maxX + range.minX)),
  13790. y: (0.5 * (range.maxY + range.minY))};
  13791. };
  13792. /**
  13793. * This function zooms out to fit all data on screen based on amount of nodes
  13794. *
  13795. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  13796. * @param {Boolean} [disableStart] | If true, start is not called.
  13797. */
  13798. Network.prototype.zoomExtent = function(animationOptions, initialZoom, disableStart) {
  13799. this._redraw(true);
  13800. if (initialZoom === undefined) {
  13801. initialZoom = false;
  13802. }
  13803. if (disableStart === undefined) {
  13804. disableStart = false;
  13805. }
  13806. if (animationOptions === undefined) {
  13807. animationOptions = false;
  13808. }
  13809. var range = this._getRange();
  13810. var zoomLevel;
  13811. if (initialZoom == true) {
  13812. var numberOfNodes = this.nodeIndices.length;
  13813. if (this.constants.smoothCurves == true) {
  13814. if (this.constants.clustering.enabled == true &&
  13815. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13816. 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.
  13817. }
  13818. else {
  13819. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13820. }
  13821. }
  13822. else {
  13823. if (this.constants.clustering.enabled == true &&
  13824. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13825. 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.
  13826. }
  13827. else {
  13828. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13829. }
  13830. }
  13831. // correct for larger canvasses.
  13832. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  13833. zoomLevel *= factor;
  13834. }
  13835. else {
  13836. var xDistance = Math.abs(range.maxX - range.minX) * 1.1;
  13837. var yDistance = Math.abs(range.maxY - range.minY) * 1.1;
  13838. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  13839. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  13840. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  13841. }
  13842. if (zoomLevel > 1.0) {
  13843. zoomLevel = 1.0;
  13844. }
  13845. var center = this._findCenter(range);
  13846. if (disableStart == false) {
  13847. var options = {position: center, scale: zoomLevel, animation: animationOptions};
  13848. this.moveTo(options);
  13849. this.moving = true;
  13850. this.start();
  13851. }
  13852. else {
  13853. center.x *= zoomLevel;
  13854. center.y *= zoomLevel;
  13855. center.x -= 0.5 * this.frame.canvas.clientWidth;
  13856. center.y -= 0.5 * this.frame.canvas.clientHeight;
  13857. this._setScale(zoomLevel);
  13858. this._setTranslation(-center.x,-center.y);
  13859. }
  13860. };
  13861. /**
  13862. * Update the this.nodeIndices with the most recent node index list
  13863. * @private
  13864. */
  13865. Network.prototype._updateNodeIndexList = function() {
  13866. this._clearNodeIndexList();
  13867. for (var idx in this.nodes) {
  13868. if (this.nodes.hasOwnProperty(idx)) {
  13869. this.nodeIndices.push(idx);
  13870. }
  13871. }
  13872. };
  13873. /**
  13874. * Set nodes and edges, and optionally options as well.
  13875. *
  13876. * @param {Object} data Object containing parameters:
  13877. * {Array | DataSet | DataView} [nodes] Array with nodes
  13878. * {Array | DataSet | DataView} [edges] Array with edges
  13879. * {String} [dot] String containing data in DOT format
  13880. * {String} [gephi] String containing data in gephi JSON format
  13881. * {Options} [options] Object with options
  13882. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  13883. */
  13884. Network.prototype.setData = function(data, disableStart) {
  13885. if (disableStart === undefined) {
  13886. disableStart = false;
  13887. }
  13888. // we set initializing to true to ensure that the hierarchical layout is not performed until both nodes and edges are added.
  13889. this.initializing = true;
  13890. if (data && data.dot && (data.nodes || data.edges)) {
  13891. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  13892. ' parameter pair "nodes" and "edges", but not both.');
  13893. }
  13894. // set options
  13895. this.setOptions(data && data.options);
  13896. // set all data
  13897. if (data && data.dot) {
  13898. // parse DOT file
  13899. if(data && data.dot) {
  13900. var dotData = dotparser.DOTToGraph(data.dot);
  13901. this.setData(dotData);
  13902. return;
  13903. }
  13904. }
  13905. else if (data && data.gephi) {
  13906. // parse DOT file
  13907. if(data && data.gephi) {
  13908. var gephiData = gephiParser.parseGephi(data.gephi);
  13909. this.setData(gephiData);
  13910. return;
  13911. }
  13912. }
  13913. else {
  13914. this._setNodes(data && data.nodes);
  13915. this._setEdges(data && data.edges);
  13916. }
  13917. this._putDataInSector();
  13918. if (disableStart == false) {
  13919. if (this.constants.hierarchicalLayout.enabled == true) {
  13920. this._resetLevels();
  13921. this._setupHierarchicalLayout();
  13922. }
  13923. else {
  13924. // find a stable position or start animating to a stable position
  13925. if (this.constants.stabilize) {
  13926. this._stabilize();
  13927. }
  13928. }
  13929. this.start();
  13930. }
  13931. this.initializing = false;
  13932. };
  13933. /**
  13934. * Set options
  13935. * @param {Object} options
  13936. */
  13937. Network.prototype.setOptions = function (options) {
  13938. if (options) {
  13939. var prop;
  13940. var fields = ['nodes','edges','smoothCurves','hierarchicalLayout','clustering','navigation',
  13941. 'keyboard','dataManipulation','onAdd','onEdit','onEditEdge','onConnect','onDelete','clickToUse'
  13942. ];
  13943. // extend all but the values in fields
  13944. util.selectiveNotDeepExtend(fields,this.constants, options);
  13945. util.selectiveNotDeepExtend(['color'],this.constants.nodes, options.nodes);
  13946. util.selectiveNotDeepExtend(['color','length'],this.constants.edges, options.edges);
  13947. if (options.physics) {
  13948. util.mergeOptions(this.constants.physics, options.physics,'barnesHut');
  13949. util.mergeOptions(this.constants.physics, options.physics,'repulsion');
  13950. if (options.physics.hierarchicalRepulsion) {
  13951. this.constants.hierarchicalLayout.enabled = true;
  13952. this.constants.physics.hierarchicalRepulsion.enabled = true;
  13953. this.constants.physics.barnesHut.enabled = false;
  13954. for (prop in options.physics.hierarchicalRepulsion) {
  13955. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  13956. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  13957. }
  13958. }
  13959. }
  13960. }
  13961. if (options.onAdd) {this.triggerFunctions.add = options.onAdd;}
  13962. if (options.onEdit) {this.triggerFunctions.edit = options.onEdit;}
  13963. if (options.onEditEdge) {this.triggerFunctions.editEdge = options.onEditEdge;}
  13964. if (options.onConnect) {this.triggerFunctions.connect = options.onConnect;}
  13965. if (options.onDelete) {this.triggerFunctions.del = options.onDelete;}
  13966. util.mergeOptions(this.constants, options,'smoothCurves');
  13967. util.mergeOptions(this.constants, options,'hierarchicalLayout');
  13968. util.mergeOptions(this.constants, options,'clustering');
  13969. util.mergeOptions(this.constants, options,'navigation');
  13970. util.mergeOptions(this.constants, options,'keyboard');
  13971. util.mergeOptions(this.constants, options,'dataManipulation');
  13972. if (options.dataManipulation) {
  13973. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13974. }
  13975. // TODO: work out these options and document them
  13976. if (options.edges) {
  13977. if (options.edges.color !== undefined) {
  13978. if (util.isString(options.edges.color)) {
  13979. this.constants.edges.color = {};
  13980. this.constants.edges.color.color = options.edges.color;
  13981. this.constants.edges.color.highlight = options.edges.color;
  13982. this.constants.edges.color.hover = options.edges.color;
  13983. }
  13984. else {
  13985. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  13986. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  13987. if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;}
  13988. }
  13989. this.constants.edges.inheritColor = false;
  13990. }
  13991. if (!options.edges.fontColor) {
  13992. if (options.edges.color !== undefined) {
  13993. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  13994. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  13995. }
  13996. }
  13997. }
  13998. if (options.nodes) {
  13999. if (options.nodes.color) {
  14000. var newColorObj = util.parseColor(options.nodes.color);
  14001. this.constants.nodes.color.background = newColorObj.background;
  14002. this.constants.nodes.color.border = newColorObj.border;
  14003. this.constants.nodes.color.highlight.background = newColorObj.highlight.background;
  14004. this.constants.nodes.color.highlight.border = newColorObj.highlight.border;
  14005. this.constants.nodes.color.hover.background = newColorObj.hover.background;
  14006. this.constants.nodes.color.hover.border = newColorObj.hover.border;
  14007. }
  14008. }
  14009. if (options.groups) {
  14010. for (var groupname in options.groups) {
  14011. if (options.groups.hasOwnProperty(groupname)) {
  14012. var group = options.groups[groupname];
  14013. this.groups.add(groupname, group);
  14014. }
  14015. }
  14016. }
  14017. if (options.tooltip) {
  14018. for (prop in options.tooltip) {
  14019. if (options.tooltip.hasOwnProperty(prop)) {
  14020. this.constants.tooltip[prop] = options.tooltip[prop];
  14021. }
  14022. }
  14023. if (options.tooltip.color) {
  14024. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  14025. }
  14026. }
  14027. if ('clickToUse' in options) {
  14028. if (options.clickToUse) {
  14029. if (!this.activator) {
  14030. this.activator = new Activator(this.frame);
  14031. this.activator.on('change', this._createKeyBinds.bind(this));
  14032. }
  14033. }
  14034. else {
  14035. if (this.activator) {
  14036. this.activator.destroy();
  14037. delete this.activator;
  14038. }
  14039. }
  14040. }
  14041. if (options.labels) {
  14042. throw new Error('Option "labels" is deprecated. Use options "locale" and "locales" instead.');
  14043. }
  14044. // (Re)loading the mixins that can be enabled or disabled in the options.
  14045. // load the force calculation functions, grouped under the physics system.
  14046. this._loadPhysicsSystem();
  14047. // load the navigation system.
  14048. this._loadNavigationControls();
  14049. // load the data manipulation system
  14050. this._loadManipulationSystem();
  14051. // configure the smooth curves
  14052. this._configureSmoothCurves();
  14053. // bind keys. If disabled, this will not do anything;
  14054. this._createKeyBinds();
  14055. this.setSize(this.constants.width, this.constants.height);
  14056. this.moving = true;
  14057. this.start();
  14058. }
  14059. };
  14060. /**
  14061. * Create the main frame for the Network.
  14062. * This function is executed once when a Network object is created. The frame
  14063. * contains a canvas, and this canvas contains all objects like the axis and
  14064. * nodes.
  14065. * @private
  14066. */
  14067. Network.prototype._create = function () {
  14068. // remove all elements from the container element.
  14069. while (this.containerElement.hasChildNodes()) {
  14070. this.containerElement.removeChild(this.containerElement.firstChild);
  14071. }
  14072. this.frame = document.createElement('div');
  14073. this.frame.className = 'vis network-frame';
  14074. this.frame.style.position = 'relative';
  14075. this.frame.style.overflow = 'hidden';
  14076. //////////////////////////////////////////////////////////////////
  14077. this.frame.canvas = document.createElement("canvas");
  14078. this.frame.canvas.style.position = 'relative';
  14079. this.frame.appendChild(this.frame.canvas);
  14080. if (!this.frame.canvas.getContext) {
  14081. var noCanvas = document.createElement( 'DIV' );
  14082. noCanvas.style.color = 'red';
  14083. noCanvas.style.fontWeight = 'bold' ;
  14084. noCanvas.style.padding = '10px';
  14085. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14086. this.frame.canvas.appendChild(noCanvas);
  14087. }
  14088. else {
  14089. var ctx = this.frame.canvas.getContext("2d");
  14090. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  14091. ctx.mozBackingStorePixelRatio ||
  14092. ctx.msBackingStorePixelRatio ||
  14093. ctx.oBackingStorePixelRatio ||
  14094. ctx.backingStorePixelRatio || 1);
  14095. this.frame.canvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  14096. }
  14097. //////////////////////////////////////////////////////////////////
  14098. var me = this;
  14099. this.drag = {};
  14100. this.pinch = {};
  14101. this.hammer = Hammer(this.frame.canvas, {
  14102. prevent_default: true
  14103. });
  14104. this.hammer.on('tap', me._onTap.bind(me) );
  14105. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14106. this.hammer.on('hold', me._onHold.bind(me) );
  14107. this.hammer.on('pinch', me._onPinch.bind(me) );
  14108. this.hammer.on('touch', me._onTouch.bind(me) );
  14109. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14110. this.hammer.on('drag', me._onDrag.bind(me) );
  14111. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14112. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14113. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14114. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14115. this.hammerFrame = Hammer(this.frame, {
  14116. prevent_default: true
  14117. });
  14118. this.hammerFrame.on('release', me._onRelease.bind(me) );
  14119. // add the frame to the container element
  14120. this.containerElement.appendChild(this.frame);
  14121. };
  14122. /**
  14123. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14124. * @private
  14125. */
  14126. Network.prototype._createKeyBinds = function() {
  14127. var me = this;
  14128. if (this.keycharm !== undefined) {
  14129. this.keycharm.destroy();
  14130. }
  14131. this.keycharm = keycharm();
  14132. this.keycharm.reset();
  14133. if (this.constants.keyboard.enabled && this.isActive()) {
  14134. this.keycharm.bind("up", this._moveUp.bind(me) , "keydown");
  14135. this.keycharm.bind("up", this._yStopMoving.bind(me), "keyup");
  14136. this.keycharm.bind("down", this._moveDown.bind(me) , "keydown");
  14137. this.keycharm.bind("down", this._yStopMoving.bind(me), "keyup");
  14138. this.keycharm.bind("left", this._moveLeft.bind(me) , "keydown");
  14139. this.keycharm.bind("left", this._xStopMoving.bind(me), "keyup");
  14140. this.keycharm.bind("right",this._moveRight.bind(me), "keydown");
  14141. this.keycharm.bind("right",this._xStopMoving.bind(me), "keyup");
  14142. this.keycharm.bind("=", this._zoomIn.bind(me), "keydown");
  14143. this.keycharm.bind("=", this._stopZoom.bind(me), "keyup");
  14144. this.keycharm.bind("num+", this._zoomIn.bind(me), "keydown");
  14145. this.keycharm.bind("num+", this._stopZoom.bind(me), "keyup");
  14146. this.keycharm.bind("num-", this._zoomOut.bind(me), "keydown");
  14147. this.keycharm.bind("num-", this._stopZoom.bind(me), "keyup");
  14148. this.keycharm.bind("-", this._zoomOut.bind(me), "keydown");
  14149. this.keycharm.bind("-", this._stopZoom.bind(me), "keyup");
  14150. this.keycharm.bind("[", this._zoomIn.bind(me), "keydown");
  14151. this.keycharm.bind("[", this._stopZoom.bind(me), "keyup");
  14152. this.keycharm.bind("]", this._zoomOut.bind(me), "keydown");
  14153. this.keycharm.bind("]", this._stopZoom.bind(me), "keyup");
  14154. this.keycharm.bind("pageup",this._zoomIn.bind(me), "keydown");
  14155. this.keycharm.bind("pageup",this._stopZoom.bind(me), "keyup");
  14156. this.keycharm.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14157. this.keycharm.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14158. }
  14159. if (this.constants.dataManipulation.enabled == true) {
  14160. this.keycharm.bind("esc",this._createManipulatorBar.bind(me));
  14161. this.keycharm.bind("delete",this._deleteSelected.bind(me));
  14162. }
  14163. };
  14164. /**
  14165. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  14166. * var network = new vis.Network(..);
  14167. * network.destroy();
  14168. * network = null;
  14169. */
  14170. Network.prototype.destroy = function() {
  14171. this.start = function () {};
  14172. this.redraw = function () {};
  14173. this.timer = false;
  14174. // cleanup physicsConfiguration if it exists
  14175. this._cleanupPhysicsConfiguration();
  14176. // remove keybindings
  14177. this.keycharm.reset();
  14178. // clear hammer bindings
  14179. this.hammer.dispose();
  14180. // clear events
  14181. this.off();
  14182. // remove all elements from the container element.
  14183. while (this.frame.hasChildNodes()) {
  14184. this.frame.removeChild(this.frame.firstChild);
  14185. }
  14186. // remove all elements from the container element.
  14187. while (this.containerElement.hasChildNodes()) {
  14188. this.containerElement.removeChild(this.containerElement.firstChild);
  14189. }
  14190. }
  14191. /**
  14192. * Get the pointer location from a touch location
  14193. * @param {{pageX: Number, pageY: Number}} touch
  14194. * @return {{x: Number, y: Number}} pointer
  14195. * @private
  14196. */
  14197. Network.prototype._getPointer = function (touch) {
  14198. return {
  14199. x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas),
  14200. y: touch.pageY - util.getAbsoluteTop(this.frame.canvas)
  14201. };
  14202. };
  14203. /**
  14204. * On start of a touch gesture, store the pointer
  14205. * @param event
  14206. * @private
  14207. */
  14208. Network.prototype._onTouch = function (event) {
  14209. if (new Date().valueOf() - this.touchTime > 100) {
  14210. this.drag.pointer = this._getPointer(event.gesture.center);
  14211. this.drag.pinched = false;
  14212. this.pinch.scale = this._getScale();
  14213. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  14214. this.touchTime = new Date().valueOf();
  14215. this._handleTouch(this.drag.pointer);
  14216. }
  14217. };
  14218. /**
  14219. * handle drag start event
  14220. * @private
  14221. */
  14222. Network.prototype._onDragStart = function () {
  14223. this._handleDragStart();
  14224. };
  14225. /**
  14226. * This function is called by _onDragStart.
  14227. * It is separated out because we can then overload it for the datamanipulation system.
  14228. *
  14229. * @private
  14230. */
  14231. Network.prototype._handleDragStart = function() {
  14232. var drag = this.drag;
  14233. var node = this._getNodeAt(drag.pointer);
  14234. // note: drag.pointer is set in _onTouch to get the initial touch location
  14235. drag.dragging = true;
  14236. drag.selection = [];
  14237. drag.translation = this._getTranslation();
  14238. drag.nodeId = null;
  14239. this.draggingNodes = false;
  14240. if (node != null && this.constants.dragNodes == true) {
  14241. this.draggingNodes = true;
  14242. drag.nodeId = node.id;
  14243. // select the clicked node if not yet selected
  14244. if (!node.isSelected()) {
  14245. this._selectObject(node,false);
  14246. }
  14247. this.emit("dragStart",{nodeIds:this.getSelection().nodes});
  14248. // create an array with the selected nodes and their original location and status
  14249. for (var objectId in this.selectionObj.nodes) {
  14250. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14251. var object = this.selectionObj.nodes[objectId];
  14252. var s = {
  14253. id: object.id,
  14254. node: object,
  14255. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14256. x: object.x,
  14257. y: object.y,
  14258. xFixed: object.xFixed,
  14259. yFixed: object.yFixed
  14260. };
  14261. object.xFixed = true;
  14262. object.yFixed = true;
  14263. drag.selection.push(s);
  14264. }
  14265. }
  14266. }
  14267. };
  14268. /**
  14269. * handle drag event
  14270. * @private
  14271. */
  14272. Network.prototype._onDrag = function (event) {
  14273. this._handleOnDrag(event)
  14274. };
  14275. /**
  14276. * This function is called by _onDrag.
  14277. * It is separated out because we can then overload it for the datamanipulation system.
  14278. *
  14279. * @private
  14280. */
  14281. Network.prototype._handleOnDrag = function(event) {
  14282. if (this.drag.pinched) {
  14283. return;
  14284. }
  14285. // remove the focus on node if it is focussed on by the focusOnNode
  14286. this.releaseNode();
  14287. var pointer = this._getPointer(event.gesture.center);
  14288. var me = this;
  14289. var drag = this.drag;
  14290. var selection = drag.selection;
  14291. if (selection && selection.length && this.constants.dragNodes == true) {
  14292. // calculate delta's and new location
  14293. var deltaX = pointer.x - drag.pointer.x;
  14294. var deltaY = pointer.y - drag.pointer.y;
  14295. // update position of all selected nodes
  14296. selection.forEach(function (s) {
  14297. var node = s.node;
  14298. if (!s.xFixed) {
  14299. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  14300. }
  14301. if (!s.yFixed) {
  14302. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  14303. }
  14304. });
  14305. // start _animationStep if not yet running
  14306. if (!this.moving) {
  14307. this.moving = true;
  14308. this.start();
  14309. }
  14310. }
  14311. else {
  14312. if (this.constants.dragNetwork == true) {
  14313. // move the network
  14314. var diffX = pointer.x - this.drag.pointer.x;
  14315. var diffY = pointer.y - this.drag.pointer.y;
  14316. this._setTranslation(
  14317. this.drag.translation.x + diffX,
  14318. this.drag.translation.y + diffY
  14319. );
  14320. this._redraw();
  14321. // this.moving = true;
  14322. // this.start();
  14323. }
  14324. }
  14325. };
  14326. /**
  14327. * handle drag start event
  14328. * @private
  14329. */
  14330. Network.prototype._onDragEnd = function (event) {
  14331. this._handleDragEnd(event);
  14332. };
  14333. Network.prototype._handleDragEnd = function(event) {
  14334. this.drag.dragging = false;
  14335. var selection = this.drag.selection;
  14336. if (selection && selection.length) {
  14337. selection.forEach(function (s) {
  14338. // restore original xFixed and yFixed
  14339. s.node.xFixed = s.xFixed;
  14340. s.node.yFixed = s.yFixed;
  14341. });
  14342. this.moving = true;
  14343. this.start();
  14344. }
  14345. else {
  14346. this._redraw();
  14347. }
  14348. if (this.draggingNodes == false) {
  14349. this.emit("dragEnd",{nodeIds:[]});
  14350. }
  14351. else {
  14352. this.emit("dragEnd",{nodeIds:this.getSelection().nodes});
  14353. }
  14354. }
  14355. /**
  14356. * handle tap/click event: select/unselect a node
  14357. * @private
  14358. */
  14359. Network.prototype._onTap = function (event) {
  14360. var pointer = this._getPointer(event.gesture.center);
  14361. this.pointerPosition = pointer;
  14362. this._handleTap(pointer);
  14363. };
  14364. /**
  14365. * handle doubletap event
  14366. * @private
  14367. */
  14368. Network.prototype._onDoubleTap = function (event) {
  14369. var pointer = this._getPointer(event.gesture.center);
  14370. this._handleDoubleTap(pointer);
  14371. };
  14372. /**
  14373. * handle long tap event: multi select nodes
  14374. * @private
  14375. */
  14376. Network.prototype._onHold = function (event) {
  14377. var pointer = this._getPointer(event.gesture.center);
  14378. this.pointerPosition = pointer;
  14379. this._handleOnHold(pointer);
  14380. };
  14381. /**
  14382. * handle the release of the screen
  14383. *
  14384. * @private
  14385. */
  14386. Network.prototype._onRelease = function (event) {
  14387. var pointer = this._getPointer(event.gesture.center);
  14388. this._handleOnRelease(pointer);
  14389. };
  14390. /**
  14391. * Handle pinch event
  14392. * @param event
  14393. * @private
  14394. */
  14395. Network.prototype._onPinch = function (event) {
  14396. var pointer = this._getPointer(event.gesture.center);
  14397. this.drag.pinched = true;
  14398. if (!('scale' in this.pinch)) {
  14399. this.pinch.scale = 1;
  14400. }
  14401. // TODO: enabled moving while pinching?
  14402. var scale = this.pinch.scale * event.gesture.scale;
  14403. this._zoom(scale, pointer)
  14404. };
  14405. /**
  14406. * Zoom the network in or out
  14407. * @param {Number} scale a number around 1, and between 0.01 and 10
  14408. * @param {{x: Number, y: Number}} pointer Position on screen
  14409. * @return {Number} appliedScale scale is limited within the boundaries
  14410. * @private
  14411. */
  14412. Network.prototype._zoom = function(scale, pointer) {
  14413. if (this.constants.zoomable == true) {
  14414. var scaleOld = this._getScale();
  14415. if (scale < 0.00001) {
  14416. scale = 0.00001;
  14417. }
  14418. if (scale > 10) {
  14419. scale = 10;
  14420. }
  14421. var preScaleDragPointer = null;
  14422. if (this.drag !== undefined) {
  14423. if (this.drag.dragging == true) {
  14424. preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
  14425. }
  14426. }
  14427. // + this.frame.canvas.clientHeight / 2
  14428. var translation = this._getTranslation();
  14429. var scaleFrac = scale / scaleOld;
  14430. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14431. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14432. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  14433. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  14434. this._setScale(scale);
  14435. this._setTranslation(tx, ty);
  14436. this.updateClustersDefault();
  14437. if (preScaleDragPointer != null) {
  14438. var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
  14439. this.drag.pointer.x = postScaleDragPointer.x;
  14440. this.drag.pointer.y = postScaleDragPointer.y;
  14441. }
  14442. this._redraw();
  14443. if (scaleOld < scale) {
  14444. this.emit("zoom", {direction:"+"});
  14445. }
  14446. else {
  14447. this.emit("zoom", {direction:"-"});
  14448. }
  14449. return scale;
  14450. }
  14451. };
  14452. /**
  14453. * Event handler for mouse wheel event, used to zoom the timeline
  14454. * See http://adomas.org/javascript-mouse-wheel/
  14455. * https://github.com/EightMedia/hammer.js/issues/256
  14456. * @param {MouseEvent} event
  14457. * @private
  14458. */
  14459. Network.prototype._onMouseWheel = function(event) {
  14460. // retrieve delta
  14461. var delta = 0;
  14462. if (event.wheelDelta) { /* IE/Opera. */
  14463. delta = event.wheelDelta/120;
  14464. } else if (event.detail) { /* Mozilla case. */
  14465. // In Mozilla, sign of delta is different than in IE.
  14466. // Also, delta is multiple of 3.
  14467. delta = -event.detail/3;
  14468. }
  14469. // If delta is nonzero, handle it.
  14470. // Basically, delta is now positive if wheel was scrolled up,
  14471. // and negative, if wheel was scrolled down.
  14472. if (delta) {
  14473. // calculate the new scale
  14474. var scale = this._getScale();
  14475. var zoom = delta / 10;
  14476. if (delta < 0) {
  14477. zoom = zoom / (1 - zoom);
  14478. }
  14479. scale *= (1 + zoom);
  14480. // calculate the pointer location
  14481. var gesture = hammerUtil.fakeGesture(this, event);
  14482. var pointer = this._getPointer(gesture.center);
  14483. // apply the new scale
  14484. this._zoom(scale, pointer);
  14485. }
  14486. // Prevent default actions caused by mouse wheel.
  14487. event.preventDefault();
  14488. };
  14489. /**
  14490. * Mouse move handler for checking whether the title moves over a node with a title.
  14491. * @param {Event} event
  14492. * @private
  14493. */
  14494. Network.prototype._onMouseMoveTitle = function (event) {
  14495. var gesture = hammerUtil.fakeGesture(this, event);
  14496. var pointer = this._getPointer(gesture.center);
  14497. // check if the previously selected node is still selected
  14498. if (this.popupObj) {
  14499. this._checkHidePopup(pointer);
  14500. }
  14501. // start a timeout that will check if the mouse is positioned above
  14502. // an element
  14503. var me = this;
  14504. var checkShow = function() {
  14505. me._checkShowPopup(pointer);
  14506. };
  14507. if (this.popupTimer) {
  14508. clearInterval(this.popupTimer); // stop any running calculationTimer
  14509. }
  14510. if (!this.drag.dragging) {
  14511. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  14512. }
  14513. /**
  14514. * Adding hover highlights
  14515. */
  14516. if (this.constants.hover == true) {
  14517. // removing all hover highlights
  14518. for (var edgeId in this.hoverObj.edges) {
  14519. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  14520. this.hoverObj.edges[edgeId].hover = false;
  14521. delete this.hoverObj.edges[edgeId];
  14522. }
  14523. }
  14524. // adding hover highlights
  14525. var obj = this._getNodeAt(pointer);
  14526. if (obj == null) {
  14527. obj = this._getEdgeAt(pointer);
  14528. }
  14529. if (obj != null) {
  14530. this._hoverObject(obj);
  14531. }
  14532. // removing all node hover highlights except for the selected one.
  14533. for (var nodeId in this.hoverObj.nodes) {
  14534. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  14535. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  14536. this._blurObject(this.hoverObj.nodes[nodeId]);
  14537. delete this.hoverObj.nodes[nodeId];
  14538. }
  14539. }
  14540. }
  14541. this.redraw();
  14542. }
  14543. };
  14544. /**
  14545. * Check if there is an element on the given position in the network
  14546. * (a node or edge). If so, and if this element has a title,
  14547. * show a popup window with its title.
  14548. *
  14549. * @param {{x:Number, y:Number}} pointer
  14550. * @private
  14551. */
  14552. Network.prototype._checkShowPopup = function (pointer) {
  14553. var obj = {
  14554. left: this._XconvertDOMtoCanvas(pointer.x),
  14555. top: this._YconvertDOMtoCanvas(pointer.y),
  14556. right: this._XconvertDOMtoCanvas(pointer.x),
  14557. bottom: this._YconvertDOMtoCanvas(pointer.y)
  14558. };
  14559. var id;
  14560. var lastPopupNode = this.popupObj;
  14561. var nodeUnderCursor = false;
  14562. if (this.popupObj == undefined) {
  14563. // search the nodes for overlap, select the top one in case of multiple nodes
  14564. var nodes = this.nodes;
  14565. for (id in nodes) {
  14566. if (nodes.hasOwnProperty(id)) {
  14567. var node = nodes[id];
  14568. if (node.isOverlappingWith(obj)) {
  14569. if (node.getTitle() !== undefined) {
  14570. this.popupObj = node;
  14571. break;
  14572. }
  14573. // if you hover over a node, the title of the edge is not supposed to be shown.
  14574. nodeUnderCursor = true;
  14575. }
  14576. }
  14577. }
  14578. }
  14579. if (this.popupObj === undefined && nodeUnderCursor == false) {
  14580. // search the edges for overlap
  14581. var edges = this.edges;
  14582. for (id in edges) {
  14583. if (edges.hasOwnProperty(id)) {
  14584. var edge = edges[id];
  14585. if (edge.connected && (edge.getTitle() !== undefined) &&
  14586. edge.isOverlappingWith(obj)) {
  14587. this.popupObj = edge;
  14588. break;
  14589. }
  14590. }
  14591. }
  14592. }
  14593. if (this.popupObj) {
  14594. // show popup message window
  14595. if (this.popupObj != lastPopupNode) {
  14596. var me = this;
  14597. if (!me.popup) {
  14598. me.popup = new Popup(me.frame, me.constants.tooltip);
  14599. }
  14600. // adjust a small offset such that the mouse cursor is located in the
  14601. // bottom left location of the popup, and you can easily move over the
  14602. // popup area
  14603. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14604. me.popup.setText(me.popupObj.getTitle());
  14605. me.popup.show();
  14606. }
  14607. }
  14608. else {
  14609. if (this.popup) {
  14610. this.popup.hide();
  14611. }
  14612. }
  14613. };
  14614. /**
  14615. * Check if the popup must be hided, which is the case when the mouse is no
  14616. * longer hovering on the object
  14617. * @param {{x:Number, y:Number}} pointer
  14618. * @private
  14619. */
  14620. Network.prototype._checkHidePopup = function (pointer) {
  14621. if (!this.popupObj || !this._getNodeAt(pointer) ) {
  14622. this.popupObj = undefined;
  14623. if (this.popup) {
  14624. this.popup.hide();
  14625. }
  14626. }
  14627. };
  14628. /**
  14629. * Set a new size for the network
  14630. * @param {string} width Width in pixels or percentage (for example '800px'
  14631. * or '50%')
  14632. * @param {string} height Height in pixels or percentage (for example '400px'
  14633. * or '30%')
  14634. */
  14635. Network.prototype.setSize = function(width, height) {
  14636. var emitEvent = false;
  14637. var oldWidth = this.frame.canvas.width;
  14638. var oldHeight = this.frame.canvas.height;
  14639. if (width != this.constants.width || height != this.constants.height || this.frame.style.width != width || this.frame.style.height != height) {
  14640. this.frame.style.width = width;
  14641. this.frame.style.height = height;
  14642. this.frame.canvas.style.width = '100%';
  14643. this.frame.canvas.style.height = '100%';
  14644. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  14645. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  14646. this.constants.width = width;
  14647. this.constants.height = height;
  14648. emitEvent = true;
  14649. }
  14650. else {
  14651. // this would adapt the width of the canvas to the width from 100% if and only if
  14652. // there is a change.
  14653. if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) {
  14654. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  14655. emitEvent = true;
  14656. }
  14657. if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) {
  14658. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  14659. emitEvent = true;
  14660. }
  14661. }
  14662. if (emitEvent == true) {
  14663. 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});
  14664. }
  14665. };
  14666. /**
  14667. * Set a data set with nodes for the network
  14668. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14669. * @private
  14670. */
  14671. Network.prototype._setNodes = function(nodes) {
  14672. var oldNodesData = this.nodesData;
  14673. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14674. this.nodesData = nodes;
  14675. }
  14676. else if (Array.isArray(nodes)) {
  14677. this.nodesData = new DataSet();
  14678. this.nodesData.add(nodes);
  14679. }
  14680. else if (!nodes) {
  14681. this.nodesData = new DataSet();
  14682. }
  14683. else {
  14684. throw new TypeError('Array or DataSet expected');
  14685. }
  14686. if (oldNodesData) {
  14687. // unsubscribe from old dataset
  14688. util.forEach(this.nodesListeners, function (callback, event) {
  14689. oldNodesData.off(event, callback);
  14690. });
  14691. }
  14692. // remove drawn nodes
  14693. this.nodes = {};
  14694. if (this.nodesData) {
  14695. // subscribe to new dataset
  14696. var me = this;
  14697. util.forEach(this.nodesListeners, function (callback, event) {
  14698. me.nodesData.on(event, callback);
  14699. });
  14700. // draw all new nodes
  14701. var ids = this.nodesData.getIds();
  14702. this._addNodes(ids);
  14703. }
  14704. this._updateSelection();
  14705. };
  14706. /**
  14707. * Add nodes
  14708. * @param {Number[] | String[]} ids
  14709. * @private
  14710. */
  14711. Network.prototype._addNodes = function(ids) {
  14712. var id;
  14713. for (var i = 0, len = ids.length; i < len; i++) {
  14714. id = ids[i];
  14715. var data = this.nodesData.get(id);
  14716. var node = new Node(data, this.images, this.groups, this.constants);
  14717. this.nodes[id] = node; // note: this may replace an existing node
  14718. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  14719. var radius = 10 * 0.1*ids.length + 10;
  14720. var angle = 2 * Math.PI * Math.random();
  14721. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14722. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14723. }
  14724. this.moving = true;
  14725. }
  14726. this._updateNodeIndexList();
  14727. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14728. this._resetLevels();
  14729. this._setupHierarchicalLayout();
  14730. }
  14731. this._updateCalculationNodes();
  14732. this._reconnectEdges();
  14733. this._updateValueRange(this.nodes);
  14734. this.updateLabels();
  14735. };
  14736. /**
  14737. * Update existing nodes, or create them when not yet existing
  14738. * @param {Number[] | String[]} ids
  14739. * @private
  14740. */
  14741. Network.prototype._updateNodes = function(ids,changedData) {
  14742. var nodes = this.nodes;
  14743. for (var i = 0, len = ids.length; i < len; i++) {
  14744. var id = ids[i];
  14745. var node = nodes[id];
  14746. var data = changedData[i];
  14747. if (node) {
  14748. // update node
  14749. node.setProperties(data, this.constants);
  14750. }
  14751. else {
  14752. // create node
  14753. node = new Node(properties, this.images, this.groups, this.constants);
  14754. nodes[id] = node;
  14755. }
  14756. }
  14757. this.moving = true;
  14758. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14759. this._resetLevels();
  14760. this._setupHierarchicalLayout();
  14761. }
  14762. this._updateNodeIndexList();
  14763. this._updateValueRange(nodes);
  14764. };
  14765. /**
  14766. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14767. * @param {Number[] | String[]} ids
  14768. * @private
  14769. */
  14770. Network.prototype._removeNodes = function(ids) {
  14771. var nodes = this.nodes;
  14772. for (var i = 0, len = ids.length; i < len; i++) {
  14773. var id = ids[i];
  14774. delete nodes[id];
  14775. }
  14776. this._updateNodeIndexList();
  14777. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14778. this._resetLevels();
  14779. this._setupHierarchicalLayout();
  14780. }
  14781. this._updateCalculationNodes();
  14782. this._reconnectEdges();
  14783. this._updateSelection();
  14784. this._updateValueRange(nodes);
  14785. };
  14786. /**
  14787. * Load edges by reading the data table
  14788. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14789. * @private
  14790. * @private
  14791. */
  14792. Network.prototype._setEdges = function(edges) {
  14793. var oldEdgesData = this.edgesData;
  14794. if (edges instanceof DataSet || edges instanceof DataView) {
  14795. this.edgesData = edges;
  14796. }
  14797. else if (Array.isArray(edges)) {
  14798. this.edgesData = new DataSet();
  14799. this.edgesData.add(edges);
  14800. }
  14801. else if (!edges) {
  14802. this.edgesData = new DataSet();
  14803. }
  14804. else {
  14805. throw new TypeError('Array or DataSet expected');
  14806. }
  14807. if (oldEdgesData) {
  14808. // unsubscribe from old dataset
  14809. util.forEach(this.edgesListeners, function (callback, event) {
  14810. oldEdgesData.off(event, callback);
  14811. });
  14812. }
  14813. // remove drawn edges
  14814. this.edges = {};
  14815. if (this.edgesData) {
  14816. // subscribe to new dataset
  14817. var me = this;
  14818. util.forEach(this.edgesListeners, function (callback, event) {
  14819. me.edgesData.on(event, callback);
  14820. });
  14821. // draw all new nodes
  14822. var ids = this.edgesData.getIds();
  14823. this._addEdges(ids);
  14824. }
  14825. this._reconnectEdges();
  14826. };
  14827. /**
  14828. * Add edges
  14829. * @param {Number[] | String[]} ids
  14830. * @private
  14831. */
  14832. Network.prototype._addEdges = function (ids) {
  14833. var edges = this.edges,
  14834. edgesData = this.edgesData;
  14835. for (var i = 0, len = ids.length; i < len; i++) {
  14836. var id = ids[i];
  14837. var oldEdge = edges[id];
  14838. if (oldEdge) {
  14839. oldEdge.disconnect();
  14840. }
  14841. var data = edgesData.get(id, {"showInternalIds" : true});
  14842. edges[id] = new Edge(data, this, this.constants);
  14843. }
  14844. this.moving = true;
  14845. this._updateValueRange(edges);
  14846. this._createBezierNodes();
  14847. this._updateCalculationNodes();
  14848. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14849. this._resetLevels();
  14850. this._setupHierarchicalLayout();
  14851. }
  14852. };
  14853. /**
  14854. * Update existing edges, or create them when not yet existing
  14855. * @param {Number[] | String[]} ids
  14856. * @private
  14857. */
  14858. Network.prototype._updateEdges = function (ids) {
  14859. var edges = this.edges,
  14860. edgesData = this.edgesData;
  14861. for (var i = 0, len = ids.length; i < len; i++) {
  14862. var id = ids[i];
  14863. var data = edgesData.get(id);
  14864. var edge = edges[id];
  14865. if (edge) {
  14866. // update edge
  14867. edge.disconnect();
  14868. edge.setProperties(data, this.constants);
  14869. edge.connect();
  14870. }
  14871. else {
  14872. // create edge
  14873. edge = new Edge(data, this, this.constants);
  14874. this.edges[id] = edge;
  14875. }
  14876. }
  14877. this._createBezierNodes();
  14878. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14879. this._resetLevels();
  14880. this._setupHierarchicalLayout();
  14881. }
  14882. this.moving = true;
  14883. this._updateValueRange(edges);
  14884. };
  14885. /**
  14886. * Remove existing edges. Non existing ids will be ignored
  14887. * @param {Number[] | String[]} ids
  14888. * @private
  14889. */
  14890. Network.prototype._removeEdges = function (ids) {
  14891. var edges = this.edges;
  14892. for (var i = 0, len = ids.length; i < len; i++) {
  14893. var id = ids[i];
  14894. var edge = edges[id];
  14895. if (edge) {
  14896. if (edge.via != null) {
  14897. delete this.sectors['support']['nodes'][edge.via.id];
  14898. }
  14899. edge.disconnect();
  14900. delete edges[id];
  14901. }
  14902. }
  14903. this.moving = true;
  14904. this._updateValueRange(edges);
  14905. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14906. this._resetLevels();
  14907. this._setupHierarchicalLayout();
  14908. }
  14909. this._updateCalculationNodes();
  14910. };
  14911. /**
  14912. * Reconnect all edges
  14913. * @private
  14914. */
  14915. Network.prototype._reconnectEdges = function() {
  14916. var id,
  14917. nodes = this.nodes,
  14918. edges = this.edges;
  14919. for (id in nodes) {
  14920. if (nodes.hasOwnProperty(id)) {
  14921. nodes[id].edges = [];
  14922. nodes[id].dynamicEdges = [];
  14923. }
  14924. }
  14925. for (id in edges) {
  14926. if (edges.hasOwnProperty(id)) {
  14927. var edge = edges[id];
  14928. edge.from = null;
  14929. edge.to = null;
  14930. edge.connect();
  14931. }
  14932. }
  14933. };
  14934. /**
  14935. * Update the values of all object in the given array according to the current
  14936. * value range of the objects in the array.
  14937. * @param {Object} obj An object containing a set of Edges or Nodes
  14938. * The objects must have a method getValue() and
  14939. * setValueRange(min, max).
  14940. * @private
  14941. */
  14942. Network.prototype._updateValueRange = function(obj) {
  14943. var id;
  14944. // determine the range of the objects
  14945. var valueMin = undefined;
  14946. var valueMax = undefined;
  14947. for (id in obj) {
  14948. if (obj.hasOwnProperty(id)) {
  14949. var value = obj[id].getValue();
  14950. if (value !== undefined) {
  14951. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  14952. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  14953. }
  14954. }
  14955. }
  14956. // adjust the range of all objects
  14957. if (valueMin !== undefined && valueMax !== undefined) {
  14958. for (id in obj) {
  14959. if (obj.hasOwnProperty(id)) {
  14960. obj[id].setValueRange(valueMin, valueMax);
  14961. }
  14962. }
  14963. }
  14964. };
  14965. /**
  14966. * Redraw the network with the current data
  14967. * chart will be resized too.
  14968. */
  14969. Network.prototype.redraw = function() {
  14970. this.setSize(this.constants.width, this.constants.height);
  14971. this._redraw();
  14972. };
  14973. /**
  14974. * Redraw the network with the current data
  14975. * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over.
  14976. * @private
  14977. */
  14978. Network.prototype._redraw = function(hidden) {
  14979. var ctx = this.frame.canvas.getContext('2d');
  14980. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  14981. // clear the canvas
  14982. var w = this.frame.canvas.width * this.pixelRatio;
  14983. var h = this.frame.canvas.height * this.pixelRatio;
  14984. ctx.clearRect(0, 0, w, h);
  14985. // set scaling and translation
  14986. ctx.save();
  14987. ctx.translate(this.translation.x, this.translation.y);
  14988. ctx.scale(this.scale, this.scale);
  14989. this.canvasTopLeft = {
  14990. "x": this._XconvertDOMtoCanvas(0),
  14991. "y": this._YconvertDOMtoCanvas(0)
  14992. };
  14993. this.canvasBottomRight = {
  14994. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth * this.pixelRatio),
  14995. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight * this.pixelRatio)
  14996. };
  14997. if (!(hidden == true)) {
  14998. this._doInAllSectors("_drawAllSectorNodes", ctx);
  14999. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
  15000. this._doInAllSectors("_drawEdges", ctx);
  15001. }
  15002. }
  15003. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
  15004. this._doInAllSectors("_drawNodes",ctx,false);
  15005. }
  15006. if (!(hidden == true)) {
  15007. if (this.controlNodesActive == true) {
  15008. this._doInAllSectors("_drawControlNodes", ctx);
  15009. }
  15010. }
  15011. // this._doInSupportSector("_drawNodes",ctx,true);
  15012. // this._drawTree(ctx,"#F00F0F");
  15013. // restore original scaling and translation
  15014. ctx.restore();
  15015. if (hidden == true) {
  15016. ctx.clearRect(0, 0, w, h);
  15017. }
  15018. };
  15019. /**
  15020. * Set the translation of the network
  15021. * @param {Number} offsetX Horizontal offset
  15022. * @param {Number} offsetY Vertical offset
  15023. * @private
  15024. */
  15025. Network.prototype._setTranslation = function(offsetX, offsetY) {
  15026. if (this.translation === undefined) {
  15027. this.translation = {
  15028. x: 0,
  15029. y: 0
  15030. };
  15031. }
  15032. if (offsetX !== undefined) {
  15033. this.translation.x = offsetX;
  15034. }
  15035. if (offsetY !== undefined) {
  15036. this.translation.y = offsetY;
  15037. }
  15038. this.emit('viewChanged');
  15039. };
  15040. /**
  15041. * Get the translation of the network
  15042. * @return {Object} translation An object with parameters x and y, both a number
  15043. * @private
  15044. */
  15045. Network.prototype._getTranslation = function() {
  15046. return {
  15047. x: this.translation.x,
  15048. y: this.translation.y
  15049. };
  15050. };
  15051. /**
  15052. * Scale the network
  15053. * @param {Number} scale Scaling factor 1.0 is unscaled
  15054. * @private
  15055. */
  15056. Network.prototype._setScale = function(scale) {
  15057. this.scale = scale;
  15058. };
  15059. /**
  15060. * Get the current scale of the network
  15061. * @return {Number} scale Scaling factor 1.0 is unscaled
  15062. * @private
  15063. */
  15064. Network.prototype._getScale = function() {
  15065. return this.scale;
  15066. };
  15067. /**
  15068. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  15069. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  15070. * @param {number} x
  15071. * @returns {number}
  15072. * @private
  15073. */
  15074. Network.prototype._XconvertDOMtoCanvas = function(x) {
  15075. return (x - this.translation.x) / this.scale;
  15076. };
  15077. /**
  15078. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  15079. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  15080. * @param {number} x
  15081. * @returns {number}
  15082. * @private
  15083. */
  15084. Network.prototype._XconvertCanvasToDOM = function(x) {
  15085. return x * this.scale + this.translation.x;
  15086. };
  15087. /**
  15088. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  15089. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  15090. * @param {number} y
  15091. * @returns {number}
  15092. * @private
  15093. */
  15094. Network.prototype._YconvertDOMtoCanvas = function(y) {
  15095. return (y - this.translation.y) / this.scale;
  15096. };
  15097. /**
  15098. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  15099. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  15100. * @param {number} y
  15101. * @returns {number}
  15102. * @private
  15103. */
  15104. Network.prototype._YconvertCanvasToDOM = function(y) {
  15105. return y * this.scale + this.translation.y ;
  15106. };
  15107. /**
  15108. *
  15109. * @param {object} pos = {x: number, y: number}
  15110. * @returns {{x: number, y: number}}
  15111. * @constructor
  15112. */
  15113. Network.prototype.canvasToDOM = function (pos) {
  15114. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  15115. };
  15116. /**
  15117. *
  15118. * @param {object} pos = {x: number, y: number}
  15119. * @returns {{x: number, y: number}}
  15120. * @constructor
  15121. */
  15122. Network.prototype.DOMtoCanvas = function (pos) {
  15123. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  15124. };
  15125. /**
  15126. * Redraw all nodes
  15127. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15128. * @param {CanvasRenderingContext2D} ctx
  15129. * @param {Boolean} [alwaysShow]
  15130. * @private
  15131. */
  15132. Network.prototype._drawNodes = function(ctx,alwaysShow) {
  15133. if (alwaysShow === undefined) {
  15134. alwaysShow = false;
  15135. }
  15136. // first draw the unselected nodes
  15137. var nodes = this.nodes;
  15138. var selected = [];
  15139. for (var id in nodes) {
  15140. if (nodes.hasOwnProperty(id)) {
  15141. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15142. if (nodes[id].isSelected()) {
  15143. selected.push(id);
  15144. }
  15145. else {
  15146. if (nodes[id].inArea() || alwaysShow) {
  15147. nodes[id].draw(ctx);
  15148. }
  15149. }
  15150. }
  15151. }
  15152. // draw the selected nodes on top
  15153. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15154. if (nodes[selected[s]].inArea() || alwaysShow) {
  15155. nodes[selected[s]].draw(ctx);
  15156. }
  15157. }
  15158. };
  15159. /**
  15160. * Redraw all edges
  15161. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15162. * @param {CanvasRenderingContext2D} ctx
  15163. * @private
  15164. */
  15165. Network.prototype._drawEdges = function(ctx) {
  15166. var edges = this.edges;
  15167. for (var id in edges) {
  15168. if (edges.hasOwnProperty(id)) {
  15169. var edge = edges[id];
  15170. edge.setScale(this.scale);
  15171. if (edge.connected) {
  15172. edges[id].draw(ctx);
  15173. }
  15174. }
  15175. }
  15176. };
  15177. /**
  15178. * Redraw all edges
  15179. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15180. * @param {CanvasRenderingContext2D} ctx
  15181. * @private
  15182. */
  15183. Network.prototype._drawControlNodes = function(ctx) {
  15184. var edges = this.edges;
  15185. for (var id in edges) {
  15186. if (edges.hasOwnProperty(id)) {
  15187. edges[id]._drawControlNodes(ctx);
  15188. }
  15189. }
  15190. };
  15191. /**
  15192. * Find a stable position for all nodes
  15193. * @private
  15194. */
  15195. Network.prototype._stabilize = function() {
  15196. if (this.constants.freezeForStabilization == true) {
  15197. this._freezeDefinedNodes();
  15198. }
  15199. // find stable position
  15200. var count = 0;
  15201. while (this.moving && count < this.constants.stabilizationIterations) {
  15202. this._physicsTick();
  15203. count++;
  15204. }
  15205. if (this.constants.zoomExtentOnStabilize == true) {
  15206. this.zoomExtent(undefined, false, true);
  15207. }
  15208. if (this.constants.freezeForStabilization == true) {
  15209. this._restoreFrozenNodes();
  15210. }
  15211. };
  15212. /**
  15213. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  15214. * because only the supportnodes for the smoothCurves have to settle.
  15215. *
  15216. * @private
  15217. */
  15218. Network.prototype._freezeDefinedNodes = function() {
  15219. var nodes = this.nodes;
  15220. for (var id in nodes) {
  15221. if (nodes.hasOwnProperty(id)) {
  15222. if (nodes[id].x != null && nodes[id].y != null) {
  15223. nodes[id].fixedData.x = nodes[id].xFixed;
  15224. nodes[id].fixedData.y = nodes[id].yFixed;
  15225. nodes[id].xFixed = true;
  15226. nodes[id].yFixed = true;
  15227. }
  15228. }
  15229. }
  15230. };
  15231. /**
  15232. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  15233. *
  15234. * @private
  15235. */
  15236. Network.prototype._restoreFrozenNodes = function() {
  15237. var nodes = this.nodes;
  15238. for (var id in nodes) {
  15239. if (nodes.hasOwnProperty(id)) {
  15240. if (nodes[id].fixedData.x != null) {
  15241. nodes[id].xFixed = nodes[id].fixedData.x;
  15242. nodes[id].yFixed = nodes[id].fixedData.y;
  15243. }
  15244. }
  15245. }
  15246. };
  15247. /**
  15248. * Check if any of the nodes is still moving
  15249. * @param {number} vmin the minimum velocity considered as 'moving'
  15250. * @return {boolean} true if moving, false if non of the nodes is moving
  15251. * @private
  15252. */
  15253. Network.prototype._isMoving = function(vmin) {
  15254. var nodes = this.nodes;
  15255. for (var id in nodes) {
  15256. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15257. return true;
  15258. }
  15259. }
  15260. return false;
  15261. };
  15262. /**
  15263. * /**
  15264. * Perform one discrete step for all nodes
  15265. *
  15266. * @private
  15267. */
  15268. Network.prototype._discreteStepNodes = function() {
  15269. var interval = this.physicsDiscreteStepsize;
  15270. var nodes = this.nodes;
  15271. var nodeId;
  15272. var nodesPresent = false;
  15273. if (this.constants.maxVelocity > 0) {
  15274. for (nodeId in nodes) {
  15275. if (nodes.hasOwnProperty(nodeId)) {
  15276. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15277. nodesPresent = true;
  15278. }
  15279. }
  15280. }
  15281. else {
  15282. for (nodeId in nodes) {
  15283. if (nodes.hasOwnProperty(nodeId)) {
  15284. nodes[nodeId].discreteStep(interval);
  15285. nodesPresent = true;
  15286. }
  15287. }
  15288. }
  15289. if (nodesPresent == true) {
  15290. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15291. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15292. return true;
  15293. }
  15294. else {
  15295. return this._isMoving(vminCorrected);
  15296. }
  15297. }
  15298. return false;
  15299. };
  15300. Network.prototype._revertPhysicsState = function() {
  15301. var nodes = this.nodes;
  15302. for (var nodeId in nodes) {
  15303. if (nodes.hasOwnProperty(nodeId)) {
  15304. nodes[nodeId].revertPosition();
  15305. }
  15306. }
  15307. }
  15308. Network.prototype._revertPhysicsTick = function() {
  15309. this._doInAllActiveSectors("_revertPhysicsState");
  15310. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  15311. this._doInSupportSector("_revertPhysicsState");
  15312. }
  15313. }
  15314. /**
  15315. * A single simulation step (or "tick") in the physics simulation
  15316. *
  15317. * @private
  15318. */
  15319. Network.prototype._physicsTick = function() {
  15320. if (!this.freezeSimulation) {
  15321. if (this.moving == true) {
  15322. var mainMovingStatus = false;
  15323. var supportMovingStatus = false;
  15324. this._doInAllActiveSectors("_initializeForceCalculation");
  15325. var mainMoving = this._doInAllActiveSectors("_discreteStepNodes");
  15326. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  15327. supportMovingStatus = this._doInSupportSector("_discreteStepNodes");
  15328. }
  15329. // gather movement data from all sectors, if one moves, we are NOT stabilzied
  15330. for (var i = 0; i < mainMoving.length; i++) {mainMovingStatus = mainMoving[0] || mainMovingStatus;}
  15331. // determine if the network has stabilzied
  15332. this.moving = mainMovingStatus || supportMovingStatus;
  15333. if (this.moving == false) {
  15334. this._revertPhysicsTick();
  15335. }
  15336. else {
  15337. // this is here to ensure that there is no start event when the network is already stable.
  15338. if (this.startedStabilization == false) {
  15339. this.emit("startStabilization");
  15340. this.startedStabilization = true;
  15341. }
  15342. }
  15343. this.stabilizationIterations++;
  15344. }
  15345. }
  15346. };
  15347. /**
  15348. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15349. * It reschedules itself at the beginning of the function
  15350. *
  15351. * @private
  15352. */
  15353. Network.prototype._animationStep = function() {
  15354. // reset the timer so a new scheduled animation step can be set
  15355. this.timer = undefined;
  15356. // handle the keyboad movement
  15357. this._handleNavigation();
  15358. var startTime = Date.now();
  15359. this._physicsTick();
  15360. var physicsTime = Date.now() - startTime;
  15361. // run double speed if it is a little graph
  15362. if ((this.renderTimestep - this.renderTime > 2 * physicsTime || this.runDoubleSpeed == true) && this.moving == true) {
  15363. this._physicsTick();
  15364. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  15365. if (this.renderTime != 0) {
  15366. this.runDoubleSpeed = true
  15367. }
  15368. }
  15369. var renderStartTime = Date.now();
  15370. this._redraw();
  15371. this.renderTime = Date.now() - renderStartTime;
  15372. // this schedules a new animation step
  15373. this.start();
  15374. };
  15375. if (typeof window !== 'undefined') {
  15376. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15377. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15378. }
  15379. /**
  15380. * Schedule a animation step with the refreshrate interval.
  15381. */
  15382. Network.prototype.start = function() {
  15383. if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15384. if (!this.timer) {
  15385. if (this.requiresTimeout == true) {
  15386. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15387. }
  15388. else {
  15389. this.timer = window.requestAnimationFrame(this._animationStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function
  15390. }
  15391. }
  15392. }
  15393. else {
  15394. this._redraw();
  15395. // 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())
  15396. if (this.stabilizationIterations > 1) {
  15397. // trigger the "stabilized" event.
  15398. // The event is triggered on the next tick, to prevent the case that
  15399. // it is fired while initializing the Network, in which case you would not
  15400. // be able to catch it
  15401. var me = this;
  15402. var params = {
  15403. iterations: me.stabilizationIterations
  15404. };
  15405. this.stabilizationIterations = 0;
  15406. this.startedStabilization = false;
  15407. setTimeout(function () {
  15408. me.emit("stabilized", params);
  15409. }, 0);
  15410. }
  15411. else {
  15412. this.stabilizationIterations = 0;
  15413. }
  15414. }
  15415. };
  15416. /**
  15417. * Move the network according to the keyboard presses.
  15418. *
  15419. * @private
  15420. */
  15421. Network.prototype._handleNavigation = function() {
  15422. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15423. var translation = this._getTranslation();
  15424. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15425. }
  15426. if (this.zoomIncrement != 0) {
  15427. var center = {
  15428. x: this.frame.canvas.clientWidth / 2,
  15429. y: this.frame.canvas.clientHeight / 2
  15430. };
  15431. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15432. }
  15433. };
  15434. /**
  15435. * Freeze the _animationStep
  15436. */
  15437. Network.prototype.toggleFreeze = function() {
  15438. if (this.freezeSimulation == false) {
  15439. this.freezeSimulation = true;
  15440. }
  15441. else {
  15442. this.freezeSimulation = false;
  15443. this.start();
  15444. }
  15445. };
  15446. /**
  15447. * This function cleans the support nodes if they are not needed and adds them when they are.
  15448. *
  15449. * @param {boolean} [disableStart]
  15450. * @private
  15451. */
  15452. Network.prototype._configureSmoothCurves = function(disableStart) {
  15453. if (disableStart === undefined) {
  15454. disableStart = true;
  15455. }
  15456. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  15457. this._createBezierNodes();
  15458. // cleanup unused support nodes
  15459. for (var nodeId in this.sectors['support']['nodes']) {
  15460. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  15461. if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) {
  15462. delete this.sectors['support']['nodes'][nodeId];
  15463. }
  15464. }
  15465. }
  15466. }
  15467. else {
  15468. // delete the support nodes
  15469. this.sectors['support']['nodes'] = {};
  15470. for (var edgeId in this.edges) {
  15471. if (this.edges.hasOwnProperty(edgeId)) {
  15472. this.edges[edgeId].via = null;
  15473. }
  15474. }
  15475. }
  15476. this._updateCalculationNodes();
  15477. if (!disableStart) {
  15478. this.moving = true;
  15479. this.start();
  15480. }
  15481. };
  15482. /**
  15483. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  15484. * are used for the force calculation.
  15485. *
  15486. * @private
  15487. */
  15488. Network.prototype._createBezierNodes = function() {
  15489. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  15490. for (var edgeId in this.edges) {
  15491. if (this.edges.hasOwnProperty(edgeId)) {
  15492. var edge = this.edges[edgeId];
  15493. if (edge.via == null) {
  15494. var nodeId = "edgeId:".concat(edge.id);
  15495. this.sectors['support']['nodes'][nodeId] = new Node(
  15496. {id:nodeId,
  15497. mass:1,
  15498. shape:'circle',
  15499. image:"",
  15500. internalMultiplier:1
  15501. },{},{},this.constants);
  15502. edge.via = this.sectors['support']['nodes'][nodeId];
  15503. edge.via.parentEdgeId = edge.id;
  15504. edge.positionBezierNode();
  15505. }
  15506. }
  15507. }
  15508. }
  15509. };
  15510. /**
  15511. * load the functions that load the mixins into the prototype.
  15512. *
  15513. * @private
  15514. */
  15515. Network.prototype._initializeMixinLoaders = function () {
  15516. for (var mixin in MixinLoader) {
  15517. if (MixinLoader.hasOwnProperty(mixin)) {
  15518. Network.prototype[mixin] = MixinLoader[mixin];
  15519. }
  15520. }
  15521. };
  15522. /**
  15523. * Load the XY positions of the nodes into the dataset.
  15524. */
  15525. Network.prototype.storePosition = function() {
  15526. console.log("storePosition is depricated: use .storePositions() from now on.")
  15527. this.storePositions();
  15528. };
  15529. /**
  15530. * Load the XY positions of the nodes into the dataset.
  15531. */
  15532. Network.prototype.storePositions = function() {
  15533. var dataArray = [];
  15534. for (var nodeId in this.nodes) {
  15535. if (this.nodes.hasOwnProperty(nodeId)) {
  15536. var node = this.nodes[nodeId];
  15537. var allowedToMoveX = !this.nodes.xFixed;
  15538. var allowedToMoveY = !this.nodes.yFixed;
  15539. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  15540. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15541. }
  15542. }
  15543. }
  15544. this.nodesData.update(dataArray);
  15545. };
  15546. /**
  15547. * Return the positions of the nodes.
  15548. */
  15549. Network.prototype.getPositions = function(ids) {
  15550. var dataArray = {};
  15551. if (ids !== undefined) {
  15552. if (Array.isArray(ids) == true) {
  15553. for (var i = 0; i < ids.length; i++) {
  15554. if (this.nodes[ids[i]] !== undefined) {
  15555. var node = this.nodes[ids[i]];
  15556. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  15557. }
  15558. }
  15559. }
  15560. else {
  15561. if (this.nodes[ids] !== undefined) {
  15562. var node = this.nodes[ids];
  15563. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  15564. }
  15565. }
  15566. }
  15567. else {
  15568. for (var nodeId in this.nodes) {
  15569. if (this.nodes.hasOwnProperty(nodeId)) {
  15570. var node = this.nodes[nodeId];
  15571. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  15572. }
  15573. }
  15574. }
  15575. return dataArray;
  15576. };
  15577. /**
  15578. * Center a node in view.
  15579. *
  15580. * @param {Number} nodeId
  15581. * @param {Number} [options]
  15582. */
  15583. Network.prototype.focusOnNode = function (nodeId, options) {
  15584. if (this.nodes.hasOwnProperty(nodeId)) {
  15585. if (options === undefined) {
  15586. options = {};
  15587. }
  15588. var nodePosition = {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  15589. options.position = nodePosition;
  15590. options.lockedOnNode = nodeId;
  15591. this.moveTo(options)
  15592. }
  15593. else {
  15594. console.log("This nodeId cannot be found.");
  15595. }
  15596. };
  15597. /**
  15598. *
  15599. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  15600. * | options.scale = Number // scale to move to
  15601. * | options.position = {x:Number, y:Number} // position to move to
  15602. * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to
  15603. */
  15604. Network.prototype.moveTo = function (options) {
  15605. if (options === undefined) {
  15606. options = {};
  15607. return;
  15608. }
  15609. if (options.offset === undefined) {options.offset = {x: 0, y: 0}; }
  15610. if (options.offset.x === undefined) {options.offset.x = 0; }
  15611. if (options.offset.y === undefined) {options.offset.y = 0; }
  15612. if (options.scale === undefined) {options.scale = this._getScale(); }
  15613. if (options.position === undefined) {options.position = this._getTranslation();}
  15614. if (options.animation === undefined) {options.animation = {duration:0}; }
  15615. if (options.animation === false ) {options.animation = {duration:0}; }
  15616. if (options.animation === true ) {options.animation = {}; }
  15617. if (options.animation.duration === undefined) {options.animation.duration = 1000; } // default duration
  15618. if (options.animation.easingFunction === undefined) {options.animation.easingFunction = "easeInOutQuad"; } // default easing function
  15619. this.animateView(options);
  15620. };
  15621. /**
  15622. *
  15623. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  15624. * | options.time = Number // animation time in milliseconds
  15625. * | options.scale = Number // scale to animate to
  15626. * | options.position = {x:Number, y:Number} // position to animate to
  15627. * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
  15628. * // easeInCubic, easeOutCubic, easeInOutCubic,
  15629. * // easeInQuart, easeOutQuart, easeInOutQuart,
  15630. * // easeInQuint, easeOutQuint, easeInOutQuint
  15631. */
  15632. Network.prototype.animateView = function (options) {
  15633. if (options === undefined) {
  15634. options = {};
  15635. return;
  15636. }
  15637. // release if something focussed on the node
  15638. this.releaseNode();
  15639. if (options.locked == true) {
  15640. this.lockedOnNodeId = options.lockedOnNode;
  15641. this.lockedOnNodeOffset = options.offset;
  15642. }
  15643. // forcefully complete the old animation if it was still running
  15644. if (this.easingTime != 0) {
  15645. this._transitionRedraw(1); // by setting easingtime to 1, we finish the animation.
  15646. }
  15647. this.sourceScale = this._getScale();
  15648. this.sourceTranslation = this._getTranslation();
  15649. this.targetScale = options.scale;
  15650. // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
  15651. // but at least then we'll have the target transition
  15652. this._setScale(this.targetScale);
  15653. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  15654. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  15655. x: viewCenter.x - options.position.x,
  15656. y: viewCenter.y - options.position.y
  15657. };
  15658. this.targetTranslation = {
  15659. x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x,
  15660. y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y
  15661. };
  15662. // if the time is set to 0, don't do an animation
  15663. if (options.animation.duration == 0) {
  15664. if (this.lockedOnNodeId != null) {
  15665. this._classicRedraw = this._redraw;
  15666. this._redraw = this._lockedRedraw;
  15667. }
  15668. else {
  15669. this._setScale(this.targetScale);
  15670. this._setTranslation(this.targetTranslation.x, this.targetTranslation.y);
  15671. this._redraw();
  15672. }
  15673. }
  15674. else {
  15675. this.animationSpeed = 1 / (this.renderRefreshRate * options.animation.duration * 0.001) || 1 / this.renderRefreshRate;
  15676. this.animationEasingFunction = options.animation.easingFunction;
  15677. this._classicRedraw = this._redraw;
  15678. this._redraw = this._transitionRedraw;
  15679. this._redraw();
  15680. this.moving = true;
  15681. this.start();
  15682. }
  15683. };
  15684. /**
  15685. * used to animate smoothly by hijacking the redraw function.
  15686. * @private
  15687. */
  15688. Network.prototype._lockedRedraw = function () {
  15689. var nodePosition = {x: this.nodes[this.lockedOnNodeId].x, y: this.nodes[this.lockedOnNodeId].y};
  15690. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  15691. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  15692. x: viewCenter.x - nodePosition.x,
  15693. y: viewCenter.y - nodePosition.y
  15694. };
  15695. var sourceTranslation = this._getTranslation();
  15696. var targetTranslation = {
  15697. x: sourceTranslation.x + distanceFromCenter.x * this.scale + this.lockedOnNodeOffset.x,
  15698. y: sourceTranslation.y + distanceFromCenter.y * this.scale + this.lockedOnNodeOffset.y
  15699. };
  15700. this._setTranslation(targetTranslation.x,targetTranslation.y);
  15701. this._classicRedraw();
  15702. }
  15703. Network.prototype.releaseNode = function () {
  15704. if (this.lockedOnNodeId != null) {
  15705. this._redraw = this._classicRedraw;
  15706. this.lockedOnNodeId = null;
  15707. this.lockedOnNodeOffset = null;
  15708. }
  15709. }
  15710. /**
  15711. *
  15712. * @param easingTime
  15713. * @private
  15714. */
  15715. Network.prototype._transitionRedraw = function (easingTime) {
  15716. this.easingTime = easingTime || this.easingTime + this.animationSpeed;
  15717. this.easingTime += this.animationSpeed;
  15718. var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime);
  15719. this._setScale(this.sourceScale + (this.targetScale - this.sourceScale) * progress);
  15720. this._setTranslation(
  15721. this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress,
  15722. this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress
  15723. );
  15724. this._classicRedraw();
  15725. this.moving = true;
  15726. // cleanup
  15727. if (this.easingTime >= 1.0) {
  15728. this.easingTime = 0;
  15729. if (this.lockedOnNodeId != null) {
  15730. this._redraw = this._lockedRedraw;
  15731. }
  15732. else {
  15733. this._redraw = this._classicRedraw;
  15734. }
  15735. this.emit("animationFinished");
  15736. }
  15737. };
  15738. Network.prototype._classicRedraw = function () {
  15739. // placeholder function to be overloaded by animations;
  15740. };
  15741. /**
  15742. * Returns true when the Network is active.
  15743. * @returns {boolean}
  15744. */
  15745. Network.prototype.isActive = function () {
  15746. return !this.activator || this.activator.active;
  15747. };
  15748. /**
  15749. * Sets the scale
  15750. * @returns {Number}
  15751. */
  15752. Network.prototype.setScale = function () {
  15753. return this._setScale();
  15754. };
  15755. /**
  15756. * Returns the scale
  15757. * @returns {Number}
  15758. */
  15759. Network.prototype.getScale = function () {
  15760. return this._getScale();
  15761. };
  15762. /**
  15763. * Returns the scale
  15764. * @returns {Number}
  15765. */
  15766. Network.prototype.getCenterCoordinates = function () {
  15767. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  15768. };
  15769. Network.prototype.getBoundingBox = function(nodeId) {
  15770. if (this.nodes[nodeId] !== undefined) {
  15771. return this.nodes[nodeId].boundingBox;
  15772. }
  15773. }
  15774. module.exports = Network;
  15775. /***/ },
  15776. /* 37 */
  15777. /***/ function(module, exports, __webpack_require__) {
  15778. var util = __webpack_require__(1);
  15779. var Node = __webpack_require__(40);
  15780. /**
  15781. * @class Edge
  15782. *
  15783. * A edge connects two nodes
  15784. * @param {Object} properties Object with properties. Must contain
  15785. * At least properties from and to.
  15786. * Available properties: from (number),
  15787. * to (number), label (string, color (string),
  15788. * width (number), style (string),
  15789. * length (number), title (string)
  15790. * @param {Network} network A Network object, used to find and edge to
  15791. * nodes.
  15792. * @param {Object} constants An object with default values for
  15793. * example for the color
  15794. */
  15795. function Edge (properties, network, networkConstants) {
  15796. if (!network) {
  15797. throw "No network provided";
  15798. }
  15799. var fields = ['edges','physics'];
  15800. var constants = util.selectiveBridgeObject(fields,networkConstants);
  15801. this.options = constants.edges;
  15802. this.physics = constants.physics;
  15803. this.options['smoothCurves'] = networkConstants['smoothCurves'];
  15804. this.network = network;
  15805. // initialize variables
  15806. this.id = undefined;
  15807. this.fromId = undefined;
  15808. this.toId = undefined;
  15809. this.title = undefined;
  15810. this.widthSelected = this.options.width * this.options.widthSelectionMultiplier;
  15811. this.value = undefined;
  15812. this.selected = false;
  15813. this.hover = false;
  15814. this.labelDimensions = {top:0,left:0,width:0,height:0,yLine:0}; // could be cached
  15815. this.dirtyLabel = true;
  15816. this.from = null; // a node
  15817. this.to = null; // a node
  15818. this.via = null; // a temp node
  15819. this.fromBackup = null; // used to clean up after reconnect
  15820. this.toBackup = null;; // used to clean up after reconnect
  15821. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  15822. // by storing the original information we can revert to the original connection when the cluser is opened.
  15823. this.originalFromId = [];
  15824. this.originalToId = [];
  15825. this.connected = false;
  15826. this.widthFixed = false;
  15827. this.lengthFixed = false;
  15828. this.setProperties(properties);
  15829. this.controlNodesEnabled = false;
  15830. this.controlNodes = {from:null, to:null, positions:{}};
  15831. this.connectedNode = null;
  15832. }
  15833. /**
  15834. * Set or overwrite properties for the edge
  15835. * @param {Object} properties an object with properties
  15836. * @param {Object} constants and object with default, global properties
  15837. */
  15838. Edge.prototype.setProperties = function(properties) {
  15839. if (!properties) {
  15840. return;
  15841. }
  15842. var fields = ['style','fontSize','fontFace','fontColor','fontFill','width',
  15843. 'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash','inheritColor'
  15844. ];
  15845. util.selectiveDeepExtend(fields, this.options, properties);
  15846. if (properties.from !== undefined) {this.fromId = properties.from;}
  15847. if (properties.to !== undefined) {this.toId = properties.to;}
  15848. if (properties.id !== undefined) {this.id = properties.id;}
  15849. if (properties.label !== undefined) {this.label = properties.label; this.dirtyLabel = true;}
  15850. if (properties.title !== undefined) {this.title = properties.title;}
  15851. if (properties.value !== undefined) {this.value = properties.value;}
  15852. if (properties.length !== undefined) {this.physics.springLength = properties.length;}
  15853. if (properties.color !== undefined) {
  15854. this.options.inheritColor = false;
  15855. if (util.isString(properties.color)) {
  15856. this.options.color.color = properties.color;
  15857. this.options.color.highlight = properties.color;
  15858. }
  15859. else {
  15860. if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;}
  15861. if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;}
  15862. if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;}
  15863. }
  15864. }
  15865. // A node is connected when it has a from and to node.
  15866. this.connect();
  15867. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  15868. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  15869. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  15870. // set draw method based on style
  15871. switch (this.options.style) {
  15872. case 'line': this.draw = this._drawLine; break;
  15873. case 'arrow': this.draw = this._drawArrow; break;
  15874. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  15875. case 'dash-line': this.draw = this._drawDashLine; break;
  15876. default: this.draw = this._drawLine; break;
  15877. }
  15878. };
  15879. /**
  15880. * Connect an edge to its nodes
  15881. */
  15882. Edge.prototype.connect = function () {
  15883. this.disconnect();
  15884. this.from = this.network.nodes[this.fromId] || null;
  15885. this.to = this.network.nodes[this.toId] || null;
  15886. this.connected = (this.from && this.to);
  15887. if (this.connected) {
  15888. this.from.attachEdge(this);
  15889. this.to.attachEdge(this);
  15890. }
  15891. else {
  15892. if (this.from) {
  15893. this.from.detachEdge(this);
  15894. }
  15895. if (this.to) {
  15896. this.to.detachEdge(this);
  15897. }
  15898. }
  15899. };
  15900. /**
  15901. * Disconnect an edge from its nodes
  15902. */
  15903. Edge.prototype.disconnect = function () {
  15904. if (this.from) {
  15905. this.from.detachEdge(this);
  15906. this.from = null;
  15907. }
  15908. if (this.to) {
  15909. this.to.detachEdge(this);
  15910. this.to = null;
  15911. }
  15912. this.connected = false;
  15913. };
  15914. /**
  15915. * get the title of this edge.
  15916. * @return {string} title The title of the edge, or undefined when no title
  15917. * has been set.
  15918. */
  15919. Edge.prototype.getTitle = function() {
  15920. return typeof this.title === "function" ? this.title() : this.title;
  15921. };
  15922. /**
  15923. * Retrieve the value of the edge. Can be undefined
  15924. * @return {Number} value
  15925. */
  15926. Edge.prototype.getValue = function() {
  15927. return this.value;
  15928. };
  15929. /**
  15930. * Adjust the value range of the edge. The edge will adjust it's width
  15931. * based on its value.
  15932. * @param {Number} min
  15933. * @param {Number} max
  15934. */
  15935. Edge.prototype.setValueRange = function(min, max) {
  15936. if (!this.widthFixed && this.value !== undefined) {
  15937. var scale = (this.options.widthMax - this.options.widthMin) / (max - min);
  15938. this.options.width= (this.value - min) * scale + this.options.widthMin;
  15939. this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
  15940. }
  15941. };
  15942. /**
  15943. * Redraw a edge
  15944. * Draw this edge in the given canvas
  15945. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  15946. * @param {CanvasRenderingContext2D} ctx
  15947. */
  15948. Edge.prototype.draw = function(ctx) {
  15949. throw "Method draw not initialized in edge";
  15950. };
  15951. /**
  15952. * Check if this object is overlapping with the provided object
  15953. * @param {Object} obj an object with parameters left, top
  15954. * @return {boolean} True if location is located on the edge
  15955. */
  15956. Edge.prototype.isOverlappingWith = function(obj) {
  15957. if (this.connected) {
  15958. var distMax = 10;
  15959. var xFrom = this.from.x;
  15960. var yFrom = this.from.y;
  15961. var xTo = this.to.x;
  15962. var yTo = this.to.y;
  15963. var xObj = obj.left;
  15964. var yObj = obj.top;
  15965. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  15966. return (dist < distMax);
  15967. }
  15968. else {
  15969. return false
  15970. }
  15971. };
  15972. Edge.prototype._getColor = function() {
  15973. var colorObj = this.options.color;
  15974. if (this.options.inheritColor == "to") {
  15975. colorObj = {
  15976. highlight: this.to.options.color.highlight.border,
  15977. hover: this.to.options.color.hover.border,
  15978. color: this.to.options.color.border
  15979. };
  15980. }
  15981. else if (this.options.inheritColor == "from" || this.options.inheritColor == true) {
  15982. colorObj = {
  15983. highlight: this.from.options.color.highlight.border,
  15984. hover: this.from.options.color.hover.border,
  15985. color: this.from.options.color.border
  15986. };
  15987. }
  15988. if (this.selected == true) {return colorObj.highlight;}
  15989. else if (this.hover == true) {return colorObj.hover;}
  15990. else {return colorObj.color;}
  15991. };
  15992. /**
  15993. * Redraw a edge as a line
  15994. * Draw this edge in the given canvas
  15995. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  15996. * @param {CanvasRenderingContext2D} ctx
  15997. * @private
  15998. */
  15999. Edge.prototype._drawLine = function(ctx) {
  16000. // set style
  16001. ctx.strokeStyle = this._getColor();
  16002. ctx.lineWidth = this._getLineWidth();
  16003. if (this.from != this.to) {
  16004. // draw line
  16005. var via = this._line(ctx);
  16006. // draw label
  16007. var point;
  16008. if (this.label) {
  16009. if (this.options.smoothCurves.enabled == true && via != null) {
  16010. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  16011. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  16012. point = {x:midpointX, y:midpointY};
  16013. }
  16014. else {
  16015. point = this._pointOnLine(0.5);
  16016. }
  16017. this._label(ctx, this.label, point.x, point.y);
  16018. }
  16019. }
  16020. else {
  16021. var x, y;
  16022. var radius = this.physics.springLength / 4;
  16023. var node = this.from;
  16024. if (!node.width) {
  16025. node.resize(ctx);
  16026. }
  16027. if (node.width > node.height) {
  16028. x = node.x + node.width / 2;
  16029. y = node.y - radius;
  16030. }
  16031. else {
  16032. x = node.x + radius;
  16033. y = node.y - node.height / 2;
  16034. }
  16035. this._circle(ctx, x, y, radius);
  16036. point = this._pointOnCircle(x, y, radius, 0.5);
  16037. this._label(ctx, this.label, point.x, point.y);
  16038. }
  16039. };
  16040. /**
  16041. * Get the line width of the edge. Depends on width and whether one of the
  16042. * connected nodes is selected.
  16043. * @return {Number} width
  16044. * @private
  16045. */
  16046. Edge.prototype._getLineWidth = function() {
  16047. if (this.selected == true) {
  16048. return Math.max(Math.min(this.widthSelected, this.options.widthMax), 0.3*this.networkScaleInv);
  16049. }
  16050. else {
  16051. if (this.hover == true) {
  16052. return Math.max(Math.min(this.options.hoverWidth, this.options.widthMax), 0.3*this.networkScaleInv);
  16053. }
  16054. else {
  16055. return Math.max(this.options.width, 0.3*this.networkScaleInv);
  16056. }
  16057. }
  16058. };
  16059. Edge.prototype._getViaCoordinates = function () {
  16060. var xVia = null;
  16061. var yVia = null;
  16062. var factor = this.options.smoothCurves.roundness;
  16063. var type = this.options.smoothCurves.type;
  16064. var dx = Math.abs(this.from.x - this.to.x);
  16065. var dy = Math.abs(this.from.y - this.to.y);
  16066. if (type == 'discrete' || type == 'diagonalCross') {
  16067. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  16068. if (this.from.y > this.to.y) {
  16069. if (this.from.x < this.to.x) {
  16070. xVia = this.from.x + factor * dy;
  16071. yVia = this.from.y - factor * dy;
  16072. }
  16073. else if (this.from.x > this.to.x) {
  16074. xVia = this.from.x - factor * dy;
  16075. yVia = this.from.y - factor * dy;
  16076. }
  16077. }
  16078. else if (this.from.y < this.to.y) {
  16079. if (this.from.x < this.to.x) {
  16080. xVia = this.from.x + factor * dy;
  16081. yVia = this.from.y + factor * dy;
  16082. }
  16083. else if (this.from.x > this.to.x) {
  16084. xVia = this.from.x - factor * dy;
  16085. yVia = this.from.y + factor * dy;
  16086. }
  16087. }
  16088. if (type == "discrete") {
  16089. xVia = dx < factor * dy ? this.from.x : xVia;
  16090. }
  16091. }
  16092. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  16093. if (this.from.y > this.to.y) {
  16094. if (this.from.x < this.to.x) {
  16095. xVia = this.from.x + factor * dx;
  16096. yVia = this.from.y - factor * dx;
  16097. }
  16098. else if (this.from.x > this.to.x) {
  16099. xVia = this.from.x - factor * dx;
  16100. yVia = this.from.y - factor * dx;
  16101. }
  16102. }
  16103. else if (this.from.y < this.to.y) {
  16104. if (this.from.x < this.to.x) {
  16105. xVia = this.from.x + factor * dx;
  16106. yVia = this.from.y + factor * dx;
  16107. }
  16108. else if (this.from.x > this.to.x) {
  16109. xVia = this.from.x - factor * dx;
  16110. yVia = this.from.y + factor * dx;
  16111. }
  16112. }
  16113. if (type == "discrete") {
  16114. yVia = dy < factor * dx ? this.from.y : yVia;
  16115. }
  16116. }
  16117. }
  16118. else if (type == "straightCross") {
  16119. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down
  16120. xVia = this.from.x;
  16121. if (this.from.y < this.to.y) {
  16122. yVia = this.to.y - (1-factor) * dy;
  16123. }
  16124. else {
  16125. yVia = this.to.y + (1-factor) * dy;
  16126. }
  16127. }
  16128. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right
  16129. if (this.from.x < this.to.x) {
  16130. xVia = this.to.x - (1-factor) * dx;
  16131. }
  16132. else {
  16133. xVia = this.to.x + (1-factor) * dx;
  16134. }
  16135. yVia = this.from.y;
  16136. }
  16137. }
  16138. else if (type == 'horizontal') {
  16139. if (this.from.x < this.to.x) {
  16140. xVia = this.to.x - (1-factor) * dx;
  16141. }
  16142. else {
  16143. xVia = this.to.x + (1-factor) * dx;
  16144. }
  16145. yVia = this.from.y;
  16146. }
  16147. else if (type == 'vertical') {
  16148. xVia = this.from.x;
  16149. if (this.from.y < this.to.y) {
  16150. yVia = this.to.y - (1-factor) * dy;
  16151. }
  16152. else {
  16153. yVia = this.to.y + (1-factor) * dy;
  16154. }
  16155. }
  16156. else { // continuous
  16157. if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
  16158. if (this.from.y > this.to.y) {
  16159. if (this.from.x < this.to.x) {
  16160. // console.log(1)
  16161. xVia = this.from.x + factor * dy;
  16162. yVia = this.from.y - factor * dy;
  16163. xVia = this.to.x < xVia ? this.to.x : xVia;
  16164. }
  16165. else if (this.from.x > this.to.x) {
  16166. // console.log(2)
  16167. xVia = this.from.x - factor * dy;
  16168. yVia = this.from.y - factor * dy;
  16169. xVia = this.to.x > xVia ? this.to.x :xVia;
  16170. }
  16171. }
  16172. else if (this.from.y < this.to.y) {
  16173. if (this.from.x < this.to.x) {
  16174. // console.log(3)
  16175. xVia = this.from.x + factor * dy;
  16176. yVia = this.from.y + factor * dy;
  16177. xVia = this.to.x < xVia ? this.to.x : xVia;
  16178. }
  16179. else if (this.from.x > this.to.x) {
  16180. // console.log(4, this.from.x, this.to.x)
  16181. xVia = this.from.x - factor * dy;
  16182. yVia = this.from.y + factor * dy;
  16183. xVia = this.to.x > xVia ? this.to.x : xVia;
  16184. }
  16185. }
  16186. }
  16187. else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  16188. if (this.from.y > this.to.y) {
  16189. if (this.from.x < this.to.x) {
  16190. // console.log(5)
  16191. xVia = this.from.x + factor * dx;
  16192. yVia = this.from.y - factor * dx;
  16193. yVia = this.to.y > yVia ? this.to.y : yVia;
  16194. }
  16195. else if (this.from.x > this.to.x) {
  16196. // console.log(6)
  16197. xVia = this.from.x - factor * dx;
  16198. yVia = this.from.y - factor * dx;
  16199. yVia = this.to.y > yVia ? this.to.y : yVia;
  16200. }
  16201. }
  16202. else if (this.from.y < this.to.y) {
  16203. if (this.from.x < this.to.x) {
  16204. // console.log(7)
  16205. xVia = this.from.x + factor * dx;
  16206. yVia = this.from.y + factor * dx;
  16207. yVia = this.to.y < yVia ? this.to.y : yVia;
  16208. }
  16209. else if (this.from.x > this.to.x) {
  16210. // console.log(8)
  16211. xVia = this.from.x - factor * dx;
  16212. yVia = this.from.y + factor * dx;
  16213. yVia = this.to.y < yVia ? this.to.y : yVia;
  16214. }
  16215. }
  16216. }
  16217. }
  16218. return {x:xVia, y:yVia};
  16219. };
  16220. /**
  16221. * Draw a line between two nodes
  16222. * @param {CanvasRenderingContext2D} ctx
  16223. * @private
  16224. */
  16225. Edge.prototype._line = function (ctx) {
  16226. // draw a straight line
  16227. ctx.beginPath();
  16228. ctx.moveTo(this.from.x, this.from.y);
  16229. if (this.options.smoothCurves.enabled == true) {
  16230. if (this.options.smoothCurves.dynamic == false) {
  16231. var via = this._getViaCoordinates();
  16232. if (via.x == null) {
  16233. ctx.lineTo(this.to.x, this.to.y);
  16234. ctx.stroke();
  16235. return null;
  16236. }
  16237. else {
  16238. // this.via.x = via.x;
  16239. // this.via.y = via.y;
  16240. ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y);
  16241. ctx.stroke();
  16242. return via;
  16243. }
  16244. }
  16245. else {
  16246. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  16247. ctx.stroke();
  16248. return this.via;
  16249. }
  16250. }
  16251. else {
  16252. ctx.lineTo(this.to.x, this.to.y);
  16253. ctx.stroke();
  16254. return null;
  16255. }
  16256. };
  16257. /**
  16258. * Draw a line from a node to itself, a circle
  16259. * @param {CanvasRenderingContext2D} ctx
  16260. * @param {Number} x
  16261. * @param {Number} y
  16262. * @param {Number} radius
  16263. * @private
  16264. */
  16265. Edge.prototype._circle = function (ctx, x, y, radius) {
  16266. // draw a circle
  16267. ctx.beginPath();
  16268. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  16269. ctx.stroke();
  16270. };
  16271. /**
  16272. * Draw label with white background and with the middle at (x, y)
  16273. * @param {CanvasRenderingContext2D} ctx
  16274. * @param {String} text
  16275. * @param {Number} x
  16276. * @param {Number} y
  16277. * @private
  16278. */
  16279. Edge.prototype._label = function (ctx, text, x, y) {
  16280. if (text) {
  16281. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  16282. this.options.fontSize + "px " + this.options.fontFace;
  16283. var yLine;
  16284. if (this.dirtyLabel == true) {
  16285. var lines = String(text).split('\n');
  16286. var lineCount = lines.length;
  16287. var fontSize = (Number(this.options.fontSize) + 4);
  16288. yLine = y + (1 - lineCount) / 2 * fontSize;
  16289. var width = ctx.measureText(lines[0]).width;
  16290. for (var i = 1; i < lineCount; i++) {
  16291. var lineWidth = ctx.measureText(lines[i]).width;
  16292. width = lineWidth > width ? lineWidth : width;
  16293. }
  16294. var height = this.options.fontSize * lineCount;
  16295. var left = x - width / 2;
  16296. var top = y - height / 2;
  16297. // cache
  16298. this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
  16299. }
  16300. if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
  16301. ctx.fillStyle = this.options.fontFill;
  16302. ctx.fillRect(this.labelDimensions.left,
  16303. this.labelDimensions.top,
  16304. this.labelDimensions.width,
  16305. this.labelDimensions.height);
  16306. }
  16307. // draw text
  16308. ctx.fillStyle = this.options.fontColor || "black";
  16309. ctx.textAlign = "center";
  16310. ctx.textBaseline = "middle";
  16311. yLine = this.labelDimensions.yLine;
  16312. for (var i = 0; i < lineCount; i++) {
  16313. ctx.fillText(lines[i], x, yLine);
  16314. yLine += fontSize;
  16315. }
  16316. }
  16317. };
  16318. /**
  16319. * Redraw a edge as a dashed line
  16320. * Draw this edge in the given canvas
  16321. * @author David Jordan
  16322. * @date 2012-08-08
  16323. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  16324. * @param {CanvasRenderingContext2D} ctx
  16325. * @private
  16326. */
  16327. Edge.prototype._drawDashLine = function(ctx) {
  16328. // set style
  16329. ctx.strokeStyle = this._getColor();
  16330. ctx.lineWidth = this._getLineWidth();
  16331. var via = null;
  16332. // only firefox and chrome support this method, else we use the legacy one.
  16333. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  16334. // configure the dash pattern
  16335. var pattern = [0];
  16336. if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) {
  16337. pattern = [this.options.dash.length,this.options.dash.gap];
  16338. }
  16339. else {
  16340. pattern = [5,5];
  16341. }
  16342. // set dash settings for chrome or firefox
  16343. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  16344. ctx.setLineDash(pattern);
  16345. ctx.lineDashOffset = 0;
  16346. } else { //Firefox
  16347. ctx.mozDash = pattern;
  16348. ctx.mozDashOffset = 0;
  16349. }
  16350. // draw the line
  16351. via = this._line(ctx);
  16352. // restore the dash settings.
  16353. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  16354. ctx.setLineDash([0]);
  16355. ctx.lineDashOffset = 0;
  16356. } else { //Firefox
  16357. ctx.mozDash = [0];
  16358. ctx.mozDashOffset = 0;
  16359. }
  16360. }
  16361. else { // unsupporting smooth lines
  16362. // draw dashed line
  16363. ctx.beginPath();
  16364. ctx.lineCap = 'round';
  16365. if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  16366. {
  16367. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  16368. [this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]);
  16369. }
  16370. 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
  16371. {
  16372. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  16373. [this.options.dash.length,this.options.dash.gap]);
  16374. }
  16375. else //If all else fails draw a line
  16376. {
  16377. ctx.moveTo(this.from.x, this.from.y);
  16378. ctx.lineTo(this.to.x, this.to.y);
  16379. }
  16380. ctx.stroke();
  16381. }
  16382. // draw label
  16383. if (this.label) {
  16384. var point;
  16385. if (this.options.smoothCurves.enabled == true && via != null) {
  16386. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  16387. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  16388. point = {x:midpointX, y:midpointY};
  16389. }
  16390. else {
  16391. point = this._pointOnLine(0.5);
  16392. }
  16393. this._label(ctx, this.label, point.x, point.y);
  16394. }
  16395. };
  16396. /**
  16397. * Get a point on a line
  16398. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  16399. * @return {Object} point
  16400. * @private
  16401. */
  16402. Edge.prototype._pointOnLine = function (percentage) {
  16403. return {
  16404. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  16405. y: (1 - percentage) * this.from.y + percentage * this.to.y
  16406. }
  16407. };
  16408. /**
  16409. * Get a point on a circle
  16410. * @param {Number} x
  16411. * @param {Number} y
  16412. * @param {Number} radius
  16413. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  16414. * @return {Object} point
  16415. * @private
  16416. */
  16417. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  16418. var angle = (percentage - 3/8) * 2 * Math.PI;
  16419. return {
  16420. x: x + radius * Math.cos(angle),
  16421. y: y - radius * Math.sin(angle)
  16422. }
  16423. };
  16424. /**
  16425. * Redraw a edge as a line with an arrow halfway the line
  16426. * Draw this edge in the given canvas
  16427. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  16428. * @param {CanvasRenderingContext2D} ctx
  16429. * @private
  16430. */
  16431. Edge.prototype._drawArrowCenter = function(ctx) {
  16432. var point;
  16433. // set style
  16434. ctx.strokeStyle = this._getColor();
  16435. ctx.fillStyle = ctx.strokeStyle;
  16436. ctx.lineWidth = this._getLineWidth();
  16437. if (this.from != this.to) {
  16438. // draw line
  16439. var via = this._line(ctx);
  16440. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  16441. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  16442. // draw an arrow halfway the line
  16443. if (this.options.smoothCurves.enabled == true && via != null) {
  16444. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  16445. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  16446. point = {x:midpointX, y:midpointY};
  16447. }
  16448. else {
  16449. point = this._pointOnLine(0.5);
  16450. }
  16451. ctx.arrow(point.x, point.y, angle, length);
  16452. ctx.fill();
  16453. ctx.stroke();
  16454. // draw label
  16455. if (this.label) {
  16456. this._label(ctx, this.label, point.x, point.y);
  16457. }
  16458. }
  16459. else {
  16460. // draw circle
  16461. var x, y;
  16462. var radius = 0.25 * Math.max(100,this.physics.springLength);
  16463. var node = this.from;
  16464. if (!node.width) {
  16465. node.resize(ctx);
  16466. }
  16467. if (node.width > node.height) {
  16468. x = node.x + node.width * 0.5;
  16469. y = node.y - radius;
  16470. }
  16471. else {
  16472. x = node.x + radius;
  16473. y = node.y - node.height * 0.5;
  16474. }
  16475. this._circle(ctx, x, y, radius);
  16476. // draw all arrows
  16477. var angle = 0.2 * Math.PI;
  16478. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  16479. point = this._pointOnCircle(x, y, radius, 0.5);
  16480. ctx.arrow(point.x, point.y, angle, length);
  16481. ctx.fill();
  16482. ctx.stroke();
  16483. // draw label
  16484. if (this.label) {
  16485. point = this._pointOnCircle(x, y, radius, 0.5);
  16486. this._label(ctx, this.label, point.x, point.y);
  16487. }
  16488. }
  16489. };
  16490. /**
  16491. * Redraw a edge as a line with an arrow
  16492. * Draw this edge in the given canvas
  16493. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  16494. * @param {CanvasRenderingContext2D} ctx
  16495. * @private
  16496. */
  16497. Edge.prototype._drawArrow = function(ctx) {
  16498. // set style
  16499. ctx.strokeStyle = this._getColor();
  16500. ctx.fillStyle = ctx.strokeStyle;
  16501. ctx.lineWidth = this._getLineWidth();
  16502. var angle, length;
  16503. //draw a line
  16504. if (this.from != this.to) {
  16505. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  16506. var dx = (this.to.x - this.from.x);
  16507. var dy = (this.to.y - this.from.y);
  16508. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  16509. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  16510. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  16511. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  16512. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  16513. var via;
  16514. if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) {
  16515. via = this.via;
  16516. }
  16517. else if (this.options.smoothCurves.enabled == true) {
  16518. via = this._getViaCoordinates();
  16519. }
  16520. if (this.options.smoothCurves.enabled == true && via.x != null) {
  16521. angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
  16522. dx = (this.to.x - via.x);
  16523. dy = (this.to.y - via.y);
  16524. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  16525. }
  16526. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  16527. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  16528. var xTo,yTo;
  16529. if (this.options.smoothCurves.enabled == true && via.x != null) {
  16530. xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
  16531. yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
  16532. }
  16533. else {
  16534. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  16535. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  16536. }
  16537. ctx.beginPath();
  16538. ctx.moveTo(xFrom,yFrom);
  16539. if (this.options.smoothCurves.enabled == true && via.x != null) {
  16540. ctx.quadraticCurveTo(via.x,via.y,xTo, yTo);
  16541. }
  16542. else {
  16543. ctx.lineTo(xTo, yTo);
  16544. }
  16545. ctx.stroke();
  16546. // draw arrow at the end of the line
  16547. length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  16548. ctx.arrow(xTo, yTo, angle, length);
  16549. ctx.fill();
  16550. ctx.stroke();
  16551. // draw label
  16552. if (this.label) {
  16553. var point;
  16554. if (this.options.smoothCurves.enabled == true && via != null) {
  16555. var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
  16556. var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
  16557. point = {x:midpointX, y:midpointY};
  16558. }
  16559. else {
  16560. point = this._pointOnLine(0.5);
  16561. }
  16562. this._label(ctx, this.label, point.x, point.y);
  16563. }
  16564. }
  16565. else {
  16566. // draw circle
  16567. var node = this.from;
  16568. var x, y, arrow;
  16569. var radius = 0.25 * Math.max(100,this.physics.springLength);
  16570. if (!node.width) {
  16571. node.resize(ctx);
  16572. }
  16573. if (node.width > node.height) {
  16574. x = node.x + node.width * 0.5;
  16575. y = node.y - radius;
  16576. arrow = {
  16577. x: x,
  16578. y: node.y,
  16579. angle: 0.9 * Math.PI
  16580. };
  16581. }
  16582. else {
  16583. x = node.x + radius;
  16584. y = node.y - node.height * 0.5;
  16585. arrow = {
  16586. x: node.x,
  16587. y: y,
  16588. angle: 0.6 * Math.PI
  16589. };
  16590. }
  16591. ctx.beginPath();
  16592. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  16593. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  16594. ctx.stroke();
  16595. // draw all arrows
  16596. var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
  16597. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  16598. ctx.fill();
  16599. ctx.stroke();
  16600. // draw label
  16601. if (this.label) {
  16602. point = this._pointOnCircle(x, y, radius, 0.5);
  16603. this._label(ctx, this.label, point.x, point.y);
  16604. }
  16605. }
  16606. };
  16607. /**
  16608. * Calculate the distance between a point (x3,y3) and a line segment from
  16609. * (x1,y1) to (x2,y2).
  16610. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  16611. * @param {number} x1
  16612. * @param {number} y1
  16613. * @param {number} x2
  16614. * @param {number} y2
  16615. * @param {number} x3
  16616. * @param {number} y3
  16617. * @private
  16618. */
  16619. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  16620. var returnValue = 0;
  16621. if (this.from != this.to) {
  16622. if (this.options.smoothCurves.enabled == true) {
  16623. var xVia, yVia;
  16624. if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) {
  16625. xVia = this.via.x;
  16626. yVia = this.via.y;
  16627. }
  16628. else {
  16629. var via = this._getViaCoordinates();
  16630. xVia = via.x;
  16631. yVia = via.y;
  16632. }
  16633. var minDistance = 1e9;
  16634. var distance;
  16635. var i,t,x,y, lastX, lastY;
  16636. for (i = 0; i < 10; i++) {
  16637. t = 0.1*i;
  16638. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2;
  16639. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2;
  16640. if (i > 0) {
  16641. distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3);
  16642. minDistance = distance < minDistance ? distance : minDistance;
  16643. }
  16644. lastX = x; lastY = y;
  16645. }
  16646. returnValue = minDistance;
  16647. }
  16648. else {
  16649. returnValue = this._getDistanceToLine(x1,y1,x2,y2,x3,y3);
  16650. }
  16651. }
  16652. else {
  16653. var x, y, dx, dy;
  16654. var radius = 0.25 * this.physics.springLength;
  16655. var node = this.from;
  16656. if (node.width > node.height) {
  16657. x = node.x + 0.5 * node.width;
  16658. y = node.y - radius;
  16659. }
  16660. else {
  16661. x = node.x + radius;
  16662. y = node.y - 0.5 * node.height;
  16663. }
  16664. dx = x - x3;
  16665. dy = y - y3;
  16666. returnValue = Math.abs(Math.sqrt(dx*dx + dy*dy) - radius);
  16667. }
  16668. if (this.labelDimensions.left < x3 &&
  16669. this.labelDimensions.left + this.labelDimensions.width > x3 &&
  16670. this.labelDimensions.top < y3 &&
  16671. this.labelDimensions.top + this.labelDimensions.height > y3) {
  16672. return 0;
  16673. }
  16674. else {
  16675. return returnValue;
  16676. }
  16677. };
  16678. Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) {
  16679. var px = x2-x1,
  16680. py = y2-y1,
  16681. something = px*px + py*py,
  16682. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  16683. if (u > 1) {
  16684. u = 1;
  16685. }
  16686. else if (u < 0) {
  16687. u = 0;
  16688. }
  16689. var x = x1 + u * px,
  16690. y = y1 + u * py,
  16691. dx = x - x3,
  16692. dy = y - y3;
  16693. //# Note: If the actual distance does not matter,
  16694. //# if you only want to compare what this function
  16695. //# returns to other results of this function, you
  16696. //# can just return the squared distance instead
  16697. //# (i.e. remove the sqrt) to gain a little performance
  16698. return Math.sqrt(dx*dx + dy*dy);
  16699. };
  16700. /**
  16701. * This allows the zoom level of the network to influence the rendering
  16702. *
  16703. * @param scale
  16704. */
  16705. Edge.prototype.setScale = function(scale) {
  16706. this.networkScaleInv = 1.0/scale;
  16707. };
  16708. Edge.prototype.select = function() {
  16709. this.selected = true;
  16710. };
  16711. Edge.prototype.unselect = function() {
  16712. this.selected = false;
  16713. };
  16714. Edge.prototype.positionBezierNode = function() {
  16715. if (this.via !== null && this.from !== null && this.to !== null) {
  16716. this.via.x = 0.5 * (this.from.x + this.to.x);
  16717. this.via.y = 0.5 * (this.from.y + this.to.y);
  16718. }
  16719. else {
  16720. this.via.x = 0;
  16721. this.via.y = 0;
  16722. }
  16723. };
  16724. /**
  16725. * This function draws the control nodes for the manipulator.
  16726. * In order to enable this, only set the this.controlNodesEnabled to true.
  16727. * @param ctx
  16728. */
  16729. Edge.prototype._drawControlNodes = function(ctx) {
  16730. if (this.controlNodesEnabled == true) {
  16731. if (this.controlNodes.from === null && this.controlNodes.to === null) {
  16732. var nodeIdFrom = "edgeIdFrom:".concat(this.id);
  16733. var nodeIdTo = "edgeIdTo:".concat(this.id);
  16734. var constants = {
  16735. nodes:{group:'', radius:8},
  16736. physics:{damping:0},
  16737. clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}}
  16738. };
  16739. this.controlNodes.from = new Node(
  16740. {id:nodeIdFrom,
  16741. shape:'dot',
  16742. color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
  16743. },{},{},constants);
  16744. this.controlNodes.to = new Node(
  16745. {id:nodeIdTo,
  16746. shape:'dot',
  16747. color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
  16748. },{},{},constants);
  16749. }
  16750. if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) {
  16751. this.controlNodes.positions = this.getControlNodePositions(ctx);
  16752. this.controlNodes.from.x = this.controlNodes.positions.from.x;
  16753. this.controlNodes.from.y = this.controlNodes.positions.from.y;
  16754. this.controlNodes.to.x = this.controlNodes.positions.to.x;
  16755. this.controlNodes.to.y = this.controlNodes.positions.to.y;
  16756. }
  16757. this.controlNodes.from.draw(ctx);
  16758. this.controlNodes.to.draw(ctx);
  16759. }
  16760. else {
  16761. this.controlNodes = {from:null, to:null, positions:{}};
  16762. }
  16763. };
  16764. /**
  16765. * Enable control nodes.
  16766. * @private
  16767. */
  16768. Edge.prototype._enableControlNodes = function() {
  16769. this.fromBackup = this.from;
  16770. this.toBackup = this.to;
  16771. this.controlNodesEnabled = true;
  16772. };
  16773. /**
  16774. * disable control nodes and remove from dynamicEdges from old node
  16775. * @private
  16776. */
  16777. Edge.prototype._disableControlNodes = function() {
  16778. this.fromId = this.from.id;
  16779. this.toId = this.to.id;
  16780. if (this.fromId != this.fromBackup.id) { // from was changed, remove edge from old 'from' node dynamic edges
  16781. this.fromBackup.detachEdge(this);
  16782. }
  16783. else if (this.toId != this.toBackup.id) { // to was changed, remove edge from old 'to' node dynamic edges
  16784. this.toBackup.detachEdge(this);
  16785. }
  16786. this.fromBackup = null;
  16787. this.toBackup = null;
  16788. this.controlNodesEnabled = false;
  16789. };
  16790. /**
  16791. * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null.
  16792. * @param x
  16793. * @param y
  16794. * @returns {null}
  16795. * @private
  16796. */
  16797. Edge.prototype._getSelectedControlNode = function(x,y) {
  16798. var positions = this.controlNodes.positions;
  16799. var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2));
  16800. var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2));
  16801. if (fromDistance < 15) {
  16802. this.connectedNode = this.from;
  16803. this.from = this.controlNodes.from;
  16804. return this.controlNodes.from;
  16805. }
  16806. else if (toDistance < 15) {
  16807. this.connectedNode = this.to;
  16808. this.to = this.controlNodes.to;
  16809. return this.controlNodes.to;
  16810. }
  16811. else {
  16812. return null;
  16813. }
  16814. };
  16815. /**
  16816. * this resets the control nodes to their original position.
  16817. * @private
  16818. */
  16819. Edge.prototype._restoreControlNodes = function() {
  16820. if (this.controlNodes.from.selected == true) {
  16821. this.from = this.connectedNode;
  16822. this.connectedNode = null;
  16823. this.controlNodes.from.unselect();
  16824. }
  16825. else if (this.controlNodes.to.selected == true) {
  16826. this.to = this.connectedNode;
  16827. this.connectedNode = null;
  16828. this.controlNodes.to.unselect();
  16829. }
  16830. };
  16831. /**
  16832. * this calculates the position of the control nodes on the edges of the parent nodes.
  16833. *
  16834. * @param ctx
  16835. * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}}
  16836. */
  16837. Edge.prototype.getControlNodePositions = function(ctx) {
  16838. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  16839. var dx = (this.to.x - this.from.x);
  16840. var dy = (this.to.y - this.from.y);
  16841. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  16842. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  16843. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  16844. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  16845. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  16846. var via;
  16847. if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true) {
  16848. via = this.via;
  16849. }
  16850. else if (this.options.smoothCurves.enabled == true) {
  16851. via = this._getViaCoordinates();
  16852. }
  16853. if (this.options.smoothCurves.enabled == true && via.x != null) {
  16854. angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
  16855. dx = (this.to.x - via.x);
  16856. dy = (this.to.y - via.y);
  16857. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  16858. }
  16859. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  16860. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  16861. var xTo,yTo;
  16862. if (this.options.smoothCurves.enabled == true && via.x != null) {
  16863. xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
  16864. yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
  16865. }
  16866. else {
  16867. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  16868. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  16869. }
  16870. return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}};
  16871. };
  16872. module.exports = Edge;
  16873. /***/ },
  16874. /* 38 */
  16875. /***/ function(module, exports, __webpack_require__) {
  16876. var util = __webpack_require__(1);
  16877. /**
  16878. * @class Groups
  16879. * This class can store groups and properties specific for groups.
  16880. */
  16881. function Groups() {
  16882. this.clear();
  16883. this.defaultIndex = 0;
  16884. }
  16885. /**
  16886. * default constants for group colors
  16887. */
  16888. Groups.DEFAULT = [
  16889. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}, hover: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  16890. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}, hover: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  16891. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}, hover: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  16892. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}, hover: {border: "#41A906", background: "#A1EC76"}}, // green
  16893. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}, hover: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  16894. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}, hover: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  16895. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}, hover: {border: "#C37F00", background: "#FFCA66"}}, // orange
  16896. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}, hover: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  16897. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}, hover: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  16898. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}, hover: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  16899. ];
  16900. /**
  16901. * Clear all groups
  16902. */
  16903. Groups.prototype.clear = function () {
  16904. this.groups = {};
  16905. this.groups.length = function()
  16906. {
  16907. var i = 0;
  16908. for ( var p in this ) {
  16909. if (this.hasOwnProperty(p)) {
  16910. i++;
  16911. }
  16912. }
  16913. return i;
  16914. }
  16915. };
  16916. /**
  16917. * get group properties of a groupname. If groupname is not found, a new group
  16918. * is added.
  16919. * @param {*} groupname Can be a number, string, Date, etc.
  16920. * @return {Object} group The created group, containing all group properties
  16921. */
  16922. Groups.prototype.get = function (groupname) {
  16923. var group = this.groups[groupname];
  16924. if (group == undefined) {
  16925. // create new group
  16926. var index = this.defaultIndex % Groups.DEFAULT.length;
  16927. this.defaultIndex++;
  16928. group = {};
  16929. group.color = Groups.DEFAULT[index];
  16930. this.groups[groupname] = group;
  16931. }
  16932. return group;
  16933. };
  16934. /**
  16935. * Add a custom group style
  16936. * @param {String} groupname
  16937. * @param {Object} style An object containing borderColor,
  16938. * backgroundColor, etc.
  16939. * @return {Object} group The created group object
  16940. */
  16941. Groups.prototype.add = function (groupname, style) {
  16942. this.groups[groupname] = style;
  16943. return style;
  16944. };
  16945. module.exports = Groups;
  16946. /***/ },
  16947. /* 39 */
  16948. /***/ function(module, exports, __webpack_require__) {
  16949. /**
  16950. * @class Images
  16951. * This class loads images and keeps them stored.
  16952. */
  16953. function Images() {
  16954. this.images = {};
  16955. this.callback = undefined;
  16956. }
  16957. /**
  16958. * Set an onload callback function. This will be called each time an image
  16959. * is loaded
  16960. * @param {function} callback
  16961. */
  16962. Images.prototype.setOnloadCallback = function(callback) {
  16963. this.callback = callback;
  16964. };
  16965. /**
  16966. *
  16967. * @param {string} url Url of the image
  16968. * @param {string} url Url of an image to use if the url image is not found
  16969. * @return {Image} img The image object
  16970. */
  16971. Images.prototype.load = function(url, brokenUrl) {
  16972. if (this.images[url] == undefined) {
  16973. // create the image
  16974. var me = this;
  16975. var img = new Image();
  16976. img.onload = function () {
  16977. // IE11 fix -- thanks dponch!
  16978. if (this.width == 0) {
  16979. document.body.appendChild(this);
  16980. this.width = this.offsetWidth;
  16981. this.height = this.offsetHeight;
  16982. document.body.removeChild(this);
  16983. }
  16984. if (me.callback) {
  16985. me.images[url] = img;
  16986. me.callback(this);
  16987. }
  16988. };
  16989. img.onerror = function () {
  16990. if (brokenUrl === undefined) {
  16991. console.error("Could not load image:", url);
  16992. delete this.src;
  16993. if (me.callback) {
  16994. me.callback(this);
  16995. }
  16996. }
  16997. else {
  16998. this.src = brokenUrl;
  16999. }
  17000. };
  17001. img.src = url;
  17002. }
  17003. return img;
  17004. };
  17005. module.exports = Images;
  17006. /***/ },
  17007. /* 40 */
  17008. /***/ function(module, exports, __webpack_require__) {
  17009. var util = __webpack_require__(1);
  17010. /**
  17011. * @class Node
  17012. * A node. A node can be connected to other nodes via one or multiple edges.
  17013. * @param {object} properties An object containing properties for the node. All
  17014. * properties are optional, except for the id.
  17015. * {number} id Id of the node. Required
  17016. * {string} label Text label for the node
  17017. * {number} x Horizontal position of the node
  17018. * {number} y Vertical position of the node
  17019. * {string} shape Node shape, available:
  17020. * "database", "circle", "ellipse",
  17021. * "box", "image", "text", "dot",
  17022. * "star", "triangle", "triangleDown",
  17023. * "square"
  17024. * {string} image An image url
  17025. * {string} title An title text, can be HTML
  17026. * {anytype} group A group name or number
  17027. * @param {Network.Images} imagelist A list with images. Only needed
  17028. * when the node has an image
  17029. * @param {Network.Groups} grouplist A list with groups. Needed for
  17030. * retrieving group properties
  17031. * @param {Object} constants An object with default values for
  17032. * example for the color
  17033. *
  17034. */
  17035. function Node(properties, imagelist, grouplist, networkConstants) {
  17036. var constants = util.selectiveBridgeObject(['nodes'],networkConstants);
  17037. this.options = constants.nodes;
  17038. this.selected = false;
  17039. this.hover = false;
  17040. this.edges = []; // all edges connected to this node
  17041. this.dynamicEdges = [];
  17042. this.reroutedEdges = {};
  17043. this.fontDrawThreshold = 3;
  17044. // set defaults for the properties
  17045. this.id = undefined;
  17046. this.allowedToMoveX = false;
  17047. this.allowedToMoveY = false;
  17048. this.xFixed = false;
  17049. this.yFixed = false;
  17050. this.horizontalAlignLeft = true; // these are for the navigation controls
  17051. this.verticalAlignTop = true; // these are for the navigation controls
  17052. this.baseRadiusValue = networkConstants.nodes.radius;
  17053. this.radiusFixed = false;
  17054. this.level = -1;
  17055. this.preassignedLevel = false;
  17056. this.hierarchyEnumerated = false;
  17057. this.labelDimensions = {top:0, left:0, width:0, height:0, yLine:0}; // could be cached
  17058. this.boundingBox = {top:0, left:0, right:0, bottom:0};
  17059. this.imagelist = imagelist;
  17060. this.grouplist = grouplist;
  17061. // physics properties
  17062. this.fx = 0.0; // external force x
  17063. this.fy = 0.0; // external force y
  17064. this.vx = 0.0; // velocity x
  17065. this.vy = 0.0; // velocity y
  17066. this.x = null;
  17067. this.y = null;
  17068. // used for reverting to previous position on stabilization
  17069. this.previousState = {vx:0,vy:0,x:0,y:0};
  17070. this.damping = networkConstants.physics.damping; // written every time gravity is calculated
  17071. this.fixedData = {x:null,y:null};
  17072. this.setProperties(properties, constants);
  17073. // creating the variables for clustering
  17074. this.resetCluster();
  17075. this.dynamicEdgesLength = 0;
  17076. this.clusterSession = 0;
  17077. this.clusterSizeWidthFactor = networkConstants.clustering.nodeScaling.width;
  17078. this.clusterSizeHeightFactor = networkConstants.clustering.nodeScaling.height;
  17079. this.clusterSizeRadiusFactor = networkConstants.clustering.nodeScaling.radius;
  17080. this.maxNodeSizeIncrements = networkConstants.clustering.maxNodeSizeIncrements;
  17081. this.growthIndicator = 0;
  17082. // variables to tell the node about the network.
  17083. this.networkScaleInv = 1;
  17084. this.networkScale = 1;
  17085. this.canvasTopLeft = {"x": -300, "y": -300};
  17086. this.canvasBottomRight = {"x": 300, "y": 300};
  17087. this.parentEdgeId = null;
  17088. }
  17089. /**
  17090. * Revert the position and velocity of the previous step.
  17091. */
  17092. Node.prototype.revertPosition = function() {
  17093. this.x = this.previousState.x;
  17094. this.y = this.previousState.y;
  17095. this.vx = this.previousState.vx;
  17096. this.vy = this.previousState.vy;
  17097. }
  17098. /**
  17099. * (re)setting the clustering variables and objects
  17100. */
  17101. Node.prototype.resetCluster = function() {
  17102. // clustering variables
  17103. this.formationScale = undefined; // this is used to determine when to open the cluster
  17104. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  17105. this.containedNodes = {};
  17106. this.containedEdges = {};
  17107. this.clusterSessions = [];
  17108. };
  17109. /**
  17110. * Attach a edge to the node
  17111. * @param {Edge} edge
  17112. */
  17113. Node.prototype.attachEdge = function(edge) {
  17114. if (this.edges.indexOf(edge) == -1) {
  17115. this.edges.push(edge);
  17116. }
  17117. if (this.dynamicEdges.indexOf(edge) == -1) {
  17118. this.dynamicEdges.push(edge);
  17119. }
  17120. this.dynamicEdgesLength = this.dynamicEdges.length;
  17121. };
  17122. /**
  17123. * Detach a edge from the node
  17124. * @param {Edge} edge
  17125. */
  17126. Node.prototype.detachEdge = function(edge) {
  17127. var index = this.edges.indexOf(edge);
  17128. if (index != -1) {
  17129. this.edges.splice(index, 1);
  17130. }
  17131. index = this.dynamicEdges.indexOf(edge);
  17132. if (index != -1) {
  17133. this.dynamicEdges.splice(index, 1);
  17134. }
  17135. this.dynamicEdgesLength = this.dynamicEdges.length;
  17136. };
  17137. /**
  17138. * Set or overwrite properties for the node
  17139. * @param {Object} properties an object with properties
  17140. * @param {Object} constants and object with default, global properties
  17141. */
  17142. Node.prototype.setProperties = function(properties, constants) {
  17143. if (!properties) {
  17144. return;
  17145. }
  17146. var fields = ['borderWidth','borderWidthSelected','shape','image','brokenImage','radius','fontColor',
  17147. 'fontSize','fontFace','fontFill','group','mass'
  17148. ];
  17149. util.selectiveDeepExtend(fields, this.options, properties);
  17150. // basic properties
  17151. if (properties.id !== undefined) {this.id = properties.id;}
  17152. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  17153. if (properties.title !== undefined) {this.title = properties.title;}
  17154. if (properties.x !== undefined) {this.x = properties.x;}
  17155. if (properties.y !== undefined) {this.y = properties.y;}
  17156. if (properties.value !== undefined) {this.value = properties.value;}
  17157. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  17158. // navigation controls properties
  17159. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  17160. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  17161. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  17162. if (this.id === undefined) {
  17163. throw "Node must have an id";
  17164. }
  17165. // copy group properties
  17166. if (typeof this.options.group === 'number' || (typeof this.options.group === 'string' && this.options.group != '')) {
  17167. var groupObj = this.grouplist.get(this.options.group);
  17168. util.deepExtend(this.options, groupObj);
  17169. // the color object needs to be completely defined. Since groups can partially overwrite the colors, we parse it again, just in case.
  17170. this.options.color = util.parseColor(this.options.color);
  17171. }
  17172. else if (properties.color === undefined) {
  17173. this.options.color = constants.nodes.color;
  17174. }
  17175. // individual shape properties
  17176. if (properties.radius !== undefined) {this.baseRadiusValue = this.options.radius;}
  17177. if (properties.color !== undefined) {this.options.color = util.parseColor(properties.color);}
  17178. if (this.options.image !== undefined && this.options.image!= "") {
  17179. if (this.imagelist) {
  17180. this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage);
  17181. }
  17182. else {
  17183. throw "No imagelist provided";
  17184. }
  17185. }
  17186. if (properties.allowedToMoveX !== undefined) {
  17187. this.xFixed = !properties.allowedToMoveX;
  17188. this.allowedToMoveX = properties.allowedToMoveX;
  17189. }
  17190. else if (properties.x !== undefined && this.allowedToMoveX == false) {
  17191. this.xFixed = true;
  17192. }
  17193. if (properties.allowedToMoveY !== undefined) {
  17194. this.yFixed = !properties.allowedToMoveY;
  17195. this.allowedToMoveY = properties.allowedToMoveY;
  17196. }
  17197. else if (properties.y !== undefined && this.allowedToMoveY == false) {
  17198. this.yFixed = true;
  17199. }
  17200. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  17201. if (this.options.shape === 'image' || this.options.shape === 'circularImage') {
  17202. this.options.radiusMin = constants.nodes.widthMin;
  17203. this.options.radiusMax = constants.nodes.widthMax;
  17204. }
  17205. // choose draw method depending on the shape
  17206. switch (this.options.shape) {
  17207. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  17208. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  17209. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  17210. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  17211. // TODO: add diamond shape
  17212. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  17213. case 'circularImage': this.draw = this._drawCircularImage; this.resize = this._resizeCircularImage; break;
  17214. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  17215. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  17216. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  17217. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  17218. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  17219. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  17220. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  17221. }
  17222. // reset the size of the node, this can be changed
  17223. this._reset();
  17224. };
  17225. /**
  17226. * select this node
  17227. */
  17228. Node.prototype.select = function() {
  17229. this.selected = true;
  17230. this._reset();
  17231. };
  17232. /**
  17233. * unselect this node
  17234. */
  17235. Node.prototype.unselect = function() {
  17236. this.selected = false;
  17237. this._reset();
  17238. };
  17239. /**
  17240. * Reset the calculated size of the node, forces it to recalculate its size
  17241. */
  17242. Node.prototype.clearSizeCache = function() {
  17243. this._reset();
  17244. };
  17245. /**
  17246. * Reset the calculated size of the node, forces it to recalculate its size
  17247. * @private
  17248. */
  17249. Node.prototype._reset = function() {
  17250. this.width = undefined;
  17251. this.height = undefined;
  17252. };
  17253. /**
  17254. * get the title of this node.
  17255. * @return {string} title The title of the node, or undefined when no title
  17256. * has been set.
  17257. */
  17258. Node.prototype.getTitle = function() {
  17259. return typeof this.title === "function" ? this.title() : this.title;
  17260. };
  17261. /**
  17262. * Calculate the distance to the border of the Node
  17263. * @param {CanvasRenderingContext2D} ctx
  17264. * @param {Number} angle Angle in radians
  17265. * @returns {number} distance Distance to the border in pixels
  17266. */
  17267. Node.prototype.distanceToBorder = function (ctx, angle) {
  17268. var borderWidth = 1;
  17269. if (!this.width) {
  17270. this.resize(ctx);
  17271. }
  17272. switch (this.options.shape) {
  17273. case 'circle':
  17274. case 'dot':
  17275. return this.options.radius+ borderWidth;
  17276. case 'ellipse':
  17277. var a = this.width / 2;
  17278. var b = this.height / 2;
  17279. var w = (Math.sin(angle) * a);
  17280. var h = (Math.cos(angle) * b);
  17281. return a * b / Math.sqrt(w * w + h * h);
  17282. // TODO: implement distanceToBorder for database
  17283. // TODO: implement distanceToBorder for triangle
  17284. // TODO: implement distanceToBorder for triangleDown
  17285. case 'box':
  17286. case 'image':
  17287. case 'text':
  17288. default:
  17289. if (this.width) {
  17290. return Math.min(
  17291. Math.abs(this.width / 2 / Math.cos(angle)),
  17292. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  17293. // TODO: reckon with border radius too in case of box
  17294. }
  17295. else {
  17296. return 0;
  17297. }
  17298. }
  17299. // TODO: implement calculation of distance to border for all shapes
  17300. };
  17301. /**
  17302. * Set forces acting on the node
  17303. * @param {number} fx Force in horizontal direction
  17304. * @param {number} fy Force in vertical direction
  17305. */
  17306. Node.prototype._setForce = function(fx, fy) {
  17307. this.fx = fx;
  17308. this.fy = fy;
  17309. };
  17310. /**
  17311. * Add forces acting on the node
  17312. * @param {number} fx Force in horizontal direction
  17313. * @param {number} fy Force in vertical direction
  17314. * @private
  17315. */
  17316. Node.prototype._addForce = function(fx, fy) {
  17317. this.fx += fx;
  17318. this.fy += fy;
  17319. };
  17320. /**
  17321. * Store the state before the next step
  17322. */
  17323. Node.prototype.storeState = function() {
  17324. this.previousState.x = this.x;
  17325. this.previousState.y = this.y;
  17326. this.previousState.vx = this.vx;
  17327. this.previousState.vy = this.vy;
  17328. }
  17329. /**
  17330. * Perform one discrete step for the node
  17331. * @param {number} interval Time interval in seconds
  17332. */
  17333. Node.prototype.discreteStep = function(interval) {
  17334. this.storeState();
  17335. if (!this.xFixed) {
  17336. var dx = this.damping * this.vx; // damping force
  17337. var ax = (this.fx - dx) / this.options.mass; // acceleration
  17338. this.vx += ax * interval; // velocity
  17339. this.x += this.vx * interval; // position
  17340. }
  17341. else {
  17342. this.fx = 0;
  17343. this.vx = 0;
  17344. }
  17345. if (!this.yFixed) {
  17346. var dy = this.damping * this.vy; // damping force
  17347. var ay = (this.fy - dy) / this.options.mass; // acceleration
  17348. this.vy += ay * interval; // velocity
  17349. this.y += this.vy * interval; // position
  17350. }
  17351. else {
  17352. this.fy = 0;
  17353. this.vy = 0;
  17354. }
  17355. };
  17356. /**
  17357. * Perform one discrete step for the node
  17358. * @param {number} interval Time interval in seconds
  17359. * @param {number} maxVelocity The speed limit imposed on the velocity
  17360. */
  17361. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  17362. this.storeState();
  17363. if (!this.xFixed) {
  17364. var dx = this.damping * this.vx; // damping force
  17365. var ax = (this.fx - dx) / this.options.mass; // acceleration
  17366. this.vx += ax * interval; // velocity
  17367. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  17368. this.x += this.vx * interval; // position
  17369. }
  17370. else {
  17371. this.fx = 0;
  17372. this.vx = 0;
  17373. }
  17374. if (!this.yFixed) {
  17375. var dy = this.damping * this.vy; // damping force
  17376. var ay = (this.fy - dy) / this.options.mass; // acceleration
  17377. this.vy += ay * interval; // velocity
  17378. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  17379. this.y += this.vy * interval; // position
  17380. }
  17381. else {
  17382. this.fy = 0;
  17383. this.vy = 0;
  17384. }
  17385. };
  17386. /**
  17387. * Check if this node has a fixed x and y position
  17388. * @return {boolean} true if fixed, false if not
  17389. */
  17390. Node.prototype.isFixed = function() {
  17391. return (this.xFixed && this.yFixed);
  17392. };
  17393. /**
  17394. * Check if this node is moving
  17395. * @param {number} vmin the minimum velocity considered as "moving"
  17396. * @return {boolean} true if moving, false if it has no velocity
  17397. */
  17398. Node.prototype.isMoving = function(vmin) {
  17399. var velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2));
  17400. // this.velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2))
  17401. return (velocity > vmin);
  17402. };
  17403. /**
  17404. * check if this node is selecte
  17405. * @return {boolean} selected True if node is selected, else false
  17406. */
  17407. Node.prototype.isSelected = function() {
  17408. return this.selected;
  17409. };
  17410. /**
  17411. * Retrieve the value of the node. Can be undefined
  17412. * @return {Number} value
  17413. */
  17414. Node.prototype.getValue = function() {
  17415. return this.value;
  17416. };
  17417. /**
  17418. * Calculate the distance from the nodes location to the given location (x,y)
  17419. * @param {Number} x
  17420. * @param {Number} y
  17421. * @return {Number} value
  17422. */
  17423. Node.prototype.getDistance = function(x, y) {
  17424. var dx = this.x - x,
  17425. dy = this.y - y;
  17426. return Math.sqrt(dx * dx + dy * dy);
  17427. };
  17428. /**
  17429. * Adjust the value range of the node. The node will adjust it's radius
  17430. * based on its value.
  17431. * @param {Number} min
  17432. * @param {Number} max
  17433. */
  17434. Node.prototype.setValueRange = function(min, max) {
  17435. if (!this.radiusFixed && this.value !== undefined) {
  17436. if (max == min) {
  17437. this.options.radius= (this.options.radiusMin + this.options.radiusMax) / 2;
  17438. }
  17439. else {
  17440. var scale = (this.options.radiusMax - this.options.radiusMin) / (max - min);
  17441. this.options.radius= (this.value - min) * scale + this.options.radiusMin;
  17442. }
  17443. }
  17444. this.baseRadiusValue = this.options.radius;
  17445. };
  17446. /**
  17447. * Draw this node in the given canvas
  17448. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  17449. * @param {CanvasRenderingContext2D} ctx
  17450. */
  17451. Node.prototype.draw = function(ctx) {
  17452. throw "Draw method not initialized for node";
  17453. };
  17454. /**
  17455. * Recalculate the size of this node in the given canvas
  17456. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  17457. * @param {CanvasRenderingContext2D} ctx
  17458. */
  17459. Node.prototype.resize = function(ctx) {
  17460. throw "Resize method not initialized for node";
  17461. };
  17462. /**
  17463. * Check if this object is overlapping with the provided object
  17464. * @param {Object} obj an object with parameters left, top, right, bottom
  17465. * @return {boolean} True if location is located on node
  17466. */
  17467. Node.prototype.isOverlappingWith = function(obj) {
  17468. return (this.left < obj.right &&
  17469. this.left + this.width > obj.left &&
  17470. this.top < obj.bottom &&
  17471. this.top + this.height > obj.top);
  17472. };
  17473. Node.prototype._resizeImage = function (ctx) {
  17474. // TODO: pre calculate the image size
  17475. if (!this.width || !this.height) { // undefined or 0
  17476. var width, height;
  17477. if (this.value) {
  17478. this.options.radius= this.baseRadiusValue;
  17479. var scale = this.imageObj.height / this.imageObj.width;
  17480. if (scale !== undefined) {
  17481. width = this.options.radius|| this.imageObj.width;
  17482. height = this.options.radius* scale || this.imageObj.height;
  17483. }
  17484. else {
  17485. width = 0;
  17486. height = 0;
  17487. }
  17488. }
  17489. else {
  17490. width = this.imageObj.width;
  17491. height = this.imageObj.height;
  17492. }
  17493. this.width = width;
  17494. this.height = height;
  17495. this.growthIndicator = 0;
  17496. if (this.width > 0 && this.height > 0) {
  17497. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  17498. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  17499. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  17500. this.growthIndicator = this.width - width;
  17501. }
  17502. }
  17503. };
  17504. Node.prototype._drawImageAtPosition = function (ctx) {
  17505. if (this.imageObj.width != 0 ) {
  17506. // draw the shade
  17507. if (this.clusterSize > 1) {
  17508. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  17509. lineWidth *= this.networkScaleInv;
  17510. lineWidth = Math.min(0.2 * this.width,lineWidth);
  17511. ctx.globalAlpha = 0.5;
  17512. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  17513. }
  17514. // draw the image
  17515. ctx.globalAlpha = 1.0;
  17516. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  17517. }
  17518. };
  17519. Node.prototype._drawImageLabel = function (ctx) {
  17520. var yLabel;
  17521. if (this.imageObj.width != 0 ) {
  17522. yLabel = this.y + this.height / 2;
  17523. }
  17524. else {
  17525. // image still loading... just draw the label for now
  17526. yLabel = this.y;
  17527. }
  17528. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  17529. };
  17530. Node.prototype._drawImage = function (ctx) {
  17531. this._resizeImage(ctx);
  17532. this.left = this.x - this.width / 2;
  17533. this.top = this.y - this.height / 2;
  17534. this._drawImageAtPosition(ctx);
  17535. this.boundingBox.top = this.top;
  17536. this.boundingBox.left = this.left;
  17537. this.boundingBox.right = this.left + this.width;
  17538. this.boundingBox.bottom = this.top + this.height;
  17539. this._drawImageLabel(ctx);
  17540. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelDimensions.left);
  17541. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelDimensions.left + this.labelDimensions.width);
  17542. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelDimensions.height);
  17543. };
  17544. Node.prototype._resizeCircularImage = function (ctx) {
  17545. this._resizeImage(ctx);
  17546. };
  17547. Node.prototype._drawCircularImage = function (ctx) {
  17548. this._resizeCircularImage(ctx);
  17549. this.left = this.x - this.width / 2;
  17550. this.top = this.y - this.height / 2;
  17551. var centerX = this.left + (this.width / 2);
  17552. var centerY = this.top + (this.height / 2);
  17553. var radius = Math.abs(this.height / 2);
  17554. this._drawRawCircle(ctx, centerX, centerY, radius);
  17555. ctx.save();
  17556. ctx.circle(this.x, this.y, radius);
  17557. ctx.stroke();
  17558. ctx.clip();
  17559. this._drawImageAtPosition(ctx);
  17560. ctx.restore();
  17561. this.boundingBox.top = this.y - this.options.radius;
  17562. this.boundingBox.left = this.x - this.options.radius;
  17563. this.boundingBox.right = this.x + this.options.radius;
  17564. this.boundingBox.bottom = this.y + this.options.radius;
  17565. this._drawImageLabel(ctx);
  17566. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelDimensions.left);
  17567. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelDimensions.left + this.labelDimensions.width);
  17568. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelDimensions.height);
  17569. };
  17570. Node.prototype._resizeBox = function (ctx) {
  17571. if (!this.width) {
  17572. var margin = 5;
  17573. var textSize = this.getTextSize(ctx);
  17574. this.width = textSize.width + 2 * margin;
  17575. this.height = textSize.height + 2 * margin;
  17576. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  17577. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  17578. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  17579. // this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  17580. }
  17581. };
  17582. Node.prototype._drawBox = function (ctx) {
  17583. this._resizeBox(ctx);
  17584. this.left = this.x - this.width / 2;
  17585. this.top = this.y - this.height / 2;
  17586. var clusterLineWidth = 2.5;
  17587. var borderWidth = this.options.borderWidth;
  17588. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  17589. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  17590. // draw the outer border
  17591. if (this.clusterSize > 1) {
  17592. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  17593. ctx.lineWidth *= this.networkScaleInv;
  17594. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  17595. 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);
  17596. ctx.stroke();
  17597. }
  17598. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  17599. ctx.lineWidth *= this.networkScaleInv;
  17600. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  17601. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  17602. ctx.roundRect(this.left, this.top, this.width, this.height, this.options.radius);
  17603. ctx.fill();
  17604. ctx.stroke();
  17605. this.boundingBox.top = this.top;
  17606. this.boundingBox.left = this.left;
  17607. this.boundingBox.right = this.left + this.width;
  17608. this.boundingBox.bottom = this.top + this.height;
  17609. this._label(ctx, this.label, this.x, this.y);
  17610. };
  17611. Node.prototype._resizeDatabase = function (ctx) {
  17612. if (!this.width) {
  17613. var margin = 5;
  17614. var textSize = this.getTextSize(ctx);
  17615. var size = textSize.width + 2 * margin;
  17616. this.width = size;
  17617. this.height = size;
  17618. // scaling used for clustering
  17619. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  17620. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  17621. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  17622. this.growthIndicator = this.width - size;
  17623. }
  17624. };
  17625. Node.prototype._drawDatabase = function (ctx) {
  17626. this._resizeDatabase(ctx);
  17627. this.left = this.x - this.width / 2;
  17628. this.top = this.y - this.height / 2;
  17629. var clusterLineWidth = 2.5;
  17630. var borderWidth = this.options.borderWidth;
  17631. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  17632. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  17633. // draw the outer border
  17634. if (this.clusterSize > 1) {
  17635. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  17636. ctx.lineWidth *= this.networkScaleInv;
  17637. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  17638. 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);
  17639. ctx.stroke();
  17640. }
  17641. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  17642. ctx.lineWidth *= this.networkScaleInv;
  17643. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  17644. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  17645. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  17646. ctx.fill();
  17647. ctx.stroke();
  17648. this.boundingBox.top = this.top;
  17649. this.boundingBox.left = this.left;
  17650. this.boundingBox.right = this.left + this.width;
  17651. this.boundingBox.bottom = this.top + this.height;
  17652. this._label(ctx, this.label, this.x, this.y);
  17653. };
  17654. Node.prototype._resizeCircle = function (ctx) {
  17655. if (!this.width) {
  17656. var margin = 5;
  17657. var textSize = this.getTextSize(ctx);
  17658. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  17659. this.options.radius = diameter / 2;
  17660. this.width = diameter;
  17661. this.height = diameter;
  17662. // scaling used for clustering
  17663. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  17664. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  17665. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  17666. this.growthIndicator = this.options.radius- 0.5*diameter;
  17667. }
  17668. };
  17669. Node.prototype._drawRawCircle = function (ctx, x, y, radius) {
  17670. var clusterLineWidth = 2.5;
  17671. var borderWidth = this.options.borderWidth;
  17672. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  17673. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  17674. // draw the outer border
  17675. if (this.clusterSize > 1) {
  17676. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  17677. ctx.lineWidth *= this.networkScaleInv;
  17678. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  17679. ctx.circle(x, y, radius+2*ctx.lineWidth);
  17680. ctx.stroke();
  17681. }
  17682. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  17683. ctx.lineWidth *= this.networkScaleInv;
  17684. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  17685. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  17686. ctx.circle(this.x, this.y, radius);
  17687. ctx.fill();
  17688. ctx.stroke();
  17689. };
  17690. Node.prototype._drawCircle = function (ctx) {
  17691. this._resizeCircle(ctx);
  17692. this.left = this.x - this.width / 2;
  17693. this.top = this.y - this.height / 2;
  17694. this._drawRawCircle(ctx, this.x, this.y, this.options.radius);
  17695. this.boundingBox.top = this.y - this.options.radius;
  17696. this.boundingBox.left = this.x - this.options.radius;
  17697. this.boundingBox.right = this.x + this.options.radius;
  17698. this.boundingBox.bottom = this.y + this.options.radius;
  17699. this._label(ctx, this.label, this.x, this.y);
  17700. };
  17701. Node.prototype._resizeEllipse = function (ctx) {
  17702. if (!this.width) {
  17703. var textSize = this.getTextSize(ctx);
  17704. this.width = textSize.width * 1.5;
  17705. this.height = textSize.height * 2;
  17706. if (this.width < this.height) {
  17707. this.width = this.height;
  17708. }
  17709. var defaultSize = this.width;
  17710. // scaling used for clustering
  17711. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  17712. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  17713. this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  17714. this.growthIndicator = this.width - defaultSize;
  17715. }
  17716. };
  17717. Node.prototype._drawEllipse = function (ctx) {
  17718. this._resizeEllipse(ctx);
  17719. this.left = this.x - this.width / 2;
  17720. this.top = this.y - this.height / 2;
  17721. var clusterLineWidth = 2.5;
  17722. var borderWidth = this.options.borderWidth;
  17723. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  17724. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  17725. // draw the outer border
  17726. if (this.clusterSize > 1) {
  17727. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  17728. ctx.lineWidth *= this.networkScaleInv;
  17729. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  17730. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  17731. ctx.stroke();
  17732. }
  17733. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  17734. ctx.lineWidth *= this.networkScaleInv;
  17735. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  17736. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  17737. ctx.ellipse(this.left, this.top, this.width, this.height);
  17738. ctx.fill();
  17739. ctx.stroke();
  17740. this.boundingBox.top = this.top;
  17741. this.boundingBox.left = this.left;
  17742. this.boundingBox.right = this.left + this.width;
  17743. this.boundingBox.bottom = this.top + this.height;
  17744. this._label(ctx, this.label, this.x, this.y);
  17745. };
  17746. Node.prototype._drawDot = function (ctx) {
  17747. this._drawShape(ctx, 'circle');
  17748. };
  17749. Node.prototype._drawTriangle = function (ctx) {
  17750. this._drawShape(ctx, 'triangle');
  17751. };
  17752. Node.prototype._drawTriangleDown = function (ctx) {
  17753. this._drawShape(ctx, 'triangleDown');
  17754. };
  17755. Node.prototype._drawSquare = function (ctx) {
  17756. this._drawShape(ctx, 'square');
  17757. };
  17758. Node.prototype._drawStar = function (ctx) {
  17759. this._drawShape(ctx, 'star');
  17760. };
  17761. Node.prototype._resizeShape = function (ctx) {
  17762. if (!this.width) {
  17763. this.options.radius= this.baseRadiusValue;
  17764. var size = 2 * this.options.radius;
  17765. this.width = size;
  17766. this.height = size;
  17767. // scaling used for clustering
  17768. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  17769. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  17770. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  17771. this.growthIndicator = this.width - size;
  17772. }
  17773. };
  17774. Node.prototype._drawShape = function (ctx, shape) {
  17775. this._resizeShape(ctx);
  17776. this.left = this.x - this.width / 2;
  17777. this.top = this.y - this.height / 2;
  17778. var clusterLineWidth = 2.5;
  17779. var borderWidth = this.options.borderWidth;
  17780. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  17781. var radiusMultiplier = 2;
  17782. // choose draw method depending on the shape
  17783. switch (shape) {
  17784. case 'dot': radiusMultiplier = 2; break;
  17785. case 'square': radiusMultiplier = 2; break;
  17786. case 'triangle': radiusMultiplier = 3; break;
  17787. case 'triangleDown': radiusMultiplier = 3; break;
  17788. case 'star': radiusMultiplier = 4; break;
  17789. }
  17790. ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border;
  17791. // draw the outer border
  17792. if (this.clusterSize > 1) {
  17793. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  17794. ctx.lineWidth *= this.networkScaleInv;
  17795. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  17796. ctx[shape](this.x, this.y, this.options.radius+ radiusMultiplier * ctx.lineWidth);
  17797. ctx.stroke();
  17798. }
  17799. ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  17800. ctx.lineWidth *= this.networkScaleInv;
  17801. ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
  17802. ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background;
  17803. ctx[shape](this.x, this.y, this.options.radius);
  17804. ctx.fill();
  17805. ctx.stroke();
  17806. this.boundingBox.top = this.y - this.options.radius;
  17807. this.boundingBox.left = this.x - this.options.radius;
  17808. this.boundingBox.right = this.x + this.options.radius;
  17809. this.boundingBox.bottom = this.y + this.options.radius;
  17810. if (this.label) {
  17811. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top',true);
  17812. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelDimensions.left);
  17813. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelDimensions.left + this.labelDimensions.width);
  17814. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelDimensions.height);
  17815. }
  17816. };
  17817. Node.prototype._resizeText = function (ctx) {
  17818. if (!this.width) {
  17819. var margin = 5;
  17820. var textSize = this.getTextSize(ctx);
  17821. this.width = textSize.width + 2 * margin;
  17822. this.height = textSize.height + 2 * margin;
  17823. // scaling used for clustering
  17824. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  17825. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  17826. this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  17827. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  17828. }
  17829. };
  17830. Node.prototype._drawText = function (ctx) {
  17831. this._resizeText(ctx);
  17832. this.left = this.x - this.width / 2;
  17833. this.top = this.y - this.height / 2;
  17834. this._label(ctx, this.label, this.x, this.y);
  17835. this.boundingBox.top = this.top;
  17836. this.boundingBox.left = this.left;
  17837. this.boundingBox.right = this.left + this.width;
  17838. this.boundingBox.bottom = this.top + this.height;
  17839. };
  17840. Node.prototype._label = function (ctx, text, x, y, align, baseline, labelUnderNode) {
  17841. if (text && Number(this.options.fontSize) * this.networkScale > this.fontDrawThreshold) {
  17842. ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace;
  17843. var lines = text.split('\n');
  17844. var lineCount = lines.length;
  17845. var fontSize = (Number(this.options.fontSize) + 4); // TODO: why is this +4 ?
  17846. var yLine = y + (1 - lineCount) / 2 * fontSize;
  17847. if (labelUnderNode == true) {
  17848. yLine = y + (1 - lineCount) / (2 * fontSize);
  17849. }
  17850. // font fill from edges now for nodes!
  17851. var width = ctx.measureText(lines[0]).width;
  17852. for (var i = 1; i < lineCount; i++) {
  17853. var lineWidth = ctx.measureText(lines[i]).width;
  17854. width = lineWidth > width ? lineWidth : width;
  17855. }
  17856. var height = this.options.fontSize * lineCount;
  17857. var left = x - width / 2;
  17858. var top = y - height / 2;
  17859. if (baseline == "top") {
  17860. top += 0.5 * fontSize;
  17861. }
  17862. this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
  17863. // create the fontfill background
  17864. if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
  17865. ctx.fillStyle = this.options.fontFill;
  17866. ctx.fillRect(left, top, width, height);
  17867. }
  17868. // draw text
  17869. ctx.fillStyle = this.options.fontColor || "black";
  17870. ctx.textAlign = align || "center";
  17871. ctx.textBaseline = baseline || "middle";
  17872. for (var i = 0; i < lineCount; i++) {
  17873. ctx.fillText(lines[i], x, yLine);
  17874. yLine += fontSize;
  17875. }
  17876. }
  17877. };
  17878. Node.prototype.getTextSize = function(ctx) {
  17879. if (this.label !== undefined) {
  17880. ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace;
  17881. var lines = this.label.split('\n'),
  17882. height = (Number(this.options.fontSize) + 4) * lines.length,
  17883. width = 0;
  17884. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  17885. width = Math.max(width, ctx.measureText(lines[i]).width);
  17886. }
  17887. return {"width": width, "height": height};
  17888. }
  17889. else {
  17890. return {"width": 0, "height": 0};
  17891. }
  17892. };
  17893. /**
  17894. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  17895. * there is a safety margin of 0.3 * width;
  17896. *
  17897. * @returns {boolean}
  17898. */
  17899. Node.prototype.inArea = function() {
  17900. if (this.width !== undefined) {
  17901. return (this.x + this.width *this.networkScaleInv >= this.canvasTopLeft.x &&
  17902. this.x - this.width *this.networkScaleInv < this.canvasBottomRight.x &&
  17903. this.y + this.height*this.networkScaleInv >= this.canvasTopLeft.y &&
  17904. this.y - this.height*this.networkScaleInv < this.canvasBottomRight.y);
  17905. }
  17906. else {
  17907. return true;
  17908. }
  17909. };
  17910. /**
  17911. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  17912. * @returns {boolean}
  17913. */
  17914. Node.prototype.inView = function() {
  17915. return (this.x >= this.canvasTopLeft.x &&
  17916. this.x < this.canvasBottomRight.x &&
  17917. this.y >= this.canvasTopLeft.y &&
  17918. this.y < this.canvasBottomRight.y);
  17919. };
  17920. /**
  17921. * This allows the zoom level of the network to influence the rendering
  17922. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  17923. *
  17924. * @param scale
  17925. * @param canvasTopLeft
  17926. * @param canvasBottomRight
  17927. */
  17928. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  17929. this.networkScaleInv = 1.0/scale;
  17930. this.networkScale = scale;
  17931. this.canvasTopLeft = canvasTopLeft;
  17932. this.canvasBottomRight = canvasBottomRight;
  17933. };
  17934. /**
  17935. * This allows the zoom level of the network to influence the rendering
  17936. *
  17937. * @param scale
  17938. */
  17939. Node.prototype.setScale = function(scale) {
  17940. this.networkScaleInv = 1.0/scale;
  17941. this.networkScale = scale;
  17942. };
  17943. /**
  17944. * set the velocity at 0. Is called when this node is contained in another during clustering
  17945. */
  17946. Node.prototype.clearVelocity = function() {
  17947. this.vx = 0;
  17948. this.vy = 0;
  17949. };
  17950. /**
  17951. * Basic preservation of (kinectic) energy
  17952. *
  17953. * @param massBeforeClustering
  17954. */
  17955. Node.prototype.updateVelocity = function(massBeforeClustering) {
  17956. var energyBefore = this.vx * this.vx * massBeforeClustering;
  17957. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  17958. this.vx = Math.sqrt(energyBefore/this.options.mass);
  17959. energyBefore = this.vy * this.vy * massBeforeClustering;
  17960. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass);
  17961. this.vy = Math.sqrt(energyBefore/this.options.mass);
  17962. };
  17963. module.exports = Node;
  17964. /***/ },
  17965. /* 41 */
  17966. /***/ function(module, exports, __webpack_require__) {
  17967. /**
  17968. * Popup is a class to create a popup window with some text
  17969. * @param {Element} container The container object.
  17970. * @param {Number} [x]
  17971. * @param {Number} [y]
  17972. * @param {String} [text]
  17973. * @param {Object} [style] An object containing borderColor,
  17974. * backgroundColor, etc.
  17975. */
  17976. function Popup(container, x, y, text, style) {
  17977. if (container) {
  17978. this.container = container;
  17979. }
  17980. else {
  17981. this.container = document.body;
  17982. }
  17983. // x, y and text are optional, see if a style object was passed in their place
  17984. if (style === undefined) {
  17985. if (typeof x === "object") {
  17986. style = x;
  17987. x = undefined;
  17988. } else if (typeof text === "object") {
  17989. style = text;
  17990. text = undefined;
  17991. } else {
  17992. // for backwards compatibility, in case clients other than Network are creating Popup directly
  17993. style = {
  17994. fontColor: 'black',
  17995. fontSize: 14, // px
  17996. fontFace: 'verdana',
  17997. color: {
  17998. border: '#666',
  17999. background: '#FFFFC6'
  18000. }
  18001. }
  18002. }
  18003. }
  18004. this.x = 0;
  18005. this.y = 0;
  18006. this.padding = 5;
  18007. if (x !== undefined && y !== undefined ) {
  18008. this.setPosition(x, y);
  18009. }
  18010. if (text !== undefined) {
  18011. this.setText(text);
  18012. }
  18013. // create the frame
  18014. this.frame = document.createElement("div");
  18015. var styleAttr = this.frame.style;
  18016. styleAttr.position = "absolute";
  18017. styleAttr.visibility = "hidden";
  18018. styleAttr.border = "1px solid " + style.color.border;
  18019. styleAttr.color = style.fontColor;
  18020. styleAttr.fontSize = style.fontSize + "px";
  18021. styleAttr.fontFamily = style.fontFace;
  18022. styleAttr.padding = this.padding + "px";
  18023. styleAttr.backgroundColor = style.color.background;
  18024. styleAttr.borderRadius = "3px";
  18025. styleAttr.MozBorderRadius = "3px";
  18026. styleAttr.WebkitBorderRadius = "3px";
  18027. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  18028. styleAttr.whiteSpace = "nowrap";
  18029. this.container.appendChild(this.frame);
  18030. }
  18031. /**
  18032. * @param {number} x Horizontal position of the popup window
  18033. * @param {number} y Vertical position of the popup window
  18034. */
  18035. Popup.prototype.setPosition = function(x, y) {
  18036. this.x = parseInt(x);
  18037. this.y = parseInt(y);
  18038. };
  18039. /**
  18040. * Set the content for the popup window. This can be HTML code or text.
  18041. * @param {string | Element} content
  18042. */
  18043. Popup.prototype.setText = function(content) {
  18044. if (content instanceof Element) {
  18045. this.frame.innerHTML = '';
  18046. this.frame.appendChild(content);
  18047. }
  18048. else {
  18049. this.frame.innerHTML = content; // string containing text or HTML
  18050. }
  18051. };
  18052. /**
  18053. * Show the popup window
  18054. * @param {boolean} show Optional. Show or hide the window
  18055. */
  18056. Popup.prototype.show = function (show) {
  18057. if (show === undefined) {
  18058. show = true;
  18059. }
  18060. if (show) {
  18061. var height = this.frame.clientHeight;
  18062. var width = this.frame.clientWidth;
  18063. var maxHeight = this.frame.parentNode.clientHeight;
  18064. var maxWidth = this.frame.parentNode.clientWidth;
  18065. var top = (this.y - height);
  18066. if (top + height + this.padding > maxHeight) {
  18067. top = maxHeight - height - this.padding;
  18068. }
  18069. if (top < this.padding) {
  18070. top = this.padding;
  18071. }
  18072. var left = this.x;
  18073. if (left + width + this.padding > maxWidth) {
  18074. left = maxWidth - width - this.padding;
  18075. }
  18076. if (left < this.padding) {
  18077. left = this.padding;
  18078. }
  18079. this.frame.style.left = left + "px";
  18080. this.frame.style.top = top + "px";
  18081. this.frame.style.visibility = "visible";
  18082. }
  18083. else {
  18084. this.hide();
  18085. }
  18086. };
  18087. /**
  18088. * Hide the popup window
  18089. */
  18090. Popup.prototype.hide = function () {
  18091. this.frame.style.visibility = "hidden";
  18092. };
  18093. module.exports = Popup;
  18094. /***/ },
  18095. /* 42 */
  18096. /***/ function(module, exports, __webpack_require__) {
  18097. /**
  18098. * Parse a text source containing data in DOT language into a JSON object.
  18099. * The object contains two lists: one with nodes and one with edges.
  18100. *
  18101. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  18102. *
  18103. * @param {String} data Text containing a graph in DOT-notation
  18104. * @return {Object} graph An object containing two parameters:
  18105. * {Object[]} nodes
  18106. * {Object[]} edges
  18107. */
  18108. function parseDOT (data) {
  18109. dot = data;
  18110. return parseGraph();
  18111. }
  18112. // token types enumeration
  18113. var TOKENTYPE = {
  18114. NULL : 0,
  18115. DELIMITER : 1,
  18116. IDENTIFIER: 2,
  18117. UNKNOWN : 3
  18118. };
  18119. // map with all delimiters
  18120. var DELIMITERS = {
  18121. '{': true,
  18122. '}': true,
  18123. '[': true,
  18124. ']': true,
  18125. ';': true,
  18126. '=': true,
  18127. ',': true,
  18128. '->': true,
  18129. '--': true
  18130. };
  18131. var dot = ''; // current dot file
  18132. var index = 0; // current index in dot file
  18133. var c = ''; // current token character in expr
  18134. var token = ''; // current token
  18135. var tokenType = TOKENTYPE.NULL; // type of the token
  18136. /**
  18137. * Get the first character from the dot file.
  18138. * The character is stored into the char c. If the end of the dot file is
  18139. * reached, the function puts an empty string in c.
  18140. */
  18141. function first() {
  18142. index = 0;
  18143. c = dot.charAt(0);
  18144. }
  18145. /**
  18146. * Get the next character from the dot file.
  18147. * The character is stored into the char c. If the end of the dot file is
  18148. * reached, the function puts an empty string in c.
  18149. */
  18150. function next() {
  18151. index++;
  18152. c = dot.charAt(index);
  18153. }
  18154. /**
  18155. * Preview the next character from the dot file.
  18156. * @return {String} cNext
  18157. */
  18158. function nextPreview() {
  18159. return dot.charAt(index + 1);
  18160. }
  18161. /**
  18162. * Test whether given character is alphabetic or numeric
  18163. * @param {String} c
  18164. * @return {Boolean} isAlphaNumeric
  18165. */
  18166. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  18167. function isAlphaNumeric(c) {
  18168. return regexAlphaNumeric.test(c);
  18169. }
  18170. /**
  18171. * Merge all properties of object b into object b
  18172. * @param {Object} a
  18173. * @param {Object} b
  18174. * @return {Object} a
  18175. */
  18176. function merge (a, b) {
  18177. if (!a) {
  18178. a = {};
  18179. }
  18180. if (b) {
  18181. for (var name in b) {
  18182. if (b.hasOwnProperty(name)) {
  18183. a[name] = b[name];
  18184. }
  18185. }
  18186. }
  18187. return a;
  18188. }
  18189. /**
  18190. * Set a value in an object, where the provided parameter name can be a
  18191. * path with nested parameters. For example:
  18192. *
  18193. * var obj = {a: 2};
  18194. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  18195. *
  18196. * @param {Object} obj
  18197. * @param {String} path A parameter name or dot-separated parameter path,
  18198. * like "color.highlight.border".
  18199. * @param {*} value
  18200. */
  18201. function setValue(obj, path, value) {
  18202. var keys = path.split('.');
  18203. var o = obj;
  18204. while (keys.length) {
  18205. var key = keys.shift();
  18206. if (keys.length) {
  18207. // this isn't the end point
  18208. if (!o[key]) {
  18209. o[key] = {};
  18210. }
  18211. o = o[key];
  18212. }
  18213. else {
  18214. // this is the end point
  18215. o[key] = value;
  18216. }
  18217. }
  18218. }
  18219. /**
  18220. * Add a node to a graph object. If there is already a node with
  18221. * the same id, their attributes will be merged.
  18222. * @param {Object} graph
  18223. * @param {Object} node
  18224. */
  18225. function addNode(graph, node) {
  18226. var i, len;
  18227. var current = null;
  18228. // find root graph (in case of subgraph)
  18229. var graphs = [graph]; // list with all graphs from current graph to root graph
  18230. var root = graph;
  18231. while (root.parent) {
  18232. graphs.push(root.parent);
  18233. root = root.parent;
  18234. }
  18235. // find existing node (at root level) by its id
  18236. if (root.nodes) {
  18237. for (i = 0, len = root.nodes.length; i < len; i++) {
  18238. if (node.id === root.nodes[i].id) {
  18239. current = root.nodes[i];
  18240. break;
  18241. }
  18242. }
  18243. }
  18244. if (!current) {
  18245. // this is a new node
  18246. current = {
  18247. id: node.id
  18248. };
  18249. if (graph.node) {
  18250. // clone default attributes
  18251. current.attr = merge(current.attr, graph.node);
  18252. }
  18253. }
  18254. // add node to this (sub)graph and all its parent graphs
  18255. for (i = graphs.length - 1; i >= 0; i--) {
  18256. var g = graphs[i];
  18257. if (!g.nodes) {
  18258. g.nodes = [];
  18259. }
  18260. if (g.nodes.indexOf(current) == -1) {
  18261. g.nodes.push(current);
  18262. }
  18263. }
  18264. // merge attributes
  18265. if (node.attr) {
  18266. current.attr = merge(current.attr, node.attr);
  18267. }
  18268. }
  18269. /**
  18270. * Add an edge to a graph object
  18271. * @param {Object} graph
  18272. * @param {Object} edge
  18273. */
  18274. function addEdge(graph, edge) {
  18275. if (!graph.edges) {
  18276. graph.edges = [];
  18277. }
  18278. graph.edges.push(edge);
  18279. if (graph.edge) {
  18280. var attr = merge({}, graph.edge); // clone default attributes
  18281. edge.attr = merge(attr, edge.attr); // merge attributes
  18282. }
  18283. }
  18284. /**
  18285. * Create an edge to a graph object
  18286. * @param {Object} graph
  18287. * @param {String | Number | Object} from
  18288. * @param {String | Number | Object} to
  18289. * @param {String} type
  18290. * @param {Object | null} attr
  18291. * @return {Object} edge
  18292. */
  18293. function createEdge(graph, from, to, type, attr) {
  18294. var edge = {
  18295. from: from,
  18296. to: to,
  18297. type: type
  18298. };
  18299. if (graph.edge) {
  18300. edge.attr = merge({}, graph.edge); // clone default attributes
  18301. }
  18302. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  18303. return edge;
  18304. }
  18305. /**
  18306. * Get next token in the current dot file.
  18307. * The token and token type are available as token and tokenType
  18308. */
  18309. function getToken() {
  18310. tokenType = TOKENTYPE.NULL;
  18311. token = '';
  18312. // skip over whitespaces
  18313. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  18314. next();
  18315. }
  18316. do {
  18317. var isComment = false;
  18318. // skip comment
  18319. if (c == '#') {
  18320. // find the previous non-space character
  18321. var i = index - 1;
  18322. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  18323. i--;
  18324. }
  18325. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  18326. // the # is at the start of a line, this is indeed a line comment
  18327. while (c != '' && c != '\n') {
  18328. next();
  18329. }
  18330. isComment = true;
  18331. }
  18332. }
  18333. if (c == '/' && nextPreview() == '/') {
  18334. // skip line comment
  18335. while (c != '' && c != '\n') {
  18336. next();
  18337. }
  18338. isComment = true;
  18339. }
  18340. if (c == '/' && nextPreview() == '*') {
  18341. // skip block comment
  18342. while (c != '') {
  18343. if (c == '*' && nextPreview() == '/') {
  18344. // end of block comment found. skip these last two characters
  18345. next();
  18346. next();
  18347. break;
  18348. }
  18349. else {
  18350. next();
  18351. }
  18352. }
  18353. isComment = true;
  18354. }
  18355. // skip over whitespaces
  18356. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  18357. next();
  18358. }
  18359. }
  18360. while (isComment);
  18361. // check for end of dot file
  18362. if (c == '') {
  18363. // token is still empty
  18364. tokenType = TOKENTYPE.DELIMITER;
  18365. return;
  18366. }
  18367. // check for delimiters consisting of 2 characters
  18368. var c2 = c + nextPreview();
  18369. if (DELIMITERS[c2]) {
  18370. tokenType = TOKENTYPE.DELIMITER;
  18371. token = c2;
  18372. next();
  18373. next();
  18374. return;
  18375. }
  18376. // check for delimiters consisting of 1 character
  18377. if (DELIMITERS[c]) {
  18378. tokenType = TOKENTYPE.DELIMITER;
  18379. token = c;
  18380. next();
  18381. return;
  18382. }
  18383. // check for an identifier (number or string)
  18384. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  18385. if (isAlphaNumeric(c) || c == '-') {
  18386. token += c;
  18387. next();
  18388. while (isAlphaNumeric(c)) {
  18389. token += c;
  18390. next();
  18391. }
  18392. if (token == 'false') {
  18393. token = false; // convert to boolean
  18394. }
  18395. else if (token == 'true') {
  18396. token = true; // convert to boolean
  18397. }
  18398. else if (!isNaN(Number(token))) {
  18399. token = Number(token); // convert to number
  18400. }
  18401. tokenType = TOKENTYPE.IDENTIFIER;
  18402. return;
  18403. }
  18404. // check for a string enclosed by double quotes
  18405. if (c == '"') {
  18406. next();
  18407. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  18408. token += c;
  18409. if (c == '"') { // skip the escape character
  18410. next();
  18411. }
  18412. next();
  18413. }
  18414. if (c != '"') {
  18415. throw newSyntaxError('End of string " expected');
  18416. }
  18417. next();
  18418. tokenType = TOKENTYPE.IDENTIFIER;
  18419. return;
  18420. }
  18421. // something unknown is found, wrong characters, a syntax error
  18422. tokenType = TOKENTYPE.UNKNOWN;
  18423. while (c != '') {
  18424. token += c;
  18425. next();
  18426. }
  18427. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  18428. }
  18429. /**
  18430. * Parse a graph.
  18431. * @returns {Object} graph
  18432. */
  18433. function parseGraph() {
  18434. var graph = {};
  18435. first();
  18436. getToken();
  18437. // optional strict keyword
  18438. if (token == 'strict') {
  18439. graph.strict = true;
  18440. getToken();
  18441. }
  18442. // graph or digraph keyword
  18443. if (token == 'graph' || token == 'digraph') {
  18444. graph.type = token;
  18445. getToken();
  18446. }
  18447. // optional graph id
  18448. if (tokenType == TOKENTYPE.IDENTIFIER) {
  18449. graph.id = token;
  18450. getToken();
  18451. }
  18452. // open angle bracket
  18453. if (token != '{') {
  18454. throw newSyntaxError('Angle bracket { expected');
  18455. }
  18456. getToken();
  18457. // statements
  18458. parseStatements(graph);
  18459. // close angle bracket
  18460. if (token != '}') {
  18461. throw newSyntaxError('Angle bracket } expected');
  18462. }
  18463. getToken();
  18464. // end of file
  18465. if (token !== '') {
  18466. throw newSyntaxError('End of file expected');
  18467. }
  18468. getToken();
  18469. // remove temporary default properties
  18470. delete graph.node;
  18471. delete graph.edge;
  18472. delete graph.graph;
  18473. return graph;
  18474. }
  18475. /**
  18476. * Parse a list with statements.
  18477. * @param {Object} graph
  18478. */
  18479. function parseStatements (graph) {
  18480. while (token !== '' && token != '}') {
  18481. parseStatement(graph);
  18482. if (token == ';') {
  18483. getToken();
  18484. }
  18485. }
  18486. }
  18487. /**
  18488. * Parse a single statement. Can be a an attribute statement, node
  18489. * statement, a series of node statements and edge statements, or a
  18490. * parameter.
  18491. * @param {Object} graph
  18492. */
  18493. function parseStatement(graph) {
  18494. // parse subgraph
  18495. var subgraph = parseSubgraph(graph);
  18496. if (subgraph) {
  18497. // edge statements
  18498. parseEdge(graph, subgraph);
  18499. return;
  18500. }
  18501. // parse an attribute statement
  18502. var attr = parseAttributeStatement(graph);
  18503. if (attr) {
  18504. return;
  18505. }
  18506. // parse node
  18507. if (tokenType != TOKENTYPE.IDENTIFIER) {
  18508. throw newSyntaxError('Identifier expected');
  18509. }
  18510. var id = token; // id can be a string or a number
  18511. getToken();
  18512. if (token == '=') {
  18513. // id statement
  18514. getToken();
  18515. if (tokenType != TOKENTYPE.IDENTIFIER) {
  18516. throw newSyntaxError('Identifier expected');
  18517. }
  18518. graph[id] = token;
  18519. getToken();
  18520. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  18521. }
  18522. else {
  18523. parseNodeStatement(graph, id);
  18524. }
  18525. }
  18526. /**
  18527. * Parse a subgraph
  18528. * @param {Object} graph parent graph object
  18529. * @return {Object | null} subgraph
  18530. */
  18531. function parseSubgraph (graph) {
  18532. var subgraph = null;
  18533. // optional subgraph keyword
  18534. if (token == 'subgraph') {
  18535. subgraph = {};
  18536. subgraph.type = 'subgraph';
  18537. getToken();
  18538. // optional graph id
  18539. if (tokenType == TOKENTYPE.IDENTIFIER) {
  18540. subgraph.id = token;
  18541. getToken();
  18542. }
  18543. }
  18544. // open angle bracket
  18545. if (token == '{') {
  18546. getToken();
  18547. if (!subgraph) {
  18548. subgraph = {};
  18549. }
  18550. subgraph.parent = graph;
  18551. subgraph.node = graph.node;
  18552. subgraph.edge = graph.edge;
  18553. subgraph.graph = graph.graph;
  18554. // statements
  18555. parseStatements(subgraph);
  18556. // close angle bracket
  18557. if (token != '}') {
  18558. throw newSyntaxError('Angle bracket } expected');
  18559. }
  18560. getToken();
  18561. // remove temporary default properties
  18562. delete subgraph.node;
  18563. delete subgraph.edge;
  18564. delete subgraph.graph;
  18565. delete subgraph.parent;
  18566. // register at the parent graph
  18567. if (!graph.subgraphs) {
  18568. graph.subgraphs = [];
  18569. }
  18570. graph.subgraphs.push(subgraph);
  18571. }
  18572. return subgraph;
  18573. }
  18574. /**
  18575. * parse an attribute statement like "node [shape=circle fontSize=16]".
  18576. * Available keywords are 'node', 'edge', 'graph'.
  18577. * The previous list with default attributes will be replaced
  18578. * @param {Object} graph
  18579. * @returns {String | null} keyword Returns the name of the parsed attribute
  18580. * (node, edge, graph), or null if nothing
  18581. * is parsed.
  18582. */
  18583. function parseAttributeStatement (graph) {
  18584. // attribute statements
  18585. if (token == 'node') {
  18586. getToken();
  18587. // node attributes
  18588. graph.node = parseAttributeList();
  18589. return 'node';
  18590. }
  18591. else if (token == 'edge') {
  18592. getToken();
  18593. // edge attributes
  18594. graph.edge = parseAttributeList();
  18595. return 'edge';
  18596. }
  18597. else if (token == 'graph') {
  18598. getToken();
  18599. // graph attributes
  18600. graph.graph = parseAttributeList();
  18601. return 'graph';
  18602. }
  18603. return null;
  18604. }
  18605. /**
  18606. * parse a node statement
  18607. * @param {Object} graph
  18608. * @param {String | Number} id
  18609. */
  18610. function parseNodeStatement(graph, id) {
  18611. // node statement
  18612. var node = {
  18613. id: id
  18614. };
  18615. var attr = parseAttributeList();
  18616. if (attr) {
  18617. node.attr = attr;
  18618. }
  18619. addNode(graph, node);
  18620. // edge statements
  18621. parseEdge(graph, id);
  18622. }
  18623. /**
  18624. * Parse an edge or a series of edges
  18625. * @param {Object} graph
  18626. * @param {String | Number} from Id of the from node
  18627. */
  18628. function parseEdge(graph, from) {
  18629. while (token == '->' || token == '--') {
  18630. var to;
  18631. var type = token;
  18632. getToken();
  18633. var subgraph = parseSubgraph(graph);
  18634. if (subgraph) {
  18635. to = subgraph;
  18636. }
  18637. else {
  18638. if (tokenType != TOKENTYPE.IDENTIFIER) {
  18639. throw newSyntaxError('Identifier or subgraph expected');
  18640. }
  18641. to = token;
  18642. addNode(graph, {
  18643. id: to
  18644. });
  18645. getToken();
  18646. }
  18647. // parse edge attributes
  18648. var attr = parseAttributeList();
  18649. // create edge
  18650. var edge = createEdge(graph, from, to, type, attr);
  18651. addEdge(graph, edge);
  18652. from = to;
  18653. }
  18654. }
  18655. /**
  18656. * Parse a set with attributes,
  18657. * for example [label="1.000", shape=solid]
  18658. * @return {Object | null} attr
  18659. */
  18660. function parseAttributeList() {
  18661. var attr = null;
  18662. while (token == '[') {
  18663. getToken();
  18664. attr = {};
  18665. while (token !== '' && token != ']') {
  18666. if (tokenType != TOKENTYPE.IDENTIFIER) {
  18667. throw newSyntaxError('Attribute name expected');
  18668. }
  18669. var name = token;
  18670. getToken();
  18671. if (token != '=') {
  18672. throw newSyntaxError('Equal sign = expected');
  18673. }
  18674. getToken();
  18675. if (tokenType != TOKENTYPE.IDENTIFIER) {
  18676. throw newSyntaxError('Attribute value expected');
  18677. }
  18678. var value = token;
  18679. setValue(attr, name, value); // name can be a path
  18680. getToken();
  18681. if (token ==',') {
  18682. getToken();
  18683. }
  18684. }
  18685. if (token != ']') {
  18686. throw newSyntaxError('Bracket ] expected');
  18687. }
  18688. getToken();
  18689. }
  18690. return attr;
  18691. }
  18692. /**
  18693. * Create a syntax error with extra information on current token and index.
  18694. * @param {String} message
  18695. * @returns {SyntaxError} err
  18696. */
  18697. function newSyntaxError(message) {
  18698. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  18699. }
  18700. /**
  18701. * Chop off text after a maximum length
  18702. * @param {String} text
  18703. * @param {Number} maxLength
  18704. * @returns {String}
  18705. */
  18706. function chop (text, maxLength) {
  18707. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  18708. }
  18709. /**
  18710. * Execute a function fn for each pair of elements in two arrays
  18711. * @param {Array | *} array1
  18712. * @param {Array | *} array2
  18713. * @param {function} fn
  18714. */
  18715. function forEach2(array1, array2, fn) {
  18716. if (Array.isArray(array1)) {
  18717. array1.forEach(function (elem1) {
  18718. if (Array.isArray(array2)) {
  18719. array2.forEach(function (elem2) {
  18720. fn(elem1, elem2);
  18721. });
  18722. }
  18723. else {
  18724. fn(elem1, array2);
  18725. }
  18726. });
  18727. }
  18728. else {
  18729. if (Array.isArray(array2)) {
  18730. array2.forEach(function (elem2) {
  18731. fn(array1, elem2);
  18732. });
  18733. }
  18734. else {
  18735. fn(array1, array2);
  18736. }
  18737. }
  18738. }
  18739. /**
  18740. * Convert a string containing a graph in DOT language into a map containing
  18741. * with nodes and edges in the format of graph.
  18742. * @param {String} data Text containing a graph in DOT-notation
  18743. * @return {Object} graphData
  18744. */
  18745. function DOTToGraph (data) {
  18746. // parse the DOT file
  18747. var dotData = parseDOT(data);
  18748. var graphData = {
  18749. nodes: [],
  18750. edges: [],
  18751. options: {}
  18752. };
  18753. // copy the nodes
  18754. if (dotData.nodes) {
  18755. dotData.nodes.forEach(function (dotNode) {
  18756. var graphNode = {
  18757. id: dotNode.id,
  18758. label: String(dotNode.label || dotNode.id)
  18759. };
  18760. merge(graphNode, dotNode.attr);
  18761. if (graphNode.image) {
  18762. graphNode.shape = 'image';
  18763. }
  18764. graphData.nodes.push(graphNode);
  18765. });
  18766. }
  18767. // copy the edges
  18768. if (dotData.edges) {
  18769. /**
  18770. * Convert an edge in DOT format to an edge with VisGraph format
  18771. * @param {Object} dotEdge
  18772. * @returns {Object} graphEdge
  18773. */
  18774. var convertEdge = function (dotEdge) {
  18775. var graphEdge = {
  18776. from: dotEdge.from,
  18777. to: dotEdge.to
  18778. };
  18779. merge(graphEdge, dotEdge.attr);
  18780. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  18781. return graphEdge;
  18782. }
  18783. dotData.edges.forEach(function (dotEdge) {
  18784. var from, to;
  18785. if (dotEdge.from instanceof Object) {
  18786. from = dotEdge.from.nodes;
  18787. }
  18788. else {
  18789. from = {
  18790. id: dotEdge.from
  18791. }
  18792. }
  18793. if (dotEdge.to instanceof Object) {
  18794. to = dotEdge.to.nodes;
  18795. }
  18796. else {
  18797. to = {
  18798. id: dotEdge.to
  18799. }
  18800. }
  18801. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  18802. dotEdge.from.edges.forEach(function (subEdge) {
  18803. var graphEdge = convertEdge(subEdge);
  18804. graphData.edges.push(graphEdge);
  18805. });
  18806. }
  18807. forEach2(from, to, function (from, to) {
  18808. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  18809. var graphEdge = convertEdge(subEdge);
  18810. graphData.edges.push(graphEdge);
  18811. });
  18812. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  18813. dotEdge.to.edges.forEach(function (subEdge) {
  18814. var graphEdge = convertEdge(subEdge);
  18815. graphData.edges.push(graphEdge);
  18816. });
  18817. }
  18818. });
  18819. }
  18820. // copy the options
  18821. if (dotData.attr) {
  18822. graphData.options = dotData.attr;
  18823. }
  18824. return graphData;
  18825. }
  18826. // exports
  18827. exports.parseDOT = parseDOT;
  18828. exports.DOTToGraph = DOTToGraph;
  18829. /***/ },
  18830. /* 43 */
  18831. /***/ function(module, exports, __webpack_require__) {
  18832. function parseGephi(gephiJSON, options) {
  18833. var edges = [];
  18834. var nodes = [];
  18835. this.options = {
  18836. edges: {
  18837. inheritColor: true
  18838. },
  18839. nodes: {
  18840. allowedToMove: false,
  18841. parseColor: false
  18842. }
  18843. };
  18844. if (options !== undefined) {
  18845. this.options.nodes['allowedToMove'] = options.allowedToMove | false;
  18846. this.options.nodes['parseColor'] = options.parseColor | false;
  18847. this.options.edges['inheritColor'] = options.inheritColor | true;
  18848. }
  18849. var gEdges = gephiJSON.edges;
  18850. var gNodes = gephiJSON.nodes;
  18851. for (var i = 0; i < gEdges.length; i++) {
  18852. var edge = {};
  18853. var gEdge = gEdges[i];
  18854. edge['id'] = gEdge.id;
  18855. edge['from'] = gEdge.source;
  18856. edge['to'] = gEdge.target;
  18857. edge['attributes'] = gEdge.attributes;
  18858. // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined;
  18859. // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size;
  18860. edge['color'] = gEdge.color;
  18861. edge['inheritColor'] = edge['color'] !== undefined ? false : this.options.inheritColor;
  18862. edges.push(edge);
  18863. }
  18864. for (var i = 0; i < gNodes.length; i++) {
  18865. var node = {};
  18866. var gNode = gNodes[i];
  18867. node['id'] = gNode.id;
  18868. node['attributes'] = gNode.attributes;
  18869. node['x'] = gNode.x;
  18870. node['y'] = gNode.y;
  18871. node['label'] = gNode.label;
  18872. if (this.options.nodes.parseColor == true) {
  18873. node['color'] = gNode.color;
  18874. }
  18875. else {
  18876. node['color'] = gNode.color !== undefined ? {background:gNode.color, border:gNode.color} : undefined;
  18877. }
  18878. node['radius'] = gNode.size;
  18879. node['allowedToMoveX'] = this.options.nodes.allowedToMove;
  18880. node['allowedToMoveY'] = this.options.nodes.allowedToMove;
  18881. nodes.push(node);
  18882. }
  18883. return {nodes:nodes, edges:edges};
  18884. }
  18885. exports.parseGephi = parseGephi;
  18886. /***/ },
  18887. /* 44 */
  18888. /***/ function(module, exports, __webpack_require__) {
  18889. // first check if moment.js is already loaded in the browser window, if so,
  18890. // use this instance. Else, load via commonjs.
  18891. module.exports = (typeof window !== 'undefined') && window['moment'] || __webpack_require__(58);
  18892. /***/ },
  18893. /* 45 */
  18894. /***/ function(module, exports, __webpack_require__) {
  18895. // Only load hammer.js when in a browser environment
  18896. // (loading hammer.js in a node.js environment gives errors)
  18897. if (typeof window !== 'undefined') {
  18898. module.exports = window['Hammer'] || __webpack_require__(59);
  18899. }
  18900. else {
  18901. module.exports = function () {
  18902. throw Error('hammer.js is only available in a browser, not in node.js.');
  18903. }
  18904. }
  18905. /***/ },
  18906. /* 46 */
  18907. /***/ function(module, exports, __webpack_require__) {
  18908. var Emitter = __webpack_require__(56);
  18909. var Hammer = __webpack_require__(45);
  18910. var util = __webpack_require__(1);
  18911. var DataSet = __webpack_require__(3);
  18912. var DataView = __webpack_require__(4);
  18913. var Range = __webpack_require__(17);
  18914. var ItemSet = __webpack_require__(27);
  18915. var Activator = __webpack_require__(55);
  18916. var DateUtil = __webpack_require__(15);
  18917. /**
  18918. * Create a timeline visualization
  18919. * @param {HTMLElement} container
  18920. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  18921. * @param {Object} [options] See Core.setOptions for the available options.
  18922. * @constructor
  18923. */
  18924. function Core () {}
  18925. // turn Core into an event emitter
  18926. Emitter(Core.prototype);
  18927. /**
  18928. * Create the main DOM for the Core: a root panel containing left, right,
  18929. * top, bottom, content, and background panel.
  18930. * @param {Element} container The container element where the Core will
  18931. * be attached.
  18932. * @private
  18933. */
  18934. Core.prototype._create = function (container) {
  18935. this.dom = {};
  18936. this.dom.root = document.createElement('div');
  18937. this.dom.background = document.createElement('div');
  18938. this.dom.backgroundVertical = document.createElement('div');
  18939. this.dom.backgroundHorizontal = document.createElement('div');
  18940. this.dom.centerContainer = document.createElement('div');
  18941. this.dom.leftContainer = document.createElement('div');
  18942. this.dom.rightContainer = document.createElement('div');
  18943. this.dom.center = document.createElement('div');
  18944. this.dom.left = document.createElement('div');
  18945. this.dom.right = document.createElement('div');
  18946. this.dom.top = document.createElement('div');
  18947. this.dom.bottom = document.createElement('div');
  18948. this.dom.shadowTop = document.createElement('div');
  18949. this.dom.shadowBottom = document.createElement('div');
  18950. this.dom.shadowTopLeft = document.createElement('div');
  18951. this.dom.shadowBottomLeft = document.createElement('div');
  18952. this.dom.shadowTopRight = document.createElement('div');
  18953. this.dom.shadowBottomRight = document.createElement('div');
  18954. this.dom.root.className = 'vis timeline root';
  18955. this.dom.background.className = 'vispanel background';
  18956. this.dom.backgroundVertical.className = 'vispanel background vertical';
  18957. this.dom.backgroundHorizontal.className = 'vispanel background horizontal';
  18958. this.dom.centerContainer.className = 'vispanel center';
  18959. this.dom.leftContainer.className = 'vispanel left';
  18960. this.dom.rightContainer.className = 'vispanel right';
  18961. this.dom.top.className = 'vispanel top';
  18962. this.dom.bottom.className = 'vispanel bottom';
  18963. this.dom.left.className = 'content';
  18964. this.dom.center.className = 'content';
  18965. this.dom.right.className = 'content';
  18966. this.dom.shadowTop.className = 'shadow top';
  18967. this.dom.shadowBottom.className = 'shadow bottom';
  18968. this.dom.shadowTopLeft.className = 'shadow top';
  18969. this.dom.shadowBottomLeft.className = 'shadow bottom';
  18970. this.dom.shadowTopRight.className = 'shadow top';
  18971. this.dom.shadowBottomRight.className = 'shadow bottom';
  18972. this.dom.root.appendChild(this.dom.background);
  18973. this.dom.root.appendChild(this.dom.backgroundVertical);
  18974. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  18975. this.dom.root.appendChild(this.dom.centerContainer);
  18976. this.dom.root.appendChild(this.dom.leftContainer);
  18977. this.dom.root.appendChild(this.dom.rightContainer);
  18978. this.dom.root.appendChild(this.dom.top);
  18979. this.dom.root.appendChild(this.dom.bottom);
  18980. this.dom.centerContainer.appendChild(this.dom.center);
  18981. this.dom.leftContainer.appendChild(this.dom.left);
  18982. this.dom.rightContainer.appendChild(this.dom.right);
  18983. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  18984. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  18985. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  18986. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  18987. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  18988. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  18989. this.on('rangechange', this.redraw.bind(this));
  18990. this.on('touch', this._onTouch.bind(this));
  18991. this.on('pinch', this._onPinch.bind(this));
  18992. this.on('dragstart', this._onDragStart.bind(this));
  18993. this.on('drag', this._onDrag.bind(this));
  18994. var me = this;
  18995. this.on('change', function (properties) {
  18996. if (properties && properties.queue == true) {
  18997. // redraw once on next tick
  18998. if (!me._redrawTimer) {
  18999. me._redrawTimer = setTimeout(function () {
  19000. me._redrawTimer = null;
  19001. me.redraw();
  19002. }, 0)
  19003. }
  19004. }
  19005. else {
  19006. // redraw immediately
  19007. me.redraw();
  19008. }
  19009. });
  19010. // create event listeners for all interesting events, these events will be
  19011. // emitted via emitter
  19012. this.hammer = Hammer(this.dom.root, {
  19013. preventDefault: true
  19014. });
  19015. this.listeners = {};
  19016. var events = [
  19017. 'touch', 'pinch',
  19018. 'tap', 'doubletap', 'hold',
  19019. 'dragstart', 'drag', 'dragend',
  19020. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  19021. ];
  19022. events.forEach(function (event) {
  19023. var listener = function () {
  19024. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  19025. if (me.isActive()) {
  19026. me.emit.apply(me, args);
  19027. }
  19028. };
  19029. me.hammer.on(event, listener);
  19030. me.listeners[event] = listener;
  19031. });
  19032. // size properties of each of the panels
  19033. this.props = {
  19034. root: {},
  19035. background: {},
  19036. centerContainer: {},
  19037. leftContainer: {},
  19038. rightContainer: {},
  19039. center: {},
  19040. left: {},
  19041. right: {},
  19042. top: {},
  19043. bottom: {},
  19044. border: {},
  19045. scrollTop: 0,
  19046. scrollTopMin: 0
  19047. };
  19048. this.touch = {}; // store state information needed for touch events
  19049. this.redrawCount = 0;
  19050. // attach the root panel to the provided container
  19051. if (!container) throw new Error('No container provided');
  19052. container.appendChild(this.dom.root);
  19053. };
  19054. /**
  19055. * Set options. Options will be passed to all components loaded in the Timeline.
  19056. * @param {Object} [options]
  19057. * {String} orientation
  19058. * Vertical orientation for the Timeline,
  19059. * can be 'bottom' (default) or 'top'.
  19060. * {String | Number} width
  19061. * Width for the timeline, a number in pixels or
  19062. * a css string like '1000px' or '75%'. '100%' by default.
  19063. * {String | Number} height
  19064. * Fixed height for the Timeline, a number in pixels or
  19065. * a css string like '400px' or '75%'. If undefined,
  19066. * The Timeline will automatically size such that
  19067. * its contents fit.
  19068. * {String | Number} minHeight
  19069. * Minimum height for the Timeline, a number in pixels or
  19070. * a css string like '400px' or '75%'.
  19071. * {String | Number} maxHeight
  19072. * Maximum height for the Timeline, a number in pixels or
  19073. * a css string like '400px' or '75%'.
  19074. * {Number | Date | String} start
  19075. * Start date for the visible window
  19076. * {Number | Date | String} end
  19077. * End date for the visible window
  19078. */
  19079. Core.prototype.setOptions = function (options) {
  19080. if (options) {
  19081. // copy the known options
  19082. var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'orientation', 'clickToUse', 'dataAttributes', 'hiddenDates'];
  19083. util.selectiveExtend(fields, this.options, options);
  19084. if ('hiddenDates' in this.options) {
  19085. DateUtil.convertHiddenOptions(this.body, this.options.hiddenDates);
  19086. }
  19087. if ('clickToUse' in options) {
  19088. if (options.clickToUse) {
  19089. if (!this.activator) {
  19090. this.activator = new Activator(this.dom.root);
  19091. }
  19092. }
  19093. else {
  19094. if (this.activator) {
  19095. this.activator.destroy();
  19096. delete this.activator;
  19097. }
  19098. }
  19099. }
  19100. // enable/disable autoResize
  19101. this._initAutoResize();
  19102. }
  19103. // propagate options to all components
  19104. this.components.forEach(function (component) {
  19105. component.setOptions(options);
  19106. });
  19107. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  19108. if (options && options.order) {
  19109. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  19110. }
  19111. // redraw everything
  19112. this.redraw();
  19113. };
  19114. /**
  19115. * Returns true when the Timeline is active.
  19116. * @returns {boolean}
  19117. */
  19118. Core.prototype.isActive = function () {
  19119. return !this.activator || this.activator.active;
  19120. };
  19121. /**
  19122. * Destroy the Core, clean up all DOM elements and event listeners.
  19123. */
  19124. Core.prototype.destroy = function () {
  19125. // unbind datasets
  19126. this.clear();
  19127. // remove all event listeners
  19128. this.off();
  19129. // stop checking for changed size
  19130. this._stopAutoResize();
  19131. // remove from DOM
  19132. if (this.dom.root.parentNode) {
  19133. this.dom.root.parentNode.removeChild(this.dom.root);
  19134. }
  19135. this.dom = null;
  19136. // remove Activator
  19137. if (this.activator) {
  19138. this.activator.destroy();
  19139. delete this.activator;
  19140. }
  19141. // cleanup hammer touch events
  19142. for (var event in this.listeners) {
  19143. if (this.listeners.hasOwnProperty(event)) {
  19144. delete this.listeners[event];
  19145. }
  19146. }
  19147. this.listeners = null;
  19148. this.hammer = null;
  19149. // give all components the opportunity to cleanup
  19150. this.components.forEach(function (component) {
  19151. component.destroy();
  19152. });
  19153. this.body = null;
  19154. };
  19155. /**
  19156. * Set a custom time bar
  19157. * @param {Date} time
  19158. */
  19159. Core.prototype.setCustomTime = function (time) {
  19160. if (!this.customTime) {
  19161. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  19162. }
  19163. this.customTime.setCustomTime(time);
  19164. };
  19165. /**
  19166. * Retrieve the current custom time.
  19167. * @return {Date} customTime
  19168. */
  19169. Core.prototype.getCustomTime = function() {
  19170. if (!this.customTime) {
  19171. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  19172. }
  19173. return this.customTime.getCustomTime();
  19174. };
  19175. /**
  19176. * Get the id's of the currently visible items.
  19177. * @returns {Array} The ids of the visible items
  19178. */
  19179. Core.prototype.getVisibleItems = function() {
  19180. return this.itemSet && this.itemSet.getVisibleItems() || [];
  19181. };
  19182. /**
  19183. * Clear the Core. By Default, items, groups and options are cleared.
  19184. * Example usage:
  19185. *
  19186. * timeline.clear(); // clear items, groups, and options
  19187. * timeline.clear({options: true}); // clear options only
  19188. *
  19189. * @param {Object} [what] Optionally specify what to clear. By default:
  19190. * {items: true, groups: true, options: true}
  19191. */
  19192. Core.prototype.clear = function(what) {
  19193. // clear items
  19194. if (!what || what.items) {
  19195. this.setItems(null);
  19196. }
  19197. // clear groups
  19198. if (!what || what.groups) {
  19199. this.setGroups(null);
  19200. }
  19201. // clear options of timeline and of each of the components
  19202. if (!what || what.options) {
  19203. this.components.forEach(function (component) {
  19204. component.setOptions(component.defaultOptions);
  19205. });
  19206. this.setOptions(this.defaultOptions); // this will also do a redraw
  19207. }
  19208. };
  19209. /**
  19210. * Set Core window such that it fits all items
  19211. * @param {Object} [options] Available options:
  19212. * `animate: boolean | number`
  19213. * If true (default), the range is animated
  19214. * smoothly to the new window.
  19215. * If a number, the number is taken as duration
  19216. * for the animation. Default duration is 500 ms.
  19217. */
  19218. Core.prototype.fit = function(options) {
  19219. var range = this._getDataRange();
  19220. // skip range set if there is no start and end date
  19221. if (range.start === null && range.end === null) {
  19222. return;
  19223. }
  19224. var animate = (options && options.animate !== undefined) ? options.animate : true;
  19225. this.range.setRange(range.start, range.end, animate);
  19226. };
  19227. /**
  19228. * Calculate the data range of the items and applies a 5% window around it.
  19229. * @returns {{start: Date | null, end: Date | null}}
  19230. * @protected
  19231. */
  19232. Core.prototype._getDataRange = function() {
  19233. // apply the data range as range
  19234. var dataRange = this.getItemRange();
  19235. // add 5% space on both sides
  19236. var start = dataRange.min;
  19237. var end = dataRange.max;
  19238. if (start != null && end != null) {
  19239. var interval = (end.valueOf() - start.valueOf());
  19240. if (interval <= 0) {
  19241. // prevent an empty interval
  19242. interval = 24 * 60 * 60 * 1000; // 1 day
  19243. }
  19244. start = new Date(start.valueOf() - interval * 0.05);
  19245. end = new Date(end.valueOf() + interval * 0.05);
  19246. }
  19247. return {
  19248. start: start,
  19249. end: end
  19250. }
  19251. };
  19252. /**
  19253. * Set the visible window. Both parameters are optional, you can change only
  19254. * start or only end. Syntax:
  19255. *
  19256. * TimeLine.setWindow(start, end)
  19257. * TimeLine.setWindow(range)
  19258. *
  19259. * Where start and end can be a Date, number, or string, and range is an
  19260. * object with properties start and end.
  19261. *
  19262. * @param {Date | Number | String | Object} [start] Start date of visible window
  19263. * @param {Date | Number | String} [end] End date of visible window
  19264. * @param {Object} [options] Available options:
  19265. * `animate: boolean | number`
  19266. * If true (default), the range is animated
  19267. * smoothly to the new window.
  19268. * If a number, the number is taken as duration
  19269. * for the animation. Default duration is 500 ms.
  19270. */
  19271. Core.prototype.setWindow = function(start, end, options) {
  19272. var animate = (options && options.animate !== undefined) ? options.animate : true;
  19273. if (arguments.length == 1) {
  19274. var range = arguments[0];
  19275. this.range.setRange(range.start, range.end, animate);
  19276. }
  19277. else {
  19278. this.range.setRange(start, end, animate);
  19279. }
  19280. };
  19281. /**
  19282. * Move the window such that given time is centered on screen.
  19283. * @param {Date | Number | String} time
  19284. * @param {Object} [options] Available options:
  19285. * `animate: boolean | number`
  19286. * If true (default), the range is animated
  19287. * smoothly to the new window.
  19288. * If a number, the number is taken as duration
  19289. * for the animation. Default duration is 500 ms.
  19290. */
  19291. Core.prototype.moveTo = function(time, options) {
  19292. var interval = this.range.end - this.range.start;
  19293. var t = util.convert(time, 'Date').valueOf();
  19294. var start = t - interval / 2;
  19295. var end = t + interval / 2;
  19296. var animate = (options && options.animate !== undefined) ? options.animate : true;
  19297. this.range.setRange(start, end, animate);
  19298. };
  19299. /**
  19300. * Get the visible window
  19301. * @return {{start: Date, end: Date}} Visible range
  19302. */
  19303. Core.prototype.getWindow = function() {
  19304. var range = this.range.getRange();
  19305. return {
  19306. start: new Date(range.start),
  19307. end: new Date(range.end)
  19308. };
  19309. };
  19310. /**
  19311. * Force a redraw of the Core. Can be useful to manually redraw when
  19312. * option autoResize=false
  19313. */
  19314. Core.prototype.redraw = function() {
  19315. var resized = false;
  19316. var options = this.options;
  19317. var props = this.props;
  19318. var dom = this.dom;
  19319. if (!dom) return; // when destroyed
  19320. DateUtil.updateHiddenDates(this.body, this.options.hiddenDates);
  19321. // update class names
  19322. if (options.orientation == 'top') {
  19323. util.addClassName(dom.root, 'top');
  19324. util.removeClassName(dom.root, 'bottom');
  19325. }
  19326. else {
  19327. util.removeClassName(dom.root, 'top');
  19328. util.addClassName(dom.root, 'bottom');
  19329. }
  19330. // update root width and height options
  19331. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  19332. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  19333. dom.root.style.width = util.option.asSize(options.width, '');
  19334. // calculate border widths
  19335. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  19336. props.border.right = props.border.left;
  19337. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  19338. props.border.bottom = props.border.top;
  19339. var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight;
  19340. var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  19341. // workaround for a bug in IE: the clientWidth of an element with
  19342. // a height:0px and overflow:hidden is not calculated and always has value 0
  19343. if (dom.centerContainer.clientHeight === 0) {
  19344. props.border.left = props.border.top;
  19345. props.border.right = props.border.left;
  19346. }
  19347. if (dom.root.clientHeight === 0) {
  19348. borderRootWidth = borderRootHeight;
  19349. }
  19350. // calculate the heights. If any of the side panels is empty, we set the height to
  19351. // minus the border width, such that the border will be invisible
  19352. props.center.height = dom.center.offsetHeight;
  19353. props.left.height = dom.left.offsetHeight;
  19354. props.right.height = dom.right.offsetHeight;
  19355. props.top.height = dom.top.clientHeight || -props.border.top;
  19356. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  19357. // TODO: compensate borders when any of the panels is empty.
  19358. // apply auto height
  19359. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  19360. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  19361. var autoHeight = props.top.height + contentHeight + props.bottom.height +
  19362. borderRootHeight + props.border.top + props.border.bottom;
  19363. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  19364. // calculate heights of the content panels
  19365. props.root.height = dom.root.offsetHeight;
  19366. props.background.height = props.root.height - borderRootHeight;
  19367. var containerHeight = props.root.height - props.top.height - props.bottom.height -
  19368. borderRootHeight;
  19369. props.centerContainer.height = containerHeight;
  19370. props.leftContainer.height = containerHeight;
  19371. props.rightContainer.height = props.leftContainer.height;
  19372. // calculate the widths of the panels
  19373. props.root.width = dom.root.offsetWidth;
  19374. props.background.width = props.root.width - borderRootWidth;
  19375. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  19376. props.leftContainer.width = props.left.width;
  19377. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  19378. props.rightContainer.width = props.right.width;
  19379. var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth;
  19380. props.center.width = centerWidth;
  19381. props.centerContainer.width = centerWidth;
  19382. props.top.width = centerWidth;
  19383. props.bottom.width = centerWidth;
  19384. // resize the panels
  19385. dom.background.style.height = props.background.height + 'px';
  19386. dom.backgroundVertical.style.height = props.background.height + 'px';
  19387. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  19388. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  19389. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  19390. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  19391. dom.background.style.width = props.background.width + 'px';
  19392. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  19393. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  19394. dom.centerContainer.style.width = props.center.width + 'px';
  19395. dom.top.style.width = props.top.width + 'px';
  19396. dom.bottom.style.width = props.bottom.width + 'px';
  19397. // reposition the panels
  19398. dom.background.style.left = '0';
  19399. dom.background.style.top = '0';
  19400. dom.backgroundVertical.style.left = (props.left.width + props.border.left) + 'px';
  19401. dom.backgroundVertical.style.top = '0';
  19402. dom.backgroundHorizontal.style.left = '0';
  19403. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  19404. dom.centerContainer.style.left = props.left.width + 'px';
  19405. dom.centerContainer.style.top = props.top.height + 'px';
  19406. dom.leftContainer.style.left = '0';
  19407. dom.leftContainer.style.top = props.top.height + 'px';
  19408. dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px';
  19409. dom.rightContainer.style.top = props.top.height + 'px';
  19410. dom.top.style.left = props.left.width + 'px';
  19411. dom.top.style.top = '0';
  19412. dom.bottom.style.left = props.left.width + 'px';
  19413. dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px';
  19414. // update the scrollTop, feasible range for the offset can be changed
  19415. // when the height of the Core or of the contents of the center changed
  19416. this._updateScrollTop();
  19417. // reposition the scrollable contents
  19418. var offset = this.props.scrollTop;
  19419. if (options.orientation == 'bottom') {
  19420. offset += Math.max(this.props.centerContainer.height - this.props.center.height -
  19421. this.props.border.top - this.props.border.bottom, 0);
  19422. }
  19423. dom.center.style.left = '0';
  19424. dom.center.style.top = offset + 'px';
  19425. dom.left.style.left = '0';
  19426. dom.left.style.top = offset + 'px';
  19427. dom.right.style.left = '0';
  19428. dom.right.style.top = offset + 'px';
  19429. // show shadows when vertical scrolling is available
  19430. var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : '';
  19431. var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : '';
  19432. dom.shadowTop.style.visibility = visibilityTop;
  19433. dom.shadowBottom.style.visibility = visibilityBottom;
  19434. dom.shadowTopLeft.style.visibility = visibilityTop;
  19435. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  19436. dom.shadowTopRight.style.visibility = visibilityTop;
  19437. dom.shadowBottomRight.style.visibility = visibilityBottom;
  19438. // redraw all components
  19439. this.components.forEach(function (component) {
  19440. resized = component.redraw() || resized;
  19441. });
  19442. if (resized) {
  19443. // keep repainting until all sizes are settled
  19444. var MAX_REDRAWS = 3; // maximum number of consecutive redraws
  19445. if (this.redrawCount < MAX_REDRAWS) {
  19446. this.redrawCount++;
  19447. this.redraw();
  19448. }
  19449. else {
  19450. console.log('WARNING: infinite loop in redraw?')
  19451. throw new Error("bla")
  19452. }
  19453. this.redrawCount = 0;
  19454. }
  19455. this.emit("finishedRedraw");
  19456. };
  19457. // TODO: deprecated since version 1.1.0, remove some day
  19458. Core.prototype.repaint = function () {
  19459. throw new Error('Function repaint is deprecated. Use redraw instead.');
  19460. };
  19461. /**
  19462. * Set a current time. This can be used for example to ensure that a client's
  19463. * time is synchronized with a shared server time.
  19464. * Only applicable when option `showCurrentTime` is true.
  19465. * @param {Date | String | Number} time A Date, unix timestamp, or
  19466. * ISO date string.
  19467. */
  19468. Core.prototype.setCurrentTime = function(time) {
  19469. if (!this.currentTime) {
  19470. throw new Error('Option showCurrentTime must be true');
  19471. }
  19472. this.currentTime.setCurrentTime(time);
  19473. };
  19474. /**
  19475. * Get the current time.
  19476. * Only applicable when option `showCurrentTime` is true.
  19477. * @return {Date} Returns the current time.
  19478. */
  19479. Core.prototype.getCurrentTime = function() {
  19480. if (!this.currentTime) {
  19481. throw new Error('Option showCurrentTime must be true');
  19482. }
  19483. return this.currentTime.getCurrentTime();
  19484. };
  19485. /**
  19486. * Convert a position on screen (pixels) to a datetime
  19487. * @param {int} x Position on the screen in pixels
  19488. * @return {Date} time The datetime the corresponds with given position x
  19489. * @private
  19490. */
  19491. // TODO: move this function to Range
  19492. Core.prototype._toTime = function(x) {
  19493. return DateUtil.toTime(this, x, this.props.center.width);
  19494. };
  19495. /**
  19496. * Convert a position on the global screen (pixels) to a datetime
  19497. * @param {int} x Position on the screen in pixels
  19498. * @return {Date} time The datetime the corresponds with given position x
  19499. * @private
  19500. */
  19501. // TODO: move this function to Range
  19502. Core.prototype._toGlobalTime = function(x) {
  19503. return DateUtil.toTime(this, x, this.props.root.width);
  19504. //var conversion = this.range.conversion(this.props.root.width);
  19505. //return new Date(x / conversion.scale + conversion.offset);
  19506. };
  19507. /**
  19508. * Convert a datetime (Date object) into a position on the screen
  19509. * @param {Date} time A date
  19510. * @return {int} x The position on the screen in pixels which corresponds
  19511. * with the given date.
  19512. * @private
  19513. */
  19514. // TODO: move this function to Range
  19515. Core.prototype._toScreen = function(time) {
  19516. return DateUtil.toScreen(this, time, this.props.center.width);
  19517. };
  19518. /**
  19519. * Convert a datetime (Date object) into a position on the root
  19520. * This is used to get the pixel density estimate for the screen, not the center panel
  19521. * @param {Date} time A date
  19522. * @return {int} x The position on root in pixels which corresponds
  19523. * with the given date.
  19524. * @private
  19525. */
  19526. // TODO: move this function to Range
  19527. Core.prototype._toGlobalScreen = function(time) {
  19528. return DateUtil.toScreen(this, time, this.props.root.width);
  19529. //var conversion = this.range.conversion(this.props.root.width);
  19530. //return (time.valueOf() - conversion.offset) * conversion.scale;
  19531. };
  19532. /**
  19533. * Initialize watching when option autoResize is true
  19534. * @private
  19535. */
  19536. Core.prototype._initAutoResize = function () {
  19537. if (this.options.autoResize == true) {
  19538. this._startAutoResize();
  19539. }
  19540. else {
  19541. this._stopAutoResize();
  19542. }
  19543. };
  19544. /**
  19545. * Watch for changes in the size of the container. On resize, the Panel will
  19546. * automatically redraw itself.
  19547. * @private
  19548. */
  19549. Core.prototype._startAutoResize = function () {
  19550. var me = this;
  19551. this._stopAutoResize();
  19552. this._onResize = function() {
  19553. if (me.options.autoResize != true) {
  19554. // stop watching when the option autoResize is changed to false
  19555. me._stopAutoResize();
  19556. return;
  19557. }
  19558. if (me.dom.root) {
  19559. // check whether the frame is resized
  19560. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  19561. // IE does not restore the clientWidth from 0 to the actual width after
  19562. // changing the timeline's container display style from none to visible
  19563. if ((me.dom.root.offsetWidth != me.props.lastWidth) ||
  19564. (me.dom.root.offsetHeight != me.props.lastHeight)) {
  19565. me.props.lastWidth = me.dom.root.offsetWidth;
  19566. me.props.lastHeight = me.dom.root.offsetHeight;
  19567. me.emit('change');
  19568. }
  19569. }
  19570. };
  19571. // add event listener to window resize
  19572. util.addEventListener(window, 'resize', this._onResize);
  19573. this.watchTimer = setInterval(this._onResize, 1000);
  19574. };
  19575. /**
  19576. * Stop watching for a resize of the frame.
  19577. * @private
  19578. */
  19579. Core.prototype._stopAutoResize = function () {
  19580. if (this.watchTimer) {
  19581. clearInterval(this.watchTimer);
  19582. this.watchTimer = undefined;
  19583. }
  19584. // remove event listener on window.resize
  19585. util.removeEventListener(window, 'resize', this._onResize);
  19586. this._onResize = null;
  19587. };
  19588. /**
  19589. * Start moving the timeline vertically
  19590. * @param {Event} event
  19591. * @private
  19592. */
  19593. Core.prototype._onTouch = function (event) {
  19594. this.touch.allowDragging = true;
  19595. };
  19596. /**
  19597. * Start moving the timeline vertically
  19598. * @param {Event} event
  19599. * @private
  19600. */
  19601. Core.prototype._onPinch = function (event) {
  19602. this.touch.allowDragging = false;
  19603. };
  19604. /**
  19605. * Start moving the timeline vertically
  19606. * @param {Event} event
  19607. * @private
  19608. */
  19609. Core.prototype._onDragStart = function (event) {
  19610. this.touch.initialScrollTop = this.props.scrollTop;
  19611. };
  19612. /**
  19613. * Move the timeline vertically
  19614. * @param {Event} event
  19615. * @private
  19616. */
  19617. Core.prototype._onDrag = function (event) {
  19618. // refuse to drag when we where pinching to prevent the timeline make a jump
  19619. // when releasing the fingers in opposite order from the touch screen
  19620. if (!this.touch.allowDragging) return;
  19621. var delta = event.gesture.deltaY;
  19622. var oldScrollTop = this._getScrollTop();
  19623. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  19624. if (newScrollTop != oldScrollTop) {
  19625. this.redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already
  19626. this.emit("verticalDrag");
  19627. }
  19628. };
  19629. /**
  19630. * Apply a scrollTop
  19631. * @param {Number} scrollTop
  19632. * @returns {Number} scrollTop Returns the applied scrollTop
  19633. * @private
  19634. */
  19635. Core.prototype._setScrollTop = function (scrollTop) {
  19636. this.props.scrollTop = scrollTop;
  19637. this._updateScrollTop();
  19638. return this.props.scrollTop;
  19639. };
  19640. /**
  19641. * Update the current scrollTop when the height of the containers has been changed
  19642. * @returns {Number} scrollTop Returns the applied scrollTop
  19643. * @private
  19644. */
  19645. Core.prototype._updateScrollTop = function () {
  19646. // recalculate the scrollTopMin
  19647. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  19648. if (scrollTopMin != this.props.scrollTopMin) {
  19649. // in case of bottom orientation, change the scrollTop such that the contents
  19650. // do not move relative to the time axis at the bottom
  19651. if (this.options.orientation == 'bottom') {
  19652. this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin);
  19653. }
  19654. this.props.scrollTopMin = scrollTopMin;
  19655. }
  19656. // limit the scrollTop to the feasible scroll range
  19657. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  19658. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  19659. return this.props.scrollTop;
  19660. };
  19661. /**
  19662. * Get the current scrollTop
  19663. * @returns {number} scrollTop
  19664. * @private
  19665. */
  19666. Core.prototype._getScrollTop = function () {
  19667. return this.props.scrollTop;
  19668. };
  19669. module.exports = Core;
  19670. /***/ },
  19671. /* 47 */
  19672. /***/ function(module, exports, __webpack_require__) {
  19673. var Hammer = __webpack_require__(45);
  19674. /**
  19675. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  19676. * @param {Element} element
  19677. * @param {Event} event
  19678. */
  19679. exports.fakeGesture = function(element, event) {
  19680. var eventType = null;
  19681. // for hammer.js 1.0.5
  19682. // var gesture = Hammer.event.collectEventData(this, eventType, event);
  19683. // for hammer.js 1.0.6+
  19684. var touches = Hammer.event.getTouchList(event, eventType);
  19685. var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  19686. // on IE in standards mode, no touches are recognized by hammer.js,
  19687. // resulting in NaN values for center.pageX and center.pageY
  19688. if (isNaN(gesture.center.pageX)) {
  19689. gesture.center.pageX = event.pageX;
  19690. }
  19691. if (isNaN(gesture.center.pageY)) {
  19692. gesture.center.pageY = event.pageY;
  19693. }
  19694. return gesture;
  19695. };
  19696. /***/ },
  19697. /* 48 */
  19698. /***/ function(module, exports, __webpack_require__) {
  19699. // English
  19700. exports['en'] = {
  19701. current: 'current',
  19702. time: 'time'
  19703. };
  19704. exports['en_EN'] = exports['en'];
  19705. exports['en_US'] = exports['en'];
  19706. // Dutch
  19707. exports['nl'] = {
  19708. custom: 'aangepaste',
  19709. time: 'tijd'
  19710. };
  19711. exports['nl_NL'] = exports['nl'];
  19712. exports['nl_BE'] = exports['nl'];
  19713. /***/ },
  19714. /* 49 */
  19715. /***/ function(module, exports, __webpack_require__) {
  19716. // English
  19717. exports['en'] = {
  19718. edit: 'Edit',
  19719. del: 'Delete selected',
  19720. back: 'Back',
  19721. addNode: 'Add Node',
  19722. addEdge: 'Add Edge',
  19723. editNode: 'Edit Node',
  19724. editEdge: 'Edit Edge',
  19725. addDescription: 'Click in an empty space to place a new node.',
  19726. edgeDescription: 'Click on a node and drag the edge to another node to connect them.',
  19727. editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.',
  19728. createEdgeError: 'Cannot link edges to a cluster.',
  19729. deleteClusterError: 'Clusters cannot be deleted.'
  19730. };
  19731. exports['en_EN'] = exports['en'];
  19732. exports['en_US'] = exports['en'];
  19733. // Dutch
  19734. exports['nl'] = {
  19735. edit: 'Wijzigen',
  19736. del: 'Selectie verwijderen',
  19737. back: 'Terug',
  19738. addNode: 'Node toevoegen',
  19739. addEdge: 'Link toevoegen',
  19740. editNode: 'Node wijzigen',
  19741. editEdge: 'Link wijzigen',
  19742. addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.',
  19743. edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.',
  19744. editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.',
  19745. createEdgeError: 'Kan geen link maken naar een cluster.',
  19746. deleteClusterError: 'Clusters kunnen niet worden verwijderd.'
  19747. };
  19748. exports['nl_NL'] = exports['nl'];
  19749. exports['nl_BE'] = exports['nl'];
  19750. /***/ },
  19751. /* 50 */
  19752. /***/ function(module, exports, __webpack_require__) {
  19753. /**
  19754. * Canvas shapes used by Network
  19755. */
  19756. if (typeof CanvasRenderingContext2D !== 'undefined') {
  19757. /**
  19758. * Draw a circle shape
  19759. */
  19760. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  19761. this.beginPath();
  19762. this.arc(x, y, r, 0, 2*Math.PI, false);
  19763. };
  19764. /**
  19765. * Draw a square shape
  19766. * @param {Number} x horizontal center
  19767. * @param {Number} y vertical center
  19768. * @param {Number} r size, width and height of the square
  19769. */
  19770. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  19771. this.beginPath();
  19772. this.rect(x - r, y - r, r * 2, r * 2);
  19773. };
  19774. /**
  19775. * Draw a triangle shape
  19776. * @param {Number} x horizontal center
  19777. * @param {Number} y vertical center
  19778. * @param {Number} r radius, half the length of the sides of the triangle
  19779. */
  19780. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  19781. // http://en.wikipedia.org/wiki/Equilateral_triangle
  19782. this.beginPath();
  19783. var s = r * 2;
  19784. var s2 = s / 2;
  19785. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  19786. var h = Math.sqrt(s * s - s2 * s2); // height
  19787. this.moveTo(x, y - (h - ir));
  19788. this.lineTo(x + s2, y + ir);
  19789. this.lineTo(x - s2, y + ir);
  19790. this.lineTo(x, y - (h - ir));
  19791. this.closePath();
  19792. };
  19793. /**
  19794. * Draw a triangle shape in downward orientation
  19795. * @param {Number} x horizontal center
  19796. * @param {Number} y vertical center
  19797. * @param {Number} r radius
  19798. */
  19799. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  19800. // http://en.wikipedia.org/wiki/Equilateral_triangle
  19801. this.beginPath();
  19802. var s = r * 2;
  19803. var s2 = s / 2;
  19804. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  19805. var h = Math.sqrt(s * s - s2 * s2); // height
  19806. this.moveTo(x, y + (h - ir));
  19807. this.lineTo(x + s2, y - ir);
  19808. this.lineTo(x - s2, y - ir);
  19809. this.lineTo(x, y + (h - ir));
  19810. this.closePath();
  19811. };
  19812. /**
  19813. * Draw a star shape, a star with 5 points
  19814. * @param {Number} x horizontal center
  19815. * @param {Number} y vertical center
  19816. * @param {Number} r radius, half the length of the sides of the triangle
  19817. */
  19818. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  19819. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  19820. this.beginPath();
  19821. for (var n = 0; n < 10; n++) {
  19822. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  19823. this.lineTo(
  19824. x + radius * Math.sin(n * 2 * Math.PI / 10),
  19825. y - radius * Math.cos(n * 2 * Math.PI / 10)
  19826. );
  19827. }
  19828. this.closePath();
  19829. };
  19830. /**
  19831. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  19832. */
  19833. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  19834. var r2d = Math.PI/180;
  19835. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  19836. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  19837. this.beginPath();
  19838. this.moveTo(x+r,y);
  19839. this.lineTo(x+w-r,y);
  19840. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  19841. this.lineTo(x+w,y+h-r);
  19842. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  19843. this.lineTo(x+r,y+h);
  19844. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  19845. this.lineTo(x,y+r);
  19846. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  19847. };
  19848. /**
  19849. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  19850. */
  19851. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  19852. var kappa = .5522848,
  19853. ox = (w / 2) * kappa, // control point offset horizontal
  19854. oy = (h / 2) * kappa, // control point offset vertical
  19855. xe = x + w, // x-end
  19856. ye = y + h, // y-end
  19857. xm = x + w / 2, // x-middle
  19858. ym = y + h / 2; // y-middle
  19859. this.beginPath();
  19860. this.moveTo(x, ym);
  19861. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  19862. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  19863. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  19864. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  19865. };
  19866. /**
  19867. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  19868. */
  19869. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  19870. var f = 1/3;
  19871. var wEllipse = w;
  19872. var hEllipse = h * f;
  19873. var kappa = .5522848,
  19874. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  19875. oy = (hEllipse / 2) * kappa, // control point offset vertical
  19876. xe = x + wEllipse, // x-end
  19877. ye = y + hEllipse, // y-end
  19878. xm = x + wEllipse / 2, // x-middle
  19879. ym = y + hEllipse / 2, // y-middle
  19880. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  19881. yeb = y + h; // y-end, bottom ellipse
  19882. this.beginPath();
  19883. this.moveTo(xe, ym);
  19884. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  19885. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  19886. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  19887. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  19888. this.lineTo(xe, ymb);
  19889. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  19890. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  19891. this.lineTo(x, ym);
  19892. };
  19893. /**
  19894. * Draw an arrow point (no line)
  19895. */
  19896. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  19897. // tail
  19898. var xt = x - length * Math.cos(angle);
  19899. var yt = y - length * Math.sin(angle);
  19900. // inner tail
  19901. // TODO: allow to customize different shapes
  19902. var xi = x - length * 0.9 * Math.cos(angle);
  19903. var yi = y - length * 0.9 * Math.sin(angle);
  19904. // left
  19905. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  19906. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  19907. // right
  19908. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  19909. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  19910. this.beginPath();
  19911. this.moveTo(x, y);
  19912. this.lineTo(xl, yl);
  19913. this.lineTo(xi, yi);
  19914. this.lineTo(xr, yr);
  19915. this.closePath();
  19916. };
  19917. /**
  19918. * Sets up the dashedLine functionality for drawing
  19919. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  19920. * @author David Jordan
  19921. * @date 2012-08-08
  19922. */
  19923. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  19924. if (!dashArray) dashArray=[10,5];
  19925. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  19926. var dashCount = dashArray.length;
  19927. this.moveTo(x, y);
  19928. var dx = (x2-x), dy = (y2-y);
  19929. var slope = dy/dx;
  19930. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  19931. var dashIndex=0, draw=true;
  19932. while (distRemaining>=0.1){
  19933. var dashLength = dashArray[dashIndex++%dashCount];
  19934. if (dashLength > distRemaining) dashLength = distRemaining;
  19935. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  19936. if (dx<0) xStep = -xStep;
  19937. x += xStep;
  19938. y += slope*xStep;
  19939. this[draw ? 'lineTo' : 'moveTo'](x,y);
  19940. distRemaining -= dashLength;
  19941. draw = !draw;
  19942. }
  19943. };
  19944. // TODO: add diamond shape
  19945. }
  19946. /***/ },
  19947. /* 51 */
  19948. /***/ function(module, exports, __webpack_require__) {
  19949. /**
  19950. * Created by Alex on 11/11/2014.
  19951. */
  19952. var DOMutil = __webpack_require__(2);
  19953. var Points = __webpack_require__(53);
  19954. function Line(groupId, options) {
  19955. this.groupId = groupId;
  19956. this.options = options;
  19957. }
  19958. Line.prototype.getYRange = function(groupData) {
  19959. var yMin = groupData[0].y;
  19960. var yMax = groupData[0].y;
  19961. for (var j = 0; j < groupData.length; j++) {
  19962. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  19963. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  19964. }
  19965. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  19966. };
  19967. /**
  19968. * draw a line graph
  19969. *
  19970. * @param dataset
  19971. * @param group
  19972. */
  19973. Line.prototype.draw = function (dataset, group, framework) {
  19974. if (dataset != null) {
  19975. if (dataset.length > 0) {
  19976. var path, d;
  19977. var svgHeight = Number(framework.svg.style.height.replace('px',''));
  19978. path = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  19979. path.setAttributeNS(null, "class", group.className);
  19980. if(group.style !== undefined) {
  19981. path.setAttributeNS(null, "style", group.style);
  19982. }
  19983. // construct path from dataset
  19984. if (group.options.catmullRom.enabled == true) {
  19985. d = Line._catmullRom(dataset, group);
  19986. }
  19987. else {
  19988. d = Line._linear(dataset);
  19989. }
  19990. // append with points for fill and finalize the path
  19991. if (group.options.shaded.enabled == true) {
  19992. var fillPath = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  19993. var dFill;
  19994. if (group.options.shaded.orientation == 'top') {
  19995. dFill = 'M' + dataset[0].x + ',' + 0 + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + 0;
  19996. }
  19997. else {
  19998. dFill = 'M' + dataset[0].x + ',' + svgHeight + ' ' + d + 'L' + dataset[dataset.length - 1].x + ',' + svgHeight;
  19999. }
  20000. fillPath.setAttributeNS(null, "class", group.className + " fill");
  20001. if(group.options.shaded.style !== undefined) {
  20002. fillPath.setAttributeNS(null, "style", group.options.shaded.style);
  20003. }
  20004. fillPath.setAttributeNS(null, "d", dFill);
  20005. }
  20006. // copy properties to path for drawing.
  20007. path.setAttributeNS(null, 'd', 'M' + d);
  20008. // draw points
  20009. if (group.options.drawPoints.enabled == true) {
  20010. Points.draw(dataset, group, framework);
  20011. }
  20012. }
  20013. }
  20014. };
  20015. /**
  20016. * This uses an uniform parametrization of the CatmullRom algorithm:
  20017. * 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al.
  20018. * @param data
  20019. * @returns {string}
  20020. * @private
  20021. */
  20022. Line._catmullRomUniform = function(data) {
  20023. // catmull rom
  20024. var p0, p1, p2, p3, bp1, bp2;
  20025. var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' ';
  20026. var normalization = 1/6;
  20027. var length = data.length;
  20028. for (var i = 0; i < length - 1; i++) {
  20029. p0 = (i == 0) ? data[0] : data[i-1];
  20030. p1 = data[i];
  20031. p2 = data[i+1];
  20032. p3 = (i + 2 < length) ? data[i+2] : p2;
  20033. // Catmull-Rom to Cubic Bezier conversion matrix
  20034. // 0 1 0 0
  20035. // -1/6 1 1/6 0
  20036. // 0 1/6 1 -1/6
  20037. // 0 0 1 0
  20038. // bp0 = { x: p1.x, y: p1.y };
  20039. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)};
  20040. bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)};
  20041. // bp0 = { x: p2.x, y: p2.y };
  20042. d += 'C' +
  20043. bp1.x + ',' +
  20044. bp1.y + ' ' +
  20045. bp2.x + ',' +
  20046. bp2.y + ' ' +
  20047. p2.x + ',' +
  20048. p2.y + ' ';
  20049. }
  20050. return d;
  20051. };
  20052. /**
  20053. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  20054. * By default, the centripetal parameterization is used because this gives the nicest results.
  20055. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  20056. *
  20057. * One optimization can be used to reuse distances since this is a sliding window approach.
  20058. * @param data
  20059. * @param group
  20060. * @returns {string}
  20061. * @private
  20062. */
  20063. Line._catmullRom = function(data, group) {
  20064. var alpha = group.options.catmullRom.alpha;
  20065. if (alpha == 0 || alpha === undefined) {
  20066. return this._catmullRomUniform(data);
  20067. }
  20068. else {
  20069. var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M;
  20070. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  20071. var d = Math.round(data[0].x) + ',' + Math.round(data[0].y) + ' ';
  20072. var length = data.length;
  20073. for (var i = 0; i < length - 1; i++) {
  20074. p0 = (i == 0) ? data[0] : data[i-1];
  20075. p1 = data[i];
  20076. p2 = data[i+1];
  20077. p3 = (i + 2 < length) ? data[i+2] : p2;
  20078. d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2));
  20079. d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2));
  20080. d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2));
  20081. // Catmull-Rom to Cubic Bezier conversion matrix
  20082. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  20083. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  20084. // [ 0 1 0 0 ]
  20085. // [ -d2^2a /N A/N d1^2a /N 0 ]
  20086. // [ 0 d3^2a /M B/M -d2^2a /M ]
  20087. // [ 0 0 1 0 ]
  20088. d3powA = Math.pow(d3, alpha);
  20089. d3pow2A = Math.pow(d3,2*alpha);
  20090. d2powA = Math.pow(d2, alpha);
  20091. d2pow2A = Math.pow(d2,2*alpha);
  20092. d1powA = Math.pow(d1, alpha);
  20093. d1pow2A = Math.pow(d1,2*alpha);
  20094. A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A;
  20095. B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A;
  20096. N = 3*d1powA * (d1powA + d2powA);
  20097. if (N > 0) {N = 1 / N;}
  20098. M = 3*d3powA * (d3powA + d2powA);
  20099. if (M > 0) {M = 1 / M;}
  20100. bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N),
  20101. y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)};
  20102. bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M),
  20103. y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)};
  20104. if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;}
  20105. if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;}
  20106. d += 'C' +
  20107. bp1.x + ',' +
  20108. bp1.y + ' ' +
  20109. bp2.x + ',' +
  20110. bp2.y + ' ' +
  20111. p2.x + ',' +
  20112. p2.y + ' ';
  20113. }
  20114. return d;
  20115. }
  20116. };
  20117. /**
  20118. * this generates the SVG path for a linear drawing between datapoints.
  20119. * @param data
  20120. * @returns {string}
  20121. * @private
  20122. */
  20123. Line._linear = function(data) {
  20124. // linear
  20125. var d = '';
  20126. for (var i = 0; i < data.length; i++) {
  20127. if (i == 0) {
  20128. d += data[i].x + ',' + data[i].y;
  20129. }
  20130. else {
  20131. d += ' ' + data[i].x + ',' + data[i].y;
  20132. }
  20133. }
  20134. return d;
  20135. };
  20136. module.exports = Line;
  20137. /***/ },
  20138. /* 52 */
  20139. /***/ function(module, exports, __webpack_require__) {
  20140. /**
  20141. * Created by Alex on 11/11/2014.
  20142. */
  20143. var DOMutil = __webpack_require__(2);
  20144. var Points = __webpack_require__(53);
  20145. function Bargraph(groupId, options) {
  20146. this.groupId = groupId;
  20147. this.options = options;
  20148. }
  20149. Bargraph.prototype.getYRange = function(groupData) {
  20150. if (this.options.barChart.handleOverlap != 'stack') {
  20151. var yMin = groupData[0].y;
  20152. var yMax = groupData[0].y;
  20153. for (var j = 0; j < groupData.length; j++) {
  20154. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  20155. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  20156. }
  20157. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  20158. }
  20159. else {
  20160. var barCombinedData = [];
  20161. for (var j = 0; j < groupData.length; j++) {
  20162. barCombinedData.push({
  20163. x: groupData[j].x,
  20164. y: groupData[j].y,
  20165. groupId: this.groupId
  20166. });
  20167. }
  20168. return barCombinedData;
  20169. }
  20170. };
  20171. /**
  20172. * draw a bar graph
  20173. *
  20174. * @param groupIds
  20175. * @param processedGroupData
  20176. */
  20177. Bargraph.draw = function (groupIds, processedGroupData, framework) {
  20178. var combinedData = [];
  20179. var intersections = {};
  20180. var coreDistance;
  20181. var key, drawData;
  20182. var group;
  20183. var i,j;
  20184. var barPoints = 0;
  20185. // combine all barchart data
  20186. for (i = 0; i < groupIds.length; i++) {
  20187. group = framework.groups[groupIds[i]];
  20188. if (group.options.style == 'bar') {
  20189. if (group.visible == true && (framework.options.groups.visibility[groupIds[i]] === undefined || framework.options.groups.visibility[groupIds[i]] == true)) {
  20190. for (j = 0; j < processedGroupData[groupIds[i]].length; j++) {
  20191. combinedData.push({
  20192. x: processedGroupData[groupIds[i]][j].x,
  20193. y: processedGroupData[groupIds[i]][j].y,
  20194. groupId: groupIds[i]
  20195. });
  20196. barPoints += 1;
  20197. }
  20198. }
  20199. }
  20200. }
  20201. if (barPoints == 0) {return;}
  20202. // sort by time and by group
  20203. combinedData.sort(function (a, b) {
  20204. if (a.x == b.x) {
  20205. return a.groupId - b.groupId;
  20206. } else {
  20207. return a.x - b.x;
  20208. }
  20209. });
  20210. // get intersections
  20211. Bargraph._getDataIntersections(intersections, combinedData);
  20212. // plot barchart
  20213. for (i = 0; i < combinedData.length; i++) {
  20214. group = framework.groups[combinedData[i].groupId];
  20215. var minWidth = 0.1 * group.options.barChart.width;
  20216. key = combinedData[i].x;
  20217. var heightOffset = 0;
  20218. if (intersections[key] === undefined) {
  20219. if (i+1 < combinedData.length) {coreDistance = Math.abs(combinedData[i+1].x - key);}
  20220. if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[i-1].x - key));}
  20221. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  20222. }
  20223. else {
  20224. var nextKey = i + (intersections[key].amount - intersections[key].resolved);
  20225. var prevKey = i - (intersections[key].resolved + 1);
  20226. if (nextKey < combinedData.length) {coreDistance = Math.abs(combinedData[nextKey].x - key);}
  20227. if (prevKey > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[prevKey].x - key));}
  20228. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  20229. intersections[key].resolved += 1;
  20230. if (group.options.barChart.handleOverlap == 'stack') {
  20231. heightOffset = intersections[key].accumulated;
  20232. intersections[key].accumulated += group.zeroPosition - combinedData[i].y;
  20233. }
  20234. else if (group.options.barChart.handleOverlap == 'sideBySide') {
  20235. drawData.width = drawData.width / intersections[key].amount;
  20236. drawData.offset += (intersections[key].resolved) * drawData.width - (0.5*drawData.width * (intersections[key].amount+1));
  20237. if (group.options.barChart.align == 'left') {drawData.offset -= 0.5*drawData.width;}
  20238. else if (group.options.barChart.align == 'right') {drawData.offset += 0.5*drawData.width;}
  20239. }
  20240. }
  20241. 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);
  20242. // draw points
  20243. if (group.options.drawPoints.enabled == true) {
  20244. DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg);
  20245. }
  20246. }
  20247. };
  20248. /**
  20249. * Fill the intersections object with counters of how many datapoints share the same x coordinates
  20250. * @param intersections
  20251. * @param combinedData
  20252. * @private
  20253. */
  20254. Bargraph._getDataIntersections = function (intersections, combinedData) {
  20255. // get intersections
  20256. var coreDistance;
  20257. for (var i = 0; i < combinedData.length; i++) {
  20258. if (i + 1 < combinedData.length) {
  20259. coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x);
  20260. }
  20261. if (i > 0) {
  20262. coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x));
  20263. }
  20264. if (coreDistance == 0) {
  20265. if (intersections[combinedData[i].x] === undefined) {
  20266. intersections[combinedData[i].x] = {amount: 0, resolved: 0, accumulated: 0};
  20267. }
  20268. intersections[combinedData[i].x].amount += 1;
  20269. }
  20270. }
  20271. };
  20272. /**
  20273. * Get the width and offset for bargraphs based on the coredistance between datapoints
  20274. *
  20275. * @param coreDistance
  20276. * @param group
  20277. * @param minWidth
  20278. * @returns {{width: Number, offset: Number}}
  20279. * @private
  20280. */
  20281. Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) {
  20282. var width, offset;
  20283. if (coreDistance < group.options.barChart.width && coreDistance > 0) {
  20284. width = coreDistance < minWidth ? minWidth : coreDistance;
  20285. offset = 0; // recalculate offset with the new width;
  20286. if (group.options.barChart.align == 'left') {
  20287. offset -= 0.5 * coreDistance;
  20288. }
  20289. else if (group.options.barChart.align == 'right') {
  20290. offset += 0.5 * coreDistance;
  20291. }
  20292. }
  20293. else {
  20294. // default settings
  20295. width = group.options.barChart.width;
  20296. offset = 0;
  20297. if (group.options.barChart.align == 'left') {
  20298. offset -= 0.5 * group.options.barChart.width;
  20299. }
  20300. else if (group.options.barChart.align == 'right') {
  20301. offset += 0.5 * group.options.barChart.width;
  20302. }
  20303. }
  20304. return {width: width, offset: offset};
  20305. };
  20306. Bargraph.getStackedBarYRange = function(barCombinedData, groupRanges, groupIds, groupLabel, orientation) {
  20307. if (barCombinedData.length > 0) {
  20308. // sort by time and by group
  20309. barCombinedData.sort(function (a, b) {
  20310. if (a.x == b.x) {
  20311. return a.groupId - b.groupId;
  20312. } else {
  20313. return a.x - b.x;
  20314. }
  20315. });
  20316. var intersections = {};
  20317. Bargraph._getDataIntersections(intersections, barCombinedData);
  20318. groupRanges[groupLabel] = Bargraph._getStackedBarYRange(intersections, barCombinedData);
  20319. groupRanges[groupLabel].yAxisOrientation = orientation;
  20320. groupIds.push(groupLabel);
  20321. }
  20322. }
  20323. Bargraph._getStackedBarYRange = function (intersections, combinedData) {
  20324. var key;
  20325. var yMin = combinedData[0].y;
  20326. var yMax = combinedData[0].y;
  20327. for (var i = 0; i < combinedData.length; i++) {
  20328. key = combinedData[i].x;
  20329. if (intersections[key] === undefined) {
  20330. yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin;
  20331. yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax;
  20332. }
  20333. else {
  20334. intersections[key].accumulated += combinedData[i].y;
  20335. }
  20336. }
  20337. for (var xpos in intersections) {
  20338. if (intersections.hasOwnProperty(xpos)) {
  20339. yMin = yMin > intersections[xpos].accumulated ? intersections[xpos].accumulated : yMin;
  20340. yMax = yMax < intersections[xpos].accumulated ? intersections[xpos].accumulated : yMax;
  20341. }
  20342. }
  20343. return {min: yMin, max: yMax};
  20344. };
  20345. module.exports = Bargraph;
  20346. /***/ },
  20347. /* 53 */
  20348. /***/ function(module, exports, __webpack_require__) {
  20349. /**
  20350. * Created by Alex on 11/11/2014.
  20351. */
  20352. var DOMutil = __webpack_require__(2);
  20353. function Points(groupId, options) {
  20354. this.groupId = groupId;
  20355. this.options = options;
  20356. }
  20357. Points.prototype.getYRange = function(groupData) {
  20358. var yMin = groupData[0].y;
  20359. var yMax = groupData[0].y;
  20360. for (var j = 0; j < groupData.length; j++) {
  20361. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  20362. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  20363. }
  20364. return {min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation};
  20365. };
  20366. Points.prototype.draw = function(dataset, group, framework, offset) {
  20367. Points.draw(dataset, group, framework, offset);
  20368. }
  20369. /**
  20370. * draw the data points
  20371. *
  20372. * @param {Array} dataset
  20373. * @param {Object} JSONcontainer
  20374. * @param {Object} svg | SVG DOM element
  20375. * @param {GraphGroup} group
  20376. * @param {Number} [offset]
  20377. */
  20378. Points.draw = function (dataset, group, framework, offset) {
  20379. if (offset === undefined) {offset = 0;}
  20380. for (var i = 0; i < dataset.length; i++) {
  20381. DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, framework.svgElements, framework.svg);
  20382. }
  20383. };
  20384. module.exports = Points;
  20385. /***/ },
  20386. /* 54 */
  20387. /***/ function(module, exports, __webpack_require__) {
  20388. var PhysicsMixin = __webpack_require__(66);
  20389. var ClusterMixin = __webpack_require__(60);
  20390. var SectorsMixin = __webpack_require__(61);
  20391. var SelectionMixin = __webpack_require__(62);
  20392. var ManipulationMixin = __webpack_require__(63);
  20393. var NavigationMixin = __webpack_require__(64);
  20394. var HierarchicalLayoutMixin = __webpack_require__(65);
  20395. /**
  20396. * Load a mixin into the network object
  20397. *
  20398. * @param {Object} sourceVariable | this object has to contain functions.
  20399. * @private
  20400. */
  20401. exports._loadMixin = function (sourceVariable) {
  20402. for (var mixinFunction in sourceVariable) {
  20403. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  20404. this[mixinFunction] = sourceVariable[mixinFunction];
  20405. }
  20406. }
  20407. };
  20408. /**
  20409. * removes a mixin from the network object.
  20410. *
  20411. * @param {Object} sourceVariable | this object has to contain functions.
  20412. * @private
  20413. */
  20414. exports._clearMixin = function (sourceVariable) {
  20415. for (var mixinFunction in sourceVariable) {
  20416. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  20417. this[mixinFunction] = undefined;
  20418. }
  20419. }
  20420. };
  20421. /**
  20422. * Mixin the physics system and initialize the parameters required.
  20423. *
  20424. * @private
  20425. */
  20426. exports._loadPhysicsSystem = function () {
  20427. this._loadMixin(PhysicsMixin);
  20428. this._loadSelectedForceSolver();
  20429. if (this.constants.configurePhysics == true) {
  20430. this._loadPhysicsConfiguration();
  20431. }
  20432. else {
  20433. this._cleanupPhysicsConfiguration();
  20434. }
  20435. };
  20436. /**
  20437. * Mixin the cluster system and initialize the parameters required.
  20438. *
  20439. * @private
  20440. */
  20441. exports._loadClusterSystem = function () {
  20442. this.clusterSession = 0;
  20443. this.hubThreshold = 5;
  20444. this._loadMixin(ClusterMixin);
  20445. };
  20446. /**
  20447. * Mixin the sector system and initialize the parameters required
  20448. *
  20449. * @private
  20450. */
  20451. exports._loadSectorSystem = function () {
  20452. this.sectors = {};
  20453. this.activeSector = ["default"];
  20454. this.sectors["active"] = {};
  20455. this.sectors["active"]["default"] = {"nodes": {},
  20456. "edges": {},
  20457. "nodeIndices": [],
  20458. "formationScale": 1.0,
  20459. "drawingNode": undefined };
  20460. this.sectors["frozen"] = {};
  20461. this.sectors["support"] = {"nodes": {},
  20462. "edges": {},
  20463. "nodeIndices": [],
  20464. "formationScale": 1.0,
  20465. "drawingNode": undefined };
  20466. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  20467. this._loadMixin(SectorsMixin);
  20468. };
  20469. /**
  20470. * Mixin the selection system and initialize the parameters required
  20471. *
  20472. * @private
  20473. */
  20474. exports._loadSelectionSystem = function () {
  20475. this.selectionObj = {nodes: {}, edges: {}};
  20476. this._loadMixin(SelectionMixin);
  20477. };
  20478. /**
  20479. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  20480. *
  20481. * @private
  20482. */
  20483. exports._loadManipulationSystem = function () {
  20484. // reset global variables -- these are used by the selection of nodes and edges.
  20485. this.blockConnectingEdgeSelection = false;
  20486. this.forceAppendSelection = false;
  20487. if (this.constants.dataManipulation.enabled == true) {
  20488. // load the manipulator HTML elements. All styling done in css.
  20489. if (this.manipulationDiv === undefined) {
  20490. this.manipulationDiv = document.createElement('div');
  20491. this.manipulationDiv.className = 'network-manipulationDiv';
  20492. if (this.editMode == true) {
  20493. this.manipulationDiv.style.display = "block";
  20494. }
  20495. else {
  20496. this.manipulationDiv.style.display = "none";
  20497. }
  20498. this.frame.appendChild(this.manipulationDiv);
  20499. }
  20500. if (this.editModeDiv === undefined) {
  20501. this.editModeDiv = document.createElement('div');
  20502. this.editModeDiv.className = 'network-manipulation-editMode';
  20503. if (this.editMode == true) {
  20504. this.editModeDiv.style.display = "none";
  20505. }
  20506. else {
  20507. this.editModeDiv.style.display = "block";
  20508. }
  20509. this.frame.appendChild(this.editModeDiv);
  20510. }
  20511. if (this.closeDiv === undefined) {
  20512. this.closeDiv = document.createElement('div');
  20513. this.closeDiv.className = 'network-manipulation-closeDiv';
  20514. this.closeDiv.style.display = this.manipulationDiv.style.display;
  20515. this.frame.appendChild(this.closeDiv);
  20516. }
  20517. // load the manipulation functions
  20518. this._loadMixin(ManipulationMixin);
  20519. // create the manipulator toolbar
  20520. this._createManipulatorBar();
  20521. }
  20522. else {
  20523. if (this.manipulationDiv !== undefined) {
  20524. // removes all the bindings and overloads
  20525. this._createManipulatorBar();
  20526. // remove the manipulation divs
  20527. this.frame.removeChild(this.manipulationDiv);
  20528. this.frame.removeChild(this.editModeDiv);
  20529. this.frame.removeChild(this.closeDiv);
  20530. this.manipulationDiv = undefined;
  20531. this.editModeDiv = undefined;
  20532. this.closeDiv = undefined;
  20533. // remove the mixin functions
  20534. this._clearMixin(ManipulationMixin);
  20535. }
  20536. }
  20537. };
  20538. /**
  20539. * Mixin the navigation (User Interface) system and initialize the parameters required
  20540. *
  20541. * @private
  20542. */
  20543. exports._loadNavigationControls = function () {
  20544. this._loadMixin(NavigationMixin);
  20545. // the clean function removes the button divs, this is done to remove the bindings.
  20546. this._cleanNavigation();
  20547. if (this.constants.navigation.enabled == true) {
  20548. this._loadNavigationElements();
  20549. }
  20550. };
  20551. /**
  20552. * Mixin the hierarchical layout system.
  20553. *
  20554. * @private
  20555. */
  20556. exports._loadHierarchySystem = function () {
  20557. this._loadMixin(HierarchicalLayoutMixin);
  20558. };
  20559. /***/ },
  20560. /* 55 */
  20561. /***/ function(module, exports, __webpack_require__) {
  20562. var keycharm = __webpack_require__(57);
  20563. var Emitter = __webpack_require__(56);
  20564. var Hammer = __webpack_require__(45);
  20565. var util = __webpack_require__(1);
  20566. /**
  20567. * Turn an element into an clickToUse element.
  20568. * When not active, the element has a transparent overlay. When the overlay is
  20569. * clicked, the mode is changed to active.
  20570. * When active, the element is displayed with a blue border around it, and
  20571. * the interactive contents of the element can be used. When clicked outside
  20572. * the element, the elements mode is changed to inactive.
  20573. * @param {Element} container
  20574. * @constructor
  20575. */
  20576. function Activator(container) {
  20577. this.active = false;
  20578. this.dom = {
  20579. container: container
  20580. };
  20581. this.dom.overlay = document.createElement('div');
  20582. this.dom.overlay.className = 'overlay';
  20583. this.dom.container.appendChild(this.dom.overlay);
  20584. this.hammer = Hammer(this.dom.overlay, {prevent_default: false});
  20585. this.hammer.on('tap', this._onTapOverlay.bind(this));
  20586. // block all touch events (except tap)
  20587. var me = this;
  20588. var events = [
  20589. 'touch', 'pinch',
  20590. 'doubletap', 'hold',
  20591. 'dragstart', 'drag', 'dragend',
  20592. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  20593. ];
  20594. events.forEach(function (event) {
  20595. me.hammer.on(event, function (event) {
  20596. event.stopPropagation();
  20597. });
  20598. });
  20599. // attach a tap event to the window, in order to deactivate when clicking outside the timeline
  20600. this.windowHammer = Hammer(window, {prevent_default: false});
  20601. this.windowHammer.on('tap', function (event) {
  20602. // deactivate when clicked outside the container
  20603. if (!_hasParent(event.target, container)) {
  20604. me.deactivate();
  20605. }
  20606. });
  20607. if (this.keycharm !== undefined) {
  20608. this.keycharm.destroy();
  20609. }
  20610. this.keycharm = keycharm();
  20611. // keycharm listener only bounded when active)
  20612. this.escListener = this.deactivate.bind(this);
  20613. }
  20614. // turn into an event emitter
  20615. Emitter(Activator.prototype);
  20616. // The currently active activator
  20617. Activator.current = null;
  20618. /**
  20619. * Destroy the activator. Cleans up all created DOM and event listeners
  20620. */
  20621. Activator.prototype.destroy = function () {
  20622. this.deactivate();
  20623. // remove dom
  20624. this.dom.overlay.parentNode.removeChild(this.dom.overlay);
  20625. // cleanup hammer instances
  20626. this.hammer = null;
  20627. this.windowHammer = null;
  20628. // FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory)
  20629. };
  20630. /**
  20631. * Activate the element
  20632. * Overlay is hidden, element is decorated with a blue shadow border
  20633. */
  20634. Activator.prototype.activate = function () {
  20635. // we allow only one active activator at a time
  20636. if (Activator.current) {
  20637. Activator.current.deactivate();
  20638. }
  20639. Activator.current = this;
  20640. this.active = true;
  20641. this.dom.overlay.style.display = 'none';
  20642. util.addClassName(this.dom.container, 'vis-active');
  20643. this.emit('change');
  20644. this.emit('activate');
  20645. // ugly hack: bind ESC after emitting the events, as the Network rebinds all
  20646. // keyboard events on a 'change' event
  20647. this.keycharm.bind('esc', this.escListener);
  20648. };
  20649. /**
  20650. * Deactivate the element
  20651. * Overlay is displayed on top of the element
  20652. */
  20653. Activator.prototype.deactivate = function () {
  20654. this.active = false;
  20655. this.dom.overlay.style.display = '';
  20656. util.removeClassName(this.dom.container, 'vis-active');
  20657. this.keycharm.unbind('esc', this.escListener);
  20658. this.emit('change');
  20659. this.emit('deactivate');
  20660. };
  20661. /**
  20662. * Handle a tap event: activate the container
  20663. * @param event
  20664. * @private
  20665. */
  20666. Activator.prototype._onTapOverlay = function (event) {
  20667. // activate the container
  20668. this.activate();
  20669. event.stopPropagation();
  20670. };
  20671. /**
  20672. * Test whether the element has the requested parent element somewhere in
  20673. * its chain of parent nodes.
  20674. * @param {HTMLElement} element
  20675. * @param {HTMLElement} parent
  20676. * @returns {boolean} Returns true when the parent is found somewhere in the
  20677. * chain of parent nodes.
  20678. * @private
  20679. */
  20680. function _hasParent(element, parent) {
  20681. while (element) {
  20682. if (element === parent) {
  20683. return true
  20684. }
  20685. element = element.parentNode;
  20686. }
  20687. return false;
  20688. }
  20689. module.exports = Activator;
  20690. /***/ },
  20691. /* 56 */
  20692. /***/ function(module, exports, __webpack_require__) {
  20693. /**
  20694. * Expose `Emitter`.
  20695. */
  20696. module.exports = Emitter;
  20697. /**
  20698. * Initialize a new `Emitter`.
  20699. *
  20700. * @api public
  20701. */
  20702. function Emitter(obj) {
  20703. if (obj) return mixin(obj);
  20704. };
  20705. /**
  20706. * Mixin the emitter properties.
  20707. *
  20708. * @param {Object} obj
  20709. * @return {Object}
  20710. * @api private
  20711. */
  20712. function mixin(obj) {
  20713. for (var key in Emitter.prototype) {
  20714. obj[key] = Emitter.prototype[key];
  20715. }
  20716. return obj;
  20717. }
  20718. /**
  20719. * Listen on the given `event` with `fn`.
  20720. *
  20721. * @param {String} event
  20722. * @param {Function} fn
  20723. * @return {Emitter}
  20724. * @api public
  20725. */
  20726. Emitter.prototype.on =
  20727. Emitter.prototype.addEventListener = function(event, fn){
  20728. this._callbacks = this._callbacks || {};
  20729. (this._callbacks[event] = this._callbacks[event] || [])
  20730. .push(fn);
  20731. return this;
  20732. };
  20733. /**
  20734. * Adds an `event` listener that will be invoked a single
  20735. * time then automatically removed.
  20736. *
  20737. * @param {String} event
  20738. * @param {Function} fn
  20739. * @return {Emitter}
  20740. * @api public
  20741. */
  20742. Emitter.prototype.once = function(event, fn){
  20743. var self = this;
  20744. this._callbacks = this._callbacks || {};
  20745. function on() {
  20746. self.off(event, on);
  20747. fn.apply(this, arguments);
  20748. }
  20749. on.fn = fn;
  20750. this.on(event, on);
  20751. return this;
  20752. };
  20753. /**
  20754. * Remove the given callback for `event` or all
  20755. * registered callbacks.
  20756. *
  20757. * @param {String} event
  20758. * @param {Function} fn
  20759. * @return {Emitter}
  20760. * @api public
  20761. */
  20762. Emitter.prototype.off =
  20763. Emitter.prototype.removeListener =
  20764. Emitter.prototype.removeAllListeners =
  20765. Emitter.prototype.removeEventListener = function(event, fn){
  20766. this._callbacks = this._callbacks || {};
  20767. // all
  20768. if (0 == arguments.length) {
  20769. this._callbacks = {};
  20770. return this;
  20771. }
  20772. // specific event
  20773. var callbacks = this._callbacks[event];
  20774. if (!callbacks) return this;
  20775. // remove all handlers
  20776. if (1 == arguments.length) {
  20777. delete this._callbacks[event];
  20778. return this;
  20779. }
  20780. // remove specific handler
  20781. var cb;
  20782. for (var i = 0; i < callbacks.length; i++) {
  20783. cb = callbacks[i];
  20784. if (cb === fn || cb.fn === fn) {
  20785. callbacks.splice(i, 1);
  20786. break;
  20787. }
  20788. }
  20789. return this;
  20790. };
  20791. /**
  20792. * Emit `event` with the given args.
  20793. *
  20794. * @param {String} event
  20795. * @param {Mixed} ...
  20796. * @return {Emitter}
  20797. */
  20798. Emitter.prototype.emit = function(event){
  20799. this._callbacks = this._callbacks || {};
  20800. var args = [].slice.call(arguments, 1)
  20801. , callbacks = this._callbacks[event];
  20802. if (callbacks) {
  20803. callbacks = callbacks.slice(0);
  20804. for (var i = 0, len = callbacks.length; i < len; ++i) {
  20805. callbacks[i].apply(this, args);
  20806. }
  20807. }
  20808. return this;
  20809. };
  20810. /**
  20811. * Return array of callbacks for `event`.
  20812. *
  20813. * @param {String} event
  20814. * @return {Array}
  20815. * @api public
  20816. */
  20817. Emitter.prototype.listeners = function(event){
  20818. this._callbacks = this._callbacks || {};
  20819. return this._callbacks[event] || [];
  20820. };
  20821. /**
  20822. * Check if this emitter has `event` handlers.
  20823. *
  20824. * @param {String} event
  20825. * @return {Boolean}
  20826. * @api public
  20827. */
  20828. Emitter.prototype.hasListeners = function(event){
  20829. return !! this.listeners(event).length;
  20830. };
  20831. /***/ },
  20832. /* 57 */
  20833. /***/ function(module, exports, __webpack_require__) {
  20834. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
  20835. /**
  20836. * Created by Alex on 11/6/2014.
  20837. */
  20838. // https://github.com/umdjs/umd/blob/master/returnExports.js#L40-L60
  20839. // if the module has no dependencies, the above pattern can be simplified to
  20840. (function (root, factory) {
  20841. if (true) {
  20842. // AMD. Register as an anonymous module.
  20843. !(__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__));
  20844. } else if (typeof exports === 'object') {
  20845. // Node. Does not work with strict CommonJS, but
  20846. // only CommonJS-like environments that support module.exports,
  20847. // like Node.
  20848. module.exports = factory();
  20849. } else {
  20850. // Browser globals (root is window)
  20851. root.keycharm = factory();
  20852. }
  20853. }(this, function () {
  20854. function keycharm(options) {
  20855. var preventDefault = options && options.preventDefault || false;
  20856. var container = options && options.container || window;
  20857. var _exportFunctions = {};
  20858. var _bound = {keydown:{}, keyup:{}};
  20859. var _keys = {};
  20860. var i;
  20861. // a - z
  20862. for (i = 97; i <= 122; i++) {_keys[String.fromCharCode(i)] = {code:65 + (i - 97), shift: false};}
  20863. // A - Z
  20864. for (i = 65; i <= 90; i++) {_keys[String.fromCharCode(i)] = {code:i, shift: true};}
  20865. // 0 - 9
  20866. for (i = 0; i <= 9; i++) {_keys['' + i] = {code:48 + i, shift: false};}
  20867. // F1 - F12
  20868. for (i = 1; i <= 12; i++) {_keys['F' + i] = {code:111 + i, shift: false};}
  20869. // num0 - num9
  20870. for (i = 0; i <= 9; i++) {_keys['num' + i] = {code:96 + i, shift: false};}
  20871. // numpad misc
  20872. _keys['num*'] = {code:106, shift: false};
  20873. _keys['num+'] = {code:107, shift: false};
  20874. _keys['num-'] = {code:109, shift: false};
  20875. _keys['num/'] = {code:111, shift: false};
  20876. _keys['num.'] = {code:110, shift: false};
  20877. // arrows
  20878. _keys['left'] = {code:37, shift: false};
  20879. _keys['up'] = {code:38, shift: false};
  20880. _keys['right'] = {code:39, shift: false};
  20881. _keys['down'] = {code:40, shift: false};
  20882. // extra keys
  20883. _keys['space'] = {code:32, shift: false};
  20884. _keys['enter'] = {code:13, shift: false};
  20885. _keys['shift'] = {code:16, shift: undefined};
  20886. _keys['esc'] = {code:27, shift: false};
  20887. _keys['backspace'] = {code:8, shift: false};
  20888. _keys['tab'] = {code:9, shift: false};
  20889. _keys['ctrl'] = {code:17, shift: false};
  20890. _keys['alt'] = {code:18, shift: false};
  20891. _keys['delete'] = {code:46, shift: false};
  20892. _keys['pageup'] = {code:33, shift: false};
  20893. _keys['pagedown'] = {code:34, shift: false};
  20894. // symbols
  20895. _keys['='] = {code:187, shift: false};
  20896. _keys['-'] = {code:189, shift: false};
  20897. _keys[']'] = {code:221, shift: false};
  20898. _keys['['] = {code:219, shift: false};
  20899. var down = function(event) {handleEvent(event,'keydown');};
  20900. var up = function(event) {handleEvent(event,'keyup');};
  20901. // handle the actualy bound key with the event
  20902. var handleEvent = function(event,type) {
  20903. if (_bound[type][event.keyCode] !== undefined) {
  20904. var bound = _bound[type][event.keyCode];
  20905. for (var i = 0; i < bound.length; i++) {
  20906. if (bound[i].shift === undefined) {
  20907. bound[i].fn(event);
  20908. }
  20909. else if (bound[i].shift == true && event.shiftKey == true) {
  20910. bound[i].fn(event);
  20911. }
  20912. else if (bound[i].shift == false && event.shiftKey == false) {
  20913. bound[i].fn(event);
  20914. }
  20915. }
  20916. if (preventDefault == true) {
  20917. event.preventDefault();
  20918. }
  20919. }
  20920. };
  20921. // bind a key to a callback
  20922. _exportFunctions.bind = function(key, callback, type) {
  20923. if (type === undefined) {
  20924. type = 'keydown';
  20925. }
  20926. if (_keys[key] === undefined) {
  20927. throw new Error("unsupported key: " + key);
  20928. }
  20929. if (_bound[type][_keys[key].code] === undefined) {
  20930. _bound[type][_keys[key].code] = [];
  20931. }
  20932. _bound[type][_keys[key].code].push({fn:callback, shift:_keys[key].shift});
  20933. };
  20934. // bind all keys to a call back (demo purposes)
  20935. _exportFunctions.bindAll = function(callback, type) {
  20936. if (type === undefined) {
  20937. type = 'keydown';
  20938. }
  20939. for (var key in _keys) {
  20940. if (_keys.hasOwnProperty(key)) {
  20941. _exportFunctions.bind(key,callback,type);
  20942. }
  20943. }
  20944. };
  20945. // get the key label from an event
  20946. _exportFunctions.getKey = function(event) {
  20947. for (var key in _keys) {
  20948. if (_keys.hasOwnProperty(key)) {
  20949. if (event.shiftKey == true && _keys[key].shift == true && event.keyCode == _keys[key].code) {
  20950. return key;
  20951. }
  20952. else if (event.shiftKey == false && _keys[key].shift == false && event.keyCode == _keys[key].code) {
  20953. return key;
  20954. }
  20955. else if (event.keyCode == _keys[key].code && key == 'shift') {
  20956. return key;
  20957. }
  20958. }
  20959. }
  20960. return "unknown key, currently not supported";
  20961. };
  20962. // unbind either a specific callback from a key or all of them (by leaving callback undefined)
  20963. _exportFunctions.unbind = function(key, callback, type) {
  20964. if (type === undefined) {
  20965. type = 'keydown';
  20966. }
  20967. if (_keys[key] === undefined) {
  20968. throw new Error("unsupported key: " + key);
  20969. }
  20970. if (callback !== undefined) {
  20971. var newBindings = [];
  20972. var bound = _bound[type][_keys[key].code];
  20973. if (bound !== undefined) {
  20974. for (var i = 0; i < bound.length; i++) {
  20975. if (!(bound[i].fn == callback && bound[i].shift == _keys[key].shift)) {
  20976. newBindings.push(_bound[type][_keys[key].code][i]);
  20977. }
  20978. }
  20979. }
  20980. _bound[type][_keys[key].code] = newBindings;
  20981. }
  20982. else {
  20983. _bound[type][_keys[key].code] = [];
  20984. }
  20985. };
  20986. // reset all bound variables.
  20987. _exportFunctions.reset = function() {
  20988. _bound = {keydown:{}, keyup:{}};
  20989. };
  20990. // unbind all listeners and reset all variables.
  20991. _exportFunctions.destroy = function() {
  20992. _bound = {keydown:{}, keyup:{}};
  20993. container.removeEventListener('keydown', down, true);
  20994. container.removeEventListener('keyup', up, true);
  20995. };
  20996. // create listeners.
  20997. container.addEventListener('keydown',down,true);
  20998. container.addEventListener('keyup',up,true);
  20999. // return the public functions.
  21000. return _exportFunctions;
  21001. }
  21002. return keycharm;
  21003. }));
  21004. /***/ },
  21005. /* 58 */
  21006. /***/ function(module, exports, __webpack_require__) {
  21007. var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(global, module) {//! moment.js
  21008. //! version : 2.9.0
  21009. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  21010. //! license : MIT
  21011. //! momentjs.com
  21012. (function (undefined) {
  21013. /************************************
  21014. Constants
  21015. ************************************/
  21016. var moment,
  21017. VERSION = '2.9.0',
  21018. // the global-scope this is NOT the global object in Node.js
  21019. globalScope = (typeof global !== 'undefined' && (typeof window === 'undefined' || window === global.window)) ? global : this,
  21020. oldGlobalMoment,
  21021. round = Math.round,
  21022. hasOwnProperty = Object.prototype.hasOwnProperty,
  21023. i,
  21024. YEAR = 0,
  21025. MONTH = 1,
  21026. DATE = 2,
  21027. HOUR = 3,
  21028. MINUTE = 4,
  21029. SECOND = 5,
  21030. MILLISECOND = 6,
  21031. // internal storage for locale config files
  21032. locales = {},
  21033. // extra moment internal properties (plugins register props here)
  21034. momentProperties = [],
  21035. // check for nodeJS
  21036. hasModule = (typeof module !== 'undefined' && module && module.exports),
  21037. // ASP.NET json date format regex
  21038. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  21039. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  21040. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  21041. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  21042. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  21043. // format tokens
  21044. 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,
  21045. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
  21046. // parsing token regexes
  21047. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  21048. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  21049. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  21050. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  21051. parseTokenDigits = /\d+/, // nonzero number of digits
  21052. parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic.
  21053. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  21054. parseTokenT = /T/i, // T (ISO separator)
  21055. parseTokenOffsetMs = /[\+\-]?\d+/, // 1234567890123
  21056. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  21057. //strict parsing regexes
  21058. parseTokenOneDigit = /\d/, // 0 - 9
  21059. parseTokenTwoDigits = /\d\d/, // 00 - 99
  21060. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  21061. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  21062. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  21063. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  21064. // iso 8601 regex
  21065. // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
  21066. 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)?)?$/,
  21067. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  21068. isoDates = [
  21069. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  21070. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  21071. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  21072. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  21073. ['YYYY-DDD', /\d{4}-\d{3}/]
  21074. ],
  21075. // iso time formats and regexes
  21076. isoTimes = [
  21077. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  21078. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  21079. ['HH:mm', /(T| )\d\d:\d\d/],
  21080. ['HH', /(T| )\d\d/]
  21081. ],
  21082. // timezone chunker '+10:00' > ['10', '00'] or '-1530' > ['-', '15', '30']
  21083. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  21084. // getter and setter names
  21085. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  21086. unitMillisecondFactors = {
  21087. 'Milliseconds' : 1,
  21088. 'Seconds' : 1e3,
  21089. 'Minutes' : 6e4,
  21090. 'Hours' : 36e5,
  21091. 'Days' : 864e5,
  21092. 'Months' : 2592e6,
  21093. 'Years' : 31536e6
  21094. },
  21095. unitAliases = {
  21096. ms : 'millisecond',
  21097. s : 'second',
  21098. m : 'minute',
  21099. h : 'hour',
  21100. d : 'day',
  21101. D : 'date',
  21102. w : 'week',
  21103. W : 'isoWeek',
  21104. M : 'month',
  21105. Q : 'quarter',
  21106. y : 'year',
  21107. DDD : 'dayOfYear',
  21108. e : 'weekday',
  21109. E : 'isoWeekday',
  21110. gg: 'weekYear',
  21111. GG: 'isoWeekYear'
  21112. },
  21113. camelFunctions = {
  21114. dayofyear : 'dayOfYear',
  21115. isoweekday : 'isoWeekday',
  21116. isoweek : 'isoWeek',
  21117. weekyear : 'weekYear',
  21118. isoweekyear : 'isoWeekYear'
  21119. },
  21120. // format function strings
  21121. formatFunctions = {},
  21122. // default relative time thresholds
  21123. relativeTimeThresholds = {
  21124. s: 45, // seconds to minute
  21125. m: 45, // minutes to hour
  21126. h: 22, // hours to day
  21127. d: 26, // days to month
  21128. M: 11 // months to year
  21129. },
  21130. // tokens to ordinalize and pad
  21131. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  21132. paddedTokens = 'M D H h m s w W'.split(' '),
  21133. formatTokenFunctions = {
  21134. M : function () {
  21135. return this.month() + 1;
  21136. },
  21137. MMM : function (format) {
  21138. return this.localeData().monthsShort(this, format);
  21139. },
  21140. MMMM : function (format) {
  21141. return this.localeData().months(this, format);
  21142. },
  21143. D : function () {
  21144. return this.date();
  21145. },
  21146. DDD : function () {
  21147. return this.dayOfYear();
  21148. },
  21149. d : function () {
  21150. return this.day();
  21151. },
  21152. dd : function (format) {
  21153. return this.localeData().weekdaysMin(this, format);
  21154. },
  21155. ddd : function (format) {
  21156. return this.localeData().weekdaysShort(this, format);
  21157. },
  21158. dddd : function (format) {
  21159. return this.localeData().weekdays(this, format);
  21160. },
  21161. w : function () {
  21162. return this.week();
  21163. },
  21164. W : function () {
  21165. return this.isoWeek();
  21166. },
  21167. YY : function () {
  21168. return leftZeroFill(this.year() % 100, 2);
  21169. },
  21170. YYYY : function () {
  21171. return leftZeroFill(this.year(), 4);
  21172. },
  21173. YYYYY : function () {
  21174. return leftZeroFill(this.year(), 5);
  21175. },
  21176. YYYYYY : function () {
  21177. var y = this.year(), sign = y >= 0 ? '+' : '-';
  21178. return sign + leftZeroFill(Math.abs(y), 6);
  21179. },
  21180. gg : function () {
  21181. return leftZeroFill(this.weekYear() % 100, 2);
  21182. },
  21183. gggg : function () {
  21184. return leftZeroFill(this.weekYear(), 4);
  21185. },
  21186. ggggg : function () {
  21187. return leftZeroFill(this.weekYear(), 5);
  21188. },
  21189. GG : function () {
  21190. return leftZeroFill(this.isoWeekYear() % 100, 2);
  21191. },
  21192. GGGG : function () {
  21193. return leftZeroFill(this.isoWeekYear(), 4);
  21194. },
  21195. GGGGG : function () {
  21196. return leftZeroFill(this.isoWeekYear(), 5);
  21197. },
  21198. e : function () {
  21199. return this.weekday();
  21200. },
  21201. E : function () {
  21202. return this.isoWeekday();
  21203. },
  21204. a : function () {
  21205. return this.localeData().meridiem(this.hours(), this.minutes(), true);
  21206. },
  21207. A : function () {
  21208. return this.localeData().meridiem(this.hours(), this.minutes(), false);
  21209. },
  21210. H : function () {
  21211. return this.hours();
  21212. },
  21213. h : function () {
  21214. return this.hours() % 12 || 12;
  21215. },
  21216. m : function () {
  21217. return this.minutes();
  21218. },
  21219. s : function () {
  21220. return this.seconds();
  21221. },
  21222. S : function () {
  21223. return toInt(this.milliseconds() / 100);
  21224. },
  21225. SS : function () {
  21226. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  21227. },
  21228. SSS : function () {
  21229. return leftZeroFill(this.milliseconds(), 3);
  21230. },
  21231. SSSS : function () {
  21232. return leftZeroFill(this.milliseconds(), 3);
  21233. },
  21234. Z : function () {
  21235. var a = this.utcOffset(),
  21236. b = '+';
  21237. if (a < 0) {
  21238. a = -a;
  21239. b = '-';
  21240. }
  21241. return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2);
  21242. },
  21243. ZZ : function () {
  21244. var a = this.utcOffset(),
  21245. b = '+';
  21246. if (a < 0) {
  21247. a = -a;
  21248. b = '-';
  21249. }
  21250. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  21251. },
  21252. z : function () {
  21253. return this.zoneAbbr();
  21254. },
  21255. zz : function () {
  21256. return this.zoneName();
  21257. },
  21258. x : function () {
  21259. return this.valueOf();
  21260. },
  21261. X : function () {
  21262. return this.unix();
  21263. },
  21264. Q : function () {
  21265. return this.quarter();
  21266. }
  21267. },
  21268. deprecations = {},
  21269. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'],
  21270. updateInProgress = false;
  21271. // Pick the first defined of two or three arguments. dfl comes from
  21272. // default.
  21273. function dfl(a, b, c) {
  21274. switch (arguments.length) {
  21275. case 2: return a != null ? a : b;
  21276. case 3: return a != null ? a : b != null ? b : c;
  21277. default: throw new Error('Implement me');
  21278. }
  21279. }
  21280. function hasOwnProp(a, b) {
  21281. return hasOwnProperty.call(a, b);
  21282. }
  21283. function defaultParsingFlags() {
  21284. // We need to deep clone this object, and es5 standard is not very
  21285. // helpful.
  21286. return {
  21287. empty : false,
  21288. unusedTokens : [],
  21289. unusedInput : [],
  21290. overflow : -2,
  21291. charsLeftOver : 0,
  21292. nullInput : false,
  21293. invalidMonth : null,
  21294. invalidFormat : false,
  21295. userInvalidated : false,
  21296. iso: false
  21297. };
  21298. }
  21299. function printMsg(msg) {
  21300. if (moment.suppressDeprecationWarnings === false &&
  21301. typeof console !== 'undefined' && console.warn) {
  21302. console.warn('Deprecation warning: ' + msg);
  21303. }
  21304. }
  21305. function deprecate(msg, fn) {
  21306. var firstTime = true;
  21307. return extend(function () {
  21308. if (firstTime) {
  21309. printMsg(msg);
  21310. firstTime = false;
  21311. }
  21312. return fn.apply(this, arguments);
  21313. }, fn);
  21314. }
  21315. function deprecateSimple(name, msg) {
  21316. if (!deprecations[name]) {
  21317. printMsg(msg);
  21318. deprecations[name] = true;
  21319. }
  21320. }
  21321. function padToken(func, count) {
  21322. return function (a) {
  21323. return leftZeroFill(func.call(this, a), count);
  21324. };
  21325. }
  21326. function ordinalizeToken(func, period) {
  21327. return function (a) {
  21328. return this.localeData().ordinal(func.call(this, a), period);
  21329. };
  21330. }
  21331. function monthDiff(a, b) {
  21332. // difference in months
  21333. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  21334. // b is in (anchor - 1 month, anchor + 1 month)
  21335. anchor = a.clone().add(wholeMonthDiff, 'months'),
  21336. anchor2, adjust;
  21337. if (b - anchor < 0) {
  21338. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  21339. // linear across the month
  21340. adjust = (b - anchor) / (anchor - anchor2);
  21341. } else {
  21342. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  21343. // linear across the month
  21344. adjust = (b - anchor) / (anchor2 - anchor);
  21345. }
  21346. return -(wholeMonthDiff + adjust);
  21347. }
  21348. while (ordinalizeTokens.length) {
  21349. i = ordinalizeTokens.pop();
  21350. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  21351. }
  21352. while (paddedTokens.length) {
  21353. i = paddedTokens.pop();
  21354. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  21355. }
  21356. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  21357. function meridiemFixWrap(locale, hour, meridiem) {
  21358. var isPm;
  21359. if (meridiem == null) {
  21360. // nothing to do
  21361. return hour;
  21362. }
  21363. if (locale.meridiemHour != null) {
  21364. return locale.meridiemHour(hour, meridiem);
  21365. } else if (locale.isPM != null) {
  21366. // Fallback
  21367. isPm = locale.isPM(meridiem);
  21368. if (isPm && hour < 12) {
  21369. hour += 12;
  21370. }
  21371. if (!isPm && hour === 12) {
  21372. hour = 0;
  21373. }
  21374. return hour;
  21375. } else {
  21376. // thie is not supposed to happen
  21377. return hour;
  21378. }
  21379. }
  21380. /************************************
  21381. Constructors
  21382. ************************************/
  21383. function Locale() {
  21384. }
  21385. // Moment prototype object
  21386. function Moment(config, skipOverflow) {
  21387. if (skipOverflow !== false) {
  21388. checkOverflow(config);
  21389. }
  21390. copyConfig(this, config);
  21391. this._d = new Date(+config._d);
  21392. // Prevent infinite loop in case updateOffset creates new moment
  21393. // objects.
  21394. if (updateInProgress === false) {
  21395. updateInProgress = true;
  21396. moment.updateOffset(this);
  21397. updateInProgress = false;
  21398. }
  21399. }
  21400. // Duration Constructor
  21401. function Duration(duration) {
  21402. var normalizedInput = normalizeObjectUnits(duration),
  21403. years = normalizedInput.year || 0,
  21404. quarters = normalizedInput.quarter || 0,
  21405. months = normalizedInput.month || 0,
  21406. weeks = normalizedInput.week || 0,
  21407. days = normalizedInput.day || 0,
  21408. hours = normalizedInput.hour || 0,
  21409. minutes = normalizedInput.minute || 0,
  21410. seconds = normalizedInput.second || 0,
  21411. milliseconds = normalizedInput.millisecond || 0;
  21412. // representation for dateAddRemove
  21413. this._milliseconds = +milliseconds +
  21414. seconds * 1e3 + // 1000
  21415. minutes * 6e4 + // 1000 * 60
  21416. hours * 36e5; // 1000 * 60 * 60
  21417. // Because of dateAddRemove treats 24 hours as different from a
  21418. // day when working around DST, we need to store them separately
  21419. this._days = +days +
  21420. weeks * 7;
  21421. // It is impossible translate months into days without knowing
  21422. // which months you are are talking about, so we have to store
  21423. // it separately.
  21424. this._months = +months +
  21425. quarters * 3 +
  21426. years * 12;
  21427. this._data = {};
  21428. this._locale = moment.localeData();
  21429. this._bubble();
  21430. }
  21431. /************************************
  21432. Helpers
  21433. ************************************/
  21434. function extend(a, b) {
  21435. for (var i in b) {
  21436. if (hasOwnProp(b, i)) {
  21437. a[i] = b[i];
  21438. }
  21439. }
  21440. if (hasOwnProp(b, 'toString')) {
  21441. a.toString = b.toString;
  21442. }
  21443. if (hasOwnProp(b, 'valueOf')) {
  21444. a.valueOf = b.valueOf;
  21445. }
  21446. return a;
  21447. }
  21448. function copyConfig(to, from) {
  21449. var i, prop, val;
  21450. if (typeof from._isAMomentObject !== 'undefined') {
  21451. to._isAMomentObject = from._isAMomentObject;
  21452. }
  21453. if (typeof from._i !== 'undefined') {
  21454. to._i = from._i;
  21455. }
  21456. if (typeof from._f !== 'undefined') {
  21457. to._f = from._f;
  21458. }
  21459. if (typeof from._l !== 'undefined') {
  21460. to._l = from._l;
  21461. }
  21462. if (typeof from._strict !== 'undefined') {
  21463. to._strict = from._strict;
  21464. }
  21465. if (typeof from._tzm !== 'undefined') {
  21466. to._tzm = from._tzm;
  21467. }
  21468. if (typeof from._isUTC !== 'undefined') {
  21469. to._isUTC = from._isUTC;
  21470. }
  21471. if (typeof from._offset !== 'undefined') {
  21472. to._offset = from._offset;
  21473. }
  21474. if (typeof from._pf !== 'undefined') {
  21475. to._pf = from._pf;
  21476. }
  21477. if (typeof from._locale !== 'undefined') {
  21478. to._locale = from._locale;
  21479. }
  21480. if (momentProperties.length > 0) {
  21481. for (i in momentProperties) {
  21482. prop = momentProperties[i];
  21483. val = from[prop];
  21484. if (typeof val !== 'undefined') {
  21485. to[prop] = val;
  21486. }
  21487. }
  21488. }
  21489. return to;
  21490. }
  21491. function absRound(number) {
  21492. if (number < 0) {
  21493. return Math.ceil(number);
  21494. } else {
  21495. return Math.floor(number);
  21496. }
  21497. }
  21498. // left zero fill a number
  21499. // see http://jsperf.com/left-zero-filling for performance comparison
  21500. function leftZeroFill(number, targetLength, forceSign) {
  21501. var output = '' + Math.abs(number),
  21502. sign = number >= 0;
  21503. while (output.length < targetLength) {
  21504. output = '0' + output;
  21505. }
  21506. return (sign ? (forceSign ? '+' : '') : '-') + output;
  21507. }
  21508. function positiveMomentsDifference(base, other) {
  21509. var res = {milliseconds: 0, months: 0};
  21510. res.months = other.month() - base.month() +
  21511. (other.year() - base.year()) * 12;
  21512. if (base.clone().add(res.months, 'M').isAfter(other)) {
  21513. --res.months;
  21514. }
  21515. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  21516. return res;
  21517. }
  21518. function momentsDifference(base, other) {
  21519. var res;
  21520. other = makeAs(other, base);
  21521. if (base.isBefore(other)) {
  21522. res = positiveMomentsDifference(base, other);
  21523. } else {
  21524. res = positiveMomentsDifference(other, base);
  21525. res.milliseconds = -res.milliseconds;
  21526. res.months = -res.months;
  21527. }
  21528. return res;
  21529. }
  21530. // TODO: remove 'name' arg after deprecation is removed
  21531. function createAdder(direction, name) {
  21532. return function (val, period) {
  21533. var dur, tmp;
  21534. //invert the arguments, but complain about it
  21535. if (period !== null && !isNaN(+period)) {
  21536. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
  21537. tmp = val; val = period; period = tmp;
  21538. }
  21539. val = typeof val === 'string' ? +val : val;
  21540. dur = moment.duration(val, period);
  21541. addOrSubtractDurationFromMoment(this, dur, direction);
  21542. return this;
  21543. };
  21544. }
  21545. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  21546. var milliseconds = duration._milliseconds,
  21547. days = duration._days,
  21548. months = duration._months;
  21549. updateOffset = updateOffset == null ? true : updateOffset;
  21550. if (milliseconds) {
  21551. mom._d.setTime(+mom._d + milliseconds * isAdding);
  21552. }
  21553. if (days) {
  21554. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  21555. }
  21556. if (months) {
  21557. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  21558. }
  21559. if (updateOffset) {
  21560. moment.updateOffset(mom, days || months);
  21561. }
  21562. }
  21563. // check if is an array
  21564. function isArray(input) {
  21565. return Object.prototype.toString.call(input) === '[object Array]';
  21566. }
  21567. function isDate(input) {
  21568. return Object.prototype.toString.call(input) === '[object Date]' ||
  21569. input instanceof Date;
  21570. }
  21571. // compare two arrays, return the number of differences
  21572. function compareArrays(array1, array2, dontConvert) {
  21573. var len = Math.min(array1.length, array2.length),
  21574. lengthDiff = Math.abs(array1.length - array2.length),
  21575. diffs = 0,
  21576. i;
  21577. for (i = 0; i < len; i++) {
  21578. if ((dontConvert && array1[i] !== array2[i]) ||
  21579. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  21580. diffs++;
  21581. }
  21582. }
  21583. return diffs + lengthDiff;
  21584. }
  21585. function normalizeUnits(units) {
  21586. if (units) {
  21587. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  21588. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  21589. }
  21590. return units;
  21591. }
  21592. function normalizeObjectUnits(inputObject) {
  21593. var normalizedInput = {},
  21594. normalizedProp,
  21595. prop;
  21596. for (prop in inputObject) {
  21597. if (hasOwnProp(inputObject, prop)) {
  21598. normalizedProp = normalizeUnits(prop);
  21599. if (normalizedProp) {
  21600. normalizedInput[normalizedProp] = inputObject[prop];
  21601. }
  21602. }
  21603. }
  21604. return normalizedInput;
  21605. }
  21606. function makeList(field) {
  21607. var count, setter;
  21608. if (field.indexOf('week') === 0) {
  21609. count = 7;
  21610. setter = 'day';
  21611. }
  21612. else if (field.indexOf('month') === 0) {
  21613. count = 12;
  21614. setter = 'month';
  21615. }
  21616. else {
  21617. return;
  21618. }
  21619. moment[field] = function (format, index) {
  21620. var i, getter,
  21621. method = moment._locale[field],
  21622. results = [];
  21623. if (typeof format === 'number') {
  21624. index = format;
  21625. format = undefined;
  21626. }
  21627. getter = function (i) {
  21628. var m = moment().utc().set(setter, i);
  21629. return method.call(moment._locale, m, format || '');
  21630. };
  21631. if (index != null) {
  21632. return getter(index);
  21633. }
  21634. else {
  21635. for (i = 0; i < count; i++) {
  21636. results.push(getter(i));
  21637. }
  21638. return results;
  21639. }
  21640. };
  21641. }
  21642. function toInt(argumentForCoercion) {
  21643. var coercedNumber = +argumentForCoercion,
  21644. value = 0;
  21645. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  21646. if (coercedNumber >= 0) {
  21647. value = Math.floor(coercedNumber);
  21648. } else {
  21649. value = Math.ceil(coercedNumber);
  21650. }
  21651. }
  21652. return value;
  21653. }
  21654. function daysInMonth(year, month) {
  21655. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  21656. }
  21657. function weeksInYear(year, dow, doy) {
  21658. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  21659. }
  21660. function daysInYear(year) {
  21661. return isLeapYear(year) ? 366 : 365;
  21662. }
  21663. function isLeapYear(year) {
  21664. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  21665. }
  21666. function checkOverflow(m) {
  21667. var overflow;
  21668. if (m._a && m._pf.overflow === -2) {
  21669. overflow =
  21670. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  21671. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  21672. m._a[HOUR] < 0 || m._a[HOUR] > 24 ||
  21673. (m._a[HOUR] === 24 && (m._a[MINUTE] !== 0 ||
  21674. m._a[SECOND] !== 0 ||
  21675. m._a[MILLISECOND] !== 0)) ? HOUR :
  21676. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  21677. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  21678. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  21679. -1;
  21680. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  21681. overflow = DATE;
  21682. }
  21683. m._pf.overflow = overflow;
  21684. }
  21685. }
  21686. function isValid(m) {
  21687. if (m._isValid == null) {
  21688. m._isValid = !isNaN(m._d.getTime()) &&
  21689. m._pf.overflow < 0 &&
  21690. !m._pf.empty &&
  21691. !m._pf.invalidMonth &&
  21692. !m._pf.nullInput &&
  21693. !m._pf.invalidFormat &&
  21694. !m._pf.userInvalidated;
  21695. if (m._strict) {
  21696. m._isValid = m._isValid &&
  21697. m._pf.charsLeftOver === 0 &&
  21698. m._pf.unusedTokens.length === 0 &&
  21699. m._pf.bigHour === undefined;
  21700. }
  21701. }
  21702. return m._isValid;
  21703. }
  21704. function normalizeLocale(key) {
  21705. return key ? key.toLowerCase().replace('_', '-') : key;
  21706. }
  21707. // pick the locale from the array
  21708. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  21709. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  21710. function chooseLocale(names) {
  21711. var i = 0, j, next, locale, split;
  21712. while (i < names.length) {
  21713. split = normalizeLocale(names[i]).split('-');
  21714. j = split.length;
  21715. next = normalizeLocale(names[i + 1]);
  21716. next = next ? next.split('-') : null;
  21717. while (j > 0) {
  21718. locale = loadLocale(split.slice(0, j).join('-'));
  21719. if (locale) {
  21720. return locale;
  21721. }
  21722. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  21723. //the next array item is better than a shallower substring of this one
  21724. break;
  21725. }
  21726. j--;
  21727. }
  21728. i++;
  21729. }
  21730. return null;
  21731. }
  21732. function loadLocale(name) {
  21733. var oldLocale = null;
  21734. if (!locales[name] && hasModule) {
  21735. try {
  21736. oldLocale = moment.locale();
  21737. !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }());
  21738. // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales
  21739. moment.locale(oldLocale);
  21740. } catch (e) { }
  21741. }
  21742. return locales[name];
  21743. }
  21744. // Return a moment from input, that is local/utc/utcOffset equivalent to
  21745. // model.
  21746. function makeAs(input, model) {
  21747. var res, diff;
  21748. if (model._isUTC) {
  21749. res = model.clone();
  21750. diff = (moment.isMoment(input) || isDate(input) ?
  21751. +input : +moment(input)) - (+res);
  21752. // Use low-level api, because this fn is low-level api.
  21753. res._d.setTime(+res._d + diff);
  21754. moment.updateOffset(res, false);
  21755. return res;
  21756. } else {
  21757. return moment(input).local();
  21758. }
  21759. }
  21760. /************************************
  21761. Locale
  21762. ************************************/
  21763. extend(Locale.prototype, {
  21764. set : function (config) {
  21765. var prop, i;
  21766. for (i in config) {
  21767. prop = config[i];
  21768. if (typeof prop === 'function') {
  21769. this[i] = prop;
  21770. } else {
  21771. this['_' + i] = prop;
  21772. }
  21773. }
  21774. // Lenient ordinal parsing accepts just a number in addition to
  21775. // number + (possibly) stuff coming from _ordinalParseLenient.
  21776. this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source);
  21777. },
  21778. _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
  21779. months : function (m) {
  21780. return this._months[m.month()];
  21781. },
  21782. _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
  21783. monthsShort : function (m) {
  21784. return this._monthsShort[m.month()];
  21785. },
  21786. monthsParse : function (monthName, format, strict) {
  21787. var i, mom, regex;
  21788. if (!this._monthsParse) {
  21789. this._monthsParse = [];
  21790. this._longMonthsParse = [];
  21791. this._shortMonthsParse = [];
  21792. }
  21793. for (i = 0; i < 12; i++) {
  21794. // make the regex if we don't have it already
  21795. mom = moment.utc([2000, i]);
  21796. if (strict && !this._longMonthsParse[i]) {
  21797. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  21798. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  21799. }
  21800. if (!strict && !this._monthsParse[i]) {
  21801. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  21802. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  21803. }
  21804. // test the regex
  21805. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  21806. return i;
  21807. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  21808. return i;
  21809. } else if (!strict && this._monthsParse[i].test(monthName)) {
  21810. return i;
  21811. }
  21812. }
  21813. },
  21814. _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
  21815. weekdays : function (m) {
  21816. return this._weekdays[m.day()];
  21817. },
  21818. _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
  21819. weekdaysShort : function (m) {
  21820. return this._weekdaysShort[m.day()];
  21821. },
  21822. _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
  21823. weekdaysMin : function (m) {
  21824. return this._weekdaysMin[m.day()];
  21825. },
  21826. weekdaysParse : function (weekdayName) {
  21827. var i, mom, regex;
  21828. if (!this._weekdaysParse) {
  21829. this._weekdaysParse = [];
  21830. }
  21831. for (i = 0; i < 7; i++) {
  21832. // make the regex if we don't have it already
  21833. if (!this._weekdaysParse[i]) {
  21834. mom = moment([2000, 1]).day(i);
  21835. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  21836. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  21837. }
  21838. // test the regex
  21839. if (this._weekdaysParse[i].test(weekdayName)) {
  21840. return i;
  21841. }
  21842. }
  21843. },
  21844. _longDateFormat : {
  21845. LTS : 'h:mm:ss A',
  21846. LT : 'h:mm A',
  21847. L : 'MM/DD/YYYY',
  21848. LL : 'MMMM D, YYYY',
  21849. LLL : 'MMMM D, YYYY LT',
  21850. LLLL : 'dddd, MMMM D, YYYY LT'
  21851. },
  21852. longDateFormat : function (key) {
  21853. var output = this._longDateFormat[key];
  21854. if (!output && this._longDateFormat[key.toUpperCase()]) {
  21855. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  21856. return val.slice(1);
  21857. });
  21858. this._longDateFormat[key] = output;
  21859. }
  21860. return output;
  21861. },
  21862. isPM : function (input) {
  21863. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  21864. // Using charAt should be more compatible.
  21865. return ((input + '').toLowerCase().charAt(0) === 'p');
  21866. },
  21867. _meridiemParse : /[ap]\.?m?\.?/i,
  21868. meridiem : function (hours, minutes, isLower) {
  21869. if (hours > 11) {
  21870. return isLower ? 'pm' : 'PM';
  21871. } else {
  21872. return isLower ? 'am' : 'AM';
  21873. }
  21874. },
  21875. _calendar : {
  21876. sameDay : '[Today at] LT',
  21877. nextDay : '[Tomorrow at] LT',
  21878. nextWeek : 'dddd [at] LT',
  21879. lastDay : '[Yesterday at] LT',
  21880. lastWeek : '[Last] dddd [at] LT',
  21881. sameElse : 'L'
  21882. },
  21883. calendar : function (key, mom, now) {
  21884. var output = this._calendar[key];
  21885. return typeof output === 'function' ? output.apply(mom, [now]) : output;
  21886. },
  21887. _relativeTime : {
  21888. future : 'in %s',
  21889. past : '%s ago',
  21890. s : 'a few seconds',
  21891. m : 'a minute',
  21892. mm : '%d minutes',
  21893. h : 'an hour',
  21894. hh : '%d hours',
  21895. d : 'a day',
  21896. dd : '%d days',
  21897. M : 'a month',
  21898. MM : '%d months',
  21899. y : 'a year',
  21900. yy : '%d years'
  21901. },
  21902. relativeTime : function (number, withoutSuffix, string, isFuture) {
  21903. var output = this._relativeTime[string];
  21904. return (typeof output === 'function') ?
  21905. output(number, withoutSuffix, string, isFuture) :
  21906. output.replace(/%d/i, number);
  21907. },
  21908. pastFuture : function (diff, output) {
  21909. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  21910. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  21911. },
  21912. ordinal : function (number) {
  21913. return this._ordinal.replace('%d', number);
  21914. },
  21915. _ordinal : '%d',
  21916. _ordinalParse : /\d{1,2}/,
  21917. preparse : function (string) {
  21918. return string;
  21919. },
  21920. postformat : function (string) {
  21921. return string;
  21922. },
  21923. week : function (mom) {
  21924. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  21925. },
  21926. _week : {
  21927. dow : 0, // Sunday is the first day of the week.
  21928. doy : 6 // The week that contains Jan 1st is the first week of the year.
  21929. },
  21930. firstDayOfWeek : function () {
  21931. return this._week.dow;
  21932. },
  21933. firstDayOfYear : function () {
  21934. return this._week.doy;
  21935. },
  21936. _invalidDate: 'Invalid date',
  21937. invalidDate: function () {
  21938. return this._invalidDate;
  21939. }
  21940. });
  21941. /************************************
  21942. Formatting
  21943. ************************************/
  21944. function removeFormattingTokens(input) {
  21945. if (input.match(/\[[\s\S]/)) {
  21946. return input.replace(/^\[|\]$/g, '');
  21947. }
  21948. return input.replace(/\\/g, '');
  21949. }
  21950. function makeFormatFunction(format) {
  21951. var array = format.match(formattingTokens), i, length;
  21952. for (i = 0, length = array.length; i < length; i++) {
  21953. if (formatTokenFunctions[array[i]]) {
  21954. array[i] = formatTokenFunctions[array[i]];
  21955. } else {
  21956. array[i] = removeFormattingTokens(array[i]);
  21957. }
  21958. }
  21959. return function (mom) {
  21960. var output = '';
  21961. for (i = 0; i < length; i++) {
  21962. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  21963. }
  21964. return output;
  21965. };
  21966. }
  21967. // format date using native date object
  21968. function formatMoment(m, format) {
  21969. if (!m.isValid()) {
  21970. return m.localeData().invalidDate();
  21971. }
  21972. format = expandFormat(format, m.localeData());
  21973. if (!formatFunctions[format]) {
  21974. formatFunctions[format] = makeFormatFunction(format);
  21975. }
  21976. return formatFunctions[format](m);
  21977. }
  21978. function expandFormat(format, locale) {
  21979. var i = 5;
  21980. function replaceLongDateFormatTokens(input) {
  21981. return locale.longDateFormat(input) || input;
  21982. }
  21983. localFormattingTokens.lastIndex = 0;
  21984. while (i >= 0 && localFormattingTokens.test(format)) {
  21985. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  21986. localFormattingTokens.lastIndex = 0;
  21987. i -= 1;
  21988. }
  21989. return format;
  21990. }
  21991. /************************************
  21992. Parsing
  21993. ************************************/
  21994. // get the regex to find the next token
  21995. function getParseRegexForToken(token, config) {
  21996. var a, strict = config._strict;
  21997. switch (token) {
  21998. case 'Q':
  21999. return parseTokenOneDigit;
  22000. case 'DDDD':
  22001. return parseTokenThreeDigits;
  22002. case 'YYYY':
  22003. case 'GGGG':
  22004. case 'gggg':
  22005. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  22006. case 'Y':
  22007. case 'G':
  22008. case 'g':
  22009. return parseTokenSignedNumber;
  22010. case 'YYYYYY':
  22011. case 'YYYYY':
  22012. case 'GGGGG':
  22013. case 'ggggg':
  22014. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  22015. case 'S':
  22016. if (strict) {
  22017. return parseTokenOneDigit;
  22018. }
  22019. /* falls through */
  22020. case 'SS':
  22021. if (strict) {
  22022. return parseTokenTwoDigits;
  22023. }
  22024. /* falls through */
  22025. case 'SSS':
  22026. if (strict) {
  22027. return parseTokenThreeDigits;
  22028. }
  22029. /* falls through */
  22030. case 'DDD':
  22031. return parseTokenOneToThreeDigits;
  22032. case 'MMM':
  22033. case 'MMMM':
  22034. case 'dd':
  22035. case 'ddd':
  22036. case 'dddd':
  22037. return parseTokenWord;
  22038. case 'a':
  22039. case 'A':
  22040. return config._locale._meridiemParse;
  22041. case 'x':
  22042. return parseTokenOffsetMs;
  22043. case 'X':
  22044. return parseTokenTimestampMs;
  22045. case 'Z':
  22046. case 'ZZ':
  22047. return parseTokenTimezone;
  22048. case 'T':
  22049. return parseTokenT;
  22050. case 'SSSS':
  22051. return parseTokenDigits;
  22052. case 'MM':
  22053. case 'DD':
  22054. case 'YY':
  22055. case 'GG':
  22056. case 'gg':
  22057. case 'HH':
  22058. case 'hh':
  22059. case 'mm':
  22060. case 'ss':
  22061. case 'ww':
  22062. case 'WW':
  22063. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  22064. case 'M':
  22065. case 'D':
  22066. case 'd':
  22067. case 'H':
  22068. case 'h':
  22069. case 'm':
  22070. case 's':
  22071. case 'w':
  22072. case 'W':
  22073. case 'e':
  22074. case 'E':
  22075. return parseTokenOneOrTwoDigits;
  22076. case 'Do':
  22077. return strict ? config._locale._ordinalParse : config._locale._ordinalParseLenient;
  22078. default :
  22079. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i'));
  22080. return a;
  22081. }
  22082. }
  22083. function utcOffsetFromString(string) {
  22084. string = string || '';
  22085. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  22086. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  22087. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  22088. minutes = +(parts[1] * 60) + toInt(parts[2]);
  22089. return parts[0] === '+' ? minutes : -minutes;
  22090. }
  22091. // function to convert string input to date
  22092. function addTimeToArrayFromToken(token, input, config) {
  22093. var a, datePartArray = config._a;
  22094. switch (token) {
  22095. // QUARTER
  22096. case 'Q':
  22097. if (input != null) {
  22098. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  22099. }
  22100. break;
  22101. // MONTH
  22102. case 'M' : // fall through to MM
  22103. case 'MM' :
  22104. if (input != null) {
  22105. datePartArray[MONTH] = toInt(input) - 1;
  22106. }
  22107. break;
  22108. case 'MMM' : // fall through to MMMM
  22109. case 'MMMM' :
  22110. a = config._locale.monthsParse(input, token, config._strict);
  22111. // if we didn't find a month name, mark the date as invalid.
  22112. if (a != null) {
  22113. datePartArray[MONTH] = a;
  22114. } else {
  22115. config._pf.invalidMonth = input;
  22116. }
  22117. break;
  22118. // DAY OF MONTH
  22119. case 'D' : // fall through to DD
  22120. case 'DD' :
  22121. if (input != null) {
  22122. datePartArray[DATE] = toInt(input);
  22123. }
  22124. break;
  22125. case 'Do' :
  22126. if (input != null) {
  22127. datePartArray[DATE] = toInt(parseInt(
  22128. input.match(/\d{1,2}/)[0], 10));
  22129. }
  22130. break;
  22131. // DAY OF YEAR
  22132. case 'DDD' : // fall through to DDDD
  22133. case 'DDDD' :
  22134. if (input != null) {
  22135. config._dayOfYear = toInt(input);
  22136. }
  22137. break;
  22138. // YEAR
  22139. case 'YY' :
  22140. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  22141. break;
  22142. case 'YYYY' :
  22143. case 'YYYYY' :
  22144. case 'YYYYYY' :
  22145. datePartArray[YEAR] = toInt(input);
  22146. break;
  22147. // AM / PM
  22148. case 'a' : // fall through to A
  22149. case 'A' :
  22150. config._meridiem = input;
  22151. // config._isPm = config._locale.isPM(input);
  22152. break;
  22153. // HOUR
  22154. case 'h' : // fall through to hh
  22155. case 'hh' :
  22156. config._pf.bigHour = true;
  22157. /* falls through */
  22158. case 'H' : // fall through to HH
  22159. case 'HH' :
  22160. datePartArray[HOUR] = toInt(input);
  22161. break;
  22162. // MINUTE
  22163. case 'm' : // fall through to mm
  22164. case 'mm' :
  22165. datePartArray[MINUTE] = toInt(input);
  22166. break;
  22167. // SECOND
  22168. case 's' : // fall through to ss
  22169. case 'ss' :
  22170. datePartArray[SECOND] = toInt(input);
  22171. break;
  22172. // MILLISECOND
  22173. case 'S' :
  22174. case 'SS' :
  22175. case 'SSS' :
  22176. case 'SSSS' :
  22177. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  22178. break;
  22179. // UNIX OFFSET (MILLISECONDS)
  22180. case 'x':
  22181. config._d = new Date(toInt(input));
  22182. break;
  22183. // UNIX TIMESTAMP WITH MS
  22184. case 'X':
  22185. config._d = new Date(parseFloat(input) * 1000);
  22186. break;
  22187. // TIMEZONE
  22188. case 'Z' : // fall through to ZZ
  22189. case 'ZZ' :
  22190. config._useUTC = true;
  22191. config._tzm = utcOffsetFromString(input);
  22192. break;
  22193. // WEEKDAY - human
  22194. case 'dd':
  22195. case 'ddd':
  22196. case 'dddd':
  22197. a = config._locale.weekdaysParse(input);
  22198. // if we didn't get a weekday name, mark the date as invalid
  22199. if (a != null) {
  22200. config._w = config._w || {};
  22201. config._w['d'] = a;
  22202. } else {
  22203. config._pf.invalidWeekday = input;
  22204. }
  22205. break;
  22206. // WEEK, WEEK DAY - numeric
  22207. case 'w':
  22208. case 'ww':
  22209. case 'W':
  22210. case 'WW':
  22211. case 'd':
  22212. case 'e':
  22213. case 'E':
  22214. token = token.substr(0, 1);
  22215. /* falls through */
  22216. case 'gggg':
  22217. case 'GGGG':
  22218. case 'GGGGG':
  22219. token = token.substr(0, 2);
  22220. if (input) {
  22221. config._w = config._w || {};
  22222. config._w[token] = toInt(input);
  22223. }
  22224. break;
  22225. case 'gg':
  22226. case 'GG':
  22227. config._w = config._w || {};
  22228. config._w[token] = moment.parseTwoDigitYear(input);
  22229. }
  22230. }
  22231. function dayOfYearFromWeekInfo(config) {
  22232. var w, weekYear, week, weekday, dow, doy, temp;
  22233. w = config._w;
  22234. if (w.GG != null || w.W != null || w.E != null) {
  22235. dow = 1;
  22236. doy = 4;
  22237. // TODO: We need to take the current isoWeekYear, but that depends on
  22238. // how we interpret now (local, utc, fixed offset). So create
  22239. // a now version of current config (take local/utc/offset flags, and
  22240. // create now).
  22241. weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year);
  22242. week = dfl(w.W, 1);
  22243. weekday = dfl(w.E, 1);
  22244. } else {
  22245. dow = config._locale._week.dow;
  22246. doy = config._locale._week.doy;
  22247. weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year);
  22248. week = dfl(w.w, 1);
  22249. if (w.d != null) {
  22250. // weekday -- low day numbers are considered next week
  22251. weekday = w.d;
  22252. if (weekday < dow) {
  22253. ++week;
  22254. }
  22255. } else if (w.e != null) {
  22256. // local weekday -- counting starts from begining of week
  22257. weekday = w.e + dow;
  22258. } else {
  22259. // default to begining of week
  22260. weekday = dow;
  22261. }
  22262. }
  22263. temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow);
  22264. config._a[YEAR] = temp.year;
  22265. config._dayOfYear = temp.dayOfYear;
  22266. }
  22267. // convert an array to a date.
  22268. // the array should mirror the parameters below
  22269. // note: all values past the year are optional and will default to the lowest possible value.
  22270. // [year, month, day , hour, minute, second, millisecond]
  22271. function dateFromConfig(config) {
  22272. var i, date, input = [], currentDate, yearToUse;
  22273. if (config._d) {
  22274. return;
  22275. }
  22276. currentDate = currentDateArray(config);
  22277. //compute day of the year from weeks and weekdays
  22278. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  22279. dayOfYearFromWeekInfo(config);
  22280. }
  22281. //if the day of the year is set, figure out what it is
  22282. if (config._dayOfYear) {
  22283. yearToUse = dfl(config._a[YEAR], currentDate[YEAR]);
  22284. if (config._dayOfYear > daysInYear(yearToUse)) {
  22285. config._pf._overflowDayOfYear = true;
  22286. }
  22287. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  22288. config._a[MONTH] = date.getUTCMonth();
  22289. config._a[DATE] = date.getUTCDate();
  22290. }
  22291. // Default to current date.
  22292. // * if no year, month, day of month are given, default to today
  22293. // * if day of month is given, default month and year
  22294. // * if month is given, default only year
  22295. // * if year is given, don't default anything
  22296. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  22297. config._a[i] = input[i] = currentDate[i];
  22298. }
  22299. // Zero out whatever was not defaulted, including time
  22300. for (; i < 7; i++) {
  22301. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  22302. }
  22303. // Check for 24:00:00.000
  22304. if (config._a[HOUR] === 24 &&
  22305. config._a[MINUTE] === 0 &&
  22306. config._a[SECOND] === 0 &&
  22307. config._a[MILLISECOND] === 0) {
  22308. config._nextDay = true;
  22309. config._a[HOUR] = 0;
  22310. }
  22311. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  22312. // Apply timezone offset from input. The actual utcOffset can be changed
  22313. // with parseZone.
  22314. if (config._tzm != null) {
  22315. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  22316. }
  22317. if (config._nextDay) {
  22318. config._a[HOUR] = 24;
  22319. }
  22320. }
  22321. function dateFromObject(config) {
  22322. var normalizedInput;
  22323. if (config._d) {
  22324. return;
  22325. }
  22326. normalizedInput = normalizeObjectUnits(config._i);
  22327. config._a = [
  22328. normalizedInput.year,
  22329. normalizedInput.month,
  22330. normalizedInput.day || normalizedInput.date,
  22331. normalizedInput.hour,
  22332. normalizedInput.minute,
  22333. normalizedInput.second,
  22334. normalizedInput.millisecond
  22335. ];
  22336. dateFromConfig(config);
  22337. }
  22338. function currentDateArray(config) {
  22339. var now = new Date();
  22340. if (config._useUTC) {
  22341. return [
  22342. now.getUTCFullYear(),
  22343. now.getUTCMonth(),
  22344. now.getUTCDate()
  22345. ];
  22346. } else {
  22347. return [now.getFullYear(), now.getMonth(), now.getDate()];
  22348. }
  22349. }
  22350. // date from string and format string
  22351. function makeDateFromStringAndFormat(config) {
  22352. if (config._f === moment.ISO_8601) {
  22353. parseISO(config);
  22354. return;
  22355. }
  22356. config._a = [];
  22357. config._pf.empty = true;
  22358. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  22359. var string = '' + config._i,
  22360. i, parsedInput, tokens, token, skipped,
  22361. stringLength = string.length,
  22362. totalParsedInputLength = 0;
  22363. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  22364. for (i = 0; i < tokens.length; i++) {
  22365. token = tokens[i];
  22366. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  22367. if (parsedInput) {
  22368. skipped = string.substr(0, string.indexOf(parsedInput));
  22369. if (skipped.length > 0) {
  22370. config._pf.unusedInput.push(skipped);
  22371. }
  22372. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  22373. totalParsedInputLength += parsedInput.length;
  22374. }
  22375. // don't parse if it's not a known token
  22376. if (formatTokenFunctions[token]) {
  22377. if (parsedInput) {
  22378. config._pf.empty = false;
  22379. }
  22380. else {
  22381. config._pf.unusedTokens.push(token);
  22382. }
  22383. addTimeToArrayFromToken(token, parsedInput, config);
  22384. }
  22385. else if (config._strict && !parsedInput) {
  22386. config._pf.unusedTokens.push(token);
  22387. }
  22388. }
  22389. // add remaining unparsed input length to the string
  22390. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  22391. if (string.length > 0) {
  22392. config._pf.unusedInput.push(string);
  22393. }
  22394. // clear _12h flag if hour is <= 12
  22395. if (config._pf.bigHour === true && config._a[HOUR] <= 12) {
  22396. config._pf.bigHour = undefined;
  22397. }
  22398. // handle meridiem
  22399. config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR],
  22400. config._meridiem);
  22401. dateFromConfig(config);
  22402. checkOverflow(config);
  22403. }
  22404. function unescapeFormat(s) {
  22405. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  22406. return p1 || p2 || p3 || p4;
  22407. });
  22408. }
  22409. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  22410. function regexpEscape(s) {
  22411. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  22412. }
  22413. // date from string and array of format strings
  22414. function makeDateFromStringAndArray(config) {
  22415. var tempConfig,
  22416. bestMoment,
  22417. scoreToBeat,
  22418. i,
  22419. currentScore;
  22420. if (config._f.length === 0) {
  22421. config._pf.invalidFormat = true;
  22422. config._d = new Date(NaN);
  22423. return;
  22424. }
  22425. for (i = 0; i < config._f.length; i++) {
  22426. currentScore = 0;
  22427. tempConfig = copyConfig({}, config);
  22428. if (config._useUTC != null) {
  22429. tempConfig._useUTC = config._useUTC;
  22430. }
  22431. tempConfig._pf = defaultParsingFlags();
  22432. tempConfig._f = config._f[i];
  22433. makeDateFromStringAndFormat(tempConfig);
  22434. if (!isValid(tempConfig)) {
  22435. continue;
  22436. }
  22437. // if there is any input that was not parsed add a penalty for that format
  22438. currentScore += tempConfig._pf.charsLeftOver;
  22439. //or tokens
  22440. currentScore += tempConfig._pf.unusedTokens.length * 10;
  22441. tempConfig._pf.score = currentScore;
  22442. if (scoreToBeat == null || currentScore < scoreToBeat) {
  22443. scoreToBeat = currentScore;
  22444. bestMoment = tempConfig;
  22445. }
  22446. }
  22447. extend(config, bestMoment || tempConfig);
  22448. }
  22449. // date from iso format
  22450. function parseISO(config) {
  22451. var i, l,
  22452. string = config._i,
  22453. match = isoRegex.exec(string);
  22454. if (match) {
  22455. config._pf.iso = true;
  22456. for (i = 0, l = isoDates.length; i < l; i++) {
  22457. if (isoDates[i][1].exec(string)) {
  22458. // match[5] should be 'T' or undefined
  22459. config._f = isoDates[i][0] + (match[6] || ' ');
  22460. break;
  22461. }
  22462. }
  22463. for (i = 0, l = isoTimes.length; i < l; i++) {
  22464. if (isoTimes[i][1].exec(string)) {
  22465. config._f += isoTimes[i][0];
  22466. break;
  22467. }
  22468. }
  22469. if (string.match(parseTokenTimezone)) {
  22470. config._f += 'Z';
  22471. }
  22472. makeDateFromStringAndFormat(config);
  22473. } else {
  22474. config._isValid = false;
  22475. }
  22476. }
  22477. // date from iso format or fallback
  22478. function makeDateFromString(config) {
  22479. parseISO(config);
  22480. if (config._isValid === false) {
  22481. delete config._isValid;
  22482. moment.createFromInputFallback(config);
  22483. }
  22484. }
  22485. function map(arr, fn) {
  22486. var res = [], i;
  22487. for (i = 0; i < arr.length; ++i) {
  22488. res.push(fn(arr[i], i));
  22489. }
  22490. return res;
  22491. }
  22492. function makeDateFromInput(config) {
  22493. var input = config._i, matched;
  22494. if (input === undefined) {
  22495. config._d = new Date();
  22496. } else if (isDate(input)) {
  22497. config._d = new Date(+input);
  22498. } else if ((matched = aspNetJsonRegex.exec(input)) !== null) {
  22499. config._d = new Date(+matched[1]);
  22500. } else if (typeof input === 'string') {
  22501. makeDateFromString(config);
  22502. } else if (isArray(input)) {
  22503. config._a = map(input.slice(0), function (obj) {
  22504. return parseInt(obj, 10);
  22505. });
  22506. dateFromConfig(config);
  22507. } else if (typeof(input) === 'object') {
  22508. dateFromObject(config);
  22509. } else if (typeof(input) === 'number') {
  22510. // from milliseconds
  22511. config._d = new Date(input);
  22512. } else {
  22513. moment.createFromInputFallback(config);
  22514. }
  22515. }
  22516. function makeDate(y, m, d, h, M, s, ms) {
  22517. //can't just apply() to create a date:
  22518. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  22519. var date = new Date(y, m, d, h, M, s, ms);
  22520. //the date constructor doesn't accept years < 1970
  22521. if (y < 1970) {
  22522. date.setFullYear(y);
  22523. }
  22524. return date;
  22525. }
  22526. function makeUTCDate(y) {
  22527. var date = new Date(Date.UTC.apply(null, arguments));
  22528. if (y < 1970) {
  22529. date.setUTCFullYear(y);
  22530. }
  22531. return date;
  22532. }
  22533. function parseWeekday(input, locale) {
  22534. if (typeof input === 'string') {
  22535. if (!isNaN(input)) {
  22536. input = parseInt(input, 10);
  22537. }
  22538. else {
  22539. input = locale.weekdaysParse(input);
  22540. if (typeof input !== 'number') {
  22541. return null;
  22542. }
  22543. }
  22544. }
  22545. return input;
  22546. }
  22547. /************************************
  22548. Relative Time
  22549. ************************************/
  22550. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  22551. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  22552. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  22553. }
  22554. function relativeTime(posNegDuration, withoutSuffix, locale) {
  22555. var duration = moment.duration(posNegDuration).abs(),
  22556. seconds = round(duration.as('s')),
  22557. minutes = round(duration.as('m')),
  22558. hours = round(duration.as('h')),
  22559. days = round(duration.as('d')),
  22560. months = round(duration.as('M')),
  22561. years = round(duration.as('y')),
  22562. args = seconds < relativeTimeThresholds.s && ['s', seconds] ||
  22563. minutes === 1 && ['m'] ||
  22564. minutes < relativeTimeThresholds.m && ['mm', minutes] ||
  22565. hours === 1 && ['h'] ||
  22566. hours < relativeTimeThresholds.h && ['hh', hours] ||
  22567. days === 1 && ['d'] ||
  22568. days < relativeTimeThresholds.d && ['dd', days] ||
  22569. months === 1 && ['M'] ||
  22570. months < relativeTimeThresholds.M && ['MM', months] ||
  22571. years === 1 && ['y'] || ['yy', years];
  22572. args[2] = withoutSuffix;
  22573. args[3] = +posNegDuration > 0;
  22574. args[4] = locale;
  22575. return substituteTimeAgo.apply({}, args);
  22576. }
  22577. /************************************
  22578. Week of Year
  22579. ************************************/
  22580. // firstDayOfWeek 0 = sun, 6 = sat
  22581. // the day of the week that starts the week
  22582. // (usually sunday or monday)
  22583. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  22584. // the first week is the week that contains the first
  22585. // of this day of the week
  22586. // (eg. ISO weeks use thursday (4))
  22587. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  22588. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  22589. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  22590. adjustedMoment;
  22591. if (daysToDayOfWeek > end) {
  22592. daysToDayOfWeek -= 7;
  22593. }
  22594. if (daysToDayOfWeek < end - 7) {
  22595. daysToDayOfWeek += 7;
  22596. }
  22597. adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd');
  22598. return {
  22599. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  22600. year: adjustedMoment.year()
  22601. };
  22602. }
  22603. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  22604. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  22605. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  22606. d = d === 0 ? 7 : d;
  22607. weekday = weekday != null ? weekday : firstDayOfWeek;
  22608. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  22609. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  22610. return {
  22611. year: dayOfYear > 0 ? year : year - 1,
  22612. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  22613. };
  22614. }
  22615. /************************************
  22616. Top Level Functions
  22617. ************************************/
  22618. function makeMoment(config) {
  22619. var input = config._i,
  22620. format = config._f,
  22621. res;
  22622. config._locale = config._locale || moment.localeData(config._l);
  22623. if (input === null || (format === undefined && input === '')) {
  22624. return moment.invalid({nullInput: true});
  22625. }
  22626. if (typeof input === 'string') {
  22627. config._i = input = config._locale.preparse(input);
  22628. }
  22629. if (moment.isMoment(input)) {
  22630. return new Moment(input, true);
  22631. } else if (format) {
  22632. if (isArray(format)) {
  22633. makeDateFromStringAndArray(config);
  22634. } else {
  22635. makeDateFromStringAndFormat(config);
  22636. }
  22637. } else {
  22638. makeDateFromInput(config);
  22639. }
  22640. res = new Moment(config);
  22641. if (res._nextDay) {
  22642. // Adding is smart enough around DST
  22643. res.add(1, 'd');
  22644. res._nextDay = undefined;
  22645. }
  22646. return res;
  22647. }
  22648. moment = function (input, format, locale, strict) {
  22649. var c;
  22650. if (typeof(locale) === 'boolean') {
  22651. strict = locale;
  22652. locale = undefined;
  22653. }
  22654. // object construction must be done this way.
  22655. // https://github.com/moment/moment/issues/1423
  22656. c = {};
  22657. c._isAMomentObject = true;
  22658. c._i = input;
  22659. c._f = format;
  22660. c._l = locale;
  22661. c._strict = strict;
  22662. c._isUTC = false;
  22663. c._pf = defaultParsingFlags();
  22664. return makeMoment(c);
  22665. };
  22666. moment.suppressDeprecationWarnings = false;
  22667. moment.createFromInputFallback = deprecate(
  22668. 'moment construction falls back to js Date. This is ' +
  22669. 'discouraged and will be removed in upcoming major ' +
  22670. 'release. Please refer to ' +
  22671. 'https://github.com/moment/moment/issues/1407 for more info.',
  22672. function (config) {
  22673. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  22674. }
  22675. );
  22676. // Pick a moment m from moments so that m[fn](other) is true for all
  22677. // other. This relies on the function fn to be transitive.
  22678. //
  22679. // moments should either be an array of moment objects or an array, whose
  22680. // first element is an array of moment objects.
  22681. function pickBy(fn, moments) {
  22682. var res, i;
  22683. if (moments.length === 1 && isArray(moments[0])) {
  22684. moments = moments[0];
  22685. }
  22686. if (!moments.length) {
  22687. return moment();
  22688. }
  22689. res = moments[0];
  22690. for (i = 1; i < moments.length; ++i) {
  22691. if (moments[i][fn](res)) {
  22692. res = moments[i];
  22693. }
  22694. }
  22695. return res;
  22696. }
  22697. moment.min = function () {
  22698. var args = [].slice.call(arguments, 0);
  22699. return pickBy('isBefore', args);
  22700. };
  22701. moment.max = function () {
  22702. var args = [].slice.call(arguments, 0);
  22703. return pickBy('isAfter', args);
  22704. };
  22705. // creating with utc
  22706. moment.utc = function (input, format, locale, strict) {
  22707. var c;
  22708. if (typeof(locale) === 'boolean') {
  22709. strict = locale;
  22710. locale = undefined;
  22711. }
  22712. // object construction must be done this way.
  22713. // https://github.com/moment/moment/issues/1423
  22714. c = {};
  22715. c._isAMomentObject = true;
  22716. c._useUTC = true;
  22717. c._isUTC = true;
  22718. c._l = locale;
  22719. c._i = input;
  22720. c._f = format;
  22721. c._strict = strict;
  22722. c._pf = defaultParsingFlags();
  22723. return makeMoment(c).utc();
  22724. };
  22725. // creating with unix timestamp (in seconds)
  22726. moment.unix = function (input) {
  22727. return moment(input * 1000);
  22728. };
  22729. // duration
  22730. moment.duration = function (input, key) {
  22731. var duration = input,
  22732. // matching against regexp is expensive, do it on demand
  22733. match = null,
  22734. sign,
  22735. ret,
  22736. parseIso,
  22737. diffRes;
  22738. if (moment.isDuration(input)) {
  22739. duration = {
  22740. ms: input._milliseconds,
  22741. d: input._days,
  22742. M: input._months
  22743. };
  22744. } else if (typeof input === 'number') {
  22745. duration = {};
  22746. if (key) {
  22747. duration[key] = input;
  22748. } else {
  22749. duration.milliseconds = input;
  22750. }
  22751. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  22752. sign = (match[1] === '-') ? -1 : 1;
  22753. duration = {
  22754. y: 0,
  22755. d: toInt(match[DATE]) * sign,
  22756. h: toInt(match[HOUR]) * sign,
  22757. m: toInt(match[MINUTE]) * sign,
  22758. s: toInt(match[SECOND]) * sign,
  22759. ms: toInt(match[MILLISECOND]) * sign
  22760. };
  22761. } else if (!!(match = isoDurationRegex.exec(input))) {
  22762. sign = (match[1] === '-') ? -1 : 1;
  22763. parseIso = function (inp) {
  22764. // We'd normally use ~~inp for this, but unfortunately it also
  22765. // converts floats to ints.
  22766. // inp may be undefined, so careful calling replace on it.
  22767. var res = inp && parseFloat(inp.replace(',', '.'));
  22768. // apply sign while we're at it
  22769. return (isNaN(res) ? 0 : res) * sign;
  22770. };
  22771. duration = {
  22772. y: parseIso(match[2]),
  22773. M: parseIso(match[3]),
  22774. d: parseIso(match[4]),
  22775. h: parseIso(match[5]),
  22776. m: parseIso(match[6]),
  22777. s: parseIso(match[7]),
  22778. w: parseIso(match[8])
  22779. };
  22780. } else if (duration == null) {// checks for null or undefined
  22781. duration = {};
  22782. } else if (typeof duration === 'object' &&
  22783. ('from' in duration || 'to' in duration)) {
  22784. diffRes = momentsDifference(moment(duration.from), moment(duration.to));
  22785. duration = {};
  22786. duration.ms = diffRes.milliseconds;
  22787. duration.M = diffRes.months;
  22788. }
  22789. ret = new Duration(duration);
  22790. if (moment.isDuration(input) && hasOwnProp(input, '_locale')) {
  22791. ret._locale = input._locale;
  22792. }
  22793. return ret;
  22794. };
  22795. // version number
  22796. moment.version = VERSION;
  22797. // default format
  22798. moment.defaultFormat = isoFormat;
  22799. // constant that refers to the ISO standard
  22800. moment.ISO_8601 = function () {};
  22801. // Plugins that add properties should also add the key here (null value),
  22802. // so we can properly clone ourselves.
  22803. moment.momentProperties = momentProperties;
  22804. // This function will be called whenever a moment is mutated.
  22805. // It is intended to keep the offset in sync with the timezone.
  22806. moment.updateOffset = function () {};
  22807. // This function allows you to set a threshold for relative time strings
  22808. moment.relativeTimeThreshold = function (threshold, limit) {
  22809. if (relativeTimeThresholds[threshold] === undefined) {
  22810. return false;
  22811. }
  22812. if (limit === undefined) {
  22813. return relativeTimeThresholds[threshold];
  22814. }
  22815. relativeTimeThresholds[threshold] = limit;
  22816. return true;
  22817. };
  22818. moment.lang = deprecate(
  22819. 'moment.lang is deprecated. Use moment.locale instead.',
  22820. function (key, value) {
  22821. return moment.locale(key, value);
  22822. }
  22823. );
  22824. // This function will load locale and then set the global locale. If
  22825. // no arguments are passed in, it will simply return the current global
  22826. // locale key.
  22827. moment.locale = function (key, values) {
  22828. var data;
  22829. if (key) {
  22830. if (typeof(values) !== 'undefined') {
  22831. data = moment.defineLocale(key, values);
  22832. }
  22833. else {
  22834. data = moment.localeData(key);
  22835. }
  22836. if (data) {
  22837. moment.duration._locale = moment._locale = data;
  22838. }
  22839. }
  22840. return moment._locale._abbr;
  22841. };
  22842. moment.defineLocale = function (name, values) {
  22843. if (values !== null) {
  22844. values.abbr = name;
  22845. if (!locales[name]) {
  22846. locales[name] = new Locale();
  22847. }
  22848. locales[name].set(values);
  22849. // backwards compat for now: also set the locale
  22850. moment.locale(name);
  22851. return locales[name];
  22852. } else {
  22853. // useful for testing
  22854. delete locales[name];
  22855. return null;
  22856. }
  22857. };
  22858. moment.langData = deprecate(
  22859. 'moment.langData is deprecated. Use moment.localeData instead.',
  22860. function (key) {
  22861. return moment.localeData(key);
  22862. }
  22863. );
  22864. // returns locale data
  22865. moment.localeData = function (key) {
  22866. var locale;
  22867. if (key && key._locale && key._locale._abbr) {
  22868. key = key._locale._abbr;
  22869. }
  22870. if (!key) {
  22871. return moment._locale;
  22872. }
  22873. if (!isArray(key)) {
  22874. //short-circuit everything else
  22875. locale = loadLocale(key);
  22876. if (locale) {
  22877. return locale;
  22878. }
  22879. key = [key];
  22880. }
  22881. return chooseLocale(key);
  22882. };
  22883. // compare moment object
  22884. moment.isMoment = function (obj) {
  22885. return obj instanceof Moment ||
  22886. (obj != null && hasOwnProp(obj, '_isAMomentObject'));
  22887. };
  22888. // for typechecking Duration objects
  22889. moment.isDuration = function (obj) {
  22890. return obj instanceof Duration;
  22891. };
  22892. for (i = lists.length - 1; i >= 0; --i) {
  22893. makeList(lists[i]);
  22894. }
  22895. moment.normalizeUnits = function (units) {
  22896. return normalizeUnits(units);
  22897. };
  22898. moment.invalid = function (flags) {
  22899. var m = moment.utc(NaN);
  22900. if (flags != null) {
  22901. extend(m._pf, flags);
  22902. }
  22903. else {
  22904. m._pf.userInvalidated = true;
  22905. }
  22906. return m;
  22907. };
  22908. moment.parseZone = function () {
  22909. return moment.apply(null, arguments).parseZone();
  22910. };
  22911. moment.parseTwoDigitYear = function (input) {
  22912. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  22913. };
  22914. moment.isDate = isDate;
  22915. /************************************
  22916. Moment Prototype
  22917. ************************************/
  22918. extend(moment.fn = Moment.prototype, {
  22919. clone : function () {
  22920. return moment(this);
  22921. },
  22922. valueOf : function () {
  22923. return +this._d - ((this._offset || 0) * 60000);
  22924. },
  22925. unix : function () {
  22926. return Math.floor(+this / 1000);
  22927. },
  22928. toString : function () {
  22929. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  22930. },
  22931. toDate : function () {
  22932. return this._offset ? new Date(+this) : this._d;
  22933. },
  22934. toISOString : function () {
  22935. var m = moment(this).utc();
  22936. if (0 < m.year() && m.year() <= 9999) {
  22937. if ('function' === typeof Date.prototype.toISOString) {
  22938. // native implementation is ~50x faster, use it when we can
  22939. return this.toDate().toISOString();
  22940. } else {
  22941. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  22942. }
  22943. } else {
  22944. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  22945. }
  22946. },
  22947. toArray : function () {
  22948. var m = this;
  22949. return [
  22950. m.year(),
  22951. m.month(),
  22952. m.date(),
  22953. m.hours(),
  22954. m.minutes(),
  22955. m.seconds(),
  22956. m.milliseconds()
  22957. ];
  22958. },
  22959. isValid : function () {
  22960. return isValid(this);
  22961. },
  22962. isDSTShifted : function () {
  22963. if (this._a) {
  22964. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  22965. }
  22966. return false;
  22967. },
  22968. parsingFlags : function () {
  22969. return extend({}, this._pf);
  22970. },
  22971. invalidAt: function () {
  22972. return this._pf.overflow;
  22973. },
  22974. utc : function (keepLocalTime) {
  22975. return this.utcOffset(0, keepLocalTime);
  22976. },
  22977. local : function (keepLocalTime) {
  22978. if (this._isUTC) {
  22979. this.utcOffset(0, keepLocalTime);
  22980. this._isUTC = false;
  22981. if (keepLocalTime) {
  22982. this.subtract(this._dateUtcOffset(), 'm');
  22983. }
  22984. }
  22985. return this;
  22986. },
  22987. format : function (inputString) {
  22988. var output = formatMoment(this, inputString || moment.defaultFormat);
  22989. return this.localeData().postformat(output);
  22990. },
  22991. add : createAdder(1, 'add'),
  22992. subtract : createAdder(-1, 'subtract'),
  22993. diff : function (input, units, asFloat) {
  22994. var that = makeAs(input, this),
  22995. zoneDiff = (that.utcOffset() - this.utcOffset()) * 6e4,
  22996. anchor, diff, output, daysAdjust;
  22997. units = normalizeUnits(units);
  22998. if (units === 'year' || units === 'month' || units === 'quarter') {
  22999. output = monthDiff(this, that);
  23000. if (units === 'quarter') {
  23001. output = output / 3;
  23002. } else if (units === 'year') {
  23003. output = output / 12;
  23004. }
  23005. } else {
  23006. diff = this - that;
  23007. output = units === 'second' ? diff / 1e3 : // 1000
  23008. units === 'minute' ? diff / 6e4 : // 1000 * 60
  23009. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  23010. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  23011. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  23012. diff;
  23013. }
  23014. return asFloat ? output : absRound(output);
  23015. },
  23016. from : function (time, withoutSuffix) {
  23017. return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  23018. },
  23019. fromNow : function (withoutSuffix) {
  23020. return this.from(moment(), withoutSuffix);
  23021. },
  23022. calendar : function (time) {
  23023. // We want to compare the start of today, vs this.
  23024. // Getting start-of-today depends on whether we're locat/utc/offset
  23025. // or not.
  23026. var now = time || moment(),
  23027. sod = makeAs(now, this).startOf('day'),
  23028. diff = this.diff(sod, 'days', true),
  23029. format = diff < -6 ? 'sameElse' :
  23030. diff < -1 ? 'lastWeek' :
  23031. diff < 0 ? 'lastDay' :
  23032. diff < 1 ? 'sameDay' :
  23033. diff < 2 ? 'nextDay' :
  23034. diff < 7 ? 'nextWeek' : 'sameElse';
  23035. return this.format(this.localeData().calendar(format, this, moment(now)));
  23036. },
  23037. isLeapYear : function () {
  23038. return isLeapYear(this.year());
  23039. },
  23040. isDST : function () {
  23041. return (this.utcOffset() > this.clone().month(0).utcOffset() ||
  23042. this.utcOffset() > this.clone().month(5).utcOffset());
  23043. },
  23044. day : function (input) {
  23045. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  23046. if (input != null) {
  23047. input = parseWeekday(input, this.localeData());
  23048. return this.add(input - day, 'd');
  23049. } else {
  23050. return day;
  23051. }
  23052. },
  23053. month : makeAccessor('Month', true),
  23054. startOf : function (units) {
  23055. units = normalizeUnits(units);
  23056. // the following switch intentionally omits break keywords
  23057. // to utilize falling through the cases.
  23058. switch (units) {
  23059. case 'year':
  23060. this.month(0);
  23061. /* falls through */
  23062. case 'quarter':
  23063. case 'month':
  23064. this.date(1);
  23065. /* falls through */
  23066. case 'week':
  23067. case 'isoWeek':
  23068. case 'day':
  23069. this.hours(0);
  23070. /* falls through */
  23071. case 'hour':
  23072. this.minutes(0);
  23073. /* falls through */
  23074. case 'minute':
  23075. this.seconds(0);
  23076. /* falls through */
  23077. case 'second':
  23078. this.milliseconds(0);
  23079. /* falls through */
  23080. }
  23081. // weeks are a special case
  23082. if (units === 'week') {
  23083. this.weekday(0);
  23084. } else if (units === 'isoWeek') {
  23085. this.isoWeekday(1);
  23086. }
  23087. // quarters are also special
  23088. if (units === 'quarter') {
  23089. this.month(Math.floor(this.month() / 3) * 3);
  23090. }
  23091. return this;
  23092. },
  23093. endOf: function (units) {
  23094. units = normalizeUnits(units);
  23095. if (units === undefined || units === 'millisecond') {
  23096. return this;
  23097. }
  23098. return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
  23099. },
  23100. isAfter: function (input, units) {
  23101. var inputMs;
  23102. units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
  23103. if (units === 'millisecond') {
  23104. input = moment.isMoment(input) ? input : moment(input);
  23105. return +this > +input;
  23106. } else {
  23107. inputMs = moment.isMoment(input) ? +input : +moment(input);
  23108. return inputMs < +this.clone().startOf(units);
  23109. }
  23110. },
  23111. isBefore: function (input, units) {
  23112. var inputMs;
  23113. units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond');
  23114. if (units === 'millisecond') {
  23115. input = moment.isMoment(input) ? input : moment(input);
  23116. return +this < +input;
  23117. } else {
  23118. inputMs = moment.isMoment(input) ? +input : +moment(input);
  23119. return +this.clone().endOf(units) < inputMs;
  23120. }
  23121. },
  23122. isBetween: function (from, to, units) {
  23123. return this.isAfter(from, units) && this.isBefore(to, units);
  23124. },
  23125. isSame: function (input, units) {
  23126. var inputMs;
  23127. units = normalizeUnits(units || 'millisecond');
  23128. if (units === 'millisecond') {
  23129. input = moment.isMoment(input) ? input : moment(input);
  23130. return +this === +input;
  23131. } else {
  23132. inputMs = +moment(input);
  23133. return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units));
  23134. }
  23135. },
  23136. min: deprecate(
  23137. 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
  23138. function (other) {
  23139. other = moment.apply(null, arguments);
  23140. return other < this ? this : other;
  23141. }
  23142. ),
  23143. max: deprecate(
  23144. 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
  23145. function (other) {
  23146. other = moment.apply(null, arguments);
  23147. return other > this ? this : other;
  23148. }
  23149. ),
  23150. zone : deprecate(
  23151. 'moment().zone is deprecated, use moment().utcOffset instead. ' +
  23152. 'https://github.com/moment/moment/issues/1779',
  23153. function (input, keepLocalTime) {
  23154. if (input != null) {
  23155. if (typeof input !== 'string') {
  23156. input = -input;
  23157. }
  23158. this.utcOffset(input, keepLocalTime);
  23159. return this;
  23160. } else {
  23161. return -this.utcOffset();
  23162. }
  23163. }
  23164. ),
  23165. // keepLocalTime = true means only change the timezone, without
  23166. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  23167. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  23168. // +0200, so we adjust the time as needed, to be valid.
  23169. //
  23170. // Keeping the time actually adds/subtracts (one hour)
  23171. // from the actual represented time. That is why we call updateOffset
  23172. // a second time. In case it wants us to change the offset again
  23173. // _changeInProgress == true case, then we have to adjust, because
  23174. // there is no such time in the given timezone.
  23175. utcOffset : function (input, keepLocalTime) {
  23176. var offset = this._offset || 0,
  23177. localAdjust;
  23178. if (input != null) {
  23179. if (typeof input === 'string') {
  23180. input = utcOffsetFromString(input);
  23181. }
  23182. if (Math.abs(input) < 16) {
  23183. input = input * 60;
  23184. }
  23185. if (!this._isUTC && keepLocalTime) {
  23186. localAdjust = this._dateUtcOffset();
  23187. }
  23188. this._offset = input;
  23189. this._isUTC = true;
  23190. if (localAdjust != null) {
  23191. this.add(localAdjust, 'm');
  23192. }
  23193. if (offset !== input) {
  23194. if (!keepLocalTime || this._changeInProgress) {
  23195. addOrSubtractDurationFromMoment(this,
  23196. moment.duration(input - offset, 'm'), 1, false);
  23197. } else if (!this._changeInProgress) {
  23198. this._changeInProgress = true;
  23199. moment.updateOffset(this, true);
  23200. this._changeInProgress = null;
  23201. }
  23202. }
  23203. return this;
  23204. } else {
  23205. return this._isUTC ? offset : this._dateUtcOffset();
  23206. }
  23207. },
  23208. isLocal : function () {
  23209. return !this._isUTC;
  23210. },
  23211. isUtcOffset : function () {
  23212. return this._isUTC;
  23213. },
  23214. isUtc : function () {
  23215. return this._isUTC && this._offset === 0;
  23216. },
  23217. zoneAbbr : function () {
  23218. return this._isUTC ? 'UTC' : '';
  23219. },
  23220. zoneName : function () {
  23221. return this._isUTC ? 'Coordinated Universal Time' : '';
  23222. },
  23223. parseZone : function () {
  23224. if (this._tzm) {
  23225. this.utcOffset(this._tzm);
  23226. } else if (typeof this._i === 'string') {
  23227. this.utcOffset(utcOffsetFromString(this._i));
  23228. }
  23229. return this;
  23230. },
  23231. hasAlignedHourOffset : function (input) {
  23232. if (!input) {
  23233. input = 0;
  23234. }
  23235. else {
  23236. input = moment(input).utcOffset();
  23237. }
  23238. return (this.utcOffset() - input) % 60 === 0;
  23239. },
  23240. daysInMonth : function () {
  23241. return daysInMonth(this.year(), this.month());
  23242. },
  23243. dayOfYear : function (input) {
  23244. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  23245. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  23246. },
  23247. quarter : function (input) {
  23248. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  23249. },
  23250. weekYear : function (input) {
  23251. var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year;
  23252. return input == null ? year : this.add((input - year), 'y');
  23253. },
  23254. isoWeekYear : function (input) {
  23255. var year = weekOfYear(this, 1, 4).year;
  23256. return input == null ? year : this.add((input - year), 'y');
  23257. },
  23258. week : function (input) {
  23259. var week = this.localeData().week(this);
  23260. return input == null ? week : this.add((input - week) * 7, 'd');
  23261. },
  23262. isoWeek : function (input) {
  23263. var week = weekOfYear(this, 1, 4).week;
  23264. return input == null ? week : this.add((input - week) * 7, 'd');
  23265. },
  23266. weekday : function (input) {
  23267. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  23268. return input == null ? weekday : this.add(input - weekday, 'd');
  23269. },
  23270. isoWeekday : function (input) {
  23271. // behaves the same as moment#day except
  23272. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  23273. // as a setter, sunday should belong to the previous week.
  23274. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  23275. },
  23276. isoWeeksInYear : function () {
  23277. return weeksInYear(this.year(), 1, 4);
  23278. },
  23279. weeksInYear : function () {
  23280. var weekInfo = this.localeData()._week;
  23281. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  23282. },
  23283. get : function (units) {
  23284. units = normalizeUnits(units);
  23285. return this[units]();
  23286. },
  23287. set : function (units, value) {
  23288. var unit;
  23289. if (typeof units === 'object') {
  23290. for (unit in units) {
  23291. this.set(unit, units[unit]);
  23292. }
  23293. }
  23294. else {
  23295. units = normalizeUnits(units);
  23296. if (typeof this[units] === 'function') {
  23297. this[units](value);
  23298. }
  23299. }
  23300. return this;
  23301. },
  23302. // If passed a locale key, it will set the locale for this
  23303. // instance. Otherwise, it will return the locale configuration
  23304. // variables for this instance.
  23305. locale : function (key) {
  23306. var newLocaleData;
  23307. if (key === undefined) {
  23308. return this._locale._abbr;
  23309. } else {
  23310. newLocaleData = moment.localeData(key);
  23311. if (newLocaleData != null) {
  23312. this._locale = newLocaleData;
  23313. }
  23314. return this;
  23315. }
  23316. },
  23317. lang : deprecate(
  23318. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  23319. function (key) {
  23320. if (key === undefined) {
  23321. return this.localeData();
  23322. } else {
  23323. return this.locale(key);
  23324. }
  23325. }
  23326. ),
  23327. localeData : function () {
  23328. return this._locale;
  23329. },
  23330. _dateUtcOffset : function () {
  23331. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  23332. // https://github.com/moment/moment/pull/1871
  23333. return -Math.round(this._d.getTimezoneOffset() / 15) * 15;
  23334. }
  23335. });
  23336. function rawMonthSetter(mom, value) {
  23337. var dayOfMonth;
  23338. // TODO: Move this out of here!
  23339. if (typeof value === 'string') {
  23340. value = mom.localeData().monthsParse(value);
  23341. // TODO: Another silent failure?
  23342. if (typeof value !== 'number') {
  23343. return mom;
  23344. }
  23345. }
  23346. dayOfMonth = Math.min(mom.date(),
  23347. daysInMonth(mom.year(), value));
  23348. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  23349. return mom;
  23350. }
  23351. function rawGetter(mom, unit) {
  23352. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  23353. }
  23354. function rawSetter(mom, unit, value) {
  23355. if (unit === 'Month') {
  23356. return rawMonthSetter(mom, value);
  23357. } else {
  23358. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  23359. }
  23360. }
  23361. function makeAccessor(unit, keepTime) {
  23362. return function (value) {
  23363. if (value != null) {
  23364. rawSetter(this, unit, value);
  23365. moment.updateOffset(this, keepTime);
  23366. return this;
  23367. } else {
  23368. return rawGetter(this, unit);
  23369. }
  23370. };
  23371. }
  23372. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  23373. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  23374. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  23375. // Setting the hour should keep the time, because the user explicitly
  23376. // specified which hour he wants. So trying to maintain the same hour (in
  23377. // a new timezone) makes sense. Adding/subtracting hours does not follow
  23378. // this rule.
  23379. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  23380. // moment.fn.month is defined separately
  23381. moment.fn.date = makeAccessor('Date', true);
  23382. moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true));
  23383. moment.fn.year = makeAccessor('FullYear', true);
  23384. moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true));
  23385. // add plural methods
  23386. moment.fn.days = moment.fn.day;
  23387. moment.fn.months = moment.fn.month;
  23388. moment.fn.weeks = moment.fn.week;
  23389. moment.fn.isoWeeks = moment.fn.isoWeek;
  23390. moment.fn.quarters = moment.fn.quarter;
  23391. // add aliased format methods
  23392. moment.fn.toJSON = moment.fn.toISOString;
  23393. // alias isUtc for dev-friendliness
  23394. moment.fn.isUTC = moment.fn.isUtc;
  23395. /************************************
  23396. Duration Prototype
  23397. ************************************/
  23398. function daysToYears (days) {
  23399. // 400 years have 146097 days (taking into account leap year rules)
  23400. return days * 400 / 146097;
  23401. }
  23402. function yearsToDays (years) {
  23403. // years * 365 + absRound(years / 4) -
  23404. // absRound(years / 100) + absRound(years / 400);
  23405. return years * 146097 / 400;
  23406. }
  23407. extend(moment.duration.fn = Duration.prototype, {
  23408. _bubble : function () {
  23409. var milliseconds = this._milliseconds,
  23410. days = this._days,
  23411. months = this._months,
  23412. data = this._data,
  23413. seconds, minutes, hours, years = 0;
  23414. // The following code bubbles up values, see the tests for
  23415. // examples of what that means.
  23416. data.milliseconds = milliseconds % 1000;
  23417. seconds = absRound(milliseconds / 1000);
  23418. data.seconds = seconds % 60;
  23419. minutes = absRound(seconds / 60);
  23420. data.minutes = minutes % 60;
  23421. hours = absRound(minutes / 60);
  23422. data.hours = hours % 24;
  23423. days += absRound(hours / 24);
  23424. // Accurately convert days to years, assume start from year 0.
  23425. years = absRound(daysToYears(days));
  23426. days -= absRound(yearsToDays(years));
  23427. // 30 days to a month
  23428. // TODO (iskren): Use anchor date (like 1st Jan) to compute this.
  23429. months += absRound(days / 30);
  23430. days %= 30;
  23431. // 12 months -> 1 year
  23432. years += absRound(months / 12);
  23433. months %= 12;
  23434. data.days = days;
  23435. data.months = months;
  23436. data.years = years;
  23437. },
  23438. abs : function () {
  23439. this._milliseconds = Math.abs(this._milliseconds);
  23440. this._days = Math.abs(this._days);
  23441. this._months = Math.abs(this._months);
  23442. this._data.milliseconds = Math.abs(this._data.milliseconds);
  23443. this._data.seconds = Math.abs(this._data.seconds);
  23444. this._data.minutes = Math.abs(this._data.minutes);
  23445. this._data.hours = Math.abs(this._data.hours);
  23446. this._data.months = Math.abs(this._data.months);
  23447. this._data.years = Math.abs(this._data.years);
  23448. return this;
  23449. },
  23450. weeks : function () {
  23451. return absRound(this.days() / 7);
  23452. },
  23453. valueOf : function () {
  23454. return this._milliseconds +
  23455. this._days * 864e5 +
  23456. (this._months % 12) * 2592e6 +
  23457. toInt(this._months / 12) * 31536e6;
  23458. },
  23459. humanize : function (withSuffix) {
  23460. var output = relativeTime(this, !withSuffix, this.localeData());
  23461. if (withSuffix) {
  23462. output = this.localeData().pastFuture(+this, output);
  23463. }
  23464. return this.localeData().postformat(output);
  23465. },
  23466. add : function (input, val) {
  23467. // supports only 2.0-style add(1, 's') or add(moment)
  23468. var dur = moment.duration(input, val);
  23469. this._milliseconds += dur._milliseconds;
  23470. this._days += dur._days;
  23471. this._months += dur._months;
  23472. this._bubble();
  23473. return this;
  23474. },
  23475. subtract : function (input, val) {
  23476. var dur = moment.duration(input, val);
  23477. this._milliseconds -= dur._milliseconds;
  23478. this._days -= dur._days;
  23479. this._months -= dur._months;
  23480. this._bubble();
  23481. return this;
  23482. },
  23483. get : function (units) {
  23484. units = normalizeUnits(units);
  23485. return this[units.toLowerCase() + 's']();
  23486. },
  23487. as : function (units) {
  23488. var days, months;
  23489. units = normalizeUnits(units);
  23490. if (units === 'month' || units === 'year') {
  23491. days = this._days + this._milliseconds / 864e5;
  23492. months = this._months + daysToYears(days) * 12;
  23493. return units === 'month' ? months : months / 12;
  23494. } else {
  23495. // handle milliseconds separately because of floating point math errors (issue #1867)
  23496. days = this._days + Math.round(yearsToDays(this._months / 12));
  23497. switch (units) {
  23498. case 'week': return days / 7 + this._milliseconds / 6048e5;
  23499. case 'day': return days + this._milliseconds / 864e5;
  23500. case 'hour': return days * 24 + this._milliseconds / 36e5;
  23501. case 'minute': return days * 24 * 60 + this._milliseconds / 6e4;
  23502. case 'second': return days * 24 * 60 * 60 + this._milliseconds / 1000;
  23503. // Math.floor prevents floating point math errors here
  23504. case 'millisecond': return Math.floor(days * 24 * 60 * 60 * 1000) + this._milliseconds;
  23505. default: throw new Error('Unknown unit ' + units);
  23506. }
  23507. }
  23508. },
  23509. lang : moment.fn.lang,
  23510. locale : moment.fn.locale,
  23511. toIsoString : deprecate(
  23512. 'toIsoString() is deprecated. Please use toISOString() instead ' +
  23513. '(notice the capitals)',
  23514. function () {
  23515. return this.toISOString();
  23516. }
  23517. ),
  23518. toISOString : function () {
  23519. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  23520. var years = Math.abs(this.years()),
  23521. months = Math.abs(this.months()),
  23522. days = Math.abs(this.days()),
  23523. hours = Math.abs(this.hours()),
  23524. minutes = Math.abs(this.minutes()),
  23525. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  23526. if (!this.asSeconds()) {
  23527. // this is the same as C#'s (Noda) and python (isodate)...
  23528. // but not other JS (goog.date)
  23529. return 'P0D';
  23530. }
  23531. return (this.asSeconds() < 0 ? '-' : '') +
  23532. 'P' +
  23533. (years ? years + 'Y' : '') +
  23534. (months ? months + 'M' : '') +
  23535. (days ? days + 'D' : '') +
  23536. ((hours || minutes || seconds) ? 'T' : '') +
  23537. (hours ? hours + 'H' : '') +
  23538. (minutes ? minutes + 'M' : '') +
  23539. (seconds ? seconds + 'S' : '');
  23540. },
  23541. localeData : function () {
  23542. return this._locale;
  23543. },
  23544. toJSON : function () {
  23545. return this.toISOString();
  23546. }
  23547. });
  23548. moment.duration.fn.toString = moment.duration.fn.toISOString;
  23549. function makeDurationGetter(name) {
  23550. moment.duration.fn[name] = function () {
  23551. return this._data[name];
  23552. };
  23553. }
  23554. for (i in unitMillisecondFactors) {
  23555. if (hasOwnProp(unitMillisecondFactors, i)) {
  23556. makeDurationGetter(i.toLowerCase());
  23557. }
  23558. }
  23559. moment.duration.fn.asMilliseconds = function () {
  23560. return this.as('ms');
  23561. };
  23562. moment.duration.fn.asSeconds = function () {
  23563. return this.as('s');
  23564. };
  23565. moment.duration.fn.asMinutes = function () {
  23566. return this.as('m');
  23567. };
  23568. moment.duration.fn.asHours = function () {
  23569. return this.as('h');
  23570. };
  23571. moment.duration.fn.asDays = function () {
  23572. return this.as('d');
  23573. };
  23574. moment.duration.fn.asWeeks = function () {
  23575. return this.as('weeks');
  23576. };
  23577. moment.duration.fn.asMonths = function () {
  23578. return this.as('M');
  23579. };
  23580. moment.duration.fn.asYears = function () {
  23581. return this.as('y');
  23582. };
  23583. /************************************
  23584. Default Locale
  23585. ************************************/
  23586. // Set default locale, other locale will inherit from English.
  23587. moment.locale('en', {
  23588. ordinalParse: /\d{1,2}(th|st|nd|rd)/,
  23589. ordinal : function (number) {
  23590. var b = number % 10,
  23591. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  23592. (b === 1) ? 'st' :
  23593. (b === 2) ? 'nd' :
  23594. (b === 3) ? 'rd' : 'th';
  23595. return number + output;
  23596. }
  23597. });
  23598. /* EMBED_LOCALES */
  23599. /************************************
  23600. Exposing Moment
  23601. ************************************/
  23602. function makeGlobal(shouldDeprecate) {
  23603. /*global ender:false */
  23604. if (typeof ender !== 'undefined') {
  23605. return;
  23606. }
  23607. oldGlobalMoment = globalScope.moment;
  23608. if (shouldDeprecate) {
  23609. globalScope.moment = deprecate(
  23610. 'Accessing Moment through the global scope is ' +
  23611. 'deprecated, and will be removed in an upcoming ' +
  23612. 'release.',
  23613. moment);
  23614. } else {
  23615. globalScope.moment = moment;
  23616. }
  23617. }
  23618. // CommonJS module is defined
  23619. if (hasModule) {
  23620. module.exports = moment;
  23621. } else if (true) {
  23622. !(__WEBPACK_AMD_DEFINE_RESULT__ = function (require, exports, module) {
  23623. if (module.config && module.config() && module.config().noGlobal === true) {
  23624. // release the global variable
  23625. globalScope.moment = oldGlobalMoment;
  23626. }
  23627. return moment;
  23628. }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  23629. makeGlobal(true);
  23630. } else {
  23631. makeGlobal();
  23632. }
  23633. }).call(this);
  23634. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(71)(module)))
  23635. /***/ },
  23636. /* 59 */
  23637. /***/ function(module, exports, __webpack_require__) {
  23638. var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v1.1.3 - 2014-05-20
  23639. * http://eightmedia.github.io/hammer.js
  23640. *
  23641. * Copyright (c) 2014 Jorik Tangelder <j.tangelder@gmail.com>;
  23642. * Licensed under the MIT license */
  23643. (function(window, undefined) {
  23644. 'use strict';
  23645. /**
  23646. * @main
  23647. * @module hammer
  23648. *
  23649. * @class Hammer
  23650. * @static
  23651. */
  23652. /**
  23653. * Hammer, use this to create instances
  23654. * ````
  23655. * var hammertime = new Hammer(myElement);
  23656. * ````
  23657. *
  23658. * @method Hammer
  23659. * @param {HTMLElement} element
  23660. * @param {Object} [options={}]
  23661. * @return {Hammer.Instance}
  23662. */
  23663. var Hammer = function Hammer(element, options) {
  23664. return new Hammer.Instance(element, options || {});
  23665. };
  23666. /**
  23667. * version, as defined in package.json
  23668. * the value will be set at each build
  23669. * @property VERSION
  23670. * @final
  23671. * @type {String}
  23672. */
  23673. Hammer.VERSION = '1.1.3';
  23674. /**
  23675. * default settings.
  23676. * more settings are defined per gesture at `/gestures`. Each gesture can be disabled/enabled
  23677. * by setting it's name (like `swipe`) to false.
  23678. * You can set the defaults for all instances by changing this object before creating an instance.
  23679. * @example
  23680. * ````
  23681. * Hammer.defaults.drag = false;
  23682. * Hammer.defaults.behavior.touchAction = 'pan-y';
  23683. * delete Hammer.defaults.behavior.userSelect;
  23684. * ````
  23685. * @property defaults
  23686. * @type {Object}
  23687. */
  23688. Hammer.defaults = {
  23689. /**
  23690. * this setting object adds styles and attributes to the element to prevent the browser from doing
  23691. * its native behavior. The css properties are auto prefixed for the browsers when needed.
  23692. * @property defaults.behavior
  23693. * @type {Object}
  23694. */
  23695. behavior: {
  23696. /**
  23697. * Disables text selection to improve the dragging gesture. When the value is `none` it also sets
  23698. * `onselectstart=false` for IE on the element. Mainly for desktop browsers.
  23699. * @property defaults.behavior.userSelect
  23700. * @type {String}
  23701. * @default 'none'
  23702. */
  23703. userSelect: 'none',
  23704. /**
  23705. * Specifies whether and how a given region can be manipulated by the user (for instance, by panning or zooming).
  23706. * Used by Chrome 35> and IE10>. By default this makes the element blocking any touch event.
  23707. * @property defaults.behavior.touchAction
  23708. * @type {String}
  23709. * @default: 'pan-y'
  23710. */
  23711. touchAction: 'pan-y',
  23712. /**
  23713. * Disables the default callout shown when you touch and hold a touch target.
  23714. * On iOS, when you touch and hold a touch target such as a link, Safari displays
  23715. * a callout containing information about the link. This property allows you to disable that callout.
  23716. * @property defaults.behavior.touchCallout
  23717. * @type {String}
  23718. * @default 'none'
  23719. */
  23720. touchCallout: 'none',
  23721. /**
  23722. * Specifies whether zooming is enabled. Used by IE10>
  23723. * @property defaults.behavior.contentZooming
  23724. * @type {String}
  23725. * @default 'none'
  23726. */
  23727. contentZooming: 'none',
  23728. /**
  23729. * Specifies that an entire element should be draggable instead of its contents.
  23730. * Mainly for desktop browsers.
  23731. * @property defaults.behavior.userDrag
  23732. * @type {String}
  23733. * @default 'none'
  23734. */
  23735. userDrag: 'none',
  23736. /**
  23737. * Overrides the highlight color shown when the user taps a link or a JavaScript
  23738. * clickable element in Safari on iPhone. This property obeys the alpha value, if specified.
  23739. *
  23740. * If you don't specify an alpha value, Safari on iPhone applies a default alpha value
  23741. * to the color. To disable tap highlighting, set the alpha value to 0 (invisible).
  23742. * If you set the alpha value to 1.0 (opaque), the element is not visible when tapped.
  23743. * @property defaults.behavior.tapHighlightColor
  23744. * @type {String}
  23745. * @default 'rgba(0,0,0,0)'
  23746. */
  23747. tapHighlightColor: 'rgba(0,0,0,0)'
  23748. }
  23749. };
  23750. /**
  23751. * hammer document where the base events are added at
  23752. * @property DOCUMENT
  23753. * @type {HTMLElement}
  23754. * @default window.document
  23755. */
  23756. Hammer.DOCUMENT = document;
  23757. /**
  23758. * detect support for pointer events
  23759. * @property HAS_POINTEREVENTS
  23760. * @type {Boolean}
  23761. */
  23762. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  23763. /**
  23764. * detect support for touch events
  23765. * @property HAS_TOUCHEVENTS
  23766. * @type {Boolean}
  23767. */
  23768. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  23769. /**
  23770. * detect mobile browsers
  23771. * @property IS_MOBILE
  23772. * @type {Boolean}
  23773. */
  23774. Hammer.IS_MOBILE = /mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent);
  23775. /**
  23776. * detect if we want to support mouseevents at all
  23777. * @property NO_MOUSEEVENTS
  23778. * @type {Boolean}
  23779. */
  23780. Hammer.NO_MOUSEEVENTS = (Hammer.HAS_TOUCHEVENTS && Hammer.IS_MOBILE) || Hammer.HAS_POINTEREVENTS;
  23781. /**
  23782. * interval in which Hammer recalculates current velocity/direction/angle in ms
  23783. * @property CALCULATE_INTERVAL
  23784. * @type {Number}
  23785. * @default 25
  23786. */
  23787. Hammer.CALCULATE_INTERVAL = 25;
  23788. /**
  23789. * eventtypes per touchevent (start, move, end) are filled by `Event.determineEventTypes` on `setup`
  23790. * the object contains the DOM event names per type (`EVENT_START`, `EVENT_MOVE`, `EVENT_END`)
  23791. * @property EVENT_TYPES
  23792. * @private
  23793. * @writeOnce
  23794. * @type {Object}
  23795. */
  23796. var EVENT_TYPES = {};
  23797. /**
  23798. * direction strings, for safe comparisons
  23799. * @property DIRECTION_DOWN|LEFT|UP|RIGHT
  23800. * @final
  23801. * @type {String}
  23802. * @default 'down' 'left' 'up' 'right'
  23803. */
  23804. var DIRECTION_DOWN = Hammer.DIRECTION_DOWN = 'down';
  23805. var DIRECTION_LEFT = Hammer.DIRECTION_LEFT = 'left';
  23806. var DIRECTION_UP = Hammer.DIRECTION_UP = 'up';
  23807. var DIRECTION_RIGHT = Hammer.DIRECTION_RIGHT = 'right';
  23808. /**
  23809. * pointertype strings, for safe comparisons
  23810. * @property POINTER_MOUSE|TOUCH|PEN
  23811. * @final
  23812. * @type {String}
  23813. * @default 'mouse' 'touch' 'pen'
  23814. */
  23815. var POINTER_MOUSE = Hammer.POINTER_MOUSE = 'mouse';
  23816. var POINTER_TOUCH = Hammer.POINTER_TOUCH = 'touch';
  23817. var POINTER_PEN = Hammer.POINTER_PEN = 'pen';
  23818. /**
  23819. * eventtypes
  23820. * @property EVENT_START|MOVE|END|RELEASE|TOUCH
  23821. * @final
  23822. * @type {String}
  23823. * @default 'start' 'change' 'move' 'end' 'release' 'touch'
  23824. */
  23825. var EVENT_START = Hammer.EVENT_START = 'start';
  23826. var EVENT_MOVE = Hammer.EVENT_MOVE = 'move';
  23827. var EVENT_END = Hammer.EVENT_END = 'end';
  23828. var EVENT_RELEASE = Hammer.EVENT_RELEASE = 'release';
  23829. var EVENT_TOUCH = Hammer.EVENT_TOUCH = 'touch';
  23830. /**
  23831. * if the window events are set...
  23832. * @property READY
  23833. * @writeOnce
  23834. * @type {Boolean}
  23835. * @default false
  23836. */
  23837. Hammer.READY = false;
  23838. /**
  23839. * plugins namespace
  23840. * @property plugins
  23841. * @type {Object}
  23842. */
  23843. Hammer.plugins = Hammer.plugins || {};
  23844. /**
  23845. * gestures namespace
  23846. * see `/gestures` for the definitions
  23847. * @property gestures
  23848. * @type {Object}
  23849. */
  23850. Hammer.gestures = Hammer.gestures || {};
  23851. /**
  23852. * setup events to detect gestures on the document
  23853. * this function is called when creating an new instance
  23854. * @private
  23855. */
  23856. function setup() {
  23857. if(Hammer.READY) {
  23858. return;
  23859. }
  23860. // find what eventtypes we add listeners to
  23861. Event.determineEventTypes();
  23862. // Register all gestures inside Hammer.gestures
  23863. Utils.each(Hammer.gestures, function(gesture) {
  23864. Detection.register(gesture);
  23865. });
  23866. // Add touch events on the document
  23867. Event.onTouch(Hammer.DOCUMENT, EVENT_MOVE, Detection.detect);
  23868. Event.onTouch(Hammer.DOCUMENT, EVENT_END, Detection.detect);
  23869. // Hammer is ready...!
  23870. Hammer.READY = true;
  23871. }
  23872. /**
  23873. * @module hammer
  23874. *
  23875. * @class Utils
  23876. * @static
  23877. */
  23878. var Utils = Hammer.utils = {
  23879. /**
  23880. * extend method, could also be used for cloning when `dest` is an empty object.
  23881. * changes the dest object
  23882. * @method extend
  23883. * @param {Object} dest
  23884. * @param {Object} src
  23885. * @param {Boolean} [merge=false] do a merge
  23886. * @return {Object} dest
  23887. */
  23888. extend: function extend(dest, src, merge) {
  23889. for(var key in src) {
  23890. if(!src.hasOwnProperty(key) || (dest[key] !== undefined && merge)) {
  23891. continue;
  23892. }
  23893. dest[key] = src[key];
  23894. }
  23895. return dest;
  23896. },
  23897. /**
  23898. * simple addEventListener wrapper
  23899. * @method on
  23900. * @param {HTMLElement} element
  23901. * @param {String} type
  23902. * @param {Function} handler
  23903. */
  23904. on: function on(element, type, handler) {
  23905. element.addEventListener(type, handler, false);
  23906. },
  23907. /**
  23908. * simple removeEventListener wrapper
  23909. * @method off
  23910. * @param {HTMLElement} element
  23911. * @param {String} type
  23912. * @param {Function} handler
  23913. */
  23914. off: function off(element, type, handler) {
  23915. element.removeEventListener(type, handler, false);
  23916. },
  23917. /**
  23918. * forEach over arrays and objects
  23919. * @method each
  23920. * @param {Object|Array} obj
  23921. * @param {Function} iterator
  23922. * @param {any} iterator.item
  23923. * @param {Number} iterator.index
  23924. * @param {Object|Array} iterator.obj the source object
  23925. * @param {Object} context value to use as `this` in the iterator
  23926. */
  23927. each: function each(obj, iterator, context) {
  23928. var i, len;
  23929. // native forEach on arrays
  23930. if('forEach' in obj) {
  23931. obj.forEach(iterator, context);
  23932. // arrays
  23933. } else if(obj.length !== undefined) {
  23934. for(i = 0, len = obj.length; i < len; i++) {
  23935. if(iterator.call(context, obj[i], i, obj) === false) {
  23936. return;
  23937. }
  23938. }
  23939. // objects
  23940. } else {
  23941. for(i in obj) {
  23942. if(obj.hasOwnProperty(i) &&
  23943. iterator.call(context, obj[i], i, obj) === false) {
  23944. return;
  23945. }
  23946. }
  23947. }
  23948. },
  23949. /**
  23950. * find if a string contains the string using indexOf
  23951. * @method inStr
  23952. * @param {String} src
  23953. * @param {String} find
  23954. * @return {Boolean} found
  23955. */
  23956. inStr: function inStr(src, find) {
  23957. return src.indexOf(find) > -1;
  23958. },
  23959. /**
  23960. * find if a array contains the object using indexOf or a simple polyfill
  23961. * @method inArray
  23962. * @param {String} src
  23963. * @param {String} find
  23964. * @return {Boolean|Number} false when not found, or the index
  23965. */
  23966. inArray: function inArray(src, find) {
  23967. if(src.indexOf) {
  23968. var index = src.indexOf(find);
  23969. return (index === -1) ? false : index;
  23970. } else {
  23971. for(var i = 0, len = src.length; i < len; i++) {
  23972. if(src[i] === find) {
  23973. return i;
  23974. }
  23975. }
  23976. return false;
  23977. }
  23978. },
  23979. /**
  23980. * convert an array-like object (`arguments`, `touchlist`) to an array
  23981. * @method toArray
  23982. * @param {Object} obj
  23983. * @return {Array}
  23984. */
  23985. toArray: function toArray(obj) {
  23986. return Array.prototype.slice.call(obj, 0);
  23987. },
  23988. /**
  23989. * find if a node is in the given parent
  23990. * @method hasParent
  23991. * @param {HTMLElement} node
  23992. * @param {HTMLElement} parent
  23993. * @return {Boolean} found
  23994. */
  23995. hasParent: function hasParent(node, parent) {
  23996. while(node) {
  23997. if(node == parent) {
  23998. return true;
  23999. }
  24000. node = node.parentNode;
  24001. }
  24002. return false;
  24003. },
  24004. /**
  24005. * get the center of all the touches
  24006. * @method getCenter
  24007. * @param {Array} touches
  24008. * @return {Object} center contains `pageX`, `pageY`, `clientX` and `clientY` properties
  24009. */
  24010. getCenter: function getCenter(touches) {
  24011. var pageX = [],
  24012. pageY = [],
  24013. clientX = [],
  24014. clientY = [],
  24015. min = Math.min,
  24016. max = Math.max;
  24017. // no need to loop when only one touch
  24018. if(touches.length === 1) {
  24019. return {
  24020. pageX: touches[0].pageX,
  24021. pageY: touches[0].pageY,
  24022. clientX: touches[0].clientX,
  24023. clientY: touches[0].clientY
  24024. };
  24025. }
  24026. Utils.each(touches, function(touch) {
  24027. pageX.push(touch.pageX);
  24028. pageY.push(touch.pageY);
  24029. clientX.push(touch.clientX);
  24030. clientY.push(touch.clientY);
  24031. });
  24032. return {
  24033. pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2,
  24034. pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2,
  24035. clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2,
  24036. clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2
  24037. };
  24038. },
  24039. /**
  24040. * calculate the velocity between two points. unit is in px per ms.
  24041. * @method getVelocity
  24042. * @param {Number} deltaTime
  24043. * @param {Number} deltaX
  24044. * @param {Number} deltaY
  24045. * @return {Object} velocity `x` and `y`
  24046. */
  24047. getVelocity: function getVelocity(deltaTime, deltaX, deltaY) {
  24048. return {
  24049. x: Math.abs(deltaX / deltaTime) || 0,
  24050. y: Math.abs(deltaY / deltaTime) || 0
  24051. };
  24052. },
  24053. /**
  24054. * calculate the angle between two coordinates
  24055. * @method getAngle
  24056. * @param {Touch} touch1
  24057. * @param {Touch} touch2
  24058. * @return {Number} angle
  24059. */
  24060. getAngle: function getAngle(touch1, touch2) {
  24061. var x = touch2.clientX - touch1.clientX,
  24062. y = touch2.clientY - touch1.clientY;
  24063. return Math.atan2(y, x) * 180 / Math.PI;
  24064. },
  24065. /**
  24066. * do a small comparision to get the direction between two touches.
  24067. * @method getDirection
  24068. * @param {Touch} touch1
  24069. * @param {Touch} touch2
  24070. * @return {String} direction matches `DIRECTION_LEFT|RIGHT|UP|DOWN`
  24071. */
  24072. getDirection: function getDirection(touch1, touch2) {
  24073. var x = Math.abs(touch1.clientX - touch2.clientX),
  24074. y = Math.abs(touch1.clientY - touch2.clientY);
  24075. if(x >= y) {
  24076. return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  24077. }
  24078. return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN;
  24079. },
  24080. /**
  24081. * calculate the distance between two touches
  24082. * @method getDistance
  24083. * @param {Touch}touch1
  24084. * @param {Touch} touch2
  24085. * @return {Number} distance
  24086. */
  24087. getDistance: function getDistance(touch1, touch2) {
  24088. var x = touch2.clientX - touch1.clientX,
  24089. y = touch2.clientY - touch1.clientY;
  24090. return Math.sqrt((x * x) + (y * y));
  24091. },
  24092. /**
  24093. * calculate the scale factor between two touchLists
  24094. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  24095. * @method getScale
  24096. * @param {Array} start array of touches
  24097. * @param {Array} end array of touches
  24098. * @return {Number} scale
  24099. */
  24100. getScale: function getScale(start, end) {
  24101. // need two fingers...
  24102. if(start.length >= 2 && end.length >= 2) {
  24103. return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]);
  24104. }
  24105. return 1;
  24106. },
  24107. /**
  24108. * calculate the rotation degrees between two touchLists
  24109. * @method getRotation
  24110. * @param {Array} start array of touches
  24111. * @param {Array} end array of touches
  24112. * @return {Number} rotation
  24113. */
  24114. getRotation: function getRotation(start, end) {
  24115. // need two fingers
  24116. if(start.length >= 2 && end.length >= 2) {
  24117. return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]);
  24118. }
  24119. return 0;
  24120. },
  24121. /**
  24122. * find out if the direction is vertical *
  24123. * @method isVertical
  24124. * @param {String} direction matches `DIRECTION_UP|DOWN`
  24125. * @return {Boolean} is_vertical
  24126. */
  24127. isVertical: function isVertical(direction) {
  24128. return direction == DIRECTION_UP || direction == DIRECTION_DOWN;
  24129. },
  24130. /**
  24131. * set css properties with their prefixes
  24132. * @param {HTMLElement} element
  24133. * @param {String} prop
  24134. * @param {String} value
  24135. * @param {Boolean} [toggle=true]
  24136. * @return {Boolean}
  24137. */
  24138. setPrefixedCss: function setPrefixedCss(element, prop, value, toggle) {
  24139. var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms'];
  24140. prop = Utils.toCamelCase(prop);
  24141. for(var i = 0; i < prefixes.length; i++) {
  24142. var p = prop;
  24143. // prefixes
  24144. if(prefixes[i]) {
  24145. p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1);
  24146. }
  24147. // test the style
  24148. if(p in element.style) {
  24149. element.style[p] = (toggle == null || toggle) && value || '';
  24150. break;
  24151. }
  24152. }
  24153. },
  24154. /**
  24155. * toggle browser default behavior by setting css properties.
  24156. * `userSelect='none'` also sets `element.onselectstart` to false
  24157. * `userDrag='none'` also sets `element.ondragstart` to false
  24158. *
  24159. * @method toggleBehavior
  24160. * @param {HtmlElement} element
  24161. * @param {Object} props
  24162. * @param {Boolean} [toggle=true]
  24163. */
  24164. toggleBehavior: function toggleBehavior(element, props, toggle) {
  24165. if(!props || !element || !element.style) {
  24166. return;
  24167. }
  24168. // set the css properties
  24169. Utils.each(props, function(value, prop) {
  24170. Utils.setPrefixedCss(element, prop, value, toggle);
  24171. });
  24172. var falseFn = toggle && function() {
  24173. return false;
  24174. };
  24175. // also the disable onselectstart
  24176. if(props.userSelect == 'none') {
  24177. element.onselectstart = falseFn;
  24178. }
  24179. // and disable ondragstart
  24180. if(props.userDrag == 'none') {
  24181. element.ondragstart = falseFn;
  24182. }
  24183. },
  24184. /**
  24185. * convert a string with underscores to camelCase
  24186. * so prevent_default becomes preventDefault
  24187. * @param {String} str
  24188. * @return {String} camelCaseStr
  24189. */
  24190. toCamelCase: function toCamelCase(str) {
  24191. return str.replace(/[_-]([a-z])/g, function(s) {
  24192. return s[1].toUpperCase();
  24193. });
  24194. }
  24195. };
  24196. /**
  24197. * @module hammer
  24198. */
  24199. /**
  24200. * @class Event
  24201. * @static
  24202. */
  24203. var Event = Hammer.event = {
  24204. /**
  24205. * when touch events have been fired, this is true
  24206. * this is used to stop mouse events
  24207. * @property prevent_mouseevents
  24208. * @private
  24209. * @type {Boolean}
  24210. */
  24211. preventMouseEvents: false,
  24212. /**
  24213. * if EVENT_START has been fired
  24214. * @property started
  24215. * @private
  24216. * @type {Boolean}
  24217. */
  24218. started: false,
  24219. /**
  24220. * when the mouse is hold down, this is true
  24221. * @property should_detect
  24222. * @private
  24223. * @type {Boolean}
  24224. */
  24225. shouldDetect: false,
  24226. /**
  24227. * simple event binder with a hook and support for multiple types
  24228. * @method on
  24229. * @param {HTMLElement} element
  24230. * @param {String} type
  24231. * @param {Function} handler
  24232. * @param {Function} [hook]
  24233. * @param {Object} hook.type
  24234. */
  24235. on: function on(element, type, handler, hook) {
  24236. var types = type.split(' ');
  24237. Utils.each(types, function(type) {
  24238. Utils.on(element, type, handler);
  24239. hook && hook(type);
  24240. });
  24241. },
  24242. /**
  24243. * simple event unbinder with a hook and support for multiple types
  24244. * @method off
  24245. * @param {HTMLElement} element
  24246. * @param {String} type
  24247. * @param {Function} handler
  24248. * @param {Function} [hook]
  24249. * @param {Object} hook.type
  24250. */
  24251. off: function off(element, type, handler, hook) {
  24252. var types = type.split(' ');
  24253. Utils.each(types, function(type) {
  24254. Utils.off(element, type, handler);
  24255. hook && hook(type);
  24256. });
  24257. },
  24258. /**
  24259. * the core touch event handler.
  24260. * this finds out if we should to detect gestures
  24261. * @method onTouch
  24262. * @param {HTMLElement} element
  24263. * @param {String} eventType matches `EVENT_START|MOVE|END`
  24264. * @param {Function} handler
  24265. * @return onTouchHandler {Function} the core event handler
  24266. */
  24267. onTouch: function onTouch(element, eventType, handler) {
  24268. var self = this;
  24269. var onTouchHandler = function onTouchHandler(ev) {
  24270. var srcType = ev.type.toLowerCase(),
  24271. isPointer = Hammer.HAS_POINTEREVENTS,
  24272. isMouse = Utils.inStr(srcType, 'mouse'),
  24273. triggerType;
  24274. // if we are in a mouseevent, but there has been a touchevent triggered in this session
  24275. // we want to do nothing. simply break out of the event.
  24276. if(isMouse && self.preventMouseEvents) {
  24277. return;
  24278. // mousebutton must be down
  24279. } else if(isMouse && eventType == EVENT_START && ev.button === 0) {
  24280. self.preventMouseEvents = false;
  24281. self.shouldDetect = true;
  24282. } else if(isPointer && eventType == EVENT_START) {
  24283. self.shouldDetect = (ev.buttons === 1 || PointerEvent.matchType(POINTER_TOUCH, ev));
  24284. // just a valid start event, but no mouse
  24285. } else if(!isMouse && eventType == EVENT_START) {
  24286. self.preventMouseEvents = true;
  24287. self.shouldDetect = true;
  24288. }
  24289. // update the pointer event before entering the detection
  24290. if(isPointer && eventType != EVENT_END) {
  24291. PointerEvent.updatePointer(eventType, ev);
  24292. }
  24293. // we are in a touch/down state, so allowed detection of gestures
  24294. if(self.shouldDetect) {
  24295. triggerType = self.doDetect.call(self, ev, eventType, element, handler);
  24296. }
  24297. // ...and we are done with the detection
  24298. // so reset everything to start each detection totally fresh
  24299. if(triggerType == EVENT_END) {
  24300. self.preventMouseEvents = false;
  24301. self.shouldDetect = false;
  24302. PointerEvent.reset();
  24303. // update the pointerevent object after the detection
  24304. }
  24305. if(isPointer && eventType == EVENT_END) {
  24306. PointerEvent.updatePointer(eventType, ev);
  24307. }
  24308. };
  24309. this.on(element, EVENT_TYPES[eventType], onTouchHandler);
  24310. return onTouchHandler;
  24311. },
  24312. /**
  24313. * the core detection method
  24314. * this finds out what hammer-touch-events to trigger
  24315. * @method doDetect
  24316. * @param {Object} ev
  24317. * @param {String} eventType matches `EVENT_START|MOVE|END`
  24318. * @param {HTMLElement} element
  24319. * @param {Function} handler
  24320. * @return {String} triggerType matches `EVENT_START|MOVE|END`
  24321. */
  24322. doDetect: function doDetect(ev, eventType, element, handler) {
  24323. var touchList = this.getTouchList(ev, eventType);
  24324. var touchListLength = touchList.length;
  24325. var triggerType = eventType;
  24326. var triggerChange = touchList.trigger; // used by fakeMultitouch plugin
  24327. var changedLength = touchListLength;
  24328. // at each touchstart-like event we want also want to trigger a TOUCH event...
  24329. if(eventType == EVENT_START) {
  24330. triggerChange = EVENT_TOUCH;
  24331. // ...the same for a touchend-like event
  24332. } else if(eventType == EVENT_END) {
  24333. triggerChange = EVENT_RELEASE;
  24334. // keep track of how many touches have been removed
  24335. changedLength = touchList.length - ((ev.changedTouches) ? ev.changedTouches.length : 1);
  24336. }
  24337. // after there are still touches on the screen,
  24338. // we just want to trigger a MOVE event. so change the START or END to a MOVE
  24339. // but only after detection has been started, the first time we actualy want a START
  24340. if(changedLength > 0 && this.started) {
  24341. triggerType = EVENT_MOVE;
  24342. }
  24343. // detection has been started, we keep track of this, see above
  24344. this.started = true;
  24345. // generate some event data, some basic information
  24346. var evData = this.collectEventData(element, triggerType, touchList, ev);
  24347. // trigger the triggerType event before the change (TOUCH, RELEASE) events
  24348. // but the END event should be at last
  24349. if(eventType != EVENT_END) {
  24350. handler.call(Detection, evData);
  24351. }
  24352. // trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed
  24353. if(triggerChange) {
  24354. evData.changedLength = changedLength;
  24355. evData.eventType = triggerChange;
  24356. handler.call(Detection, evData);
  24357. evData.eventType = triggerType;
  24358. delete evData.changedLength;
  24359. }
  24360. // trigger the END event
  24361. if(triggerType == EVENT_END) {
  24362. handler.call(Detection, evData);
  24363. // ...and we are done with the detection
  24364. // so reset everything to start each detection totally fresh
  24365. this.started = false;
  24366. }
  24367. return triggerType;
  24368. },
  24369. /**
  24370. * we have different events for each device/browser
  24371. * determine what we need and set them in the EVENT_TYPES constant
  24372. * the `onTouch` method is bind to these properties.
  24373. * @method determineEventTypes
  24374. * @return {Object} events
  24375. */
  24376. determineEventTypes: function determineEventTypes() {
  24377. var types;
  24378. if(Hammer.HAS_POINTEREVENTS) {
  24379. if(window.PointerEvent) {
  24380. types = [
  24381. 'pointerdown',
  24382. 'pointermove',
  24383. 'pointerup pointercancel lostpointercapture'
  24384. ];
  24385. } else {
  24386. types = [
  24387. 'MSPointerDown',
  24388. 'MSPointerMove',
  24389. 'MSPointerUp MSPointerCancel MSLostPointerCapture'
  24390. ];
  24391. }
  24392. } else if(Hammer.NO_MOUSEEVENTS) {
  24393. types = [
  24394. 'touchstart',
  24395. 'touchmove',
  24396. 'touchend touchcancel'
  24397. ];
  24398. } else {
  24399. types = [
  24400. 'touchstart mousedown',
  24401. 'touchmove mousemove',
  24402. 'touchend touchcancel mouseup'
  24403. ];
  24404. }
  24405. EVENT_TYPES[EVENT_START] = types[0];
  24406. EVENT_TYPES[EVENT_MOVE] = types[1];
  24407. EVENT_TYPES[EVENT_END] = types[2];
  24408. return EVENT_TYPES;
  24409. },
  24410. /**
  24411. * create touchList depending on the event
  24412. * @method getTouchList
  24413. * @param {Object} ev
  24414. * @param {String} eventType
  24415. * @return {Array} touches
  24416. */
  24417. getTouchList: function getTouchList(ev, eventType) {
  24418. // get the fake pointerEvent touchlist
  24419. if(Hammer.HAS_POINTEREVENTS) {
  24420. return PointerEvent.getTouchList();
  24421. }
  24422. // get the touchlist
  24423. if(ev.touches) {
  24424. if(eventType == EVENT_MOVE) {
  24425. return ev.touches;
  24426. }
  24427. var identifiers = [];
  24428. var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches));
  24429. var touchList = [];
  24430. Utils.each(concat, function(touch) {
  24431. if(Utils.inArray(identifiers, touch.identifier) === false) {
  24432. touchList.push(touch);
  24433. }
  24434. identifiers.push(touch.identifier);
  24435. });
  24436. return touchList;
  24437. }
  24438. // make fake touchList from mouse position
  24439. ev.identifier = 1;
  24440. return [ev];
  24441. },
  24442. /**
  24443. * collect basic event data
  24444. * @method collectEventData
  24445. * @param {HTMLElement} element
  24446. * @param {String} eventType matches `EVENT_START|MOVE|END`
  24447. * @param {Array} touches
  24448. * @param {Object} ev
  24449. * @return {Object} ev
  24450. */
  24451. collectEventData: function collectEventData(element, eventType, touches, ev) {
  24452. // find out pointerType
  24453. var pointerType = POINTER_TOUCH;
  24454. if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) {
  24455. pointerType = POINTER_MOUSE;
  24456. } else if(PointerEvent.matchType(POINTER_PEN, ev)) {
  24457. pointerType = POINTER_PEN;
  24458. }
  24459. return {
  24460. center: Utils.getCenter(touches),
  24461. timeStamp: Date.now(),
  24462. target: ev.target,
  24463. touches: touches,
  24464. eventType: eventType,
  24465. pointerType: pointerType,
  24466. srcEvent: ev,
  24467. /**
  24468. * prevent the browser default actions
  24469. * mostly used to disable scrolling of the browser
  24470. */
  24471. preventDefault: function() {
  24472. var srcEvent = this.srcEvent;
  24473. srcEvent.preventManipulation && srcEvent.preventManipulation();
  24474. srcEvent.preventDefault && srcEvent.preventDefault();
  24475. },
  24476. /**
  24477. * stop bubbling the event up to its parents
  24478. */
  24479. stopPropagation: function() {
  24480. this.srcEvent.stopPropagation();
  24481. },
  24482. /**
  24483. * immediately stop gesture detection
  24484. * might be useful after a swipe was detected
  24485. * @return {*}
  24486. */
  24487. stopDetect: function() {
  24488. return Detection.stopDetect();
  24489. }
  24490. };
  24491. }
  24492. };
  24493. /**
  24494. * @module hammer
  24495. *
  24496. * @class PointerEvent
  24497. * @static
  24498. */
  24499. var PointerEvent = Hammer.PointerEvent = {
  24500. /**
  24501. * holds all pointers, by `identifier`
  24502. * @property pointers
  24503. * @type {Object}
  24504. */
  24505. pointers: {},
  24506. /**
  24507. * get the pointers as an array
  24508. * @method getTouchList
  24509. * @return {Array} touchlist
  24510. */
  24511. getTouchList: function getTouchList() {
  24512. var touchlist = [];
  24513. // we can use forEach since pointerEvents only is in IE10
  24514. Utils.each(this.pointers, function(pointer) {
  24515. touchlist.push(pointer);
  24516. });
  24517. return touchlist;
  24518. },
  24519. /**
  24520. * update the position of a pointer
  24521. * @method updatePointer
  24522. * @param {String} eventType matches `EVENT_START|MOVE|END`
  24523. * @param {Object} pointerEvent
  24524. */
  24525. updatePointer: function updatePointer(eventType, pointerEvent) {
  24526. if(eventType == EVENT_END || (eventType != EVENT_END && pointerEvent.buttons !== 1)) {
  24527. delete this.pointers[pointerEvent.pointerId];
  24528. } else {
  24529. pointerEvent.identifier = pointerEvent.pointerId;
  24530. this.pointers[pointerEvent.pointerId] = pointerEvent;
  24531. }
  24532. },
  24533. /**
  24534. * check if ev matches pointertype
  24535. * @method matchType
  24536. * @param {String} pointerType matches `POINTER_MOUSE|TOUCH|PEN`
  24537. * @param {PointerEvent} ev
  24538. */
  24539. matchType: function matchType(pointerType, ev) {
  24540. if(!ev.pointerType) {
  24541. return false;
  24542. }
  24543. var pt = ev.pointerType,
  24544. types = {};
  24545. types[POINTER_MOUSE] = (pt === (ev.MSPOINTER_TYPE_MOUSE || POINTER_MOUSE));
  24546. types[POINTER_TOUCH] = (pt === (ev.MSPOINTER_TYPE_TOUCH || POINTER_TOUCH));
  24547. types[POINTER_PEN] = (pt === (ev.MSPOINTER_TYPE_PEN || POINTER_PEN));
  24548. return types[pointerType];
  24549. },
  24550. /**
  24551. * reset the stored pointers
  24552. * @method reset
  24553. */
  24554. reset: function resetList() {
  24555. this.pointers = {};
  24556. }
  24557. };
  24558. /**
  24559. * @module hammer
  24560. *
  24561. * @class Detection
  24562. * @static
  24563. */
  24564. var Detection = Hammer.detection = {
  24565. // contains all registred Hammer.gestures in the correct order
  24566. gestures: [],
  24567. // data of the current Hammer.gesture detection session
  24568. current: null,
  24569. // the previous Hammer.gesture session data
  24570. // is a full clone of the previous gesture.current object
  24571. previous: null,
  24572. // when this becomes true, no gestures are fired
  24573. stopped: false,
  24574. /**
  24575. * start Hammer.gesture detection
  24576. * @method startDetect
  24577. * @param {Hammer.Instance} inst
  24578. * @param {Object} eventData
  24579. */
  24580. startDetect: function startDetect(inst, eventData) {
  24581. // already busy with a Hammer.gesture detection on an element
  24582. if(this.current) {
  24583. return;
  24584. }
  24585. this.stopped = false;
  24586. // holds current session
  24587. this.current = {
  24588. inst: inst, // reference to HammerInstance we're working for
  24589. startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc
  24590. lastEvent: false, // last eventData
  24591. lastCalcEvent: false, // last eventData for calculations.
  24592. futureCalcEvent: false, // last eventData for calculations.
  24593. lastCalcData: {}, // last lastCalcData
  24594. name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  24595. };
  24596. this.detect(eventData);
  24597. },
  24598. /**
  24599. * Hammer.gesture detection
  24600. * @method detect
  24601. * @param {Object} eventData
  24602. * @return {any}
  24603. */
  24604. detect: function detect(eventData) {
  24605. if(!this.current || this.stopped) {
  24606. return;
  24607. }
  24608. // extend event data with calculations about scale, distance etc
  24609. eventData = this.extendEventData(eventData);
  24610. // hammer instance and instance options
  24611. var inst = this.current.inst,
  24612. instOptions = inst.options;
  24613. // call Hammer.gesture handlers
  24614. Utils.each(this.gestures, function triggerGesture(gesture) {
  24615. // only when the instance options have enabled this gesture
  24616. if(!this.stopped && inst.enabled && instOptions[gesture.name]) {
  24617. gesture.handler.call(gesture, eventData, inst);
  24618. }
  24619. }, this);
  24620. // store as previous event event
  24621. if(this.current) {
  24622. this.current.lastEvent = eventData;
  24623. }
  24624. if(eventData.eventType == EVENT_END) {
  24625. this.stopDetect();
  24626. }
  24627. return eventData;
  24628. },
  24629. /**
  24630. * clear the Hammer.gesture vars
  24631. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  24632. * to stop other Hammer.gestures from being fired
  24633. * @method stopDetect
  24634. */
  24635. stopDetect: function stopDetect() {
  24636. // clone current data to the store as the previous gesture
  24637. // used for the double tap gesture, since this is an other gesture detect session
  24638. this.previous = Utils.extend({}, this.current);
  24639. // reset the current
  24640. this.current = null;
  24641. this.stopped = true;
  24642. },
  24643. /**
  24644. * calculate velocity, angle and direction
  24645. * @method getVelocityData
  24646. * @param {Object} ev
  24647. * @param {Object} center
  24648. * @param {Number} deltaTime
  24649. * @param {Number} deltaX
  24650. * @param {Number} deltaY
  24651. */
  24652. getCalculatedData: function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) {
  24653. var cur = this.current,
  24654. recalc = false,
  24655. calcEv = cur.lastCalcEvent,
  24656. calcData = cur.lastCalcData;
  24657. if(calcEv && ev.timeStamp - calcEv.timeStamp > Hammer.CALCULATE_INTERVAL) {
  24658. center = calcEv.center;
  24659. deltaTime = ev.timeStamp - calcEv.timeStamp;
  24660. deltaX = ev.center.clientX - calcEv.center.clientX;
  24661. deltaY = ev.center.clientY - calcEv.center.clientY;
  24662. recalc = true;
  24663. }
  24664. if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
  24665. cur.futureCalcEvent = ev;
  24666. }
  24667. if(!cur.lastCalcEvent || recalc) {
  24668. calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY);
  24669. calcData.angle = Utils.getAngle(center, ev.center);
  24670. calcData.direction = Utils.getDirection(center, ev.center);
  24671. cur.lastCalcEvent = cur.futureCalcEvent || ev;
  24672. cur.futureCalcEvent = ev;
  24673. }
  24674. ev.velocityX = calcData.velocity.x;
  24675. ev.velocityY = calcData.velocity.y;
  24676. ev.interimAngle = calcData.angle;
  24677. ev.interimDirection = calcData.direction;
  24678. },
  24679. /**
  24680. * extend eventData for Hammer.gestures
  24681. * @method extendEventData
  24682. * @param {Object} ev
  24683. * @return {Object} ev
  24684. */
  24685. extendEventData: function extendEventData(ev) {
  24686. var cur = this.current,
  24687. startEv = cur.startEvent,
  24688. lastEv = cur.lastEvent || startEv;
  24689. // update the start touchlist to calculate the scale/rotation
  24690. if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
  24691. startEv.touches = [];
  24692. Utils.each(ev.touches, function(touch) {
  24693. startEv.touches.push({
  24694. clientX: touch.clientX,
  24695. clientY: touch.clientY
  24696. });
  24697. });
  24698. }
  24699. var deltaTime = ev.timeStamp - startEv.timeStamp,
  24700. deltaX = ev.center.clientX - startEv.center.clientX,
  24701. deltaY = ev.center.clientY - startEv.center.clientY;
  24702. this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY);
  24703. Utils.extend(ev, {
  24704. startEvent: startEv,
  24705. deltaTime: deltaTime,
  24706. deltaX: deltaX,
  24707. deltaY: deltaY,
  24708. distance: Utils.getDistance(startEv.center, ev.center),
  24709. angle: Utils.getAngle(startEv.center, ev.center),
  24710. direction: Utils.getDirection(startEv.center, ev.center),
  24711. scale: Utils.getScale(startEv.touches, ev.touches),
  24712. rotation: Utils.getRotation(startEv.touches, ev.touches)
  24713. });
  24714. return ev;
  24715. },
  24716. /**
  24717. * register new gesture
  24718. * @method register
  24719. * @param {Object} gesture object, see `gestures/` for documentation
  24720. * @return {Array} gestures
  24721. */
  24722. register: function register(gesture) {
  24723. // add an enable gesture options if there is no given
  24724. var options = gesture.defaults || {};
  24725. if(options[gesture.name] === undefined) {
  24726. options[gesture.name] = true;
  24727. }
  24728. // extend Hammer default options with the Hammer.gesture options
  24729. Utils.extend(Hammer.defaults, options, true);
  24730. // set its index
  24731. gesture.index = gesture.index || 1000;
  24732. // add Hammer.gesture to the list
  24733. this.gestures.push(gesture);
  24734. // sort the list by index
  24735. this.gestures.sort(function(a, b) {
  24736. if(a.index < b.index) {
  24737. return -1;
  24738. }
  24739. if(a.index > b.index) {
  24740. return 1;
  24741. }
  24742. return 0;
  24743. });
  24744. return this.gestures;
  24745. }
  24746. };
  24747. /**
  24748. * @module hammer
  24749. */
  24750. /**
  24751. * create new hammer instance
  24752. * all methods should return the instance itself, so it is chainable.
  24753. *
  24754. * @class Instance
  24755. * @constructor
  24756. * @param {HTMLElement} element
  24757. * @param {Object} [options={}] options are merged with `Hammer.defaults`
  24758. * @return {Hammer.Instance}
  24759. */
  24760. Hammer.Instance = function(element, options) {
  24761. var self = this;
  24762. // setup HammerJS window events and register all gestures
  24763. // this also sets up the default options
  24764. setup();
  24765. /**
  24766. * @property element
  24767. * @type {HTMLElement}
  24768. */
  24769. this.element = element;
  24770. /**
  24771. * @property enabled
  24772. * @type {Boolean}
  24773. * @protected
  24774. */
  24775. this.enabled = true;
  24776. /**
  24777. * options, merged with the defaults
  24778. * options with an _ are converted to camelCase
  24779. * @property options
  24780. * @type {Object}
  24781. */
  24782. Utils.each(options, function(value, name) {
  24783. delete options[name];
  24784. options[Utils.toCamelCase(name)] = value;
  24785. });
  24786. this.options = Utils.extend(Utils.extend({}, Hammer.defaults), options || {});
  24787. // add some css to the element to prevent the browser from doing its native behavoir
  24788. if(this.options.behavior) {
  24789. Utils.toggleBehavior(this.element, this.options.behavior, true);
  24790. }
  24791. /**
  24792. * event start handler on the element to start the detection
  24793. * @property eventStartHandler
  24794. * @type {Object}
  24795. */
  24796. this.eventStartHandler = Event.onTouch(element, EVENT_START, function(ev) {
  24797. if(self.enabled && ev.eventType == EVENT_START) {
  24798. Detection.startDetect(self, ev);
  24799. } else if(ev.eventType == EVENT_TOUCH) {
  24800. Detection.detect(ev);
  24801. }
  24802. });
  24803. /**
  24804. * keep a list of user event handlers which needs to be removed when calling 'dispose'
  24805. * @property eventHandlers
  24806. * @type {Array}
  24807. */
  24808. this.eventHandlers = [];
  24809. };
  24810. Hammer.Instance.prototype = {
  24811. /**
  24812. * bind events to the instance
  24813. * @method on
  24814. * @chainable
  24815. * @param {String} gestures multiple gestures by splitting with a space
  24816. * @param {Function} handler
  24817. * @param {Object} handler.ev event object
  24818. */
  24819. on: function onEvent(gestures, handler) {
  24820. var self = this;
  24821. Event.on(self.element, gestures, handler, function(type) {
  24822. self.eventHandlers.push({ gesture: type, handler: handler });
  24823. });
  24824. return self;
  24825. },
  24826. /**
  24827. * unbind events to the instance
  24828. * @method off
  24829. * @chainable
  24830. * @param {String} gestures
  24831. * @param {Function} handler
  24832. */
  24833. off: function offEvent(gestures, handler) {
  24834. var self = this;
  24835. Event.off(self.element, gestures, handler, function(type) {
  24836. var index = Utils.inArray({ gesture: type, handler: handler });
  24837. if(index !== false) {
  24838. self.eventHandlers.splice(index, 1);
  24839. }
  24840. });
  24841. return self;
  24842. },
  24843. /**
  24844. * trigger gesture event
  24845. * @method trigger
  24846. * @chainable
  24847. * @param {String} gesture
  24848. * @param {Object} [eventData]
  24849. */
  24850. trigger: function triggerEvent(gesture, eventData) {
  24851. // optional
  24852. if(!eventData) {
  24853. eventData = {};
  24854. }
  24855. // create DOM event
  24856. var event = Hammer.DOCUMENT.createEvent('Event');
  24857. event.initEvent(gesture, true, true);
  24858. event.gesture = eventData;
  24859. // trigger on the target if it is in the instance element,
  24860. // this is for event delegation tricks
  24861. var element = this.element;
  24862. if(Utils.hasParent(eventData.target, element)) {
  24863. element = eventData.target;
  24864. }
  24865. element.dispatchEvent(event);
  24866. return this;
  24867. },
  24868. /**
  24869. * enable of disable hammer.js detection
  24870. * @method enable
  24871. * @chainable
  24872. * @param {Boolean} state
  24873. */
  24874. enable: function enable(state) {
  24875. this.enabled = state;
  24876. return this;
  24877. },
  24878. /**
  24879. * dispose this hammer instance
  24880. * @method dispose
  24881. * @return {Null}
  24882. */
  24883. dispose: function dispose() {
  24884. var i, eh;
  24885. // undo all changes made by stop_browser_behavior
  24886. Utils.toggleBehavior(this.element, this.options.behavior, false);
  24887. // unbind all custom event handlers
  24888. for(i = -1; (eh = this.eventHandlers[++i]);) {
  24889. Utils.off(this.element, eh.gesture, eh.handler);
  24890. }
  24891. this.eventHandlers = [];
  24892. // unbind the start event listener
  24893. Event.off(this.element, EVENT_TYPES[EVENT_START], this.eventStartHandler);
  24894. return null;
  24895. }
  24896. };
  24897. /**
  24898. * @module gestures
  24899. */
  24900. /**
  24901. * Move with x fingers (default 1) around on the page.
  24902. * Preventing the default browser behavior is a good way to improve feel and working.
  24903. * ````
  24904. * hammertime.on("drag", function(ev) {
  24905. * console.log(ev);
  24906. * ev.gesture.preventDefault();
  24907. * });
  24908. * ````
  24909. *
  24910. * @class Drag
  24911. * @static
  24912. */
  24913. /**
  24914. * @event drag
  24915. * @param {Object} ev
  24916. */
  24917. /**
  24918. * @event dragstart
  24919. * @param {Object} ev
  24920. */
  24921. /**
  24922. * @event dragend
  24923. * @param {Object} ev
  24924. */
  24925. /**
  24926. * @event drapleft
  24927. * @param {Object} ev
  24928. */
  24929. /**
  24930. * @event dragright
  24931. * @param {Object} ev
  24932. */
  24933. /**
  24934. * @event dragup
  24935. * @param {Object} ev
  24936. */
  24937. /**
  24938. * @event dragdown
  24939. * @param {Object} ev
  24940. */
  24941. /**
  24942. * @param {String} name
  24943. */
  24944. (function(name) {
  24945. var triggered = false;
  24946. function dragGesture(ev, inst) {
  24947. var cur = Detection.current;
  24948. // max touches
  24949. if(inst.options.dragMaxTouches > 0 &&
  24950. ev.touches.length > inst.options.dragMaxTouches) {
  24951. return;
  24952. }
  24953. switch(ev.eventType) {
  24954. case EVENT_START:
  24955. triggered = false;
  24956. break;
  24957. case EVENT_MOVE:
  24958. // when the distance we moved is too small we skip this gesture
  24959. // or we can be already in dragging
  24960. if(ev.distance < inst.options.dragMinDistance &&
  24961. cur.name != name) {
  24962. return;
  24963. }
  24964. var startCenter = cur.startEvent.center;
  24965. // we are dragging!
  24966. if(cur.name != name) {
  24967. cur.name = name;
  24968. if(inst.options.dragDistanceCorrection && ev.distance > 0) {
  24969. // When a drag is triggered, set the event center to dragMinDistance pixels from the original event center.
  24970. // Without this correction, the dragged distance would jumpstart at dragMinDistance pixels instead of at 0.
  24971. // It might be useful to save the original start point somewhere
  24972. var factor = Math.abs(inst.options.dragMinDistance / ev.distance);
  24973. startCenter.pageX += ev.deltaX * factor;
  24974. startCenter.pageY += ev.deltaY * factor;
  24975. startCenter.clientX += ev.deltaX * factor;
  24976. startCenter.clientY += ev.deltaY * factor;
  24977. // recalculate event data using new start point
  24978. ev = Detection.extendEventData(ev);
  24979. }
  24980. }
  24981. // lock drag to axis?
  24982. if(cur.lastEvent.dragLockToAxis ||
  24983. ( inst.options.dragLockToAxis &&
  24984. inst.options.dragLockMinDistance <= ev.distance
  24985. )) {
  24986. ev.dragLockToAxis = true;
  24987. }
  24988. // keep direction on the axis that the drag gesture started on
  24989. var lastDirection = cur.lastEvent.direction;
  24990. if(ev.dragLockToAxis && lastDirection !== ev.direction) {
  24991. if(Utils.isVertical(lastDirection)) {
  24992. ev.direction = (ev.deltaY < 0) ? DIRECTION_UP : DIRECTION_DOWN;
  24993. } else {
  24994. ev.direction = (ev.deltaX < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
  24995. }
  24996. }
  24997. // first time, trigger dragstart event
  24998. if(!triggered) {
  24999. inst.trigger(name + 'start', ev);
  25000. triggered = true;
  25001. }
  25002. // trigger events
  25003. inst.trigger(name, ev);
  25004. inst.trigger(name + ev.direction, ev);
  25005. var isVertical = Utils.isVertical(ev.direction);
  25006. // block the browser events
  25007. if((inst.options.dragBlockVertical && isVertical) ||
  25008. (inst.options.dragBlockHorizontal && !isVertical)) {
  25009. ev.preventDefault();
  25010. }
  25011. break;
  25012. case EVENT_RELEASE:
  25013. if(triggered && ev.changedLength <= inst.options.dragMaxTouches) {
  25014. inst.trigger(name + 'end', ev);
  25015. triggered = false;
  25016. }
  25017. break;
  25018. case EVENT_END:
  25019. triggered = false;
  25020. break;
  25021. }
  25022. }
  25023. Hammer.gestures.Drag = {
  25024. name: name,
  25025. index: 50,
  25026. handler: dragGesture,
  25027. defaults: {
  25028. /**
  25029. * minimal movement that have to be made before the drag event gets triggered
  25030. * @property dragMinDistance
  25031. * @type {Number}
  25032. * @default 10
  25033. */
  25034. dragMinDistance: 10,
  25035. /**
  25036. * Set dragDistanceCorrection to true to make the starting point of the drag
  25037. * be calculated from where the drag was triggered, not from where the touch started.
  25038. * Useful to avoid a jerk-starting drag, which can make fine-adjustments
  25039. * through dragging difficult, and be visually unappealing.
  25040. * @property dragDistanceCorrection
  25041. * @type {Boolean}
  25042. * @default true
  25043. */
  25044. dragDistanceCorrection: true,
  25045. /**
  25046. * set 0 for unlimited, but this can conflict with transform
  25047. * @property dragMaxTouches
  25048. * @type {Number}
  25049. * @default 1
  25050. */
  25051. dragMaxTouches: 1,
  25052. /**
  25053. * prevent default browser behavior when dragging occurs
  25054. * be careful with it, it makes the element a blocking element
  25055. * when you are using the drag gesture, it is a good practice to set this true
  25056. * @property dragBlockHorizontal
  25057. * @type {Boolean}
  25058. * @default false
  25059. */
  25060. dragBlockHorizontal: false,
  25061. /**
  25062. * same as `dragBlockHorizontal`, but for vertical movement
  25063. * @property dragBlockVertical
  25064. * @type {Boolean}
  25065. * @default false
  25066. */
  25067. dragBlockVertical: false,
  25068. /**
  25069. * dragLockToAxis keeps the drag gesture on the axis that it started on,
  25070. * It disallows vertical directions if the initial direction was horizontal, and vice versa.
  25071. * @property dragLockToAxis
  25072. * @type {Boolean}
  25073. * @default false
  25074. */
  25075. dragLockToAxis: false,
  25076. /**
  25077. * drag lock only kicks in when distance > dragLockMinDistance
  25078. * This way, locking occurs only when the distance has become large enough to reliably determine the direction
  25079. * @property dragLockMinDistance
  25080. * @type {Number}
  25081. * @default 25
  25082. */
  25083. dragLockMinDistance: 25
  25084. }
  25085. };
  25086. })('drag');
  25087. /**
  25088. * @module gestures
  25089. */
  25090. /**
  25091. * trigger a simple gesture event, so you can do anything in your handler.
  25092. * only usable if you know what your doing...
  25093. *
  25094. * @class Gesture
  25095. * @static
  25096. */
  25097. /**
  25098. * @event gesture
  25099. * @param {Object} ev
  25100. */
  25101. Hammer.gestures.Gesture = {
  25102. name: 'gesture',
  25103. index: 1337,
  25104. handler: function releaseGesture(ev, inst) {
  25105. inst.trigger(this.name, ev);
  25106. }
  25107. };
  25108. /**
  25109. * @module gestures
  25110. */
  25111. /**
  25112. * Touch stays at the same place for x time
  25113. *
  25114. * @class Hold
  25115. * @static
  25116. */
  25117. /**
  25118. * @event hold
  25119. * @param {Object} ev
  25120. */
  25121. /**
  25122. * @param {String} name
  25123. */
  25124. (function(name) {
  25125. var timer;
  25126. function holdGesture(ev, inst) {
  25127. var options = inst.options,
  25128. current = Detection.current;
  25129. switch(ev.eventType) {
  25130. case EVENT_START:
  25131. clearTimeout(timer);
  25132. // set the gesture so we can check in the timeout if it still is
  25133. current.name = name;
  25134. // set timer and if after the timeout it still is hold,
  25135. // we trigger the hold event
  25136. timer = setTimeout(function() {
  25137. if(current && current.name == name) {
  25138. inst.trigger(name, ev);
  25139. }
  25140. }, options.holdTimeout);
  25141. break;
  25142. case EVENT_MOVE:
  25143. if(ev.distance > options.holdThreshold) {
  25144. clearTimeout(timer);
  25145. }
  25146. break;
  25147. case EVENT_RELEASE:
  25148. clearTimeout(timer);
  25149. break;
  25150. }
  25151. }
  25152. Hammer.gestures.Hold = {
  25153. name: name,
  25154. index: 10,
  25155. defaults: {
  25156. /**
  25157. * @property holdTimeout
  25158. * @type {Number}
  25159. * @default 500
  25160. */
  25161. holdTimeout: 500,
  25162. /**
  25163. * movement allowed while holding
  25164. * @property holdThreshold
  25165. * @type {Number}
  25166. * @default 2
  25167. */
  25168. holdThreshold: 2
  25169. },
  25170. handler: holdGesture
  25171. };
  25172. })('hold');
  25173. /**
  25174. * @module gestures
  25175. */
  25176. /**
  25177. * when a touch is being released from the page
  25178. *
  25179. * @class Release
  25180. * @static
  25181. */
  25182. /**
  25183. * @event release
  25184. * @param {Object} ev
  25185. */
  25186. Hammer.gestures.Release = {
  25187. name: 'release',
  25188. index: Infinity,
  25189. handler: function releaseGesture(ev, inst) {
  25190. if(ev.eventType == EVENT_RELEASE) {
  25191. inst.trigger(this.name, ev);
  25192. }
  25193. }
  25194. };
  25195. /**
  25196. * @module gestures
  25197. */
  25198. /**
  25199. * triggers swipe events when the end velocity is above the threshold
  25200. * for best usage, set `preventDefault` (on the drag gesture) to `true`
  25201. * ````
  25202. * hammertime.on("dragleft swipeleft", function(ev) {
  25203. * console.log(ev);
  25204. * ev.gesture.preventDefault();
  25205. * });
  25206. * ````
  25207. *
  25208. * @class Swipe
  25209. * @static
  25210. */
  25211. /**
  25212. * @event swipe
  25213. * @param {Object} ev
  25214. */
  25215. /**
  25216. * @event swipeleft
  25217. * @param {Object} ev
  25218. */
  25219. /**
  25220. * @event swiperight
  25221. * @param {Object} ev
  25222. */
  25223. /**
  25224. * @event swipeup
  25225. * @param {Object} ev
  25226. */
  25227. /**
  25228. * @event swipedown
  25229. * @param {Object} ev
  25230. */
  25231. Hammer.gestures.Swipe = {
  25232. name: 'swipe',
  25233. index: 40,
  25234. defaults: {
  25235. /**
  25236. * @property swipeMinTouches
  25237. * @type {Number}
  25238. * @default 1
  25239. */
  25240. swipeMinTouches: 1,
  25241. /**
  25242. * @property swipeMaxTouches
  25243. * @type {Number}
  25244. * @default 1
  25245. */
  25246. swipeMaxTouches: 1,
  25247. /**
  25248. * horizontal swipe velocity
  25249. * @property swipeVelocityX
  25250. * @type {Number}
  25251. * @default 0.6
  25252. */
  25253. swipeVelocityX: 0.6,
  25254. /**
  25255. * vertical swipe velocity
  25256. * @property swipeVelocityY
  25257. * @type {Number}
  25258. * @default 0.6
  25259. */
  25260. swipeVelocityY: 0.6
  25261. },
  25262. handler: function swipeGesture(ev, inst) {
  25263. if(ev.eventType == EVENT_RELEASE) {
  25264. var touches = ev.touches.length,
  25265. options = inst.options;
  25266. // max touches
  25267. if(touches < options.swipeMinTouches ||
  25268. touches > options.swipeMaxTouches) {
  25269. return;
  25270. }
  25271. // when the distance we moved is too small we skip this gesture
  25272. // or we can be already in dragging
  25273. if(ev.velocityX > options.swipeVelocityX ||
  25274. ev.velocityY > options.swipeVelocityY) {
  25275. // trigger swipe events
  25276. inst.trigger(this.name, ev);
  25277. inst.trigger(this.name + ev.direction, ev);
  25278. }
  25279. }
  25280. }
  25281. };
  25282. /**
  25283. * @module gestures
  25284. */
  25285. /**
  25286. * Single tap and a double tap on a place
  25287. *
  25288. * @class Tap
  25289. * @static
  25290. */
  25291. /**
  25292. * @event tap
  25293. * @param {Object} ev
  25294. */
  25295. /**
  25296. * @event doubletap
  25297. * @param {Object} ev
  25298. */
  25299. /**
  25300. * @param {String} name
  25301. */
  25302. (function(name) {
  25303. var hasMoved = false;
  25304. function tapGesture(ev, inst) {
  25305. var options = inst.options,
  25306. current = Detection.current,
  25307. prev = Detection.previous,
  25308. sincePrev,
  25309. didDoubleTap;
  25310. switch(ev.eventType) {
  25311. case EVENT_START:
  25312. hasMoved = false;
  25313. break;
  25314. case EVENT_MOVE:
  25315. hasMoved = hasMoved || (ev.distance > options.tapMaxDistance);
  25316. break;
  25317. case EVENT_END:
  25318. if(!Utils.inStr(ev.srcEvent.type, 'cancel') && ev.deltaTime < options.tapMaxTime && !hasMoved) {
  25319. // previous gesture, for the double tap since these are two different gesture detections
  25320. sincePrev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp;
  25321. didDoubleTap = false;
  25322. // check if double tap
  25323. if(prev && prev.name == name &&
  25324. (sincePrev && sincePrev < options.doubleTapInterval) &&
  25325. ev.distance < options.doubleTapDistance) {
  25326. inst.trigger('doubletap', ev);
  25327. didDoubleTap = true;
  25328. }
  25329. // do a single tap
  25330. if(!didDoubleTap || options.tapAlways) {
  25331. current.name = name;
  25332. inst.trigger(current.name, ev);
  25333. }
  25334. }
  25335. break;
  25336. }
  25337. }
  25338. Hammer.gestures.Tap = {
  25339. name: name,
  25340. index: 100,
  25341. handler: tapGesture,
  25342. defaults: {
  25343. /**
  25344. * max time of a tap, this is for the slow tappers
  25345. * @property tapMaxTime
  25346. * @type {Number}
  25347. * @default 250
  25348. */
  25349. tapMaxTime: 250,
  25350. /**
  25351. * max distance of movement of a tap, this is for the slow tappers
  25352. * @property tapMaxDistance
  25353. * @type {Number}
  25354. * @default 10
  25355. */
  25356. tapMaxDistance: 10,
  25357. /**
  25358. * always trigger the `tap` event, even while double-tapping
  25359. * @property tapAlways
  25360. * @type {Boolean}
  25361. * @default true
  25362. */
  25363. tapAlways: true,
  25364. /**
  25365. * max distance between two taps
  25366. * @property doubleTapDistance
  25367. * @type {Number}
  25368. * @default 20
  25369. */
  25370. doubleTapDistance: 20,
  25371. /**
  25372. * max time between two taps
  25373. * @property doubleTapInterval
  25374. * @type {Number}
  25375. * @default 300
  25376. */
  25377. doubleTapInterval: 300
  25378. }
  25379. };
  25380. })('tap');
  25381. /**
  25382. * @module gestures
  25383. */
  25384. /**
  25385. * when a touch is being touched at the page
  25386. *
  25387. * @class Touch
  25388. * @static
  25389. */
  25390. /**
  25391. * @event touch
  25392. * @param {Object} ev
  25393. */
  25394. Hammer.gestures.Touch = {
  25395. name: 'touch',
  25396. index: -Infinity,
  25397. defaults: {
  25398. /**
  25399. * call preventDefault at touchstart, and makes the element blocking by disabling the scrolling of the page,
  25400. * but it improves gestures like transforming and dragging.
  25401. * be careful with using this, it can be very annoying for users to be stuck on the page
  25402. * @property preventDefault
  25403. * @type {Boolean}
  25404. * @default false
  25405. */
  25406. preventDefault: false,
  25407. /**
  25408. * disable mouse events, so only touch (or pen!) input triggers events
  25409. * @property preventMouse
  25410. * @type {Boolean}
  25411. * @default false
  25412. */
  25413. preventMouse: false
  25414. },
  25415. handler: function touchGesture(ev, inst) {
  25416. if(inst.options.preventMouse && ev.pointerType == POINTER_MOUSE) {
  25417. ev.stopDetect();
  25418. return;
  25419. }
  25420. if(inst.options.preventDefault) {
  25421. ev.preventDefault();
  25422. }
  25423. if(ev.eventType == EVENT_TOUCH) {
  25424. inst.trigger('touch', ev);
  25425. }
  25426. }
  25427. };
  25428. /**
  25429. * @module gestures
  25430. */
  25431. /**
  25432. * User want to scale or rotate with 2 fingers
  25433. * Preventing the default browser behavior is a good way to improve feel and working. This can be done with the
  25434. * `preventDefault` option.
  25435. *
  25436. * @class Transform
  25437. * @static
  25438. */
  25439. /**
  25440. * @event transform
  25441. * @param {Object} ev
  25442. */
  25443. /**
  25444. * @event transformstart
  25445. * @param {Object} ev
  25446. */
  25447. /**
  25448. * @event transformend
  25449. * @param {Object} ev
  25450. */
  25451. /**
  25452. * @event pinchin
  25453. * @param {Object} ev
  25454. */
  25455. /**
  25456. * @event pinchout
  25457. * @param {Object} ev
  25458. */
  25459. /**
  25460. * @event rotate
  25461. * @param {Object} ev
  25462. */
  25463. /**
  25464. * @param {String} name
  25465. */
  25466. (function(name) {
  25467. var triggered = false;
  25468. function transformGesture(ev, inst) {
  25469. switch(ev.eventType) {
  25470. case EVENT_START:
  25471. triggered = false;
  25472. break;
  25473. case EVENT_MOVE:
  25474. // at least multitouch
  25475. if(ev.touches.length < 2) {
  25476. return;
  25477. }
  25478. var scaleThreshold = Math.abs(1 - ev.scale);
  25479. var rotationThreshold = Math.abs(ev.rotation);
  25480. // when the distance we moved is too small we skip this gesture
  25481. // or we can be already in dragging
  25482. if(scaleThreshold < inst.options.transformMinScale &&
  25483. rotationThreshold < inst.options.transformMinRotation) {
  25484. return;
  25485. }
  25486. // we are transforming!
  25487. Detection.current.name = name;
  25488. // first time, trigger dragstart event
  25489. if(!triggered) {
  25490. inst.trigger(name + 'start', ev);
  25491. triggered = true;
  25492. }
  25493. inst.trigger(name, ev); // basic transform event
  25494. // trigger rotate event
  25495. if(rotationThreshold > inst.options.transformMinRotation) {
  25496. inst.trigger('rotate', ev);
  25497. }
  25498. // trigger pinch event
  25499. if(scaleThreshold > inst.options.transformMinScale) {
  25500. inst.trigger('pinch', ev);
  25501. inst.trigger('pinch' + (ev.scale < 1 ? 'in' : 'out'), ev);
  25502. }
  25503. break;
  25504. case EVENT_RELEASE:
  25505. if(triggered && ev.changedLength < 2) {
  25506. inst.trigger(name + 'end', ev);
  25507. triggered = false;
  25508. }
  25509. break;
  25510. }
  25511. }
  25512. Hammer.gestures.Transform = {
  25513. name: name,
  25514. index: 45,
  25515. defaults: {
  25516. /**
  25517. * minimal scale factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  25518. * @property transformMinScale
  25519. * @type {Number}
  25520. * @default 0.01
  25521. */
  25522. transformMinScale: 0.01,
  25523. /**
  25524. * rotation in degrees
  25525. * @property transformMinRotation
  25526. * @type {Number}
  25527. * @default 1
  25528. */
  25529. transformMinRotation: 1
  25530. },
  25531. handler: transformGesture
  25532. };
  25533. })('transform');
  25534. /**
  25535. * @module hammer
  25536. */
  25537. // AMD export
  25538. if(true) {
  25539. !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
  25540. return Hammer;
  25541. }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  25542. // commonjs export
  25543. } else if(typeof module !== 'undefined' && module.exports) {
  25544. module.exports = Hammer;
  25545. // browser export
  25546. } else {
  25547. window.Hammer = Hammer;
  25548. }
  25549. })(window);
  25550. /***/ },
  25551. /* 60 */
  25552. /***/ function(module, exports, __webpack_require__) {
  25553. /**
  25554. * Creation of the ClusterMixin var.
  25555. *
  25556. * This contains all the functions the Network object can use to employ clustering
  25557. */
  25558. /**
  25559. * This is only called in the constructor of the network object
  25560. *
  25561. */
  25562. exports.startWithClustering = function() {
  25563. // cluster if the data set is big
  25564. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  25565. // updates the lables after clustering
  25566. this.updateLabels();
  25567. // this is called here because if clusterin is disabled, the start and stabilize are called in
  25568. // the setData function.
  25569. if (this.stabilize) {
  25570. this._stabilize();
  25571. }
  25572. this.start();
  25573. };
  25574. /**
  25575. * This function clusters until the initialMaxNodes has been reached
  25576. *
  25577. * @param {Number} maxNumberOfNodes
  25578. * @param {Boolean} reposition
  25579. */
  25580. exports.clusterToFit = function(maxNumberOfNodes, reposition) {
  25581. var numberOfNodes = this.nodeIndices.length;
  25582. var maxLevels = 50;
  25583. var level = 0;
  25584. // we first cluster the hubs, then we pull in the outliers, repeat
  25585. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  25586. if (level % 3 == 0) {
  25587. this.forceAggregateHubs(true);
  25588. this.normalizeClusterLevels();
  25589. }
  25590. else {
  25591. this.increaseClusterLevel(); // this also includes a cluster normalization
  25592. }
  25593. numberOfNodes = this.nodeIndices.length;
  25594. level += 1;
  25595. }
  25596. // after the clustering we reposition the nodes to reduce the initial chaos
  25597. if (level > 0 && reposition == true) {
  25598. this.repositionNodes();
  25599. }
  25600. this._updateCalculationNodes();
  25601. };
  25602. /**
  25603. * This function can be called to open up a specific cluster. It is only called by
  25604. * It will unpack the cluster back one level.
  25605. *
  25606. * @param node | Node object: cluster to open.
  25607. */
  25608. exports.openCluster = function(node) {
  25609. var isMovingBeforeClustering = this.moving;
  25610. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  25611. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  25612. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  25613. this._addSector(node);
  25614. var level = 0;
  25615. // we decluster until we reach a decent number of nodes
  25616. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  25617. this.decreaseClusterLevel();
  25618. level += 1;
  25619. }
  25620. }
  25621. else {
  25622. this._expandClusterNode(node,false,true);
  25623. // update the index list, dynamic edges and labels
  25624. this._updateNodeIndexList();
  25625. this._updateDynamicEdges();
  25626. this._updateCalculationNodes();
  25627. this.updateLabels();
  25628. }
  25629. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  25630. if (this.moving != isMovingBeforeClustering) {
  25631. this.start();
  25632. }
  25633. };
  25634. /**
  25635. * This calls the updateClustes with default arguments
  25636. */
  25637. exports.updateClustersDefault = function() {
  25638. if (this.constants.clustering.enabled == true) {
  25639. this.updateClusters(0,false,false);
  25640. }
  25641. };
  25642. /**
  25643. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  25644. * be clustered with their connected node. This can be repeated as many times as needed.
  25645. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  25646. */
  25647. exports.increaseClusterLevel = function() {
  25648. this.updateClusters(-1,false,true);
  25649. };
  25650. /**
  25651. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  25652. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  25653. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  25654. */
  25655. exports.decreaseClusterLevel = function() {
  25656. this.updateClusters(1,false,true);
  25657. };
  25658. /**
  25659. * This is the main clustering function. It clusters and declusters on zoom or forced
  25660. * This function clusters on zoom, it can be called with a predefined zoom direction
  25661. * If out, check if we can form clusters, if in, check if we can open clusters.
  25662. * This function is only called from _zoom()
  25663. *
  25664. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  25665. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  25666. * @param {Boolean} force | enabled or disable forcing
  25667. * @param {Boolean} doNotStart | if true do not call start
  25668. *
  25669. */
  25670. exports.updateClusters = function(zoomDirection,recursive,force,doNotStart) {
  25671. var isMovingBeforeClustering = this.moving;
  25672. var amountOfNodes = this.nodeIndices.length;
  25673. // on zoom out collapse the sector if the scale is at the level the sector was made
  25674. if (this.previousScale > this.scale && zoomDirection == 0) {
  25675. this._collapseSector();
  25676. }
  25677. // check if we zoom in or out
  25678. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  25679. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  25680. // outer nodes determines if it is being clustered
  25681. this._formClusters(force);
  25682. }
  25683. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  25684. if (force == true) {
  25685. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  25686. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  25687. this._openClusters(recursive,force);
  25688. }
  25689. else {
  25690. // if a cluster takes up a set percentage of the active window
  25691. this._openClustersBySize();
  25692. }
  25693. }
  25694. this._updateNodeIndexList();
  25695. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  25696. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  25697. this._aggregateHubs(force);
  25698. this._updateNodeIndexList();
  25699. }
  25700. // we now reduce chains.
  25701. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  25702. this.handleChains();
  25703. this._updateNodeIndexList();
  25704. }
  25705. this.previousScale = this.scale;
  25706. // rest of the update the index list, dynamic edges and labels
  25707. this._updateDynamicEdges();
  25708. this.updateLabels();
  25709. // if a cluster was formed, we increase the clusterSession
  25710. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  25711. this.clusterSession += 1;
  25712. // if clusters have been made, we normalize the cluster level
  25713. this.normalizeClusterLevels();
  25714. }
  25715. if (doNotStart == false || doNotStart === undefined) {
  25716. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  25717. if (this.moving != isMovingBeforeClustering) {
  25718. this.start();
  25719. }
  25720. }
  25721. this._updateCalculationNodes();
  25722. };
  25723. /**
  25724. * This function handles the chains. It is called on every updateClusters().
  25725. */
  25726. exports.handleChains = function() {
  25727. // after clustering we check how many chains there are
  25728. var chainPercentage = this._getChainFraction();
  25729. if (chainPercentage > this.constants.clustering.chainThreshold) {
  25730. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  25731. }
  25732. };
  25733. /**
  25734. * this functions starts clustering by hubs
  25735. * The minimum hub threshold is set globally
  25736. *
  25737. * @private
  25738. */
  25739. exports._aggregateHubs = function(force) {
  25740. this._getHubSize();
  25741. this._formClustersByHub(force,false);
  25742. };
  25743. /**
  25744. * This function is fired by keypress. It forces hubs to form.
  25745. *
  25746. */
  25747. exports.forceAggregateHubs = function(doNotStart) {
  25748. var isMovingBeforeClustering = this.moving;
  25749. var amountOfNodes = this.nodeIndices.length;
  25750. this._aggregateHubs(true);
  25751. // update the index list, dynamic edges and labels
  25752. this._updateNodeIndexList();
  25753. this._updateDynamicEdges();
  25754. this.updateLabels();
  25755. // if a cluster was formed, we increase the clusterSession
  25756. if (this.nodeIndices.length != amountOfNodes) {
  25757. this.clusterSession += 1;
  25758. }
  25759. if (doNotStart == false || doNotStart === undefined) {
  25760. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  25761. if (this.moving != isMovingBeforeClustering) {
  25762. this.start();
  25763. }
  25764. }
  25765. };
  25766. /**
  25767. * If a cluster takes up more than a set percentage of the screen, open the cluster
  25768. *
  25769. * @private
  25770. */
  25771. exports._openClustersBySize = function() {
  25772. for (var nodeId in this.nodes) {
  25773. if (this.nodes.hasOwnProperty(nodeId)) {
  25774. var node = this.nodes[nodeId];
  25775. if (node.inView() == true) {
  25776. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  25777. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  25778. this.openCluster(node);
  25779. }
  25780. }
  25781. }
  25782. }
  25783. };
  25784. /**
  25785. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  25786. * has to be opened based on the current zoom level.
  25787. *
  25788. * @private
  25789. */
  25790. exports._openClusters = function(recursive,force) {
  25791. for (var i = 0; i < this.nodeIndices.length; i++) {
  25792. var node = this.nodes[this.nodeIndices[i]];
  25793. this._expandClusterNode(node,recursive,force);
  25794. this._updateCalculationNodes();
  25795. }
  25796. };
  25797. /**
  25798. * This function checks if a node has to be opened. This is done by checking the zoom level.
  25799. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  25800. * This recursive behaviour is optional and can be set by the recursive argument.
  25801. *
  25802. * @param {Node} parentNode | to check for cluster and expand
  25803. * @param {Boolean} recursive | enabled or disable recursive calling
  25804. * @param {Boolean} force | enabled or disable forcing
  25805. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  25806. * @private
  25807. */
  25808. exports._expandClusterNode = function(parentNode, recursive, force, openAll) {
  25809. // first check if node is a cluster
  25810. if (parentNode.clusterSize > 1) {
  25811. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  25812. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  25813. openAll = true;
  25814. }
  25815. recursive = openAll ? true : recursive;
  25816. // if the last child has been added on a smaller scale than current scale decluster
  25817. if (parentNode.formationScale < this.scale || force == true) {
  25818. // we will check if any of the contained child nodes should be removed from the cluster
  25819. for (var containedNodeId in parentNode.containedNodes) {
  25820. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  25821. var childNode = parentNode.containedNodes[containedNodeId];
  25822. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  25823. // the largest cluster is the one that comes from outside
  25824. if (force == true) {
  25825. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  25826. || openAll) {
  25827. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  25828. }
  25829. }
  25830. else {
  25831. if (this._nodeInActiveArea(parentNode)) {
  25832. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  25833. }
  25834. }
  25835. }
  25836. }
  25837. }
  25838. }
  25839. };
  25840. /**
  25841. * ONLY CALLED FROM _expandClusterNode
  25842. *
  25843. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  25844. * the child node from the parent contained_node object and put it back into the global nodes object.
  25845. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  25846. *
  25847. * @param {Node} parentNode | the parent node
  25848. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  25849. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  25850. * With force and recursive both true, the entire cluster is unpacked
  25851. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  25852. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  25853. * @private
  25854. */
  25855. exports._expelChildFromParent = function(parentNode, containedNodeId, recursive, force, openAll) {
  25856. var childNode = parentNode.containedNodes[containedNodeId];
  25857. // if child node has been added on smaller scale than current, kick out
  25858. if (childNode.formationScale < this.scale || force == true) {
  25859. // unselect all selected items
  25860. this._unselectAll();
  25861. // put the child node back in the global nodes object
  25862. this.nodes[containedNodeId] = childNode;
  25863. // release the contained edges from this childNode back into the global edges
  25864. this._releaseContainedEdges(parentNode,childNode);
  25865. // reconnect rerouted edges to the childNode
  25866. this._connectEdgeBackToChild(parentNode,childNode);
  25867. // validate all edges in dynamicEdges
  25868. this._validateEdges(parentNode);
  25869. // undo the changes from the clustering operation on the parent node
  25870. parentNode.options.mass -= childNode.options.mass;
  25871. parentNode.clusterSize -= childNode.clusterSize;
  25872. parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*(parentNode.clusterSize-1));
  25873. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  25874. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  25875. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  25876. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  25877. // remove node from the list
  25878. delete parentNode.containedNodes[containedNodeId];
  25879. // check if there are other childs with this clusterSession in the parent.
  25880. var othersPresent = false;
  25881. for (var childNodeId in parentNode.containedNodes) {
  25882. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  25883. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  25884. othersPresent = true;
  25885. break;
  25886. }
  25887. }
  25888. }
  25889. // if there are no others, remove the cluster session from the list
  25890. if (othersPresent == false) {
  25891. parentNode.clusterSessions.pop();
  25892. }
  25893. this._repositionBezierNodes(childNode);
  25894. // this._repositionBezierNodes(parentNode);
  25895. // remove the clusterSession from the child node
  25896. childNode.clusterSession = 0;
  25897. // recalculate the size of the node on the next time the node is rendered
  25898. parentNode.clearSizeCache();
  25899. // restart the simulation to reorganise all nodes
  25900. this.moving = true;
  25901. }
  25902. // check if a further expansion step is possible if recursivity is enabled
  25903. if (recursive == true) {
  25904. this._expandClusterNode(childNode,recursive,force,openAll);
  25905. }
  25906. };
  25907. /**
  25908. * position the bezier nodes at the center of the edges
  25909. *
  25910. * @param node
  25911. * @private
  25912. */
  25913. exports._repositionBezierNodes = function(node) {
  25914. for (var i = 0; i < node.dynamicEdges.length; i++) {
  25915. node.dynamicEdges[i].positionBezierNode();
  25916. }
  25917. };
  25918. /**
  25919. * This function checks if any nodes at the end of their trees have edges below a threshold length
  25920. * This function is called only from updateClusters()
  25921. * forceLevelCollapse ignores the length of the edge and collapses one level
  25922. * This means that a node with only one edge will be clustered with its connected node
  25923. *
  25924. * @private
  25925. * @param {Boolean} force
  25926. */
  25927. exports._formClusters = function(force) {
  25928. if (force == false) {
  25929. this._formClustersByZoom();
  25930. }
  25931. else {
  25932. this._forceClustersByZoom();
  25933. }
  25934. };
  25935. /**
  25936. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  25937. *
  25938. * @private
  25939. */
  25940. exports._formClustersByZoom = function() {
  25941. var dx,dy,length,
  25942. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  25943. // check if any edges are shorter than minLength and start the clustering
  25944. // the clustering favours the node with the larger mass
  25945. for (var edgeId in this.edges) {
  25946. if (this.edges.hasOwnProperty(edgeId)) {
  25947. var edge = this.edges[edgeId];
  25948. if (edge.connected) {
  25949. if (edge.toId != edge.fromId) {
  25950. dx = (edge.to.x - edge.from.x);
  25951. dy = (edge.to.y - edge.from.y);
  25952. length = Math.sqrt(dx * dx + dy * dy);
  25953. if (length < minLength) {
  25954. // first check which node is larger
  25955. var parentNode = edge.from;
  25956. var childNode = edge.to;
  25957. if (edge.to.options.mass > edge.from.options.mass) {
  25958. parentNode = edge.to;
  25959. childNode = edge.from;
  25960. }
  25961. if (childNode.dynamicEdgesLength == 1) {
  25962. this._addToCluster(parentNode,childNode,false);
  25963. }
  25964. else if (parentNode.dynamicEdgesLength == 1) {
  25965. this._addToCluster(childNode,parentNode,false);
  25966. }
  25967. }
  25968. }
  25969. }
  25970. }
  25971. }
  25972. };
  25973. /**
  25974. * This function forces the network to cluster all nodes with only one connecting edge to their
  25975. * connected node.
  25976. *
  25977. * @private
  25978. */
  25979. exports._forceClustersByZoom = function() {
  25980. for (var nodeId in this.nodes) {
  25981. // another node could have absorbed this child.
  25982. if (this.nodes.hasOwnProperty(nodeId)) {
  25983. var childNode = this.nodes[nodeId];
  25984. // the edges can be swallowed by another decrease
  25985. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  25986. var edge = childNode.dynamicEdges[0];
  25987. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  25988. // group to the largest node
  25989. if (childNode.id != parentNode.id) {
  25990. if (parentNode.options.mass > childNode.options.mass) {
  25991. this._addToCluster(parentNode,childNode,true);
  25992. }
  25993. else {
  25994. this._addToCluster(childNode,parentNode,true);
  25995. }
  25996. }
  25997. }
  25998. }
  25999. }
  26000. };
  26001. /**
  26002. * To keep the nodes of roughly equal size we normalize the cluster levels.
  26003. * This function clusters a node to its smallest connected neighbour.
  26004. *
  26005. * @param node
  26006. * @private
  26007. */
  26008. exports._clusterToSmallestNeighbour = function(node) {
  26009. var smallestNeighbour = -1;
  26010. var smallestNeighbourNode = null;
  26011. for (var i = 0; i < node.dynamicEdges.length; i++) {
  26012. if (node.dynamicEdges[i] !== undefined) {
  26013. var neighbour = null;
  26014. if (node.dynamicEdges[i].fromId != node.id) {
  26015. neighbour = node.dynamicEdges[i].from;
  26016. }
  26017. else if (node.dynamicEdges[i].toId != node.id) {
  26018. neighbour = node.dynamicEdges[i].to;
  26019. }
  26020. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  26021. smallestNeighbour = neighbour.clusterSessions.length;
  26022. smallestNeighbourNode = neighbour;
  26023. }
  26024. }
  26025. }
  26026. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  26027. this._addToCluster(neighbour, node, true);
  26028. }
  26029. };
  26030. /**
  26031. * This function forms clusters from hubs, it loops over all nodes
  26032. *
  26033. * @param {Boolean} force | Disregard zoom level
  26034. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  26035. * @private
  26036. */
  26037. exports._formClustersByHub = function(force, onlyEqual) {
  26038. // we loop over all nodes in the list
  26039. for (var nodeId in this.nodes) {
  26040. // we check if it is still available since it can be used by the clustering in this loop
  26041. if (this.nodes.hasOwnProperty(nodeId)) {
  26042. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  26043. }
  26044. }
  26045. };
  26046. /**
  26047. * This function forms a cluster from a specific preselected hub node
  26048. *
  26049. * @param {Node} hubNode | the node we will cluster as a hub
  26050. * @param {Boolean} force | Disregard zoom level
  26051. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  26052. * @param {Number} [absorptionSizeOffset] |
  26053. * @private
  26054. */
  26055. exports._formClusterFromHub = function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  26056. if (absorptionSizeOffset === undefined) {
  26057. absorptionSizeOffset = 0;
  26058. }
  26059. // we decide if the node is a hub
  26060. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  26061. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  26062. // initialize variables
  26063. var dx,dy,length;
  26064. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  26065. var allowCluster = false;
  26066. // we create a list of edges because the dynamicEdges change over the course of this loop
  26067. var edgesIdarray = [];
  26068. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  26069. for (var j = 0; j < amountOfInitialEdges; j++) {
  26070. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  26071. }
  26072. // if the hub clustering is not forces, we check if one of the edges connected
  26073. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  26074. if (force == false) {
  26075. allowCluster = false;
  26076. for (j = 0; j < amountOfInitialEdges; j++) {
  26077. var edge = this.edges[edgesIdarray[j]];
  26078. if (edge !== undefined) {
  26079. if (edge.connected) {
  26080. if (edge.toId != edge.fromId) {
  26081. dx = (edge.to.x - edge.from.x);
  26082. dy = (edge.to.y - edge.from.y);
  26083. length = Math.sqrt(dx * dx + dy * dy);
  26084. if (length < minLength) {
  26085. allowCluster = true;
  26086. break;
  26087. }
  26088. }
  26089. }
  26090. }
  26091. }
  26092. }
  26093. // start the clustering if allowed
  26094. if ((!force && allowCluster) || force) {
  26095. // we loop over all edges INITIALLY connected to this hub
  26096. for (j = 0; j < amountOfInitialEdges; j++) {
  26097. edge = this.edges[edgesIdarray[j]];
  26098. // the edge can be clustered by this function in a previous loop
  26099. if (edge !== undefined) {
  26100. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  26101. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  26102. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  26103. (childNode.id != hubNode.id)) {
  26104. this._addToCluster(hubNode,childNode,force);
  26105. }
  26106. }
  26107. }
  26108. }
  26109. }
  26110. };
  26111. /**
  26112. * This function adds the child node to the parent node, creating a cluster if it is not already.
  26113. *
  26114. * @param {Node} parentNode | this is the node that will house the child node
  26115. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  26116. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  26117. * @private
  26118. */
  26119. exports._addToCluster = function(parentNode, childNode, force) {
  26120. // join child node in the parent node
  26121. parentNode.containedNodes[childNode.id] = childNode;
  26122. // manage all the edges connected to the child and parent nodes
  26123. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  26124. var edge = childNode.dynamicEdges[i];
  26125. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  26126. this._addToContainedEdges(parentNode,childNode,edge);
  26127. }
  26128. else {
  26129. this._connectEdgeToCluster(parentNode,childNode,edge);
  26130. }
  26131. }
  26132. // a contained node has no dynamic edges.
  26133. childNode.dynamicEdges = [];
  26134. // remove circular edges from clusters
  26135. this._containCircularEdgesFromNode(parentNode,childNode);
  26136. // remove the childNode from the global nodes object
  26137. delete this.nodes[childNode.id];
  26138. // update the properties of the child and parent
  26139. var massBefore = parentNode.options.mass;
  26140. childNode.clusterSession = this.clusterSession;
  26141. parentNode.options.mass += childNode.options.mass;
  26142. parentNode.clusterSize += childNode.clusterSize;
  26143. parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  26144. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  26145. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  26146. parentNode.clusterSessions.push(this.clusterSession);
  26147. }
  26148. // forced clusters only open from screen size and double tap
  26149. if (force == true) {
  26150. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  26151. parentNode.formationScale = 0;
  26152. }
  26153. else {
  26154. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  26155. }
  26156. // recalculate the size of the node on the next time the node is rendered
  26157. parentNode.clearSizeCache();
  26158. // set the pop-out scale for the childnode
  26159. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  26160. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  26161. childNode.clearVelocity();
  26162. // the mass has altered, preservation of energy dictates the velocity to be updated
  26163. parentNode.updateVelocity(massBefore);
  26164. // restart the simulation to reorganise all nodes
  26165. this.moving = true;
  26166. };
  26167. /**
  26168. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  26169. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  26170. * It has to be called if a level is collapsed. It is called by _formClusters().
  26171. * @private
  26172. */
  26173. exports._updateDynamicEdges = function() {
  26174. for (var i = 0; i < this.nodeIndices.length; i++) {
  26175. var node = this.nodes[this.nodeIndices[i]];
  26176. node.dynamicEdgesLength = node.dynamicEdges.length;
  26177. // this corrects for multiple edges pointing at the same other node
  26178. var correction = 0;
  26179. if (node.dynamicEdgesLength > 1) {
  26180. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  26181. var edgeToId = node.dynamicEdges[j].toId;
  26182. var edgeFromId = node.dynamicEdges[j].fromId;
  26183. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  26184. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  26185. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  26186. correction += 1;
  26187. }
  26188. }
  26189. }
  26190. }
  26191. node.dynamicEdgesLength -= correction;
  26192. }
  26193. };
  26194. /**
  26195. * This adds an edge from the childNode to the contained edges of the parent node
  26196. *
  26197. * @param parentNode | Node object
  26198. * @param childNode | Node object
  26199. * @param edge | Edge object
  26200. * @private
  26201. */
  26202. exports._addToContainedEdges = function(parentNode, childNode, edge) {
  26203. // create an array object if it does not yet exist for this childNode
  26204. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  26205. parentNode.containedEdges[childNode.id] = []
  26206. }
  26207. // add this edge to the list
  26208. parentNode.containedEdges[childNode.id].push(edge);
  26209. // remove the edge from the global edges object
  26210. delete this.edges[edge.id];
  26211. // remove the edge from the parent object
  26212. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  26213. if (parentNode.dynamicEdges[i].id == edge.id) {
  26214. parentNode.dynamicEdges.splice(i,1);
  26215. break;
  26216. }
  26217. }
  26218. };
  26219. /**
  26220. * This function connects an edge that was connected to a child node to the parent node.
  26221. * It keeps track of which nodes it has been connected to with the originalId array.
  26222. *
  26223. * @param {Node} parentNode | Node object
  26224. * @param {Node} childNode | Node object
  26225. * @param {Edge} edge | Edge object
  26226. * @private
  26227. */
  26228. exports._connectEdgeToCluster = function(parentNode, childNode, edge) {
  26229. // handle circular edges
  26230. if (edge.toId == edge.fromId) {
  26231. this._addToContainedEdges(parentNode, childNode, edge);
  26232. }
  26233. else {
  26234. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  26235. edge.originalToId.push(childNode.id);
  26236. edge.to = parentNode;
  26237. edge.toId = parentNode.id;
  26238. }
  26239. else { // edge connected to other node with the "from" side
  26240. edge.originalFromId.push(childNode.id);
  26241. edge.from = parentNode;
  26242. edge.fromId = parentNode.id;
  26243. }
  26244. this._addToReroutedEdges(parentNode,childNode,edge);
  26245. }
  26246. };
  26247. /**
  26248. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  26249. * these edges inside of the cluster.
  26250. *
  26251. * @param parentNode
  26252. * @param childNode
  26253. * @private
  26254. */
  26255. exports._containCircularEdgesFromNode = function(parentNode, childNode) {
  26256. // manage all the edges connected to the child and parent nodes
  26257. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  26258. var edge = parentNode.dynamicEdges[i];
  26259. // handle circular edges
  26260. if (edge.toId == edge.fromId) {
  26261. this._addToContainedEdges(parentNode, childNode, edge);
  26262. }
  26263. }
  26264. };
  26265. /**
  26266. * This adds an edge from the childNode to the rerouted edges of the parent node
  26267. *
  26268. * @param parentNode | Node object
  26269. * @param childNode | Node object
  26270. * @param edge | Edge object
  26271. * @private
  26272. */
  26273. exports._addToReroutedEdges = function(parentNode, childNode, edge) {
  26274. // create an array object if it does not yet exist for this childNode
  26275. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  26276. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  26277. parentNode.reroutedEdges[childNode.id] = [];
  26278. }
  26279. parentNode.reroutedEdges[childNode.id].push(edge);
  26280. // this edge becomes part of the dynamicEdges of the cluster node
  26281. parentNode.dynamicEdges.push(edge);
  26282. };
  26283. /**
  26284. * This function connects an edge that was connected to a cluster node back to the child node.
  26285. *
  26286. * @param parentNode | Node object
  26287. * @param childNode | Node object
  26288. * @private
  26289. */
  26290. exports._connectEdgeBackToChild = function(parentNode, childNode) {
  26291. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  26292. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  26293. var edge = parentNode.reroutedEdges[childNode.id][i];
  26294. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  26295. edge.originalFromId.pop();
  26296. edge.fromId = childNode.id;
  26297. edge.from = childNode;
  26298. }
  26299. else {
  26300. edge.originalToId.pop();
  26301. edge.toId = childNode.id;
  26302. edge.to = childNode;
  26303. }
  26304. // append this edge to the list of edges connecting to the childnode
  26305. childNode.dynamicEdges.push(edge);
  26306. // remove the edge from the parent object
  26307. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  26308. if (parentNode.dynamicEdges[j].id == edge.id) {
  26309. parentNode.dynamicEdges.splice(j,1);
  26310. break;
  26311. }
  26312. }
  26313. }
  26314. // remove the entry from the rerouted edges
  26315. delete parentNode.reroutedEdges[childNode.id];
  26316. }
  26317. };
  26318. /**
  26319. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  26320. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  26321. * parentNode
  26322. *
  26323. * @param parentNode | Node object
  26324. * @private
  26325. */
  26326. exports._validateEdges = function(parentNode) {
  26327. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  26328. var edge = parentNode.dynamicEdges[i];
  26329. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  26330. parentNode.dynamicEdges.splice(i,1);
  26331. }
  26332. }
  26333. };
  26334. /**
  26335. * This function released the contained edges back into the global domain and puts them back into the
  26336. * dynamic edges of both parent and child.
  26337. *
  26338. * @param {Node} parentNode |
  26339. * @param {Node} childNode |
  26340. * @private
  26341. */
  26342. exports._releaseContainedEdges = function(parentNode, childNode) {
  26343. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  26344. var edge = parentNode.containedEdges[childNode.id][i];
  26345. // put the edge back in the global edges object
  26346. this.edges[edge.id] = edge;
  26347. // put the edge back in the dynamic edges of the child and parent
  26348. childNode.dynamicEdges.push(edge);
  26349. parentNode.dynamicEdges.push(edge);
  26350. }
  26351. // remove the entry from the contained edges
  26352. delete parentNode.containedEdges[childNode.id];
  26353. };
  26354. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  26355. /**
  26356. * This updates the node labels for all nodes (for debugging purposes)
  26357. */
  26358. exports.updateLabels = function() {
  26359. var nodeId;
  26360. // update node labels
  26361. for (nodeId in this.nodes) {
  26362. if (this.nodes.hasOwnProperty(nodeId)) {
  26363. var node = this.nodes[nodeId];
  26364. if (node.clusterSize > 1) {
  26365. node.label = "[".concat(String(node.clusterSize),"]");
  26366. }
  26367. }
  26368. }
  26369. // update node labels
  26370. for (nodeId in this.nodes) {
  26371. if (this.nodes.hasOwnProperty(nodeId)) {
  26372. node = this.nodes[nodeId];
  26373. if (node.clusterSize == 1) {
  26374. if (node.originalLabel !== undefined) {
  26375. node.label = node.originalLabel;
  26376. }
  26377. else {
  26378. node.label = String(node.id);
  26379. }
  26380. }
  26381. }
  26382. }
  26383. // /* Debug Override */
  26384. // for (nodeId in this.nodes) {
  26385. // if (this.nodes.hasOwnProperty(nodeId)) {
  26386. // node = this.nodes[nodeId];
  26387. // node.label = String(node.level);
  26388. // }
  26389. // }
  26390. };
  26391. /**
  26392. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  26393. * if the rest of the nodes are already a few cluster levels in.
  26394. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  26395. * clustered enough to the clusterToSmallestNeighbours function.
  26396. */
  26397. exports.normalizeClusterLevels = function() {
  26398. var maxLevel = 0;
  26399. var minLevel = 1e9;
  26400. var clusterLevel = 0;
  26401. var nodeId;
  26402. // we loop over all nodes in the list
  26403. for (nodeId in this.nodes) {
  26404. if (this.nodes.hasOwnProperty(nodeId)) {
  26405. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  26406. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  26407. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  26408. }
  26409. }
  26410. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  26411. var amountOfNodes = this.nodeIndices.length;
  26412. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  26413. // we loop over all nodes in the list
  26414. for (nodeId in this.nodes) {
  26415. if (this.nodes.hasOwnProperty(nodeId)) {
  26416. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  26417. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  26418. }
  26419. }
  26420. }
  26421. this._updateNodeIndexList();
  26422. this._updateDynamicEdges();
  26423. // if a cluster was formed, we increase the clusterSession
  26424. if (this.nodeIndices.length != amountOfNodes) {
  26425. this.clusterSession += 1;
  26426. }
  26427. }
  26428. };
  26429. /**
  26430. * This function determines if the cluster we want to decluster is in the active area
  26431. * this means around the zoom center
  26432. *
  26433. * @param {Node} node
  26434. * @returns {boolean}
  26435. * @private
  26436. */
  26437. exports._nodeInActiveArea = function(node) {
  26438. return (
  26439. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  26440. &&
  26441. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  26442. )
  26443. };
  26444. /**
  26445. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  26446. * It puts large clusters away from the center and randomizes the order.
  26447. *
  26448. */
  26449. exports.repositionNodes = function() {
  26450. for (var i = 0; i < this.nodeIndices.length; i++) {
  26451. var node = this.nodes[this.nodeIndices[i]];
  26452. if ((node.xFixed == false || node.yFixed == false)) {
  26453. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.options.mass);
  26454. var angle = 2 * Math.PI * Math.random();
  26455. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  26456. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  26457. this._repositionBezierNodes(node);
  26458. }
  26459. }
  26460. };
  26461. /**
  26462. * We determine how many connections denote an important hub.
  26463. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  26464. *
  26465. * @private
  26466. */
  26467. exports._getHubSize = function() {
  26468. var average = 0;
  26469. var averageSquared = 0;
  26470. var hubCounter = 0;
  26471. var largestHub = 0;
  26472. for (var i = 0; i < this.nodeIndices.length; i++) {
  26473. var node = this.nodes[this.nodeIndices[i]];
  26474. if (node.dynamicEdgesLength > largestHub) {
  26475. largestHub = node.dynamicEdgesLength;
  26476. }
  26477. average += node.dynamicEdgesLength;
  26478. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  26479. hubCounter += 1;
  26480. }
  26481. average = average / hubCounter;
  26482. averageSquared = averageSquared / hubCounter;
  26483. var variance = averageSquared - Math.pow(average,2);
  26484. var standardDeviation = Math.sqrt(variance);
  26485. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  26486. // always have at least one to cluster
  26487. if (this.hubThreshold > largestHub) {
  26488. this.hubThreshold = largestHub;
  26489. }
  26490. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  26491. // console.log("hubThreshold:",this.hubThreshold);
  26492. };
  26493. /**
  26494. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  26495. * with this amount we can cluster specifically on these chains.
  26496. *
  26497. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  26498. * @private
  26499. */
  26500. exports._reduceAmountOfChains = function(fraction) {
  26501. this.hubThreshold = 2;
  26502. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  26503. for (var nodeId in this.nodes) {
  26504. if (this.nodes.hasOwnProperty(nodeId)) {
  26505. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  26506. if (reduceAmount > 0) {
  26507. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  26508. reduceAmount -= 1;
  26509. }
  26510. }
  26511. }
  26512. }
  26513. };
  26514. /**
  26515. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  26516. * with this amount we can cluster specifically on these chains.
  26517. *
  26518. * @private
  26519. */
  26520. exports._getChainFraction = function() {
  26521. var chains = 0;
  26522. var total = 0;
  26523. for (var nodeId in this.nodes) {
  26524. if (this.nodes.hasOwnProperty(nodeId)) {
  26525. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  26526. chains += 1;
  26527. }
  26528. total += 1;
  26529. }
  26530. }
  26531. return chains/total;
  26532. };
  26533. /***/ },
  26534. /* 61 */
  26535. /***/ function(module, exports, __webpack_require__) {
  26536. var util = __webpack_require__(1);
  26537. var Node = __webpack_require__(40);
  26538. /**
  26539. * Creation of the SectorMixin var.
  26540. *
  26541. * This contains all the functions the Network object can use to employ the sector system.
  26542. * The sector system is always used by Network, though the benefits only apply to the use of clustering.
  26543. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  26544. */
  26545. /**
  26546. * This function is only called by the setData function of the Network object.
  26547. * This loads the global references into the active sector. This initializes the sector.
  26548. *
  26549. * @private
  26550. */
  26551. exports._putDataInSector = function() {
  26552. this.sectors["active"][this._sector()].nodes = this.nodes;
  26553. this.sectors["active"][this._sector()].edges = this.edges;
  26554. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  26555. };
  26556. /**
  26557. * /**
  26558. * This function sets the global references to nodes, edges and nodeIndices back to
  26559. * those of the supplied (active) sector. If a type is defined, do the specific type
  26560. *
  26561. * @param {String} sectorId
  26562. * @param {String} [sectorType] | "active" or "frozen"
  26563. * @private
  26564. */
  26565. exports._switchToSector = function(sectorId, sectorType) {
  26566. if (sectorType === undefined || sectorType == "active") {
  26567. this._switchToActiveSector(sectorId);
  26568. }
  26569. else {
  26570. this._switchToFrozenSector(sectorId);
  26571. }
  26572. };
  26573. /**
  26574. * This function sets the global references to nodes, edges and nodeIndices back to
  26575. * those of the supplied active sector.
  26576. *
  26577. * @param sectorId
  26578. * @private
  26579. */
  26580. exports._switchToActiveSector = function(sectorId) {
  26581. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  26582. this.nodes = this.sectors["active"][sectorId]["nodes"];
  26583. this.edges = this.sectors["active"][sectorId]["edges"];
  26584. };
  26585. /**
  26586. * This function sets the global references to nodes, edges and nodeIndices back to
  26587. * those of the supplied active sector.
  26588. *
  26589. * @private
  26590. */
  26591. exports._switchToSupportSector = function() {
  26592. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  26593. this.nodes = this.sectors["support"]["nodes"];
  26594. this.edges = this.sectors["support"]["edges"];
  26595. };
  26596. /**
  26597. * This function sets the global references to nodes, edges and nodeIndices back to
  26598. * those of the supplied frozen sector.
  26599. *
  26600. * @param sectorId
  26601. * @private
  26602. */
  26603. exports._switchToFrozenSector = function(sectorId) {
  26604. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  26605. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  26606. this.edges = this.sectors["frozen"][sectorId]["edges"];
  26607. };
  26608. /**
  26609. * This function sets the global references to nodes, edges and nodeIndices back to
  26610. * those of the currently active sector.
  26611. *
  26612. * @private
  26613. */
  26614. exports._loadLatestSector = function() {
  26615. this._switchToSector(this._sector());
  26616. };
  26617. /**
  26618. * This function returns the currently active sector Id
  26619. *
  26620. * @returns {String}
  26621. * @private
  26622. */
  26623. exports._sector = function() {
  26624. return this.activeSector[this.activeSector.length-1];
  26625. };
  26626. /**
  26627. * This function returns the previously active sector Id
  26628. *
  26629. * @returns {String}
  26630. * @private
  26631. */
  26632. exports._previousSector = function() {
  26633. if (this.activeSector.length > 1) {
  26634. return this.activeSector[this.activeSector.length-2];
  26635. }
  26636. else {
  26637. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  26638. }
  26639. };
  26640. /**
  26641. * We add the active sector at the end of the this.activeSector array
  26642. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  26643. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  26644. *
  26645. * @param newId
  26646. * @private
  26647. */
  26648. exports._setActiveSector = function(newId) {
  26649. this.activeSector.push(newId);
  26650. };
  26651. /**
  26652. * We remove the currently active sector id from the active sector stack. This happens when
  26653. * we reactivate the previously active sector
  26654. *
  26655. * @private
  26656. */
  26657. exports._forgetLastSector = function() {
  26658. this.activeSector.pop();
  26659. };
  26660. /**
  26661. * This function creates a new active sector with the supplied newId. This newId
  26662. * is the expanding node id.
  26663. *
  26664. * @param {String} newId | Id of the new active sector
  26665. * @private
  26666. */
  26667. exports._createNewSector = function(newId) {
  26668. // create the new sector
  26669. this.sectors["active"][newId] = {"nodes":{},
  26670. "edges":{},
  26671. "nodeIndices":[],
  26672. "formationScale": this.scale,
  26673. "drawingNode": undefined};
  26674. // create the new sector render node. This gives visual feedback that you are in a new sector.
  26675. this.sectors["active"][newId]['drawingNode'] = new Node(
  26676. {id:newId,
  26677. color: {
  26678. background: "#eaefef",
  26679. border: "495c5e"
  26680. }
  26681. },{},{},this.constants);
  26682. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  26683. };
  26684. /**
  26685. * This function removes the currently active sector. This is called when we create a new
  26686. * active sector.
  26687. *
  26688. * @param {String} sectorId | Id of the active sector that will be removed
  26689. * @private
  26690. */
  26691. exports._deleteActiveSector = function(sectorId) {
  26692. delete this.sectors["active"][sectorId];
  26693. };
  26694. /**
  26695. * This function removes the currently active sector. This is called when we reactivate
  26696. * the previously active sector.
  26697. *
  26698. * @param {String} sectorId | Id of the active sector that will be removed
  26699. * @private
  26700. */
  26701. exports._deleteFrozenSector = function(sectorId) {
  26702. delete this.sectors["frozen"][sectorId];
  26703. };
  26704. /**
  26705. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  26706. * We copy the references, then delete the active entree.
  26707. *
  26708. * @param sectorId
  26709. * @private
  26710. */
  26711. exports._freezeSector = function(sectorId) {
  26712. // we move the set references from the active to the frozen stack.
  26713. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  26714. // we have moved the sector data into the frozen set, we now remove it from the active set
  26715. this._deleteActiveSector(sectorId);
  26716. };
  26717. /**
  26718. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  26719. * object to the "active" object.
  26720. *
  26721. * @param sectorId
  26722. * @private
  26723. */
  26724. exports._activateSector = function(sectorId) {
  26725. // we move the set references from the frozen to the active stack.
  26726. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  26727. // we have moved the sector data into the active set, we now remove it from the frozen stack
  26728. this._deleteFrozenSector(sectorId);
  26729. };
  26730. /**
  26731. * This function merges the data from the currently active sector with a frozen sector. This is used
  26732. * in the process of reverting back to the previously active sector.
  26733. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  26734. * upon the creation of a new active sector.
  26735. *
  26736. * @param sectorId
  26737. * @private
  26738. */
  26739. exports._mergeThisWithFrozen = function(sectorId) {
  26740. // copy all nodes
  26741. for (var nodeId in this.nodes) {
  26742. if (this.nodes.hasOwnProperty(nodeId)) {
  26743. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  26744. }
  26745. }
  26746. // copy all edges (if not fully clustered, else there are no edges)
  26747. for (var edgeId in this.edges) {
  26748. if (this.edges.hasOwnProperty(edgeId)) {
  26749. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  26750. }
  26751. }
  26752. // merge the nodeIndices
  26753. for (var i = 0; i < this.nodeIndices.length; i++) {
  26754. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  26755. }
  26756. };
  26757. /**
  26758. * This clusters the sector to one cluster. It was a single cluster before this process started so
  26759. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  26760. *
  26761. * @private
  26762. */
  26763. exports._collapseThisToSingleCluster = function() {
  26764. this.clusterToFit(1,false);
  26765. };
  26766. /**
  26767. * We create a new active sector from the node that we want to open.
  26768. *
  26769. * @param node
  26770. * @private
  26771. */
  26772. exports._addSector = function(node) {
  26773. // this is the currently active sector
  26774. var sector = this._sector();
  26775. // // this should allow me to select nodes from a frozen set.
  26776. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  26777. // console.log("the node is part of the active sector");
  26778. // }
  26779. // else {
  26780. // console.log("I dont know what the fuck happened!!");
  26781. // }
  26782. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  26783. delete this.nodes[node.id];
  26784. var unqiueIdentifier = util.randomUUID();
  26785. // we fully freeze the currently active sector
  26786. this._freezeSector(sector);
  26787. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  26788. this._createNewSector(unqiueIdentifier);
  26789. // we add the active sector to the sectors array to be able to revert these steps later on
  26790. this._setActiveSector(unqiueIdentifier);
  26791. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  26792. this._switchToSector(this._sector());
  26793. // finally we add the node we removed from our previous active sector to the new active sector
  26794. this.nodes[node.id] = node;
  26795. };
  26796. /**
  26797. * We close the sector that is currently open and revert back to the one before.
  26798. * If the active sector is the "default" sector, nothing happens.
  26799. *
  26800. * @private
  26801. */
  26802. exports._collapseSector = function() {
  26803. // the currently active sector
  26804. var sector = this._sector();
  26805. // we cannot collapse the default sector
  26806. if (sector != "default") {
  26807. if ((this.nodeIndices.length == 1) ||
  26808. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  26809. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  26810. var previousSector = this._previousSector();
  26811. // we collapse the sector back to a single cluster
  26812. this._collapseThisToSingleCluster();
  26813. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  26814. // This previous sector is the one we will reactivate
  26815. this._mergeThisWithFrozen(previousSector);
  26816. // the previously active (frozen) sector now has all the data from the currently active sector.
  26817. // we can now delete the active sector.
  26818. this._deleteActiveSector(sector);
  26819. // we activate the previously active (and currently frozen) sector.
  26820. this._activateSector(previousSector);
  26821. // we load the references from the newly active sector into the global references
  26822. this._switchToSector(previousSector);
  26823. // we forget the previously active sector because we reverted to the one before
  26824. this._forgetLastSector();
  26825. // finally, we update the node index list.
  26826. this._updateNodeIndexList();
  26827. // we refresh the list with calulation nodes and calculation node indices.
  26828. this._updateCalculationNodes();
  26829. }
  26830. }
  26831. };
  26832. /**
  26833. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  26834. *
  26835. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  26836. * | we dont pass the function itself because then the "this" is the window object
  26837. * | instead of the Network object
  26838. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  26839. * @private
  26840. */
  26841. exports._doInAllActiveSectors = function(runFunction,argument) {
  26842. var returnValues = [];
  26843. if (argument === undefined) {
  26844. for (var sector in this.sectors["active"]) {
  26845. if (this.sectors["active"].hasOwnProperty(sector)) {
  26846. // switch the global references to those of this sector
  26847. this._switchToActiveSector(sector);
  26848. returnValues.push( this[runFunction]() );
  26849. }
  26850. }
  26851. }
  26852. else {
  26853. for (var sector in this.sectors["active"]) {
  26854. if (this.sectors["active"].hasOwnProperty(sector)) {
  26855. // switch the global references to those of this sector
  26856. this._switchToActiveSector(sector);
  26857. var args = Array.prototype.splice.call(arguments, 1);
  26858. if (args.length > 1) {
  26859. returnValues.push( this[runFunction](args[0],args[1]) );
  26860. }
  26861. else {
  26862. returnValues.push( this[runFunction](argument) );
  26863. }
  26864. }
  26865. }
  26866. }
  26867. // we revert the global references back to our active sector
  26868. this._loadLatestSector();
  26869. return returnValues;
  26870. };
  26871. /**
  26872. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  26873. *
  26874. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  26875. * | we dont pass the function itself because then the "this" is the window object
  26876. * | instead of the Network object
  26877. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  26878. * @private
  26879. */
  26880. exports._doInSupportSector = function(runFunction,argument) {
  26881. var returnValues = false;
  26882. if (argument === undefined) {
  26883. this._switchToSupportSector();
  26884. returnValues = this[runFunction]();
  26885. }
  26886. else {
  26887. this._switchToSupportSector();
  26888. var args = Array.prototype.splice.call(arguments, 1);
  26889. if (args.length > 1) {
  26890. returnValues = this[runFunction](args[0],args[1]);
  26891. }
  26892. else {
  26893. returnValues = this[runFunction](argument);
  26894. }
  26895. }
  26896. // we revert the global references back to our active sector
  26897. this._loadLatestSector();
  26898. return returnValues;
  26899. };
  26900. /**
  26901. * This runs a function in all frozen sectors. This is used in the _redraw().
  26902. *
  26903. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  26904. * | we don't pass the function itself because then the "this" is the window object
  26905. * | instead of the Network object
  26906. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  26907. * @private
  26908. */
  26909. exports._doInAllFrozenSectors = function(runFunction,argument) {
  26910. if (argument === undefined) {
  26911. for (var sector in this.sectors["frozen"]) {
  26912. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  26913. // switch the global references to those of this sector
  26914. this._switchToFrozenSector(sector);
  26915. this[runFunction]();
  26916. }
  26917. }
  26918. }
  26919. else {
  26920. for (var sector in this.sectors["frozen"]) {
  26921. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  26922. // switch the global references to those of this sector
  26923. this._switchToFrozenSector(sector);
  26924. var args = Array.prototype.splice.call(arguments, 1);
  26925. if (args.length > 1) {
  26926. this[runFunction](args[0],args[1]);
  26927. }
  26928. else {
  26929. this[runFunction](argument);
  26930. }
  26931. }
  26932. }
  26933. }
  26934. this._loadLatestSector();
  26935. };
  26936. /**
  26937. * This runs a function in all sectors. This is used in the _redraw().
  26938. *
  26939. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  26940. * | we don't pass the function itself because then the "this" is the window object
  26941. * | instead of the Network object
  26942. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  26943. * @private
  26944. */
  26945. exports._doInAllSectors = function(runFunction,argument) {
  26946. var args = Array.prototype.splice.call(arguments, 1);
  26947. if (argument === undefined) {
  26948. this._doInAllActiveSectors(runFunction);
  26949. this._doInAllFrozenSectors(runFunction);
  26950. }
  26951. else {
  26952. if (args.length > 1) {
  26953. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  26954. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  26955. }
  26956. else {
  26957. this._doInAllActiveSectors(runFunction,argument);
  26958. this._doInAllFrozenSectors(runFunction,argument);
  26959. }
  26960. }
  26961. };
  26962. /**
  26963. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  26964. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  26965. *
  26966. * @private
  26967. */
  26968. exports._clearNodeIndexList = function() {
  26969. var sector = this._sector();
  26970. this.sectors["active"][sector]["nodeIndices"] = [];
  26971. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  26972. };
  26973. /**
  26974. * Draw the encompassing sector node
  26975. *
  26976. * @param ctx
  26977. * @param sectorType
  26978. * @private
  26979. */
  26980. exports._drawSectorNodes = function(ctx,sectorType) {
  26981. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  26982. for (var sector in this.sectors[sectorType]) {
  26983. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  26984. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  26985. this._switchToSector(sector,sectorType);
  26986. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  26987. for (var nodeId in this.nodes) {
  26988. if (this.nodes.hasOwnProperty(nodeId)) {
  26989. node = this.nodes[nodeId];
  26990. node.resize(ctx);
  26991. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  26992. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  26993. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  26994. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  26995. }
  26996. }
  26997. node = this.sectors[sectorType][sector]["drawingNode"];
  26998. node.x = 0.5 * (maxX + minX);
  26999. node.y = 0.5 * (maxY + minY);
  27000. node.width = 2 * (node.x - minX);
  27001. node.height = 2 * (node.y - minY);
  27002. node.options.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  27003. node.setScale(this.scale);
  27004. node._drawCircle(ctx);
  27005. }
  27006. }
  27007. }
  27008. };
  27009. exports._drawAllSectorNodes = function(ctx) {
  27010. this._drawSectorNodes(ctx,"frozen");
  27011. this._drawSectorNodes(ctx,"active");
  27012. this._loadLatestSector();
  27013. };
  27014. /***/ },
  27015. /* 62 */
  27016. /***/ function(module, exports, __webpack_require__) {
  27017. var Node = __webpack_require__(40);
  27018. /**
  27019. * This function can be called from the _doInAllSectors function
  27020. *
  27021. * @param object
  27022. * @param overlappingNodes
  27023. * @private
  27024. */
  27025. exports._getNodesOverlappingWith = function(object, overlappingNodes) {
  27026. var nodes = this.nodes;
  27027. for (var nodeId in nodes) {
  27028. if (nodes.hasOwnProperty(nodeId)) {
  27029. if (nodes[nodeId].isOverlappingWith(object)) {
  27030. overlappingNodes.push(nodeId);
  27031. }
  27032. }
  27033. }
  27034. };
  27035. /**
  27036. * retrieve all nodes overlapping with given object
  27037. * @param {Object} object An object with parameters left, top, right, bottom
  27038. * @return {Number[]} An array with id's of the overlapping nodes
  27039. * @private
  27040. */
  27041. exports._getAllNodesOverlappingWith = function (object) {
  27042. var overlappingNodes = [];
  27043. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  27044. return overlappingNodes;
  27045. };
  27046. /**
  27047. * Return a position object in canvasspace from a single point in screenspace
  27048. *
  27049. * @param pointer
  27050. * @returns {{left: number, top: number, right: number, bottom: number}}
  27051. * @private
  27052. */
  27053. exports._pointerToPositionObject = function(pointer) {
  27054. var x = this._XconvertDOMtoCanvas(pointer.x);
  27055. var y = this._YconvertDOMtoCanvas(pointer.y);
  27056. return {
  27057. left: x,
  27058. top: y,
  27059. right: x,
  27060. bottom: y
  27061. };
  27062. };
  27063. /**
  27064. * Get the top node at the a specific point (like a click)
  27065. *
  27066. * @param {{x: Number, y: Number}} pointer
  27067. * @return {Node | null} node
  27068. * @private
  27069. */
  27070. exports._getNodeAt = function (pointer) {
  27071. // we first check if this is an navigation controls element
  27072. var positionObject = this._pointerToPositionObject(pointer);
  27073. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  27074. // if there are overlapping nodes, select the last one, this is the
  27075. // one which is drawn on top of the others
  27076. if (overlappingNodes.length > 0) {
  27077. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  27078. }
  27079. else {
  27080. return null;
  27081. }
  27082. };
  27083. /**
  27084. * retrieve all edges overlapping with given object, selector is around center
  27085. * @param {Object} object An object with parameters left, top, right, bottom
  27086. * @return {Number[]} An array with id's of the overlapping nodes
  27087. * @private
  27088. */
  27089. exports._getEdgesOverlappingWith = function (object, overlappingEdges) {
  27090. var edges = this.edges;
  27091. for (var edgeId in edges) {
  27092. if (edges.hasOwnProperty(edgeId)) {
  27093. if (edges[edgeId].isOverlappingWith(object)) {
  27094. overlappingEdges.push(edgeId);
  27095. }
  27096. }
  27097. }
  27098. };
  27099. /**
  27100. * retrieve all nodes overlapping with given object
  27101. * @param {Object} object An object with parameters left, top, right, bottom
  27102. * @return {Number[]} An array with id's of the overlapping nodes
  27103. * @private
  27104. */
  27105. exports._getAllEdgesOverlappingWith = function (object) {
  27106. var overlappingEdges = [];
  27107. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  27108. return overlappingEdges;
  27109. };
  27110. /**
  27111. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  27112. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  27113. *
  27114. * @param pointer
  27115. * @returns {null}
  27116. * @private
  27117. */
  27118. exports._getEdgeAt = function(pointer) {
  27119. var positionObject = this._pointerToPositionObject(pointer);
  27120. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  27121. if (overlappingEdges.length > 0) {
  27122. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  27123. }
  27124. else {
  27125. return null;
  27126. }
  27127. };
  27128. /**
  27129. * Add object to the selection array.
  27130. *
  27131. * @param obj
  27132. * @private
  27133. */
  27134. exports._addToSelection = function(obj) {
  27135. if (obj instanceof Node) {
  27136. this.selectionObj.nodes[obj.id] = obj;
  27137. }
  27138. else {
  27139. this.selectionObj.edges[obj.id] = obj;
  27140. }
  27141. };
  27142. /**
  27143. * Add object to the selection array.
  27144. *
  27145. * @param obj
  27146. * @private
  27147. */
  27148. exports._addToHover = function(obj) {
  27149. if (obj instanceof Node) {
  27150. this.hoverObj.nodes[obj.id] = obj;
  27151. }
  27152. else {
  27153. this.hoverObj.edges[obj.id] = obj;
  27154. }
  27155. };
  27156. /**
  27157. * Remove a single option from selection.
  27158. *
  27159. * @param {Object} obj
  27160. * @private
  27161. */
  27162. exports._removeFromSelection = function(obj) {
  27163. if (obj instanceof Node) {
  27164. delete this.selectionObj.nodes[obj.id];
  27165. }
  27166. else {
  27167. delete this.selectionObj.edges[obj.id];
  27168. }
  27169. };
  27170. /**
  27171. * Unselect all. The selectionObj is useful for this.
  27172. *
  27173. * @param {Boolean} [doNotTrigger] | ignore trigger
  27174. * @private
  27175. */
  27176. exports._unselectAll = function(doNotTrigger) {
  27177. if (doNotTrigger === undefined) {
  27178. doNotTrigger = false;
  27179. }
  27180. for(var nodeId in this.selectionObj.nodes) {
  27181. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27182. this.selectionObj.nodes[nodeId].unselect();
  27183. }
  27184. }
  27185. for(var edgeId in this.selectionObj.edges) {
  27186. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27187. this.selectionObj.edges[edgeId].unselect();
  27188. }
  27189. }
  27190. this.selectionObj = {nodes:{},edges:{}};
  27191. if (doNotTrigger == false) {
  27192. this.emit('select', this.getSelection());
  27193. }
  27194. };
  27195. /**
  27196. * Unselect all clusters. The selectionObj is useful for this.
  27197. *
  27198. * @param {Boolean} [doNotTrigger] | ignore trigger
  27199. * @private
  27200. */
  27201. exports._unselectClusters = function(doNotTrigger) {
  27202. if (doNotTrigger === undefined) {
  27203. doNotTrigger = false;
  27204. }
  27205. for (var nodeId in this.selectionObj.nodes) {
  27206. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27207. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  27208. this.selectionObj.nodes[nodeId].unselect();
  27209. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  27210. }
  27211. }
  27212. }
  27213. if (doNotTrigger == false) {
  27214. this.emit('select', this.getSelection());
  27215. }
  27216. };
  27217. /**
  27218. * return the number of selected nodes
  27219. *
  27220. * @returns {number}
  27221. * @private
  27222. */
  27223. exports._getSelectedNodeCount = function() {
  27224. var count = 0;
  27225. for (var nodeId in this.selectionObj.nodes) {
  27226. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27227. count += 1;
  27228. }
  27229. }
  27230. return count;
  27231. };
  27232. /**
  27233. * return the selected node
  27234. *
  27235. * @returns {number}
  27236. * @private
  27237. */
  27238. exports._getSelectedNode = function() {
  27239. for (var nodeId in this.selectionObj.nodes) {
  27240. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27241. return this.selectionObj.nodes[nodeId];
  27242. }
  27243. }
  27244. return null;
  27245. };
  27246. /**
  27247. * return the selected edge
  27248. *
  27249. * @returns {number}
  27250. * @private
  27251. */
  27252. exports._getSelectedEdge = function() {
  27253. for (var edgeId in this.selectionObj.edges) {
  27254. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27255. return this.selectionObj.edges[edgeId];
  27256. }
  27257. }
  27258. return null;
  27259. };
  27260. /**
  27261. * return the number of selected edges
  27262. *
  27263. * @returns {number}
  27264. * @private
  27265. */
  27266. exports._getSelectedEdgeCount = function() {
  27267. var count = 0;
  27268. for (var edgeId in this.selectionObj.edges) {
  27269. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27270. count += 1;
  27271. }
  27272. }
  27273. return count;
  27274. };
  27275. /**
  27276. * return the number of selected objects.
  27277. *
  27278. * @returns {number}
  27279. * @private
  27280. */
  27281. exports._getSelectedObjectCount = function() {
  27282. var count = 0;
  27283. for(var nodeId in this.selectionObj.nodes) {
  27284. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27285. count += 1;
  27286. }
  27287. }
  27288. for(var edgeId in this.selectionObj.edges) {
  27289. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27290. count += 1;
  27291. }
  27292. }
  27293. return count;
  27294. };
  27295. /**
  27296. * Check if anything is selected
  27297. *
  27298. * @returns {boolean}
  27299. * @private
  27300. */
  27301. exports._selectionIsEmpty = function() {
  27302. for(var nodeId in this.selectionObj.nodes) {
  27303. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27304. return false;
  27305. }
  27306. }
  27307. for(var edgeId in this.selectionObj.edges) {
  27308. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27309. return false;
  27310. }
  27311. }
  27312. return true;
  27313. };
  27314. /**
  27315. * check if one of the selected nodes is a cluster.
  27316. *
  27317. * @returns {boolean}
  27318. * @private
  27319. */
  27320. exports._clusterInSelection = function() {
  27321. for(var nodeId in this.selectionObj.nodes) {
  27322. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27323. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  27324. return true;
  27325. }
  27326. }
  27327. }
  27328. return false;
  27329. };
  27330. /**
  27331. * select the edges connected to the node that is being selected
  27332. *
  27333. * @param {Node} node
  27334. * @private
  27335. */
  27336. exports._selectConnectedEdges = function(node) {
  27337. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27338. var edge = node.dynamicEdges[i];
  27339. edge.select();
  27340. this._addToSelection(edge);
  27341. }
  27342. };
  27343. /**
  27344. * select the edges connected to the node that is being selected
  27345. *
  27346. * @param {Node} node
  27347. * @private
  27348. */
  27349. exports._hoverConnectedEdges = function(node) {
  27350. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27351. var edge = node.dynamicEdges[i];
  27352. edge.hover = true;
  27353. this._addToHover(edge);
  27354. }
  27355. };
  27356. /**
  27357. * unselect the edges connected to the node that is being selected
  27358. *
  27359. * @param {Node} node
  27360. * @private
  27361. */
  27362. exports._unselectConnectedEdges = function(node) {
  27363. for (var i = 0; i < node.dynamicEdges.length; i++) {
  27364. var edge = node.dynamicEdges[i];
  27365. edge.unselect();
  27366. this._removeFromSelection(edge);
  27367. }
  27368. };
  27369. /**
  27370. * This is called when someone clicks on a node. either select or deselect it.
  27371. * If there is an existing selection and we don't want to append to it, clear the existing selection
  27372. *
  27373. * @param {Node || Edge} object
  27374. * @param {Boolean} append
  27375. * @param {Boolean} [doNotTrigger] | ignore trigger
  27376. * @private
  27377. */
  27378. exports._selectObject = function(object, append, doNotTrigger, highlightEdges, overrideSelectable) {
  27379. if (doNotTrigger === undefined) {
  27380. doNotTrigger = false;
  27381. }
  27382. if (highlightEdges === undefined) {
  27383. highlightEdges = true;
  27384. }
  27385. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  27386. this._unselectAll(true);
  27387. }
  27388. // selectable allows the object to be selected. Override can be used if needed to bypass this.
  27389. if (object.selected == false && (this.constants.selectable == true || overrideSelectable)) {
  27390. object.select();
  27391. this._addToSelection(object);
  27392. if (object instanceof Node && this.blockConnectingEdgeSelection == false && highlightEdges == true) {
  27393. this._selectConnectedEdges(object);
  27394. }
  27395. }
  27396. // do not select the object if selectable is false, only add it to selection to allow drag to work
  27397. else if (object.selected == false) {
  27398. this._addToSelection(object);
  27399. doNotTrigger = true;
  27400. }
  27401. else {
  27402. object.unselect();
  27403. this._removeFromSelection(object);
  27404. }
  27405. if (doNotTrigger == false) {
  27406. this.emit('select', this.getSelection());
  27407. }
  27408. };
  27409. /**
  27410. * This is called when someone clicks on a node. either select or deselect it.
  27411. * If there is an existing selection and we don't want to append to it, clear the existing selection
  27412. *
  27413. * @param {Node || Edge} object
  27414. * @private
  27415. */
  27416. exports._blurObject = function(object) {
  27417. if (object.hover == true) {
  27418. object.hover = false;
  27419. this.emit("blurNode",{node:object.id});
  27420. }
  27421. };
  27422. /**
  27423. * This is called when someone clicks on a node. either select or deselect it.
  27424. * If there is an existing selection and we don't want to append to it, clear the existing selection
  27425. *
  27426. * @param {Node || Edge} object
  27427. * @private
  27428. */
  27429. exports._hoverObject = function(object) {
  27430. if (object.hover == false) {
  27431. object.hover = true;
  27432. this._addToHover(object);
  27433. if (object instanceof Node) {
  27434. this.emit("hoverNode",{node:object.id});
  27435. }
  27436. }
  27437. if (object instanceof Node) {
  27438. this._hoverConnectedEdges(object);
  27439. }
  27440. };
  27441. /**
  27442. * handles the selection part of the touch, only for navigation controls elements;
  27443. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  27444. * This is the most responsive solution
  27445. *
  27446. * @param {Object} pointer
  27447. * @private
  27448. */
  27449. exports._handleTouch = function(pointer) {
  27450. };
  27451. /**
  27452. * handles the selection part of the tap;
  27453. *
  27454. * @param {Object} pointer
  27455. * @private
  27456. */
  27457. exports._handleTap = function(pointer) {
  27458. var node = this._getNodeAt(pointer);
  27459. if (node != null) {
  27460. this._selectObject(node, false);
  27461. }
  27462. else {
  27463. var edge = this._getEdgeAt(pointer);
  27464. if (edge != null) {
  27465. this._selectObject(edge, false);
  27466. }
  27467. else {
  27468. this._unselectAll();
  27469. }
  27470. }
  27471. var properties = this.getSelection();
  27472. properties['pointer'] = {
  27473. DOM: {x: pointer.x, y: pointer.y},
  27474. canvas: {x: this._XconvertDOMtoCanvas(pointer.x), y: this._YconvertDOMtoCanvas(pointer.y)}
  27475. }
  27476. this.emit("click", properties);
  27477. this._redraw();
  27478. };
  27479. /**
  27480. * handles the selection part of the double tap and opens a cluster if needed
  27481. *
  27482. * @param {Object} pointer
  27483. * @private
  27484. */
  27485. exports._handleDoubleTap = function(pointer) {
  27486. var node = this._getNodeAt(pointer);
  27487. if (node != null && node !== undefined) {
  27488. // we reset the areaCenter here so the opening of the node will occur
  27489. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  27490. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  27491. this.openCluster(node);
  27492. }
  27493. var properties = this.getSelection();
  27494. properties['pointer'] = {
  27495. DOM: {x: pointer.x, y: pointer.y},
  27496. canvas: {x: this._XconvertDOMtoCanvas(pointer.x), y: this._YconvertDOMtoCanvas(pointer.y)}
  27497. }
  27498. this.emit("doubleClick", properties);
  27499. };
  27500. /**
  27501. * Handle the onHold selection part
  27502. *
  27503. * @param pointer
  27504. * @private
  27505. */
  27506. exports._handleOnHold = function(pointer) {
  27507. var node = this._getNodeAt(pointer);
  27508. if (node != null) {
  27509. this._selectObject(node,true);
  27510. }
  27511. else {
  27512. var edge = this._getEdgeAt(pointer);
  27513. if (edge != null) {
  27514. this._selectObject(edge,true);
  27515. }
  27516. }
  27517. this._redraw();
  27518. };
  27519. /**
  27520. * handle the onRelease event. These functions are here for the navigation controls module
  27521. * and data manipulation module.
  27522. *
  27523. * @private
  27524. */
  27525. exports._handleOnRelease = function(pointer) {
  27526. this._manipulationReleaseOverload(pointer);
  27527. this._navigationReleaseOverload(pointer);
  27528. };
  27529. exports._manipulationReleaseOverload = function (pointer) {};
  27530. exports._navigationReleaseOverload = function (pointer) {};
  27531. /**
  27532. *
  27533. * retrieve the currently selected objects
  27534. * @return {{nodes: Array.<String>, edges: Array.<String>}} selection
  27535. */
  27536. exports.getSelection = function() {
  27537. var nodeIds = this.getSelectedNodes();
  27538. var edgeIds = this.getSelectedEdges();
  27539. return {nodes:nodeIds, edges:edgeIds};
  27540. };
  27541. /**
  27542. *
  27543. * retrieve the currently selected nodes
  27544. * @return {String[]} selection An array with the ids of the
  27545. * selected nodes.
  27546. */
  27547. exports.getSelectedNodes = function() {
  27548. var idArray = [];
  27549. if (this.constants.selectable == true) {
  27550. for (var nodeId in this.selectionObj.nodes) {
  27551. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27552. idArray.push(nodeId);
  27553. }
  27554. }
  27555. }
  27556. return idArray
  27557. };
  27558. /**
  27559. *
  27560. * retrieve the currently selected edges
  27561. * @return {Array} selection An array with the ids of the
  27562. * selected nodes.
  27563. */
  27564. exports.getSelectedEdges = function() {
  27565. var idArray = [];
  27566. if (this.constants.selectable == true) {
  27567. for (var edgeId in this.selectionObj.edges) {
  27568. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27569. idArray.push(edgeId);
  27570. }
  27571. }
  27572. }
  27573. return idArray;
  27574. };
  27575. /**
  27576. * select zero or more nodes DEPRICATED
  27577. * @param {Number[] | String[]} selection An array with the ids of the
  27578. * selected nodes.
  27579. */
  27580. exports.setSelection = function() {
  27581. console.log("setSelection is deprecated. Please use selectNodes instead.")
  27582. };
  27583. /**
  27584. * select zero or more nodes with the option to highlight edges
  27585. * @param {Number[] | String[]} selection An array with the ids of the
  27586. * selected nodes.
  27587. * @param {boolean} [highlightEdges]
  27588. */
  27589. exports.selectNodes = function(selection, highlightEdges) {
  27590. var i, iMax, id;
  27591. if (!selection || (selection.length == undefined))
  27592. throw 'Selection must be an array with ids';
  27593. // first unselect any selected node
  27594. this._unselectAll(true);
  27595. for (i = 0, iMax = selection.length; i < iMax; i++) {
  27596. id = selection[i];
  27597. var node = this.nodes[id];
  27598. if (!node) {
  27599. throw new RangeError('Node with id "' + id + '" not found');
  27600. }
  27601. this._selectObject(node,true,true,highlightEdges,true);
  27602. }
  27603. this.redraw();
  27604. };
  27605. /**
  27606. * select zero or more edges
  27607. * @param {Number[] | String[]} selection An array with the ids of the
  27608. * selected nodes.
  27609. */
  27610. exports.selectEdges = function(selection) {
  27611. var i, iMax, id;
  27612. if (!selection || (selection.length == undefined))
  27613. throw 'Selection must be an array with ids';
  27614. // first unselect any selected node
  27615. this._unselectAll(true);
  27616. for (i = 0, iMax = selection.length; i < iMax; i++) {
  27617. id = selection[i];
  27618. var edge = this.edges[id];
  27619. if (!edge) {
  27620. throw new RangeError('Edge with id "' + id + '" not found');
  27621. }
  27622. this._selectObject(edge,true,true,false,true);
  27623. }
  27624. this.redraw();
  27625. };
  27626. /**
  27627. * Validate the selection: remove ids of nodes which no longer exist
  27628. * @private
  27629. */
  27630. exports._updateSelection = function () {
  27631. for(var nodeId in this.selectionObj.nodes) {
  27632. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  27633. if (!this.nodes.hasOwnProperty(nodeId)) {
  27634. delete this.selectionObj.nodes[nodeId];
  27635. }
  27636. }
  27637. }
  27638. for(var edgeId in this.selectionObj.edges) {
  27639. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  27640. if (!this.edges.hasOwnProperty(edgeId)) {
  27641. delete this.selectionObj.edges[edgeId];
  27642. }
  27643. }
  27644. }
  27645. };
  27646. /***/ },
  27647. /* 63 */
  27648. /***/ function(module, exports, __webpack_require__) {
  27649. var util = __webpack_require__(1);
  27650. var Node = __webpack_require__(40);
  27651. var Edge = __webpack_require__(37);
  27652. /**
  27653. * clears the toolbar div element of children
  27654. *
  27655. * @private
  27656. */
  27657. exports._clearManipulatorBar = function() {
  27658. while (this.manipulationDiv.hasChildNodes()) {
  27659. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  27660. }
  27661. this.manipulationDOM = {};
  27662. this._manipulationReleaseOverload = function () {};
  27663. delete this.sectors['support']['nodes']['targetNode'];
  27664. delete this.sectors['support']['nodes']['targetViaNode'];
  27665. this.controlNodesActive = false;
  27666. };
  27667. /**
  27668. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  27669. * these functions to their original functionality, we saved them in this.cachedFunctions.
  27670. * This function restores these functions to their original function.
  27671. *
  27672. * @private
  27673. */
  27674. exports._restoreOverloadedFunctions = function() {
  27675. for (var functionName in this.cachedFunctions) {
  27676. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  27677. this[functionName] = this.cachedFunctions[functionName];
  27678. }
  27679. }
  27680. };
  27681. /**
  27682. * Enable or disable edit-mode.
  27683. *
  27684. * @private
  27685. */
  27686. exports._toggleEditMode = function() {
  27687. this.editMode = !this.editMode;
  27688. var toolbar = this.manipulationDiv;
  27689. var closeDiv = this.closeDiv;
  27690. var editModeDiv = this.editModeDiv;
  27691. if (this.editMode == true) {
  27692. toolbar.style.display="block";
  27693. closeDiv.style.display="block";
  27694. editModeDiv.style.display="none";
  27695. closeDiv.onclick = this._toggleEditMode.bind(this);
  27696. }
  27697. else {
  27698. toolbar.style.display="none";
  27699. closeDiv.style.display="none";
  27700. editModeDiv.style.display="block";
  27701. closeDiv.onclick = null;
  27702. }
  27703. this._createManipulatorBar()
  27704. };
  27705. /**
  27706. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  27707. *
  27708. * @private
  27709. */
  27710. exports._createManipulatorBar = function() {
  27711. // remove bound functions
  27712. if (this.boundFunction) {
  27713. this.off('select', this.boundFunction);
  27714. }
  27715. var locale = this.constants.locales[this.constants.locale];
  27716. if (this.edgeBeingEdited !== undefined) {
  27717. this.edgeBeingEdited._disableControlNodes();
  27718. this.edgeBeingEdited = undefined;
  27719. this.selectedControlNode = null;
  27720. this.controlNodesActive = false;
  27721. this._redraw();
  27722. }
  27723. // restore overloaded functions
  27724. this._restoreOverloadedFunctions();
  27725. // resume calculation
  27726. this.freezeSimulation = false;
  27727. // reset global variables
  27728. this.blockConnectingEdgeSelection = false;
  27729. this.forceAppendSelection = false;
  27730. this.manipulationDOM = {};
  27731. if (this.editMode == true) {
  27732. while (this.manipulationDiv.hasChildNodes()) {
  27733. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  27734. }
  27735. this.manipulationDOM['addNodeSpan'] = document.createElement('span');
  27736. this.manipulationDOM['addNodeSpan'].className = 'network-manipulationUI add';
  27737. this.manipulationDOM['addNodeLabelSpan'] = document.createElement('span');
  27738. this.manipulationDOM['addNodeLabelSpan'].className = 'network-manipulationLabel';
  27739. this.manipulationDOM['addNodeLabelSpan'].innerHTML = locale['addNode'];
  27740. this.manipulationDOM['addNodeSpan'].appendChild(this.manipulationDOM['addNodeLabelSpan']);
  27741. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  27742. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  27743. this.manipulationDOM['addEdgeSpan'] = document.createElement('span');
  27744. this.manipulationDOM['addEdgeSpan'].className = 'network-manipulationUI connect';
  27745. this.manipulationDOM['addEdgeLabelSpan'] = document.createElement('span');
  27746. this.manipulationDOM['addEdgeLabelSpan'].className = 'network-manipulationLabel';
  27747. this.manipulationDOM['addEdgeLabelSpan'].innerHTML = locale['addEdge'];
  27748. this.manipulationDOM['addEdgeSpan'].appendChild(this.manipulationDOM['addEdgeLabelSpan']);
  27749. this.manipulationDiv.appendChild(this.manipulationDOM['addNodeSpan']);
  27750. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  27751. this.manipulationDiv.appendChild(this.manipulationDOM['addEdgeSpan']);
  27752. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  27753. this.manipulationDOM['seperatorLineDiv2'] = document.createElement('div');
  27754. this.manipulationDOM['seperatorLineDiv2'].className = 'network-seperatorLine';
  27755. this.manipulationDOM['editNodeSpan'] = document.createElement('span');
  27756. this.manipulationDOM['editNodeSpan'].className = 'network-manipulationUI edit';
  27757. this.manipulationDOM['editNodeLabelSpan'] = document.createElement('span');
  27758. this.manipulationDOM['editNodeLabelSpan'].className = 'network-manipulationLabel';
  27759. this.manipulationDOM['editNodeLabelSpan'].innerHTML = locale['editNode'];
  27760. this.manipulationDOM['editNodeSpan'].appendChild(this.manipulationDOM['editNodeLabelSpan']);
  27761. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv2']);
  27762. this.manipulationDiv.appendChild(this.manipulationDOM['editNodeSpan']);
  27763. }
  27764. else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
  27765. this.manipulationDOM['seperatorLineDiv3'] = document.createElement('div');
  27766. this.manipulationDOM['seperatorLineDiv3'].className = 'network-seperatorLine';
  27767. this.manipulationDOM['editEdgeSpan'] = document.createElement('span');
  27768. this.manipulationDOM['editEdgeSpan'].className = 'network-manipulationUI edit';
  27769. this.manipulationDOM['editEdgeLabelSpan'] = document.createElement('span');
  27770. this.manipulationDOM['editEdgeLabelSpan'].className = 'network-manipulationLabel';
  27771. this.manipulationDOM['editEdgeLabelSpan'].innerHTML = locale['editEdge'];
  27772. this.manipulationDOM['editEdgeSpan'].appendChild(this.manipulationDOM['editEdgeLabelSpan']);
  27773. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv3']);
  27774. this.manipulationDiv.appendChild(this.manipulationDOM['editEdgeSpan']);
  27775. }
  27776. if (this._selectionIsEmpty() == false) {
  27777. this.manipulationDOM['seperatorLineDiv4'] = document.createElement('div');
  27778. this.manipulationDOM['seperatorLineDiv4'].className = 'network-seperatorLine';
  27779. this.manipulationDOM['deleteSpan'] = document.createElement('span');
  27780. this.manipulationDOM['deleteSpan'].className = 'network-manipulationUI delete';
  27781. this.manipulationDOM['deleteLabelSpan'] = document.createElement('span');
  27782. this.manipulationDOM['deleteLabelSpan'].className = 'network-manipulationLabel';
  27783. this.manipulationDOM['deleteLabelSpan'].innerHTML = locale['del'];
  27784. this.manipulationDOM['deleteSpan'].appendChild(this.manipulationDOM['deleteLabelSpan']);
  27785. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv4']);
  27786. this.manipulationDiv.appendChild(this.manipulationDOM['deleteSpan']);
  27787. }
  27788. // bind the icons
  27789. this.manipulationDOM['addNodeSpan'].onclick = this._createAddNodeToolbar.bind(this);
  27790. this.manipulationDOM['addEdgeSpan'].onclick = this._createAddEdgeToolbar.bind(this);
  27791. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  27792. this.manipulationDOM['editNodeSpan'].onclick = this._editNode.bind(this);
  27793. }
  27794. else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
  27795. this.manipulationDOM['editEdgeSpan'].onclick = this._createEditEdgeToolbar.bind(this);
  27796. }
  27797. if (this._selectionIsEmpty() == false) {
  27798. this.manipulationDOM['deleteSpan'].onclick = this._deleteSelected.bind(this);
  27799. }
  27800. this.closeDiv.onclick = this._toggleEditMode.bind(this);
  27801. this.boundFunction = this._createManipulatorBar.bind(this);
  27802. this.on('select', this.boundFunction);
  27803. }
  27804. else {
  27805. while (this.editModeDiv.hasChildNodes()) {
  27806. this.editModeDiv.removeChild(this.editModeDiv.firstChild);
  27807. }
  27808. this.manipulationDOM['editModeSpan'] = document.createElement('span');
  27809. this.manipulationDOM['editModeSpan'].className = 'network-manipulationUI edit editmode';
  27810. this.manipulationDOM['editModeLabelSpan'] = document.createElement('span');
  27811. this.manipulationDOM['editModeLabelSpan'].className = 'network-manipulationLabel';
  27812. this.manipulationDOM['editModeLabelSpan'].innerHTML = locale['edit'];
  27813. this.manipulationDOM['editModeSpan'].appendChild(this.manipulationDOM['editModeLabelSpan']);
  27814. this.editModeDiv.appendChild(this.manipulationDOM['editModeSpan']);
  27815. this.manipulationDOM['editModeSpan'].onclick = this._toggleEditMode.bind(this);
  27816. }
  27817. };
  27818. /**
  27819. * Create the toolbar for adding Nodes
  27820. *
  27821. * @private
  27822. */
  27823. exports._createAddNodeToolbar = function() {
  27824. // clear the toolbar
  27825. this._clearManipulatorBar();
  27826. if (this.boundFunction) {
  27827. this.off('select', this.boundFunction);
  27828. }
  27829. var locale = this.constants.locales[this.constants.locale];
  27830. this.manipulationDOM = {};
  27831. this.manipulationDOM['backSpan'] = document.createElement('span');
  27832. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  27833. this.manipulationDOM['backLabelSpan'] = document.createElement('span');
  27834. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  27835. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  27836. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  27837. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  27838. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  27839. this.manipulationDOM['descriptionSpan'] = document.createElement('span');
  27840. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  27841. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('span');
  27842. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  27843. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['addDescription'];
  27844. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  27845. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  27846. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  27847. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  27848. // bind the icon
  27849. this.manipulationDOM['backSpan'].onclick = this._createManipulatorBar.bind(this);
  27850. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  27851. this.boundFunction = this._addNode.bind(this);
  27852. this.on('select', this.boundFunction);
  27853. };
  27854. /**
  27855. * create the toolbar to connect nodes
  27856. *
  27857. * @private
  27858. */
  27859. exports._createAddEdgeToolbar = function() {
  27860. // clear the toolbar
  27861. this._clearManipulatorBar();
  27862. this._unselectAll(true);
  27863. this.freezeSimulation = true;
  27864. var locale = this.constants.locales[this.constants.locale];
  27865. if (this.boundFunction) {
  27866. this.off('select', this.boundFunction);
  27867. }
  27868. this._unselectAll();
  27869. this.forceAppendSelection = false;
  27870. this.blockConnectingEdgeSelection = true;
  27871. this.manipulationDOM = {};
  27872. this.manipulationDOM['backSpan'] = document.createElement('span');
  27873. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  27874. this.manipulationDOM['backLabelSpan'] = document.createElement('span');
  27875. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  27876. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  27877. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  27878. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  27879. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  27880. this.manipulationDOM['descriptionSpan'] = document.createElement('span');
  27881. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  27882. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('span');
  27883. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  27884. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['edgeDescription'];
  27885. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  27886. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  27887. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  27888. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  27889. // bind the icon
  27890. this.manipulationDOM['backSpan'].onclick = this._createManipulatorBar.bind(this);
  27891. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  27892. this.boundFunction = this._handleConnect.bind(this);
  27893. this.on('select', this.boundFunction);
  27894. // temporarily overload functions
  27895. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  27896. this.cachedFunctions["_manipulationReleaseOverload"] = this._manipulationReleaseOverload;
  27897. this.cachedFunctions["_handleDragStart"] = this._handleDragStart;
  27898. this.cachedFunctions["_handleDragEnd"] = this._handleDragEnd;
  27899. this._handleTouch = this._handleConnect;
  27900. this._manipulationReleaseOverload = function () {};
  27901. this._handleDragStart = function () {};
  27902. this._handleDragEnd = this._finishConnect;
  27903. // redraw to show the unselect
  27904. this._redraw();
  27905. };
  27906. /**
  27907. * create the toolbar to edit edges
  27908. *
  27909. * @private
  27910. */
  27911. exports._createEditEdgeToolbar = function() {
  27912. // clear the toolbar
  27913. this._clearManipulatorBar();
  27914. this.controlNodesActive = true;
  27915. if (this.boundFunction) {
  27916. this.off('select', this.boundFunction);
  27917. }
  27918. this.edgeBeingEdited = this._getSelectedEdge();
  27919. this.edgeBeingEdited._enableControlNodes();
  27920. var locale = this.constants.locales[this.constants.locale];
  27921. this.manipulationDOM = {};
  27922. this.manipulationDOM['backSpan'] = document.createElement('span');
  27923. this.manipulationDOM['backSpan'].className = 'network-manipulationUI back';
  27924. this.manipulationDOM['backLabelSpan'] = document.createElement('span');
  27925. this.manipulationDOM['backLabelSpan'].className = 'network-manipulationLabel';
  27926. this.manipulationDOM['backLabelSpan'].innerHTML = locale['back'];
  27927. this.manipulationDOM['backSpan'].appendChild(this.manipulationDOM['backLabelSpan']);
  27928. this.manipulationDOM['seperatorLineDiv1'] = document.createElement('div');
  27929. this.manipulationDOM['seperatorLineDiv1'].className = 'network-seperatorLine';
  27930. this.manipulationDOM['descriptionSpan'] = document.createElement('span');
  27931. this.manipulationDOM['descriptionSpan'].className = 'network-manipulationUI none';
  27932. this.manipulationDOM['descriptionLabelSpan'] = document.createElement('span');
  27933. this.manipulationDOM['descriptionLabelSpan'].className = 'network-manipulationLabel';
  27934. this.manipulationDOM['descriptionLabelSpan'].innerHTML = locale['editEdgeDescription'];
  27935. this.manipulationDOM['descriptionSpan'].appendChild(this.manipulationDOM['descriptionLabelSpan']);
  27936. this.manipulationDiv.appendChild(this.manipulationDOM['backSpan']);
  27937. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv1']);
  27938. this.manipulationDiv.appendChild(this.manipulationDOM['descriptionSpan']);
  27939. // bind the icon
  27940. this.manipulationDOM['backSpan'].onclick = this._createManipulatorBar.bind(this);
  27941. // temporarily overload functions
  27942. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  27943. this.cachedFunctions["_manipulationReleaseOverload"] = this._manipulationReleaseOverload;
  27944. this.cachedFunctions["_handleTap"] = this._handleTap;
  27945. this.cachedFunctions["_handleDragStart"] = this._handleDragStart;
  27946. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  27947. this._handleTouch = this._selectControlNode;
  27948. this._handleTap = function () {};
  27949. this._handleOnDrag = this._controlNodeDrag;
  27950. this._handleDragStart = function () {}
  27951. this._manipulationReleaseOverload = this._releaseControlNode;
  27952. // redraw to show the unselect
  27953. this._redraw();
  27954. };
  27955. /**
  27956. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  27957. * to walk the user through the process.
  27958. *
  27959. * @private
  27960. */
  27961. exports._selectControlNode = function(pointer) {
  27962. this.edgeBeingEdited.controlNodes.from.unselect();
  27963. this.edgeBeingEdited.controlNodes.to.unselect();
  27964. this.selectedControlNode = this.edgeBeingEdited._getSelectedControlNode(this._XconvertDOMtoCanvas(pointer.x),this._YconvertDOMtoCanvas(pointer.y));
  27965. if (this.selectedControlNode !== null) {
  27966. this.selectedControlNode.select();
  27967. this.freezeSimulation = true;
  27968. }
  27969. this._redraw();
  27970. };
  27971. /**
  27972. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  27973. * to walk the user through the process.
  27974. *
  27975. * @private
  27976. */
  27977. exports._controlNodeDrag = function(event) {
  27978. var pointer = this._getPointer(event.gesture.center);
  27979. if (this.selectedControlNode !== null && this.selectedControlNode !== undefined) {
  27980. this.selectedControlNode.x = this._XconvertDOMtoCanvas(pointer.x);
  27981. this.selectedControlNode.y = this._YconvertDOMtoCanvas(pointer.y);
  27982. }
  27983. this._redraw();
  27984. };
  27985. exports._releaseControlNode = function(pointer) {
  27986. var newNode = this._getNodeAt(pointer);
  27987. if (newNode !== null) {
  27988. if (this.edgeBeingEdited.controlNodes.from.selected == true) {
  27989. this._editEdge(newNode.id, this.edgeBeingEdited.to.id);
  27990. this.edgeBeingEdited.controlNodes.from.unselect();
  27991. }
  27992. if (this.edgeBeingEdited.controlNodes.to.selected == true) {
  27993. this._editEdge(this.edgeBeingEdited.from.id, newNode.id);
  27994. this.edgeBeingEdited.controlNodes.to.unselect();
  27995. }
  27996. }
  27997. else {
  27998. this.edgeBeingEdited._restoreControlNodes();
  27999. }
  28000. this.freezeSimulation = false;
  28001. this._redraw();
  28002. };
  28003. /**
  28004. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  28005. * to walk the user through the process.
  28006. *
  28007. * @private
  28008. */
  28009. exports._handleConnect = function(pointer) {
  28010. if (this._getSelectedNodeCount() == 0) {
  28011. var node = this._getNodeAt(pointer);
  28012. if (node != null) {
  28013. if (node.clusterSize > 1) {
  28014. alert(this.constants.locales[this.constants.locale]['createEdgeError'])
  28015. }
  28016. else {
  28017. this._selectObject(node,false);
  28018. var supportNodes = this.sectors['support']['nodes'];
  28019. // create a node the temporary line can look at
  28020. supportNodes['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  28021. var targetNode = supportNodes['targetNode'];
  28022. targetNode.x = node.x;
  28023. targetNode.y = node.y;
  28024. // create a temporary edge
  28025. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:targetNode.id}, this, this.constants);
  28026. var connectionEdge = this.edges['connectionEdge'];
  28027. connectionEdge.from = node;
  28028. connectionEdge.connected = true;
  28029. connectionEdge.options.smoothCurves = {enabled: true,
  28030. dynamic: false,
  28031. type: "continuous",
  28032. roundness: 0.5
  28033. };
  28034. connectionEdge.selected = true;
  28035. connectionEdge.to = targetNode;
  28036. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  28037. this._handleOnDrag = function(event) {
  28038. var pointer = this._getPointer(event.gesture.center);
  28039. var connectionEdge = this.edges['connectionEdge'];
  28040. connectionEdge.to.x = this._XconvertDOMtoCanvas(pointer.x);
  28041. connectionEdge.to.y = this._YconvertDOMtoCanvas(pointer.y);
  28042. };
  28043. this.moving = true;
  28044. this.start();
  28045. }
  28046. }
  28047. }
  28048. };
  28049. exports._finishConnect = function(event) {
  28050. if (this._getSelectedNodeCount() == 1) {
  28051. var pointer = this._getPointer(event.gesture.center);
  28052. // restore the drag function
  28053. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  28054. delete this.cachedFunctions["_handleOnDrag"];
  28055. // remember the edge id
  28056. var connectFromId = this.edges['connectionEdge'].fromId;
  28057. // remove the temporary nodes and edge
  28058. delete this.edges['connectionEdge'];
  28059. delete this.sectors['support']['nodes']['targetNode'];
  28060. delete this.sectors['support']['nodes']['targetViaNode'];
  28061. var node = this._getNodeAt(pointer);
  28062. if (node != null) {
  28063. if (node.clusterSize > 1) {
  28064. alert(this.constants.locales[this.constants.locale]["createEdgeError"])
  28065. }
  28066. else {
  28067. this._createEdge(connectFromId,node.id);
  28068. this._createManipulatorBar();
  28069. }
  28070. }
  28071. this._unselectAll();
  28072. }
  28073. };
  28074. /**
  28075. * Adds a node on the specified location
  28076. */
  28077. exports._addNode = function() {
  28078. if (this._selectionIsEmpty() && this.editMode == true) {
  28079. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  28080. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  28081. if (this.triggerFunctions.add) {
  28082. if (this.triggerFunctions.add.length == 2) {
  28083. var me = this;
  28084. this.triggerFunctions.add(defaultData, function(finalizedData) {
  28085. me.nodesData.add(finalizedData);
  28086. me._createManipulatorBar();
  28087. me.moving = true;
  28088. me.start();
  28089. });
  28090. }
  28091. else {
  28092. throw new Error('The function for add does not support two arguments (data,callback)');
  28093. this._createManipulatorBar();
  28094. this.moving = true;
  28095. this.start();
  28096. }
  28097. }
  28098. else {
  28099. this.nodesData.add(defaultData);
  28100. this._createManipulatorBar();
  28101. this.moving = true;
  28102. this.start();
  28103. }
  28104. }
  28105. };
  28106. /**
  28107. * connect two nodes with a new edge.
  28108. *
  28109. * @private
  28110. */
  28111. exports._createEdge = function(sourceNodeId,targetNodeId) {
  28112. if (this.editMode == true) {
  28113. var defaultData = {from:sourceNodeId, to:targetNodeId};
  28114. if (this.triggerFunctions.connect) {
  28115. if (this.triggerFunctions.connect.length == 2) {
  28116. var me = this;
  28117. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  28118. me.edgesData.add(finalizedData);
  28119. me.moving = true;
  28120. me.start();
  28121. });
  28122. }
  28123. else {
  28124. throw new Error('The function for connect does not support two arguments (data,callback)');
  28125. this.moving = true;
  28126. this.start();
  28127. }
  28128. }
  28129. else {
  28130. this.edgesData.add(defaultData);
  28131. this.moving = true;
  28132. this.start();
  28133. }
  28134. }
  28135. };
  28136. /**
  28137. * connect two nodes with a new edge.
  28138. *
  28139. * @private
  28140. */
  28141. exports._editEdge = function(sourceNodeId,targetNodeId) {
  28142. if (this.editMode == true) {
  28143. var defaultData = {id: this.edgeBeingEdited.id, from:sourceNodeId, to:targetNodeId};
  28144. if (this.triggerFunctions.editEdge) {
  28145. if (this.triggerFunctions.editEdge.length == 2) {
  28146. var me = this;
  28147. this.triggerFunctions.editEdge(defaultData, function(finalizedData) {
  28148. me.edgesData.update(finalizedData);
  28149. me.moving = true;
  28150. me.start();
  28151. });
  28152. }
  28153. else {
  28154. throw new Error('The function for edit does not support two arguments (data, callback)');
  28155. this.moving = true;
  28156. this.start();
  28157. }
  28158. }
  28159. else {
  28160. this.edgesData.update(defaultData);
  28161. this.moving = true;
  28162. this.start();
  28163. }
  28164. }
  28165. };
  28166. /**
  28167. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  28168. *
  28169. * @private
  28170. */
  28171. exports._editNode = function() {
  28172. if (this.triggerFunctions.edit && this.editMode == true) {
  28173. var node = this._getSelectedNode();
  28174. var data = {id:node.id,
  28175. label: node.label,
  28176. group: node.options.group,
  28177. shape: node.options.shape,
  28178. color: {
  28179. background:node.options.color.background,
  28180. border:node.options.color.border,
  28181. highlight: {
  28182. background:node.options.color.highlight.background,
  28183. border:node.options.color.highlight.border
  28184. }
  28185. }};
  28186. if (this.triggerFunctions.edit.length == 2) {
  28187. var me = this;
  28188. this.triggerFunctions.edit(data, function (finalizedData) {
  28189. me.nodesData.update(finalizedData);
  28190. me._createManipulatorBar();
  28191. me.moving = true;
  28192. me.start();
  28193. });
  28194. }
  28195. else {
  28196. throw new Error('The function for edit does not support two arguments (data, callback)');
  28197. }
  28198. }
  28199. else {
  28200. throw new Error('No edit function has been bound to this button');
  28201. }
  28202. };
  28203. /**
  28204. * delete everything in the selection
  28205. *
  28206. * @private
  28207. */
  28208. exports._deleteSelected = function() {
  28209. if (!this._selectionIsEmpty() && this.editMode == true) {
  28210. if (!this._clusterInSelection()) {
  28211. var selectedNodes = this.getSelectedNodes();
  28212. var selectedEdges = this.getSelectedEdges();
  28213. if (this.triggerFunctions.del) {
  28214. var me = this;
  28215. var data = {nodes: selectedNodes, edges: selectedEdges};
  28216. if (this.triggerFunctions.del.length == 2) {
  28217. this.triggerFunctions.del(data, function (finalizedData) {
  28218. me.edgesData.remove(finalizedData.edges);
  28219. me.nodesData.remove(finalizedData.nodes);
  28220. me._unselectAll();
  28221. me.moving = true;
  28222. me.start();
  28223. });
  28224. }
  28225. else {
  28226. throw new Error('The function for delete does not support two arguments (data, callback)')
  28227. }
  28228. }
  28229. else {
  28230. this.edgesData.remove(selectedEdges);
  28231. this.nodesData.remove(selectedNodes);
  28232. this._unselectAll();
  28233. this.moving = true;
  28234. this.start();
  28235. }
  28236. }
  28237. else {
  28238. alert(this.constants.locales[this.constants.locale]["deleteClusterError"]);
  28239. }
  28240. }
  28241. };
  28242. /***/ },
  28243. /* 64 */
  28244. /***/ function(module, exports, __webpack_require__) {
  28245. var util = __webpack_require__(1);
  28246. var Hammer = __webpack_require__(45);
  28247. exports._cleanNavigation = function() {
  28248. // clean hammer bindings
  28249. if (this.navigationHammers.existing.length != 0) {
  28250. for (var i = 0; i < this.navigationHammers.existing.length; i++) {
  28251. this.navigationHammers.existing[i].dispose();
  28252. }
  28253. this.navigationHammers.existing = [];
  28254. }
  28255. this._navigationReleaseOverload = function () {};
  28256. // clean up previous navigation items
  28257. if (this.navigationDivs && this.navigationDivs['wrapper'] && this.navigationDivs['wrapper'].parentNode) {
  28258. this.navigationDivs['wrapper'].parentNode.removeChild(this.navigationDivs['wrapper']);
  28259. }
  28260. };
  28261. /**
  28262. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  28263. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  28264. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  28265. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  28266. *
  28267. * @private
  28268. */
  28269. exports._loadNavigationElements = function() {
  28270. this._cleanNavigation();
  28271. this.navigationDivs = {};
  28272. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  28273. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','_zoomExtent'];
  28274. this.navigationDivs['wrapper'] = document.createElement('div');
  28275. this.frame.appendChild(this.navigationDivs['wrapper']);
  28276. for (var i = 0; i < navigationDivs.length; i++) {
  28277. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  28278. this.navigationDivs[navigationDivs[i]].className = 'network-navigation ' + navigationDivs[i];
  28279. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  28280. var hammer = Hammer(this.navigationDivs[navigationDivs[i]], {prevent_default: true});
  28281. hammer.on('touch', this[navigationDivActions[i]].bind(this));
  28282. this.navigationHammers._new.push(hammer);
  28283. }
  28284. this._navigationReleaseOverload = this._stopMovement;
  28285. this.navigationHammers.existing = this.navigationHammers._new;
  28286. };
  28287. /**
  28288. * this stops all movement induced by the navigation buttons
  28289. *
  28290. * @private
  28291. */
  28292. exports._zoomExtent = function(event) {
  28293. this.zoomExtent({duration:700});
  28294. event.stopPropagation();
  28295. };
  28296. /**
  28297. * this stops all movement induced by the navigation buttons
  28298. *
  28299. * @private
  28300. */
  28301. exports._stopMovement = function() {
  28302. this._xStopMoving();
  28303. this._yStopMoving();
  28304. this._stopZoom();
  28305. };
  28306. /**
  28307. * move the screen up
  28308. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  28309. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  28310. * To avoid this behaviour, we do the translation in the start loop.
  28311. *
  28312. * @private
  28313. */
  28314. exports._moveUp = function(event) {
  28315. this.yIncrement = this.constants.keyboard.speed.y;
  28316. this.start(); // if there is no node movement, the calculation wont be done
  28317. event.preventDefault();
  28318. };
  28319. /**
  28320. * move the screen down
  28321. * @private
  28322. */
  28323. exports._moveDown = function(event) {
  28324. this.yIncrement = -this.constants.keyboard.speed.y;
  28325. this.start(); // if there is no node movement, the calculation wont be done
  28326. event.preventDefault();
  28327. };
  28328. /**
  28329. * move the screen left
  28330. * @private
  28331. */
  28332. exports._moveLeft = function(event) {
  28333. this.xIncrement = this.constants.keyboard.speed.x;
  28334. this.start(); // if there is no node movement, the calculation wont be done
  28335. event.preventDefault();
  28336. };
  28337. /**
  28338. * move the screen right
  28339. * @private
  28340. */
  28341. exports._moveRight = function(event) {
  28342. this.xIncrement = -this.constants.keyboard.speed.y;
  28343. this.start(); // if there is no node movement, the calculation wont be done
  28344. event.preventDefault();
  28345. };
  28346. /**
  28347. * Zoom in, using the same method as the movement.
  28348. * @private
  28349. */
  28350. exports._zoomIn = function(event) {
  28351. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  28352. this.start(); // if there is no node movement, the calculation wont be done
  28353. event.preventDefault();
  28354. };
  28355. /**
  28356. * Zoom out
  28357. * @private
  28358. */
  28359. exports._zoomOut = function(event) {
  28360. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  28361. this.start(); // if there is no node movement, the calculation wont be done
  28362. event.preventDefault();
  28363. };
  28364. /**
  28365. * Stop zooming and unhighlight the zoom controls
  28366. * @private
  28367. */
  28368. exports._stopZoom = function(event) {
  28369. this.zoomIncrement = 0;
  28370. event && event.preventDefault();
  28371. };
  28372. /**
  28373. * Stop moving in the Y direction and unHighlight the up and down
  28374. * @private
  28375. */
  28376. exports._yStopMoving = function(event) {
  28377. this.yIncrement = 0;
  28378. event && event.preventDefault();
  28379. };
  28380. /**
  28381. * Stop moving in the X direction and unHighlight left and right.
  28382. * @private
  28383. */
  28384. exports._xStopMoving = function(event) {
  28385. this.xIncrement = 0;
  28386. event && event.preventDefault();
  28387. };
  28388. /***/ },
  28389. /* 65 */
  28390. /***/ function(module, exports, __webpack_require__) {
  28391. exports._resetLevels = function() {
  28392. for (var nodeId in this.nodes) {
  28393. if (this.nodes.hasOwnProperty(nodeId)) {
  28394. var node = this.nodes[nodeId];
  28395. if (node.preassignedLevel == false) {
  28396. node.level = -1;
  28397. node.hierarchyEnumerated = false;
  28398. }
  28399. }
  28400. }
  28401. };
  28402. /**
  28403. * This is the main function to layout the nodes in a hierarchical way.
  28404. * It checks if the node details are supplied correctly
  28405. *
  28406. * @private
  28407. */
  28408. exports._setupHierarchicalLayout = function() {
  28409. if (this.constants.hierarchicalLayout.enabled == true && this.nodeIndices.length > 0) {
  28410. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  28411. this.constants.hierarchicalLayout.levelSeparation = this.constants.hierarchicalLayout.levelSeparation < 0 ? this.constants.hierarchicalLayout.levelSeparation : this.constants.hierarchicalLayout.levelSeparation * -1;
  28412. }
  28413. else {
  28414. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  28415. }
  28416. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "LR") {
  28417. if (this.constants.smoothCurves.enabled == true) {
  28418. this.constants.smoothCurves.type = "vertical";
  28419. }
  28420. }
  28421. else {
  28422. if (this.constants.smoothCurves.enabled == true) {
  28423. this.constants.smoothCurves.type = "horizontal";
  28424. }
  28425. }
  28426. // get the size of the largest hubs and check if the user has defined a level for a node.
  28427. var hubsize = 0;
  28428. var node, nodeId;
  28429. var definedLevel = false;
  28430. var undefinedLevel = false;
  28431. for (nodeId in this.nodes) {
  28432. if (this.nodes.hasOwnProperty(nodeId)) {
  28433. node = this.nodes[nodeId];
  28434. if (node.level != -1) {
  28435. definedLevel = true;
  28436. }
  28437. else {
  28438. undefinedLevel = true;
  28439. }
  28440. if (hubsize < node.edges.length) {
  28441. hubsize = node.edges.length;
  28442. }
  28443. }
  28444. }
  28445. // if the user defined some levels but not all, alert and run without hierarchical layout
  28446. if (undefinedLevel == true && definedLevel == true) {
  28447. throw new Error("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  28448. this.zoomExtent(undefined,true,this.constants.clustering.enabled);
  28449. if (!this.constants.clustering.enabled) {
  28450. this.start();
  28451. }
  28452. }
  28453. else {
  28454. // setup the system to use hierarchical method.
  28455. this._changeConstants();
  28456. // define levels if undefined by the users. Based on hubsize
  28457. if (undefinedLevel == true) {
  28458. if (this.constants.hierarchicalLayout.layout == "hubsize") {
  28459. this._determineLevels(hubsize);
  28460. }
  28461. else {
  28462. this._determineLevelsDirected();
  28463. }
  28464. }
  28465. // check the distribution of the nodes per level.
  28466. var distribution = this._getDistribution();
  28467. // place the nodes on the canvas. This also stablilizes the system.
  28468. this._placeNodesByHierarchy(distribution);
  28469. // start the simulation.
  28470. this.start();
  28471. }
  28472. }
  28473. };
  28474. /**
  28475. * This function places the nodes on the canvas based on the hierarchial distribution.
  28476. *
  28477. * @param {Object} distribution | obtained by the function this._getDistribution()
  28478. * @private
  28479. */
  28480. exports._placeNodesByHierarchy = function(distribution) {
  28481. var nodeId, node;
  28482. // start placing all the level 0 nodes first. Then recursively position their branches.
  28483. for (var level in distribution) {
  28484. if (distribution.hasOwnProperty(level)) {
  28485. for (nodeId in distribution[level].nodes) {
  28486. if (distribution[level].nodes.hasOwnProperty(nodeId)) {
  28487. node = distribution[level].nodes[nodeId];
  28488. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  28489. if (node.xFixed) {
  28490. node.x = distribution[level].minPos;
  28491. node.xFixed = false;
  28492. distribution[level].minPos += distribution[level].nodeSpacing;
  28493. }
  28494. }
  28495. else {
  28496. if (node.yFixed) {
  28497. node.y = distribution[level].minPos;
  28498. node.yFixed = false;
  28499. distribution[level].minPos += distribution[level].nodeSpacing;
  28500. }
  28501. }
  28502. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  28503. }
  28504. }
  28505. }
  28506. }
  28507. // stabilize the system after positioning. This function calls zoomExtent.
  28508. this._stabilize();
  28509. };
  28510. /**
  28511. * This function get the distribution of levels based on hubsize
  28512. *
  28513. * @returns {Object}
  28514. * @private
  28515. */
  28516. exports._getDistribution = function() {
  28517. var distribution = {};
  28518. var nodeId, node, level;
  28519. // 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.
  28520. // the fix of X is removed after the x value has been set.
  28521. for (nodeId in this.nodes) {
  28522. if (this.nodes.hasOwnProperty(nodeId)) {
  28523. node = this.nodes[nodeId];
  28524. node.xFixed = true;
  28525. node.yFixed = true;
  28526. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  28527. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  28528. }
  28529. else {
  28530. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  28531. }
  28532. if (distribution[node.level] === undefined) {
  28533. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  28534. }
  28535. distribution[node.level].amount += 1;
  28536. distribution[node.level].nodes[nodeId] = node;
  28537. }
  28538. }
  28539. // determine the largest amount of nodes of all levels
  28540. var maxCount = 0;
  28541. for (level in distribution) {
  28542. if (distribution.hasOwnProperty(level)) {
  28543. if (maxCount < distribution[level].amount) {
  28544. maxCount = distribution[level].amount;
  28545. }
  28546. }
  28547. }
  28548. // set the initial position and spacing of each nodes accordingly
  28549. for (level in distribution) {
  28550. if (distribution.hasOwnProperty(level)) {
  28551. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  28552. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  28553. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  28554. }
  28555. }
  28556. return distribution;
  28557. };
  28558. /**
  28559. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  28560. *
  28561. * @param hubsize
  28562. * @private
  28563. */
  28564. exports._determineLevels = function(hubsize) {
  28565. var nodeId, node;
  28566. // determine hubs
  28567. for (nodeId in this.nodes) {
  28568. if (this.nodes.hasOwnProperty(nodeId)) {
  28569. node = this.nodes[nodeId];
  28570. if (node.edges.length == hubsize) {
  28571. node.level = 0;
  28572. }
  28573. }
  28574. }
  28575. // branch from hubs
  28576. for (nodeId in this.nodes) {
  28577. if (this.nodes.hasOwnProperty(nodeId)) {
  28578. node = this.nodes[nodeId];
  28579. if (node.level == 0) {
  28580. this._setLevel(1,node.edges,node.id);
  28581. }
  28582. }
  28583. }
  28584. };
  28585. /**
  28586. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  28587. *
  28588. * @param hubsize
  28589. * @private
  28590. */
  28591. exports._determineLevelsDirected = function() {
  28592. var nodeId, node;
  28593. // set first node to source
  28594. for (nodeId in this.nodes) {
  28595. if (this.nodes.hasOwnProperty(nodeId)) {
  28596. this.nodes[nodeId].level = 10000;
  28597. break;
  28598. }
  28599. }
  28600. // branch from hubs
  28601. for (nodeId in this.nodes) {
  28602. if (this.nodes.hasOwnProperty(nodeId)) {
  28603. node = this.nodes[nodeId];
  28604. if (node.level == 10000) {
  28605. this._setLevelDirected(10000,node.edges,node.id);
  28606. }
  28607. }
  28608. }
  28609. // branch from hubs
  28610. var minLevel = 10000;
  28611. for (nodeId in this.nodes) {
  28612. if (this.nodes.hasOwnProperty(nodeId)) {
  28613. node = this.nodes[nodeId];
  28614. minLevel = node.level < minLevel ? node.level : minLevel;
  28615. }
  28616. }
  28617. // branch from hubs
  28618. for (nodeId in this.nodes) {
  28619. if (this.nodes.hasOwnProperty(nodeId)) {
  28620. node = this.nodes[nodeId];
  28621. node.level -= minLevel;
  28622. }
  28623. }
  28624. };
  28625. /**
  28626. * Since hierarchical layout does not support:
  28627. * - smooth curves (based on the physics),
  28628. * - clustering (based on dynamic node counts)
  28629. *
  28630. * We disable both features so there will be no problems.
  28631. *
  28632. * @private
  28633. */
  28634. exports._changeConstants = function() {
  28635. this.constants.clustering.enabled = false;
  28636. this.constants.physics.barnesHut.enabled = false;
  28637. this.constants.physics.hierarchicalRepulsion.enabled = true;
  28638. this._loadSelectedForceSolver();
  28639. if (this.constants.smoothCurves.enabled == true) {
  28640. this.constants.smoothCurves.dynamic = false;
  28641. }
  28642. this._configureSmoothCurves();
  28643. };
  28644. /**
  28645. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  28646. * on a X position that ensures there will be no overlap.
  28647. *
  28648. * @param edges
  28649. * @param parentId
  28650. * @param distribution
  28651. * @param parentLevel
  28652. * @private
  28653. */
  28654. exports._placeBranchNodes = function(edges, parentId, distribution, parentLevel) {
  28655. for (var i = 0; i < edges.length; i++) {
  28656. var childNode = null;
  28657. if (edges[i].toId == parentId) {
  28658. childNode = edges[i].from;
  28659. }
  28660. else {
  28661. childNode = edges[i].to;
  28662. }
  28663. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  28664. var nodeMoved = false;
  28665. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  28666. if (childNode.xFixed && childNode.level > parentLevel) {
  28667. childNode.xFixed = false;
  28668. childNode.x = distribution[childNode.level].minPos;
  28669. nodeMoved = true;
  28670. }
  28671. }
  28672. else {
  28673. if (childNode.yFixed && childNode.level > parentLevel) {
  28674. childNode.yFixed = false;
  28675. childNode.y = distribution[childNode.level].minPos;
  28676. nodeMoved = true;
  28677. }
  28678. }
  28679. if (nodeMoved == true) {
  28680. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  28681. if (childNode.edges.length > 1) {
  28682. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  28683. }
  28684. }
  28685. }
  28686. };
  28687. /**
  28688. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  28689. *
  28690. * @param level
  28691. * @param edges
  28692. * @param parentId
  28693. * @private
  28694. */
  28695. exports._setLevel = function(level, edges, parentId) {
  28696. for (var i = 0; i < edges.length; i++) {
  28697. var childNode = null;
  28698. if (edges[i].toId == parentId) {
  28699. childNode = edges[i].from;
  28700. }
  28701. else {
  28702. childNode = edges[i].to;
  28703. }
  28704. if (childNode.level == -1 || childNode.level > level) {
  28705. childNode.level = level;
  28706. if (childNode.edges.length > 1) {
  28707. this._setLevel(level+1, childNode.edges, childNode.id);
  28708. }
  28709. }
  28710. }
  28711. };
  28712. /**
  28713. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  28714. *
  28715. * @param level
  28716. * @param edges
  28717. * @param parentId
  28718. * @private
  28719. */
  28720. exports._setLevelDirected = function(level, edges, parentId) {
  28721. this.nodes[parentId].hierarchyEnumerated = true;
  28722. for (var i = 0; i < edges.length; i++) {
  28723. var childNode = null;
  28724. var direction = 1;
  28725. if (edges[i].toId == parentId) {
  28726. childNode = edges[i].from;
  28727. direction = -1;
  28728. }
  28729. else {
  28730. childNode = edges[i].to;
  28731. }
  28732. if (childNode.level == -1) {
  28733. childNode.level = level + direction;
  28734. }
  28735. }
  28736. for (var i = 0; i < edges.length; i++) {
  28737. var childNode = null;
  28738. if (edges[i].toId == parentId) {childNode = edges[i].from;}
  28739. else {childNode = edges[i].to;}
  28740. if (childNode.edges.length > 1 && childNode.hierarchyEnumerated === false) {
  28741. this._setLevelDirected(childNode.level, childNode.edges, childNode.id);
  28742. }
  28743. }
  28744. };
  28745. /**
  28746. * Unfix nodes
  28747. *
  28748. * @private
  28749. */
  28750. exports._restoreNodes = function() {
  28751. for (var nodeId in this.nodes) {
  28752. if (this.nodes.hasOwnProperty(nodeId)) {
  28753. this.nodes[nodeId].xFixed = false;
  28754. this.nodes[nodeId].yFixed = false;
  28755. }
  28756. }
  28757. };
  28758. /***/ },
  28759. /* 66 */
  28760. /***/ function(module, exports, __webpack_require__) {
  28761. var util = __webpack_require__(1);
  28762. var RepulsionMixin = __webpack_require__(68);
  28763. var HierarchialRepulsionMixin = __webpack_require__(69);
  28764. var BarnesHutMixin = __webpack_require__(70);
  28765. /**
  28766. * Toggling barnes Hut calculation on and off.
  28767. *
  28768. * @private
  28769. */
  28770. exports._toggleBarnesHut = function () {
  28771. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  28772. this._loadSelectedForceSolver();
  28773. this.moving = true;
  28774. this.start();
  28775. };
  28776. /**
  28777. * This loads the node force solver based on the barnes hut or repulsion algorithm
  28778. *
  28779. * @private
  28780. */
  28781. exports._loadSelectedForceSolver = function () {
  28782. // this overloads the this._calculateNodeForces
  28783. if (this.constants.physics.barnesHut.enabled == true) {
  28784. this._clearMixin(RepulsionMixin);
  28785. this._clearMixin(HierarchialRepulsionMixin);
  28786. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  28787. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  28788. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  28789. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  28790. this._loadMixin(BarnesHutMixin);
  28791. }
  28792. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  28793. this._clearMixin(BarnesHutMixin);
  28794. this._clearMixin(RepulsionMixin);
  28795. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  28796. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  28797. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  28798. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  28799. this._loadMixin(HierarchialRepulsionMixin);
  28800. }
  28801. else {
  28802. this._clearMixin(BarnesHutMixin);
  28803. this._clearMixin(HierarchialRepulsionMixin);
  28804. this.barnesHutTree = undefined;
  28805. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  28806. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  28807. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  28808. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  28809. this._loadMixin(RepulsionMixin);
  28810. }
  28811. };
  28812. /**
  28813. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  28814. * if there is more than one node. If it is just one node, we dont calculate anything.
  28815. *
  28816. * @private
  28817. */
  28818. exports._initializeForceCalculation = function () {
  28819. // stop calculation if there is only one node
  28820. if (this.nodeIndices.length == 1) {
  28821. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  28822. }
  28823. else {
  28824. // if there are too many nodes on screen, we cluster without repositioning
  28825. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  28826. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  28827. }
  28828. // we now start the force calculation
  28829. this._calculateForces();
  28830. }
  28831. };
  28832. /**
  28833. * Calculate the external forces acting on the nodes
  28834. * Forces are caused by: edges, repulsing forces between nodes, gravity
  28835. * @private
  28836. */
  28837. exports._calculateForces = function () {
  28838. // Gravity is required to keep separated groups from floating off
  28839. // the forces are reset to zero in this loop by using _setForce instead
  28840. // of _addForce
  28841. this._calculateGravitationalForces();
  28842. this._calculateNodeForces();
  28843. if (this.constants.physics.springConstant > 0) {
  28844. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  28845. this._calculateSpringForcesWithSupport();
  28846. }
  28847. else {
  28848. if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  28849. this._calculateHierarchicalSpringForces();
  28850. }
  28851. else {
  28852. this._calculateSpringForces();
  28853. }
  28854. }
  28855. }
  28856. };
  28857. /**
  28858. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  28859. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  28860. * This function joins the datanodes and invisible (called support) nodes into one object.
  28861. * We do this so we do not contaminate this.nodes with the support nodes.
  28862. *
  28863. * @private
  28864. */
  28865. exports._updateCalculationNodes = function () {
  28866. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  28867. this.calculationNodes = {};
  28868. this.calculationNodeIndices = [];
  28869. for (var nodeId in this.nodes) {
  28870. if (this.nodes.hasOwnProperty(nodeId)) {
  28871. this.calculationNodes[nodeId] = this.nodes[nodeId];
  28872. }
  28873. }
  28874. var supportNodes = this.sectors['support']['nodes'];
  28875. for (var supportNodeId in supportNodes) {
  28876. if (supportNodes.hasOwnProperty(supportNodeId)) {
  28877. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  28878. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  28879. }
  28880. else {
  28881. supportNodes[supportNodeId]._setForce(0, 0);
  28882. }
  28883. }
  28884. }
  28885. for (var idx in this.calculationNodes) {
  28886. if (this.calculationNodes.hasOwnProperty(idx)) {
  28887. this.calculationNodeIndices.push(idx);
  28888. }
  28889. }
  28890. }
  28891. else {
  28892. this.calculationNodes = this.nodes;
  28893. this.calculationNodeIndices = this.nodeIndices;
  28894. }
  28895. };
  28896. /**
  28897. * this function applies the central gravity effect to keep groups from floating off
  28898. *
  28899. * @private
  28900. */
  28901. exports._calculateGravitationalForces = function () {
  28902. var dx, dy, distance, node, i;
  28903. var nodes = this.calculationNodes;
  28904. var gravity = this.constants.physics.centralGravity;
  28905. var gravityForce = 0;
  28906. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  28907. node = nodes[this.calculationNodeIndices[i]];
  28908. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  28909. // gravity does not apply when we are in a pocket sector
  28910. if (this._sector() == "default" && gravity != 0) {
  28911. dx = -node.x;
  28912. dy = -node.y;
  28913. distance = Math.sqrt(dx * dx + dy * dy);
  28914. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  28915. node.fx = dx * gravityForce;
  28916. node.fy = dy * gravityForce;
  28917. }
  28918. else {
  28919. node.fx = 0;
  28920. node.fy = 0;
  28921. }
  28922. }
  28923. };
  28924. /**
  28925. * this function calculates the effects of the springs in the case of unsmooth curves.
  28926. *
  28927. * @private
  28928. */
  28929. exports._calculateSpringForces = function () {
  28930. var edgeLength, edge, edgeId;
  28931. var dx, dy, fx, fy, springForce, distance;
  28932. var edges = this.edges;
  28933. // forces caused by the edges, modelled as springs
  28934. for (edgeId in edges) {
  28935. if (edges.hasOwnProperty(edgeId)) {
  28936. edge = edges[edgeId];
  28937. if (edge.connected) {
  28938. // only calculate forces if nodes are in the same sector
  28939. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  28940. edgeLength = edge.physics.springLength;
  28941. // this implies that the edges between big clusters are longer
  28942. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  28943. dx = (edge.from.x - edge.to.x);
  28944. dy = (edge.from.y - edge.to.y);
  28945. distance = Math.sqrt(dx * dx + dy * dy);
  28946. if (distance == 0) {
  28947. distance = 0.01;
  28948. }
  28949. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  28950. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  28951. fx = dx * springForce;
  28952. fy = dy * springForce;
  28953. edge.from.fx += fx;
  28954. edge.from.fy += fy;
  28955. edge.to.fx -= fx;
  28956. edge.to.fy -= fy;
  28957. }
  28958. }
  28959. }
  28960. }
  28961. };
  28962. /**
  28963. * This function calculates the springforces on the nodes, accounting for the support nodes.
  28964. *
  28965. * @private
  28966. */
  28967. exports._calculateSpringForcesWithSupport = function () {
  28968. var edgeLength, edge, edgeId, combinedClusterSize;
  28969. var edges = this.edges;
  28970. // forces caused by the edges, modelled as springs
  28971. for (edgeId in edges) {
  28972. if (edges.hasOwnProperty(edgeId)) {
  28973. edge = edges[edgeId];
  28974. if (edge.connected) {
  28975. // only calculate forces if nodes are in the same sector
  28976. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  28977. if (edge.via != null) {
  28978. var node1 = edge.to;
  28979. var node2 = edge.via;
  28980. var node3 = edge.from;
  28981. edgeLength = edge.physics.springLength;
  28982. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  28983. // this implies that the edges between big clusters are longer
  28984. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  28985. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  28986. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  28987. }
  28988. }
  28989. }
  28990. }
  28991. }
  28992. };
  28993. /**
  28994. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  28995. *
  28996. * @param node1
  28997. * @param node2
  28998. * @param edgeLength
  28999. * @private
  29000. */
  29001. exports._calculateSpringForce = function (node1, node2, edgeLength) {
  29002. var dx, dy, fx, fy, springForce, distance;
  29003. dx = (node1.x - node2.x);
  29004. dy = (node1.y - node2.y);
  29005. distance = Math.sqrt(dx * dx + dy * dy);
  29006. if (distance == 0) {
  29007. distance = 0.01;
  29008. }
  29009. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  29010. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  29011. fx = dx * springForce;
  29012. fy = dy * springForce;
  29013. node1.fx += fx;
  29014. node1.fy += fy;
  29015. node2.fx -= fx;
  29016. node2.fy -= fy;
  29017. };
  29018. exports._cleanupPhysicsConfiguration = function() {
  29019. if (this.physicsConfiguration !== undefined) {
  29020. while (this.physicsConfiguration.hasChildNodes()) {
  29021. this.physicsConfiguration.removeChild(this.physicsConfiguration.firstChild);
  29022. }
  29023. this.physicsConfiguration.parentNode.removeChild(this.physicsConfiguration);
  29024. this.physicsConfiguration = undefined;
  29025. }
  29026. }
  29027. /**
  29028. * Load the HTML for the physics config and bind it
  29029. * @private
  29030. */
  29031. exports._loadPhysicsConfiguration = function () {
  29032. if (this.physicsConfiguration === undefined) {
  29033. this.backupConstants = {};
  29034. util.deepExtend(this.backupConstants,this.constants);
  29035. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  29036. this.physicsConfiguration = document.createElement('div');
  29037. this.physicsConfiguration.className = "PhysicsConfiguration";
  29038. this.physicsConfiguration.innerHTML = '' +
  29039. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  29040. '<tr>' +
  29041. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  29042. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  29043. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  29044. '</tr>' +
  29045. '</table>' +
  29046. '<table id="graph_BH_table" style="display:none">' +
  29047. '<tr><td><b>Barnes Hut</b></td></tr>' +
  29048. '<tr>' +
  29049. '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="0" max="20000" value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-20000</td><td><input value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>' +
  29050. '</tr>' +
  29051. '<tr>' +
  29052. '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" 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>' +
  29053. '</tr>' +
  29054. '<tr>' +
  29055. '<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>' +
  29056. '</tr>' +
  29057. '<tr>' +
  29058. '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.barnesHut.springConstant + '" step="0.001" style="width:300px" id="graph_BH_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.barnesHut.springConstant + '" id="graph_BH_sc_value" style="width:60px"></td>' +
  29059. '</tr>' +
  29060. '<tr>' +
  29061. '<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>' +
  29062. '</tr>' +
  29063. '</table>' +
  29064. '<table id="graph_R_table" style="display:none">' +
  29065. '<tr><td><b>Repulsion</b></td></tr>' +
  29066. '<tr>' +
  29067. '<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>' +
  29068. '</tr>' +
  29069. '<tr>' +
  29070. '<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>' +
  29071. '</tr>' +
  29072. '<tr>' +
  29073. '<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>' +
  29074. '</tr>' +
  29075. '<tr>' +
  29076. '<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>' +
  29077. '</tr>' +
  29078. '<tr>' +
  29079. '<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>' +
  29080. '</tr>' +
  29081. '</table>' +
  29082. '<table id="graph_H_table" style="display:none">' +
  29083. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  29084. '<tr>' +
  29085. '<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>' +
  29086. '</tr>' +
  29087. '<tr>' +
  29088. '<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>' +
  29089. '</tr>' +
  29090. '<tr>' +
  29091. '<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>' +
  29092. '</tr>' +
  29093. '<tr>' +
  29094. '<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>' +
  29095. '</tr>' +
  29096. '<tr>' +
  29097. '<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>' +
  29098. '</tr>' +
  29099. '<tr>' +
  29100. '<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>' +
  29101. '</tr>' +
  29102. '<tr>' +
  29103. '<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>' +
  29104. '</tr>' +
  29105. '<tr>' +
  29106. '<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>' +
  29107. '</tr>' +
  29108. '</table>' +
  29109. '<table><tr><td><b>Options:</b></td></tr>' +
  29110. '<tr>' +
  29111. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  29112. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  29113. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  29114. '</tr>' +
  29115. '</table>'
  29116. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  29117. this.optionsDiv = document.createElement("div");
  29118. this.optionsDiv.style.fontSize = "14px";
  29119. this.optionsDiv.style.fontFamily = "verdana";
  29120. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  29121. var rangeElement;
  29122. rangeElement = document.getElementById('graph_BH_gc');
  29123. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  29124. rangeElement = document.getElementById('graph_BH_cg');
  29125. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  29126. rangeElement = document.getElementById('graph_BH_sc');
  29127. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  29128. rangeElement = document.getElementById('graph_BH_sl');
  29129. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  29130. rangeElement = document.getElementById('graph_BH_damp');
  29131. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  29132. rangeElement = document.getElementById('graph_R_nd');
  29133. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  29134. rangeElement = document.getElementById('graph_R_cg');
  29135. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  29136. rangeElement = document.getElementById('graph_R_sc');
  29137. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  29138. rangeElement = document.getElementById('graph_R_sl');
  29139. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  29140. rangeElement = document.getElementById('graph_R_damp');
  29141. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  29142. rangeElement = document.getElementById('graph_H_nd');
  29143. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  29144. rangeElement = document.getElementById('graph_H_cg');
  29145. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  29146. rangeElement = document.getElementById('graph_H_sc');
  29147. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  29148. rangeElement = document.getElementById('graph_H_sl');
  29149. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  29150. rangeElement = document.getElementById('graph_H_damp');
  29151. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  29152. rangeElement = document.getElementById('graph_H_direction');
  29153. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  29154. rangeElement = document.getElementById('graph_H_levsep');
  29155. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  29156. rangeElement = document.getElementById('graph_H_nspac');
  29157. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  29158. var radioButton1 = document.getElementById("graph_physicsMethod1");
  29159. var radioButton2 = document.getElementById("graph_physicsMethod2");
  29160. var radioButton3 = document.getElementById("graph_physicsMethod3");
  29161. radioButton2.checked = true;
  29162. if (this.constants.physics.barnesHut.enabled) {
  29163. radioButton1.checked = true;
  29164. }
  29165. if (this.constants.hierarchicalLayout.enabled) {
  29166. radioButton3.checked = true;
  29167. }
  29168. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  29169. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  29170. var graph_generateOptions = document.getElementById("graph_generateOptions");
  29171. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  29172. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  29173. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  29174. if (this.constants.smoothCurves == true && this.constants.dynamicSmoothCurves == false) {
  29175. graph_toggleSmooth.style.background = "#A4FF56";
  29176. }
  29177. else {
  29178. graph_toggleSmooth.style.background = "#FF8532";
  29179. }
  29180. switchConfigurations.apply(this);
  29181. radioButton1.onchange = switchConfigurations.bind(this);
  29182. radioButton2.onchange = switchConfigurations.bind(this);
  29183. radioButton3.onchange = switchConfigurations.bind(this);
  29184. }
  29185. };
  29186. /**
  29187. * This overwrites the this.constants.
  29188. *
  29189. * @param constantsVariableName
  29190. * @param value
  29191. * @private
  29192. */
  29193. exports._overWriteGraphConstants = function (constantsVariableName, value) {
  29194. var nameArray = constantsVariableName.split("_");
  29195. if (nameArray.length == 1) {
  29196. this.constants[nameArray[0]] = value;
  29197. }
  29198. else if (nameArray.length == 2) {
  29199. this.constants[nameArray[0]][nameArray[1]] = value;
  29200. }
  29201. else if (nameArray.length == 3) {
  29202. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  29203. }
  29204. };
  29205. /**
  29206. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  29207. */
  29208. function graphToggleSmoothCurves () {
  29209. this.constants.smoothCurves.enabled = !this.constants.smoothCurves.enabled;
  29210. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  29211. if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  29212. else {graph_toggleSmooth.style.background = "#FF8532";}
  29213. this._configureSmoothCurves(false);
  29214. }
  29215. /**
  29216. * this function is used to scramble the nodes
  29217. *
  29218. */
  29219. function graphRepositionNodes () {
  29220. for (var nodeId in this.calculationNodes) {
  29221. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  29222. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  29223. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  29224. }
  29225. }
  29226. if (this.constants.hierarchicalLayout.enabled == true) {
  29227. this._setupHierarchicalLayout();
  29228. showValueOfRange.call(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  29229. showValueOfRange.call(this, 'graph_H_cg', 1, "physics_centralGravity");
  29230. showValueOfRange.call(this, 'graph_H_sc', 1, "physics_springConstant");
  29231. showValueOfRange.call(this, 'graph_H_sl', 1, "physics_springLength");
  29232. showValueOfRange.call(this, 'graph_H_damp', 1, "physics_damping");
  29233. }
  29234. else {
  29235. this.repositionNodes();
  29236. }
  29237. this.moving = true;
  29238. this.start();
  29239. }
  29240. /**
  29241. * this is used to generate an options file from the playing with physics system.
  29242. */
  29243. function graphGenerateOptions () {
  29244. var options = "No options are required, default values used.";
  29245. var optionsSpecific = [];
  29246. var radioButton1 = document.getElementById("graph_physicsMethod1");
  29247. var radioButton2 = document.getElementById("graph_physicsMethod2");
  29248. if (radioButton1.checked == true) {
  29249. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  29250. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  29251. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  29252. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  29253. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  29254. if (optionsSpecific.length != 0) {
  29255. options = "var options = {";
  29256. options += "physics: {barnesHut: {";
  29257. for (var i = 0; i < optionsSpecific.length; i++) {
  29258. options += optionsSpecific[i];
  29259. if (i < optionsSpecific.length - 1) {
  29260. options += ", "
  29261. }
  29262. }
  29263. options += '}}'
  29264. }
  29265. if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) {
  29266. if (optionsSpecific.length == 0) {options = "var options = {";}
  29267. else {options += ", "}
  29268. options += "smoothCurves: " + this.constants.smoothCurves.enabled;
  29269. }
  29270. if (options != "No options are required, default values used.") {
  29271. options += '};'
  29272. }
  29273. }
  29274. else if (radioButton2.checked == true) {
  29275. options = "var options = {";
  29276. options += "physics: {barnesHut: {enabled: false}";
  29277. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  29278. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  29279. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  29280. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  29281. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  29282. if (optionsSpecific.length != 0) {
  29283. options += ", repulsion: {";
  29284. for (var i = 0; i < optionsSpecific.length; i++) {
  29285. options += optionsSpecific[i];
  29286. if (i < optionsSpecific.length - 1) {
  29287. options += ", "
  29288. }
  29289. }
  29290. options += '}}'
  29291. }
  29292. if (optionsSpecific.length == 0) {options += "}"}
  29293. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  29294. options += ", smoothCurves: " + this.constants.smoothCurves;
  29295. }
  29296. options += '};'
  29297. }
  29298. else {
  29299. options = "var options = {";
  29300. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  29301. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  29302. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  29303. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  29304. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  29305. if (optionsSpecific.length != 0) {
  29306. options += "physics: {hierarchicalRepulsion: {";
  29307. for (var i = 0; i < optionsSpecific.length; i++) {
  29308. options += optionsSpecific[i];
  29309. if (i < optionsSpecific.length - 1) {
  29310. options += ", ";
  29311. }
  29312. }
  29313. options += '}},';
  29314. }
  29315. options += 'hierarchicalLayout: {';
  29316. optionsSpecific = [];
  29317. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  29318. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  29319. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  29320. if (optionsSpecific.length != 0) {
  29321. for (var i = 0; i < optionsSpecific.length; i++) {
  29322. options += optionsSpecific[i];
  29323. if (i < optionsSpecific.length - 1) {
  29324. options += ", "
  29325. }
  29326. }
  29327. options += '}'
  29328. }
  29329. else {
  29330. options += "enabled:true}";
  29331. }
  29332. options += '};'
  29333. }
  29334. this.optionsDiv.innerHTML = options;
  29335. }
  29336. /**
  29337. * this is used to switch between barnesHut, repulsion and hierarchical.
  29338. *
  29339. */
  29340. function switchConfigurations () {
  29341. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  29342. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  29343. var tableId = "graph_" + radioButton + "_table";
  29344. var table = document.getElementById(tableId);
  29345. table.style.display = "block";
  29346. for (var i = 0; i < ids.length; i++) {
  29347. if (ids[i] != tableId) {
  29348. table = document.getElementById(ids[i]);
  29349. table.style.display = "none";
  29350. }
  29351. }
  29352. this._restoreNodes();
  29353. if (radioButton == "R") {
  29354. this.constants.hierarchicalLayout.enabled = false;
  29355. this.constants.physics.hierarchicalRepulsion.enabled = false;
  29356. this.constants.physics.barnesHut.enabled = false;
  29357. }
  29358. else if (radioButton == "H") {
  29359. if (this.constants.hierarchicalLayout.enabled == false) {
  29360. this.constants.hierarchicalLayout.enabled = true;
  29361. this.constants.physics.hierarchicalRepulsion.enabled = true;
  29362. this.constants.physics.barnesHut.enabled = false;
  29363. this.constants.smoothCurves.enabled = false;
  29364. this._setupHierarchicalLayout();
  29365. }
  29366. }
  29367. else {
  29368. this.constants.hierarchicalLayout.enabled = false;
  29369. this.constants.physics.hierarchicalRepulsion.enabled = false;
  29370. this.constants.physics.barnesHut.enabled = true;
  29371. }
  29372. this._loadSelectedForceSolver();
  29373. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  29374. if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  29375. else {graph_toggleSmooth.style.background = "#FF8532";}
  29376. this.moving = true;
  29377. this.start();
  29378. }
  29379. /**
  29380. * this generates the ranges depending on the iniital values.
  29381. *
  29382. * @param id
  29383. * @param map
  29384. * @param constantsVariableName
  29385. */
  29386. function showValueOfRange (id,map,constantsVariableName) {
  29387. var valueId = id + "_value";
  29388. var rangeValue = document.getElementById(id).value;
  29389. if (Array.isArray(map)) {
  29390. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  29391. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  29392. }
  29393. else {
  29394. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  29395. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  29396. }
  29397. if (constantsVariableName == "hierarchicalLayout_direction" ||
  29398. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  29399. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  29400. this._setupHierarchicalLayout();
  29401. }
  29402. this.moving = true;
  29403. this.start();
  29404. }
  29405. /***/ },
  29406. /* 67 */
  29407. /***/ function(module, exports, __webpack_require__) {
  29408. function webpackContext(req) {
  29409. throw new Error("Cannot find module '" + req + "'.");
  29410. }
  29411. webpackContext.keys = function() { return []; };
  29412. webpackContext.resolve = webpackContext;
  29413. module.exports = webpackContext;
  29414. webpackContext.id = 67;
  29415. /***/ },
  29416. /* 68 */
  29417. /***/ function(module, exports, __webpack_require__) {
  29418. /**
  29419. * Calculate the forces the nodes apply on each other based on a repulsion field.
  29420. * This field is linearly approximated.
  29421. *
  29422. * @private
  29423. */
  29424. exports._calculateNodeForces = function () {
  29425. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  29426. repulsingForce, node1, node2, i, j;
  29427. var nodes = this.calculationNodes;
  29428. var nodeIndices = this.calculationNodeIndices;
  29429. // approximation constants
  29430. var a_base = -2 / 3;
  29431. var b = 4 / 3;
  29432. // repulsing forces between nodes
  29433. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  29434. var minimumDistance = nodeDistance;
  29435. // we loop from i over all but the last entree in the array
  29436. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  29437. for (i = 0; i < nodeIndices.length - 1; i++) {
  29438. node1 = nodes[nodeIndices[i]];
  29439. for (j = i + 1; j < nodeIndices.length; j++) {
  29440. node2 = nodes[nodeIndices[j]];
  29441. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  29442. dx = node2.x - node1.x;
  29443. dy = node2.y - node1.y;
  29444. distance = Math.sqrt(dx * dx + dy * dy);
  29445. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  29446. var a = a_base / minimumDistance;
  29447. if (distance < 2 * minimumDistance) {
  29448. if (distance < 0.5 * minimumDistance) {
  29449. repulsingForce = 1.0;
  29450. }
  29451. else {
  29452. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  29453. }
  29454. // amplify the repulsion for clusters.
  29455. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  29456. repulsingForce = repulsingForce / Math.max(distance,0.01*minimumDistance);
  29457. fx = dx * repulsingForce;
  29458. fy = dy * repulsingForce;
  29459. node1.fx -= fx;
  29460. node1.fy -= fy;
  29461. node2.fx += fx;
  29462. node2.fy += fy;
  29463. }
  29464. }
  29465. }
  29466. };
  29467. /***/ },
  29468. /* 69 */
  29469. /***/ function(module, exports, __webpack_require__) {
  29470. /**
  29471. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  29472. * This field is linearly approximated.
  29473. *
  29474. * @private
  29475. */
  29476. exports._calculateNodeForces = function () {
  29477. var dx, dy, distance, fx, fy,
  29478. repulsingForce, node1, node2, i, j;
  29479. var nodes = this.calculationNodes;
  29480. var nodeIndices = this.calculationNodeIndices;
  29481. // repulsing forces between nodes
  29482. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  29483. // we loop from i over all but the last entree in the array
  29484. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  29485. for (i = 0; i < nodeIndices.length - 1; i++) {
  29486. node1 = nodes[nodeIndices[i]];
  29487. for (j = i + 1; j < nodeIndices.length; j++) {
  29488. node2 = nodes[nodeIndices[j]];
  29489. // nodes only affect nodes on their level
  29490. if (node1.level == node2.level) {
  29491. dx = node2.x - node1.x;
  29492. dy = node2.y - node1.y;
  29493. distance = Math.sqrt(dx * dx + dy * dy);
  29494. var steepness = 0.05;
  29495. if (distance < nodeDistance) {
  29496. repulsingForce = -Math.pow(steepness*distance,2) + Math.pow(steepness*nodeDistance,2);
  29497. }
  29498. else {
  29499. repulsingForce = 0;
  29500. }
  29501. // normalize force with
  29502. if (distance == 0) {
  29503. distance = 0.01;
  29504. }
  29505. else {
  29506. repulsingForce = repulsingForce / distance;
  29507. }
  29508. fx = dx * repulsingForce;
  29509. fy = dy * repulsingForce;
  29510. node1.fx -= fx;
  29511. node1.fy -= fy;
  29512. node2.fx += fx;
  29513. node2.fy += fy;
  29514. }
  29515. }
  29516. }
  29517. };
  29518. /**
  29519. * this function calculates the effects of the springs in the case of unsmooth curves.
  29520. *
  29521. * @private
  29522. */
  29523. exports._calculateHierarchicalSpringForces = function () {
  29524. var edgeLength, edge, edgeId;
  29525. var dx, dy, fx, fy, springForce, distance;
  29526. var edges = this.edges;
  29527. var nodes = this.calculationNodes;
  29528. var nodeIndices = this.calculationNodeIndices;
  29529. for (var i = 0; i < nodeIndices.length; i++) {
  29530. var node1 = nodes[nodeIndices[i]];
  29531. node1.springFx = 0;
  29532. node1.springFy = 0;
  29533. }
  29534. // forces caused by the edges, modelled as springs
  29535. for (edgeId in edges) {
  29536. if (edges.hasOwnProperty(edgeId)) {
  29537. edge = edges[edgeId];
  29538. if (edge.connected) {
  29539. // only calculate forces if nodes are in the same sector
  29540. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  29541. edgeLength = edge.physics.springLength;
  29542. // this implies that the edges between big clusters are longer
  29543. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  29544. dx = (edge.from.x - edge.to.x);
  29545. dy = (edge.from.y - edge.to.y);
  29546. distance = Math.sqrt(dx * dx + dy * dy);
  29547. if (distance == 0) {
  29548. distance = 0.01;
  29549. }
  29550. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  29551. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  29552. fx = dx * springForce;
  29553. fy = dy * springForce;
  29554. if (edge.to.level != edge.from.level) {
  29555. edge.to.springFx -= fx;
  29556. edge.to.springFy -= fy;
  29557. edge.from.springFx += fx;
  29558. edge.from.springFy += fy;
  29559. }
  29560. else {
  29561. var factor = 0.5;
  29562. edge.to.fx -= factor*fx;
  29563. edge.to.fy -= factor*fy;
  29564. edge.from.fx += factor*fx;
  29565. edge.from.fy += factor*fy;
  29566. }
  29567. }
  29568. }
  29569. }
  29570. }
  29571. // normalize spring forces
  29572. var springForce = 1;
  29573. var springFx, springFy;
  29574. for (i = 0; i < nodeIndices.length; i++) {
  29575. var node = nodes[nodeIndices[i]];
  29576. springFx = Math.min(springForce,Math.max(-springForce,node.springFx));
  29577. springFy = Math.min(springForce,Math.max(-springForce,node.springFy));
  29578. node.fx += springFx;
  29579. node.fy += springFy;
  29580. }
  29581. // retain energy balance
  29582. var totalFx = 0;
  29583. var totalFy = 0;
  29584. for (i = 0; i < nodeIndices.length; i++) {
  29585. var node = nodes[nodeIndices[i]];
  29586. totalFx += node.fx;
  29587. totalFy += node.fy;
  29588. }
  29589. var correctionFx = totalFx / nodeIndices.length;
  29590. var correctionFy = totalFy / nodeIndices.length;
  29591. for (i = 0; i < nodeIndices.length; i++) {
  29592. var node = nodes[nodeIndices[i]];
  29593. node.fx -= correctionFx;
  29594. node.fy -= correctionFy;
  29595. }
  29596. };
  29597. /***/ },
  29598. /* 70 */
  29599. /***/ function(module, exports, __webpack_require__) {
  29600. /**
  29601. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  29602. * The Barnes Hut method is used to speed up this N-body simulation.
  29603. *
  29604. * @private
  29605. */
  29606. exports._calculateNodeForces = function() {
  29607. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  29608. var node;
  29609. var nodes = this.calculationNodes;
  29610. var nodeIndices = this.calculationNodeIndices;
  29611. var nodeCount = nodeIndices.length;
  29612. this._formBarnesHutTree(nodes,nodeIndices);
  29613. var barnesHutTree = this.barnesHutTree;
  29614. // place the nodes one by one recursively
  29615. for (var i = 0; i < nodeCount; i++) {
  29616. node = nodes[nodeIndices[i]];
  29617. if (node.options.mass > 0) {
  29618. // starting with root is irrelevant, it never passes the BarnesHut condition
  29619. this._getForceContribution(barnesHutTree.root.children.NW,node);
  29620. this._getForceContribution(barnesHutTree.root.children.NE,node);
  29621. this._getForceContribution(barnesHutTree.root.children.SW,node);
  29622. this._getForceContribution(barnesHutTree.root.children.SE,node);
  29623. }
  29624. }
  29625. }
  29626. };
  29627. /**
  29628. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  29629. * If a region contains a single node, we check if it is not itself, then we apply the force.
  29630. *
  29631. * @param parentBranch
  29632. * @param node
  29633. * @private
  29634. */
  29635. exports._getForceContribution = function(parentBranch,node) {
  29636. // we get no force contribution from an empty region
  29637. if (parentBranch.childrenCount > 0) {
  29638. var dx,dy,distance;
  29639. // get the distance from the center of mass to the node.
  29640. dx = parentBranch.centerOfMass.x - node.x;
  29641. dy = parentBranch.centerOfMass.y - node.y;
  29642. distance = Math.sqrt(dx * dx + dy * dy);
  29643. // BarnesHut condition
  29644. // original condition : s/d < thetaInverted = passed === d/s > 1/theta = passed
  29645. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  29646. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.thetaInverted) {
  29647. // duplicate code to reduce function calls to speed up program
  29648. if (distance == 0) {
  29649. distance = 0.1*Math.random();
  29650. dx = distance;
  29651. }
  29652. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance);
  29653. var fx = dx * gravityForce;
  29654. var fy = dy * gravityForce;
  29655. node.fx += fx;
  29656. node.fy += fy;
  29657. }
  29658. else {
  29659. // Did not pass the condition, go into children if available
  29660. if (parentBranch.childrenCount == 4) {
  29661. this._getForceContribution(parentBranch.children.NW,node);
  29662. this._getForceContribution(parentBranch.children.NE,node);
  29663. this._getForceContribution(parentBranch.children.SW,node);
  29664. this._getForceContribution(parentBranch.children.SE,node);
  29665. }
  29666. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  29667. if (parentBranch.children.data.id != node.id) { // if it is not self
  29668. // duplicate code to reduce function calls to speed up program
  29669. if (distance == 0) {
  29670. distance = 0.5*Math.random();
  29671. dx = distance;
  29672. }
  29673. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance);
  29674. var fx = dx * gravityForce;
  29675. var fy = dy * gravityForce;
  29676. node.fx += fx;
  29677. node.fy += fy;
  29678. }
  29679. }
  29680. }
  29681. }
  29682. };
  29683. /**
  29684. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  29685. *
  29686. * @param nodes
  29687. * @param nodeIndices
  29688. * @private
  29689. */
  29690. exports._formBarnesHutTree = function(nodes,nodeIndices) {
  29691. var node;
  29692. var nodeCount = nodeIndices.length;
  29693. var minX = Number.MAX_VALUE,
  29694. minY = Number.MAX_VALUE,
  29695. maxX =-Number.MAX_VALUE,
  29696. maxY =-Number.MAX_VALUE;
  29697. // get the range of the nodes
  29698. for (var i = 0; i < nodeCount; i++) {
  29699. var x = nodes[nodeIndices[i]].x;
  29700. var y = nodes[nodeIndices[i]].y;
  29701. if (nodes[nodeIndices[i]].options.mass > 0) {
  29702. if (x < minX) { minX = x; }
  29703. if (x > maxX) { maxX = x; }
  29704. if (y < minY) { minY = y; }
  29705. if (y > maxY) { maxY = y; }
  29706. }
  29707. }
  29708. // make the range a square
  29709. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  29710. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  29711. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  29712. var minimumTreeSize = 1e-5;
  29713. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  29714. var halfRootSize = 0.5 * rootSize;
  29715. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  29716. // construct the barnesHutTree
  29717. var barnesHutTree = {
  29718. root:{
  29719. centerOfMass: {x:0, y:0},
  29720. mass:0,
  29721. range: {
  29722. minX: centerX-halfRootSize,maxX:centerX+halfRootSize,
  29723. minY: centerY-halfRootSize,maxY:centerY+halfRootSize
  29724. },
  29725. size: rootSize,
  29726. calcSize: 1 / rootSize,
  29727. children: { data:null},
  29728. maxWidth: 0,
  29729. level: 0,
  29730. childrenCount: 4
  29731. }
  29732. };
  29733. this._splitBranch(barnesHutTree.root);
  29734. // place the nodes one by one recursively
  29735. for (i = 0; i < nodeCount; i++) {
  29736. node = nodes[nodeIndices[i]];
  29737. if (node.options.mass > 0) {
  29738. this._placeInTree(barnesHutTree.root,node);
  29739. }
  29740. }
  29741. // make global
  29742. this.barnesHutTree = barnesHutTree
  29743. };
  29744. /**
  29745. * this updates the mass of a branch. this is increased by adding a node.
  29746. *
  29747. * @param parentBranch
  29748. * @param node
  29749. * @private
  29750. */
  29751. exports._updateBranchMass = function(parentBranch, node) {
  29752. var totalMass = parentBranch.mass + node.options.mass;
  29753. var totalMassInv = 1/totalMass;
  29754. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass;
  29755. parentBranch.centerOfMass.x *= totalMassInv;
  29756. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass;
  29757. parentBranch.centerOfMass.y *= totalMassInv;
  29758. parentBranch.mass = totalMass;
  29759. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  29760. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  29761. };
  29762. /**
  29763. * determine in which branch the node will be placed.
  29764. *
  29765. * @param parentBranch
  29766. * @param node
  29767. * @param skipMassUpdate
  29768. * @private
  29769. */
  29770. exports._placeInTree = function(parentBranch,node,skipMassUpdate) {
  29771. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  29772. // update the mass of the branch.
  29773. this._updateBranchMass(parentBranch,node);
  29774. }
  29775. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  29776. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  29777. this._placeInRegion(parentBranch,node,"NW");
  29778. }
  29779. else { // in SW
  29780. this._placeInRegion(parentBranch,node,"SW");
  29781. }
  29782. }
  29783. else { // in NE or SE
  29784. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  29785. this._placeInRegion(parentBranch,node,"NE");
  29786. }
  29787. else { // in SE
  29788. this._placeInRegion(parentBranch,node,"SE");
  29789. }
  29790. }
  29791. };
  29792. /**
  29793. * actually place the node in a region (or branch)
  29794. *
  29795. * @param parentBranch
  29796. * @param node
  29797. * @param region
  29798. * @private
  29799. */
  29800. exports._placeInRegion = function(parentBranch,node,region) {
  29801. switch (parentBranch.children[region].childrenCount) {
  29802. case 0: // place node here
  29803. parentBranch.children[region].children.data = node;
  29804. parentBranch.children[region].childrenCount = 1;
  29805. this._updateBranchMass(parentBranch.children[region],node);
  29806. break;
  29807. case 1: // convert into children
  29808. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  29809. // we move one node a pixel and we do not put it in the tree.
  29810. if (parentBranch.children[region].children.data.x == node.x &&
  29811. parentBranch.children[region].children.data.y == node.y) {
  29812. node.x += Math.random();
  29813. node.y += Math.random();
  29814. }
  29815. else {
  29816. this._splitBranch(parentBranch.children[region]);
  29817. this._placeInTree(parentBranch.children[region],node);
  29818. }
  29819. break;
  29820. case 4: // place in branch
  29821. this._placeInTree(parentBranch.children[region],node);
  29822. break;
  29823. }
  29824. };
  29825. /**
  29826. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  29827. * after the split is complete.
  29828. *
  29829. * @param parentBranch
  29830. * @private
  29831. */
  29832. exports._splitBranch = function(parentBranch) {
  29833. // if the branch is shaded with a node, replace the node in the new subset.
  29834. var containedNode = null;
  29835. if (parentBranch.childrenCount == 1) {
  29836. containedNode = parentBranch.children.data;
  29837. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  29838. }
  29839. parentBranch.childrenCount = 4;
  29840. parentBranch.children.data = null;
  29841. this._insertRegion(parentBranch,"NW");
  29842. this._insertRegion(parentBranch,"NE");
  29843. this._insertRegion(parentBranch,"SW");
  29844. this._insertRegion(parentBranch,"SE");
  29845. if (containedNode != null) {
  29846. this._placeInTree(parentBranch,containedNode);
  29847. }
  29848. };
  29849. /**
  29850. * This function subdivides the region into four new segments.
  29851. * Specifically, this inserts a single new segment.
  29852. * It fills the children section of the parentBranch
  29853. *
  29854. * @param parentBranch
  29855. * @param region
  29856. * @param parentRange
  29857. * @private
  29858. */
  29859. exports._insertRegion = function(parentBranch, region) {
  29860. var minX,maxX,minY,maxY;
  29861. var childSize = 0.5 * parentBranch.size;
  29862. switch (region) {
  29863. case "NW":
  29864. minX = parentBranch.range.minX;
  29865. maxX = parentBranch.range.minX + childSize;
  29866. minY = parentBranch.range.minY;
  29867. maxY = parentBranch.range.minY + childSize;
  29868. break;
  29869. case "NE":
  29870. minX = parentBranch.range.minX + childSize;
  29871. maxX = parentBranch.range.maxX;
  29872. minY = parentBranch.range.minY;
  29873. maxY = parentBranch.range.minY + childSize;
  29874. break;
  29875. case "SW":
  29876. minX = parentBranch.range.minX;
  29877. maxX = parentBranch.range.minX + childSize;
  29878. minY = parentBranch.range.minY + childSize;
  29879. maxY = parentBranch.range.maxY;
  29880. break;
  29881. case "SE":
  29882. minX = parentBranch.range.minX + childSize;
  29883. maxX = parentBranch.range.maxX;
  29884. minY = parentBranch.range.minY + childSize;
  29885. maxY = parentBranch.range.maxY;
  29886. break;
  29887. }
  29888. parentBranch.children[region] = {
  29889. centerOfMass:{x:0,y:0},
  29890. mass:0,
  29891. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  29892. size: 0.5 * parentBranch.size,
  29893. calcSize: 2 * parentBranch.calcSize,
  29894. children: {data:null},
  29895. maxWidth: 0,
  29896. level: parentBranch.level+1,
  29897. childrenCount: 0
  29898. };
  29899. };
  29900. /**
  29901. * This function is for debugging purposed, it draws the tree.
  29902. *
  29903. * @param ctx
  29904. * @param color
  29905. * @private
  29906. */
  29907. exports._drawTree = function(ctx,color) {
  29908. if (this.barnesHutTree !== undefined) {
  29909. ctx.lineWidth = 1;
  29910. this._drawBranch(this.barnesHutTree.root,ctx,color);
  29911. }
  29912. };
  29913. /**
  29914. * This function is for debugging purposes. It draws the branches recursively.
  29915. *
  29916. * @param branch
  29917. * @param ctx
  29918. * @param color
  29919. * @private
  29920. */
  29921. exports._drawBranch = function(branch,ctx,color) {
  29922. if (color === undefined) {
  29923. color = "#FF0000";
  29924. }
  29925. if (branch.childrenCount == 4) {
  29926. this._drawBranch(branch.children.NW,ctx);
  29927. this._drawBranch(branch.children.NE,ctx);
  29928. this._drawBranch(branch.children.SE,ctx);
  29929. this._drawBranch(branch.children.SW,ctx);
  29930. }
  29931. ctx.strokeStyle = color;
  29932. ctx.beginPath();
  29933. ctx.moveTo(branch.range.minX,branch.range.minY);
  29934. ctx.lineTo(branch.range.maxX,branch.range.minY);
  29935. ctx.stroke();
  29936. ctx.beginPath();
  29937. ctx.moveTo(branch.range.maxX,branch.range.minY);
  29938. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  29939. ctx.stroke();
  29940. ctx.beginPath();
  29941. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  29942. ctx.lineTo(branch.range.minX,branch.range.maxY);
  29943. ctx.stroke();
  29944. ctx.beginPath();
  29945. ctx.moveTo(branch.range.minX,branch.range.maxY);
  29946. ctx.lineTo(branch.range.minX,branch.range.minY);
  29947. ctx.stroke();
  29948. /*
  29949. if (branch.mass > 0) {
  29950. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  29951. ctx.stroke();
  29952. }
  29953. */
  29954. };
  29955. /***/ },
  29956. /* 71 */
  29957. /***/ function(module, exports, __webpack_require__) {
  29958. module.exports = function(module) {
  29959. if(!module.webpackPolyfill) {
  29960. module.deprecate = function() {};
  29961. module.paths = [];
  29962. // module.parent = undefined by default
  29963. module.children = [];
  29964. module.webpackPolyfill = 1;
  29965. }
  29966. return module;
  29967. }
  29968. /***/ }
  29969. /******/ ])
  29970. });